Repository navigation
feat: long-lived client authentication — rotating refresh tokens for mocactl (B14, #395) - #467
Conversation
…rossoctl#395) Rotating opaque refresh tokens with reuse detection, 30-day idle and 90-day absolute login, 15-minute stateless API tokens, and mocactl auth token / logout [--all] as the hook's contract. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…, invalid_grant Found while planning: holding the plaintext successor in the family hash would leave the current refresh token at rest for the whole idle limit. A PX-expiring grace key bounds that to the grace window. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…nute API token (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…mance suite (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…no ! assertions (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ne Lua script (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…gin issues a refresh token (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ry on a rejected token (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…every command (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…d saveAuth (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…soctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…voke-all (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…octl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…mocactl logout (rossoctl#395) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… logins (rossoctl#395) Every audit XADD (Lua scripts, unknown-token write, OwnershipIndex.audit) trims with MAXLEN ~ AUDIT_MAXLEN. The TUI no longer warns of expiry when a refresh token renews the login, and /doctor renews the login before diagnosing. Log refresh store errors (message only), assert the new routes' auth, document the grace-window caveat. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Summary
The refresh-token design is solid: rotating opaque tokens, reuse detection, a grace window, Lua-atomic check+mutate+audit, roles recomputed on every refresh, and a shared conformance suite that runs against both stores and real Redis. I found no correctness bug in RefreshStore, the handlers, or ensureAuth's locking. Two things block merge. First, the branch conflicts with main, so CI has never run on these 3,275 lines of auth code. Second, two demo procedures this PR edits still read .apiToken straight out of auth.json, which breaks now that API tokens last 15 minutes.
Must-fix
- Rebase on
mainand get CI green. GitHub reportsmergeable: false(conflicts indeploy/k8s/README.md,docs/demos/vm-multi-user-demo.md, anddocs/demos/vm-two-user-acceptance.mdagainst #464/#465). Because of the conflict,ci.yml,security-scans.ymlandk8s-e2e.ymlhave not run on 13debc3. Only DCO has. The test results in the PR body come from the author's local run. When you resolvedeploy/k8s/README.md, note that #464 madeSH_API_TOKEN_TTL_SECONDSa stickysetup.shsetting, and main's text now says "lasts an hour unless setup.sh was run with SH_API_TOKEN_TTL_SECONDS". Both halves of that are now wrong (see the inline comment). - Demo header files built from
auth.json(vm-two-user-acceptance.md:254,vm-multi-user-demo.md:463; see the inline comments).
Suggestions (non-blocking)
- An unauthenticated caller can evict the audit history (inline on
refresh-redis.ts). SH_REFRESH_IDLE_TTL_SECONDS/SH_REFRESH_MAX_TTL_SECONDS/SH_REFRESH_REUSE_GRACE_SECONDSare wired into compose and the VM env example but not intodeploy/k8s. #464 just added themoca-settingsConfigMap plumbing for the token TTLs, so these probably belong in the same place. A follow-up is fine.
Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane refresh store, Redis Lua, handlers/routes/config; mocactl ensureAuth/lock/CLI/runtime), tests, OpenAPI, deploy docs/env, demo guides, spec/ADR
Agent/IDE config (.claude/.vscode): none
Commits: 17 commits, all signed-off: yes
CI status: not run on this head: the PR has merge conflicts, so only DCO (pass) ran
|
|
||
| The API token lasts an hour (`SH_API_TOKEN_TTL_SECONDS` is not set by `setup.sh`). Log in close to | ||
| the start of the acts. `MOCA_TENANCY` is unset, as on the VM demo; see its note on tenancy. | ||
| `mocactl` renews its 15-minute API token by itself, for 30 days after its last use (90 at most), so |
There was a problem hiding this comment.
must-fix (on rebase): This conflicts with #464, which reworded this paragraph to say "The API token lasts an hour unless setup.sh was run with SH_API_TOKEN_TTL_SECONDS" and made that TTL a sticky ConfigMap setting. The resolution needs both facts. The default is now 15 minutes, and a sticky SH_API_TOKEN_TTL_SECONDS (e.g. the 28800 example in §2) still overrides it. That override also stretches revocation latency to the same length, which is worth one sentence here since ADR-0039 relies on short API tokens.
There was a problem hiding this comment.
Fixed in ef3a5be (merge of main). The paragraph now says the token lasts 15 minutes unless setup.sh was run with SH_API_TOKEN_TTL_SECONDS (§2), and that a longer value buys nothing with a renewing login: mocactl logout stops new tokens at once, but a token already minted stays valid for its whole lifetime. §2's sticky-settings bullet also said an empty value gives the 3600-second default; it now says 900.
| | # | Finding | Status | | ||
| | --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | ||
| | 1 | **`/resources` without kubectl.** On a VM, `/v1/sessions/{id}/resources` answers `sandbox.phase: "unknown"`, and `mocactl` never calls the route, so nothing breaks. The route also reports `harness.mode: "knative"` on P6: `resources.ts` guesses the mode from the pod name. | Cosmetic. Make the mode honest when the route gains a VM consumer. | | ||
| | 2 | **Token expiry mid-demo.** Session tokens (5 min) re-mint on their own. The API token lasts 15 minutes and `mocactl` renews it by itself for 30 days after last use (90 at most). Only a lapsed refresh token makes the TUI open its login overlay and replay the prompt, and makes headless `mocactl run` say to run `mocactl login`. | Works as designed. A long demo needs no setting. | |
There was a problem hiding this comment.
must-fix: "A long demo needs no setting" holds for mocactl, but not for Act 2 on this page. Line 254 builds API_HDR once with jq -r '.apiToken' auth.json, and every probe/not_mine call reuses it. The cached API token is now valid for at most 15 minutes after the last mocactl command, and nothing re-reads it. If Act 2 runs past that, the probes get 401. not_mine then prints "THEIRS answers you, so it is yours", which fails safe but points the presenter at the wrong cause. Build the header from mocactl auth token instead (mocactl auth token | sed 's/^/Authorization: Bearer /' >"$API_HDR") and re-run that before each block, or wrap curl so it calls auth token each time. This also matches the spec's rule that callers never read auth.json.
There was a problem hiding this comment.
Fixed in eab0cd1. Act 2 builds API_HDR with an api_hdr helper, which pipes mocactl auth token through sed to prefix Authorization: Bearer , and probe calls it before every request. A long act therefore gets a renewed token, not a 401 that not_mine would misreport. If the login has lapsed, probe prints "no API token: run mocactl login" and stops. I checked the helper in bash and zsh against a stub mocactl that exits 0 and 3.
| ``` | ||
|
|
||
| Only tokens minted after the restart get the new lifetime, so the users log in after this (Act 1). | ||
| **The login needs no lengthening.** An API token lasts 15 minutes, and `mocactl` renews it by itself |
There was a problem hiding this comment.
must-fix (same issue): Line 463 still builds API_HDR with jq -r '.apiToken' auth.json. That is a single-use block, but the cached token can already be expired by the time it runs (more than 15 minutes since the user's last mocactl command), and then it lists nothing and returns a 401. mocactl auth token refreshes when needed and is the documented contract for this.
There was a problem hiding this comment.
Fixed in eab0cd1: 3a builds the header from mocactl auth token (renewed if it lapsed) instead of auth.json. Neither guide reads auth.json any more.
| '*', | ||
| { | ||
| ts: String(nowMs), | ||
| subject: '-', |
There was a problem hiding this comment.
suggestion: /v1/auth/token is unauthenticated, and any well-shaped mrt_ + 43 chars is free to generate. Each such request appends a refresh_refused/unknown entry to sh:cp:audit. Because every audit write now trims with MAXLEN ~ 1_000_000, roughly a million anonymous requests push out the whole history, including credential-access and refresh_reuse_detected entries. The cap fixes the memory risk but makes the audit log erasable by anyone. Two cheaper options: count unknown-token refusals (an INCR counter or a metric) instead of streaming them, or send them to a separate capped stream so sh:cp:audit only takes entries tied to a real family or principal. Rate-limiting the route would also help.
There was a problem hiding this comment.
Agreed that the cap made the history erasable. Fixed in a39072c, using your second option. A refusal of a token nobody issued, from both the TS path and the Lua family-gone path, now goes to sh:cp:audit:anon with MAXLEN ~ 100000. sh:cp:audit only takes entries tied to a real family or principal, so anonymous traffic can no longer trim it. The shared contract suite asserts this on both stores: the main stream is empty and the anon stream holds the entry. The Redis-only cap test checks both lengths. The spec §4.5 records the exception. Rate-limiting the route is not done here; it would be the cheaper next step if the anon stream itself becomes the target.
| 'createdAt', ARGV[5], 'absExp', ARGV[6], 'idleExp', ARGV[7], 'currentHash', ARGV[8], 'prevHash', '') | ||
| redis.call('PEXPIRE', KEYS[1], ARGV[9]) | ||
| redis.call('SET', KEYS[2], ARGV[1], 'PX', ARGV[9]) | ||
| redis.call('ZADD', KEYS[3], ARGV[5], ARGV[1]) |
There was a problem hiding this comment.
nit: sh:cp:owner:<h>:families has no TTL, and members are pruned only in revokeAllFor. A user who logs in from CI or fresh machines and never runs logout --all builds up one dead member per login for good. Consider PEXPIRE-ing the zset to the max TTL on each ZADD, or ZREMRANGEBYSCORE-ing members older than maxTtl on issue.
There was a problem hiding this comment.
Fixed in a39072c, with both. ISSUE now ZREMRANGEBYSCOREs members scored at or before now − maxTtl (families past the absolute limit) and PEXPIREs the set to the absolute limit on each login. A new Redis test seeds a 91-day-old member and checks that it is pruned and the TTL is set.
| | `sh:cp:owner:<subjectHash>:families` | zset | `<fid>` scored by `createdAt` | none (members pruned on read) | | ||
|
|
||
| - `fid` is a random UUID. `label` is a client-supplied hint (`mocactl` sends the hostname), capped at 64 | ||
| characters, shown in `mocactl doctor`; it is never trusted for anything. |
There was a problem hiding this comment.
nit: The spec says label is "shown in mocactl doctor", but nothing reads it back yet: doctor prints only the refreshExpiresAt date. Either drop the claim or note that it's for the deferred device-listing surface (§8).
There was a problem hiding this comment.
Fixed in a39072c. The spec now says nothing reads label back yet, and that it is stored for the device-listing surface §8 defers.
Conflicts with rossoctl#464 and rossoctl#465 in deploy/k8s/README.md and the two VM demo guides. Kept main's newer rows and settings text; the token rows say the 15-minute API token renews itself, and the k8s README's sticky SH_API_TOKEN_TTL_SECONDS default is now 900 seconds, with a note that a longer value only stretches revocation latency. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…per probe (rossoctl#395) The guides read .apiToken straight from auth.json, which goes stale 15 minutes after the last mocactl command now that API tokens are short. Act 2's probe rewrites the header before every call, so a long act gets a renewed token instead of 401s that not_mine would misreport. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ire the owner set (rossoctl#395) Review of rossoctl#467: with every audit write capped, about a million anonymous POST /v1/auth/token calls could trim away the whole sh:cp:audit history. A refusal of a token nobody issued names no family or principal, so it now goes to sh:cp:audit:anon (MAXLEN ~ 100000), and sh:cp:audit holds only entries tied to a real login or principal. The owner set of a subject's logins had no TTL. Issuing a login now drops members past the absolute limit and expires the set with its newest member. The spec no longer claims mocactl doctor shows the label. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
All six review threads are addressed in three new commits on top of 13debc3 (no history rewrite):
Local gate on the merged tree: Not in this PR: wiring |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. I checked all six threads from the last round against a39072c and they are resolved. The merge of main is clean (I checked git show --remerge-diff ef3a5be: only the three expected conflicts, resolved as described), both demo guides now get the header from mocactl auth token, unknown-token refusals go to sh:cp:audit:anon, and CI is green on every check.
Must-fix (new, one item): the owner-set pruning added in a39072c works out its cutoff from the current maxTtl, but each family's absolute expiry is stored with the family. Once an operator lowers SH_REFRESH_MAX_TTL_SECONDS, the next login drops families that are still live from the owner index, and logout --all then stops revoking them. See the inline comment. This comes from my own nit last round, sorry about that.
Nit (outside the diff): deploy/k8s/setup.sh:20 ("empty means its defaults, 3600 and 300") and deploy/k8s/base/control-plane.yaml:84 ("3600 for an API token") still give the old API-token default. It is now 900 (main.ts:94).
Deferring the SH_REFRESH_* → moca-settings wiring to a follow-up is fine.
| redis.call('PEXPIRE', KEYS[1], ARGV[9]) | ||
| redis.call('SET', KEYS[2], ARGV[1], 'PX', ARGV[9]) | ||
| local maxTtl = tonumber(ARGV[6]) - tonumber(ARGV[5]) | ||
| redis.call('ZREMRANGEBYSCORE', KEYS[3], '-inf', tostring(tonumber(ARGV[5]) - maxTtl)) |
There was a problem hiding this comment.
must-fix: This pruning and the PEXPIRE two lines down both use the current policy's maxTtl. ROTATE, though, judges each family by its own stored absExp. Suppose an operator lowers SH_REFRESH_MAX_TTL_SECONDS, say from 90 d to 7 d, which is a typical tightening after an incident. The next login by that user then:
ZREMRANGEBYSCOREs every family created more than 7 days ago, even though those families keep working until their storedabsExp, up to 90 days out, andPEXPIREs the whole set to 7 days.
revokeAllFor only walks this zset, so mocactl logout --all no longer revokes those families. The lost laptop's refresh token stays alive, and the revoke count is low with no sign that anything was missed.
Suggested fix: score members by absExp instead of createdAt. Then ZREMRANGEBYSCORE owner -inf now removes exactly the dead families under any policy, and the set can expire at its highest score (PEXPIREAT to the max score, or only ever extend the TTL, never shorten it). Spec §4.2's row and the 91-day Redis test would need updating too. A test that issues under a long policy, then under a short one, then calls revokeAllFor would pin this down.
There was a problem hiding this comment.
Fixed in ca9c0ec. Owner-set members are now scored by each family's own absExp instead of createdAt.
ISSUEprunesZREMRANGEBYSCORE owner -inf now, which removes exactly the dead families whatever the policy is.- The set's
PEXPIREis computed from its highest score, so it can never be shorter than any member it indexes. - I used a relative
PEXPIREfrom the caller'snowMs, notPEXPIREAT, to match every other TTL in the store: expiry is judged from stored fields, and TTLs only collect garbage, so tests can drive the clock.
New Redis test, as you suggested: issue under a 90-day policy, then 8 days later issue under a 7-day policy on the same keyspace. The old family is still indexed, the set's TTL is over 80 days, revokeAllFor returns 2, and the old token gets revoked. The spec §4.2 row is updated. Your nit is fixed in the same commit: the setup.sh:20 and control-plane.yaml:84 comments now say 900.
…ossoctl#395) Review of rossoctl#467: pruning by now - maxTtl used the CURRENT policy. Lowering SH_REFRESH_MAX_TTL_SECONDS would then unindex families that still work until their stored absExp, so logout --all would silently stop ending them, and the set's TTL would shrink below its members'. Members are now scored by absExp: pruning drops exactly the dead ones under any policy, and the set expires with its latest member. Also: the API-token default in deploy/k8s's setup.sh and control-plane.yaml comments is 900, not 3600. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Re-review addressed in ca9c0ec: owner-set members are scored by each family's own |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Re-review at ca9c0ec: the must-fix from a39072c is fixed. Owner-set members are now scored by each family's own absExp. ISSUE prunes -inf..now and expires the set from its highest score, so lowering SH_REFRESH_MAX_TTL_SECONDS no longer unindexes live families, and logout --all still ends them. The new 90 d → 7 d Redis test covers this. The prune boundary (<= now) matches ROTATE's nowMs >= absExp refusal. revokeAllFor is the only other reader of the set and walks it by rank, and the memory store has no index to keep in step. The 900 s default comments in setup.sh/control-plane.yaml are fixed, and the moca-settings wiring is tracked in #470.
Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (refresh-redis, tests), spec, k8s comments
Agent/IDE config (.claude/.vscode): none
Commits: 21 commits, all signed-off: yes
CI status: passing (14/14 on ca9c0ec)
Sixteen ADRs still said Proposed although their decisions are in code on main. Each status line now names the merged PRs that implemented it and the date the core landed (format of ADR-0042), and notes what is still owed where only part is built: - 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041) - 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225) - 0032 (rossoctl#249, rossoctl#350, as amended by MI1) - 0035 (rossoctl#251; ADR-0048 adds lease mode beside it) - 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481) - 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620) - 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed) - 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed) - 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the security review's lease sections are signed off) The README index follows, and its 0033 row, which still said Proposed after rossoctl#249 accepted the ADR, is corrected. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ifications Adds the five MOCA_NOTIFY_* vars to all three deploy targets (vm env example, compose pass-through, k8s optional configMapKeyRefs), bumps the control-plane OpenAPI version to 1.38.0 with a CHANGELOG entry for GET/PUT/DELETE /v1/notifications, updates change-policy.md's running version citation, and adds an operator section to the multi-user guide covering sink setup, webhook verification, the two rate limits, and that the approval deep link 404s until #467/B8b lands. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…clarifications MOCA_NOTIFY_PER_HOUR and its mute behavior are a fixed window (two bookkeeping fields, not a sliding log of timestamps), but the env example and the multi-user doc both said "rolling" -- fixed and rolling windows reset and re-arm differently, so this was an operator-facing inaccuracy, not just phrasing. Also documents: the X-Moca-Delivery header carries the batch's head cursor rather than a fresh id per attempt (CHANGELOG), that the approve deep link 404s until the login-gated approval page (#467/B8b) lands (CHANGELOG, openapi.yaml), notify-store's advance() against a DELETE racing a sweep's read-modify-write, and renderNotification's "first paused event only" batching behavior. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Summary
After a night away,
mocactl(and the Claude Code hook planned on top of it) reattaches without an interactive login. The credential that allows this can be revoked, and every refresh is audited. Closes #395 (epic #378, item B14).docs/specs/2026-10-08-b14-long-lived-client-auth-design.mdHow it works
XADDas one Lua script. A refresh can never rotate without being audited, and two concurrent callers can never both rotate.What's in it
Control plane
RefreshStoreinterface with two implementations:RedisRefreshStore(Lua) andMemoryRefreshStore. One conformance suite runs against both, pinning the §4.3 check order and the exact audit entry for every outcome.POST /v1/auth/token,/v1/auth/revoke(RFC 7009-shaped, always 200) and/v1/auth/revoke-all. The device-flow response gainsrefreshTokenandrefreshExpiresAt, and its request takes an optionallabel.SH_ADMIN_SUBJECTSon every refresh.invalid_grant(400).SH_REFRESH_IDLE_TTL_SECONDS,SH_REFRESH_MAX_TTL_SECONDSandSH_REFRESH_REUSE_GRACE_SECONDS.SH_API_TOKEN_TTL_SECONDSnow defaults to 900.MAXLEN ~ 1000000, because an unauthenticated route can now append to it.mocactl
ensureAuth(). Refreshes are serialized by anO_EXCLlock that carries an ownership token, so a process only releases its own lock. A stale lock is broken by renaming it aside. After waiting, the client re-readsauth.json, writes the new pair before using it, and gives the refresh call a 20 s timeout.mocactl auth token [--json]is the hook's whole contract: it prints a token, or exits 3 (log in) or 4 (control plane unreachable), and never prompts.mocactl logout [--all]is new too.Docs: the env example, compose,
deploy/k8sanddeploy/vmREADMEs, and the two VM demo guides, which no longer need the 4-hour token workaround.Compatibility
auth.jsonfrom an older mocactl, or a hand-minted one (p4-turn-smoke.sh, the deploy/vm recipe), has no refresh token and works as before until itsexpiresAt.Known limits (documented, deferred)
mocactl doctor's "renews until" date shows the 90-day cap; the 30-day idle limit can end the login sooner.Testing
make lint,make typecheckandmake testall pass: control-plane 600, mocactl 664, and every other package.mocactl auth token), "revoked token refused" and "refreshes audited".🤖 Generated with Claude Code