Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/oidc-contract-v4.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/session-exchange-sign-in-only.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion docs/adr/0003-native-admin-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ B has no usable revocation story: every event above that should end the CLI's ac
- **Requested** with `resource=<oidc_issuer>/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

Expand Down
8 changes: 8 additions & 0 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
},
Expand Down
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
7 changes: 6 additions & 1 deletion src/generated/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
};
Expand Down
21 changes: 16 additions & 5 deletions src/services/oidcClientRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<OidcClientMetadata | null> {
const client = await findActiveOidcClient(id);

Expand All @@ -85,11 +100,7 @@ export async function getOidcClientMetadata(id: string): Promise<OidcClientMetad
client_name: client.name,
application_type: client.redirectUris.some(isNativeRedirectUri) ? 'native' : 'web',
token_endpoint_auth_method: client.tokenEndpointAuthMethod,
// The device grant only for a first-party client with the flag on (ADR 0001, D10),
// whatever the stored grant list says.
grant_types: client.grantTypes.filter(
(grant) => 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,
Expand Down
53 changes: 53 additions & 0 deletions src/services/oidcPayloadStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SessionExchangeSourceModel | null> {
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<OidcPayloadAttributes>,
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<string, unknown>) {
return OidcPayload.findOne({
where: {
Expand Down
41 changes: 34 additions & 7 deletions src/services/oidcSigning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<string, unknown>;
Expand All @@ -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<SessionExchangeSourceModel, string> = {
AuthorizationCode: 'authorization_code',
DeviceCode: DEVICE_CODE_GRANT,
};

const PROTOCOL_CLAIMS = [
'iss',
Expand Down Expand Up @@ -301,13 +315,19 @@ 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<OidcSignOutcome | null> {
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 ||
!client.grantTypes.includes(request.grantType) ||
!origin ||
!served.includes(request.grantType) ||
!served.includes(origin) ||
(device && !(client.firstParty && client.deviceFlowEnabled))
) {
return refuse('grant_not_allowed');
Expand Down Expand Up @@ -415,12 +435,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<OidcSignOutcome | null> {
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)) {
Expand All @@ -438,5 +458,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;
}
2 changes: 1 addition & 1 deletion tests/integration/oidc/oidcEdge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading