Authenticate and authorize every route: org layer + Supabase JWKS

Until now every HTTP route was unauthenticated. A probe against the
running server returned a farm's `edgeProxyToken` and a printer's
`accessCode` to an anonymous caller, and that pair is enough to connect
as a farm's gateway and drive its printers. The previous commit stopped
the credentials appearing in responses; this one makes the routes ask
who is calling.

Authentication. Access tokens are verified against the Supabase
project's published JWKS via `createSupabaseJwtVerifier` from
`@continuum/ts-core`: RS256, public key only, no secret in this
process. It replaces the HS256 `@elysiajs/jwt` path, where
`SUPABASE_JWT_SECRET` was simultaneously the verification key and a
key that could mint tokens, present in the environment of every
instance. `src/auth/verifier.ts` builds it at module load so a
misconfigured deployment fails at boot rather than on first login.

The edge-gateway token stays symmetric and that is not an
inconsistency: this service is both its issuer and its only verifier,
so there is no second party to keep a secret from. It now carries an
`exp`, which it did not, despite the response saying
`expiresInSeconds: 3600`.

Tenancy. An org layer above farms - `organisations`,
`org_members(org_id, user_id, role)`, `farms.org_id` - so a farm can
have more than one operator without sharing an account. `farms.owner_id`
is gone. Authorization is one rule applied everywhere: resolve the
thing being acted on back to an organisation and check the caller's
role there, user -> org -> farm -> printer, with nothing in between
carrying permissions of its own. The ladder is
`viewer` < `operator` < `owner`; printer commands and job submission
need `operator`, because they move physical machines, and that is the
one boundary here that is not about data.

A non-member gets 404, not 403: a 403 would confirm that a given farm
or printer id exists and belongs to someone, which is an enumeration
oracle over the whole system. 403 is kept for a member who may see the
record but not do this to it.

List endpoints scope in the `where` clause, not after the query - a
filter applied to the result is one `return` away from being skipped.
They are also bounded now (`limit`/`offset`, default 50, max 200
refused rather than clamped).

`ownerId` and `submittedBy` no longer come from request bodies. Nor do
the printer telemetry columns: `POST /printers` is narrowed to the
columns a client owns, because a client that could POST
`status: "idle"` could make the scheduler send work to a printer that
is mid-print.

Also fills the CRUD gaps that made the API unusable - PATCH and DELETE
for farms, printers, jobs and orgs, and membership management - plus
one error shape for the whole API via `toErrorResponse`, so an
authorization failure is a throw that leaves the handler rather than a
status somebody has to remember to set.

Guards on the two changes that cannot be undone through the API:
removing or demoting an organisation's last owner, and deleting an
organisation while farms are still attached (it would cascade to every
printer, print job and stored frame).

Migration 0001 is hand-edited after generation. drizzle-kit emitted
`ADD COLUMN org_id uuid NOT NULL`, which cannot apply to a populated
table, and dropped `owner_id` without moving what it encodes anywhere.
It now adds the column nullable, creates one organisation per distinct
legacy owner with that user as its `owner` member, points each farm at
it, and only then tightens the column and drops `owner_id`. Verified
both ways: from empty via `drizzle-kit migrate`, and against a seeded
database where two farms shared an owner and a third did not.

Testing. `scripts/dev-auth.ts` is a local RS256 issuer publishing a
JWKS at the path the backend fetches, so the real verification path is
testable without a Supabase project. The alternative was a test-only
bypass in the backend - an env var making it trust an unsigned token -
which would be a permanent hole one misconfiguration from production,
and would mean the code under test is not the code that ships.

- `tests/authz.test.ts` (19 tests): the role ladder written out in full
  rather than derived the same way the implementation derives it, and
  the real JWKS path - a token signed by a key outside the JWKS, an
  expired token and a token with `aud: "anon"` (Supabase's own anon key
  is a valid project JWT) are all rejected, with the same message, so
  probing cannot tell which part of a forged token to fix next.
- `scripts/e2e-authz.sh` (68 assertions, real Postgres, real routes):
  four users across two organisations; anonymous 401s, cross-org 404s,
  viewer-cannot-command, operator-cannot-rotate, a spoofed
  `submittedBy` in the body ignored, no credential in any read, and the
  rotated token still minting an edge JWT.
- `scripts/e2e-edge.sh` updated for the org layer and now authenticates
  as a seeded `operator` - the weakest role that should work, so the
  run would fail if the command boundary were not where it claims to
  be. Re-verified against both live printers: telemetry from `h2c` and
  `p1p` persisted, and an authenticated `set_fan_speed` went
  HTTP -> WebSocket -> MQTT -> P1P and back `ok:true`, fan returned
  to 0.

Two bugs found in the test scripts while writing this, both the same
shape as the earlier `pkill -f` incident: `kill "${PID:-0}"` with an
unset PID signals the whole process group, including the harness, and
`uuidgen` is not installed in this sandbox.
This commit is contained in:
2026-10-03 15:49:29 +00:00
parent 01bcc73996
commit d8f8653dee
25 changed files with 2458 additions and 180 deletions
+130 -46
View File
@@ -1,38 +1,79 @@
import { Elysia, t } from "elysia";
import { eq } from "drizzle-orm";
import { and, desc, eq } from "drizzle-orm";
import { NotFoundError } from "@continuum/ts-core";
import { db } from "../db";
import { farms } from "../db/schema";
import { farmProjection } from "../db/projections";
import { requireFarm, requireOrg, requireUser, visibleFarms } from "../auth";
import { PaginationQuery, paginate } from "./pagination";
const IdParams = t.Object({ id: t.String({ format: "uuid" }) });
export const farmRoutes = new Elysia({ prefix: "/farms" })
// A projection rather than `select *`: the table holds
// `edgeProxyToken`, which trades for an edge JWT and so must never leave
// the server in a list or a fetch. See src/db/projections.ts.
.get("/", async () => db.query.farms.findMany({ columns: farmProjection.columns }))
.get("/:id", async ({ params, set }) => {
const farm = await db.query.farms.findFirst({
columns: farmProjection.columns,
where: eq(farms.id, params.id),
});
if (!farm) {
set.status = 404;
return { error: { code: "NOT_FOUND", message: `Farm ${params.id} not found` } };
}
return farm;
})
.use(requireUser)
/**
* Farms in the caller's organisations. The scoping is in the `where`, not
* applied to the result afterwards: a filter that runs after the query is
* one `return` away from being skipped, and it also makes the database read
* rows it is not allowed to show.
*
* A projection rather than `select *`, because the table holds
* `edgeProxyToken`, which trades for an edge JWT - see src/db/projections.ts.
*/
.get(
"/",
async ({ user, query }) => {
const scope = query.orgId
? and(visibleFarms(user.id), eq(farms.orgId, query.orgId))
: visibleFarms(user.id);
return db.query.farms.findMany({
columns: farmProjection.columns,
where: scope,
orderBy: [desc(farms.createdAt)],
...paginate(query),
});
},
{
query: t.Object({
orgId: t.Optional(t.String({ format: "uuid" })),
...PaginationQuery,
}),
detail: { tags: ["farms"], summary: "Farms in the caller's organisations" },
},
)
.get(
"/:id",
async ({ user, params }) => {
const { role } = await requireFarm(user.id, params.id, "viewer");
const farm = await db.query.farms.findFirst({
columns: farmProjection.columns,
where: eq(farms.id, params.id),
});
if (!farm) throw new NotFoundError(`Farm ${params.id} not found`);
return { ...farm, role };
},
{ params: IdParams, detail: { tags: ["farms"] } },
)
.post(
"/",
async ({ body, set }) => {
// The generated token is deliberately not returned here either. A farm
// is created far more often than a gateway is provisioned, and a
// credential that comes back from a routine create ends up in logs,
// browser history and screenshots. Fetch it when a gateway actually
// needs it, through the endpoint below.
async ({ user, body, set }) => {
// `orgId` comes from the body and is then authorized, which is the
// right way round: the caller says where the farm should go, and the
// check is whether they own that organisation. What must never come
// from the body is *who the caller is* - that is `user.id`, from a
// verified token, and it is why there is no `ownerId` field here any
// more.
await requireOrg(user.id, body.orgId, "owner", "creating a farm");
// The generated token is deliberately not returned. A farm is created
// far more often than a gateway is provisioned, and a credential that
// comes back from a routine create ends up in logs, browser history and
// screenshots. Fetch it when a gateway actually needs it, below.
const [farm] = await db
.insert(farms)
.values({
name: body.name,
ownerId: body.ownerId,
orgId: body.orgId,
edgeProxyToken: crypto.randomUUID(),
location: body.location,
})
@@ -42,12 +83,50 @@ export const farmRoutes = new Elysia({ prefix: "/farms" })
},
{
body: t.Object({
name: t.String({ minLength: 1 }),
ownerId: t.String({ format: "uuid" }),
location: t.Optional(t.String()),
name: t.String({ minLength: 1, maxLength: 200 }),
orgId: t.String({ format: "uuid" }),
location: t.Optional(t.String({ maxLength: 500 })),
}),
detail: { tags: ["farms"] },
},
)
.patch(
"/:id",
async ({ user, params, body }) => {
await requireFarm(user.id, params.id, "owner", "editing a farm");
// `orgId` is not patchable here on purpose: moving a farm between
// organisations changes who can see its print history and would need
// the `owner` role in *both*, so it wants its own endpoint rather than
// a field on a general update.
const [farm] = await db
.update(farms)
.set({ ...body, updatedAt: new Date() })
.where(eq(farms.id, params.id))
.returning(farmProjection.returning);
if (!farm) throw new NotFoundError(`Farm ${params.id} not found`);
return farm;
},
{
params: IdParams,
body: t.Object({
name: t.Optional(t.String({ minLength: 1, maxLength: 200 })),
location: t.Optional(t.String({ maxLength: 500 })),
settings: t.Optional(t.Record(t.String(), t.Unknown())),
}),
detail: { tags: ["farms"] },
},
)
.delete(
"/:id",
async ({ user, params }) => {
await requireFarm(user.id, params.id, "owner", "deleting a farm");
// Cascades to the farm's printers and print jobs, per the schema's
// foreign keys. Worth knowing before calling it.
await db.delete(farms).where(eq(farms.id, params.id));
return { deleted: params.id };
},
{ params: IdParams, detail: { tags: ["farms"] } },
)
/**
* Issues a *new* `edgeProxyToken` for this farm and returns it once.
*
@@ -62,26 +141,31 @@ export const farmRoutes = new Elysia({ prefix: "/farms" })
* token until it is reconfigured, which is the right trade for a credential
* that drives physical machines - but it does mean this is not a "show me
* the token" button.
*
* NOT YET AUTHENTICATED, like every route here. Until it is, this is a
* better-shaped hole, not a closed one.
*/
.post("/:id/edge-proxy-token", async ({ params, set }) => {
const token = crypto.randomUUID();
const [farm] = await db
.update(farms)
.set({ edgeProxyToken: token, updatedAt: new Date() })
.where(eq(farms.id, params.id))
.returning({ id: farms.id });
.post(
"/:id/edge-proxy-token",
async ({ user, params }) => {
await requireFarm(user.id, params.id, "owner", "rotating a farm's gateway credential");
if (!farm) {
set.status = 404;
return { error: { code: "NOT_FOUND", message: `Farm ${params.id} not found` } };
}
const token = crypto.randomUUID();
const [farm] = await db
.update(farms)
.set({ edgeProxyToken: token, updatedAt: new Date() })
.where(eq(farms.id, params.id))
.returning({ id: farms.id });
if (!farm) throw new NotFoundError(`Farm ${params.id} not found`);
return {
farmId: farm.id,
edgeProxyToken: token,
note: "Any gateway still using the previous token must be reconfigured.",
};
});
return {
farmId: farm.id,
edgeProxyToken: token,
note: "Any gateway still using the previous token must be reconfigured.",
};
},
{
params: IdParams,
detail: {
tags: ["farms"],
summary: "Rotate and return this farm's edge-proxy token (owner only)",
},
},
);