Refresh managed credentials under a row lock, with typed revocation

refreshLinkedIdentityCredentialIfNeeded is deleted. refreshManagedCredential
owns the policy; HeimdallStore.updateLinkedIdentityCredential owns the row
(SELECT ... FOR UPDATE in Postgres, a per-id chain in memory), so a refresh
token is presented once across concurrent requests and processes. invalid_grant
clears the tokens (410 managed_credential_revoked); any other failure keeps
them (502 managed_credential_refresh_failed). The "?? refreshToken" keep-old
fallback is gone; keeping it is an explicit branch for non-rotating providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-19 11:11:34 +02:00
commit c81f923890
10 changed files with 979 additions and 99 deletions

View file

@ -34,6 +34,7 @@ import {
summarizePatreonMemberships,
type OAuthRuntimeRegistry,
} from "./oauth.js";
import { ManagedCredentialRefreshFailed, refreshManagedCredential } from "./managed-credential.js";
import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js";
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js";
import { createStore, type HeimdallStore } from "./store/index.js";
@ -44,8 +45,6 @@ import {
type UpsertLinkedIdentityInput,
} from "./store/types.js";
const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000;
export interface BuildAppOptions {
config?: HeimdallConfig;
store?: HeimdallStore;
@ -367,63 +366,6 @@ function centsToDecimalString(cents: number): string {
return (cents / 100).toFixed(2);
}
async function refreshLinkedIdentityCredentialIfNeeded(options: {
config: HeimdallConfig;
store: HeimdallStore;
tokenCustody: TokenCustody;
oauthRuntimes: OAuthRuntimeRegistry;
linkedIdentity: StoredLinkedIdentity;
now: string;
}): Promise<StoredLinkedIdentity> {
const expiresAt = options.linkedIdentity.tokenExpiresAt ? Date.parse(options.linkedIdentity.tokenExpiresAt) : undefined;
if (
!expiresAt ||
expiresAt - Date.now() > MANAGED_CREDENTIAL_REFRESH_SKEW_MS ||
!options.linkedIdentity.refreshTokenEncrypted
) {
return options.linkedIdentity;
}
const runtime = options.oauthRuntimes[options.linkedIdentity.provider];
if (!runtime.refreshAccessToken) {
return options.linkedIdentity;
}
const refreshToken = options.tokenCustody.decrypt(options.linkedIdentity.refreshTokenEncrypted);
const refreshed = await runtime.refreshAccessToken({
config: options.config,
refreshToken,
});
const upsertInput: UpsertLinkedIdentityInput = {
id: options.linkedIdentity.id,
accountId: options.linkedIdentity.accountId,
provider: options.linkedIdentity.provider,
providerUserId: options.linkedIdentity.providerUserId,
accessTokenEncrypted: options.tokenCustody.encrypt(refreshed.accessToken),
refreshTokenEncrypted: options.tokenCustody.encrypt(refreshed.refreshToken ?? refreshToken),
scopes: refreshed.scope.length ? refreshed.scope : options.linkedIdentity.scopes,
profileJson: options.linkedIdentity.profileJson,
createdAt: options.linkedIdentity.createdAt,
updatedAt: options.now,
};
const tokenExpiresAt = refreshed.expiresAt ?? options.linkedIdentity.tokenExpiresAt;
if (tokenExpiresAt !== undefined) {
upsertInput.tokenExpiresAt = tokenExpiresAt;
}
if (options.linkedIdentity.username !== undefined) {
upsertInput.username = options.linkedIdentity.username;
}
if (options.linkedIdentity.displayName !== undefined) {
upsertInput.displayName = options.linkedIdentity.displayName;
}
if (options.linkedIdentity.primaryEmail !== undefined) {
upsertInput.primaryEmail = options.linkedIdentity.primaryEmail;
}
return options.store.upsertLinkedIdentity(upsertInput);
}
function storedIdentityToResolvedIdentity(identity: StoredLinkedIdentity) {
const resolved = {
provider: identity.provider,
@ -450,7 +392,6 @@ async function evaluateStoredEntitlements(options: {
appSlug: AppSlug;
accountId: string;
entitlementPolicies: OAuthEntitlementPolicy[];
now: string;
}): Promise<string[]> {
const profile = getAppProfile(options.appSlug);
if (!profile) {
@ -460,19 +401,13 @@ async function evaluateStoredEntitlements(options: {
const facts: string[] = [];
for (const storedIdentity of linkedIdentities) {
if (!profile.entitlementSources.includes(storedIdentity.provider) || !storedIdentity.accessTokenEncrypted) {
if (!profile.entitlementSources.includes(storedIdentity.provider)) {
continue;
}
const linkedIdentity = await refreshLinkedIdentityCredentialIfNeeded({
config: options.config,
store: options.store,
tokenCustody: options.tokenCustody,
oauthRuntimes: options.oauthRuntimes,
linkedIdentity: storedIdentity,
now: options.now,
});
if (!linkedIdentity.accessTokenEncrypted) {
const refreshed = await refreshManagedCredential(options, storedIdentity);
const linkedIdentity = refreshed.identity;
if (refreshed.kind === "revoked" || !linkedIdentity.accessTokenEncrypted) {
continue;
}
@ -714,7 +649,6 @@ export async function refreshAppSession(
appSlug,
accountId: refreshClaim.account_id,
entitlementPolicies,
now: nowIso,
});
const issueInput: IssueAccessClaimInput = {
appSlug,
@ -1620,21 +1554,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
}
const storedLinkedIdentity = await store.findStoredLinkedIdentityForAccount(request.body.accountId, "patreon");
if (!storedLinkedIdentity?.accessTokenEncrypted) {
if (!storedLinkedIdentity) {
reply.code(404);
return { error: "patreon_identity_not_linked" };
}
const now = new Date().toISOString();
const linkedIdentity = await refreshLinkedIdentityCredentialIfNeeded({
config,
store,
tokenCustody,
oauthRuntimes,
linkedIdentity: storedLinkedIdentity,
now,
});
if (!linkedIdentity.accessTokenEncrypted) {
const refreshed = await refreshManagedCredential({ config, store, tokenCustody, oauthRuntimes }, storedLinkedIdentity);
const linkedIdentity = refreshed.identity;
if (refreshed.kind === "revoked" || !linkedIdentity.accessTokenEncrypted) {
reply.code(404);
return { error: "patreon_identity_not_linked" };
}
@ -1772,22 +1700,24 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
}
const storedLinkedIdentity = await store.findStoredLinkedIdentityForAccount(request.body.accountId, request.body.provider);
if (!storedLinkedIdentity?.accessTokenEncrypted) {
if (!storedLinkedIdentity) {
reply.code(404);
return { error: "managed_credential_not_found" };
}
const now = new Date().toISOString();
const linkedIdentity = await refreshLinkedIdentityCredentialIfNeeded({
config,
store,
tokenCustody,
oauthRuntimes,
linkedIdentity: storedLinkedIdentity,
now,
});
if (!linkedIdentity.accessTokenEncrypted) {
reply.code(404);
return { error: "managed_credential_not_found" };
let refreshed;
try {
refreshed = await refreshManagedCredential({ config, store, tokenCustody, oauthRuntimes }, storedLinkedIdentity);
} catch (error) {
if (error instanceof ManagedCredentialRefreshFailed) {
reply.code(502);
return { error: error.code, provider: error.provider };
}
throw error;
}
const linkedIdentity = refreshed.identity;
if (refreshed.kind === "revoked" || !linkedIdentity.accessTokenEncrypted) {
reply.code(410);
return { error: "managed_credential_revoked", provider: linkedIdentity.provider };
}
const response: {

140
src/managed-credential.ts Normal file
View file

@ -0,0 +1,140 @@
import { type HeimdallConfig } from "./config.js";
import { type Provider } from "./contracts.js";
import { type TokenCustody } from "./custody.js";
import { type OAuthProviderRuntime, type OAuthRuntimeRegistry, ProviderResponseError } from "./oauth.js";
import { providerCatalog } from "./providers.js";
import { type HeimdallStore } from "./store/index.js";
import { type CredentialDecision, type StoredLinkedIdentity } from "./store/types.js";
/** A stored access token this close to expiry (or past it) is refreshed before use. */
export const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000;
/**
* The longest a refresh may hold the row lock: the provider call is aborted
* at this bound, and every waiter holds a pooled connection for at most this
* long behind the holder.
*/
export const MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS = 10_000;
export interface ManagedCredentialContext {
config: HeimdallConfig;
store: HeimdallStore;
tokenCustody: TokenCustody;
oauthRuntimes: OAuthRuntimeRegistry;
clock?: () => number;
timeoutMs?: number;
}
export type ManagedCredentialRevocationReason = "provider_revoked" | "rotation_missing";
/** `revoked` means the identity holds no access token: the provider took the grant back, or it was never held. */
export type ManagedCredentialOutcome =
| { kind: "current"; identity: StoredLinkedIdentity }
| { kind: "revoked"; identity: StoredLinkedIdentity };
/**
* The provider could not be asked, or answered with something that is not a
* grant verdict (invalid_client, 5xx, timeout, malformed body). The stored
* tokens are untouched. Carries the provider and nothing the provider said.
*/
export class ManagedCredentialRefreshFailed extends Error {
readonly code = "managed_credential_refresh_failed";
readonly provider: Provider;
constructor(provider: Provider) {
super(`${providerCatalog[provider].displayName} managed credential refresh failed.`);
this.name = "ManagedCredentialRefreshFailed";
this.provider = provider;
}
}
function dueForRefresh(identity: StoredLinkedIdentity, runtime: OAuthProviderRuntime, now: number): boolean {
if (!identity.tokenExpiresAt || !identity.refreshTokenEncrypted || !runtime.refreshAccessToken) {
return false;
}
return Date.parse(identity.tokenExpiresAt) - now <= MANAGED_CREDENTIAL_REFRESH_SKEW_MS;
}
function withoutTokens(identity: StoredLinkedIdentity): StoredLinkedIdentity {
const { accessTokenEncrypted: _a, refreshTokenEncrypted: _r, tokenExpiresAt: _e, ...rest } = identity;
return rest;
}
/**
* The one refresh policy. `snapshot` is a hint: it may skip the lock when no
* refresh is due and never decides one. The row's lock owns when a refresh
* token is presented; the decision is made on the row as read under it.
*/
export async function refreshManagedCredential(
ctx: ManagedCredentialContext,
snapshot: StoredLinkedIdentity
): Promise<ManagedCredentialOutcome> {
const clock = ctx.clock ?? Date.now;
const provider = snapshot.provider;
const runtime = ctx.oauthRuntimes[provider];
if (!snapshot.accessTokenEncrypted) {
return { kind: "revoked", identity: snapshot };
}
if (!dueForRefresh(snapshot, runtime, clock())) {
return { kind: "current", identity: snapshot };
}
let revocation: ManagedCredentialRevocationReason | undefined;
const decide = async (locked: StoredLinkedIdentity): Promise<CredentialDecision> => {
if (!locked.accessTokenEncrypted || !dueForRefresh(locked, runtime, clock())) {
return { kind: "keep" };
}
const updatedAt = new Date(clock()).toISOString();
const refreshToken = ctx.tokenCustody.decrypt(locked.refreshTokenEncrypted!);
let refreshed;
try {
refreshed = await runtime.refreshAccessToken!({
config: ctx.config,
refreshToken,
signal: AbortSignal.timeout(ctx.timeoutMs ?? MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS),
});
} catch (error) {
if (error instanceof ProviderResponseError && error.oauthError === "invalid_grant") {
revocation = "provider_revoked";
return { kind: "revoke", updatedAt };
}
throw new ManagedCredentialRefreshFailed(provider);
}
let refreshTokenEncrypted: string;
if (refreshed.refreshToken) {
refreshTokenEncrypted = ctx.tokenCustody.encrypt(refreshed.refreshToken);
} else if (providerCatalog[provider].rotatesRefreshTokens) {
revocation = "rotation_missing";
return { kind: "revoke", updatedAt };
} else {
refreshTokenEncrypted = locked.refreshTokenEncrypted!;
}
const tokenExpiresAt = refreshed.expiresAt ?? locked.tokenExpiresAt;
return {
kind: "rotate",
accessTokenEncrypted: ctx.tokenCustody.encrypt(refreshed.accessToken),
refreshTokenEncrypted,
...(tokenExpiresAt !== undefined ? { tokenExpiresAt } : {}),
scopes: refreshed.scope.length ? refreshed.scope : locked.scopes,
updatedAt,
};
};
const committed = await ctx.store.updateLinkedIdentityCredential(snapshot.id, decide);
if (revocation) {
await ctx.store.createAuditEvent({
accountId: snapshot.accountId,
eventType: "managed_credential_revoked",
eventPayloadJson: { provider, reason: revocation },
createdAt: new Date(clock()).toISOString(),
});
}
if (!committed) {
return { kind: "revoked", identity: withoutTokens(snapshot) };
}
return { kind: committed.accessTokenEncrypted ? "current" : "revoked", identity: committed };
}

View file

@ -61,6 +61,25 @@ export interface OAuthProviderRuntime {
}): Promise<EntitlementEvaluation>;
}
const oauthErrorCodes = [
"invalid_request",
"invalid_client",
"invalid_grant",
"unauthorized_client",
"unsupported_grant_type",
"invalid_scope",
] as const;
export type OAuthErrorCode = (typeof oauthErrorCodes)[number];
function readOAuthErrorCode(text: string): OAuthErrorCode | undefined {
try {
const error = (JSON.parse(text) as { error?: unknown } | null)?.error;
return oauthErrorCodes.find((code) => code === error);
} catch {
return undefined;
}
}
/**
* A provider answer Heimdall cannot use: a non-2xx status, or a body that is
* not JSON. It carries the status and a code, never the body or the parser's
@ -71,12 +90,18 @@ export interface OAuthProviderRuntime {
export class ProviderResponseError extends Error {
readonly status: number;
readonly code: "provider_status" | "provider_body_not_json";
/**
* The RFC 6749 section 5.2 error code of a refusal, when the provider sent
* one from that closed set. The only value taken from a provider's body.
*/
readonly oauthError: OAuthErrorCode | undefined;
constructor(status: number, code: ProviderResponseError["code"], failure: string) {
constructor(status: number, code: ProviderResponseError["code"], failure: string, oauthError?: OAuthErrorCode) {
super(`${failure} (status ${status}, ${code}).`);
this.name = "ProviderResponseError";
this.status = status;
this.code = code;
this.oauthError = oauthError;
}
}
@ -84,7 +109,7 @@ export class ProviderResponseError extends Error {
async function readProviderJson<T>(response: Response, failure: string): Promise<T> {
const text = await response.text();
if (!response.ok) {
throw new ProviderResponseError(response.status, "provider_status", failure);
throw new ProviderResponseError(response.status, "provider_status", failure, readOAuthErrorCode(text));
}
if (!text) {
return {} as T;

View file

@ -6,6 +6,7 @@ import {
type CreateAuthCompletionInput,
type CreateAuditEventInput,
type CreateCapabilityGrantInput,
type CredentialDecision,
type CreateEntitlementSnapshotInput,
type CreateSessionInput,
type CreatePrivateCommandReceiptInput,
@ -37,6 +38,8 @@ function isGrantActive(grant: StoredCapabilityGrant, appSlug: AppSlug, at: strin
}
export class InMemoryStore implements HeimdallStore {
/** Tail of each linked identity's credential-decision chain; an entry is removed when it drains. */
private readonly credentialChains = new Map<string, Promise<unknown>>();
private readonly accounts = new Map<string, StoredAccount>();
private readonly linkedIdentities = new Map<string, StoredLinkedIdentity>();
private readonly grants = new Map<string, StoredCapabilityGrant>();
@ -174,6 +177,45 @@ export class InMemoryStore implements HeimdallStore {
return clone(linkedIdentity);
}
async updateLinkedIdentityCredential(
id: string,
decide: (locked: StoredLinkedIdentity) => Promise<CredentialDecision>,
): Promise<StoredLinkedIdentity | null> {
const previous = this.credentialChains.get(id) ?? Promise.resolve();
const run = previous.then(async () => {
const current = this.linkedIdentities.get(id);
if (!current) {
return null;
}
const decision = await decide(clone(current));
if (decision.kind === "keep") {
return clone(current);
}
const next: StoredLinkedIdentity = { ...current, updatedAt: decision.updatedAt };
delete next.accessTokenEncrypted;
delete next.refreshTokenEncrypted;
delete next.tokenExpiresAt;
if (decision.kind === "rotate") {
next.accessTokenEncrypted = decision.accessTokenEncrypted;
next.refreshTokenEncrypted = decision.refreshTokenEncrypted;
if (decision.tokenExpiresAt !== undefined) {
next.tokenExpiresAt = decision.tokenExpiresAt;
}
next.scopes = [...decision.scopes];
}
this.linkedIdentities.set(id, clone(next));
return clone(next);
});
const tail = run.catch(() => undefined);
this.credentialChains.set(id, tail);
void tail.then(() => {
if (this.credentialChains.get(id) === tail) {
this.credentialChains.delete(id);
}
});
return run;
}
async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> {
return [...this.linkedIdentities.values()]
.filter((identity) => identity.accountId === accountId)

View file

@ -8,6 +8,7 @@ import {
type CreateAuthCompletionInput,
type CreateAuditEventInput,
type CreateCapabilityGrantInput,
type CredentialDecision,
type CreateEntitlementSnapshotInput,
type CreateSessionInput,
type CreatePrivateCommandReceiptInput,
@ -546,7 +547,7 @@ export async function checkSchemaRequirements(pool: Pick<Pool, "query">, require
}
export class PostgresStore implements HeimdallStore {
constructor(private readonly pool: Pick<Pool, "query" | "end">) {}
constructor(private readonly pool: Pick<Pool, "query" | "end" | "connect">) {}
async ensureSchema(): Promise<void> {
await this.pool.query(CREATE_SCHEMA_SQL);
@ -722,6 +723,60 @@ export class PostgresStore implements HeimdallStore {
return mapLinkedIdentityRow(expectRow(result.rows[0], "upsertLinkedIdentity"));
}
async updateLinkedIdentityCredential(
id: string,
decide: (locked: StoredLinkedIdentity) => Promise<CredentialDecision>,
): Promise<StoredLinkedIdentity | null> {
const client = await this.pool.connect();
try {
await client.query("BEGIN");
try {
const locked = await client.query<LinkedIdentityRow>(
"SELECT * FROM linked_identities WHERE id = $1 FOR UPDATE",
[id]
);
if (!locked.rowCount) {
await client.query("COMMIT");
return null;
}
const row = mapLinkedIdentityRow(expectRow(locked.rows[0], "updateLinkedIdentityCredential"));
const decision = await decide(row);
let committed = row;
if (decision.kind !== "keep") {
const rotated = decision.kind === "rotate" ? decision : undefined;
const written = await client.query<LinkedIdentityRow>(
`
UPDATE linked_identities
SET access_token_encrypted = $2,
refresh_token_encrypted = $3,
token_expires_at = $4,
scopes = $5,
updated_at = $6
WHERE id = $1
RETURNING *
`,
[
id,
nullable(rotated?.accessTokenEncrypted),
nullable(rotated?.refreshTokenEncrypted),
nullable(rotated?.tokenExpiresAt),
(rotated?.scopes ?? row.scopes).join(" "),
decision.updatedAt,
]
);
committed = mapLinkedIdentityRow(expectRow(written.rows[0], "updateLinkedIdentityCredential"));
}
await client.query("COMMIT");
return committed;
} catch (error) {
await client.query("ROLLBACK");
throw error;
}
} finally {
client.release();
}
}
async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> {
const result = await this.pool.query<LinkedIdentityRow>(
`

View file

@ -56,6 +56,23 @@ export interface UpsertLinkedIdentityInput {
updatedAt: string;
}
/**
* 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.
*/
export type CredentialDecision =
| { kind: "keep" }
| {
kind: "rotate";
accessTokenEncrypted: string;
refreshTokenEncrypted: string;
tokenExpiresAt?: string;
scopes: string[];
updatedAt: string;
}
| { kind: "revoke"; updatedAt: string };
export interface StoredSession {
id: string;
accountId: string;
@ -213,6 +230,17 @@ export interface HeimdallStore {
findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise<StoredLinkedIdentity | null>;
listStoredLinkedIdentitiesForAccount(accountId: string): Promise<StoredLinkedIdentity[]>;
upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity>;
/**
* Serialise decisions about one row's credential. `decide` receives the row
* as read under the lock (never a caller's snapshot) and the decision is
* committed before this resolves, so a rotated pair is persisted before any
* caller sees the new access token. Returns the committed row, or null when
* no row has that id. A throw from `decide` writes nothing.
*/
updateLinkedIdentityCredential(
id: string,
decide: (locked: StoredLinkedIdentity) => Promise<CredentialDecision>,
): Promise<StoredLinkedIdentity | null>;
listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]>;
createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant>;
listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]>;