Repository navigation
AI-2617: guest refresh secrets expire, and a replayed one clears them - #2678
Merged
Loschcode merged 5 commits intoNov 29, 2026
Merged
Conversation
…them A refresh secret now stops working 30 days after it was issued or last rotated, checked in the rotating UPDATE. The secret a rotation spends is kept; presented again after a 30 second grace, it means somebody else holds a copy, so both of the guest's secrets are cleared and the replay is logged at warn. Inside the grace it is only refused, so two requests from one device carrying the same secret are not taken for a theft. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
Author
|
/jeffery review |
|
Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it. How it works
Commands (each as a whole comment)
|
|
No open findings, but I'm not approving this head: required sweep skipped; push a commit or comment /jeffery rereview. |
Loschcode
added a commit
that referenced
this pull request
Nov 27, 2026
## Why https://linear.app/stream/issue/AI-3202/a-reopened-fork-loses-its-parents-turns A fork's channel starts empty, so its parent's turns reach the model only through `spec.Recall`, which is set when the fork is created. A fork that ended and is carried on from its row (`reopenedFromRow`) got no recall, so the parent's turns were lost on every reopen. This affected a fork at a `response_id` and a whole fork alike. The row only had `forked_from`, and that is not enough to rebuild the recall. A whole fork, a fork at a response, and a fork with `messages: false` all look the same there. ## What changed - **Migrations**: - `migrations/shard/20270301001930_session_fork_point.sql` adds a nullable `agent_sessions.fork_point jsonb`. It is expand-only and uses the 5s lock timeout. - The column holds `{"messages": true, "response_id": "…"}` or `{"messages": false}`. - NULL means a session that is not a fork, or a fork made before this change, which is reopened as today. - I chose jsonb over a text column because a text column would need a sentinel string mixed in with response ids to say "none". - `migrations/global/20270301009100_session_index_fork_point.sql` adds the same column to `session_index`, and `fork_point` is added to `indexedSessions`. The session lists read every model column from the shared copy. - **Version slots:** shard `20270301001930` is above main's `…001920`. Global `20270301009100` is above main's `…008300` and above every open PR's global migration (#2678 `…008400`, #2633 `…009000`). #2247, the squash, touches both sets. - **Fork create** (`forkSession` → `forkPoint`) records where the fork's history stops: - At a response, it is that response. - For a whole fork, it is the parent's last response at the moment of the fork, read after flushing a running parent's records. The parent's later turns are therefore never the fork's. - **Reopen** (`forkRecall`) rebuilds the recall from the parent's recorded turns on the path to the cut (`Responses.ExchangesAt`), whatever was rewound or regenerated since: - `ExchangesAt` reads the session's responses once, walks `parent_response_id` up from the cut (`responseTree.pathTo`), then loads the answers. That is two queries. - Rows from before branches name no parent. Through those, the path carries on by creation time, keeping those still in the conversation at that point. - It runs on both reopen paths: from the row, and from the spec a fork ended on in this process (`carryOn`). - **The reopen never fails because of the parent:** - If the parent was deleted, or the response at the cut no longer exists, the fork goes on without the parent's turns. This is logged at info, and it also replaces what an in-process fork was opened with, so deleted data is not handed to a model again. - If the read fails, the row path goes on without the parent's turns, and the in-process path keeps what it was opened with. The warn is throttled to once a minute per app (`quota.Throttle`). - A reopened session whose recall still reads a channel (only the in-process snapshot after a failed re-read) logs a throttled warn and goes on, instead of refusing. A fresh fork that cannot read its parent is still refused. - The datamove `bareColumns` gains `fork_point`, and the `forked_from` comment now says it is read with the customer. ## Tests `internal/api/fork_reopen_test.go` (`ForkReopenSuite`) uses the `recites` model, so each answer is the exact history the model was given. Most cases run on both reopen paths: "stopped" (from the row) and "ended here" (in process). - **At a response, and whole fork.** The history after the reopen must start with the history before it. Both fail on main on the row path. - **Whole fork after the parent says more.** The reopened fork does not see the parent's later turns. It fails on the previous head on both paths. - **Parent regenerates the fork point.** The reopened fork keeps the parent's turn as it was. It fails on the previous head on both paths. - **Fork point deleted.** The fork goes on without the parent's turns. On the in-process path, the test fails if the `ErrUnknownResponse` branch is removed. - **Other cases:** - parent deleted (both paths); - `messages: false`; - a pre-deploy fork with NULL; - a whole fork of a parent without a channel; - a fork of a fork; - a fork made by a backend for another user than the parent's (at a response: a whole fork of a channel they can't read is refused at create). - **Stored fork point:** one test for each kind of fork. - **Store:** `ExchangesAt` follows the path through a regenerate, carries on through pre-branch rows, refuses an unknown or another customer's response, and stays within its query budget of 2. The fork, reopen, branch, document, connector, reopen-settings, resume-history and ownership suites pass locally. The schema files were regenerated. ## Not in this PR - A whole fork of a fork is made from a live read of its parent's channel, which holds only the parent's own turns, so the grandparent's turns are missing even at create. The `forkSpec` comment that the parent's channel "already holds both" is wrong. This predates this PR. - Tool history across a fork is still lost, because `store.ReplyItems` is scoped to the conversation id. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Laurent Schaffner <laurentschaffner@Laurents-MacBook-Pro-Stream.local> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…617-guest-refresh-secrets-never-expire
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Round 2 on 361b195d95e3 · 🆕 1 new
Still open: 1 should-fix. Full list on the checks tab.
…mark A refresh secret is now <family>.<random>, and every rotation keeps the family, so a secret of the guest's family that is not the one held is a replay however many rotations ago it was spent. A secret from before families redeems as before and starts one. A replay clears only the secret held and keeps the previous hash as a mark, so the guest's own token (possibly the thief's) cannot re-arm them; only the backend can. The own token can replace an expired secret. An import no longer overwrites the expiry of a secret handed out here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…617-guest-refresh-secrets-never-expire
Contributor
Author
|
/jeffery review |
Nothing changed since round 3 on |
Loschcode
deleted the
laurentschaffner/ai-2617-guest-refresh-secrets-never-expire
branch
November 29, 2026 12:24
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
https://linear.app/stream/issue/AI-2617/guest-refresh-secrets-never-expire-and-a-replayed-secret-goes
A guest's
refresh_secret(follow-up of AI-2487) never expired. A thief who redeemed a stolen one first kept the guest, and nothing noticed when the spent secret came back. This PR does both options from the ticket: an expiry, and reuse detection.What changed
Expiry. A refresh secret stops working 30 days after it was issued or last rotated (
store.GuestSecretTTL).users.refresh_secret_expires_at:InsertGuest,RotateGuestSecret,SetGuestSecretandGiveGuestSecret.RotateGuestSecretchecks the expiry inside its oneUPDATE, so the check is atomic.ErrGuestSecretRefused, the same answer as a wrong secret: the caller is minted a new guest and learns nothing.GiveGuestSecret).Reuse detection, at any depth. A secret is now
<family>.<random>.NextGuestSecret).SetGuestSecretandGiveGuestSecretstart a new one.users.refresh_family_secret_hashholds the family's hash.clearReplayedGuestSecret. It is a replay (ErrGuestSecretReplayed) when its secret:previous_refresh_secret_hash). That is the only check a secret from before families gets.What a replay does.
refresh_secret_hashand keepsprevious_refresh_secret_hashas a mark.GiveGuestSecretgives no secret to a guest carrying that mark, because the token asking may be the one the leaked secret was redeemed for. So the thief's token cannot re-arm the guest.SetGuestSecretclears the mark, which leaves the app's backend as the only way back.redeemGuestSecretlogs the replay at warn with the guest id only, never the secret, and answers exactly as for a wrong secret. The log comment notes that a device retrying, later than the grace, a request whose answer it lost also trips this line.Race safety. Two requests from one device carrying the same secret (two tabs, a retry) both mint before either rotates. The loser blocks on the row lock, then finds its secret spent a moment ago.
GuestSecretReplayGrace(30s) after it, and is not treated as leaked.expires_at - TTL, read in the same statement as the clear. A rotation that commits while the second redeem waits is therefore seen.Moves.
refresh_secret_expires_atis in theusersvouchedlist, so an import or a replayed change never overwrites the expiry of a secret handed out here. The secret itself never moves._secret_hash.isSecretand the older triggers' SQL copy of that rule keep them out of exports, imports and recorded changes with no code change.Migration
acceleration/migrations/global/20270301009600_users_refresh_secret_expiry.sql. It is expand-only and adds three nullable columns tousers.refresh_secret_expires_atdefaults tonow() + interval '30 days'.atthasmissingis set.previous_refresh_secret_hashandrefresh_family_secret_hash.schema/global.sqlis regenerated.20270301009100. The open PRs hold…9000([AI-4220] Per-app data keys for every sealed secret #2628) and…9500(AI-2122: move a claimed guest's mem0 memories to the account #2668), so this one takes…9600.Docs. The
refresh_secretfield docs mention the expiry.openapi.yamland every generated client are regenerated, and that is a doc-string change only. No SDK changes behaviour: secrets stay opaque strings, and a refused secret already makes a new guest.Revoking the guest's tokens: not done.
internal/auth).revoke_tokens_issued_beforeexists through a user update, but the router's own check would not honour it.Overlap. #2668 (AI-2122) also edits
internal/api/guests.go, in the claim path. It does not overlapredeemGuestSecretorreturningGuest's secret code.Tests
In
internal/store(StoreSuite and DataMoveSuite):TestAnExpiredRefreshSecretIsRefusedTestAnExpiredSecretOfTheFamilyIsOnlyRefusedTestEveryWayAGuestIsHandedASecretStartsItsThirtyDays: insert, rotate, set, giveTestASpentSecretPresentedAgainClearsTheGuestsSecretAndLeavesAMark: the guest's own token then gets no secret, and the backend brings them backTestASecretSpentRotationsAgoIsSeenAsLeaked: the thief rotates S1→S2→S3, then the victim presents S1TestAnotherFamilysSecretIsOnlyWrongTestASpentSecretPresentedRightAfterItsRotationIsOnlyRefusedTestConcurrentRedeemsOfOneSecretRotateItOnceAndClearNothing: 8 at onceTestARotationThatLandsWhileARedeemOfTheSameSecretWaitsIsNoSignOfALeak: a rotation holds the row lock, the second redeem waits on it, then the rotation commitsTestASecretTheBackendSetIsNotClearedByAnOlderOneComingBackTestAGuestWhoseSecretExpiredIsGivenANewOneByTheirOwnTokenTestASecretFromBeforeTheMigrationRedeemsAndStartsAFamily: a row written as the release before writes it, dated by the column defaultTestImportingAGuestAgainLeavesTheExpiryOfTheSecretHandedOutHere: import, give, import again with a stale expiry and with none, then redeemTestGuestQueryBudgets: a refused secret costs 2 queriesTestATriggerThatWouldRecordASecretIsRefusedcovers the new columns.In
internal/api(GuestsSuite):TestAnExpiredRefreshSecretMintsANewGuestTestASpentRefreshSecretPresentedAgainClearsTheGuestsSecretsTestAfterAReplayTheTokenTheLeakedSecretWasRedeemedForGetsNoNewSecretTestASecretSpentRotationsAgoIsSeenAsLeakedTestAGuestWhoseSecretExpiredIsHandedANewOneByTheirOwnTokenTestTwoRequestsRedeemingOneSecretBringTheGuestBackOnce, extended: the stored hash is the winner's, not clearedRun locally against Postgres 19, all passing:
TestStoreSuiteTestDataMoveSuite,TestServingRoleSuite,TestShardedStoreSuite/TestTheSchemaFilesAreCurrentTestGuestsSuite,TestGuestsProxiedSuite,TestAdmissionSuite,TestRequestKeyMintSuitego vet ./...,gofmtand the generated-files check are clean.Each rule was reverted on its own in a scratch copy, and these tests then failed:
UPDATETestAnExpiredRefreshSecretIsRefused,TestAnExpiredSecretOfTheFamilyIsOnlyRefused,TestAnExpiredRefreshSecretMintsANewGuestTestARotationThatLandsWhileARedeemOfTheSameSecretWaitsIsNoSignOfALeak,TestConcurrentRedeemsOfOneSecretRotateItOnceAndClearNothing,TestASpentSecretPresentedRightAfterItsRotationIsOnlyRefused,TestTwoRequestsRedeemingOneSecretBringTheGuestBackOnce,TestARefreshSecretWorksOnceand two moreTestASecretSpentRotationsAgoIsSeenAsLeaked,TestASpentSecretPresentedAgainClearsTheGuestsSecretAndLeavesAMark,TestASpentRefreshSecretPresentedAgainClearsTheGuestsSecrets,TestAfterAReplayTheTokenTheLeakedSecretWasRedeemedForGetsNoNewSecretTestASecretSpentRotationsAgoIsSeenAsLeakedTestASpentSecretPresentedAgainClearsTheGuestsSecretAndLeavesAMark,TestAfterAReplayTheTokenTheLeakedSecretWasRedeemedForGetsNoNewSecretGiveGuestSecret's mark checkGiveGuestSecret's expired branch…WhoseSecretExpiredIs…ByTheirOwnTokentestsTestEveryWayAGuestIsHandedASecretStartsItsThirtyDaysSetGuestSecretclearing the previous hashTestASecretTheBackendSetIsNotClearedByAnOlderOneComingBackrefresh_secret_expires_atinvouchedTestImportingAGuestAgainLeavesTheExpiryOfTheSecretHandedOutHere🤖 Generated with Claude Code