mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
feat(api): let public API keys be scoped to single areas
A key could only ever read everything a user owns. When a second service reads TREK on that user's behalf, that is more than it needs: Dawarich wants trips, days and places, not notes, bookings or the wish list. Keys can now be minted with an explicit list of areas, checked in the guard and shown when the key is listed. Keys that existed before this keep full read access, so nothing that works today stops working. A key marked as limited whose list cannot be read grants nothing rather than everything.
This commit is contained in:
@@ -21,13 +21,17 @@ import { TokenService } from '../tokens/token.service';
|
||||
* - **No session JWT.** A session cookie leaking into a third-party integration is
|
||||
* exactly what a machine credential exists to prevent, and a JWT that reaches
|
||||
* this surface is almost always an accident.
|
||||
* - **No OAuth tokens (yet).** They carry scopes this surface does not interpret
|
||||
* yet, and accepting a credential whose restrictions you ignore is worse than
|
||||
* refusing it. When `/api/v1` grows write routes, scopes get honoured first.
|
||||
* - **No OAuth tokens.** They carry MCP scopes, which are a different vocabulary
|
||||
* from the read sections this surface understands — `trips:write` has no
|
||||
* meaning on a read-only API, and quietly mapping one onto the other would be
|
||||
* inventing permissions nobody granted. Accepting a credential whose
|
||||
* restrictions you reinterpret is worse than refusing it.
|
||||
*
|
||||
* The guard authenticates but does not authorise: it resolves `req.user` and stops
|
||||
* there. Which trips that user may read is decided per row against
|
||||
* `DatabaseService.canAccessTrip`, never from anything the caller sent.
|
||||
* The guard resolves two things and then stops: **who** is calling (`req.user`)
|
||||
* and **what their key may read** (`req.apiToken`). Both are needed and neither
|
||||
* is sufficient. Which trips that user may reach is still decided per row
|
||||
* against `DatabaseService.canAccessTrip`, never from anything the caller sent;
|
||||
* the grant only narrows that further, and can never widen it.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ApiTokenGuard implements CanActivate {
|
||||
@@ -42,14 +46,15 @@ export class ApiTokenGuard implements CanActivate {
|
||||
401,
|
||||
);
|
||||
}
|
||||
const user = this.tokens.verifyApiToken(token);
|
||||
if (!user) {
|
||||
const resolved = this.tokens.verifyApiTokenWithGrant(token);
|
||||
if (!resolved) {
|
||||
throw new HttpException(
|
||||
{ error: 'Invalid API token', code: 'API_TOKEN_INVALID' },
|
||||
401,
|
||||
);
|
||||
}
|
||||
req.user = user;
|
||||
req.user = resolved.user;
|
||||
req.apiToken = resolved.grant;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { PUBLIC_API_SCOPES, type PublicApiScope } from '@trek/shared';
|
||||
import type { RateLimitService } from '../common/rate-limit.service';
|
||||
|
||||
/**
|
||||
@@ -44,3 +45,57 @@ export function requireUserId(req: Request): number {
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the key on this request may read.
|
||||
*
|
||||
* A request that somehow reached a route without the guard has no grant, and
|
||||
* the honest answer there is "nothing" rather than "everything" — the same
|
||||
* fail-closed reasoning as `requireUserId` throwing a 401. A key with no
|
||||
* narrowing has already been resolved to the full list by the token service,
|
||||
* so there is no absent-means-all rule left to get wrong here.
|
||||
*/
|
||||
export function grantedScopes(req: Request): readonly PublicApiScope[] {
|
||||
return req.apiToken?.scopes ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a request whose key does not cover the section it asked for.
|
||||
*
|
||||
* **403, and a code of its own.** Not 401: the credential is valid and
|
||||
* re-authenticating will not help. Not 404: an integrator debugging a key they
|
||||
* narrowed themselves needs to be told that, not sent looking for a missing
|
||||
* trip. The two existing codes are deliberately left alone so
|
||||
* "expired/invalid" and "not enough access" stay distinguishable.
|
||||
*/
|
||||
export function requireScope(req: Request, scope: PublicApiScope): void {
|
||||
if (!grantedScopes(req).includes(scope)) {
|
||||
throw new HttpException(
|
||||
{
|
||||
error: `This API key is not allowed to read ${scope}`,
|
||||
code: 'API_SCOPE_FORBIDDEN',
|
||||
required_scope: scope,
|
||||
},
|
||||
403,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow a set of requested sections to what the key may actually read.
|
||||
*
|
||||
* Filtering rather than refusing, for one specific case: `include` defaults to
|
||||
* everything, so a narrow key asking for a trip with no `include` at all would
|
||||
* otherwise be refused for wanting sections it never named. It gets what it may
|
||||
* have. A caller that *names* a forbidden section is a different matter and is
|
||||
* refused by `requireScope` at the controller, because silently dropping what
|
||||
* somebody explicitly asked for is how integrators end up debugging their own
|
||||
* correct code.
|
||||
*/
|
||||
export function narrowToGrant<T extends string>(sections: readonly T[], req: Request): T[] {
|
||||
const granted = new Set<string>(grantedScopes(req));
|
||||
return sections.filter((section) => granted.has(section));
|
||||
}
|
||||
|
||||
/** Every section, for the callers that need the canonical list. */
|
||||
export const ALL_PUBLIC_API_SCOPES: readonly PublicApiScope[] = PUBLIC_API_SCOPES;
|
||||
|
||||
@@ -10,7 +10,12 @@ import {
|
||||
} from '@trek/shared';
|
||||
import { ApiTokenGuard } from './api-token.guard';
|
||||
import { PublicApiService } from './public-api.service';
|
||||
import { enforcePublicApiRateLimit, requireUserId } from './public-api-request';
|
||||
import {
|
||||
enforcePublicApiRateLimit,
|
||||
narrowToGrant,
|
||||
requireScope,
|
||||
requireUserId,
|
||||
} from './public-api-request';
|
||||
import { RateLimitService } from '../common/rate-limit.service';
|
||||
|
||||
/**
|
||||
@@ -48,6 +53,7 @@ export class PublicApiController {
|
||||
@Get('trips')
|
||||
listTrips(@Req() req: Request): PublicApiTripList {
|
||||
this.limit(req);
|
||||
requireScope(req, 'trips');
|
||||
return { trips: this.api.listTrips(requireUserId(req)) };
|
||||
}
|
||||
|
||||
@@ -61,6 +67,7 @@ export class PublicApiController {
|
||||
@Get('bucket-list')
|
||||
listBucketList(@Req() req: Request): PublicApiBucketList {
|
||||
this.limit(req);
|
||||
requireScope(req, 'bucket-list');
|
||||
return { items: this.api.listBucketList(requireUserId(req)) };
|
||||
}
|
||||
|
||||
@@ -78,8 +85,20 @@ export class PublicApiController {
|
||||
@Query('include') include?: string,
|
||||
): PublicApiTrip {
|
||||
this.limit(req);
|
||||
requireScope(req, 'trips');
|
||||
const tripId = parseTripId(id);
|
||||
const trip = this.api.getTrip(tripId, requireUserId(req), parseInclude(include));
|
||||
|
||||
// A named section the key may not read is refused outright; an unnamed one —
|
||||
// `include` absent, which means "everything" — is simply narrowed. Silently
|
||||
// dropping a section somebody asked for by name is how an integrator ends
|
||||
// up debugging their own correct code.
|
||||
const asked = parseInclude(include);
|
||||
if (include !== undefined && include.trim() !== '') {
|
||||
for (const section of asked) requireScope(req, section);
|
||||
}
|
||||
const allowed = narrowToGrant(asked, req);
|
||||
|
||||
const trip = this.api.getTrip(tripId, requireUserId(req), allowed);
|
||||
if (!trip) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomBytes, createHash } from 'crypto';
|
||||
import {
|
||||
PUBLIC_API_SCOPES,
|
||||
type PublicApiGrant,
|
||||
type PublicApiScope,
|
||||
} from '@trek/shared';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
|
||||
// Import from sessionManager directly, NOT the ../../mcp barrel: the barrel pulls
|
||||
@@ -57,21 +62,46 @@ export class TokenService {
|
||||
}
|
||||
|
||||
private listTokens(userId: number, kind: TokenKind) {
|
||||
return this.db.all(
|
||||
'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE user_id = ? AND kind = ? ORDER BY created_at DESC',
|
||||
const rows = this.db.all<TokenRow>(
|
||||
'SELECT id, name, token_prefix, created_at, last_used_at, scope_mode, api_scopes FROM mcp_tokens WHERE user_id = ? AND kind = ? ORDER BY created_at DESC',
|
||||
userId, kind
|
||||
);
|
||||
// The MCP list keeps the exact shape it has always had: those tokens carry
|
||||
// no read scopes, and two columns that are always "everything" would be
|
||||
// noise in a panel that cannot act on them.
|
||||
if (kind === 'mcp') {
|
||||
return rows.map(({ scope_mode: _mode, api_scopes: _scopes, ...rest }) => rest);
|
||||
}
|
||||
return rows.map((row) => {
|
||||
const grant = resolveGrant(row.scope_mode, row.api_scopes);
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
token_prefix: row.token_prefix,
|
||||
created_at: row.created_at,
|
||||
last_used_at: row.last_used_at,
|
||||
scope_mode: grant.mode,
|
||||
scopes: grant.scopes,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
createMcpToken(userId: number, rawName: unknown) {
|
||||
return this.createToken(userId, rawName, 'mcp');
|
||||
}
|
||||
|
||||
createApiToken(userId: number, rawName: unknown) {
|
||||
return this.createToken(userId, rawName, 'api');
|
||||
/**
|
||||
* An integration key, optionally narrowed to a few sections.
|
||||
*
|
||||
* Omitting `scopes` means the key reads everything — what every key did
|
||||
* before this argument existed. Narrowing is opt-in on purpose: shipping the
|
||||
* column must not change what an already-running integration can do.
|
||||
*/
|
||||
createApiToken(userId: number, rawName: unknown, scopes?: readonly string[]) {
|
||||
return this.createToken(userId, rawName, 'api', scopes);
|
||||
}
|
||||
|
||||
private createToken(userId: number, rawName: unknown, kind: TokenKind): { error?: string; status?: number; token?: Record<string, unknown> } {
|
||||
private createToken(userId: number, rawName: unknown, kind: TokenKind, scopes?: readonly string[]): { error?: string; status?: number; token?: Record<string, unknown> } {
|
||||
const name = rawName as string | undefined;
|
||||
if (!name?.trim()) return { error: 'Token name is required', status: 400 };
|
||||
if (name.trim().length > 100) return { error: 'Token name must be 100 characters or less', status: 400 };
|
||||
@@ -83,9 +113,15 @@ export class TokenService {
|
||||
const tokenHash = createHash('sha256').update(rawToken).digest('hex');
|
||||
const tokenPrefix = rawToken.slice(0, 13);
|
||||
|
||||
// An MCP token never carries read scopes, so it is stored as "everything" —
|
||||
// the column default — rather than being handed a list it would ignore.
|
||||
const narrowed = kind === 'api' ? sanitizeScopes(scopes) : null;
|
||||
|
||||
const result = this.db.run(
|
||||
'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix, kind) VALUES (?, ?, ?, ?, ?)',
|
||||
userId, name.trim(), tokenHash, tokenPrefix, kind
|
||||
'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix, kind, scope_mode, api_scopes) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
userId, name.trim(), tokenHash, tokenPrefix, kind,
|
||||
narrowed ? 'limited' : 'all',
|
||||
narrowed ? JSON.stringify(narrowed) : null,
|
||||
);
|
||||
|
||||
const token = this.db.get(
|
||||
@@ -93,7 +129,10 @@ export class TokenService {
|
||||
result.lastInsertRowid
|
||||
);
|
||||
|
||||
return { token: { ...(token as object), raw_token: rawToken } };
|
||||
const grant = kind === 'api'
|
||||
? { scope_mode: narrowed ? 'limited' : 'all', scopes: narrowed ?? [...PUBLIC_API_SCOPES] }
|
||||
: {};
|
||||
return { token: { ...(token as object), ...grant, raw_token: rawToken } };
|
||||
}
|
||||
|
||||
deleteMcpToken(userId: number, tokenId: string) {
|
||||
@@ -183,6 +222,27 @@ export class TokenService {
|
||||
return this.verifyToken(rawToken, 'api');
|
||||
}
|
||||
|
||||
/**
|
||||
* The same lookup, plus what the key is allowed to read.
|
||||
*
|
||||
* A second method rather than a widened `verifyApiToken`: the guard needs
|
||||
* both halves, nothing else needs either, and the existing signature is
|
||||
* pinned by tests that assert exactly a `User`.
|
||||
*/
|
||||
verifyApiTokenWithGrant(rawToken: string): { user: User; grant: PublicApiGrant } | null {
|
||||
const hash = createHash('sha256').update(rawToken).digest('hex');
|
||||
const row = this.db.get<User & { scope_mode: string | null; api_scopes: string | null }>(`
|
||||
SELECT u.id, u.username, u.email, u.role, mt.scope_mode, mt.api_scopes
|
||||
FROM mcp_tokens mt
|
||||
JOIN users u ON mt.user_id = u.id
|
||||
WHERE mt.token_hash = ? AND mt.kind = 'api'
|
||||
`, hash);
|
||||
if (!row) return null;
|
||||
this.db.run('UPDATE mcp_tokens SET last_used_at = CURRENT_TIMESTAMP WHERE token_hash = ?', hash);
|
||||
const { scope_mode, api_scopes, ...user } = row;
|
||||
return { user: user as User, grant: resolveGrant(scope_mode, api_scopes) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash, look up, and require the kind the calling surface accepts.
|
||||
*
|
||||
@@ -206,3 +266,58 @@ export class TokenService {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface TokenRow {
|
||||
id: number;
|
||||
name: string;
|
||||
token_prefix: string;
|
||||
created_at: string;
|
||||
last_used_at: string | null;
|
||||
scope_mode: string | null;
|
||||
api_scopes: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The requested sections, cleaned up — unknown values dropped, duplicates
|
||||
* collapsed, order pinned to the canonical list so two keys with the same
|
||||
* access read the same in the panel.
|
||||
*
|
||||
* Returns null for "no narrowing was asked for", which is what makes the caller
|
||||
* store full access rather than an empty list that would lock the key out of
|
||||
* everything.
|
||||
*/
|
||||
function sanitizeScopes(scopes: readonly string[] | undefined): PublicApiScope[] | null {
|
||||
if (!scopes || scopes.length === 0) return null;
|
||||
const wanted = new Set(scopes);
|
||||
const kept = PUBLIC_API_SCOPES.filter((scope) => wanted.has(scope));
|
||||
return kept.length > 0 ? [...kept] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a stored row means, read defensively — in both directions.
|
||||
*
|
||||
* A row that does not say 'limited' is a full-access key: that is what every key
|
||||
* written before this column existed had, and a missing narrowing must not cost
|
||||
* a running integration its access. Narrowing is a deliberate act; its absence
|
||||
* is not a denial.
|
||||
*
|
||||
* But once a row HAS said 'limited', every way of failing to read its list
|
||||
* denies. Unparseable JSON, a non-array, or a list of scope names this version
|
||||
* no longer knows (a renamed constant, a hand-edited row) resolves to no scopes
|
||||
* at all rather than to everything: the whole reason `scope_mode` is an explicit
|
||||
* flag instead of "NULL means everything" is that a key minted as restricted
|
||||
* must never widen on its own. A key that stops working is a support ticket; a
|
||||
* key that quietly reads every trip is the bug this feature exists to prevent.
|
||||
*/
|
||||
function resolveGrant(mode: string | null, raw: string | null): PublicApiGrant {
|
||||
if (mode !== 'limited') return { mode: 'all', scopes: [...PUBLIC_API_SCOPES] };
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
parsed = null;
|
||||
}
|
||||
if (!Array.isArray(parsed)) return { mode: 'limited', scopes: [] };
|
||||
const kept = sanitizeScopes(parsed.filter((value): value is string => typeof value === 'string'));
|
||||
return { mode: 'limited', scopes: kept ?? [] };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user