sh-mcp/packages/shared/src/auth.ts

114 lines
4.5 KiB
TypeScript
Raw Normal View History

Phase 0b slice: monorepo scaffold + @sh-mcp/shared core + integration packages (#2) * Phase 0b slice: monorepo scaffold + shared core + integration packages The 0a-INDEPENDENT code slice (one-shot via af-0b-package-slice workflow: Haiku scaffold + Sonnet packages, Sonnet fix-to-green). Nothing deploys; no CDK/servers. - Monorepo scaffold: npm workspaces, strict TS (NodeNext), vitest (80% gate), eslint 9 flat config, prettier; ci.yaml/deploy.yaml callers (Node 24, enable-qemu). - @sh-mcp/shared: transport-agnostic core — Scope/AuthContext/ToolDef, ToolRegistry, redact()+maskValue() (PII), OpenAPI 3.1 generator. AUTH STUBBED behind an AuthProvider interface (TODO auth-layer-0a); JWT/aud/client_id/JWKS/deny-list deferred per design.md §2. - 9 integration packages (qbo, google-maps, internal-data, payments, knowledge-base, gmail, calendar, tasks, reminders): tools against shared, external deps mocked behind injected client interfaces; finance handlers call redact(). Verified green: tsc -b clean, vitest 245/245, eslint 0 errors. Auth mechanism intentionally deferred until the 0a spike resolves it (G16/§0.4). * Complete Cognito auth provider + Phase 1 build brief Finish the WIP CognitoAuthProvider (client_id allow-list as audience boundary, finance TTL ceiling, deny-list, scope-prefix stripping) with its test suite, and check in docs/build-plan-phase-1.md so the Phase 1 work has its governing brief in-tree (design.md §2.5). * ci: disable cdk synth for Phase 0b (no CDK app yet) The reusable ci-typescript-cdk workflow defaults run-cdk-synth: true, but the Phase 0b package scaffold has no cdk.json or stacks, so cdk synth fails with '--app is required'. Disable it here; Phase 1 re-enables it with the server CDK stubs.
2026-06-26 12:42:17 -04:00
/**
* Authorization interface and scope-enforcement guard.
*
* This file defines the scope-enforcement contract every tool handler relies on:
* 1. `ScopeError` — a typed error thrown when a required scope is absent.
* 2. `requireScope()` — enforces scope presence on an already-decoded
* AuthContext. Call this at the top of every tool handler.
* 3. `AuthProvider` interface — the contract the auth layer implements. Each
* server wires an AuthProvider into its request pipeline so that by the
* time `handler(input, ctx)` is called the context is already validated.
*
* The concrete implementation of `AuthProvider` now lives in `cognito-auth.ts`
* (`CognitoAuthProvider`) — built and verified after the 0a spike proved the
* live Cognito access-token shape (verified `sub`/`scope`/`client_id`, no native
* `aud`). It verifies the JWT signature against the pool JWKS, validates `iss`,
* enforces the `client_id` allow-list AS the audience boundary (the token has no
* `aud`), applies the finance TTL ceiling and deny-list, and extracts scopes.
* This file stays transport- and provider-agnostic; see docs/design.md §2.
*/
import type { AuthContext, Scope } from './types.js';
// ---------------------------------------------------------------------------
// ScopeError
// ---------------------------------------------------------------------------
/**
* Thrown by `requireScope()` when the caller's AuthContext does not include
* the required scope.
*
* Transport adapters (OpenAPI handler, MCP dispatcher) should catch this and
* return an appropriate 403 / permission-denied response.
*/
export class ScopeError extends Error {
/** The scope that was required but absent. */
readonly requiredScope: Scope;
/** The `sub` from the AuthContext that triggered the error. */
readonly sub: string;
constructor(sub: string, requiredScope: Scope) {
super(
`User "${sub}" does not have the required scope "${requiredScope}".`,
);
this.name = 'ScopeError';
this.requiredScope = requiredScope;
this.sub = sub;
// Maintain proper prototype chain for `instanceof` checks.
Object.setPrototypeOf(this, new.target.prototype);
}
}
// ---------------------------------------------------------------------------
// requireScope
// ---------------------------------------------------------------------------
/**
* Assert that `ctx` contains `scope`. Throws `ScopeError` if it does not.
*
* Call at the top of every tool handler before touching any input or reaching
* any downstream service:
*
* ```ts
* handler: async (input, ctx) => {
* requireScope(ctx, 'finance:read');
* // ... safe to proceed
* },
* ```
*
* NOTE: Server-side enforcement is authoritative. Tool-hiding in the agent UI
* is a convenience only (design.md §2.5). This guard enforces independently.
*
* NOTE: JWT signature/issuer/aud/client_id validation is NOT done here — see
* the TODO above. By the time `handler` is called, the `AuthProvider` has
* already validated the token and populated `ctx`.
*/
export function requireScope(ctx: AuthContext, scope: Scope): void {
if (!ctx.scopes.includes(scope)) {
throw new ScopeError(ctx.sub, scope);
}
}
// ---------------------------------------------------------------------------
// AuthProvider interface (deferred 0a-gated auth layer contract)
// ---------------------------------------------------------------------------
/**
* Contract that each server's concrete auth layer must implement.
*
* The server's request pipeline calls `authenticate(req)` once per inbound
* request and passes the resolved `AuthContext` into every tool handler.
*
* `req` is typed as `unknown` so this interface stays transport-agnostic
* (works for an Express `Request`, a raw `IncomingMessage`, a Lambda event,
* or a test-double). The concrete implementation casts to the appropriate type.
*
* TODO(auth-layer-0a): Implement this interface in the deferred auth layer.
* A concrete implementation lives in `servers/sh-mcp-ops/src/auth.ts` and
* `servers/sh-mcp-finance/src/auth.ts` once that layer is built.
*/
export interface AuthProvider {
/**
* Extract and validate the inbound token from `req`, returning a fully
* populated AuthContext on success.
*
* Throws (or rejects) on any validation failure:
* - Missing / malformed Authorization header
* - Invalid JWT signature
* - Wrong issuer, audience, or client_id
* - Expired token
* - User on the deny-list
*/
authenticate(req: unknown): Promise<AuthContext>;
}