fix(auth): renew a session cookie only after it verifies on its own

SessionRenewalInterceptor took req.user as proof that the trek_session cookie
had been verified. On a route with its own guard chain that does not hold:
ApiTokenGuard authenticates a public API key and sets req.user, and the cookie
sent beside it is never checked. Past half its lifetime such a cookie was
decoded without its signature and renewed, so a holder of a read-only key
could come away with a signed session of the key's owner.

The interceptor now runs the cookie through the guards' own check (signature,
expiry, password version, active session) before it renews, requires it to
name the request's user, and renews nothing on a request a public API key
authenticated.
This commit is contained in:
Maurice
2026-11-22 18:15:51 +01:00
parent 49b9ffc77d
commit c7de823c78
4 changed files with 118 additions and 19 deletions
@@ -1,6 +1,7 @@
import { decodeSessionClaims } from '../auth-core/jwt-verify';
import { setAuthCookie } from '../common/cookie';
import { SessionsService, sessionClientFrom } from '../sessions/sessions.service';
import { AuthService } from './auth.service';
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import type { Request, Response } from 'express';
@@ -15,19 +16,23 @@ import type { Observable } from 'rxjs';
* historical default duration).
*
* Cheap by construction, one write per half-life at most:
* - `req.user` is only set after a guard ran verifyJwtAndLoadUser on this exact
* request, which already proved the token's `pv` matches the DB and its
* session is active, so the user id, pv and session id can be copied from
* the decoded (not re-verified) token.
* - Only a token past half its life is looked at again: the decoded claims
* answer that, and every younger token costs nothing more.
* - Such a token is verified once more, through the same check the guards use
* (signature, expiry, `pv` against the DB, an active session), and must name
* the user this request runs as. `req.user` alone proves nothing about the
* cookie: a route with its own guard chain lets that chain authenticate, and
* ApiTokenGuard does so with a public API key while the cookie beside it was
* never checked. Renewing that cookie re-signed whatever it claimed.
* - A request a public API key authenticated renews nothing, even beside a
* valid cookie: the key is that request's credential, and a key must never
* yield a browser session.
* - A tracked token is re-signed under the same session id and the session's
* expiry moves with it; a token from before sessions were tracked comes back
* as a tracked session whose id is derived from that token, so the parallel
* requests of one page load renew it into one session, not several. If the
* session ended in between, nothing is renewed.
* - The cookie is only renewed when it is the verified credential: extractToken
* prefers the cookie over the Authorization header, so cookie-present +
* req.user set means the guard verified the cookie. Bearer-only callers
* (MCP, API clients) are never renewed.
* - Bearer-only callers (MCP, API clients) carry no cookie and are never renewed.
*
* The cookie is written eagerly, before the handler runs: renewal doesn't
* depend on the handler's outcome, and this sidesteps @Res()/streaming routes
@@ -38,7 +43,10 @@ import type { Observable } from 'rxjs';
*/
@Injectable()
export class SessionRenewalInterceptor implements NestInterceptor {
constructor(private readonly sessions: SessionsService) {}
constructor(
private readonly sessions: SessionsService,
private readonly auth: AuthService,
) {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
if (context.getType() === 'http') {
@@ -51,7 +59,7 @@ export class SessionRenewalInterceptor implements NestInterceptor {
private async maybeRenew(req: Request & { user?: { id: number } }, res: Response): Promise<void> {
const cookieToken: string | undefined = (req as { cookies?: Record<string, string> }).cookies?.trek_session;
if (!req.user || !cookieToken || res.headersSent) return;
if (!req.user || req.apiToken || !cookieToken || res.headersSent) return;
const claims = decodeSessionClaims(cookieToken);
if (!claims || claims.purpose || claims.id !== req.user.id) return;
@@ -60,6 +68,9 @@ export class SessionRenewalInterceptor implements NestInterceptor {
const halfLife = claims.iat + (claims.exp - claims.iat) / 2;
if (Date.now() / 1000 < halfLife) return;
const owner = await this.auth.verifyJwtToken(cookieToken);
if (!owner || owner.id !== req.user.id) return;
const token = await this.sessions.renew(
{ id: req.user.id, pv: claims.pv, remember: claims.remember, jti: claims.jti, token: cookieToken },
sessionClientFrom(req),
+4 -1
View File
@@ -12,6 +12,7 @@ import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { AuthModule } from '../../src/nest/auth/auth.module';
import { AuthService } from '../../src/nest/auth/auth.service';
import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor';
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
@@ -86,7 +87,9 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
nest.useGlobalPipes(new ZodValidationPipe());
// Mirror the production APP_INTERCEPTOR: sliding session renewal (#1927).
// Inert for the harness's exp-less tokens and freshly issued logins.
nest.useGlobalInterceptors(new SessionRenewalInterceptor(moduleRef.get(SessionsService)));
nest.useGlobalInterceptors(
new SessionRenewalInterceptor(moduleRef.get(SessionsService), moduleRef.get(AuthService)),
);
await nest.init();
return nest;
}
+42 -2
View File
@@ -15,16 +15,19 @@ import { db } from '../../src/db/database';
import { UserSessions } from '../../src/db/entities/UserSessions.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { AuthModule } from '../../src/nest/auth/auth.module';
import { AuthService } from '../../src/nest/auth/auth.service';
import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor';
import { encryptMfaSecret } from '../../src/nest/common/crypto/mfaCrypto';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { withRequestContext } from '../../src/nest/database/request-context';
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
import { PublicApiModule } from '../../src/nest/public-api/public-api.module';
import { SessionPurgeJob } from '../../src/nest/sessions/session-purge.job';
import { SessionsService } from '../../src/nest/sessions/sessions.service';
import { createUser } from '../helpers/factories';
import { insertRow, updateRows } from '../helpers/factories/rows';
import { makeMcpToken } from '../helpers/factories/tokens';
import { sessionRows } from '../helpers/sessions';
import { resetRateLimits } from '../helpers/test-db';
import { createTestMikroOrmModule } from '../helpers/test-orm';
@@ -71,7 +74,14 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
async function build() {
moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule],
// PublicApiModule brings the one guard chain that authenticates by something
// other than the session cookie, which the renewal must not mistake for it.
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
AuthModule,
PublicApiModule,
],
})
.overrideProvider(MailerService)
.useValue({ sendPasswordResetEmail })
@@ -80,7 +90,9 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalInterceptors(new SessionRenewalInterceptor(moduleRef.get(SessionsService)));
nest.useGlobalInterceptors(
new SessionRenewalInterceptor(moduleRef.get(SessionsService), moduleRef.get(AuthService)),
);
await nest.init();
return nest;
}
@@ -296,6 +308,34 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
]);
}, 10000);
it('a public API key beside a session cookie never yields a session, whatever the cookie claims', async () => {
const { user } = freshUser('sess-apikey');
const key = 'trek_' + '7'.repeat(48);
await makeMcpToken(moduleRef.get(MikroORM), user.id, {
rawToken: key,
token_prefix: key.slice(0, 13),
kind: 'api',
});
const iat = Math.floor(Date.now() / 1000) - 60000;
// Past half its life, naming the key's owner and no session: one signed with a
// secret that is not the server's, and a real one.
const forged = `trek_session=${jwt.sign({ id: user.id, pv: 0, iat }, 'not-the-server-secret', { expiresIn: 86400, algorithm: 'HS256' })}`;
const genuine = sessionCookie(user.id, 0, { lifetime: 86400, consumed: 60000 });
for (const cookie of [forged, genuine]) {
const res = await request(server)
.get('/api/v1/trips')
.set('Authorization', `Bearer ${key}`)
.set('Cookie', cookie);
expect(res.status).toBe(200);
const set = (res.headers['set-cookie'] ?? []) as unknown as string[];
expect(set.some((c) => c.startsWith('trek_session='))).toBe(false);
}
expect(await sessionRows(db as never, user.id)).toEqual([]);
// The forged cookie opens nothing on its own either.
expect((await me(forged)).status).toBe(401);
}, 10000);
it("on a demo instance, visitors of the shared demo account neither see nor end each other's sessions", async () => {
createUser(db as never, { username: 'demo', email: 'demo@trek.app' });
vi.stubEnv('DEMO_MODE', 'true');
@@ -4,8 +4,10 @@
* lifetime. Covers the renew path (fresh token + cookie semantics per the
* `remember` claim) and every skip condition: young token, bearer-only request,
* unauthenticated request, purpose token, id mismatch, malformed claims,
* headers already sent, non-http context.
* headers already sent, non-http context, a cookie the session check refuses
* and a request a public API key authenticated.
*/
import type { AuthService } from '../../../src/nest/auth/auth.service';
import { SessionRenewalInterceptor } from '../../../src/nest/auth/session-renewal.interceptor';
import type { SessionsService } from '../../../src/nest/sessions/sessions.service';
import type { CallHandler, ExecutionContext } from '@nestjs/common';
@@ -30,6 +32,7 @@ function makeRes(headersSent = false) {
type ReqShape = {
cookies?: Record<string, string>;
user?: { id: number };
apiToken?: { scopes: string[] | null };
headers?: Record<string, string>;
secure?: boolean;
};
@@ -46,10 +49,18 @@ function handler(): CallHandler & { handle: ReturnType<typeof vi.fn> } {
return { handle: vi.fn(() => of('ok')) };
}
function makeInterceptor(renewed: string | null = 'renewed.jwt') {
/**
* `verified` is what the session check answers for the cookie: the user its
* token names when it is a live session, null when it is not one.
*/
function makeInterceptor(renewed: string | null = 'renewed.jwt', verified: { id: number } | null = { id: 1 }) {
const renew = vi.fn().mockResolvedValue(renewed);
const interceptor = new SessionRenewalInterceptor({ renew } as unknown as SessionsService);
return { interceptor, renew };
const verifyJwtToken = vi.fn().mockResolvedValue(verified);
const interceptor = new SessionRenewalInterceptor(
{ renew } as unknown as SessionsService,
{ verifyJwtToken } as unknown as AuthService,
);
return { interceptor, renew, verifyJwtToken };
}
async function run(
@@ -65,12 +76,13 @@ async function run(
}
describe('SessionRenewalInterceptor', () => {
it('SES-RENEW-001: does not renew a token under half of its lifetime', async () => {
const { interceptor, renew } = makeInterceptor();
it('SES-RENEW-001: does not renew a token under half of its lifetime, nor look it up', async () => {
const { interceptor, renew, verifyJwtToken } = makeInterceptor();
const res = makeRes();
const t = token({ id: 1, pv: 0 }, 86400, 1000); // ~1% consumed
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 } }, res);
expect(renew).not.toHaveBeenCalled();
expect(verifyJwtToken).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
@@ -226,4 +238,37 @@ describe('SessionRenewalInterceptor', () => {
expect(renew).toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it('SES-RENEW-014: renews no cookie the session check refuses, whoever req.user is', async () => {
// What a route with its own guard chain can see: ApiTokenGuard set req.user from
// a key, and the cookie beside it is unsigned, past half its life and names the
// key's owner without a session id. Decoding it alone would re-sign it.
const { interceptor, renew, verifyJwtToken } = makeInterceptor('renewed.jwt', null);
const res = makeRes();
const iat = Math.floor(Date.now() / 1000) - 60000;
const forged = jwt.sign({ id: 1, pv: 0, iat }, 'not-the-server-secret', { expiresIn: 86400, algorithm: 'HS256' });
await run(interceptor, { cookies: { trek_session: forged }, user: { id: 1 } }, res);
expect(verifyJwtToken).toHaveBeenCalledWith(forged);
expect(renew).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it('SES-RENEW-015: renews no cookie whose session belongs to another user than the request', async () => {
const { interceptor, renew } = makeInterceptor('renewed.jwt', { id: 2 });
const res = makeRes();
const t = token({ id: 1, pv: 0 }, 86400, 60000);
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 } }, res);
expect(renew).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it('SES-RENEW-016: a request a public API key authenticated renews nothing, even beside a valid cookie', async () => {
const { interceptor, renew, verifyJwtToken } = makeInterceptor();
const res = makeRes();
const t = token({ id: 1, pv: 0 }, 86400, 60000);
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 }, apiToken: { scopes: null } }, res);
expect(verifyJwtToken).not.toHaveBeenCalled();
expect(renew).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
});