Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
# Auth `requireApiPermission` middleware
**Package**: `@suaveplan/auth`
**Status**: PROPOSED
**Type**: feature
## Why
`@suaveplan/auth` (`packages/auth/auth/src/`) ships `validateApiKeyMiddleware` (which attaches the validated `ApiKey` to the request) and `hasPermission` (which checks whether an `ApiKey` grants a permission), but lacks a chainable `requireApiPermission(permission)` middleware that combines the two. Without it, every consumer wires the `validateApiKeyMiddleware` → `hasPermission` → 403 dance by hand, and the legacy upstream package shipped this as a first-class export. Genesis already adopted the framework-agnostic `MiddlewareFn` shape (see `packages/flow/rate-limiter/src/middleware/rate-limit-middleware/rate-limit-middleware.ts`) — porting `requireApiPermission` onto that same shape closes the parity gap with one small, well-bounded module.
Legacy reference: `packages/universal/auth/src/api-keys.ts` L487-L506 (the 19-line `requireApiPermission` export). Genesis already has the `PermissionDeniedError` class registered with `AUTH.PERMISSION_DENIED` so no new error code is required.
## What changes
### `@suaveplan/auth`
- ADDED: `requireApiPermission(permission: string, options?: ApiKeyMiddlewareOptions): MiddlewareFn` — returns a framework-agnostic middleware that:
1. Reads `req.apiKey` (must have been attached by `validateApiKeyMiddleware`).
2. If absent, calls `next(new ApiKeyInvalidError({ message: "API key required" }))` and returns.
3. If present, checks `hasPermission(apiKey, permission)`. On miss, calls `next(new PermissionDeniedError({ permission }))`.
4. On match, calls `next()` to advance the chain.
- ADDED: `requireAnyApiPermission(permissions: readonly string[], options?: ApiKeyMiddlewareOptions): MiddlewareFn` — passes if the API key holds AT LEAST one of the listed permissions. Mirrors the existing `requireAnyPermission` user-permission middleware.
- ADDED: `requireAllApiPermissions(permissions: readonly string[], options?: ApiKeyMiddlewareOptions): MiddlewareFn` — passes if the API key holds ALL listed permissions.
- ADDED: subpath export `./api-keys/require-api-permission/require-api-permission` for tree-shaking.
- MODIFIED: root `src/index.ts` re-exports the three new middleware factories alongside the existing `validateApiKeyMiddleware`.
The implementation lives at `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.ts` (new feature dir), keeping `api-keys.ts` focused on the lifecycle calls. The `MiddlewareFn` shape is the same `(req, res, next)` triple already used by `validateApiKeyMiddleware`, the JWT middlewares, and the rate-limiter middleware — compatible with Express directly and with Hono via the same thin adapter all genesis middleware uses.
## Out of scope
- **Express / Hono adapter packages** — out of scope. The framework-agnostic `MiddlewareFn` is the genesis convention; consumers wrap it for their framework. See the existing `auth-middleware.md` for the pattern.
- **Permission-tree resolution** (e.g. `user:write` implies `user:read`) — out of scope. Genesis treats permissions as flat strings with a single `*` wildcard. Hierarchical permissions are a separate change once a real consumer needs them.
- **Audit-logging on permission denial** — out of scope. The thrown `PermissionDeniedError` already carries `{ permission, userId? }` context for downstream audit log adapters; no logging here.
- **Replacing `req.apiKey` mutation pattern with a `getRequestApiKey(req)` helper** — out of scope. The `req.apiKey` mutation matches the existing `validateApiKeyMiddleware` contract; changing both is a separate refactor.
## Source mapping
This change derives from `../suaveplan/enterprise/auth.md` and the upstream `api-keys.ts` source.
| Requirement | Source file | Source lines | Notes |
|---|---|---|---|
| `requireApiPermission(permission)` | `packages/universal/auth/src/api-keys.ts` | L487-L506 | Verbatim port; replace upstream's `res.status(401).json(...)` express-only path with the genesis `next(error)` framework-agnostic path used by `validateApiKeyMiddleware` (auth.types.ts L96-L99) |
### Requirements with no source line
| Requirement | Justification |
|---|---|
| `requireAnyApiPermission(permissions)` | Symmetry with the user-permission `requireAnyPermission` middleware in `auth-middleware.ts`. Upstream had only the single-permission form; genesis adds the array form for parity with the user-permission surface. |
| `requireAllApiPermissions(permissions)` | Same symmetry argument as above. |
| Framework-agnostic `MiddlewareFn` shape (vs upstream's express-only `(req, res, next)` with `res.status(...)`) | Genesis convention: every auth middleware returns a `MiddlewareFn` and signals failure via `next(error)`, never via `res.status(...)`. See `validateApiKeyMiddleware` at `packages/auth/auth/src/api-keys/api-keys.ts` L233-L279 and `auth-middleware.ts` for the established pattern. Upstream's express-only path would break in Hono-style adapters. |
## Verification approach
Each requirement carries a `**Verified by:**` line in the spec delta.
- `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts` — covers all three middleware factories: success path, missing-`req.apiKey` path, missing-permission path, wildcard `*` path, edge cases for empty permission arrays in `requireAnyApiPermission` / `requireAllApiPermissions`
- `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.spec-conformance.test.ts` — pins `MiddlewareFn` typing (`expectTypeOf`), pins behavior under both `(req, res, next)` and Hono-style adapter shapes, OTel `auth.apikey.permission_check_total` counter emission
## Impact
### Affected dependents
Run `bunx turbo ls --filter=...@suaveplan/auth` to enumerate.
- No dependents (verified by `grep -rl "@suaveplan/auth" /home/ubuntu/web/genesis/packages/ --include="package.json"` → only `packages/auth/auth/package.json` itself).
Pure additive change — no consumer-visible behavior changes to existing exports.
## Migration impact
None — additive only. Existing `validateApiKeyMiddleware`, `hasPermission`, and the user-permission middleware (`requirePermission`, `requireAnyPermission`, `requireAllPermissions`) are unchanged. Consumers that currently chain `validateApiKeyMiddleware` → custom permission check can migrate to `requireApiPermission` at their own pace; both patterns continue to work.

View File

@@ -0,0 +1,118 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: auth (auth-require-api-permission)
**Package**: `@suaveplan/auth`
**Status**: PROPOSED
> Every requirement below carries a `**Verified by:**` line at authoring time. (See `openspec/AGENTS.md` Section 13.)
## ADDED Requirements
### Requirement: requireApiPermission middleware factory
The package SHALL expose `requireApiPermission(permission: string, options?: ApiKeyMiddlewareOptions): MiddlewareFn`. The returned middleware SHALL read `req.apiKey` (attached by `validateApiKeyMiddleware` upstream in the chain), check `hasPermission(apiKey, permission)`, and:
- Call `next()` (no arguments) when the API key holds the permission (or holds the wildcard `*`).
- Call `next(new PermissionDeniedError({ permission, userId: apiKey.userId }))` when the API key is present but lacks the permission.
- Call `next(new ApiKeyInvalidError({ message: "API key required for permission check" }))` when `req.apiKey` is absent or undefined.
The middleware SHALL be framework-agnostic — the returned function matches the genesis `MiddlewareFn` shape (compatible with both Express-style `(req, res, next)` and Hono-style `(c, next)` adapter wrappers).
#### Scenario: permission grant calls next with no args
- **WHEN** `req.apiKey = { permissions: ["user:write"], ... }` and the middleware is called for `permission = "user:write"`
- **THEN** `next` is called once with no arguments
#### Scenario: missing permission calls next with PermissionDeniedError
- **WHEN** `req.apiKey = { permissions: ["user:read"], userId: "u-1" }` and the middleware is called for `permission = "user:write"`
- **THEN** `next` is called once with a `PermissionDeniedError` whose `code === "AUTH.PERMISSION_DENIED"` AND `context.permission === "user:write"`
#### Scenario: missing req.apiKey calls next with ApiKeyInvalidError
- **WHEN** `req.apiKey` is `undefined`
- **THEN** `next` is called once with an `ApiKeyInvalidError` whose `code === "AUTH.API_KEY_INVALID"` AND `message` contains `"API key required"`
#### Scenario: wildcard permission grants any
- **WHEN** `req.apiKey = { permissions: ["*"], ... }` and the middleware is called for ANY non-empty permission
- **THEN** `next` is called once with no arguments
#### Scenario: returned middleware satisfies MiddlewareFn type
- **WHEN** `expectTypeOf(requireApiPermission("x")).toMatchTypeOf<MiddlewareFn>()` is asserted
- **THEN** the type assertion passes (`MiddlewareFn` is `(req, res, next) => void | Promise<void>`)
**Verified by:** `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"calls next with no args when permission granted"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"calls next with PermissionDeniedError when permission missing"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"calls next with ApiKeyInvalidError when req.apiKey missing"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"wildcard permission grants any"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.spec-conformance.test.ts::"return type matches MiddlewareFn"`
---
### Requirement: requireAnyApiPermission accepts a list (OR semantics)
The package SHALL expose `requireAnyApiPermission(permissions: readonly string[], options?: ApiKeyMiddlewareOptions): MiddlewareFn`. The returned middleware SHALL pass when the API key holds AT LEAST one of the listed permissions (or the wildcard `*`). On no match, it SHALL call `next(new PermissionDeniedError({ permission: permissions.join(" | "), userId }))`. An empty `permissions` array SHALL throw `ApiKeyInvalidError` with `message: "permissions array must be non-empty"` at factory-call time (not at request time).
#### Scenario: subset match grants
- **WHEN** `req.apiKey.permissions = ["user:read"]` and the middleware is called with `["user:read", "user:write"]`
- **THEN** `next` is called once with no arguments
#### Scenario: no match denies
- **WHEN** `req.apiKey.permissions = ["billing:read"]` and the middleware is called with `["user:read", "user:write"]`
- **THEN** `next` is called once with `PermissionDeniedError` whose `context.permission === "user:read | user:write"`
#### Scenario: empty array throws at factory time
- **WHEN** `requireAnyApiPermission([])` is constructed
- **THEN** it throws `ApiKeyInvalidError` synchronously (NOT lazily on request)
**Verified by:** `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"requireAnyApiPermission grants on subset match"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"requireAnyApiPermission denies on no match"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"requireAnyApiPermission throws on empty array"`
---
### Requirement: requireAllApiPermissions accepts a list (AND semantics)
The package SHALL expose `requireAllApiPermissions(permissions: readonly string[], options?: ApiKeyMiddlewareOptions): MiddlewareFn`. The returned middleware SHALL pass when the API key holds EVERY listed permission (the wildcard `*` satisfies all checks). On any miss, it SHALL call `next(new PermissionDeniedError({ permission: <first-missing>, userId }))`. An empty `permissions` array SHALL throw `ApiKeyInvalidError` at factory-call time.
#### Scenario: full match grants
- **WHEN** `req.apiKey.permissions = ["user:read", "user:write"]` and the middleware is called with `["user:read", "user:write"]`
- **THEN** `next` is called once with no arguments
#### Scenario: partial match denies on first missing
- **WHEN** `req.apiKey.permissions = ["user:read"]` and the middleware is called with `["user:read", "user:write"]`
- **THEN** `next` is called once with `PermissionDeniedError` whose `context.permission === "user:write"` (the first missing)
#### Scenario: wildcard satisfies all
- **WHEN** `req.apiKey.permissions = ["*"]` and the middleware is called with `["user:read", "user:write", "billing:read"]`
- **THEN** `next` is called once with no arguments
**Verified by:** `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"requireAllApiPermissions grants on full match"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"requireAllApiPermissions denies on partial match"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts::"requireAllApiPermissions accepts wildcard"`
---
### Requirement: Permission check emits OTel counter
The package SHALL emit `auth.apikey.permission_check_total` (counter) tagged `{ result: "granted" | "denied" | "missing-key", permission?: string }` from each call to the three middleware functions. Counter increments SHALL be observable through a real in-memory `MeterProvider`.
#### Scenario: granted check increments counter with result=granted
- **WHEN** the middleware passes (apiKey holds the permission)
- **THEN** the counter records exactly one increment with attributes `{ result: "granted" }`
#### Scenario: denied check increments counter with result=denied
- **WHEN** the middleware denies (apiKey lacks the permission)
- **THEN** the counter records exactly one increment with attributes `{ result: "denied" }`
#### Scenario: missing-key increments counter with result=missing-key
- **WHEN** `req.apiKey` is undefined
- **THEN** the counter records exactly one increment with attributes `{ result: "missing-key" }`
**Verified by:** `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.spec-conformance.test.ts::"emits granted increment on success"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.spec-conformance.test.ts::"emits denied increment on permission miss"` AND `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.spec-conformance.test.ts::"emits missing-key increment when req.apiKey absent"`
<!-- markdownlint-enable MD024 -->

View File

@@ -0,0 +1,89 @@
# Tasks — Auth `requireApiPermission` middleware
> Every checkbox MUST reflect work actually done in this change. Do not retroactively tick.
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## Audit Note (2026-05-02)
**Minimal progress** — DEFERRED, do not archive.
- No `packages/auth/auth/src/api-keys/require-api-permission/` directory exists.
- `grep -rn "requireApiPermission\|requireAnyApiPermission\|requireAllApiPermissions" packages/auth/auth/src/` returns zero hits.
- `bunx turbo lint typecheck test --filter=@suaveplan/auth` is GREEN (161 tests) — but the green is on the existing surface; the new exports promised by this proposal are not implemented.
- All 43 tasks remain to be done as written (spec authoring, three-middleware implementation, OTel counter, Zod boundary validation, sibling `.md`, README, subpath export, conformance test).
## 1. Spec authoring
- [ ] 1.1 Read `../suaveplan/enterprise/auth.md` end-to-end (confirm `requireApiPermission` is documented at L1-L100 baseline)
- [ ] 1.2 Read `openspec/specs/auth/spec.md` (canonical capability spec; this change introduces it if absent)
- [ ] 1.3 Read `openspec/AGENTS.md` Sections 13 and 14
- [ ] 1.4 Read existing `packages/auth/auth/src/api-keys/api-keys.ts` and `auth-middleware/auth-middleware.ts` to confirm the `MiddlewareFn` and `next(error)` patterns
- [ ] 1.5 Draft `proposal.md` from `openspec/templates/proposal.md`
- [ ] 1.6 Fill `## Source mapping` table with upstream `api-keys.ts` L487-L506 reference
- [ ] 1.7 Draft `specs/auth/spec.md` from `openspec/templates/spec-delta.md`
- [ ] 1.8 Every requirement carries a `**Verified by:**` line
- [ ] 1.9 `openspec change validate auth-require-api-permission` exits with no errors
## 2. Implementation
- [ ] 2.1 Create new feature directory `packages/auth/auth/src/api-keys/require-api-permission/`
- [ ] 2.2 Implement `requireApiPermission(permission, options?): MiddlewareFn` in `require-api-permission.ts`:
1. Read `req.apiKey` (cast through the same `r as Record<string, unknown>` pattern used in `validateApiKeyMiddleware`).
2. If absent, call `next(new ApiKeyInvalidError({ message: "API key required for permission check" }))` and return.
3. If present, check `hasPermission(apiKey, permission)`. On miss, call `next(new PermissionDeniedError({ permission, userId: apiKey.userId }))`.
4. On match, call `next()`.
- [ ] 2.3 Implement `requireAnyApiPermission(permissions, options?): MiddlewareFn` — passes if `permissions.some(p => hasPermission(apiKey, p))`
- [ ] 2.4 Implement `requireAllApiPermissions(permissions, options?): MiddlewareFn` — passes if `permissions.every(p => hasPermission(apiKey, p))`
- [ ] 2.5 Emit OTel counter `auth.apikey.permission_check_total` tagged `{ result: "granted" | "denied" | "missing-key" }`
- [ ] 2.6 Reject empty `permissions` array in `requireAnyApiPermission` / `requireAllApiPermissions` at construction time (throw `ApiKeyInvalidError` with `message: "permissions array must be non-empty"`)
- [ ] 2.7 Write barrel `index.ts` re-exporting the three middleware factories
- [ ] 2.8 Sibling `.md` (≥200 words, basic + advanced examples)
## 3. Wiring
- [ ] 3.1 Update `packages/auth/auth/src/index.ts` to re-export `requireApiPermission`, `requireAnyApiPermission`, `requireAllApiPermissions` from the new feature directory
- [ ] 3.2 Add subpath export `./api-keys/require-api-permission/require-api-permission` to `packages/auth/auth/package.json` `exports`
- [ ] 3.3 Update root `README.md` `## Modules` section to link the new co-located `.md`
## 4. Tests
- [ ] 4.1 `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.test.ts` — happy path (apiKey has permission, `next()` called with no args); missing `req.apiKey` (`next(ApiKeyInvalidError)`); missing permission (`next(PermissionDeniedError)`); wildcard `*` permission grants any (`next()` called with no args)
- [ ] 4.2 `requireAnyApiPermission` tests — passes with subset match; fails when none match; throws on empty array
- [ ] 4.3 `requireAllApiPermissions` tests — passes when all match (including via wildcard); fails on partial match; throws on empty array
- [ ] 4.4 `packages/auth/auth/src/api-keys/require-api-permission/require-api-permission.spec-conformance.test.ts` — `expectTypeOf<ReturnType<typeof requireApiPermission>>().toMatchTypeOf<MiddlewareFn>()`; OTel counter `auth.apikey.permission_check_total` increments with the right `result` tag for each branch; works under Express-style `(req, res, next)` AND Hono-style `(c, next)` adapter shapes
- [ ] 4.5 Every `it(...)` carries `{ timeout: 5000 }`
## 5. Documentation
- [ ] 5.1 Sibling `.md` for `require-api-permission.ts` (≥200 words, basic + advanced examples, full API reference covering all three factories)
- [ ] 5.2 README links the new `.md` under `## Modules`
- [ ] 5.3 Update `api-keys.md` `## Features` bullet list to mention the new permission-check middleware (cross-link, do not duplicate the API reference)
## 6. Pre-archive verification (the 5-gate triple)
- [ ] 6.1 `bun run check` — Biome 0/0/0 across the monorepo
- [ ] 6.2 `bunx turbo lint typecheck test --filter=@suaveplan/auth` — green
- [ ] 6.3 `bunx turbo test:coverage --filter=@suaveplan/auth` — 100/100/100/100
- [ ] 6.4 `bun scripts/openspec-conformance.ts @suaveplan/auth` — exit 0, no `error` findings
- [ ] 6.5 `bunx turbo build --filter=@suaveplan/auth` — green
## 7. Pre-archive 7-row checklist (AGENTS.md Section 13)
- [ ] 7.1 Generics threaded; `expectTypeOf` assertion that the return type matches `MiddlewareFn`
- [ ] 7.2 Zod schemas wired at the public boundary — accept `permission: string` validated as non-empty
- [ ] 7.3 Existing error codes (`AUTH.API_KEY_INVALID`, `AUTH.PERMISSION_DENIED`) thrown from the new production paths; no new codes registered (none needed)
- [ ] 7.4 Strict-mode tested: explicit `undefined` apiKey vs missing apiKey property both route to `ApiKeyInvalidError`
- [ ] 7.5 OTel counter `auth.apikey.permission_check_total` emitted from production paths and asserted with a real in-memory `MeterProvider`
- [ ] 7.6 Lifecycle dedup: middleware is a fresh closure per call to the factory; verified that two factory calls produce independent `MiddlewareFn` instances
- [ ] 7.7 No retroactive tick — every box reflects work done in this change
## 8. Archive
- [ ] 8.1 Fold spec delta into `openspec/specs/auth/spec.md` (creating it if absent)
- [ ] 8.2 Move `openspec/changes/auth-require-api-permission/` → `openspec/archive/<yyyy-mm-dd>-auth-require-api-permission/`
- [ ] 8.3 Refresh `MANIFEST.md` (no package set or dep changes expected, but rerun for safety)