Skip to content

Tailnet sessions that survive restarts and end on rotation #231

Closed

Description

@davison

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

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 token token.Store holds (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_host is refused under another even with the same token.
  • Check. Exact field count and lengths (a truncated or padded MAC is refused before comparing), hmac.Equal for 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 Authenticate returns the generation today): token.Store gets 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 one Set-Cookie a 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-Age equals 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 caps Max-Age at 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 on Rotate and on a replaced file, is stable across Open of the same file (a restart), and authenticate-and-derive is one read.
  • internal/server (over HTTP): restart (log in on one Server, present the cookie to a new Server over 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 new Server: 401); forged/replayed cookies (other token, other host, tampered, truncated, pre-rotation); refresh (Set-Cookie after 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/e2e suite that runs the built mdn behind a TLS proxy in Node (a self-signed certificate from openssl, --host-resolver-rules in 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 where openssl is 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 --app legs 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

  1. added
    cc:task
    on Sep 30, 2026
  2. davison commented on Sep 30, 2026

    @davison
    OwnerAuthor

    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 the cc:needs-decision label. The resolution is gathered into the milestone record; task finish refuses while the label is present or the gate lacks a resolution comment.

  3. added
    cc:needs-decision
    on Sep 30, 2026
  4. self-assigned this
    on Sep 30, 2026
  5. davison commented on Sep 30, 2026

    @davison
    OwnerAuthor

    Started by @davison.

  6. davison commented on Sep 30, 2026

    @davison
    OwnerAuthor

    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 is HMAC-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 is hmac.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-host behind a local TLS proxy standing in for tailscale serve):

    Step v0.3.0 tree (1c9698b) this branch (build 1, then build 2 of the same tree)
    logged in once app, 200 app, 200
    daemon restarted, same token login page, 401 app, 200
    browser closed and reopened, same profile login page app, 200
    --app window, same profile login page app, 200
    token 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
    first cookie replayed by hand after two rotations 401 401

    Upgrade 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.Check takes 1.1 µs/op (go test -bench), plus one HMAC for the derivation. The one stat per request that the token already costs is unchanged.

    Why the #39 rejections no longer hold.

    • "A signed stateless cookie … makes the token the signing key for a bearer credential that leaves the machine." The signing key is derived from the token, not the token itself, and the token cannot be recovered from the cookie (TestTheValueDoesNotCarryTheKey, TestDerivedKeyMovesOnlyWhenTheTokenDoes).
    • "Nothing to revoke short of rotating." This was already true of the Tailnet access: extra Host name, token login and session cookie #39 design, which chose no logout and names rotation as the revocation that matters.
    • "A per-request rolling renewal (a Set-Cookie on every response…)." A reissue happens at most once a day. M12-R3 requires refresh on use.
    • "Persisting sessions beside roots.json." Still rejected: M12-R4 forbids a second secret at rest.

    Trade-off:

    • Logging in again no longer deletes the session the browser held. That cookie stays valid until its own idle limit, though the browser has already overwritten it. TestLoggingInAgainEndsTheOldSession becomes TestLoggingInAgainIssuesAFreshSession.
    • The store's cap of 64 sessions goes, since there is no store to grow.
    • The token's generation counter is replaced by the derived key. AuthenticateDerive keeps the one-read guarantee at login, so a rotation mid-login cannot sign a cookie under a token the browser never presented.

    Rejected:

    • (b) a persisted store in --state: a second secret at rest, which is the operator's decision under M12-R4, and it still needs a rotation check.
    • Keeping the token itself as the HMAC key: the derivation costs nothing and keeps the key and the token distinct.
    • Leaving the host out of the MAC: a cookie issued under one tailnet_host would then check under another name that holds the same token (TestTailnetCookieIsBoundToItsHostName).

    Installed app: a real install through CDP PWA.install fails with kNotValidManifestForWebApp behind the self-signed certificate. That is Chromium's installability check refusing an untrusted origin. The --app window 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.

  7. davison commented on Sep 30, 2026

    @davison
    OwnerAuthor

    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 --state from 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.

  8. 5 remaining items

  9. davison commented on Sep 30, 2026

    @davison
    OwnerAuthor

    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's Closes #231 at merge, even with the operator's manual Development link in place — the same failure recorded in the deviation above (5909597289).

  10. davison commented on Sep 30, 2026

    @davison
    OwnerAuthor

    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.

    1. Nothing pins the cookie across builds (M12-R1, "an upgrade to a newer build"). Every Go test and the e2e suite issue and check a session with the same build, so they cannot see a change that makes one build's cookie unreadable to the next.
      • What I did: changed KeyPurpose in internal/session/session.go from "mdn session key v1" to "mdn session key v1x", then ran go 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.
      • What happened:
        ok  github.com/davison/md-notes/internal/session  0.001s
        ok  github.com/davison/md-notes/internal/server   8.238s
        ok  github.com/davison/md-notes/internal/token    0.003s
        
      • What should happen: R1 says a session survives an upgrade. The plan covers the "newer build" leg only with the scratch rig, so no test enforces it.
      • Suggested guard: one known-answer vector in internal/session: a fixed token, host, issued-at and id, the expected value as a literal, and a Check that 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 bump v1.
    2. Nothing asserts "no second secret at rest" (M12-R4). The PR says nothing is written to disk. I confirmed it by tracing the daemon (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 beside roots.json would pass every test. A server test could list the --state directory 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

cc:task

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions