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
@@ -29,6 +29,12 @@ import type { Request, Response } from 'express';
const MIN = 60_000;
/** The id of the cookie session a consent comes from, null for a token from before sessions were tracked. */
function consentingSession(req: Request): string | null {
const jti = verifiedSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session)?.jti;
return typeof jti === 'string' ? jti : null;
}
/**
* Authenticated OAuth management endpoints (the SPA's consent + client/session
* UI) — byte-identical to the legacy oauthApiRouter (server/src/routes/oauth.ts):
@@ -136,9 +142,8 @@ 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,
// The cookie session the guard has just verified: the code is good only while it stands.
sessionId: consentingSession(req),
});
if (!code) {
throw new HttpException(
@@ -96,7 +96,7 @@ export class OauthPublicController {
if (!this.oauth.verifyPKCE(code_verifier, pending.codeChallenge))
return invalidGrant('pkce_failed', pending.userId);
const tokens = await this.oauth.issueTokensForCode(pending);
if (!tokens) return invalidGrant('password_changed', pending.userId);
if (!tokens) return invalidGrant('session_ended', pending.userId);
await this.audit.writeAudit({
userId: pending.userId,
action: 'oauth.token.issue',
+5 -3
View File
@@ -8,6 +8,7 @@ import { createMcpAddonGate } from '../addons/mcp-addon-gate';
import { AuditModule } from '../audit/audit.module';
import { RateLimitModule } from '../common/rate-limit.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { SessionsModule } from '../sessions/sessions.module';
import { OauthApiController } from './oauth-api.controller';
import { CimdClientResolver } from './oauth-cimd';
import { OauthPublicController } from './oauth-public.controller';
@@ -59,14 +60,15 @@ import type { MiddlewareConsumer, NestModule } from '@nestjs/common';
* shape `McpTokensRepository`/`InviteTokensRepository` already use across
* `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);
* `OauthService` injects `UsersRepository` only to check that the password
* an authorization code was granted under still holds.
* `Users` call (Task 1's ruling: "do not add users methods" for this join).
* Whether the session that consented to an authorization code still stands
* is the sessions domain's to answer (`SessionsService.findActive`).
*/
@Module({
imports: [
RateLimitModule,
AuditModule,
SessionsModule,
AddonsModule,
SchedulingModule,
MikroOrmModule.forFeature([OauthClients, OauthTokens, OauthConsents, Users]),
+6 -2
View File
@@ -28,8 +28,12 @@ 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;
/**
* The browser session that consented (`user_sessions.id`), or null for a
* token from before sessions were tracked; the code mints tokens only while
* that session is active.
*/
sessionId: string | null;
expiresAt: number;
}
+12 -9
View File
@@ -3,7 +3,6 @@ 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,
@@ -13,7 +12,6 @@ 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
@@ -30,6 +28,7 @@ import { AuditService } from '../audit/audit.service';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { SessionsService } from '../sessions/sessions.service';
import { CimdClientResolver, isCimdClientId, type CimdClient } from './oauth-cimd';
import {
ACCESS_TOKEN_TTL_S,
@@ -135,7 +134,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 sessions: SessionsService,
private readonly addons: AddonsService,
private readonly audit: AuditService,
private readonly uow: UnitOfWork,
@@ -320,7 +319,7 @@ export class OauthService {
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
passwordVersion: number;
sessionId: string | null;
}): Promise<string | null> {
const rawCode = randomBytes(32).toString('hex');
const stored = await this.pendingCodes.put(rawCode, { ...params, expiresAt: Date.now() + AUTH_CODE_TTL_MS });
@@ -393,14 +392,18 @@ export class OauthService {
// -------------------------------------------------------------------------
/**
* 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.
* The tokens a redeemed authorization code grants, or null when the session
* that consented has ended since: a password reset or change ends every
* session along with the user's tokens, and a sign-out ends this one, so a
* code from before must not mint new tokens. 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.
*/
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;
if (pending.sessionId !== null && !(await this.sessions.findActive(pending.sessionId, pending.userId, dbNow()))) {
return null;
}
return this.issueTokens(pending.clientId, pending.userId, pending.scopes, null, pending.resource ?? null);
});
}