sh-mcp/packages/shared/src/cognito-auth.test.ts
Adam Moussa 22c09e99fe
Some checks are pending
deploy / deploy (push) Waiting to run
Phase 1: runnable MCP + OpenAPI servers (ops + finance) (#3)
* Add shared transport: dispatch, MCP + OpenAPI adapters, local auth

Add the single authoritative tool-execution path (executeTool) plus the two
universal interfaces over it (design.md §2.5, §7.3):
- dispatch.ts: scope enforcement, ajv input validation, rate limiting, finance
  egress redaction (redactDeep), and structured audit emission on one path.
- audit.ts / rate-limit.ts: injected AuditLogger + RateLimiter abstractions.
- mcp.ts: low-level MCP Server with scope-filtered tools/list (tool-hiding) and
  tools/call routed through executeTool.
- http.ts: Express host mounting /mcp, /openapi.json, POST /tools/:name, /healthz.
- openapi.ts: buildOpenApiDocument wraps the existing path generator into a full
  OpenAPI 3.1 document.
- local-auth.ts: LocalAuthProvider (dev bearer tokens) that refuses to construct
  outside SH_MCP_ENV=local and enforces audience binding (design.md §3, §6).

* Add in-memory dev clients; make package tool exports lazy

Add an in-memory Client implementation per integration package (seeded fake
data, no network) selected when SH_MCP_ENV=local (build-plan §4). Gmail/calendar/
tasks dev clients partition by ctx.sub; payments/qbo seed sensitive-looking
fields so the redaction egress path has real targets to mask.

Make the eager default-tool exports in tasks/reminders/qbo LAZY (getDefaultTools)
so importing a package barrel no longer constructs an AWS client at module load
(build-plan §7 'no I/O at import time') — the previous eager construction broke
server startup. Fix payments tsconfig rootDir (src, was '.') so its declarations
resolve under dist/index.d.ts like the other 8 packages.

* Add runnable sh-mcp-ops and sh-mcp-finance servers

Two thin composition-root servers over the shared transport (design.md §3):
- ops: internal-data, knowledge-base, google-maps, gmail, calendar, tasks,
  reminders. finance: qbo, payments (audited + redacted on egress).
- config from env only (no hardcoded ids/issuer/tables); SH_MCP_ENV selects
  LocalAuthProvider + dev clients (local) vs CognitoAuthProvider + real stubs
  (aws). Finance applies the 15-min finance-token TTL ceiling (design.md §2.5).
- index.ts is the only place .listen() is called; a Lambda handler placeholder
  is exported but not depended on.
- synth-only CDK stubs (no real IAM/Cognito/WAF) so 'cdk synth' has a valid app
  (build-plan §6); READMEs document local run, dev tokens, curl, MCP Inspector.

* Add security-weighted test suite + coverage gate; wire tooling

Add tests for the highest-risk surface (build-plan §5, design.md §7.3):
tool-hiding, server-side scope enforcement (incl. forced hidden calls),
audience binding, input-schema validation, finance redaction on egress, audit
emission with hashed args, prompt-injection regression (tool output is data),
rate limiting, MCP conformance (in-memory transport round-trip), OpenAPI 3.1
validity, and local-auth safety. Add HTTP integration tests (supertest) for both
servers and per-package dev-client tests. 405 tests pass.

Wire the coverage gate into vitest.config.ts: 80% overall, with per-file
thresholds on the auth + dispatch crown jewels; exclude deferred real client
stubs, entrypoints, cdk apps, and aws-only config from the gate (documented).
Extend eslint flat config + add .prettierignore to cover servers/. Commit the
updated package-lock.json.

* Suppress pre-existing dev-tooling + out-of-scope scanner findings

Add written-justification suppressions for the 4 confirmed crit/high pre-push
scanner findings, none of which are in this PR's Phase 1 production code:
- npmaudit vitest / @vitest/coverage-v8 / vite: dev/test-only deps that never
  run in the deployed server/Lambda runtime (pins carried from Phase 0b;
  Dependabot will bump).
- gitleaks docs/agentforce-plan.md secret: that file is not on this branch and
  not in this changeset; flagged for the maintainer to scrub on its own branch.

The deep agentic /sh-security-review (required for this auth/authz-touching PR)
was NOT run by the agent and is flagged outstanding in the PR body.

* Address CodeQL findings: bound ajv error work + edge rate limiting

GHAS code-scanning alerts on this PR:
- dispatch.ts (js/resource-exhaustion): ajv ran with allErrors:true on
  untrusted input, letting a crafted payload force unbounded error
  enumeration. Switch to allErrors:false (default) so validation
  short-circuits on the first failure; the 400 still names that path.
- http.ts (js/missing-rate-limiting): the authenticated routes (/mcp,
  /tools/:name) had no edge throttle — auth/JWT verification ran on every
  request before the per-sub dispatch limiter could apply. Add an IP-keyed
  express-rate-limit in front of authenticate (120/60s default, configurable),
  returning the standard 429 shape. Defense-in-depth over the per-sub +
  per-tool limiter in executeTool; API GW/WAF remains the production edge.

Tests: +2 cases proving the edge limiter throttles before auth (429, not
401) on /tools and /mcp. 407 pass; tsc/eslint/prettier clean.

* Fix polynomial ReDoS in Bearer-token extraction (CodeQL js/polynomial-redos)

extractBearerToken matched /^Bearer\s+(.+)$/ — \s and . both match a space,
so the two quantifiers overlap and a crafted header can drive polynomial
backtracking. Require the capture to start with a non-whitespace char
(/^Bearer\s+(\S.*)$/), removing the ambiguity → linear match. Behavior is
unchanged for real tokens; +2 regression tests.

* Harden auth + finance redaction (sh-security-review confirmed mediums)

Two confirmed medium findings from the agentic security review:

- Fail-open SH_MCP_ENV: config defaulted to 'local' when the var was unset,
  so a deploy that forgot SH_MCP_ENV=aws would silently run LocalAuthProvider
  and accept static dev bearer tokens (dev-finance-admin -> finance:admin).
  Now fail-closed: SH_MCP_ENV must be explicitly 'local' or 'aws' or the
  server refuses to start. Plus an independent guard in LocalAuthProvider
  that refuses to construct in an AWS runtime (AWS_LAMBDA_FUNCTION_NAME /
  AWS_EXECUTION_ENV present), regardless of the env flag.

- Finance egress redaction gap: redactDeep only wholesale-masked a sensitive
  key when its value was a scalar; an object/array under a sensitive key was
  recursed into, letting a bare nested value (e.g. {account:{number:...}})
  escape the keyword-gated pattern matcher. Now the entire subtree under a
  sensitive key is masked. No current finance tool emitted such shapes (all
  flat strings), so this closes a latent hole in the universal safety net.

+4 tests (subtree redaction, AWS-runtime guard). 411 pass; coverage gate green.

Review also produced lows (memo free-text digits, unsalted argsHash,
unauth /openapi.json by-design, session-cap no-reset by-design) tracked
separately; 0 confirmed critical/high — review verdict PASS.
2026-06-26 13:33:21 -04:00

273 lines
9.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Security-weighted tests for the Cognito auth layer.
*
* The token claims here mirror the shape the 0a spike actually observed from
* live Cognito (access token: prefixed `scope` string, `client_id`, `token_use`,
* no native `aud`). The audience-boundary, scope-isolation, TTL-ceiling and
* revocation cases are the trust-tier guarantees from design.md §2 — they are
* the reason this file carries the heaviest coverage in the platform.
*/
import { describe, it, expect } from 'vitest';
import { generateKeyPair, SignJWT, type JWTVerifyGetKey } from 'jose';
import {
CognitoAuthProvider,
AuthError,
extractScopes,
extractBearerToken,
cognitoIssuer,
type CognitoAuthConfig,
} from './cognito-auth.js';
import { requireScope } from './auth.js';
type KeyPair = Awaited<ReturnType<typeof generateKeyPair>>;
const ISSUER = cognitoIssuer('us-east-1', 'us-east-1_TESTPOOL');
const OPS_CLIENT = 'ops-app-client-id';
const FIN_CLIENT = 'finance-app-client-id';
// Signing keys for the suite, plus a second pair to forge bad signatures.
const signing: KeyPair = await generateKeyPair('RS256');
const attacker: KeyPair = await generateKeyPair('RS256');
/** A JWKS resolver that returns our test public key (stands in for the pool's JWKS). */
const jwks: JWTVerifyGetKey = async () => signing.publicKey;
function baseConfig(overrides: Partial<CognitoAuthConfig> = {}): CognitoAuthConfig {
return {
issuer: ISSUER,
audience: 'sh-mcp-ops',
allowedClientIds: [OPS_CLIENT],
scopePrefix: 'sh-mcp-ops',
jwks,
...overrides,
};
}
function financeConfig(overrides: Partial<CognitoAuthConfig> = {}): CognitoAuthConfig {
return baseConfig({
audience: 'sh-mcp-finance',
allowedClientIds: [FIN_CLIENT],
scopePrefix: 'sh-mcp-finance',
maxTtlSeconds: 900,
ttlGuardedScopes: ['finance:read', 'finance:admin'],
...overrides,
});
}
interface MintOpts {
issuer?: string;
clientId?: string;
scope?: string;
tokenUse?: string;
sub?: string;
iat?: number;
ttlSeconds?: number;
signer?: KeyPair['privateKey'];
}
async function mint(opts: MintOpts = {}): Promise<string> {
const now = Math.floor(Date.now() / 1000);
const iat = opts.iat ?? now;
const ttl = opts.ttlSeconds ?? 3600;
return new SignJWT({
token_use: opts.tokenUse ?? 'access',
client_id: opts.clientId ?? OPS_CLIENT,
scope: opts.scope ?? 'sh-mcp-ops/ops:read sh-mcp-ops/ops:tasks openid email',
})
.setProtectedHeader({ alg: 'RS256' })
.setSubject(opts.sub ?? 'user-sub-123')
.setIssuer(opts.issuer ?? ISSUER)
.setIssuedAt(iat)
.setExpirationTime(iat + ttl)
.sign(opts.signer ?? signing.privateKey);
}
describe('CognitoAuthProvider.authenticate', () => {
it('accepts a valid access token and extracts sub + this tier’s scopes', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const ctx = await provider.authenticate(`Bearer ${await mint()}`);
expect(ctx.sub).toBe('user-sub-123');
expect(ctx.aud).toBe('sh-mcp-ops');
expect(ctx.scopes).toEqual(['ops:read', 'ops:tasks']);
});
it('drops cross-tier and standard (openid/email) scopes', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const token = await mint({
scope: 'sh-mcp-ops/ops:read sh-mcp-finance/finance:read openid email',
});
const ctx = await provider.authenticate(`Bearer ${token}`);
expect(ctx.scopes).toEqual(['ops:read']);
});
it('rejects a token from the wrong issuer', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const token = await mint({ issuer: 'https://evil.example.com/pool' });
await expect(provider.authenticate(`Bearer ${token}`)).rejects.toMatchObject({
code: 'invalid_token',
});
});
it('AUDIENCE BOUNDARY: rejects an ops token presented to the finance server', async () => {
const finance = new CognitoAuthProvider(financeConfig());
const opsToken = await mint({ clientId: OPS_CLIENT, scope: 'sh-mcp-ops/ops:read' });
await expect(finance.authenticate(`Bearer ${opsToken}`)).rejects.toMatchObject({
code: 'client_not_allowed',
});
});
it('rejects an id token (token_use !== "access")', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const token = await mint({ tokenUse: 'id' });
await expect(provider.authenticate(`Bearer ${token}`)).rejects.toMatchObject({
code: 'invalid_token',
});
});
it('rejects an expired token', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const now = Math.floor(Date.now() / 1000);
const token = await mint({ iat: now - 7200, ttlSeconds: 3600 }); // expired ~1h ago
await expect(provider.authenticate(`Bearer ${token}`)).rejects.toMatchObject({
code: 'invalid_token',
});
});
it('rejects a token signed by an unknown key (forged signature)', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const token = await mint({ signer: attacker.privateKey });
await expect(provider.authenticate(`Bearer ${token}`)).rejects.toMatchObject({
code: 'invalid_token',
});
});
it('rejects a missing Authorization header', async () => {
const provider = new CognitoAuthProvider(baseConfig());
await expect(provider.authenticate({ headers: {} })).rejects.toMatchObject({
code: 'missing_token',
});
});
it('FINANCE TTL: rejects a finance-scoped token whose lifetime exceeds the ceiling', async () => {
const finance = new CognitoAuthProvider(financeConfig());
const longToken = await mint({
clientId: FIN_CLIENT,
scope: 'sh-mcp-finance/finance:read',
ttlSeconds: 3600,
});
await expect(finance.authenticate(`Bearer ${longToken}`)).rejects.toMatchObject({
code: 'ttl_exceeded',
});
});
it('FINANCE TTL: accepts a finance-scoped token within the ceiling', async () => {
const finance = new CognitoAuthProvider(financeConfig());
const shortToken = await mint({
clientId: FIN_CLIENT,
scope: 'sh-mcp-finance/finance:read',
ttlSeconds: 600,
});
const ctx = await finance.authenticate(`Bearer ${shortToken}`);
expect(ctx.scopes).toEqual(['finance:read']);
});
it('does not apply the TTL ceiling to non-guarded scopes', async () => {
const finance = new CognitoAuthProvider(financeConfig());
// ops:read carried under the finance prefix is known but not TTL-guarded.
const longToken = await mint({
clientId: FIN_CLIENT,
scope: 'sh-mcp-finance/ops:read',
ttlSeconds: 3600,
});
const ctx = await finance.authenticate(`Bearer ${longToken}`);
expect(ctx.scopes).toEqual(['ops:read']);
});
it('rejects a revoked (deny-listed) user', async () => {
const provider = new CognitoAuthProvider(
baseConfig({ denyList: { isDenied: async (sub) => sub === 'revoked-user' } }),
);
const token = await mint({ sub: 'revoked-user' });
await expect(provider.authenticate(`Bearer ${token}`)).rejects.toMatchObject({
code: 'revoked',
});
});
it('returns a context that satisfies requireScope for granted scopes only', async () => {
const provider = new CognitoAuthProvider(baseConfig());
const ctx = await provider.authenticate(`Bearer ${await mint()}`);
expect(() => requireScope(ctx, 'ops:read')).not.toThrow();
expect(() => requireScope(ctx, 'finance:read')).toThrow();
});
});
describe('extractScopes', () => {
it('strips the tier prefix and keeps known scopes in order', () => {
expect(extractScopes('sh-mcp-ops/ops:read sh-mcp-ops/ops:tasks', 'sh-mcp-ops')).toEqual([
'ops:read',
'ops:tasks',
]);
});
it('drops other tiers and standard scopes', () => {
expect(
extractScopes('sh-mcp-ops/ops:read sh-mcp-finance/finance:read openid email', 'sh-mcp-ops'),
).toEqual(['ops:read']);
});
it('drops prefixed-but-unknown scopes', () => {
expect(extractScopes('sh-mcp-ops/bogus:scope', 'sh-mcp-ops')).toEqual([]);
});
it('de-duplicates', () => {
expect(extractScopes('sh-mcp-ops/ops:read sh-mcp-ops/ops:read', 'sh-mcp-ops')).toEqual([
'ops:read',
]);
});
it('handles empty / non-string input', () => {
expect(extractScopes('', 'sh-mcp-ops')).toEqual([]);
expect(extractScopes(undefined, 'sh-mcp-ops')).toEqual([]);
expect(extractScopes(null, 'sh-mcp-ops')).toEqual([]);
});
});
describe('extractBearerToken', () => {
it('reads a raw Authorization header string', () => {
expect(extractBearerToken('Bearer abc.def.ghi')).toBe('abc.def.ghi');
});
it('is case-insensitive on the scheme', () => {
expect(extractBearerToken('bearer abc')).toBe('abc');
});
it('reads a plain headers object (either header casing)', () => {
expect(extractBearerToken({ headers: { authorization: 'Bearer xyz' } })).toBe('xyz');
expect(extractBearerToken({ headers: { Authorization: 'Bearer XYZ' } })).toBe('XYZ');
});
it('reads a Fetch Headers-like object', () => {
const headers = new Headers({ authorization: 'Bearer fetchtoken' });
expect(extractBearerToken({ headers })).toBe('fetchtoken');
});
it('throws AuthError on a missing header', () => {
expect(() => extractBearerToken({ headers: {} })).toThrow(AuthError);
});
it('throws AuthError on a non-Bearer header', () => {
expect(() => extractBearerToken('Basic abc')).toThrow(AuthError);
});
// ReDoS guard (CodeQL js/polynomial-redos): the matcher is /\s+(\S.*)/, not
// the ambiguous /\s+(.+)/. These pin the behavior that the `\S` fix preserves.
it('still captures a token that follows multiple separating spaces', () => {
expect(extractBearerToken('Bearer abc.def')).toBe('abc.def');
});
it('rejects a "Bearer" header with no token after the whitespace', () => {
expect(() => extractBearerToken(`Bearer ${' '.repeat(5_000)}`)).toThrow(AuthError);
});
});