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
+379 -12
View File
@@ -1,6 +1,5 @@
import {
createAuthenticatedPrincipal,
parseAuthorizationScope,
parseEkklesiaUserId,
parseGrantId,
parsePermissionId,
@@ -50,7 +49,7 @@ function fakeStore(overrides: Partial<AuthorizationStore> = {}): AuthorizationSt
grantPlatformOwner: vi.fn(),
hasActiveGrant: vi.fn().mockResolvedValue(false),
isPlatformOwner: vi.fn().mockResolvedValue(false),
listGrantsForUser: vi.fn().mockResolvedValue([]),
listGrantsForUser: vi.fn().mockResolvedValue({ grants: [] }),
revokeGrant: vi.fn(),
revokePlatformOwner: vi.fn(),
...overrides,
@@ -59,6 +58,7 @@ function fakeStore(overrides: Partial<AuthorizationStore> = {}): AuthorizationSt
function buildApp(options: {
readonly allowed?: boolean;
readonly now?: () => Date;
readonly runtime?: EkklesiaIdentityRuntime;
readonly store?: AuthorizationStore;
}) {
@@ -72,6 +72,7 @@ function buildApp(options: {
"/",
createGrantsRoutes({
evaluator,
...(options.now === undefined ? {} : { now: options.now }),
registry: CORE_PERMISSION_REGISTRY,
runtime,
store,
@@ -103,15 +104,20 @@ describe("GET /api/v1/grants", () => {
userId: subjectUserId,
},
];
const store = fakeStore({ listGrantsForUser: vi.fn().mockResolvedValue(grants) });
const store = fakeStore({ listGrantsForUser: vi.fn().mockResolvedValue({ grants }) });
const { app } = buildApp({ store });
const response = await app.request(`/api/v1/grants?userId=${subjectUserId}`);
const body = (await response.json()) as { grants: unknown[] };
const body = (await response.json()) as { grants: unknown[]; nextCursor: string | null };
expect(response.status).toBe(200);
expect(body.grants).toHaveLength(1);
expect(store.listGrantsForUser).toHaveBeenCalledWith(subjectUserId, { sourceKind: "explicit" });
expect(body.nextCursor).toBeNull();
// The default page size is applied server-side; `sourceKind` filtering stays server-side too.
expect(store.listGrantsForUser).toHaveBeenCalledWith(subjectUserId, {
limit: 50,
sourceKind: "explicit",
});
});
it("rejects a missing or malformed userId query parameter", async () => {
@@ -184,7 +190,6 @@ describe("POST /api/v1/grants", () => {
createdAt: new Date("2026-01-01T00:00:00.000Z"),
id: grantId,
permission: registeredPermission,
scope: parseAuthorizationScope("calendar-event:123"),
sourceKind: "explicit" as const,
userId: subjectUserId,
};
@@ -192,11 +197,7 @@ describe("POST /api/v1/grants", () => {
const { app } = buildApp({ store });
const response = await app.request("/api/v1/grants", {
body: JSON.stringify({
permission: registeredPermission,
scope: "calendar-event:123",
subjectUserId,
}),
body: JSON.stringify({ permission: registeredPermission, subjectUserId }),
headers: { "content-type": "application/json", origin: trustedOrigin },
method: "POST",
});
@@ -208,11 +209,14 @@ describe("POST /api/v1/grants", () => {
expect.objectContaining({
actor: { type: "user", userId: manager.userId },
permission: registeredPermission,
scope: "calendar-event:123",
sourceKind: "explicit",
userId: subjectUserId,
}),
);
// The generic HTTP surface creates unscoped explicit grants only.
expect(store.createGrant).toHaveBeenCalledWith(
expect.not.objectContaining({ scope: expect.anything() }),
);
});
it("rejects a well-formed but unregistered permission with the same sanitized denial as an unauthorized caller, and never calls the store", async () => {
@@ -512,3 +516,366 @@ describe("Core grant mutation request body limit", () => {
expect(store.revokeGrant).not.toHaveBeenCalled();
});
});
/**
* Pass 3 request-contract regressions. Every case here asserts both the sanitized public response
* *and* that the store was never reached, because the point of each fix is that a malformed or
* unsupported request is decided at the request boundary rather than turning into database work or
* an indistinguishable infrastructure failure.
*/
describe("explicit-grant request invariants", () => {
const validExpiry = "2099-01-01T00:00:00.000Z";
async function post(app: Hono, body: unknown) {
return await app.request("/api/v1/grants", {
body: JSON.stringify(body),
headers: { "content-type": "application/json", origin: trustedOrigin },
method: "POST",
});
}
it("rejects a scope field in any form, before any store mutation", async () => {
// Core keeps scoped-grant semantics for trusted internal callers, but no HTTP middleware
// supplies a scope to the evaluator, so a scope accepted here could never authorize anything.
for (const scope of ["calendar-event:123", "", " ", null, 42, {}, []]) {
const { app, store } = buildApp({});
const response = await post(app, { permission: registeredPermission, scope, subjectUserId });
expect(response.status, `scope ${JSON.stringify(scope)}`).toBe(400);
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
expect(response.headers.get("cache-control")).toBe("no-store");
expect(store.createGrant).not.toHaveBeenCalled();
}
});
it("accepts exactly one canonical expiration representation", async () => {
const createdGrant = {
createdAt: new Date("2026-01-01T00:00:00.000Z"),
expiresAt: new Date(validExpiry),
id: grantId,
permission: registeredPermission,
sourceKind: "explicit" as const,
userId: subjectUserId,
};
const store = fakeStore({ createGrant: vi.fn().mockResolvedValue(createdGrant) });
const { app } = buildApp({ store });
const response = await post(app, {
expiresAt: validExpiry,
permission: registeredPermission,
subjectUserId,
});
expect(response.status).toBe(201);
expect(store.createGrant).toHaveBeenCalledWith(
expect.objectContaining({ expiresAt: new Date(validExpiry) }),
);
});
it("rejects normalized-impossible, locale, offset, imprecise, padded, and past expirations", async () => {
const now = new Date("2026-07-26T12:00:00.000Z");
for (const expiresAt of [
// Normalized impossible date: `new Date` silently rewrote this to March 3rd.
"2026-02-31T00:00:00.000Z",
"2026-13-01T00:00:00.000Z",
// Locale-shaped and date-only forms.
"March 5, 2027",
"2027-01-01",
// Missing milliseconds, excess fractional precision, offsets, lowercase separators.
"2027-01-01T00:00:00Z",
"2027-01-01T00:00:00.123456Z",
"2027-01-01T00:00:00.000+02:00",
"2027-01-01t00:00:00.000z",
"2027-01-01T00:00:00.000+00:00",
// Whitespace padding and trailing text.
" 2027-01-01T00:00:00.000Z",
"2027-01-01T00:00:00.000Z ",
"2027-01-01T00:00:00.000Z extra",
// Past and exactly-now are both dead on arrival.
"2020-01-01T00:00:00.000Z",
"2026-07-26T12:00:00.000Z",
// Non-strings.
42,
null,
true,
]) {
const { app, store } = buildApp({ now: () => now });
const response = await post(app, {
expiresAt,
permission: registeredPermission,
subjectUserId,
});
expect(response.status, `expiresAt ${JSON.stringify(expiresAt)}`).toBe(400);
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
expect(store.createGrant).not.toHaveBeenCalled();
}
});
it("returns a sanitized 409 for an equivalent grant that is already effective", async () => {
const store = fakeStore({
createGrant: vi
.fn()
.mockRejectedValue(new AuthorizationStoreError("AUTHORIZATION_GRANT_ALREADY_EXISTS")),
});
const { app } = buildApp({ store });
const response = await post(app, { permission: registeredPermission, subjectUserId });
const raw = await response.text();
expect(response.status).toBe(409);
expect(JSON.parse(raw)).toEqual({ code: "AUTHORIZATION_GRANT_ALREADY_EXISTS" });
expect(response.headers.get("cache-control")).toBe("no-store");
// The body is the stable code and nothing else — no existing grant id, actor, scope, source
// reference, expiry, SQL, constraint name, or driver text.
expect(Object.keys(JSON.parse(raw))).toEqual(["code"]);
for (const leaked of [
grantId,
manager.userId,
subjectUserId,
"calendar-event",
"constraint",
"select ",
"insert ",
"ekklesia_core_grant",
"Error",
"at ",
]) {
expect(raw, `must not leak ${leaked}`).not.toContain(leaked);
}
});
it("rejects a non-canonical grant id on revoke without ever calling the store", async () => {
for (const raw of [
"not-a-uuid",
"0B36B1B6-9A29-4C4E-9E2D-4C0E4C5E6F70",
"%200b36b1b6-9a29-4c4e-9e2d-4c0e4c5e6f70",
"0b36b1b6-9a29-4c4e-9e2d-4c0e4c5e6f7",
"0b36b1b6-9a29-4c4e-9e2d-4c0e4c5e6f700",
"0b36b1b69a294c4e9e2d4c0e4c5e6f70",
]) {
const { app, store } = buildApp({});
const response = await app.request(`/api/v1/grants/${raw}/revoke`, {
headers: { origin: trustedOrigin },
method: "POST",
});
expect(response.status, `grantId ${raw}`).toBe(400);
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
expect(response.headers.get("cache-control")).toBe("no-store");
expect(store.revokeGrant).not.toHaveBeenCalled();
}
});
it("still returns the sanitized 404 for a canonical but unknown grant id", async () => {
const store = fakeStore({
revokeGrant: vi
.fn()
.mockRejectedValue(new AuthorizationStoreError("AUTHORIZATION_GRANT_NOT_FOUND")),
});
const { app } = buildApp({ store });
const response = await app.request(`/api/v1/grants/${grantId}/revoke`, {
headers: { origin: trustedOrigin },
method: "POST",
});
expect(response.status).toBe(404);
expect(await response.json()).toEqual({ code: "AUTHORIZATION_GRANT_NOT_FOUND" });
expect(store.revokeGrant).toHaveBeenCalled();
});
});
describe("explicit-grant listing pagination", () => {
function grantAt(index: number, iso: string) {
return {
createdAt: new Date(iso),
id: parseGrantId(`00000000-0000-4000-8000-${String(index).padStart(12, "0")}`),
permission: registeredPermission,
sourceKind: "explicit" as const,
userId: subjectUserId,
};
}
it("applies the default limit of 50 and accepts the 1 and 100 boundaries", async () => {
for (const [query, expected] of [
["", 50],
["&limit=1", 1],
["&limit=50", 50],
["&limit=100", 100],
] as const) {
const { app, store } = buildApp({});
const response = await app.request(`/api/v1/grants?userId=${subjectUserId}${query}`);
expect(response.status, query).toBe(200);
expect(store.listGrantsForUser).toHaveBeenCalledWith(subjectUserId, {
limit: expected,
sourceKind: "explicit",
});
}
});
it("rejects every non-canonical or out-of-range limit before any store work", async () => {
for (const limit of [
"0",
"101",
"-1",
"+5",
"1.0",
"1.5",
"01",
"005",
" 5",
"5 ",
"1e2",
"",
"abc",
"0x10",
"Infinity",
"NaN",
]) {
const { app, store } = buildApp({});
const response = await app.request(
`/api/v1/grants?userId=${subjectUserId}&limit=${encodeURIComponent(limit)}`,
);
expect(response.status, `limit ${JSON.stringify(limit)}`).toBe(400);
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
expect(response.headers.get("cache-control")).toBe("no-store");
expect(store.listGrantsForUser).not.toHaveBeenCalled();
}
});
it("rejects unknown and duplicated query keys", async () => {
for (const query of [
`userId=${subjectUserId}&sort=asc`,
`userId=${subjectUserId}&offset=10`,
`userId=${subjectUserId}&sourceKind=relationship`,
`userId=${subjectUserId}&userId=${subjectUserId}`,
`userId=${subjectUserId}&limit=5&limit=6`,
`userId=${subjectUserId}&cursor=a&cursor=b`,
`userId=${subjectUserId}&cursor=`,
]) {
const { app, store } = buildApp({});
const response = await app.request(`/api/v1/grants?${query}`);
expect(response.status, query).toBe(400);
expect(store.listGrantsForUser).not.toHaveBeenCalled();
}
});
it("emits a cursor only when another page exists, and traverses without duplicates or omissions", async () => {
// Three rows sharing one `created_at`, which is exactly the case a timestamp-only keyset
// boundary would skip or repeat.
const sameInstant = "2026-01-01T00:00:00.000Z";
const all = [grantAt(3, sameInstant), grantAt(2, sameInstant), grantAt(1, sameInstant)];
const seen: string[] = [];
let cursor: string | null = null;
let pages = 0;
do {
const store = fakeStore({
listGrantsForUser: vi.fn().mockImplementation((_userId, listOptions) => {
const startIndex =
listOptions.after === undefined
? 0
: all.findIndex((grant) => grant.id === listOptions.after.id) + 1;
const slice = all.slice(startIndex, startIndex + listOptions.limit);
const more = startIndex + listOptions.limit < all.length;
const last = slice.at(-1);
return Promise.resolve({
grants: slice,
...(more && last ? { nextBoundary: { createdAt: last.createdAt, id: last.id } } : {}),
});
}),
});
const { app } = buildApp({ store });
const url: string = `/api/v1/grants?userId=${subjectUserId}&limit=1${
cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`
}`;
const response = await app.request(url);
const body = (await response.json()) as {
grants: { id: string }[];
nextCursor: string | null;
};
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(body.grants).toHaveLength(1);
seen.push(body.grants[0]?.id as string);
cursor = body.nextCursor;
pages += 1;
} while (cursor !== null && pages < 10);
expect(pages).toBe(3);
expect(seen).toEqual(all.map((grant) => grant.id));
expect(new Set(seen).size).toBe(3);
// The final page ends the traversal explicitly.
expect(cursor).toBeNull();
});
it("refuses a cursor issued for a different subject, and every malformed encoding", async () => {
const boundary = { createdAt: new Date("2026-01-01T00:00:00.000Z"), id: grantId };
const store = fakeStore({
listGrantsForUser: vi.fn().mockResolvedValue({
grants: [grantAt(1, boundary.createdAt.toISOString())],
nextBoundary: boundary,
}),
});
const { app: issuingApp } = buildApp({ store });
const issued = (await (
await issuingApp.request(`/api/v1/grants?userId=${subjectUserId}&limit=1`)
).json()) as { nextCursor: string };
expect(issued.nextCursor).toMatch(/^[A-Za-z0-9_-]+$/u);
const encode = (payload: unknown) =>
Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
const canonical = {
g: grantId,
t: "2026-01-01T00:00:00.000Z",
u: subjectUserId,
v: 1,
};
for (const [label, cursor] of [
// A cursor minted for a different subject must not be replayable against this one.
["other subject", encode({ ...canonical, u: "someone_else_1" })],
["wrong version", encode({ ...canonical, v: 2 })],
["extra field", encode({ ...canonical, extra: "x" })],
["missing field", encode({ g: canonical.g, t: canonical.t, u: canonical.u })],
["invalid timestamp", encode({ ...canonical, t: "2026-01-01" })],
["non-canonical timestamp", encode({ ...canonical, t: "2026-01-01T00:00:00Z" })],
["invalid grant id", encode({ ...canonical, g: "not-a-uuid" })],
["array payload", encode([canonical])],
["not json", Buffer.from("nonsense", "utf8").toString("base64url")],
["padded base64", `${Buffer.from(JSON.stringify(canonical), "utf8").toString("base64")}`],
["malformed base64url", "!!!not-base64!!!"],
["trailing data", `${encode(canonical)}AA`],
] as const) {
const { app, store: pagedStore } = buildApp({});
const response = await app.request(
`/api/v1/grants?userId=${subjectUserId}&cursor=${encodeURIComponent(cursor)}`,
);
const raw = await response.text();
expect(response.status, label).toBe(400);
expect(JSON.parse(raw)).toEqual({ code: "INVALID_REQUEST" });
// A rejected cursor reveals nothing it decoded, and does zero store/database work.
expect(raw).not.toContain(grantId);
expect(raw).not.toContain("someone_else_1");
expect(pagedStore.listGrantsForUser).not.toHaveBeenCalled();
}
// The cursor the API itself issued is accepted.
const { app: acceptingApp, store: acceptingStore } = buildApp({});
const accepted = await acceptingApp.request(
`/api/v1/grants?userId=${subjectUserId}&cursor=${encodeURIComponent(issued.nextCursor)}`,
);
expect(accepted.status).toBe(200);
expect(acceptingStore.listGrantsForUser).toHaveBeenCalledWith(subjectUserId, {
after: boundary,
limit: 50,
sourceKind: "explicit",
});
});
});