Repository navigation
Description
Goal
Replace the in-memory session store so a tailnet login survives restarts and upgrades and ends only when the token is rotated: weigh stateless token-keyed cookies against a persisted store (capture #229's Shape), refresh the cookie on use, keep every #39 cookie protection, document how long a login lasts and what ends it. Any bound the #39 design relied on that the plan drops goes to the operator as a gate.
Requirements
M12-R1,M12-R2,M12-R3,M12-R4,M12-R5
Adopts
- A tailnet login should last until the token is rotated, not end at every daemon restart #229 — A tailnet login should last until the token is rotated, not end at every daemon restart
Plan
Requirements: M12-R1, M12-R2, M12-R3, M12-R4, and this task's share of M12-R5 (the introduction's Authentication section and contrib/mdn.1; the record is the doc-synthesizer's). Adopts #229.
Measured today (v0.3.0 tree, main at 1c9698b)
A real mdn serve --tailnet-host mdn-231.test:8832 behind a local TLS proxy standing in for tailscale serve (terminates TLS, forwards to loopback with X-Forwarded-Proto: https), driven by headless Chromium 153 through Playwright on a persistent profile. Script: measure.mjs in the implementer's scratch; it will be run again against the fix and the output posted.
| Step | Browser shown | GET /api/roots |
Cookie in the browser |
|---|---|---|---|
| 2. logged in once | the app | 200 | present, expires +30 d |
| 3. daemon restarted, same token | login page | 401 | present |
| 4. browser closed and reopened | login page | 401 | present |
5. --app window on the same profile |
login page | 401 | present |
| 6. token rotated while running | login page | 401 | present |
| 8. rotated while stopped, then started | login page | 401 | present |
| 10. restarted again, same token | login page | 401 | present |
So on desktop Chromium the cookie is kept, across a browser restart and in an app window, and the daemon refuses it after a restart: "cookie present but refused". The daemon is the thing to fix; the phone and tablet check is the operator's after release, per the #230 Decision.
Stateless vs persisted: stateless
The cookie becomes a signed value the daemon can check with nothing but the token file it already has:
__Host-mdn_session=v1.<issued-at, unix seconds>.<16 random bytes, base64url>.<HMAC-SHA256, base64url>
- Key.
HMAC-SHA256(key = token, "mdn session key v1"), derived on each check from the tokentoken.Storeholds (the file is still re-read only when its stat changes). The MAC key is not the token, and the cookie carries nothing from which the token can be recovered. - MAC'd payload. Version, the tailnet host name, issued-at and the random id. The host is in the MAC so that a cookie minted under one
tailnet_hostis refused under another even with the same token. - Check. Exact field count and lengths (a truncated or padded MAC is refused before comparing),
hmac.Equalfor the comparison, then the age check below. An issued-at in the future beyond a small skew is refused. - Rotation, by construction. A new token is a new key, so every cookie signed under the old one fails its MAC, on the next request, whether or not the daemon restarted in between. No generation, no store, no sweep.
- Login race. Validating the token and deriving the key must be one read of the token (the reason
Authenticatereturns the generation today):token.Storegets one call that checks the presented token and returns the key derived from that same value, so a rotation landing mid-login cannot sign a cookie under a token the browser never presented. - Nothing new at rest. No file in
--state, so M12-R4's "no second secret at rest" holds and no operator decision is needed for (b). Persisting was rejected: it adds a secret at rest, and it would still need a rotation check. - The in-memory
session.Store(map, cap of 64, eviction) is replaced by a codec (session.Sign/session.Check, clock injectable for tests).
This reverses two rejections recorded in the #39 session Decision (a signed stateless cookie; per-request renewal). M12 asks for exactly those properties, and the #39 objections are met: the token is not the signing key (a derived key is), refresh is at most once a day (below), and "nothing to revoke short of rotating" was already true, since #39 chose no logout. A Decision comment will record this when the code lands.
Expiry and refresh
- The payload's issued-at is the session's age. A valid cookie older than 24 hours is reissued on the response (same id, new issued-at, full
Max-Age), so a device in use sends at most oneSet-Cookiea day, not one per response, which was Tailnet access: extra Host name, token login and session cookie #39's objection to rolling renewal. - A cookie is refused once its issued-at is older than the idle limit, and
Max-Ageequals that limit, so the browser and the daemon agree. The idle limit is what bounds a lost or borrowed device. Its value is the checkpoint below. Chromium capsMax-Ageat 400 days, so no value can exceed that. - Dropped from Tailnet access: extra Host name, token login and session cookie #39: the 30-day absolute bound (a device in use never lapses now), and "logging in again deletes the session the browser held" (a stateless cookie that was superseded is still valid until its own age runs out, the same bound as any other cookie; the browser has already overwritten it). Rotation still ends every session from the machine. No "log out other devices" action is proposed; it is not needed for M12 and would be scope for the operator.
Kept, and shown kept by the existing tests passing
__Host- prefix, Path=/, no Domain, HttpOnly, Secure, SameSite=Strict, the token never in the cookie, the https check at login, the Origin check on cookie requests, the login throttle, loopback behaviour, the bearer token's Origin exemption, and the allow-list. Tests that assert the old store's internals (TestTailnetSessionExpires with session.New, TestLoggingInAgainEndsTheOldSession counting entries) are rewritten against the new behaviour, and each change is named in the PR.
Tests (written first where they prove a requirement; each shown failing against today's code)
internal/session: sign/check round trip; refused: another token's key, another host, tampered issued-at/id/version, truncated and extended MAC, bad base64, wrong field count, empty; expiry at the idle limit; future issued-at; refresh due after 24 h and not before.internal/token: the derived key changes onRotateand on a replaced file, is stable acrossOpenof the same file (a restart), and authenticate-and-derive is one read.internal/server(over HTTP): restart (log in on oneServer, present the cookie to a newServerover the same token file: 200; fails today); newer build covered by the e2e below; rotate while running; rotate while stopped (replace the token file, then build a newServer: 401); forged/replayed cookies (other token, other host, tampered, truncated, pre-rotation); refresh (Set-Cookieafter 24 h on the injected clock, none before, attributes intact); login throttle, loopback and bearer tests unchanged and passing.- End to end (M12-R1): a
ui/e2esuite that runs the builtmdnbehind a TLS proxy in Node (a self-signed certificate fromopenssl,--host-resolver-rulesin Chromium): log in once in Chromium, stop and start the daemon, the same cookie is accepted with no token; rotate, it is refused. Skips with a# skipped:line whereopensslis missing, and fails instead under CI, as the harness does for Chromium. The newer build leg (v0.3.0 binary logs in, this branch's binary accepts the cookie; and this branch's binary restarted into a second build of the same tree) and the browser-restart and--applegs are measured with the scratch rig and the output posted on the PR. The old binary's cookie is expected to be refused once by the new one: that is the migration.
Migration and docs (M12-R5, this task's share)
Existing in-memory sessions end once, at the upgrade to v0.3.1: every device logs in one more time, then survives restarts. The introduction's Authentication section (the Set-Cookie example and the paragraph after it, plus "so does restarting the daemon") and contrib/mdn.1 (tailnet host / token --rotate) will say: a login lasts until the token is rotated or the device goes unused for the idle limit; restarts and upgrades do not end it; rotation ends every session at once; the one-time logout at this upgrade. Also the lines in docs/running.md and the internal/session package comment that say a restart logs out.
Commits
fix(token), fix(session), fix(server), test(e2e); the man page takes fix(man) (CI must run for it), the introduction prose docs. No feat: no user-facing surface is added.
Ask-the-human points
- The idle limit that replaces Tailnet access: extra Host name, token login and session cookie #39's 30-day absolute bound (M12-R3, operator's call). Raised as a checkpoint on this task. Held: only the constant and the sentence in the docs that names it; everything else proceeds with the recommended value and changes by one line if the answer differs.
Activity
davison commentedon Sep 30, 2026
Gate raised: M12-R3: a tailnet session no longer expires on a fixed date (the cookie is reissued at most once a day while the device is used). That drops the 30-day absolute bound the #39 Decision relied on for a lost or borrowed device. What should bound a session that is NOT being used? Options: (A) 30-day idle limit, recommended: a device used at least once a month never asks for the token again; a browser used once and left behind lapses within 30 days, as today; a device someone else keeps using stays in until you rotate (mdn token --rotate), which is also true today for up to 30 days. (B) 400-day idle limit, Chromium's cap on a cookie lifetime: in practice only rotation ends a session, matching your words on #229, and a borrowed browser stays logged in for about 13 months unless you rotate. (C) 90-day idle limit, between the two, for an e-ink tablet that can sit unused for weeks. Recommendation: A, because it keeps the #39 reason for a bound and costs one paste only after a month of disuse; choose B if the tablet is often idle for more than a month. Held until answered: only the constant and the sentence in the docs that names it. The rest of the task proceeds with A.
Resolve by replying with a comment starting
**Gate resolved:**— the decision, and the trade-off if one was weighed — then removing thecc:needs-decisionlabel. The resolution is gathered into the milestone record;task finishrefuses while the label is present or the gate lacks a resolution comment.davison commentedon Sep 30, 2026
Started by @davison.
davison commentedon Sep 30, 2026
Decision: a tailnet session is a stateless signed cookie, keyed by a key derived from the token. Nothing is persisted. This reverses two rejections recorded in the #39 session Decision (#39 (comment)), for the reasons below.
Shape.
__Host-mdn_session=v1.<issued-at, unix s>.<16 random bytes>.<HMAC-SHA256>. The MAC covers the version, the tailnet host name, the issued-at and the id. Its key isHMAC-SHA256(token, "mdn session key v1")(token.Store.Derive). The check refuses a wrong field count, a non-canonical issued-at, an id or MAC of the wrong decoded length, and non-canonical base64, all before the MAC comparison, which ishmac.Equal. It then refuses an issued-at more than 5 minutes in the future or 30 days or more in the past. A session a day old or more is reissued on a response the guard serves. A request that the Origin check or the allow-list refuses keeps its old cookie (TestTailnetRefusedRequestIsNotReissued).Measured end to end (headless Chromium 153, a real
mdn serve --tailnet-hostbehind a local TLS proxy standing in fortailscale serve):--appwindow, same profileUpgrade leg (v0.3.0 binary, then this branch's): the v0.3.0 cookie is refused once at the restart into the new build. That is the migration. After one login, the next restart keeps the session. Cost:
session.Checktakes 1.1 µs/op (go test -bench), plus one HMAC for the derivation. The onestatper request that the token already costs is unchanged.Why the #39 rejections no longer hold.
TestTheValueDoesNotCarryTheKey,TestDerivedKeyMovesOnlyWhenTheTokenDoes).Trade-off:
TestLoggingInAgainEndsTheOldSessionbecomesTestLoggingInAgainIssuesAFreshSession.AuthenticateDerivekeeps the one-read guarantee at login, so a rotation mid-login cannot sign a cookie under a token the browser never presented.Rejected:
--state: a second secret at rest, which is the operator's decision under M12-R4, and it still needs a rotation check.tailnet_hostwould then check under another name that holds the same token (TestTailnetCookieIsBoundToItsHostName).Installed app: a real install through CDP
PWA.installfails withkNotValidManifestForWebAppbehind the self-signed certificate. That is Chromium's installability check refusing an untrusted origin. The--appwindow on the same profile, which is what a desktop install opens, kept the session. The operator's own phone and tablet check comes after release, per the #230 Decision.test(server): a test daemon can be restarted over the same base (#231)
fix(session): a tailnet login survives restarts and ends on rotation (#…
test(e2e): a tailnet login across daemon restarts, behind TLS (#231)
fix(man): how long a tailnet login lasts and what ends it (#231)
docs: how long a tailnet login lasts and what ends it (#231)
davison commentedon Sep 30, 2026
Decision: an addendum to the stateless-session Decision (#231 (comment)), covering review nits 2 and 5 on PR #232 (#232 (comment)).
Writing an earlier token back revives its sessions. A cookie is good while the token it was signed under is in force. If an earlier token is written back, for example by restoring
--statefrom a backup after a rotation made to revoke a device, the sessions signed with that token are good again, up to their idle limit. The reviewer measured it: 401 after the rotation, 200 once the old token was written back. v0.3.0 behaved differently: its generation counter moved on every change of value, so within one process a restored token did not bring a session back. I accept this rather than add state to prevent it. Anyone holding the restored token can log in anyway, and preventing it would need a record of past tokens, which is a second thing at rest. "Rotation ends every session" holds as long as the rotated-away token is not restored. The introduction's rotation bullet now says so (commit 3621f42).A refreshed cookie gets a new random id. It does not keep the old id with a new issued-at, as the plan's refresh bullet said: this corrects the plan. Why: nothing reads the id. It exists only so that two values issued in the same second differ, and it is under the MAC. Reusing it would mean parsing it out of the presented cookie and passing it back into
Issue, which is an extra code path with no effect. With a fresh id, the reissue is the same call a login makes, and each reissued value is distinct. The code is unchanged.test(session): an id of the wrong length is refused (#231)
docs: a restored token revives its sessions, and v0.3.1 logs out once (…
5 remaining items
docs: reflow the idle-limit bullet in the introduction (#231)
test(server): a test daemon can be restarted over the same base (#231)
fix(session): a tailnet login survives restarts and ends on rotation (#…
test(e2e): a tailnet login across daemon restarts, behind TLS (#231)
fix(man): how long a tailnet login lasts and what ends it (#231)
docs: how long a tailnet login lasts and what ends it (#231)
test(session): an id of the wrong length is refused (#231)
docs: a restored token revives its sessions, and v0.3.1 logs out once (…
fix(man): a tailnet login ends after 30 days idle, not a fixed lifeti…
docs: the 30 days are counted from the last use, not the login (#231)
docs: reflow the idle-limit bullet in the introduction (#231)
davison commentedon Sep 30, 2026
Delivered by PR #233 (merged 2026-09-30T11:24:50Z as 19823d0 via
gh codecrew task finish 231 --operator-confirm). Closed by hand: GitHub did not act on the PR'sCloses #231at merge, even with the operator's manual Development link in place — the same failure recorded in the deviation above (5909597289).davison commentedon Sep 30, 2026
QA finding (suite gap, M12-R1 and M12-R4); behaviour is correct. From the qa seat's M12 pass on merged
main(19823d0). Nothing here is broken today. These are places where the shipped tests would stay green if the promise broke.KeyPurposeininternal/session/session.gofrom"mdn session key v1"to"mdn session key v1x", then rango test -count=1 ./internal/session ./internal/server ./internal/token. The same edit shipped would log out every device at the next upgrade, which is the migration M12 exists to make happen only once.internal/session: a fixed token, host, issued-at and id, the expected value as a literal, and aCheckthat accepts it. That pins the key derivation, the MAC layout and the encoding together. A deliberate format change would then have to edit the vector and bumpv1.strace -f -e trace=openat,renameat,mkdirat,unlinkat,…over 14 daemon lifetimes, with logins, reissues and rotations): the only file ever created is the token file at first start. No test checks this, though. A later change that persisted sessions besideroots.jsonwould pass every test. A server test could list the--statedirectory after a login, a reissue and a restart, and expect only the token file.Neither blocks a verdict. I measured the behaviour directly: #230 (the qa verdict comment). A fix belongs to a task the coordination layer opens, if it wants one.