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:
co-authored by
Claude Opus 5
parent
532ce3803b
commit
5c589d8fec
@@ -1396,7 +1396,7 @@ describe.sequential("live API — platform owner and delegated grant management"
|
||||
headers: { cookie: ownerCookie },
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ grants: [] });
|
||||
expect(await response.json()).toEqual({ grants: [], nextCursor: null });
|
||||
});
|
||||
|
||||
it("lets the owner delegate grants.manage to another account through the explicit-grant HTTP API", async () => {
|
||||
@@ -1480,10 +1480,13 @@ describe.sequential("live API — platform owner and delegated grant management"
|
||||
|
||||
it("creates an explicit grant via HTTP, deriving sourceKind and actor server-side, and records an atomic audit entry", async () => {
|
||||
const response = await fetch(`${origin}/api/v1/grants`, {
|
||||
// A subject with no equivalent grant yet — the manager already holds an equivalent
|
||||
// `grants.manage` grant from the delegation scenario above, which the new duplicate
|
||||
// invariant would (correctly) refuse. Unscoped: the generic HTTP surface creates only
|
||||
// unscoped explicit grants, since a scope it accepted could never authorize anything.
|
||||
body: JSON.stringify({
|
||||
permission: testPermission,
|
||||
scope: "calendar-event:1",
|
||||
subjectUserId: managerUserId,
|
||||
subjectUserId: ownerUserId,
|
||||
}),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
@@ -1498,7 +1501,7 @@ describe.sequential("live API — platform owner and delegated grant management"
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(body.grant.sourceKind).toBe("explicit");
|
||||
expect(body.grant.userId).toBe(managerUserId);
|
||||
expect(body.grant.userId).toBe(ownerUserId);
|
||||
createdGrantId = body.grant.id;
|
||||
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
@@ -1514,14 +1517,21 @@ describe.sequential("live API — platform owner and delegated grant management"
|
||||
}
|
||||
});
|
||||
|
||||
it("lists the explicit grant via HTTP", async () => {
|
||||
const response = await fetch(`${origin}/api/v1/grants?userId=${managerUserId}`, {
|
||||
it("lists the explicit grant via HTTP, bounded and with an explicit next-page cursor field", async () => {
|
||||
const response = await fetch(`${origin}/api/v1/grants?userId=${ownerUserId}`, {
|
||||
headers: { cookie: ownerCookie },
|
||||
});
|
||||
const body = (await response.json()) as { grants: Array<{ id: string }> };
|
||||
const body = (await response.json()) as {
|
||||
grants: Array<{ id: string; scope: string | null }>;
|
||||
nextCursor: string | null;
|
||||
};
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(body.grants.some((grant) => grant.id === createdGrantId)).toBe(true);
|
||||
// Created through the generic HTTP surface, so it is unscoped.
|
||||
expect(body.grants.find((grant) => grant.id === createdGrantId)?.scope).toBeNull();
|
||||
expect(body.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a create-grant request carrying disallowed fields such as actor or sourceKind, even alongside otherwise-valid fields", async () => {
|
||||
@@ -1659,6 +1669,302 @@ describe.sequential("live API — authorization infrastructure failure is never
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Pass 3's explicit-grant invariants, exercised end-to-end through a real authorized
|
||||
* grants-management session against real PostgreSQL — the layer where a validation decision that
|
||||
* "should" happen before the database either does or does not.
|
||||
*/
|
||||
describe.sequential("live API — explicit-grant invariants over real HTTP", () => {
|
||||
let database: { name: string; url: string };
|
||||
let running: RunningApi;
|
||||
let origin: string;
|
||||
let ownerUserId: string;
|
||||
let subjectUserId: string;
|
||||
let ownerCookie: string;
|
||||
const password = "correct horse battery staple";
|
||||
const managePermission = "core.authorization.grants.manage";
|
||||
|
||||
async function post(path: string, body?: unknown): Promise<Response> {
|
||||
return await fetch(`${origin}${path}`, {
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
headers: {
|
||||
...(body === undefined ? {} : { "content-type": "application/json" }),
|
||||
cookie: ownerCookie,
|
||||
origin: dashboardOrigin,
|
||||
},
|
||||
method: "POST",
|
||||
});
|
||||
}
|
||||
|
||||
async function list(query: string): Promise<{ body: unknown; response: Response }> {
|
||||
const response = await fetch(`${origin}/api/v1/grants?${query}`, {
|
||||
headers: { cookie: ownerCookie },
|
||||
});
|
||||
return { body: await response.json(), response };
|
||||
}
|
||||
|
||||
it("starts a freshly migrated API with a bootstrapped owner and a separate grant subject", async () => {
|
||||
database = await createDisposableDatabase("grant_invariants");
|
||||
await applyCoreMigrations(database.url);
|
||||
running = await startMigratedApi(database.url);
|
||||
origin = apiOrigin(running);
|
||||
|
||||
ownerUserId = (await signUp(origin, "[email protected]", password)).body.user.id;
|
||||
subjectUserId = (await signUp(origin, "[email protected]", password)).body.user
|
||||
.id;
|
||||
|
||||
const { close, db } = createAuthorizationDrizzleDatabase(database.url);
|
||||
try {
|
||||
await bootstrapPlatformOwner(db, { userId: parseEkklesiaUserId(ownerUserId) });
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
const ownerSignIn = await signIn(origin, "[email protected]", password);
|
||||
expect(ownerSignIn.cookiePair).toBeDefined();
|
||||
ownerCookie = ownerSignIn.cookiePair as string;
|
||||
});
|
||||
|
||||
it("rejects a malformed non-UUID grant id with a sanitized 400, never a database failure", async () => {
|
||||
for (const malformed of [
|
||||
"not-a-uuid",
|
||||
"0B36B1B6-9A29-4C4E-9E2D-4C0E4C5E6F70",
|
||||
"0b36b1b6-9a29-4c4e-9e2d-4c0e4c5e6f7",
|
||||
]) {
|
||||
const response = await post(`/api/v1/grants/${malformed}/revoke`);
|
||||
const raw = await response.text();
|
||||
|
||||
// Before Pass 3 this reached PostgreSQL's own UUID comparison and returned 503.
|
||||
expect(response.status, malformed).toBe(400);
|
||||
expect(JSON.parse(raw)).toEqual({ code: "INVALID_REQUEST" });
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(raw).not.toContain(malformed);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns the sanitized 404 for a canonical but unknown grant id", async () => {
|
||||
const response = await post("/api/v1/grants/00000000-0000-4000-8000-000000000000/revoke");
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.json()).toEqual({ code: "AUTHORIZATION_GRANT_NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("rejects a scoped create body with a sanitized 400 and writes nothing", async () => {
|
||||
const response = await post("/api/v1/grants", {
|
||||
permission: managePermission,
|
||||
scope: "calendar-event:1",
|
||||
subjectUserId,
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
|
||||
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
expect(
|
||||
await safeQuery(admin, `select id from "ekklesia_core_grant" where user_id = $1`, [
|
||||
subjectUserId,
|
||||
]),
|
||||
).toHaveLength(0);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects normalized-impossible, non-canonical, and past expirations with a sanitized 400", async () => {
|
||||
for (const expiresAt of [
|
||||
"2026-02-31T00:00:00.000Z",
|
||||
"March 5, 2027",
|
||||
"2027-01-01",
|
||||
"2027-01-01T00:00:00Z",
|
||||
"2027-01-01T00:00:00.000+02:00",
|
||||
"2020-01-01T00:00:00.000Z",
|
||||
]) {
|
||||
const response = await post("/api/v1/grants", {
|
||||
expiresAt,
|
||||
permission: managePermission,
|
||||
subjectUserId,
|
||||
});
|
||||
expect(response.status, expiresAt).toBe(400);
|
||||
expect(await response.json()).toEqual({ code: "INVALID_REQUEST" });
|
||||
}
|
||||
});
|
||||
|
||||
it("creates one grant, then answers an equivalent creation with a sanitized 409 and no second row", async () => {
|
||||
const created = await post("/api/v1/grants", {
|
||||
permission: managePermission,
|
||||
subjectUserId,
|
||||
});
|
||||
expect(created.status).toBe(201);
|
||||
|
||||
const duplicate = await post("/api/v1/grants", {
|
||||
permission: managePermission,
|
||||
subjectUserId,
|
||||
});
|
||||
const raw = await duplicate.text();
|
||||
expect(duplicate.status).toBe(409);
|
||||
expect(JSON.parse(raw)).toEqual({ code: "AUTHORIZATION_GRANT_ALREADY_EXISTS" });
|
||||
expect(duplicate.headers.get("cache-control")).toBe("no-store");
|
||||
// No existing grant id, actor, scope, source reference, SQL, or driver text leaks.
|
||||
expect(raw).not.toContain(ownerUserId);
|
||||
expect(raw).not.toContain(subjectUserId);
|
||||
expect(raw).not.toContain("ekklesia_core_grant");
|
||||
|
||||
// A differing expiration is not a different grant either.
|
||||
const withExpiry = await post("/api/v1/grants", {
|
||||
expiresAt: "2099-01-01T00:00:00.000Z",
|
||||
permission: managePermission,
|
||||
subjectUserId,
|
||||
});
|
||||
expect(withExpiry.status).toBe(409);
|
||||
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
expect(
|
||||
await safeQuery(
|
||||
admin,
|
||||
`select id from "ekklesia_core_grant" where user_id = $1 and revoked_at is null`,
|
||||
[subjectUserId],
|
||||
),
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
});
|
||||
|
||||
it("paginates deterministically across at least three pages and ends with a null cursor", async () => {
|
||||
// Seeded through the test-only administrative client so the page count is deterministic and
|
||||
// independent of how many grants the scenarios above happened to create.
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
await safeQuery(
|
||||
admin,
|
||||
`insert into "ekklesia_core_grant"
|
||||
(user_id, permission_id, scope, source_kind, source_ref, created_by_actor_type, created_by_actor_id, created_at)
|
||||
select $1, 'calendar.events.page' || generation, null, 'explicit', null, 'user', $2,
|
||||
timestamptz '2026-01-01 00:00:00Z'
|
||||
from generate_series(1, 6) as generation`,
|
||||
[subjectUserId, ownerUserId],
|
||||
);
|
||||
await safeQuery(
|
||||
admin,
|
||||
`insert into "ekklesia_core_grant"
|
||||
(user_id, permission_id, scope, source_kind, source_ref, created_by_actor_type, created_by_actor_id)
|
||||
values ($1, 'roster.volunteer.read', null, 'relationship', 'roster:1', 'user', $2)`,
|
||||
[subjectUserId, ownerUserId],
|
||||
);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
let pages = 0;
|
||||
for (;;) {
|
||||
const query = `userId=${subjectUserId}&limit=3${
|
||||
cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`
|
||||
}`;
|
||||
const { body, response } = await list(query);
|
||||
const page = body as {
|
||||
grants: Array<{ id: string; sourceKind: string }>;
|
||||
nextCursor: string | null;
|
||||
};
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(page.grants.length).toBeLessThanOrEqual(3);
|
||||
// Relationship grants never appear on any page.
|
||||
expect(page.grants.every((grant) => grant.sourceKind === "explicit")).toBe(true);
|
||||
seen.push(...page.grants.map((grant) => grant.id));
|
||||
pages += 1;
|
||||
if (page.nextCursor === null) {
|
||||
break;
|
||||
}
|
||||
cursor = page.nextCursor;
|
||||
expect(pages).toBeLessThan(10);
|
||||
}
|
||||
|
||||
expect(pages).toBeGreaterThanOrEqual(3);
|
||||
expect(seen).toHaveLength(7);
|
||||
expect(new Set(seen).size).toBe(seen.length);
|
||||
});
|
||||
|
||||
it("rejects an out-of-range limit and a foreign or malformed cursor with a sanitized 400", async () => {
|
||||
for (const query of [
|
||||
`userId=${subjectUserId}&limit=0`,
|
||||
`userId=${subjectUserId}&limit=101`,
|
||||
`userId=${subjectUserId}&limit=01`,
|
||||
`userId=${subjectUserId}&limit=1&limit=2`,
|
||||
`userId=${subjectUserId}&unknown=1`,
|
||||
`userId=${subjectUserId}&cursor=!!!`,
|
||||
// A cursor minted for a different subject must not be replayable against this one.
|
||||
`userId=${subjectUserId}&cursor=${encodeURIComponent(
|
||||
Buffer.from(
|
||||
JSON.stringify({
|
||||
g: "00000000-0000-4000-8000-000000000000",
|
||||
t: "2026-01-01T00:00:00.000Z",
|
||||
u: ownerUserId,
|
||||
v: 1,
|
||||
}),
|
||||
"utf8",
|
||||
).toString("base64url"),
|
||||
)}`,
|
||||
]) {
|
||||
const { body, response } = await list(query);
|
||||
expect(response.status, query).toBe(400);
|
||||
expect(body).toEqual({ code: "INVALID_REQUEST" });
|
||||
}
|
||||
});
|
||||
|
||||
it("revokes every unrevoked equivalent through one HTTP revocation, leaving nothing authorizing", async () => {
|
||||
const permission = "calendar.events.legacydupe";
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
let ids: string[] = [];
|
||||
try {
|
||||
// Legacy duplicates the pre-Pass-3 store could produce, planted directly because the
|
||||
// production store now refuses to create them.
|
||||
const rows = await safeQuery<{ id: string }>(
|
||||
admin,
|
||||
`insert into "ekklesia_core_grant"
|
||||
(user_id, permission_id, scope, source_kind, source_ref, created_by_actor_type, created_by_actor_id)
|
||||
values ($1, $2, null, 'explicit', null, 'user', $3),
|
||||
($1, $2, null, 'explicit', null, 'user', $3),
|
||||
($1, $2, null, 'explicit', null, 'user', $3)
|
||||
returning id`,
|
||||
[subjectUserId, permission, ownerUserId],
|
||||
);
|
||||
ids = rows.map((row) => row.id);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
|
||||
const response = await post(`/api/v1/grants/${ids[0]}/revoke`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ success: true });
|
||||
|
||||
const inspector = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
const remaining = await safeQuery(
|
||||
inspector,
|
||||
`select id from "ekklesia_core_grant"
|
||||
where user_id = $1 and permission_id = $2 and revoked_at is null`,
|
||||
[subjectUserId, permission],
|
||||
);
|
||||
expect(remaining).toHaveLength(0);
|
||||
const audit = await safeQuery<{ grant_id: string }>(
|
||||
inspector,
|
||||
`select grant_id from "ekklesia_core_authorization_audit"
|
||||
where action = 'grant.revoke' and grant_id = any($1::uuid[])`,
|
||||
[ids],
|
||||
);
|
||||
expect([...new Set(audit.map((row) => row.grant_id))].sort()).toEqual([...ids].sort());
|
||||
} finally {
|
||||
await safeEnd(inspector);
|
||||
}
|
||||
});
|
||||
|
||||
it("shuts down cleanly", async () => {
|
||||
await running.shutdown();
|
||||
await dropDatabase(database.name);
|
||||
});
|
||||
});
|
||||
|
||||
describe.sequential("live API — installed module permission end-to-end", () => {
|
||||
let database: { name: string; url: string };
|
||||
let modulesDirectory: string;
|
||||
|
||||
Reference in New Issue
Block a user