From efe6b05907378b496976443e61bfcd009716e82c Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Wed, 18 Nov 2026 20:12:16 -0500 Subject: [PATCH 1/3] fix(oidc): sign session exchange tokens only for a sign-in Each session:exchange token must claim the authorization or device code consumed for the same session and client in the same token request, and each code backs one token. The reported grant must match the code. Session exchange clients are not served the refresh_token grant. --- .changeset/session-exchange-sign-in-only.md | 5 + docs/adr/0003-native-admin-access.md | 3 +- src/services/oidcClientRegistry.ts | 21 +++- src/services/oidcPayloadStore.ts | 53 ++++++++++ src/services/oidcSigning.ts | 33 +++++-- tests/postgres/sessionExchange.spec.ts | 99 ++++++++++++++++++- .../unit/services/oidcClientRegistry.spec.ts | 20 ++++ tests/unit/services/oidcPayloadStore.spec.ts | 72 ++++++++++++++ tests/unit/services/oidcSigning.spec.ts | 70 ++++++++++++- 9 files changed, 362 insertions(+), 14 deletions(-) create mode 100644 .changeset/session-exchange-sign-in-only.md diff --git a/.changeset/session-exchange-sign-in-only.md b/.changeset/session-exchange-sign-in-only.md new file mode 100644 index 00000000..7039e827 --- /dev/null +++ b/.changeset/session-exchange-sign-in-only.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': patch +--- + +Session exchange tokens are now signed only for a sign-in. `/oidc/sign` ties each `session:exchange` token to the authorization or device code the edge consumed in the same token request, signs at most one token per code, and refuses a token whose reported grant does not match that code. A refresh grant consumes no code, so it can no longer mint a session exchange token, whatever grant type the edge reports. Session exchange clients are no longer served the `refresh_token` grant, whatever their stored grant list says, and `/oidc/sign` refuses refresh grant tokens for them. diff --git a/docs/adr/0003-native-admin-access.md b/docs/adr/0003-native-admin-access.md index e0411085..29a87f20 100644 --- a/docs/adr/0003-native-admin-access.md +++ b/docs/adr/0003-native-admin-access.md @@ -122,7 +122,8 @@ B has no usable revocation story: every event above that should end the CLI's ac - **Requested** with `resource=/seamless` (RFC 8707) and `scope=openid session:exchange`, on the authorization request or the device authorization request. - **Allowed** by the registry only for a client that is first-party, public and native (`applicationType: native`, from a loopback or private-use redirect, N2), and that an admin has turned `sessionExchangeEnabled` on for. `getOidcClientResources` adds the built-in resource with that one scope and `accessTokenTtlSeconds: 60` for such a client, the way it adds `notices:send` for a notices client. The edge already takes the lifetime from that list (`resourceServers.ts`). - **Signed** only when the token's scope is exactly `session:exchange`, `aud` is a single string equal to the built-in resource, `jti` is present and `exp - iat` is at most 120. A client credentials token can never carry the scope. -- **No refresh token.** The CLI does not ask for `offline_access`, so the only long-lived credential it ends up with is the first-party one. +- **Only at a sign-in.** Each token must be backed by an authorization or device code that the edge consumed for the same session and client in the last minute (`claimSessionExchangeSource` in `src/services/oidcPayloadStore.ts`), and each code backs at most one token. The claim is kept under a model the edge's payload routes cannot name. The grant the edge reports must match the code claimed, and that verified grant is what the X3 record stores. A refresh consumes no code, so it cannot mint one whatever grant type the edge reports, which also covers an older edge that reports every non-device grant as `authorization_code`. +- **No refresh token.** The CLI does not ask for `offline_access`, so the only long-lived credential it ends up with is the first-party one. The registry also never serves `refresh_token` to a session exchange client, whatever its stored grant list says (`servedGrantTypes` in `src/services/oidcClientRegistry.ts`), and `/oidc/sign` refuses a refresh grant for one. ## X3. Signing record and single use diff --git a/src/services/oidcClientRegistry.ts b/src/services/oidcClientRegistry.ts index b137e00b..1ff6453f 100644 --- a/src/services/oidcClientRegistry.ts +++ b/src/services/oidcClientRegistry.ts @@ -75,6 +75,21 @@ export async function findSessionExchangeClient(id: string) { return client && isSessionExchangeClient(client) ? client : null; } +/** + * The grants a client may use, whatever the stored list says. The device grant only for a + * first-party client with the flag on (ADR 0001, D10). No refresh grant for a session exchange + * client (ADR 0003, X2): its sign-ins are each one user confirmation, and a refresh token + * would let it keep asking for tokens without one. + */ +export function servedGrantTypes(client: OidcClient) { + const exchange = isSessionExchangeClient(client); + return client.grantTypes.filter( + (grant) => + (grant !== DEVICE_CODE_GRANT || (client.firstParty && client.deviceFlowEnabled)) && + (grant !== 'refresh_token' || !exchange), + ); +} + export async function getOidcClientMetadata(id: string): Promise { const client = await findActiveOidcClient(id); @@ -85,11 +100,7 @@ export async function getOidcClientMetadata(id: string): Promise grant !== DEVICE_CODE_GRANT || (client.firstParty && client.deviceFlowEnabled), - ) as OidcClientMetadata['grant_types'], + grant_types: servedGrantTypes(client) as OidcClientMetadata['grant_types'], response_types: client.grantTypes.includes('authorization_code') ? ['code'] : [], redirect_uris: client.redirectUris, post_logout_redirect_uris: client.postLogoutRedirectUris, diff --git a/src/services/oidcPayloadStore.ts b/src/services/oidcPayloadStore.ts index 45be3f48..dd35890f 100644 --- a/src/services/oidcPayloadStore.ts +++ b/src/services/oidcPayloadStore.ts @@ -223,6 +223,59 @@ export async function recordSessionExchangeToken( } } +// Under a model the edge's payload routes cannot name, so it cannot pre-claim or release a code. +const SESSION_EXCHANGE_SOURCE = 'SessionExchangeSource'; + +/** The library consumes the code and signs the token in the one token request. */ +export const SESSION_EXCHANGE_SOURCE_WINDOW_MS = 1000 * 60; + +const SESSION_EXCHANGE_SOURCE_MODELS = ['AuthorizationCode', 'DeviceCode'] as const; +export type SessionExchangeSourceModel = (typeof SESSION_EXCHANGE_SOURCE_MODELS)[number]; + +/** + * ADR 0003, X2. A session exchange token is minted only by a sign-in, so it must be backed by + * an authorization or device code for this session and client that the edge consumed in the + * same token request. Each code backs at most one token. A refresh consumes no code, so it + * finds nothing to claim whatever grant the edge reports. Returns the model of the code + * claimed, or null. + */ +export async function claimSessionExchangeSource( + sessionId: string, + clientId: string, +): Promise { + if (!isUuid(sessionId)) return null; + + const now = new Date(); + const codes = await OidcPayload.findAll({ + where: { + model: { [Op.in]: [...SESSION_EXCHANGE_SOURCE_MODELS] }, + sessionId, + payload: { clientId }, + consumedAt: { [Op.gte]: new Date(now.getTime() - SESSION_EXCHANGE_SOURCE_WINDOW_MS) }, + } as WhereOptions, + order: [['consumedAt', 'DESC']], + }); + + // A claim outlives the window, so a code is never claimable twice. + const expiresAt = new Date(now.getTime() + 2 * SESSION_EXCHANGE_SOURCE_WINDOW_MS); + for (const code of codes) { + if (code.payload.clientId !== clientId) continue; + if ( + await insertIfAbsent( + SESSION_EXCHANGE_SOURCE, + `${code.model}:${code.id}`, + { sessionId, clientId }, + expiresAt, + now, + ) + ) { + return code.model as SessionExchangeSourceModel; + } + } + + return null; +} + function findBinding(where: Record) { return OidcPayload.findOne({ where: { diff --git a/src/services/oidcSigning.ts b/src/services/oidcSigning.ts index d0861289..b8c9213b 100644 --- a/src/services/oidcSigning.ts +++ b/src/services/oidcSigning.ts @@ -15,6 +15,7 @@ import { import { constants, sign } from 'crypto'; import { getSystemConfig } from '../config/getSystemConfig.js'; +import type { OidcClient } from '../models/oidcClients.js'; import { Session } from '../models/sessions.js'; import { parseDurationToSeconds } from '../utils/utils.js'; import { @@ -23,8 +24,17 @@ import { providerTokenClaims, } from './oidcAccountClaims.js'; import { deriveAcrAmr, resolveCurrentSession, sessionAuthTime } from './oidcAuthContext.js'; -import { findActiveOidcClient, getOidcClientResourceScopes } from './oidcClientRegistry.js'; -import { hasOidcGrantForSession, recordSessionExchangeToken } from './oidcPayloadStore.js'; +import { + findActiveOidcClient, + getOidcClientResourceScopes, + servedGrantTypes, +} from './oidcClientRegistry.js'; +import { + claimSessionExchangeSource, + hasOidcGrantForSession, + recordSessionExchangeToken, + type SessionExchangeSourceModel, +} from './oidcPayloadStore.js'; import { getActiveOidcSigningKey, OidcProviderKeysError } from './oidcProviderKeys.js'; type JsonObject = Record; @@ -48,6 +58,10 @@ const MAX_SESSION_EXCHANGE_TOKEN_SECONDS = 120; // A token the user just signed in for. A refresh is not a sign-in, and the record has to // say which grant to treat the child as. const SESSION_EXCHANGE_GRANTS = new Set(['authorization_code', DEVICE_CODE_GRANT]); +const SESSION_EXCHANGE_SOURCE_GRANTS: Record = { + AuthorizationCode: 'authorization_code', + DeviceCode: DEVICE_CODE_GRANT, +}; const PROTOCOL_CLAIMS = [ 'iss', @@ -301,13 +315,13 @@ export async function recordProviderActivity(sessionId: string) { async function checkUserToken( request: OidcSignRequest, claims: JsonObject, - client: { id: string; grantTypes: string[]; firstParty: boolean; deviceFlowEnabled: boolean }, + client: OidcClient, issuer: string, ): Promise { const device = request.grantType === DEVICE_CODE_GRANT; if ( !request.grantType || - !client.grantTypes.includes(request.grantType) || + !servedGrantTypes(client).includes(request.grantType) || (device && !(client.firstParty && client.deviceFlowEnabled)) ) { return refuse('grant_not_allowed'); @@ -415,12 +429,12 @@ async function checkAccountClaims( } /** ADR 0003, X2: a token useful nowhere else, that lives briefly and can be told apart. */ -function checkSessionExchangeToken( +async function checkSessionExchangeToken( request: OidcSignRequest, claims: JsonObject, issuer: string, userId: string, -): OidcSignOutcome | null { +): Promise { if (claims.aud !== seamlessBuiltInResource(issuer)) return refuse('audience_mismatch', userId); if (claims.scope !== SESSION_EXCHANGE_SCOPE) return refuse('grant_not_allowed', userId); if (!SESSION_EXCHANGE_GRANTS.has(request.grantType as string)) { @@ -438,5 +452,12 @@ function checkSessionExchangeToken( return refuse('malformed_signing_input', userId); } + // The grant the edge reports is checked against the code the sign-in consumed, so a refresh + // reported as a sign-in, by an edge of any version, finds no code to claim. + const source = await claimSessionExchangeSource(request.sessionId as string, request.clientId); + if (!source || SESSION_EXCHANGE_SOURCE_GRANTS[source] !== request.grantType) { + return refuse('grant_not_allowed', userId); + } + return null; } diff --git a/tests/postgres/sessionExchange.spec.ts b/tests/postgres/sessionExchange.spec.ts index af7505d4..498a155f 100644 --- a/tests/postgres/sessionExchange.spec.ts +++ b/tests/postgres/sessionExchange.spec.ts @@ -202,11 +202,25 @@ function subjectClaims(client: OidcClient, userId: string, overrides = {}) { } /** Has `/oidc/sign` sign an access token, the way the edge asks for one. */ +/** The code the edge's token request consumes just before it asks for the signature. */ +async function consumeCode(client: OidcClient, parent: Session, grantType = AUTHORIZATION_CODE) { + const model = grantType === DEVICE_CODE ? 'DeviceCode' : 'AuthorizationCode'; + const id = randomUUID(); + await store.upsertOidcPayload(model, id, { + payload: { clientId: client.id, accountId: parent.userId, grantId: randomUUID() }, + expiresIn: 300, + sessionId: parent.id, + }); + expect(await store.consumeOidcPayload(model, id)).toBe(true); + return { model, id }; +} + async function signSubject( client: OidcClient, parent: Session, - { grantType = AUTHORIZATION_CODE, claims = {} } = {}, + { grantType = AUTHORIZATION_CODE, claims = {}, code = true } = {}, ) { + if (code) await consumeCode(client, parent, grantType); const body = subjectClaims(client, parent.userId, claims); const signingInput = jwtInput({ alg: 'RS256', kid: KID, typ: 'at+jwt' }, body); const outcome = await signing.signForOidcEdge({ @@ -596,6 +610,89 @@ describe('/oidc/sign for a session:exchange token', () => { expect(record?.consumedAt).not.toBeNull(); }); + describe('ties each token to the code its sign-in consumed', () => { + it('refuses a refresh reported as a code grant, since a refresh consumes no code', async () => { + const { client, parent } = await eligible(); + + const { outcome, jti } = await signSubject(client, parent, { code: false }); + + expect(outcome).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + expect( + await OidcPayload.findOne({ where: { model: 'SessionExchangeToken', id: jti } }), + ).toBeNull(); + }); + + it('signs one token per code', async () => { + const { client, parent } = await eligible(); + + expect((await signSubject(client, parent)).outcome.ok).toBe(true); + const again = await signSubject(client, parent, { code: false }); + + expect(again.outcome).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + }); + + it('refuses a code consumed before the window', async () => { + const { client, parent } = await eligible(); + const { model, id } = await consumeCode(client, parent); + await OidcPayload.update( + { consumedAt: new Date(Date.now() - store.SESSION_EXCHANGE_SOURCE_WINDOW_MS - 1000) }, + { where: { model, id } }, + ); + + const { outcome } = await signSubject(client, parent, { code: false }); + + expect(outcome).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + }); + + it('refuses a code that was stored but never consumed', async () => { + const { client, parent } = await eligible(); + await store.upsertOidcPayload('AuthorizationCode', randomUUID(), { + payload: { clientId: client.id, accountId: parent.userId }, + expiresIn: 300, + sessionId: parent.id, + }); + + const { outcome } = await signSubject(client, parent, { code: false }); + + expect(outcome).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + }); + + it('refuses a code another client consumed on the same session', async () => { + const { client, parent } = await eligible(); + await consumeCode(await nativeClient(), parent); + + const { outcome } = await signSubject(client, parent, { code: false }); + + expect(outcome).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + }); + + it('refuses a grant the edge reports that differs from the code consumed', async () => { + const { client, parent } = await eligible(); + await consumeCode(client, parent, DEVICE_CODE); + + const { outcome } = await signSubject(client, parent, { code: false }); + + expect(outcome).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + }); + + it('keeps the claims out of reach of the edge payload routes', async () => { + const { OidcPayloadModelSchema } = await import('@seamless-auth/types'); + + expect(OidcPayloadModelSchema.safeParse('SessionExchangeSource').success).toBe(false); + }); + }); + + it('serves an exchange client no refresh grant, whatever it stores', async () => { + const client = await nativeClient({ + grantTypes: [AUTHORIZATION_CODE, 'refresh_token', DEVICE_CODE], + }); + + expect((await registry.getOidcClientMetadata(client.id))?.grant_types).toEqual([ + AUTHORIZATION_CODE, + DEVICE_CODE, + ]); + }); + it('keeps the record out of reach of the edge payload routes', async () => { const { OidcPayloadModelSchema } = await import('@seamless-auth/types'); diff --git a/tests/unit/services/oidcClientRegistry.spec.ts b/tests/unit/services/oidcClientRegistry.spec.ts index 7e7b64b7..002fd096 100644 --- a/tests/unit/services/oidcClientRegistry.spec.ts +++ b/tests/unit/services/oidcClientRegistry.spec.ts @@ -144,6 +144,26 @@ describe('getOidcClientMetadata', () => { expect((await getOidcClientMetadata('app'))?.grant_types).toEqual(['refresh_token']); }); + it('lists no refresh grant for a session exchange client', async () => { + const exchange = { + clientType: 'public', + tokenEndpointAuthMethod: 'none', + redirectUris: ['http://127.0.0.1/callback'], + sessionExchangeEnabled: true, + }; + + vi.mocked(OidcClient.findByPk).mockResolvedValue(client(exchange) as never); + expect((await getOidcClientMetadata('app'))?.grant_types).toEqual(['authorization_code']); + + vi.mocked(OidcClient.findByPk).mockResolvedValue( + client({ ...exchange, sessionExchangeEnabled: false }) as never, + ); + expect((await getOidcClientMetadata('app'))?.grant_types).toEqual([ + 'authorization_code', + 'refresh_token', + ]); + }); + it.each(['http://127.0.0.1/cb', 'http://[::1]/cb', 'com.example.app:/cb'])( 'treats %s as a native redirect', async (uri) => { diff --git a/tests/unit/services/oidcPayloadStore.spec.ts b/tests/unit/services/oidcPayloadStore.spec.ts index 994f4d32..356b2a50 100644 --- a/tests/unit/services/oidcPayloadStore.spec.ts +++ b/tests/unit/services/oidcPayloadStore.spec.ts @@ -6,6 +6,7 @@ vi.mock('../../../src/models/oidcPayloads', () => ({ create: vi.fn(), upsert: vi.fn(), findOne: vi.fn(), + findAll: vi.fn(), update: vi.fn(), destroy: vi.fn(), sequelize: { query: vi.fn() }, @@ -32,6 +33,7 @@ import { DEVICE_CODE_EXPIRED_GRACE_MS, bindOidcSession, claimOAuthStateUse, + claimSessionExchangeSource, consumeOidcPayload, destroyOidcPayload, ExpiryTooLongError, @@ -46,6 +48,7 @@ import { MAX_EXPIRES_IN_SECONDS, purgeExpiredOidcPayloads, revokeOidcPayloadsByGrant, + SESSION_EXCHANGE_SOURCE_WINDOW_MS, startOidcPayloadPurge, upsertOidcPayload, } from '../../../src/services/oidcPayloadStore'; @@ -152,6 +155,75 @@ describe('claimOAuthStateUse', () => { }); }); +describe('claimSessionExchangeSource', () => { + const code = (model: string, id: string, clientId = 'cli') => + ({ model, id, payload: { clientId } }) as never; + + beforeEach(() => { + vi.mocked(OidcPayload.findAll).mockReset(); + vi.mocked(OidcPayload.sequelize!.query).mockReset(); + }); + + it('claims a code this session and client consumed just now', async () => { + vi.mocked(OidcPayload.findAll).mockResolvedValueOnce([code('AuthorizationCode', 'c1')]); + vi.mocked(OidcPayload.sequelize!.query).mockResolvedValueOnce([{ id: 'x' }] as never); + const before = Date.now(); + + expect(await claimSessionExchangeSource(SESSION, 'cli')).toBe('AuthorizationCode'); + + const { where } = vi.mocked(OidcPayload.findAll).mock.calls[0][0] as { + where: Record & { consumedAt: { [Op.gte]: Date } }; + }; + expect(where).toMatchObject({ + model: { [Op.in]: ['AuthorizationCode', 'DeviceCode'] }, + sessionId: SESSION, + payload: { clientId: 'cli' }, + }); + expect(where.consumedAt[Op.gte].getTime()).toBeGreaterThanOrEqual( + before - SESSION_EXCHANGE_SOURCE_WINDOW_MS, + ); + expect(vi.mocked(OidcPayload.sequelize!.query).mock.calls[0][1]).toMatchObject({ + replacements: { id: 'AuthorizationCode:c1', model: 'SessionExchangeSource' }, + }); + }); + + it('moves on to the next code when one is already claimed', async () => { + vi.mocked(OidcPayload.findAll).mockResolvedValueOnce([ + code('AuthorizationCode', 'c1'), + code('DeviceCode', 'd1'), + ]); + vi.mocked(OidcPayload.sequelize!.query) + .mockResolvedValueOnce([] as never) + .mockResolvedValueOnce([{ id: 'x' }] as never); + + expect(await claimSessionExchangeSource(SESSION, 'cli')).toBe('DeviceCode'); + }); + + it('finds nothing to claim for a refresh, which consumes no code', async () => { + vi.mocked(OidcPayload.findAll).mockResolvedValueOnce([]); + expect(await claimSessionExchangeSource(SESSION, 'cli')).toBeNull(); + }); + + it('refuses when every code is already claimed', async () => { + vi.mocked(OidcPayload.findAll).mockResolvedValueOnce([code('AuthorizationCode', 'c1')]); + vi.mocked(OidcPayload.sequelize!.query).mockResolvedValueOnce([] as never); + expect(await claimSessionExchangeSource(SESSION, 'cli')).toBeNull(); + }); + + it('skips a code for another client', async () => { + vi.mocked(OidcPayload.findAll).mockResolvedValueOnce([ + code('AuthorizationCode', 'c1', 'other'), + ]); + expect(await claimSessionExchangeSource(SESSION, 'cli')).toBeNull(); + expect(OidcPayload.sequelize!.query).not.toHaveBeenCalled(); + }); + + it('refuses a malformed session id without a query', async () => { + expect(await claimSessionExchangeSource('not-a-uuid', 'cli')).toBeNull(); + expect(OidcPayload.findAll).not.toHaveBeenCalled(); + }); +}); + describe('finding records', () => { beforeEach(() => { vi.mocked(resolveCurrentSession).mockResolvedValue({ id: SESSION } as never); diff --git a/tests/unit/services/oidcSigning.spec.ts b/tests/unit/services/oidcSigning.spec.ts index 6015ea64..7edbe77a 100644 --- a/tests/unit/services/oidcSigning.spec.ts +++ b/tests/unit/services/oidcSigning.spec.ts @@ -2,7 +2,8 @@ import { generateKeyPairSync, verify } from 'crypto'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('../../../src/services/oidcClientRegistry', () => ({ +vi.mock('../../../src/services/oidcClientRegistry', async (importOriginal) => ({ + ...(await importOriginal()), findActiveOidcClient: vi.fn(), getOidcClientResourceScopes: vi.fn(), })); @@ -13,6 +14,7 @@ vi.mock('../../../src/services/oidcAccountClaims', async (importOriginal) => ({ })); vi.mock('../../../src/services/oidcPayloadStore', () => ({ + claimSessionExchangeSource: vi.fn(), hasOidcGrantForSession: vi.fn(), recordSessionExchangeToken: vi.fn(), })); @@ -36,6 +38,7 @@ import { getOidcClientResourceScopes, } from '../../../src/services/oidcClientRegistry'; import { + claimSessionExchangeSource, hasOidcGrantForSession, recordSessionExchangeToken, } from '../../../src/services/oidcPayloadStore'; @@ -757,9 +760,11 @@ describe('a session:exchange token', () => { vi.mocked(resolveCurrentSession).mockResolvedValue(passkeySession as never); vi.mocked(hasOidcGrantForSession).mockResolvedValue(true); vi.mocked(recordSessionExchangeToken).mockResolvedValue(true); + vi.mocked(claimSessionExchangeSource).mockReset().mockResolvedValue('AuthorizationCode'); }); it('is signed and recorded', async () => { + vi.mocked(claimSessionExchangeSource).mockResolvedValue('DeviceCode'); const outcome = await signForOidcEdge(exchangeRequest({}, DEVICE)); expect(outcome).toMatchObject({ ok: true }); @@ -803,6 +808,69 @@ describe('a session:exchange token', () => { }); }); + it('claims the code the sign-in consumed', async () => { + expect(await signForOidcEdge(exchangeRequest())).toMatchObject({ ok: true }); + expect(claimSessionExchangeSource).toHaveBeenCalledWith(SESSION, 'cli'); + }); + + it('is refused on a refresh the edge reports as a sign-in', async () => { + vi.mocked(claimSessionExchangeSource).mockResolvedValue(null); + + expect(await signForOidcEdge(exchangeRequest())).toMatchObject({ + ok: false, + code: 'grant_not_allowed', + }); + expect(recordSessionExchangeToken).not.toHaveBeenCalled(); + }); + + it.each([ + ['a device code reported as a code grant', 'DeviceCode', 'authorization_code'], + ['an authorization code reported as a device grant', 'AuthorizationCode', DEVICE], + ] as const)('is refused for %s', async (_name, source, grantType) => { + vi.mocked(claimSessionExchangeSource).mockResolvedValue(source); + + expect(await signForOidcEdge(exchangeRequest({}, grantType))).toMatchObject({ + ok: false, + code: 'grant_not_allowed', + }); + }); + + it('refuses any refresh grant token for a session exchange client', async () => { + vi.mocked(findActiveOidcClient).mockResolvedValue({ + id: 'cli', + grantTypes: ['authorization_code', 'refresh_token'], + firstParty: true, + clientType: 'public', + tokenEndpointAuthMethod: 'none', + redirectUris: ['http://127.0.0.1/callback'], + sessionExchangeEnabled: true, + } as never); + vi.mocked(getOidcClientResourceScopes).mockResolvedValue(new Map([[API, new Set(['read'])]])); + const issuedAt = now(); + const request = { + ...exchangeRequest(), + grantType: 'refresh_token', + signingInput: input( + { alg: 'RS256', kid: 'k1', typ: 'at+jwt' }, + { + iss: ISSUER, + sub: 'user-1', + aud: API, + iat: issuedAt, + exp: issuedAt + 60, + jti: 'jti-2', + client_id: 'cli', + scope: 'read', + }, + ), + }; + + expect(await signForOidcEdge(request as never)).toMatchObject({ + ok: false, + code: 'grant_not_allowed', + }); + }); + it('is refused on a client credentials token', async () => { const issuedAt = now(); const outcome = await signForOidcEdge({ From aad24b03e82e542984f0afdff5fdcdb81446eb91 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Wed, 18 Nov 2026 20:14:12 -0500 Subject: [PATCH 2/3] feat(oidc): accept the refresh grant on /oidc/sign under contract 4 A refresh names the sign-in grant it continues in originGrantType, and a refresh of a device approval keeps the device-grant rules. Needs @seamless-auth/types 0.41.0. package-lock.json is updated when it publishes. --- .changeset/oidc-contract-v4.md | 5 ++ openapi.json | 8 ++++ package.json | 2 +- src/generated/api.ts | 7 ++- src/services/oidcSigning.ts | 10 +++- tests/integration/oidc/oidcEdge.spec.ts | 2 +- tests/unit/services/oidcSigning.spec.ts | 62 ++++++++++++++++++++++--- 7 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 .changeset/oidc-contract-v4.md diff --git a/.changeset/oidc-contract-v4.md b/.changeset/oidc-contract-v4.md new file mode 100644 index 00000000..71b7a087 --- /dev/null +++ b/.changeset/oidc-contract-v4.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': minor +--- + +The OIDC edge contract is now version 4 (`@seamless-auth/types` 0.41). `/oidc/sign` accepts `grantType: refresh_token` with the sign-in grant it continues in `originGrantType`, and applies the device-grant rules (ADR 0001, D10) to a refresh of a device approval. The client must still hold both grants. An OpenID Provider service on contract 3 refuses to start against this API, so upgrade `@seamless-auth/oidc-provider` together with the API. diff --git a/openapi.json b/openapi.json index 0f6aeb19..9e88a1e7 100644 --- a/openapi.json +++ b/openapi.json @@ -19137,6 +19137,14 @@ "clientId": { "type": "string", "minLength": 1 }, "sessionId": { "type": "string", "minLength": 1 }, "grantType": { + "type": "string", + "enum": [ + "authorization_code", + "urn:ietf:params:oauth:grant-type:device_code", + "refresh_token" + ] + }, + "originGrantType": { "type": "string", "enum": ["authorization_code", "urn:ietf:params:oauth:grant-type:device_code"] }, diff --git a/package.json b/package.json index d6f6bd14..58dbd163 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.40.0", + "@seamless-auth/types": "^0.41.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", diff --git a/src/generated/api.ts b/src/generated/api.ts index da93732b..546a25b1 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -18041,7 +18041,12 @@ export interface paths { clientId: string; sessionId?: string; /** @enum {string} */ - grantType?: 'authorization_code' | 'urn:ietf:params:oauth:grant-type:device_code'; + grantType?: + | 'authorization_code' + | 'urn:ietf:params:oauth:grant-type:device_code' + | 'refresh_token'; + /** @enum {string} */ + originGrantType?: 'authorization_code' | 'urn:ietf:params:oauth:grant-type:device_code'; signingInput: string; }; }; diff --git a/src/services/oidcSigning.ts b/src/services/oidcSigning.ts index b8c9213b..ed393be0 100644 --- a/src/services/oidcSigning.ts +++ b/src/services/oidcSigning.ts @@ -318,10 +318,16 @@ async function checkUserToken( client: OidcClient, issuer: string, ): Promise { - const device = request.grantType === DEVICE_CODE_GRANT; + // A refresh names the sign-in grant it continues, and the client must still hold both. + const origin = + request.grantType === 'refresh_token' ? request.originGrantType : request.grantType; + const device = origin === DEVICE_CODE_GRANT; + const served = servedGrantTypes(client); if ( !request.grantType || - !servedGrantTypes(client).includes(request.grantType) || + !origin || + !served.includes(request.grantType) || + !served.includes(origin) || (device && !(client.firstParty && client.deviceFlowEnabled)) ) { return refuse('grant_not_allowed'); diff --git a/tests/integration/oidc/oidcEdge.spec.ts b/tests/integration/oidc/oidcEdge.spec.ts index b48b8d54..15b4a7c9 100644 --- a/tests/integration/oidc/oidcEdge.spec.ts +++ b/tests/integration/oidc/oidcEdge.spec.ts @@ -180,7 +180,7 @@ describe('GET /oidc/config', () => { const res = await edge('get', '/oidc/config'); expect(res.body).toEqual({ - contractVersion: 3, + contractVersion: 4, issuer: ISSUER, appName: 'SeamlessAuth', allowClientSecrets: false, diff --git a/tests/unit/services/oidcSigning.spec.ts b/tests/unit/services/oidcSigning.spec.ts index 7edbe77a..63d42675 100644 --- a/tests/unit/services/oidcSigning.spec.ts +++ b/tests/unit/services/oidcSigning.spec.ts @@ -552,6 +552,35 @@ describe('signForOidcEdge', () => { }); }); + describe('refresh tokens', () => { + const refresh = { + grantType: 'refresh_token' as const, + originGrantType: 'authorization_code' as const, + }; + + it('signs a refresh of a code grant with the assurance the session earned', async () => { + expect((await signForOidcEdge({ ...idTokenRequest(), ...refresh })).ok).toBe(true); + }); + + it('refuses a refresh that names no sign-in grant', async () => { + expect( + await signForOidcEdge({ ...idTokenRequest(), grantType: 'refresh_token' }), + ).toMatchObject({ ok: false, code: 'grant_not_allowed' }); + }); + + it('refuses a refresh for a client without the refresh grant', async () => { + vi.mocked(findActiveOidcClient).mockResolvedValue({ + id: 'app', + grantTypes: ['authorization_code'], + firstParty: true, + } as never); + expect(await signForOidcEdge({ ...idTokenRequest(), ...refresh })).toMatchObject({ + ok: false, + code: 'grant_not_allowed', + }); + }); + }); + describe('device-flow tokens (ADR 0001, D10)', () => { const DEVICE = 'urn:ietf:params:oauth:grant-type:device_code' as const; @@ -608,6 +637,23 @@ describe('signForOidcEdge', () => { expect(await signForOidcEdge(request)).toMatchObject({ code: 'grant_not_allowed' }); }); + it('treats a refresh of a device approval as a device token', async () => { + deviceClient(); + const refresh = { grantType: 'refresh_token' as const, originGrantType: DEVICE }; + const { acr: _acr, amr: _amr, auth_time: _authTime, ...claims } = idTokenClaims(); + + expect((await signForOidcEdge({ ...idTokenRequest(claims), ...refresh })).ok).toBe(true); + expect(await signForOidcEdge({ ...idTokenRequest(), ...refresh })).toMatchObject({ + ok: false, + code: 'auth_context_mismatch', + }); + + deviceClient({ deviceFlowEnabled: false }); + expect(await signForOidcEdge({ ...idTokenRequest(claims), ...refresh })).toMatchObject({ + code: 'grant_not_allowed', + }); + }); + it('refuses a user token that names no grant, or one the client lacks', async () => { deviceClient(); expect(await signForOidcEdge(idTokenRequest())).toMatchObject({ @@ -801,12 +847,16 @@ describe('a session:exchange token', () => { }, ); - it('is refused on a refresh grant', async () => { - expect(await signForOidcEdge(exchangeRequest({}, 'refresh_token'))).toMatchObject({ - ok: false, - code: 'grant_not_allowed', - }); - }); + it.each(['authorization_code', DEVICE])( + 'is refused on a refresh of a %s grant', + async (origin) => { + const request = { ...exchangeRequest({}, 'refresh_token'), originGrantType: origin }; + expect(await signForOidcEdge(request as never)).toMatchObject({ + ok: false, + code: 'grant_not_allowed', + }); + }, + ); it('claims the code the sign-in consumed', async () => { expect(await signForOidcEdge(exchangeRequest())).toMatchObject({ ok: true }); From a0c53f612b8ca4336d8cdfd8b590cd4837e10356 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Thu, 26 Nov 2026 22:44:37 -0500 Subject: [PATCH 3/3] chore(deps): lock @seamless-auth/types 0.41.0 --- package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5240e709..03a21ec4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,19 @@ { "name": "seamless-auth-api", - "version": "0.22.0", + "version": "0.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seamless-auth-api", - "version": "0.22.0", + "version": "0.23.0", "license": "Apache-2.0", "dependencies": { "@asteasolutions/zod-to-openapi": "^9.1.0", "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.40.0", + "@seamless-auth/types": "^0.41.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", @@ -2927,9 +2927,9 @@ } }, "node_modules/@seamless-auth/types": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.40.0.tgz", - "integrity": "sha512-NpFVCWE0VSNrBK9M4yBxsloyQgGHXP6B8/QmDPxsFz48/qV6jcDqdUpuV4PAJslG9B9X+4BcnTSQzI+iPSRNsA==", + "version": "0.41.0", + "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.41.0.tgz", + "integrity": "sha512-1/hETcuRN0FsdTNrHEwAWLENKTIIQuvIQ+cAyKLppWor4ovIkP9mPuF0f52CMFnjyWCvBavmgmJZWeaQyQsZgA==", "license": "Apache-2.0", "dependencies": { "zod": "^4.5.0"