fix(oauth): bind an authorization code to the session that consented, not to the password version

Reading the password version from the oauth domain meant injecting the
users repository, which the auth domain owns. The sessions domain answers
the same question and more: a password reset or change ends every session
of the user, and a sign-out ends the one that consented. The code now
carries that session's id and both token endpoints issue tokens for it
only while the session is active, checked in the transaction that writes
them. A token from before sessions were tracked has no session to check
and passes, as it does everywhere until it expires. A refused code is
audited as session_ended.
This commit is contained in:
Maurice
2026-11-26 22:46:15 +01:00
parent 05843c8e5b
commit d383d3527b
10 changed files with 78 additions and 55 deletions
@@ -264,7 +264,7 @@ describe('GET /oauth/authorize — SDK authorizationHandler over trekOAuthProvid
// SDK-side exchange see it.
const code = await withRequestContext(orm, () =>
containerSideOauth.createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId,
userId: user.id,
redirectUri: 'https://client.example.com/cb',
+15 -15
View File
@@ -332,7 +332,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
// Create code for client1
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r1.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app1.example.com/cb',
@@ -361,7 +361,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -389,7 +389,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -417,7 +417,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -445,7 +445,7 @@ describe('POST /oauth/token — authorization_code grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -505,7 +505,7 @@ describe('POST /oauth/token — refresh_token grant', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -592,7 +592,7 @@ describe('POST /oauth/revoke', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1066,7 +1066,7 @@ describe('Sessions — /api/oauth/sessions', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1115,7 +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,
sessionId: null,
clientId: client.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1210,7 +1210,7 @@ describe('H1 — PKCE format validation', () => {
const { challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1265,7 +1265,7 @@ describe('H5 — All invalid_grant cases return identical response body', () =>
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1287,7 +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,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1418,7 +1418,7 @@ describe('C3 — Refresh token replay detection', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1467,7 +1467,7 @@ describe('C3 — Refresh token replay detection', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -1509,7 +1509,7 @@ describe('C3 — Refresh token replay detection', () => {
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: r.client!.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
@@ -132,7 +132,7 @@ describe('OauthPublicController /token', () => {
);
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.
// The consenting session ended since: the code grants nothing, and the refusal is audited.
const stale = makeRes();
const staleSvc = osvc({
consumeAuthCode: vi.fn().mockReturnValue({
@@ -157,7 +157,7 @@ describe('OauthPublicController /token', () => {
expect(staleAudit.writeAudit).toHaveBeenCalledWith(
expect.objectContaining({
action: 'oauth.token.grant_failed',
details: { client_id: 'c', reason: 'password_changed' },
details: { client_id: 'c', reason: 'session_ended' },
}),
);
});
@@ -627,14 +627,14 @@ 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 () => {
it('authorize: the code carries 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' });
const cookie = jwt.sign({ id: user.id, jti: 'sess-4' }, JWT_SECRET, { algorithm: 'HS256' });
await new OauthApiController(svc, rl()).authorize(
user,
{
@@ -647,7 +647,7 @@ describe('OauthApiController', () => {
},
{ ...req, cookies: { trek_session: cookie } } as unknown as Request,
);
expect(createAuthCode).toHaveBeenCalledWith(expect.objectContaining({ passwordVersion: 4 }));
expect(createAuthCode).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'sess-4' }));
});
it('clients/sessions: 403 when MCP off, else CRUD', async () => {
+23 -14
View File
@@ -37,6 +37,7 @@ import {
sweepPendingCodes,
} from '../../../src/nest/oauth/oauth.pending-codes';
import { OauthService } from '../../../src/nest/oauth/oauth.service';
import type { SessionsService } from '../../../src/nest/sessions/sessions.service';
import { createUser } from '../../helpers/factories';
import { countRows, findRow, findRows, insertRow, updateRows } from '../../helpers/factories/rows';
import { resetTestDb } from '../../helpers/test-db';
@@ -121,6 +122,12 @@ const getConsent = (...args: Parameters<OauthService['getConsent']>) => svc.getC
const isConsentSufficient = (...args: Parameters<OauthService['isConsentSufficient']>) =>
svc.isConsentSufficient(...args);
/** Sessions a reset or a sign-out ended; every other id reads as an active session. */
const endedSessions = new Set<string>();
const sessionsStub = {
findActive: vi.fn(async (id: string) => (endedSessions.has(id) ? null : { id, last_seen_at: '2026-01-01 00:00:00' })),
} as unknown as SessionsService & { findActive: ReturnType<typeof vi.fn> };
beforeAll(async () => {
t = await createTestOrm(testDb);
auditLogRepo = t.repo(AuditLog);
@@ -132,7 +139,7 @@ beforeAll(async () => {
clientsRepo,
tokensRepo,
consentsRepo,
usersRepo,
sessionsStub,
addonsStub,
new AuditService(auditLogRepo, usersRepo),
new UnitOfWork(t.em, new SqliteEngine()),
@@ -411,7 +418,7 @@ describe('createAuthCode + consumeAuthCode', () => {
const clientId = created.client!.client_id as string;
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
@@ -437,7 +444,7 @@ describe('createAuthCode + consumeAuthCode', () => {
const clientId = created.client!.client_id as string;
const code = await createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
@@ -451,13 +458,13 @@ describe('createAuthCode + consumeAuthCode', () => {
expect(await consumeAuthCode(code)).toBeNull();
});
it('a code mints tokens only while the password it was granted under holds', async () => {
it('a code mints tokens only while the session that consented stands', async () => {
const { user } = createUser(testDb);
const created = await makeClient(user.id);
const clientId = String(created.client?.client_id);
const grant = async () => {
const grant = async (sessionId: string | null) => {
const code = await createAuthCode({
passwordVersion: 0,
sessionId,
clientId,
userId: user.id,
redirectUri: 'https://example.com/callback',
@@ -471,13 +478,15 @@ describe('createAuthCode + consumeAuthCode', () => {
return pending;
};
const kept = await svc.issueTokensForCode(await grant());
expect(kept?.access_token).toEqual(expect.any(String));
expect((await svc.issueTokensForCode(await grant('sess-live')))?.access_token).toEqual(expect.any(String));
// A token from before sessions were tracked has no session to check.
expect((await svc.issueTokensForCode(await grant(null)))?.access_token).toEqual(expect.any(String));
const beforeReset = await grant();
await updateRows(t, Users, { id: user.id }, { password_version: 1 });
const beforeReset = await grant('sess-reset');
endedSessions.add('sess-reset');
expect(await svc.issueTokensForCode(beforeReset)).toBeNull();
expect(await countRows(t, OauthTokens, { user: user.id })).toBe(1);
expect(await countRows(t, OauthTokens, { user: user.id })).toBe(2);
expect(sessionsStub.findActive).toHaveBeenCalledWith('sess-reset', user.id, expect.any(String));
});
});
@@ -1305,7 +1314,7 @@ describe('addon gate and MCP endpoint', () => {
describe('pending-code store', () => {
const codeParams = {
passwordVersion: 0,
sessionId: null,
clientId: 'c',
userId: 42,
redirectUri: 'https://example.com/callback',
@@ -1466,7 +1475,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,
sessionId: null,
clientId: 'c',
userId: 42,
redirectUri: 'https://example.com/callback',
@@ -1480,7 +1489,7 @@ describe('module-scoped OAuth state', () => {
clientsRepo,
tokensRepo,
consentsRepo,
usersRepo,
sessionsStub,
addonsStub,
new AuditService(auditLogRepo, usersRepo),
new UnitOfWork(t.em, new SqliteEngine()),
@@ -66,7 +66,7 @@ function code(over: Partial<PendingCode> = {}): PendingCode {
resource: null,
codeChallenge: 'x',
codeChallengeMethod: 'S256',
passwordVersion: 0,
sessionId: null,
expiresAt: Date.now() + 60_000,
...over,
};
@@ -135,7 +135,7 @@ describe('OAuth pending codes', () => {
store,
);
const issued = await service.createAuthCode({
passwordVersion: 0,
sessionId: null,
clientId: 'c',
userId: 1,
redirectUri: 'https://app.example/cb',