Record a failed refresh on the linked identity row so another process does not re-present the token
A failed or timed-out refresh attempt now writes refresh_failed_at under the row lock; a process that takes the lock inside a 60 s backoff answers managed_credential_refresh_failed without calling the provider. Rotation, revocation and re-link clear the marker. Closes the cross-process residual that refresh-once-per-token left to a follow-up, and pins it on the two-pool rig. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2bd5096d81
commit
f5f4b2830f
7 changed files with 156 additions and 21 deletions
|
|
@ -16,6 +16,14 @@ export const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000;
|
|||
*/
|
||||
export const MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* After a refresh attempt fails or times out, no process presents the row's
|
||||
* refresh token again until this long has passed (the failure is recorded on
|
||||
* the row, read under the lock). A provider that rotates may have consumed the
|
||||
* token before the attempt was aborted, and presenting it again reads as theft.
|
||||
*/
|
||||
export const MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS = 60 * 1000;
|
||||
|
||||
export interface ManagedCredentialContext {
|
||||
config: HeimdallConfig;
|
||||
store: HeimdallStore;
|
||||
|
|
@ -68,10 +76,8 @@ function withoutTokens(identity: StoredLinkedIdentity): StoredLinkedIdentity {
|
|||
* attempt is in flight join it and receive its outcome, success or failure.
|
||||
* The entry lives exactly as long as the attempt: a later request retries.
|
||||
*
|
||||
* Known residual risk (docs/service-contract.md): one presentation per
|
||||
* process per burst, so N processes may present one token N times. The
|
||||
* cross-process failed-refresh marker that would close it is
|
||||
* joystick:follow_up:cross-process-failed-refresh-marker.
|
||||
* Across processes the row owns it: a failed attempt leaves a marker on the
|
||||
* row, and a process that takes the lock inside the backoff presents nothing.
|
||||
*/
|
||||
const refreshesInFlight = new WeakMap<HeimdallStore, Map<string, Promise<ManagedCredentialOutcome>>>();
|
||||
|
||||
|
|
@ -120,10 +126,15 @@ async function refreshUnderLock(
|
|||
const runtime = ctx.oauthRuntimes[provider];
|
||||
|
||||
let revocation: ManagedCredentialRevocationReason | undefined;
|
||||
let failed = false;
|
||||
const decide = async (locked: StoredLinkedIdentity): Promise<CredentialDecision> => {
|
||||
if (!locked.accessTokenEncrypted || !dueForRefresh(locked, runtime, clock())) {
|
||||
return { kind: "keep" };
|
||||
}
|
||||
if (locked.refreshFailedAt && clock() - Date.parse(locked.refreshFailedAt) < MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS) {
|
||||
failed = true;
|
||||
return { kind: "keep" };
|
||||
}
|
||||
const updatedAt = new Date(clock()).toISOString();
|
||||
const refreshToken = ctx.tokenCustody.decrypt(locked.refreshTokenEncrypted!);
|
||||
|
||||
|
|
@ -139,7 +150,8 @@ async function refreshUnderLock(
|
|||
revocation = "provider_revoked";
|
||||
return { kind: "revoke", updatedAt };
|
||||
}
|
||||
throw new ManagedCredentialRefreshFailed(provider);
|
||||
failed = true;
|
||||
return { kind: "failed", failedAt: updatedAt };
|
||||
}
|
||||
|
||||
let refreshTokenEncrypted: string;
|
||||
|
|
@ -174,6 +186,9 @@ async function refreshUnderLock(
|
|||
createdAt: new Date(clock()).toISOString(),
|
||||
});
|
||||
}
|
||||
if (failed) {
|
||||
throw new ManagedCredentialRefreshFailed(provider);
|
||||
}
|
||||
if (!committed) {
|
||||
return { kind: "revoked", identity: withoutTokens(snapshot) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -203,7 +203,13 @@ export class InMemoryStore implements HeimdallStore {
|
|||
if (decision.kind === "keep") {
|
||||
return clone(current);
|
||||
}
|
||||
if (decision.kind === "failed") {
|
||||
const marked: StoredLinkedIdentity = { ...current, refreshFailedAt: decision.failedAt };
|
||||
this.linkedIdentities.set(id, clone(marked));
|
||||
return clone(marked);
|
||||
}
|
||||
const next: StoredLinkedIdentity = { ...current, updatedAt: decision.updatedAt };
|
||||
delete next.refreshFailedAt;
|
||||
delete next.accessTokenEncrypted;
|
||||
delete next.refreshTokenEncrypted;
|
||||
delete next.tokenExpiresAt;
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ interface LinkedIdentityRow extends QueryResultRow {
|
|||
access_token_encrypted: string | null;
|
||||
refresh_token_encrypted: string | null;
|
||||
token_expires_at: string | null;
|
||||
refresh_failed_at: string | null;
|
||||
scopes: string;
|
||||
profile_json: Record<string, unknown>;
|
||||
created_at: string;
|
||||
|
|
@ -207,6 +208,10 @@ function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity {
|
|||
identity.tokenExpiresAt = new Date(row.token_expires_at).toISOString();
|
||||
}
|
||||
|
||||
if (row.refresh_failed_at) {
|
||||
identity.refreshFailedAt = new Date(row.refresh_failed_at).toISOString();
|
||||
}
|
||||
|
||||
return identity;
|
||||
}
|
||||
|
||||
|
|
@ -777,6 +782,7 @@ export class PostgresStore implements HeimdallStore {
|
|||
access_token_encrypted = EXCLUDED.access_token_encrypted,
|
||||
refresh_token_encrypted = EXCLUDED.refresh_token_encrypted,
|
||||
token_expires_at = EXCLUDED.token_expires_at,
|
||||
refresh_failed_at = NULL,
|
||||
scopes = EXCLUDED.scopes,
|
||||
profile_json = EXCLUDED.profile_json,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
|
|
@ -822,7 +828,13 @@ export class PostgresStore implements HeimdallStore {
|
|||
const row = mapLinkedIdentityRow(expectRow(locked.rows[0], "updateLinkedIdentityCredential"));
|
||||
const decision = await decide(row);
|
||||
let committed = row;
|
||||
if (decision.kind !== "keep") {
|
||||
if (decision.kind === "failed") {
|
||||
const marked = await client.query<LinkedIdentityRow>(
|
||||
"UPDATE linked_identities SET refresh_failed_at = $2 WHERE id = $1 RETURNING *",
|
||||
[id, decision.failedAt]
|
||||
);
|
||||
committed = mapLinkedIdentityRow(expectRow(marked.rows[0], "updateLinkedIdentityCredential"));
|
||||
} else if (decision.kind !== "keep") {
|
||||
const rotated = decision.kind === "rotate" ? decision : undefined;
|
||||
const written = await client.query<LinkedIdentityRow>(
|
||||
`
|
||||
|
|
@ -830,6 +842,7 @@ export class PostgresStore implements HeimdallStore {
|
|||
SET access_token_encrypted = $2,
|
||||
refresh_token_encrypted = $3,
|
||||
token_expires_at = $4,
|
||||
refresh_failed_at = NULL,
|
||||
scopes = $5,
|
||||
updated_at = $6
|
||||
WHERE id = $1
|
||||
|
|
|
|||
|
|
@ -123,6 +123,11 @@ ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT;
|
|||
-- compares it against the target the redeeming app states.
|
||||
ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS target_id TEXT;
|
||||
|
||||
-- When a refresh attempt on this row last failed or timed out, read under the row
|
||||
-- lock so a second Heimdall process does not present the same refresh token
|
||||
-- right behind it. Cleared by rotation, revocation and re-link.
|
||||
ALTER TABLE linked_identities ADD COLUMN IF NOT EXISTS refresh_failed_at TIMESTAMPTZ;
|
||||
|
||||
-- One attempt handle may bind at most one unconsumed completion (R21.1): a
|
||||
-- second completion for the same handle would let the by-attempt UPDATE in
|
||||
-- consumeAuthCompletionByAttempt match more than one row, silently consuming
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ export interface StoredLinkedIdentity {
|
|||
accessTokenEncrypted?: string;
|
||||
refreshTokenEncrypted?: string;
|
||||
tokenExpiresAt?: string;
|
||||
/** When a refresh attempt last failed; cleared by the next rotation, revocation or re-link. */
|
||||
refreshFailedAt?: string;
|
||||
scopes: string[];
|
||||
profileJson: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
|
|
@ -58,8 +60,9 @@ export interface UpsertLinkedIdentityInput {
|
|||
|
||||
/**
|
||||
* What the owner of a refresh decides after reading the row under its lock.
|
||||
* `rotate` and `revoke` write token columns, scopes and updated_at only; they
|
||||
* never touch account, profile or identity fields.
|
||||
* `rotate` and `revoke` write token columns, scopes, updated_at and clear the
|
||||
* failed-refresh marker; `failed` writes the marker alone. None touches
|
||||
* account, profile or identity fields.
|
||||
*/
|
||||
export type CredentialDecision =
|
||||
| { kind: "keep" }
|
||||
|
|
@ -71,7 +74,8 @@ export type CredentialDecision =
|
|||
scopes: string[];
|
||||
updatedAt: string;
|
||||
}
|
||||
| { kind: "revoke"; updatedAt: string };
|
||||
| { kind: "revoke"; updatedAt: string }
|
||||
| { kind: "failed"; failedAt: string };
|
||||
|
||||
export interface StoredSession {
|
||||
id: string;
|
||||
|
|
|
|||
Loading…
Reference in a new issue