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,