fix: enforce explicit grant invariants

Explicit-grant management could produce states an operator could not reason
about, and pushed request-shaped problems into the database.

Two identical createGrant calls produced two grants; five concurrent identical
calls produced five. Revoking one returned success while the equivalent kept
authorizing the same user — an operator could believe they had removed access
that was still live. Two issuances are now the same authorization source when
user_id, permission_id, scope, source_kind, and source_ref are all equal, with
NULL equal only to NULL; expiry, creation metadata, actor, and grant id do not
distinguish them. Creating one while an equivalent is currently effective fails
with AUTHORIZATION_GRANT_ALREADY_EXISTS (HTTP 409, no-store) naming nothing about
the grant that already exists, and writing no grant and no audit row. A revoked
or expired equivalent does not block a fresh issuance. Conflict rather than
idempotent return: the caller asked to record a new authorization with their own
actor and expiry, and answering "done" while recording neither would hide that
nothing happened.

Enforcement is database-backed, since nothing constrains the number of API
processes: every create and revoke touching one equivalence tuple takes a
transaction-scoped advisory lock keyed by a hash of that tuple, encoded as a JSON
array so NULL stays distinct from the empty string and a crafted scope cannot
forge a separator. A collision can only make unrelated tuples serialize, never
hide a conflict, because the decision is always an exact SQL predicate. Its
single-key lock space is verified disjoint from the two-key space the migration
runner and bootstrap use. A time-dependent partial unique index was rejected:
now() is not immutable and cannot be indexed.

One revocation now clears every unrevoked equivalent — including expired-but-
unrevoked legacy rows, so the history is left in one state — with one audit row
per grant actually revoked, each carrying its own id, in one transaction.
Differently scoped or sourced grants are untouched. Historical duplicates are not
silently revoked by migration; the store prevents new effective equivalents and
an operator's explicit revocation resolves the class.

The request boundary no longer leaks into PostgreSQL. GrantId accepts exactly the
canonical lowercase hyphenated UUID the database emits, with no trimming and no
case folding, so a malformed path parameter is a 400 decided after authorization
but before any store call instead of reaching the UUID comparison and returning
an indistinguishable 503; a canonical unknown id still returns 404. expiresAt
accepts exactly YYYY-MM-DDTHH:mm:ss.sssZ, byte-for-byte equal to the parsed
date's own toISOString, and must be strictly future — bare new Date silently
rewrote 2026-02-31 to March 3rd and accepted locale, date-only, offset, and
millisecond-free forms, and a past expiry was stored as a grant dead on arrival.
The store validates the same thing before any SQL so trusted internal callers get
the guarantee too.

The generic HTTP surface now rejects a scope field in every form, including null.
No route middleware supplies a scope to the evaluator, so a scope accepted here
produced a grant that persisted, listed, and authorized nothing. Core's scope
semantics are unchanged for internal callers; no resolver was added.

Listing was unbounded and returned a user's entire history. It is now keyset
pagination over created_at DESC, id DESC with a strict boundary on both values,
so rows sharing a timestamp are neither skipped nor repeated, at most limit + 1
rows read, explicit-source filtering server-side on every page, and an opaque
unsigned position cursor that is strictly decoded and reveals nothing on
rejection. Core's list method requires a validated finite bound with no
unbounded fallback anywhere.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
ekklesia
2026-07-26 21:56:32 -05:00
co-authored by Claude Opus 5
parent 532ce3803b
commit 5c589d8fec
15 changed files with 2177 additions and 107 deletions
+220 -35
View File
@@ -1,16 +1,17 @@
import type { AuthorizationScope, EkklesiaUserId, PermissionId } from "@ekklesia/contracts";
import type { EkklesiaUserId, GrantId, PermissionId } from "@ekklesia/contracts";
import {
createUserActor,
isAuthenticatedPrincipal,
safeParseAuthorizationScope,
safeParseEkklesiaUserId,
safeParseGrantId,
safeParsePermissionId,
} from "@ekklesia/contracts";
import {
AUTHORIZATION_GRANT_LIST_MAX_LIMIT,
type AuthorizationStore,
AuthorizationStoreError,
CORE_AUTHORIZATION_GRANTS_MANAGE,
type GrantPageBoundary,
type GrantRecord,
} from "@ekklesia/core/authorization";
import { Hono } from "hono";
@@ -26,13 +27,36 @@ import { CORE_MUTATION_MAX_BODY_BYTES, platformBodyLimit } from "./body-limits.j
export interface CreateGrantsRoutesOptions extends AuthorizationMiddlewareOptions {
readonly store: AuthorizationStore;
readonly trustedOrigins: ReadonlySet<string>;
/** Injected only so expiration validation is deterministic under test. Production composition
* leaves this unset and the routes read real time. */
readonly now?: () => Date;
}
const DEFAULT_LIST_LIMIT = 50;
function sanitizedStoreErrorResponse(c: Context, error: unknown): Response {
c.header("Cache-Control", "no-store");
if (error instanceof AuthorizationStoreError) {
const status = error.code === "AUTHORIZATION_GRANT_NOT_FOUND" ? 404 : 503;
return c.json({ code: error.code }, status);
if (error.code === "AUTHORIZATION_GRANT_NOT_FOUND") {
return c.json({ code: error.code }, 404);
}
// The one conflict the caller can act on. It deliberately reveals nothing about the grant that
// already exists — not its id, actor, scope, source reference, or expiry — only that an
// equivalent authorization is already effective for this subject.
if (error.code === "AUTHORIZATION_GRANT_ALREADY_EXISTS") {
return c.json({ code: error.code }, 409);
}
// Defense in depth: the routes below reject both of these before ever reaching the store, so
// arriving here means a request-shaped problem slipped through. It is still a client input
// failure, never an infrastructure one, and it reports exactly like any other malformed
// request rather than leaking the store's internal distinction.
if (
error.code === "AUTHORIZATION_GRANT_EXPIRATION_INVALID" ||
error.code === "AUTHORIZATION_GRANT_LIMIT_INVALID"
) {
return c.json({ code: "INVALID_REQUEST" }, 400);
}
return c.json({ code: error.code }, 503);
}
return c.json({ code: "INTERNAL_ERROR" }, 503);
}
@@ -40,20 +64,55 @@ function sanitizedStoreErrorResponse(c: Context, error: unknown): Response {
interface ParsedCreateGrantBody {
readonly expiresAt?: Date;
readonly permission: PermissionId;
readonly scope?: AuthorizationScope;
readonly subjectUserId: EkklesiaUserId;
}
const CREATE_GRANT_ALLOWED_KEYS = new Set(["subjectUserId", "permission", "scope", "expiresAt"]);
const CREATE_GRANT_ALLOWED_KEYS = new Set(["subjectUserId", "permission", "expiresAt"]);
/**
* Accepts only `subjectUserId`, `permission`, an optional `scope`, and an optional `expiresAt`.
* Any other key present — `actor`, `sourceKind`, `sourceRef`, any audit field, `createdAt`,
* `revokedAt`, a grant id, or anything claiming owner/effective-permission state — makes the
* whole body invalid rather than being silently dropped, so a caller cannot smuggle
* server-derived fields through a request that otherwise looks well-formed.
* The one accepted expiration representation: `YYYY-MM-DDTHH:mm:ss.sssZ`, byte-for-byte equal to
* the parsed `Date`'s own `toISOString()`.
*
* `new Date(value)` alone was far too permissive. It silently *normalized* impossible dates
* (`2026-02-31T00:00:00.000Z` became March 3rd) and accepted locale-shaped input
* (`"March 5, 2027"`), date-only values, offsets, and missing milliseconds — so what an operator
* typed and what the platform stored could differ without any error. The regular expression pins
* the lexical form and the round-trip comparison rejects every value the parser would otherwise
* quietly rewrite.
*/
function parseCreateGrantBody(raw: unknown): ParsedCreateGrantBody | undefined {
const CANONICAL_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
function parseCanonicalFutureInstant(value: unknown, now: Date): Date | undefined {
if (typeof value !== "string" || !CANONICAL_INSTANT_PATTERN.test(value)) {
return undefined;
}
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) {
return undefined;
}
// Strictly future: an expiration equal to or before the acceptance clock produces a grant that
// is already dead, which is never what the caller meant.
if (parsed.getTime() <= now.getTime()) {
return undefined;
}
return parsed;
}
/**
* Accepts only `subjectUserId`, `permission`, and an optional `expiresAt`. Any other key present —
* `actor`, `sourceKind`, `sourceRef`, any audit field, `createdAt`, `revokedAt`, a grant id, or
* anything claiming owner/effective-permission state — makes the whole body invalid rather than
* being silently dropped, so a caller cannot smuggle server-derived fields through a request that
* otherwise looks well-formed.
*
* **`scope` is deliberately among the rejected keys**, including when supplied as `null`, empty, or
* an otherwise valid scope string. Core's scoped-grant semantics remain intact for trusted internal
* callers, but no HTTP route middleware supplies a scope to the evaluator today, so a scope
* accepted here would produce a grant that looks meaningful, persists, appears in listings, and can
* authorize nothing at all. Accepting it would be offering a switch that is not connected to
* anything. When a server-owned resolver exists, this is the one place that changes.
*/
function parseCreateGrantBody(raw: unknown, now: Date): ParsedCreateGrantBody | undefined {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return undefined;
}
@@ -71,31 +130,138 @@ function parseCreateGrantBody(raw: unknown): ParsedCreateGrantBody | undefined {
return undefined;
}
let scope: AuthorizationScope | undefined;
if (body.scope !== undefined) {
const parsedScope = safeParseAuthorizationScope(body.scope);
if (!parsedScope.success) {
return undefined;
}
scope = parsedScope.data;
}
let expiresAt: Date | undefined;
if (body.expiresAt !== undefined) {
if (typeof body.expiresAt !== "string") {
expiresAt = parseCanonicalFutureInstant(body.expiresAt, now);
if (expiresAt === undefined) {
return undefined;
}
const parsedDate = new Date(body.expiresAt);
if (Number.isNaN(parsedDate.getTime())) {
return undefined;
}
expiresAt = parsedDate;
}
return Object.freeze({
...(expiresAt === undefined ? {} : { expiresAt }),
permission: permission.data,
...(scope === undefined ? {} : { scope }),
subjectUserId: subjectUserId.data,
});
}
const CURSOR_VERSION = 1;
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
/**
* An opaque pagination *position*, not an authorization token. It carries only the subject user id,
* the boundary row's creation instant, and the boundary grant id — never a permission, scope,
* source reference, actor, credential, or secret — so there is nothing in it worth protecting.
*
* It is deliberately unsigned. Signing would imply the cursor carries authority it does not have:
* the permission check and the server-side subject filter remain authoritative on every page, and
* a forged cursor can at most name a different position within grants the caller is already
* entitled to list. The strict decode below still refuses anything that is not exactly what this
* function would emit.
*/
function encodeCursor(userId: EkklesiaUserId, boundary: GrantPageBoundary): string {
return Buffer.from(
JSON.stringify({
g: boundary.id,
t: boundary.createdAt.toISOString(),
u: userId,
v: CURSOR_VERSION,
}),
"utf8",
).toString("base64url");
}
/**
* Strict in every dimension: canonical unpadded base64url, valid UTF-8 JSON, an object with exactly
* the four expected keys, the exact version, a subject matching the *requested* one, a canonical
* `toISOString()` timestamp, a canonical `GrantId`, and — the catch-all — a re-encoding that
* reproduces the supplied string byte-for-byte, which rejects padding, trailing data, and any
* alternative encoding of the same payload. A rejected cursor reveals nothing it decoded.
*/
function decodeCursor(raw: string, userId: EkklesiaUserId): GrantPageBoundary | undefined {
if (!BASE64URL_PATTERN.test(raw)) {
return undefined;
}
let parsed: unknown;
try {
parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
} catch {
return undefined;
}
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
return undefined;
}
const payload = parsed as Record<string, unknown>;
if (Object.keys(payload).sort().join(",") !== "g,t,u,v") {
return undefined;
}
if (payload.v !== CURSOR_VERSION || payload.u !== userId || typeof payload.t !== "string") {
return undefined;
}
const createdAt = new Date(payload.t);
if (Number.isNaN(createdAt.getTime()) || createdAt.toISOString() !== payload.t) {
return undefined;
}
const id = safeParseGrantId(payload.g);
if (!id.success) {
return undefined;
}
const boundary: GrantPageBoundary = Object.freeze({ createdAt, id: id.data });
if (encodeCursor(userId, boundary) !== raw) {
return undefined;
}
return boundary;
}
const LIST_ALLOWED_QUERY_KEYS = new Set(["userId", "limit", "cursor"]);
/** Canonical base-10, no sign, no leading zero, no decimal point, no whitespace, no exponent. */
const CANONICAL_POSITIVE_INTEGER_PATTERN = /^[1-9][0-9]*$/u;
interface ParsedListQuery {
readonly after?: GrantPageBoundary;
readonly limit: number;
readonly subjectUserId: EkklesiaUserId;
}
/** Fully validated before any store or database work happens, so an invalid page request never
* becomes a query, and never becomes a way to probe which subjects or grants exist. */
function parseListQuery(url: string): ParsedListQuery | undefined {
const searchParams = new URL(url).searchParams;
for (const key of searchParams.keys()) {
if (!LIST_ALLOWED_QUERY_KEYS.has(key) || searchParams.getAll(key).length > 1) {
return undefined;
}
}
const subjectUserId = safeParseEkklesiaUserId(searchParams.get("userId"));
if (!subjectUserId.success) {
return undefined;
}
let limit = DEFAULT_LIST_LIMIT;
const rawLimit = searchParams.get("limit");
if (rawLimit !== null) {
if (!CANONICAL_POSITIVE_INTEGER_PATTERN.test(rawLimit)) {
return undefined;
}
limit = Number(rawLimit);
if (!Number.isSafeInteger(limit) || limit < 1 || limit > AUTHORIZATION_GRANT_LIST_MAX_LIMIT) {
return undefined;
}
}
let after: GrantPageBoundary | undefined;
const rawCursor = searchParams.get("cursor");
if (rawCursor !== null) {
after = decodeCursor(rawCursor, subjectUserId.data);
if (after === undefined) {
return undefined;
}
}
return Object.freeze({
...(after === undefined ? {} : { after }),
limit,
subjectUserId: subjectUserId.data,
});
}
@@ -125,9 +291,12 @@ function serializeGrant(grant: GrantRecord) {
* `sourceKind` at all), and revocation is constrained to `sourceKind: "explicit"`, so attempting
* to revoke a relationship-derived grant by id behaves exactly like the grant does not exist —
* those grants remain owned by the module operation that established the relationship.
*
* Creation is unscoped-only; see `parseCreateGrantBody`.
*/
export function createGrantsRoutes(options: CreateGrantsRoutesOptions): Hono {
const routes = new Hono();
const now = options.now ?? ((): Date => new Date());
const requireManagePermission = requirePermission(options, CORE_AUTHORIZATION_GRANTS_MANAGE);
const requireOrigin = requireTrustedOrigin(options.trustedOrigins);
// Origin is checked first (a rejected cross-origin mutation must never have its body read), then
@@ -137,15 +306,29 @@ export function createGrantsRoutes(options: CreateGrantsRoutesOptions): Hono {
routes.get("/api/v1/grants", requireManagePermission, async (c) => {
c.header("Cache-Control", "no-store");
const subjectUserId = safeParseEkklesiaUserId(c.req.query("userId"));
if (!subjectUserId.success) {
// Reached only after `requireManagePermission` allowed the caller, so query validation can
// never disclose a validation distinction — or the existence of any subject or grant — to an
// unauthorized caller.
const query = parseListQuery(c.req.url);
if (!query) {
return c.json({ code: "INVALID_REQUEST" }, 400);
}
try {
const grants = await options.store.listGrantsForUser(subjectUserId.data, {
const page = await options.store.listGrantsForUser(query.subjectUserId, {
...(query.after === undefined ? {} : { after: query.after }),
limit: query.limit,
sourceKind: "explicit",
});
return c.json({ grants: grants.map(serializeGrant) }, 200);
return c.json(
{
grants: page.grants.map(serializeGrant),
nextCursor:
page.nextBoundary === undefined
? null
: encodeCursor(query.subjectUserId, page.nextBoundary),
},
200,
);
} catch (error) {
return sanitizedStoreErrorResponse(c, error);
}
@@ -169,7 +352,7 @@ export function createGrantsRoutes(options: CreateGrantsRoutesOptions): Hono {
} catch {
return c.json({ code: "INVALID_REQUEST" }, 400);
}
const parsed = parseCreateGrantBody(rawBody);
const parsed = parseCreateGrantBody(rawBody, now());
if (!parsed) {
return c.json({ code: "INVALID_REQUEST" }, 400);
}
@@ -189,7 +372,6 @@ export function createGrantsRoutes(options: CreateGrantsRoutesOptions): Hono {
actor: createUserActor(principal.userId),
...(parsed.expiresAt === undefined ? {} : { expiresAt: parsed.expiresAt }),
permission: parsed.permission,
...(parsed.scope === undefined ? {} : { scope: parsed.scope }),
sourceKind: "explicit",
userId: parsed.subjectUserId,
});
@@ -212,6 +394,9 @@ export function createGrantsRoutes(options: CreateGrantsRoutesOptions): Hono {
return c.json({ code: "AUTHORIZATION_DENIED" }, 403);
}
// Canonical-UUID validation happens after authorization but strictly before any store or
// database call: a malformed id previously reached PostgreSQL's own UUID comparison and came
// back as an indistinguishable infrastructure failure (503) rather than a request problem.
const grantId = safeParseGrantId(c.req.param("grantId"));
if (!grantId.success) {
return c.json({ code: "INVALID_REQUEST" }, 400);
@@ -220,7 +405,7 @@ export function createGrantsRoutes(options: CreateGrantsRoutesOptions): Hono {
try {
await options.store.revokeGrant({
actor: createUserActor(principal.userId),
grantId: grantId.data,
grantId: grantId.data satisfies GrantId,
sourceKind: "explicit",
});
return c.json({ success: true }, 200);