fix(oauth): an authorization code mints tokens only while the password it was granted under holds

The consent page mints a two-minute authorization code from the cookie
session. A password reset or change revokes the user's OAuth tokens but
left such a pending code alone, so a code granted before the reset still
redeemed afterwards into a fresh token pair at either token endpoint.

The code now carries the password version of the session that consented,
and both token endpoints issue tokens for it only while that version is
still the account's, checked in the transaction that writes the tokens.
A refused code answers invalid_grant as any other and is audited as
password_changed.
This commit is contained in:
Maurice
2026-11-26 22:21:46 +01:00
parent c88d3abc5e
commit f9ab280b7e
13 changed files with 161 additions and 24 deletions
@@ -3,6 +3,7 @@ import { getClientIp } from '../audit/client-ip';
import { CookieAuthGuard } from '../auth-core/cookie-auth.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { verifiedSessionClaims } from '../auth-core/jwt-verify';
import { OptionalJwtGuard } from '../auth-core/optional-jwt.guard';
import { DEMO_ACCOUNT_REFUSAL, refuseForDemoAccount } from '../common/demo-write';
import { RateLimitService } from '../common/rate-limit.service';
@@ -135,6 +136,9 @@ export class OauthApiController {
resource: validation.resource ?? null,
codeChallenge: body.code_challenge,
codeChallengeMethod: 'S256',
// The cookie session the guard has just verified: the code is good only under its password.
passwordVersion:
verifiedSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session)?.pv ?? 0,
});
if (!code) {
throw new HttpException(
@@ -95,13 +95,8 @@ export class OauthPublicController {
}
if (!this.oauth.verifyPKCE(code_verifier, pending.codeChallenge))
return invalidGrant('pkce_failed', pending.userId);
const tokens = await this.oauth.issueTokens(
client_id,
pending.userId,
pending.scopes,
null,
pending.resource ?? null,
);
const tokens = await this.oauth.issueTokensForCode(pending);
if (!tokens) return invalidGrant('password_changed', pending.userId);
await this.audit.writeAudit({
userId: pending.userId,
action: 'oauth.token.issue',
+2 -7
View File
@@ -184,13 +184,8 @@ export class TrekOAuthProvider implements OAuthServerProvider {
if (!codeVerifier || !this.oauth.verifyPKCE(codeVerifier, pending.codeChallenge))
throw new Error('Authorization grant is invalid.');
const tokens = await this.oauth.issueTokens(
client.client_id,
pending.userId,
pending.scopes,
null,
pending.resource ?? null,
);
const tokens = await this.oauth.issueTokensForCode(pending);
if (!tokens) throw new Error('Authorization grant is invalid.');
await this.audit.writeAudit({
userId: pending.userId,
action: 'oauth.token.issue',
+4 -3
View File
@@ -57,10 +57,11 @@ import type { MiddlewareConsumer, NestModule } from '@nestjs/common';
* module availability (inventory §6 — `OauthTokensRepository` needs to be
* importable from `AuthModule` too, Task 5's `revokeAllForUser`, the same
* shape `McpTokensRepository`/`InviteTokensRepository` already use across
* `nest/tokens`/`nest/auth`/`nest/oidc`) even though `OauthService` itself
* never injects `UsersRepository` directly — OA16/OA31 read `users` columns
* `nest/tokens`/`nest/auth`/`nest/oidc`). OA16/OA31 read `users` columns
* THROUGH `OauthTokensRepository`'s own join methods, not a separate
* `Users` call (Task 1's ruling: "do not add users methods" for this join).
* `Users` call (Task 1's ruling: "do not add users methods" for this join);
* `OauthService` injects `UsersRepository` only to check that the password
* an authorization code was granted under still holds.
*/
@Module({
imports: [
@@ -28,6 +28,8 @@ export interface PendingCode {
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
/** The password version the consent was given under; the code mints tokens only while it holds. */
passwordVersion: number;
expiresAt: number;
}
+17
View File
@@ -3,6 +3,7 @@ import { getMcpSafeUrl } from '../../app-config';
import { OauthClients } from '../../db/entities/OauthClients.entity';
import { OauthConsents } from '../../db/entities/OauthConsents.entity';
import { OauthTokens } from '../../db/entities/OauthTokens.entity';
import { Users } from '../../db/entities/Users.entity';
import {
OAUTH_CLIENT_ALLOWED_SCOPES,
OAUTH_CLIENT_REDIRECT_URIS,
@@ -12,6 +13,7 @@ import {
import type { OauthClientRow, OauthClientsRepository } from '../../db/repositories/OauthClients.repository';
import type { OauthConsentsRepository } from '../../db/repositories/OauthConsents.repository';
import type { OauthTokenRefreshRow, OauthTokensRepository } from '../../db/repositories/OauthTokens.repository';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { dbNow, parseDbTimestamp } from '../../db/types';
// Import from scopes/sessionManager directly, NOT the ../../mcp barrel: the
// barrel pulls the whole tools fan-out (and via the domain bridges, the Nest
@@ -133,6 +135,7 @@ export class OauthService {
@InjectRepository(OauthClients) private readonly clients: OauthClientsRepository,
@InjectRepository(OauthTokens) private readonly tokens: OauthTokensRepository,
@InjectRepository(OauthConsents) private readonly consents: OauthConsentsRepository,
@InjectRepository(Users) private readonly users: UsersRepository,
private readonly addons: AddonsService,
private readonly audit: AuditService,
private readonly uow: UnitOfWork,
@@ -317,6 +320,7 @@ export class OauthService {
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
passwordVersion: number;
}): Promise<string | null> {
const rawCode = randomBytes(32).toString('hex');
const stored = await this.pendingCodes.put(rawCode, { ...params, expiresAt: Date.now() + AUTH_CODE_TTL_MS });
@@ -388,6 +392,19 @@ export class OauthService {
// Token issuance
// -------------------------------------------------------------------------
/**
* The tokens a redeemed authorization code grants, or null when the
* password changed since the consent: a reset or a change revokes the
* user's tokens, and a code from before it must not mint new ones. Checked
* in the transaction that writes the tokens.
*/
async issueTokensForCode(pending: PendingCode): Promise<Awaited<ReturnType<OauthService['issueTokens']>> | null> {
return this.uow.transactional(async () => {
if ((await this.users.getPasswordVersion(pending.userId)) !== pending.passwordVersion) return null;
return this.issueTokens(pending.clientId, pending.userId, pending.scopes, null, pending.resource ?? null);
});
}
async issueTokens(
clientId: string,
userId: number,
+1
View File
@@ -61,6 +61,7 @@ const { oauthSvc } = vi.hoisted(() => ({
consumeAuthCode: vi.fn(),
saveConsent: vi.fn(),
issueTokens: vi.fn(),
issueTokensForCode: vi.fn(),
issueClientCredentialsToken: vi.fn(),
refreshTokens: vi.fn(),
revokeToken: vi.fn(),
@@ -264,6 +264,7 @@ describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvid
// SDK-side exchange see it.
const code = await withRequestContext(orm, () =>
containerSideOauth.createAuthCode({
passwordVersion: 0,
clientId,
userId: user.id,
redirectUri: 'https://client.example.com/cb',
+15
View File
@@ -332,6 +332,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
// Create code for client1
const code = await createAuthCode({
passwordVersion: 0,
clientId: r1.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app1.example.com/cb',
@@ -360,6 +361,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -387,6 +389,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -414,6 +417,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -441,6 +445,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -500,6 +505,7 @@ describe('POST /oauth/token — refresh_token grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -586,6 +592,7 @@ describe('POST /oauth/revoke', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1059,6 +1066,7 @@ describe('Sessions — /api/oauth/sessions', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1107,6 +1115,7 @@ describe('Sessions — /api/oauth/sessions', () => {
if (!client) throw new Error('the OAuth client was not created');
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: client.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1201,6 +1210,7 @@ describe('H1 — PKCE format validation', () => {
const { challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1255,6 +1265,7 @@ describe('H5 — All invalid_grant cases return identical response body', () =>
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1276,6 +1287,7 @@ describe('H5 — All invalid_grant cases return identical response body', () =>
// Redirect URI mismatch (need fresh code since code is single-use)
const code2 = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1406,6 +1418,7 @@ describe('C3 — Refresh token replay detection', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1454,6 +1467,7 @@ describe('C3 — Refresh token replay detection', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1495,6 +1509,7 @@ describe('C3 — Refresh token replay detection', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -37,7 +37,7 @@ function makeOauth(overrides: Partial<Record<keyof OauthService, unknown>> = {})
getSdkClient: vi.fn(),
createOAuthClient: vi.fn(() => ({ client: baseClientRecord() })),
consumeAuthCode: vi.fn(),
issueTokens: vi.fn(() => tokens()),
issueTokensForCode: vi.fn(() => tokens()),
refreshTokens: vi.fn(() => ({ tokens: tokens() })),
getUserByAccessToken: vi.fn(),
revokeToken: vi.fn(),
@@ -459,7 +459,8 @@ describe('TrekOAuthProvider.exchangeAuthorizationCode', () => {
});
it('SDKP-045: a valid exchange issues tokens and audits the issue', async () => {
const oauth = makeOauth({ consumeAuthCode: vi.fn(async () => pending()) });
const code = pending();
const oauth = makeOauth({ consumeAuthCode: vi.fn(async () => code) });
const audit = makeAudit();
const { provider } = makeProvider(oauth, audit);
const result = await provider.exchangeAuthorizationCode(
@@ -470,7 +471,7 @@ describe('TrekOAuthProvider.exchangeAuthorizationCode', () => {
new URL('https://trek.example.test/mcp'),
);
expect(result).toEqual(tokens());
expect(oauth.issueTokens).toHaveBeenCalledWith('cid-1', 7, ['trips:read'], null, 'https://trek.example.test/mcp');
expect(oauth.issueTokensForCode).toHaveBeenCalledWith(code);
expect(audit.writeAudit).toHaveBeenCalledWith({
userId: 7,
action: 'oauth.token.issue',
@@ -480,17 +481,29 @@ describe('TrekOAuthProvider.exchangeAuthorizationCode', () => {
});
it('SDKP-046: a pending code without a resource issues a null-audience token', async () => {
const oauth = makeOauth({ consumeAuthCode: vi.fn(async () => pending({ resource: null })) });
const code = pending({ resource: null });
const oauth = makeOauth({ consumeAuthCode: vi.fn(async () => code) });
const { provider } = makeProvider(oauth);
await provider.exchangeAuthorizationCode(clientInfo(), 'code', 'verifier');
expect(oauth.issueTokens).toHaveBeenCalledWith('cid-1', 7, ['trips:read'], null, null);
expect(oauth.issueTokensForCode).toHaveBeenCalledWith(code);
});
it('SDKP-048: a code whose password changed since the consent mints no tokens', async () => {
const oauth = makeOauth({
consumeAuthCode: vi.fn(async () => pending()),
issueTokensForCode: vi.fn(async () => null),
});
const audit = makeAudit();
const { provider } = makeProvider(oauth, audit);
await expect(provider.exchangeAuthorizationCode(clientInfo(), 'code', 'verifier')).rejects.toThrow(invalid);
expect(audit.writeAudit).not.toHaveBeenCalled();
});
it('SDKP-047: a missing codeVerifier is refused, not waved through', async () => {
const oauth = makeOauth({ consumeAuthCode: vi.fn(async () => pending()) });
const { provider } = makeProvider(oauth);
await expect(provider.exchangeAuthorizationCode(clientInfo(), 'code')).rejects.toThrow(invalid);
expect(oauth.issueTokens).not.toHaveBeenCalled();
expect(oauth.issueTokensForCode).not.toHaveBeenCalled();
});
});
@@ -1,3 +1,4 @@
import { JWT_SECRET } from '../../../src/config';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import { getClientIp } from '../../../src/nest/audit/client-ip';
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
@@ -8,6 +9,7 @@ import type { User } from '../../../src/types';
import { HttpException } from '@nestjs/common';
import type { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
@@ -122,13 +124,44 @@ describe('OauthPublicController /token', () => {
}),
authenticateClient: vi.fn().mockReturnValue({ id: 'c' }),
verifyPKCE: vi.fn().mockReturnValue(true),
issueTokens: vi.fn().mockReturnValue({ access_token: 'at', token_type: 'Bearer' }),
issueTokensForCode: vi.fn().mockReturnValue({ access_token: 'at', token_type: 'Bearer' }),
});
await opc(svc, rl()).token(
reqWith({ grant_type: 'authorization_code', client_id: 'c', code: 'x', redirect_uri: 'u', code_verifier: 'v' }),
ok,
);
expect(ok.body).toEqual({ access_token: 'at', token_type: 'Bearer' });
// The password changed since the consent: the code grants nothing, and the refusal is audited.
const stale = makeRes();
const staleSvc = osvc({
consumeAuthCode: vi
.fn()
.mockReturnValue({
clientId: 'c',
redirectUri: 'u',
userId: 1,
scopes: ['s'],
codeChallenge: 'cc',
resource: null,
}),
authenticateClient: vi.fn().mockReturnValue({ id: 'c' }),
verifyPKCE: vi.fn().mockReturnValue(true),
issueTokensForCode: vi.fn().mockReturnValue(null),
});
const staleAudit = { writeAudit: vi.fn() };
await new OauthPublicController(staleSvc, rl(), staleAudit as unknown as AuditService).token(
reqWith({ grant_type: 'authorization_code', client_id: 'c', code: 'x', redirect_uri: 'u', code_verifier: 'v' }),
stale,
);
expect(stale.statusCode).toBe(400);
expect(stale.body).toEqual({ error: 'invalid_grant', error_description: 'Authorization grant is invalid.' });
expect(staleAudit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({
action: 'oauth.token.grant_failed',
details: { client_id: 'c', reason: 'password_changed' },
}),
);
});
it('authorization_code: maps client_id / redirect_uri / resource mismatches + pkce + client auth', async () => {
@@ -596,6 +629,29 @@ describe('OauthApiController', () => {
expect((ok as { redirect: string }).redirect).toContain('code=the_code');
});
it('authorize: the code carries the password version of the cookie session that consented', async () => {
const createAuthCode = vi.fn().mockReturnValue('the_code');
const svc = osvc({
validateAuthorizeRequest: vi.fn().mockReturnValue({ valid: true, scopes: ['s'], resource: null }),
saveConsent: vi.fn(),
createAuthCode,
});
const cookie = jwt.sign({ id: user.id, pv: 4 }, JWT_SECRET, { algorithm: 'HS256' });
await new OauthApiController(svc, rl()).authorize(
user,
{
client_id: 'c',
redirect_uri: 'https://cb',
scope: 's',
code_challenge: 'cc',
code_challenge_method: 'S256',
approved: true,
},
{ ...req, cookies: { trek_session: cookie } } as unknown as Request,
);
expect(createAuthCode).toHaveBeenCalledWith(expect.objectContaining({ passwordVersion: 4 }));
});
it('clients/sessions: 403 when MCP off, else CRUD', async () => {
expect(
await thrownAsync(() =>
@@ -132,6 +132,7 @@ beforeAll(async () => {
clientsRepo,
tokensRepo,
consentsRepo,
usersRepo,
addonsStub,
new AuditService(auditLogRepo, usersRepo),
new UnitOfWork(t.em, new SqliteEngine()),
@@ -410,6 +411,7 @@ describe('createAuthCode + consumeAuthCode', () => {
const clientId = created.client!.client_id as string;
const code = await createAuthCode({
passwordVersion: 0,
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
@@ -435,6 +437,7 @@ describe('createAuthCode + consumeAuthCode', () => {
const clientId = created.client!.client_id as string;
const code = await createAuthCode({
passwordVersion: 0,
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
@@ -447,6 +450,33 @@ describe('createAuthCode + consumeAuthCode', () => {
await consumeAuthCode(code);
expect(await consumeAuthCode(code)).toBeNull();
});
it('a code mints tokens only while the password it was granted under holds', async () => {
const { user } = createUser(testDb);
const created = await makeClient(user.id);
const clientId = created.client!.client_id as string;
const grant = async () =>
(await consumeAuthCode(
(await createAuthCode({
passwordVersion: 0,
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
scopes: ['trips:read'],
resource: null,
codeChallenge: 'abc123',
codeChallengeMethod: 'S256',
}))!,
))!;
const kept = await svc.issueTokensForCode(await grant());
expect(kept?.access_token).toEqual(expect.any(String));
const beforeReset = await grant();
await updateRows(t, Users, { id: user.id }, { password_version: 1 });
expect(await svc.issueTokensForCode(beforeReset)).toBeNull();
expect(await countRows(t, OauthTokens, { user: user.id })).toBe(1);
});
});
// ---------------------------------------------------------------------------
@@ -1273,6 +1303,7 @@ describe('addon gate and MCP endpoint', () => {
describe('pending-code store', () => {
const codeParams = {
passwordVersion: 0,
clientId: 'c',
userId: 42,
redirectUri: 'https://example.com/callback',
@@ -1433,6 +1464,7 @@ describe('module-scoped OAuth state', () => {
// scoped, so even a second hand-built instance must see it — two maps would
// kill the authorization-code flow silently.
const code = (await createAuthCode({
passwordVersion: 0,
clientId: 'c',
userId: 42,
redirectUri: 'https://example.com/callback',
@@ -1446,6 +1478,7 @@ describe('module-scoped OAuth state', () => {
clientsRepo,
tokensRepo,
consentsRepo,
usersRepo,
addonsStub,
new AuditService(auditLogRepo, usersRepo),
new UnitOfWork(t.em, new SqliteEngine()),
@@ -130,9 +130,11 @@ describe('OAuth pending codes', () => {
{} as never,
{} as never,
{} as never,
{} as never,
store,
);
const issued = await service.createAuthCode({
passwordVersion: 0,
clientId: 'c',
userId: 1,
redirectUri: 'https://app.example/cb',
@@ -156,6 +158,7 @@ describe('OAuth pending codes', () => {
{} as never,
{} as never,
{} as never,
{} as never,
);
expect((service as unknown as { pendingCodes: unknown }).pendingCodes).toBe(processPendingCodes);
});
@@ -176,6 +179,7 @@ describe('OAuth pending codes', () => {
{} as never,
{} as never,
{} as never,
{} as never,
);
expect((service as unknown as { pendingCodes: unknown }).pendingCodes).toBe(fake);
} finally {