Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Accounts 2 fixes: denials nobody signed in can cause are rate-limited, refused credentials audited, wider redaction

Claudeea1843f608a9
diff --git a/src/server/access/actor.ts b/src/server/access/actor.ts
index 2620dcf5..ab948abc 100644
--- a/src/server/access/actor.ts
+++ b/src/server/access/actor.ts
@@ -22,6 +22,8 @@ export interface RequestScope {
userAgent?: string | null;
method?: string;
path?: string;
+ /** The route's pattern (`/api/generations/[id]`): the path with each dynamic segment named, for rate-limited denials. */
+ route?: string;
}
declare global {
diff --git a/src/server/access/audit.ts b/src/server/access/audit.ts
index 3f3ecaa8..c8930ad8 100644
--- a/src/server/access/audit.ts
+++ b/src/server/access/audit.ts
@@ -1,5 +1,6 @@
import "server-only";
import { appendAudit, verifyAuditChain, type AuditChainCheck } from "../identity/audit-log";
+import { SETTINGS, type SettingDef } from "../settings";
import { requestScope } from "./actor";
/**
@@ -7,11 +8,15 @@ import { requestScope } from "./actor";
* takes who acted, from which address and with which browser from the request scope, and appends a row to the
* hash-chained, append-only `audit_log` (src/server/identity/audit-log.ts). Core events: auth.*, token.*, people.*,
* team.*, install.*, keys.* (setting names and masked prefixes only), limits.*, content.share|move|grant, `denied`
- * (every 403 a route answers) and `denied.hidden` (404s for records the actor may not see, at most one a minute per
- * person and route).
+ * (every 403) and `denied.hidden` (404s for records the actor may not see).
*
- * Secrets never reach the log: meta fields named like one (password, secret, token, apiKey…) are replaced before the
- * row is written, whatever the caller passed.
+ * Denials nobody signed in can cause (a public route's 403, a turned-off person's credentials) and hidden-record 404s
+ * are written at most once a minute per person (or address) and route; the next entry says how many more there were
+ * (`more`), so a script can't grow the log as fast as it can send requests.
+ *
+ * Secrets never reach the log: meta fields named like one (password, secret, token, a key: apiKey, falKey, "fal.key"…),
+ * values shaped like one (an API key, a bearer token), and the value of a secret setting are replaced before the row
+ * is written, whatever the caller passed, in nested objects and lists too.
*/
export interface AuditTarget {
@@ -19,66 +24,158 @@ export interface AuditTarget {
id?: string | null;
}
-const SECRET_NAME = /(pass(word)?|secret|token|api_?key|private_?key|authorization|cookie)$/i;
-/** Names that look like a secret's but only describe one. */
-const DESCRIBES = /(prefix|id|name|kind|count|at|tokens)$/i;
+// ---------------------------------------------------------------------------
+// Redaction
+
+const REDACTED = "[redacted]";
+const SECRET_NAME = /(pass(word)?|passphrase|secret|token|key|authorization|cookie|credentials?)$/i;
+/** Names that look like a secret's but only describe one (a prefix, an id, a count, where it is kept). */
+const DESCRIBES = /(prefix|id|ids|name|names|kind|count|at|tokens|mode|source|scope|scopes|set|masked|hint|last4|length)$/i;
+/** Values shaped like a credential: Fuobe tokens, provider keys (sk-, r8_, hf_, AIza…), fal's id:secret, a bearer header. */
+const SECRET_VALUE = [
+ /^(fuobe_|sk-|sk_|rk_|pk_live_|r8_|hf_|ghp_|gho_|ghs_|github_pat_|glpat-|xox[abpr]-|AIza|AKIA)[A-Za-z0-9_\-.]{12,}$/,
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:[0-9a-f]{20,}$/i,
+ /^(Bearer|Basic)\s+\S{8,}$/i,
+];
+/** A masked value ("sk-l••••abcd", "fuobe_ab…") is what the log may keep. */
+const MASKED = /••••|…/;
+
+const SETTING_DEFS = Object.entries(SETTINGS) as [string, SettingDef][];
+/** Every secret setting, by its name in code and its stored key (falKey, "fal.key"). */
+const SECRET_SETTINGS = new Set(SETTING_DEFS.filter(([, d]) => d.secret).flatMap(([name, d]) => [name, d.key]));
+/** Every setting's name, which is a name and not a secret even in a field called `key`. */
+const SETTING_NAMES = new Set(SETTING_DEFS.flatMap(([name, d]) => [name, d.key]));
+/** The fields that carry a setting's value next to its name. */
+const VALUE_FIELDS = new Set(["value", "from", "to", "old", "new", "previous", "next", "before", "after"]);
+
+const secretName = (k: string) => SECRET_NAME.test(k) && !DESCRIBES.test(k);
+const secretValue = (v: string) => !MASKED.test(v) && SECRET_VALUE.some((re) => re.test(v.trim()));
+
+/** Whether this object (or the entry's target) names a secret setting, so its value fields are secrets too. */
+function namesSecretSetting(o: Record<string, unknown>, target?: AuditTarget | null): boolean {
+ if (target?.kind === "setting" && target.id && SECRET_SETTINGS.has(target.id)) return true;
+ return ["key", "setting", "name"].some((k) => typeof o[k] === "string" && (SECRET_SETTINGS.has(o[k] as string) || (SECRET_NAME.test(o[k] as string) && !SETTING_NAMES.has(o[k] as string) && !DESCRIBES.test(o[k] as string))));
+}
-function redact(meta: Record<string, unknown>): Record<string, unknown> {
+function redactValue(v: unknown, target?: AuditTarget | null): unknown {
+ if (typeof v === "string") return secretValue(v) ? REDACTED : v;
+ if (Array.isArray(v)) return v.map((x) => redactValue(x));
+ if (v && typeof v === "object") return redact(v as Record<string, unknown>, target);
+ return v;
+}
+
+function redact(meta: Record<string, unknown>, target?: AuditTarget | null): Record<string, unknown> {
+ const secretSetting = namesSecretSetting(meta, target);
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(meta)) {
- if (SECRET_NAME.test(k) && !DESCRIBES.test(k) && typeof v === "string" && v) out[k] = "[redacted]";
- else if (v && typeof v === "object" && !Array.isArray(v)) out[k] = redact(v as Record<string, unknown>);
- else out[k] = v;
+ const isString = typeof v === "string" && v !== "";
+ // A field named like a secret keeps a value that is only a setting's name ("key": "fal.key") or already masked.
+ if (secretName(k) && isString && !SETTING_NAMES.has(v as string) && !MASKED.test(v as string)) out[k] = REDACTED;
+ else if (secretName(k) && v && typeof v === "object") out[k] = REDACTED;
+ else if (secretSetting && VALUE_FIELDS.has(k) && isString && !MASKED.test(v as string)) out[k] = REDACTED;
+ else out[k] = redactValue(v);
}
return out;
}
-/** Append an entry for whoever is acting now (the request's person, a runner's row owner, or the server). */
-export function audit(action: string, target?: AuditTarget | null, meta: Record<string, unknown> = {}): void {
+// ---------------------------------------------------------------------------
+// Writing
+
+interface Who {
+ actorId: string | null;
+ via: string | null;
+ meta: Record<string, unknown>;
+}
+
+function write(action: string, target: AuditTarget | null | undefined, meta: Record<string, unknown>, who?: Who): void {
const scope = requestScope();
const actor = scope?.actor ?? null;
- appendAudit({
- action,
+ const by: Who = who ?? {
actorId: actor?.userId ?? null,
via: actor?.via ?? null,
+ meta: { ...(actor?.impersonatorId && { impersonator: actor.impersonatorId }), ...(actor?.tokenId && { tokenId: actor.tokenId }) },
+ };
+ appendAudit({
+ action,
+ actorId: by.actorId,
+ via: by.via,
targetKind: target?.kind ?? null,
targetId: target?.id ?? null,
- meta: redact({
- ...(actor?.impersonatorId && { impersonator: actor.impersonatorId }),
- ...(actor?.tokenId && { tokenId: actor.tokenId }),
- ...meta,
- }),
+ meta: redact({ ...by.meta, ...meta }, target),
ip: scope?.ip ?? null,
userAgent: scope?.userAgent ?? null,
});
}
-/** A 403: what was refused and why (a permission, a token's scope, a code like REAUTH). */
-export function auditDenied(reason: string, meta: Record<string, unknown> = {}): void {
- const scope = requestScope();
- audit("denied", null, { method: scope?.method, path: scope?.path, reason, ...meta });
+/** Append an entry for whoever is acting now (the request's person, a runner's row owner, or the server). */
+export function audit(action: string, target?: AuditTarget | null, meta: Record<string, unknown> = {}): void {
+ write(action, target, meta);
}
+// ---------------------------------------------------------------------------
+// Denials
+
declare global {
- var __fuobeHiddenDenials: Map<string, number> | undefined;
+ var __fuobeAuditThrottle: Map<string, { at: number; more: number }> | undefined;
}
-const HIDDEN_EVERY_MS = 60_000;
+const THROTTLE_MS = 60_000;
/**
- * A 404 for a record that exists but isn't the actor's to see. Logged at most once a minute per person and route, so
- * probing ids can't flood the log (the scoping package calls it through NotFoundError({ hidden: true })).
+ * Whether an entry under `key` may be written now (at most one a minute), and how many were held back since the last
+ * one. The map forgets keys a minute old once it grows, so it stays small whatever is probed.
*/
-export function auditHidden(target?: AuditTarget | null): void {
- const scope = requestScope();
- const key = `${scope?.actor?.userId ?? "-"} ${scope?.method ?? ""} ${scope?.path ?? ""}`;
- const seen = (globalThis.__fuobeHiddenDenials ??= new Map());
+function throttle(key: string): { write: boolean; more: number } {
+ const seen = (globalThis.__fuobeAuditThrottle ??= new Map());
const now = Date.now();
const last = seen.get(key);
- if (last !== undefined && now - last < HIDDEN_EVERY_MS) return;
- if (seen.size > 5000) for (const [k, t] of seen) if (now - t >= HIDDEN_EVERY_MS) seen.delete(k);
- seen.set(key, now);
- audit("denied.hidden", target, { method: scope?.method, path: scope?.path });
+ if (last && now - last.at < THROTTLE_MS) {
+ last.more++;
+ return { write: false, more: 0 };
+ }
+ if (seen.size > 5000) for (const [k, t] of seen) if (now - t.at >= THROTTLE_MS) seen.delete(k);
+ seen.set(key, { at: now, more: 0 });
+ return { write: true, more: last?.more ?? 0 };
+}
+
+/** The route a request reached: its path with each dynamic segment named (handler() fills it in), else the path. */
+const routeOf = () => {
+ const scope = requestScope();
+ return scope?.route ?? scope?.path ?? "";
+};
+
+/**
+ * A 403: what was refused and why (a permission, a token's scope, a code like REAUTH). Every one is written for a
+ * signed-in person; for nobody (a public route's own 403), at most one a minute per address and route.
+ */
+export function auditDenied(reason: string, meta: Record<string, unknown> = {}): void {
+ const scope = requestScope();
+ const base = { method: scope?.method, path: scope?.path, reason, ...meta };
+ if (scope?.actor) return write("denied", null, base);
+ const t = throttle(`denied nobody ${scope?.ip ?? "-"} ${scope?.method ?? ""} ${routeOf()}`);
+ if (t.write) write("denied", null, { ...base, ...(t.more && { more: t.more }) });
+}
+
+/**
+ * A 403 for a person who may not act right now (pending, turned off, dormant) and showed their credentials anyway: who
+ * they are and why, at most one a minute per person and route.
+ */
+export function auditRefused(userId: string, via: string, code: string): void {
+ const scope = requestScope();
+ const t = throttle(`denied ${userId} ${scope?.method ?? ""} ${routeOf()}`);
+ if (t.write) write("denied", null, { method: scope?.method, path: scope?.path, reason: code, ...(t.more && { more: t.more }) }, { actorId: userId, via, meta: {} });
+}
+
+/**
+ * A 404 for a record that exists but isn't the actor's to see. Logged at most once a minute per person and route (the
+ * route's pattern, so probing ids can't flood the log); the scoping package calls it through
+ * NotFoundError({ hidden: true }).
+ */
+export function auditHidden(target?: AuditTarget | null): void {
+ const scope = requestScope();
+ const who = scope?.actor?.userId ?? `nobody ${scope?.ip ?? "-"}`;
+ const t = throttle(`hidden ${who} ${scope?.method ?? ""} ${routeOf()}`);
+ if (t.write) write("denied.hidden", target, { method: scope?.method, path: scope?.path, ...(t.more && { more: t.more }) });
}
export { verifyAuditChain, type AuditChainCheck };
diff --git a/src/server/access/route.ts b/src/server/access/route.ts
index 7893a261..0e36619f 100644
--- a/src/server/access/route.ts
+++ b/src/server/access/route.ts
@@ -2,7 +2,7 @@ import "server-only";
import { CLIENT_IP_HEADER, type Principal, resolvePrincipal } from "../identity/principal";
import { refusal } from "../identity/refusals";
import { withScope, type Actor } from "./actor";
-import { auditDenied, auditHidden } from "./audit";
+import { auditDenied, auditHidden, auditRefused } from "./audit";
import { AccessError, ForbiddenError, NotFoundError, UnauthenticatedError } from "./errors";
import { can, permissionExists } from "./permissions";
@@ -24,8 +24,10 @@ import { can, permissionExists } from "./permissions";
* Token scopes: a bearer token may call a route only when one of its scopes is listed (Full always may). By default
* reads (GET, HEAD) take any scope, writes take Generate or Admin, and permission routes take Admin.
*
- * Refusals thrown inside (src/server/access/errors.ts) become their answers: 404, 403, 401, 402 and 403 REAUTH. Every
- * 403 is audited as `denied`, including one the route answers itself.
+ * Refusals thrown inside (src/server/access/errors.ts) become their answers: 404, 403, 401, 402 and 403 REAUTH. A route
+ * (or a studio's error helper) that catches errors to answer them itself passes these on with rethrowAccess(e). Every
+ * 403 is audited as `denied`, including one the route answers itself and a turned-off person's refused credentials;
+ * the ones nobody signed in can cause are written at most once a minute per address and route (src/server/access/audit.ts).
*/
export type Access = "public" | "signed-in" | "browser" | `perm:${string}`;
@@ -98,6 +100,8 @@ const json = (status: number, error: string, code?: string, headers?: HeadersIni
function signedOut(principal: Principal): Response {
if (principal.code && principal.code !== "INVALID_TOKEN") {
const r = refusal(principal.code);
+ // A pending, turned-off or dormant person's own credentials: a denial, audited under their name.
+ if (r.status === 403 && principal.refused) auditRefused(principal.refused.userId, principal.refused.via, r.code ?? principal.code);
return json(r.status, r.message, r.code);
}
const error = principal.code === "INVALID_TOKEN" ? "That API token isn't valid. Create a new one in Settings → Security." : new UnauthenticatedError().message;
@@ -129,9 +133,43 @@ function answer(e: unknown): Response {
return json(e.status, e.message, e.code);
}
+const decode = (s: string) => {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+};
+
+/**
+ * The route's pattern from the params Next matched: `/api/generations/g_123` with `{ id: "g_123" }` is
+ * `/api/generations/[id]`, and a catch-all's run of segments is `[...path]`. Rate-limited denials are counted per
+ * route, so probing ids or paths doesn't make each one new.
+ */
+export async function routePattern(pathname: string, ctx: unknown): Promise<string> {
+ const raw = ctx && typeof ctx === "object" && "params" in ctx ? (ctx as { params: unknown }).params : undefined;
+ const params = raw ? await Promise.resolve(raw).catch(() => null) : null;
+ if (!params || typeof params !== "object") return pathname;
+ let segs = pathname.split("/");
+ for (const [name, value] of Object.entries(params as Record<string, unknown>)) {
+ if (Array.isArray(value)) {
+ const n = value.length;
+ for (let i = segs.length - n; n && i >= 1; i--) {
+ if (value.every((v, j) => decode(segs[i + j]) === String(v))) {
+ segs = [...segs.slice(0, i), `[...${name}]`, ...segs.slice(i + n)];
+ break;
+ }
+ }
+ } else if (typeof value === "string" && value) {
+ segs = segs.map((s) => (s && decode(s) === value ? `[${name}]` : s));
+ }
+ }
+ return segs.join("/");
+}
+
/**
* Wrap a route handler. The request scope it opens carries the actor (null on a public route answered for nobody), the
- * client's address (only when a trusted proxy reported it) and user agent, the method and the path.
+ * client's address (only when a trusted proxy reported it) and user agent, the method, the path and the route.
*/
export function handler<Req extends Request = Request, C = unknown>(
opts: HandlerOptions,
@@ -154,6 +192,7 @@ export function handler<Req extends Request = Request, C = unknown>(
userAgent: request.headers.get("user-agent"),
method,
path: url.pathname,
+ route: await routePattern(url.pathname, ctx),
};
return withScope(scope, async () => {
if (!actor && access !== "public") return signedOut(principal);
diff --git a/src/server/identity/principal.ts b/src/server/identity/principal.ts
index 23155b7c..61bf0f8d 100644
--- a/src/server/identity/principal.ts
+++ b/src/server/identity/principal.ts
@@ -39,6 +39,8 @@ export interface Principal {
actor: Actor | null;
/** Why there is no actor: INVALID_TOKEN (401), or a refusal code (ACCOUNT_PENDING…). */
code?: string;
+ /** The person a refusal code is about (their token or session was valid, they may not act now): for the audit log. */
+ refused?: { userId: string; via: "token" | "session" };
/** The session is due for its daily refresh, which only a POST performs (deferSessionRefresh). */
needsRefresh?: boolean;
}
@@ -83,7 +85,7 @@ async function resolve(request: Request): Promise<Principal> {
const p = person(bearer.userId);
if (!p) return { actor: null, code: "INVALID_TOKEN" };
const code = blocked(p);
- if (code) return { actor: null, code };
+ if (code) return { actor: null, code, refused: { userId: p.id, via: "token" } };
return { actor: { userId: p.id, role: p.role, via: "token", tokenId: bearer.tokenId, scopes: bearer.scopes, workspacePin: bearer.workspacePin } };
}
if (hasSessionCookie(request)) {
@@ -93,7 +95,7 @@ async function resolve(request: Request): Promise<Principal> {
if (found) {
const p = ensurePendingPerson(found.user.id);
const code = blocked(p);
- if (code) return { actor: null, code };
+ if (code) return { actor: null, code, refused: { userId: p.id, via: "session" } };
return {
actor: { userId: p.id, role: p.role, via: "session", sessionId: found.session.id, scopes: ["full"] },
needsRefresh: !!(found as { needsRefresh?: boolean }).needsRefresh,
diff --git a/tests/access-roles.test.ts b/tests/access-roles.test.ts
index a58b4221..a7506020 100644
--- a/tests/access-roles.test.ts
+++ b/tests/access-roles.test.ts
@@ -22,12 +22,12 @@ for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOB
const { db } = await import("@/server/db");
const { bootstrapIdentity } = await import("@/server/identity/bootstrap");
-const { handler, registerActorSubstitute, registerRestrictedKind, restrictedAllows } = await import("@/server/access/route");
+const { handler, registerActorSubstitute, registerRestrictedKind, restrictedAllows, routePattern } = await import("@/server/access/route");
const { currentActor, maybeActor, LOCAL_OWNER, runAs, SYSTEM } = await import("@/server/access/actor");
const errors = await import("@/server/access/errors");
const perms = await import("@/server/access/permissions");
const { gate, gateRefusal, registerGate } = await import("@/server/access/gates");
-const { seedPerson, seedTeam, tokenFor, request, actor, asNobody } = await import("./helpers/actors");
+const { seedPerson, seedTeam, tokenFor, request, actor, asNobody, updatePerson } = await import("./helpers/actors");
const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");
const settingsRoute = await import("@/app/api/settings/route");
const modelsRoute = await import("@/app/api/settings/models/route");
@@ -312,3 +312,116 @@ describe("the test harness", () => {
expect(currentActor().userId).toBe("u_owner");
});
});
+
+describe("denials that can't flood the log", () => {
+ it("writes a public route's own 403 for nobody at most once a minute per address and route, counting the rest", async () => {
+ await setOwnerPassword("correct horse battery");
+ try {
+ // Better Auth's router answers 403 to every endpoint it keeps closed.
+ const blocked = handler({ access: "public" }, () => Response.json({ error: "blocked" }, { status: 403 }));
+ const send = (o: { bearer?: string } = {}) => blocked(request("/api/identity/sign-up/email", { method: "POST", body: {}, ...o }));
+ const before = auditCount("denied");
+ for (let i = 0; i < 20; i++) expect((await send()).status).toBe(403);
+ expect(auditCount("denied")).toBe(before + 1);
+ expect(lastAudit()).toMatchObject({ actor_id: null });
+ // A signed-in person's 403s are each written.
+ const token = tokenFor(member);
+ for (let i = 0; i < 3; i++) await send({ bearer: token });
+ expect(auditCount("denied")).toBe(before + 4);
+ // A minute on, the next one is written and says how many were held back.
+ vi.useFakeTimers({ now: Date.now() + 61_000, toFake: ["Date"] });
+ try {
+ await send();
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(auditCount("denied")).toBe(before + 5);
+ expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ path: "/api/identity/sign-up/email", reason: "route", more: 19 });
+ } finally {
+ await setOwnerPassword(null);
+ }
+ });
+
+ it("counts hidden-record 404s per person and route, not per id", async () => {
+ const hidden = handler({}, async (_req: Request, ctx: { params: Promise<{ id: string }> }) => {
+ await ctx.params;
+ throw new errors.NotFoundError("Not found", true);
+ });
+ const before = auditCount("denied.hidden");
+ for (let i = 0; i < 50; i++) expect((await hidden(request(`/api/generations/id-${i}`), { params: Promise.resolve({ id: `id-${i}` }) })).status).toBe(404);
+ expect(auditCount("denied.hidden")).toBe(before + 1);
+ expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ path: "/api/generations/id-0" });
+ });
+
+ it("names a route's dynamic segments from the params Next matched", async () => {
+ expect(await routePattern("/api/generations/g_1", { params: Promise.resolve({ id: "g_1" }) })).toBe("/api/generations/[id]");
+ expect(await routePattern("/s/tok/f/a/b%20c.png", { params: Promise.resolve({ token: "tok", path: ["a", "b c.png"] }) })).toBe("/s/[token]/f/[...path]");
+ expect(await routePattern("/api/settings", undefined)).toBe("/api/settings");
+ });
+
+ it("audits a turned-off person's refused credentials under their name", async () => {
+ const off = seedPerson({ role: "member" });
+ const token = tokenFor(off);
+ updatePerson(off, { status: "disabled" });
+ const echo = handler({}, () => Response.json({}));
+ const before = auditCount("denied");
+ const res = await echo(request("/api/mcp", { method: "POST", body: {}, bearer: token }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: "ACCOUNT_DISABLED" });
+ expect(auditCount("denied")).toBe(before + 1);
+ expect(lastAudit()).toMatchObject({ actor_id: off, actor_via: "token" });
+ expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ reason: "ACCOUNT_DISABLED", path: "/api/mcp", method: "POST" });
+ });
+});
+
+describe("refusals the studios pass on", () => {
+ it("answers a refusal thrown inside a studio's error helper with its status, and audits each 403", async () => {
+ const cinema = await import("@/server/cinema-schemas");
+ const faceless = await import("@/server/faceless");
+ const factory = await import("@/server/content-factory");
+ const shorts = await import("@/server/shorts-schemas");
+ const { failure } = await import("@/server/marketing");
+ const { recipeFailure } = await import("@/server/recipe-routes");
+ const caught = (answer: (e: unknown) => Response) => (fn: () => never) => {
+ try {
+ return fn();
+ } catch (e) {
+ return answer(e);
+ }
+ };
+ const wrappers: [string, (fn: () => never) => Response | Promise<Response>][] = [
+ ["cinema", cinema.handle],
+ ["faceless", faceless.handle],
+ ["content factory", factory.handle],
+ ["shorts", shorts.handle],
+ ["marketing", caught(failure)],
+ ["recipes", caught(recipeFailure)],
+ ];
+ const refusals: [Error, number][] = [
+ [new errors.ForbiddenError("No.", "NOPE"), 403],
+ [new errors.NotFoundError(), 404],
+ [new errors.PaymentRequiredError(), 402],
+ [new errors.ReauthRequiredError(), 403],
+ ];
+ for (const [name, wrap] of wrappers) {
+ for (const [e, status] of refusals) {
+ const before = auditCount("denied");
+ const res = await handler({}, () =>
+ wrap(() => {
+ throw e;
+ }),
+ )(request(`/studio/${name.replace(/ /g, "-")}`, { method: "POST", body: {} }));
+ expect(res.status, `${name}: ${e.name}`).toBe(status);
+ expect(((await res.json()) as { error: string }).error, `${name}: ${e.name}`).toBe(e.message);
+ expect(auditCount("denied"), `${name}: ${e.name}`).toBe(before + (status === 403 ? 1 : 0));
+ }
+ // Anything else is still the studio's own answer.
+ const own = await handler({}, () =>
+ wrap(() => {
+ throw new Error("Pick a clip first");
+ }),
+ )(request("/studio/own", { method: "POST", body: {} }));
+ expect([422, 500], name).toContain(own.status);
+ }
+ });
+});
diff --git a/tests/audit-log.test.ts b/tests/audit-log.test.ts
index a3300d1f..4982b0da 100644
--- a/tests/audit-log.test.ts
+++ b/tests/audit-log.test.ts
@@ -78,6 +78,53 @@ describe("audit()", () => {
expect(last().meta_json).not.toMatch(/sk-live|hunter2|Bearer x/);
});
+ it("knows Fuobe's own key names, plain key and value fields, values shaped like a key, and lists", () => {
+ audit("keys.set", null, {
+ falKey: "fal-SECRET-1",
+ anthropicKey: "sk-ant-SECRET",
+ "fal.key": "SECRET-dotted",
+ openaiKey: "sk-SECRET-openai",
+ replicateToken: "r8_SECRETSECRETSECRET",
+ key: "plain-SECRET",
+ list: [{ password: "SECRET-in-a-list" }, "fuobe_SECRETSECRETSECRET1234"],
+ note: "sk-ant-api03-SECRETSECRETSECRET",
+ falLike: "0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b:00112233445566778899aabbccddeeff",
+ header: "Bearer SECRET-bearer-value",
+ maskedKey: "sk-a••••cret",
+ keyPrefix: "sk-ant-",
+ keyName: "anthropicKey",
+ });
+ const meta = JSON.parse(last().meta_json);
+ expect(meta).toEqual({
+ falKey: "[redacted]",
+ anthropicKey: "[redacted]",
+ "fal.key": "[redacted]",
+ openaiKey: "[redacted]",
+ replicateToken: "[redacted]",
+ key: "[redacted]",
+ list: [{ password: "[redacted]" }, "[redacted]"],
+ note: "[redacted]",
+ falLike: "[redacted]",
+ header: "[redacted]",
+ maskedKey: "sk-a••••cret",
+ keyPrefix: "sk-ant-",
+ keyName: "anthropicKey",
+ });
+ expect(last().meta_json).not.toMatch(/SECRET/);
+ });
+
+ it("keeps a setting's name but not its value: a key/value pair, or from/to on a secret setting's entry", () => {
+ audit("keys.set", null, { key: "falKey", value: "fal-SECRET-2" });
+ expect(JSON.parse(last().meta_json)).toEqual({ key: "falKey", value: "[redacted]" });
+ audit("install.setting_changed", null, { setting: "anthropic.key", from: "", to: "sk-ant-SECRET-3" });
+ expect(JSON.parse(last().meta_json)).toEqual({ setting: "anthropic.key", from: "", to: "[redacted]" });
+ audit("install.setting_changed", { kind: "setting", id: "fal.key" }, { from: "old-SECRET", to: "new-SECRET" });
+ expect(JSON.parse(last().meta_json)).toEqual({ from: "[redacted]", to: "[redacted]" });
+ // An ordinary setting keeps its values.
+ audit("install.setting_changed", { kind: "setting", id: "engine.mode" }, { key: "engineMode", from: "both", to: "open" });
+ expect(JSON.parse(last().meta_json)).toEqual({ key: "engineMode", from: "both", to: "open" });
+ });
+
it("records a denial with the route and the reason", () => {
withScope({ actor: actor("u_alex"), method: "POST", path: "/api/loras" }, () => auditDenied("FORBIDDEN"));
expect(last().action).toBe("denied");