Skip to content

fix(session): a tailnet login survives restarts and ends on rotation (#231) - #232

Closed
davison wants to merge 9 commits into
mainfrom
task/231-tailnet-sessions-that-survive-restarts-a
Closed

davison wants to merge 9 commits into
mainfrom
task/231-tailnet-sessions-that-survive-restarts-a

Conversation

@davison

@davison davison commented Sep 30, 2026 •

Copy link
Copy Markdown
Owner

Closes #231

A tailnet login now survives daemon restarts, upgrades and reboots, and ends when the token is rotated. Milestone M12 (#230); this adopts capture #229, which task finish closes.

What changed

  • internal/session: the in-memory store is replaced by a stateless signed value: v1.<issued-at>.<random id>.<HMAC-SHA256>. The MAC covers the fields and the tailnet host name, and its key is derived from the token. The check is strict about shape, compares with hmac.Equal, and refuses an issued-at from the future or one past the idle limit.
  • internal/token: the generation counter is replaced by Derive(purpose) and AuthenticateDerive(presented, purpose), which keep the one-read guarantee the login relies on.
  • internal/server: the guard checks the cookie against the key of the token in force now. It reissues a session a day old or more, but only on a response it serves. Every cookie, whether from a login or a reissue, gets the same attributes from one function.
  • Docs: the introduction's "A browser on the tailnet" section, docs/running.md and contrib/mdn.1 say how long a login lasts, what ends it, and that every device logs in once more at the upgrade to v0.3.1.

Requirements

  • M12-R1 (survives a restart): TestTailnetSessionSurvivesARestart, and ui/e2e/tailnet-session.test.mjs in Chromium behind TLS. The upgrade and newer-build legs were measured with a scratch rig; the table is in the Decision linked below.
  • M12-R2 (rotation ends every session, with no forgery or replay): TestTailnetRotationEndsTheSession (existing), TestTailnetRotationWhileStoppedEndsTheSession, TestTailnetRotationEndsTheSessionAcrossARestart, TestTailnetCookieFromAnotherTokenIsRefused, TestTailnetCookieIsBoundToItsHostName, TestTailnetRejectsAForgedCookie (existing), and the session package's tamper, truncation and other-key tests. The e2e suite covers rotation while running and while stopped.
  • M12-R3 (refreshed on use, and the remaining bound stated): TestTailnetSessionIsRefreshedOnUse, TestTailnetUnusedSessionLapses and TestTailnetRefusedRequestIsNotReissued. The idle limit is 30 days, chosen by the operator on the checkpoint (option A, Tailnet sessions that survive restarts and end on rotation #231 (comment)). It lives in session.Idle (internal/session/session.go:48) and in the docs at docs/introduction.md:431 (Max-Age=2592000 in the Set-Cookie example), :448, :451-452, and contrib/mdn.1:59-60. Each says the limit counts idle time, not a fixed lifetime.
  • M12-R4 (protections kept, nothing new at rest): the cookie attributes are asserted in the unit tests and the e2e suite. Nothing is written to disk. The throttle, loopback and bearer-token tests pass unchanged.
  • M12-R5 (this task's share): the introduction and the man page. The record belongs to the doc-synthesizer.

Decisions and deviations

Checks

make check and make e2e pass locally (Chromium 153). Run against the v0.3.0 tree's binary, the new e2e suite fails on the restart leg, as it should.

No feat commit: nothing user-facing is added. The commits are fix, test, and one docs for the prose.

🤖 Generated with Claude Code

davison and others added 5 commits September 30, 2026 11:20
serveBase starts a second Server over the notes and token file an earlier
one used, which is what a restarted process has and nothing more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…231)

A session was a random id in the daemon's memory, so every restart,
upgrade and reboot logged every device out. It is now a signed value:
v1.<issued-at>.<random id>.<HMAC-SHA256>, the MAC over the fields and the
tailnet name, keyed by a key derived from the token (token.Store.Derive).
Nothing about sessions is held in memory or on disk, so:

- a daemon started over the same token file derives the same key and
  accepts the cookie the browser kept;
- mdn token --rotate, or a token file replaced while stopped, changes the
  key, and every older cookie fails its MAC on the next request;
- no secret is at rest beyond the token file.

A session a day old or more is reissued on a request the guard serves,
with Max-Age equal to the idle limit (session.Idle, 30 days pending the
operator's answer on the checkpoint), and refused once unused for that
long. The token's generation counter is replaced by the derived key;
AuthenticateDerive keeps the one-read guarantee the login needs. The
throttle, loopback, the bearer token's exemption and the cookie's
attributes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Chromium logs in through a local TLS proxy that stands in for tailscale
serve; the daemon is stopped and started and the same cookie is still a
session; a rotation while running, and one while stopped, end it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The introduction's browser-on-the-tailnet section and the running guide:
a login survives restarts and upgrades, ends on rotation or after 30 days
unused, and every device logs in once more at the upgrade to v0.3.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davison

davison commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Review — 5f8bf1c

Reviewer seat, clean context, under the operator's gh auth. Head unchanged since dispatch. Worktree at 5f8bf1c, detached. I read the diff before the PR body.

The design holds up under attack. The MAC, rotation, host binding, refresh gating and cookie attributes all behave as the Decision says, against a real daemon behind TLS and in Chromium. The one blocking item is procedural: the unused-session gate is still open on #231, and the contract forbids approving past it. Everything else is a nit.

Findings

1. blocking (procedural): the gate on #231 is unresolved. #231 still carries cc:needs-decision for the idle-limit checkpoint (#231 (comment)). The reviewer contract says never to approve with that label on the task. I am not judging which option is right. I checked the "one-constant change" claim for the code, and it holds: Idle (internal/session/session.go:48) is the only place the value lives. setSessionCookie derives Max-Age from it, and every test uses session.Idle or RefreshAfter by name (grep for 2592000|30 \* 24|30 days over *.go finds only line 48). Nothing in code needs changing for B: 400 × 86400 = 34,560,000 s is exactly Chromium's cap, so it is not clamped. The docs are a different count; see 4. Fix: the operator answers the gate. If the answer is A, nothing changes and this finding is closed. Otherwise a re-review covers only the constant and the doc lines.

2. nit: an earlier token written back revives its sessions, and nothing says so. This is a change from v0.3.0. There, the generation counter moved on any change of value, so a restored token never brought an old session back within a process. Now a cookie is good for as long as its token is in force.
Measured with my rig (attack.mjs, real daemon, TLS proxy):

A after rotate (running): 401
A after the old token is written back (running): 200

Restoring --state from a backup is a plausible way to hit this, straight after a rotation made to revoke a device. The idle limit still bounds it. This is arguably the right semantics: anyone holding that token could log in anyway. Both the #231 Decision and the docs say rotation ends sessions "by construction", though, and this is the case where it doesn't. Fix: one sentence in the Decision's trade-offs and in the introduction's rotation bullet: "Writing an earlier token back, for example by restoring a backup, makes the sessions signed with it good again, up to their idle limit."

3. nit: the id length check is untested. I made seven mutations and ran go test ./internal/session ./internal/server ./internal/token. Six were caught: host dropped from the MAC, skew check removed, reissue before the Origin and allow-list checks, derive ignoring the token, the canonical issued-at check removed, and hmac.Equal swapped for != (that one is untestable, as expected). This one survived:

err != nil || len(raw) != idBytes   →   err != nil && len(raw) != idBytes
ok github.com/davison/md-notes/internal/session / server / token

The consequence is nil, because the id is under the MAC. But the Decision lists "an id … of the wrong decoded length" as refused, and no test pins it. Fix: add a resign(key, host, "v1", parts[1], <15-byte id>) case to TestTamperingIsRefused. Its test-builder already exists for exactly this.

4. nit: the docs. The upgrade logout appears in one place, and the idle limit in more places than the PR body says.

  • The one extra login at the v0.3.1 upgrade is in docs/introduction.md:452-457 only. docs/running.md:65, where an operator reads about restarts and upgrades, now says "Restarting or upgrading the daemon does not", and that is untrue for exactly one upgrade. Add a clause there. The man page can stay version-agnostic.
  • The PR body says a different idle limit is "session.Idle plus the two doc sentences that name it". The value appears in four places: docs/introduction.md:431 (Max-Age=2592000 in the Set-Cookie example), :446, :449, and contrib/mdn.1:60. Name all four so the gate follow-up doesn't miss the Max-Age example.
  • docs/running.md:65 is no longer wrapped like the rest of the paragraph (it runs past 100 columns).

5. nit: a small deviation from the plan. The plan's refresh bullet says a reissue keeps the "same id, new issued-at". sessionOf calls session.Issue, which draws a new random id (internal/server/tailnet.go:118). A new id is fine and arguably better, and nothing depends on the id. It is just unrecorded. Fix: a line in the Decision, or in the PR's deviations list.

6. nit: the PR closes nothing (closingIssuesReferences: []). The contract wants that list to name the task. The body's first line is clean, with no BOM or zero-width characters (od -c shows C l o s e s d a v i s o n / m d - n o t e s # 2 3 1 \n). The base is main, the default branch, and the PR is not cross-repo. What stands out is that no earlier PR in this repo used the owner-qualified form for a same-repo issue. #219's Closes #214 and #218's Closes #215 both linked. The qualified self-reference is the likeliest reason GitHub made no link. I have not proven it by editing the body. Fix: make the first line Closes #231, then check gh pr view 232 --json closingIssuesReferences shows [231] and nothing else. Not a code finding.

Your specific questions, answered

  • Re-login leaves the old value valid. Measured: re-login: old A: 200 / new B 200. I think this is acceptable, and it needs no extra gate. The superseded value sits in a browser that has already overwritten it. It lasts exactly as long as any unused session, which is the idle limit the open gate asks about. And a copy of a cookie someone else is using stays live until rotation under either design, which the gate's option A text already says. The Tailnet access: extra Host name, token login and session cookie #39 point ("a credential nothing will present should not stay live") is weakened from "at once" to "within the idle limit". The Decision's trade-offs record this. Nothing more is needed.
  • The removed 64-session cap. It bounded memory, not access: Tailnet access: extra Host name, token login and session cookie #39's own text says it was there "so that repeated logins cannot grow the map". With no map, nothing grows. Minting still needs the token. Failed logins are still throttled: 20 wrong logins: 4537 ms, last status 429, then correct login after: 303 in 2 ms.
  • "Generation" now is simply the token value. A byte-different re-save of the same token (leading spaces, trailing blank lines, new inode) is not a rotation: A after same token re-saved with whitespace (running): 200, and 200 again after a restart. read trims, as it did before.

What I verified, and how

Checks. make check exited 0 in my worktree (Go, UI and extension tests, vet, build, extension zip). CI: gate, check and e2e all SUCCESS, so they ran rather than skipped.

Commit types, per the local rule. I read each commit against its files:

  • 175f8f7 test(server): server_test.go only.
  • e8af254 fix(session): code and tests.
  • a6c80bb test(e2e): the suite.
  • aec7e9e fix(man): contrib/mdn.1, so CI runs for it. Correct.
  • 5f8bf1c docs: docs/introduction.md and docs/running.md only. Correct.

The MAC.

  • Key. HMAC-SHA256(key=token, "mdn session key v1"): a keyed PRF with a versioned purpose label, so it is domain-separated, and neither the raw token nor a bare hash.
  • Coverage. The MAC covers version, host, issued-at and id, joined with \x00. The only field that could contain a NUL is the host, and that comes from config, not the client. strconv digits and base64url cannot, so the encoding has no boundary ambiguity.
  • Canonical input. Decoding is strict (RawURLEncoding.Strict(), exact decoded lengths). Issued-at must round-trip through FormatInt, so +, leading zeros and -0 are refused. The comparison is hmac.Equal.
  • Hostile input, signed with the real key. I derived the key from the token in the rig, so these reached the MAC-valid path. Every one returned 401 and the daemon stayed up: issued-at 9223372036854775807, -9223372036854775808, -1 and 0.
  • Garbage. Empty, ..., 5,000 dots, unicode, = padding and surrounding spaces all gave 401 with no panic. A 60 kB value gets Go's 431. The quoted form "<valid>" is accepted, because Go's cookie parser unquotes it. That is harmless.
  • Timing. Mean over 300 requests: garbage 0.280 ms, wrong MAC 0.163 ms, valid 0.151 ms. That is noise, not an oracle, and the early rejects only look at public shape.

Rotation.

  • mdn token --rotate while running: 401. A pre-rotation cookie two days old gets 401 and no Set-Cookie, so refresh cannot outlive rotation. The reissue is signed with the same key value that just verified the cookie, so a rotation between check and reissue cannot mint under the new token.
  • Rotated while stopped, then started: 401.
  • The v0.3.0 → head upgrade: the v0.3.0 cookie gets 401 once, then a login, a restart, and 200.
  • Rotate-back: see finding 2.

Host binding.

  • A cookie presented under another Host is refused by the Host guard (403 bad_host).
  • The same token with the daemon reconfigured to other.tailnet.test: 401.
  • On loopback the cookie is never consulted. A valid cookie with a foreign Origin gets the loopback 403. POST /login on loopback gets 405 and no Set-Cookie. A bearer request on loopback gets 200 and no Set-Cookie. So neither the extension nor a loopback caller can mint or use a session.

Expiry and refresh.

issued status Set-Cookie
1 hour ago 200 none
2 days ago, served 200 yes
2 days ago, foreign Origin 403 none
2 days ago, loopback-only write 403 none
29 d 23 h ago 200 yes
30 d ago 401 none
4 min in the future 200 none
6 min in the future 401 none
1 h in the future 401 none

A two-day-old cookie on a path the mux answers with the SPA fallback also gets 200 and a new cookie. That counts as served, and it is fine.

Cookie attributes. Each issued cookie reads Path=/; Max-Age=2592000; HttpOnly; Secure; SameSite=Strict, with __Host- and no Domain, on both the login and the reissue (one function sets both). 2,592,000 s is well under the 400-day cap.

The e2e proof, with the fix reverted. I built the v0.3.0 tree (1c9698b) and ran MDN_BIN=<that> node --test e2e/tailnet-session.test.mjs. It fails on the restart leg:

✖ keeps a login across a daemon restart … actual: { status: 401, login: true }, expected: { status: 200, login: false }

On the head binary all three legs pass.

The implementer's table, measured again. My own Playwright script: headless Chromium on a persistent profile behind a Node TLS proxy, with a second go build of the head standing in for build 2.

Step v0.3.0 tree head (build 1, then build 2)
logged in once app 200, api 200 app 200, api 200
daemon restarted, same token login page 401, api 401, cookie present app 200, api 200
browser closed and reopened login page 401 app 200
--app window, same profile login page 401 app 200
rotated while running login page 401 login page 401
rotated while stopped, then started login page 401 login page 401
restarted again, same token login page 401 app 200

It matches the Decision's table. My by-hand replay row went out with the wrong Host, because Node's fetch drops a Host header, so I don't count it. The same replay through the TLS proxy is in attack.mjs: the first cookie, after rotate / write-back / rotate-while-stopped, gets 401.

Docs. The introduction's Authentication section, docs/running.md and contrib/mdn.1 all say that restarts, upgrades and reboots don't end a login, and that rotation (running or stopped) and 30 days unused do. The introduction states the v0.3.1 one-time login, and that a lost device someone keeps using stays in until you rotate. No stale "restart logs out" claim remains (grep of docs/, README.md, contrib/, internal/session). The only command the docs add, mdn token --rotate [--token-file], was run as written by both rigs.

Capture candidates

None. The clock-forward-then-corrected case (sessions reissued under a clock set in the future are refused once it's put right, costing one login) is inherent to any time-stamped cookie and not worth a capture on a desktop host.

Verdict: changes requested

davison and others added 2 commits September 30, 2026 11:36
Review nit 3 on PR #232: removing the id-length check went unnoticed.
Three re-signed cases, a byte short, a byte long and empty, now fail
against that mutation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#231)

Review nits 2 and 4 on PR #232: the introduction's rotation bullet says
that writing an earlier token back makes its sessions good again, up to
the idle limit; docs/running.md no longer says an upgrade never logs a
device out, and is rewrapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davison davison changed the title fix(session): a tailnet login survives restarts and ends on rotation (#231) fix(session): a tailnet login survives restarts and ends on rotation (#231). Sep 30, 2026
@davison davison changed the title fix(session): a tailnet login survives restarts and ends on rotation (#231). fix(session): a tailnet login survives restarts and ends on rotation (#231) Sep 30, 2026
@davison davison closed this Sep 30, 2026
@davison davison reopened this Sep 30, 2026
davison and others added 2 commits September 30, 2026 11:38
…me (#231)

The operator chose a 30-day idle limit on the checkpoint; the page now
says idle, as the introduction does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davison

davison commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Closing: GitHub never linked this PR to #231 (no connected event, closingIssuesReferences empty after body, title and close/reopen edits), so task finish refuses NO_PR. A replacement PR from the same branch follows straight after this comment; I will link it here. The review rounds on this PR stand: #232 (comment)

@davison

davison commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Replaced by #233.

davison added a commit that referenced this pull request Sep 30, 2026
Review nit 3 on PR #232: removing the id-length check went unnoticed.
Three re-signed cases, a byte short, a byte long and empty, now fail
against that mutation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
davison added a commit that referenced this pull request Sep 30, 2026
…#231)

Review nits 2 and 4 on PR #232: the introduction's rotation bullet says
that writing an earlier token back makes its sessions good again, up to
the idle limit; docs/running.md no longer says an upgrade never logs a
device out, and is rewrapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tailnet sessions that survive restarts and end on rotation

1 participant