mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
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:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user