Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/mandates.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ if (!r.allowed) return new Response(r.message, { status: 403 });

**Elsewhere:** `POST {issuer}/api/mandates/authorize` with the same fields as JSON. The answer is the same.

**Showing a mandate later:** an app that kept `r.mandate` can ask whether it still stands, for example to print "signed on the 3rd, stopped on the 9th" next to something the mandate once let through.

```ts
const s = await env.MANDATES.status(mandateId);
// s.status: "active" | "revoked" | "expired" | "unknown", s.created_at, s.expires_at, s.revoked_at
```

`status` takes no chain and no proof, writes nothing to the trail and says nothing about the person. It is for display only: a request is let through by `authorize`, never by `status`. It is available over the service binding, not over HTTP. Any app with the binding can ask about any id, not only one it got from `authorize`: the ids are random, and the answer holds the state and three dates, nothing else.

**Offline:** `src/mandates/verify.ts` depends on `jose` and WebCrypto only, and an app can copy it to check chains without stem. It can't know about a stop, the budget or a replayed proof, so use it as a first filter, not instead of the live check.

Refusal reasons: `invalid_chain`, `invalid_human_proof`, `wider_than_parent`, `too_deep`, `invalid_pop`, `outside_mandate`, `revoked`, `expired`, `unknown`, `over_budget`, `replayed`.
Expand Down
26 changes: 25 additions & 1 deletion src/mandates/authorize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import type { JSONWebKeySet } from "jose";
import type { Env } from "../env";
import { createAuth } from "../auth";
import { verifyMandate, allows, MandateError, type Right, type Budget } from "./verify";
import type { Outcome } from "./object";
import type { Outcome, MandateStatus } from "./object";
import type { MandateRow } from "./plugin";

export type AuthorizeInput = {
/** The tokens from "Authorization: Mandate a~b~c", in order. */
Expand Down Expand Up @@ -65,12 +66,35 @@ export async function authorize(env: Env, i: AuthorizeInput): Promise<AuthorizeR
return { allowed: true, mandate: v.mandate, sub: v.sub, purpose: v.purpose, holder: v.holder, depth: v.depth, rights: v.rights, remaining: live.remaining, exp: v.exp };
}

export type StatusResult = { status: MandateStatus["status"]; created_at: string | null; expires_at: string | null; revoked_at: string | null };

const UNKNOWN: StatusResult = { status: "unknown", created_at: null, expires_at: null, revoked_at: null };

/** Whether a mandate still stands, for an app that kept its id from an earlier authorize() and wants
* to show it: "signed on the 3rd, stopped on the 9th". No chain, no proof, nothing in the trail, and
* nothing about the person. Never a reason to let a request through: that is what authorize() is for.
* Starts from stem's own list, so asking about an id nobody issued doesn't create an object for it. */
export async function status(env: Env, id: unknown): Promise<StatusResult> {
if (!env.MANDATE || typeof id !== "string" || !/^[0-9a-f-]{36}$/i.test(id)) return UNKNOWN;
const db = (await createAuth(env).$context).adapter;
const m = await db.findOne<MandateRow>({ model: "mandate", where: [{ field: "id", value: id }] });
if (!m) return UNKNOWN;
const iso = (d: Date | string | null | undefined) => (d ? new Date(d).toISOString() : null);
let state: StatusResult["status"] = m.status === "revoked" ? "revoked" : new Date(m.expiresAt).getTime() < Date.now() ? "expired" : "active";
// The object has the last word while the list says active: a stop reaches it first.
if (state === "active") state = (await env.MANDATE.get(env.MANDATE.idFromName(m.id)).status().catch(() => null))?.status ?? state;
return { status: state, created_at: iso(m.createdAt), expires_at: iso(m.expiresAt), revoked_at: iso(m.revokedAt) };
}

/** Named entrypoint for app Workers on the same account:
* `services: [{ binding: "MANDATES", service: "stem", entrypoint: "MandateGateway" }]`. */
export class MandateGatewayBase extends WorkerEntrypoint<Env> {
authorize(input: AuthorizeInput) {
return authorize(this.env, input);
}
status(mandate: string) {
return status(this.env, mandate);
}
jwks() {
return ownJwks(this.env);
}
Expand Down
49 changes: 49 additions & 0 deletions test/mandates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,55 @@ describe("mandates: the whole flow", () => {
});
});

describe("mandates: asking whether one still stands", () => {
// Its own stem: the flow above uses up the request limit of the agent's address.
const env = makeEnv();
const gw = new MandateGateway(ctx as never, env);
const b = new Browser(env);
const pk = new Passkey();
beforeAll(async () => {
pk.enrol(env, (await signIn(b, "ada@example.com")).id);
});

it("tells an app the state and the dates, and leaves no trace in the trail", async () => {
const root = await approvedMandate(env, b, pk);
const objects = (env.MANDATE as unknown as { objects: Map<string, MandateState> }).objects;
const active = await gw.status(root.id);
expect(active).toMatchObject({ status: "active", revoked_at: null });
expect(new Date(active.expires_at!).getTime() - new Date(active.created_at!).getTime()).toBeGreaterThan(86_000_000);
// Nothing about the person or the rights.
expect(Object.keys(active).sort()).toEqual(["created_at", "expires_at", "revoked_at", "status"]);

// An id nobody issued is unknown, and asking about it creates no object.
const made = objects.size;
const nobody = crypto.randomUUID();
for (const id of [nobody, "", "../etc", 42, null]) expect(await gw.status(id as never)).toEqual({ status: "unknown", created_at: null, expires_at: null, revoked_at: null });
expect(objects.size).toBe(made);
expect(objects.has(nobody)).toBe(false);

const db = env.DB as unknown as DatabaseSync;
const until = (db.prepare(`select expiresAt from mandate where id = ?`).get(root.id) as { expiresAt: string }).expiresAt;
db.prepare(`update mandate set expiresAt = ? where id = ?`).run(new Date(Date.now() - 1000).toISOString(), root.id);
expect(await gw.status(root.id)).toMatchObject({ status: "expired" });
db.prepare(`update mandate set expiresAt = ? where id = ?`).run(until, root.id);
expect(await gw.status(root.id)).toMatchObject({ status: "active" });

// A stop that reached the object but not yet the list still counts.
objects.get(root.id)!.revoke();
expect(await gw.status(root.id)).toMatchObject({ status: "revoked", revoked_at: null });
expect((await b.json("/api/auth/mandates/revoke", { id: root.id })).status).toBe(200);
const stopped = await gw.status(root.id);
expect(stopped.status).toBe("revoked");
expect(Date.parse(stopped.revoked_at!)).toBeGreaterThan(Date.now() - 60_000);

expect(((await (await b.fetch(`/api/auth/mandates/trail?id=${root.id}`)).json()) as unknown[]).length).toBe(0);
});

it("knows nothing when mandates are off", async () => {
expect(await new MandateGateway(ctx as never, makeEnv({ MANDATE: undefined })).status(crypto.randomUUID())).toMatchObject({ status: "unknown" });
});
});

describe("mandates: the verifier on its own", () => {
// A stem of our own, to forge what a stolen signing key could produce.
async function setup(uv = true) {
Expand Down