Skip to content

AI-2617: guest refresh secrets expire, and a replayed one clears them - #2678

Merged
Loschcode merged 5 commits into
mainfrom
laurentschaffner/ai-2617-guest-refresh-secrets-never-expire
Nov 29, 2026
Merged

Loschcode merged 5 commits into
mainfrom
laurentschaffner/ai-2617-guest-refresh-secrets-never-expire

Conversation

@Loschcode

@Loschcode Loschcode commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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).

  • Every writer sets users.refresh_secret_expires_at: InsertGuest, RotateGuestSecret, SetGuestSecret and GiveGuestSecret.
  • RotateGuestSecret checks the expiry inside its one UPDATE, so the check is atomic.
  • An expired secret is ErrGuestSecretRefused, the same answer as a wrong secret: the caller is minted a new guest and learns nothing.
  • A guest whose secret expired is given a new one by their own still-valid token (GiveGuestSecret).

Reuse detection, at any depth. A secret is now <family>.<random>.

  • Every rotation keeps the family (NextGuestSecret). SetGuestSecret and GiveGuestSecret start a new one.
  • users.refresh_family_secret_hash holds the family's hash.
  • A redeem that misses is checked by clearReplayedGuestSecret. It is a replay (ErrGuestSecretReplayed) when its secret:
    • is of the guest's family but is not the secret held, however many rotations ago it was spent; or
    • is the one the last rotation spent (previous_refresh_secret_hash). That is the only check a secret from before families gets.
  • An expired secret that is the one held is only refused.
  • A secret from before families still redeems, and the secret it rotates to starts a family.

What a replay does.

  • It clears refresh_secret_hash and keeps previous_refresh_secret_hash as a mark.
  • GiveGuestSecret gives 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.
  • SetGuestSecret clears the mark, which leaves the app's backend as the only way back.
  • redeemGuestSecret logs 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.

  • So the secret the last rotation spent is only refused for GuestSecretReplayGrace (30s) after it, and is not treated as leaked.
  • The rotation time is 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_at is in the users vouched list, so an import or a replayed change never overwrites the expiry of a secret handed out here. The secret itself never moves.
  • Both new hash columns end in _secret_hash. isSecret and 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 to users.

  • refresh_secret_expires_at defaults to now() + interval '30 days'.
    • This takes Postgres's fast-default path, with no table rewrite. I checked on PG 19 that the relfilenode is unchanged and atthasmissing is set.
    • The default dates every secret already handed out from the deploy. It also covers guests that a router of the release before inserts while this one rolls out.
  • The other two are previous_refresh_secret_hash and refresh_family_secret_hash.
  • schema/global.sql is regenerated.
  • Main's newest global migration is 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_secret field docs mention the expiry. openapi.yaml and 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.

  • The router has nothing that revokes a user's tokens, and it verifies guest JWTs itself (internal/auth).
  • Stream's revoke_tokens_issued_before exists through a user update, but the router's own check would not honour it.
  • So a thief keeps the token their redeem gave them until it expires (24h). Because of the mark, that token cannot get a new secret.

Overlap. #2668 (AI-2122) also edits internal/api/guests.go, in the claim path. It does not overlap redeemGuestSecret or returningGuest's secret code.

Tests

In internal/store (StoreSuite and DataMoveSuite):

  • TestAnExpiredRefreshSecretIsRefused
  • TestAnExpiredSecretOfTheFamilyIsOnlyRefused
  • TestEveryWayAGuestIsHandedASecretStartsItsThirtyDays: insert, rotate, set, give
  • TestASpentSecretPresentedAgainClearsTheGuestsSecretAndLeavesAMark: the guest's own token then gets no secret, and the backend brings them back
  • TestASecretSpentRotationsAgoIsSeenAsLeaked: the thief rotates S1→S2→S3, then the victim presents S1
  • TestAnotherFamilysSecretIsOnlyWrong
  • TestASpentSecretPresentedRightAfterItsRotationIsOnlyRefused
  • TestConcurrentRedeemsOfOneSecretRotateItOnceAndClearNothing: 8 at once
  • TestARotationThatLandsWhileARedeemOfTheSameSecretWaitsIsNoSignOfALeak: a rotation holds the row lock, the second redeem waits on it, then the rotation commits
  • TestASecretTheBackendSetIsNotClearedByAnOlderOneComingBack
  • TestAGuestWhoseSecretExpiredIsGivenANewOneByTheirOwnToken
  • TestASecretFromBeforeTheMigrationRedeemsAndStartsAFamily: a row written as the release before writes it, dated by the column default
  • TestImportingAGuestAgainLeavesTheExpiryOfTheSecretHandedOutHere: import, give, import again with a stale expiry and with none, then redeem
  • TestGuestQueryBudgets: a refused secret costs 2 queries
  • The export and change-feed tests assert neither new hash column leaves. TestATriggerThatWouldRecordASecretIsRefused covers the new columns.

In internal/api (GuestsSuite):

  • TestAnExpiredRefreshSecretMintsANewGuest
  • TestASpentRefreshSecretPresentedAgainClearsTheGuestsSecrets
  • TestAfterAReplayTheTokenTheLeakedSecretWasRedeemedForGetsNoNewSecret
  • TestASecretSpentRotationsAgoIsSeenAsLeaked
  • TestAGuestWhoseSecretExpiredIsHandedANewOneByTheirOwnToken
  • TestTwoRequestsRedeemingOneSecretBringTheGuestBackOnce, extended: the stored hash is the winner's, not cleared

Run locally against Postgres 19, all passing:

  • the guest and secret tests of TestStoreSuite
  • TestDataMoveSuite, TestServingRoleSuite, TestShardedStoreSuite/TestTheSchemaFilesAreCurrent
  • TestGuestsSuite, TestGuestsProxiedSuite, TestAdmissionSuite, TestRequestKeyMintSuite
  • go vet ./..., gofmt and the generated-files check are clean.

Each rule was reverted on its own in a scratch copy, and these tests then failed:

Reverted Failing tests
Expiry check in the rotating UPDATE TestAnExpiredRefreshSecretIsRefused, TestAnExpiredSecretOfTheFamilyIsOnlyRefused, TestAnExpiredRefreshSecretMintsANewGuest
The replay grace TestARotationThatLandsWhileARedeemOfTheSameSecretWaitsIsNoSignOfALeak, TestConcurrentRedeemsOfOneSecretRotateItOnceAndClearNothing, TestASpentSecretPresentedRightAfterItsRotationIsOnlyRefused, TestTwoRequestsRedeemingOneSecretBringTheGuestBackOnce, TestARefreshSecretWorksOnce and two more
The replay clear both TestASecretSpentRotationsAgoIsSeenAsLeaked, TestASpentSecretPresentedAgainClearsTheGuestsSecretAndLeavesAMark, TestASpentRefreshSecretPresentedAgainClearsTheGuestsSecrets, TestAfterAReplayTheTokenTheLeakedSecretWasRedeemedForGetsNoNewSecret
Family match (previous hash only) both TestASecretSpentRotationsAgoIsSeenAsLeaked
The mark (clear the previous hash on a replay) TestASpentSecretPresentedAgainClearsTheGuestsSecretAndLeavesAMark, TestAfterAReplayTheTokenTheLeakedSecretWasRedeemedForGetsNoNewSecret
GiveGuestSecret's mark check the same two
GiveGuestSecret's expired branch both …WhoseSecretExpiredIs…ByTheirOwnToken tests
Rotation moving the expiry TestEveryWayAGuestIsHandedASecretStartsItsThirtyDays
SetGuestSecret clearing the previous hash TestASecretTheBackendSetIsNotClearedByAnOlderOneComingBack
refresh_secret_expires_at in vouched TestImportingAGuestAgainLeavesTheExpiryOfTheSecretHandedOutHere

🤖 Generated with Claude Code

…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>
@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it.

How it works

  • Findings come as inline comments, each starting with [Must Fix], [Should Fix], nit: or consider:.
  • Push fixes whenever you're ready. Once the branch has been quiet for 10 minutes I review the new head and resolve the threads it fixes. To skip the wait, comment /jeffery review.
  • If you disagree or have a question, reply in the thread. I'll answer there, and resolve it if you're right.
  • I approve once every must-fix and should-fix is closed and nobody has requested changes. CI isn't part of that; branch protection still holds the merge until it's green. From round 3 on, open should-fix findings stop blocking.
  • I don't approve release/* branches or changes to protected paths, and I'll say so when that applies.
  • If a must-fix is still open after round 8, I stop and hand the PR to a human. Draft PRs wait until they're marked ready.

Commands (each as a whole comment)

Command What it does
/jeffery review Review the current head now
/jeffery rereview Start over at round 1 on the current head and withdraw my approval. This redoes the whole review and costs as much as the first one, so use it only when you don't trust the earlier rounds. If nothing changed since my last round I say so instead; add force to redo it anyway
/jeffery pause / /jeffery resume Stop or restart automatic reviews on this PR
/jeffery status What I last reviewed, and why I have or haven't approved
/jeffery help This list

/review-agent or a mention of me works in place of /jeffery.

@getstream-metis

Copy link
Copy Markdown

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>
Laurent Schaffner and others added 2 commits November 27, 2026 17:31
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2 on 361b195d95e3 · 🆕 1 new
Still open: 1 should-fix. Full list on the checks tab.

Laurent Schaffner and others added 2 commits November 27, 2026 18:00
…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>

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3 on bb263365f830 · 🆕 2 new

Comment thread acceleration/internal/store/guest.go Resolved
Comment thread acceleration/internal/store/guest.go Resolved

@getstream-metis getstream-metis Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved bb263365f830 after 3 rounds · 1 fixed · 2 dropped after discussion

@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

/jeffery review

Nothing changed since round 3 on bb263365f830; comment /jeffery rereview force to redo the full review anyway.

@Loschcode
Loschcode merged commit 1ea2154 into main Nov 29, 2026
24 checks passed
@Loschcode
Loschcode deleted the laurentschaffner/ai-2617-guest-refresh-secrets-never-expire branch November 29, 2026 12:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant