mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
fix(admin): guard revisions and tenant targets
Read-time authorization alone cannot protect concurrent edits. Guard revisions, current roles and destination ownership in the write transaction, and use per-group endpoints for isolated changes.
This commit is contained in:
1 parent
4fc784ab9f
commit
2ec541ad7c
10 files changed
+2615
-300
No files matched your search
+80
-48
@@ -1,5 +1,13 @@
|
||||
import type { FilterNode } from "./types";
|
||||
import { log } from "./lib/log";
|
||||
import { canUseD1 } from "./storage/d1";
|
||||
import {
|
||||
ConfigConflictError,
|
||||
groupVersion,
|
||||
groupVersionBump,
|
||||
groupVersionGuard,
|
||||
runGuarded,
|
||||
} from "./storage/config-store";
|
||||
|
||||
export interface NamedFragment {
|
||||
id: string;
|
||||
@@ -15,59 +23,83 @@ interface D1FragmentRow {
|
||||
node: string;
|
||||
}
|
||||
|
||||
export async function loadFragments(db: D1Database): Promise<NamedFragment[]> {
|
||||
try {
|
||||
const stmt = db.prepare("SELECT id, group_id, name, node FROM d1_fragments ORDER BY id");
|
||||
if (typeof stmt.all !== "function") return [];
|
||||
const { results } = await stmt.all<D1FragmentRow>();
|
||||
if (!results || results.length === 0) return [];
|
||||
return results.map((r) => ({
|
||||
id: r.id,
|
||||
groupId: r.group_id || undefined,
|
||||
name: r.name,
|
||||
node: JSON.parse(r.node) as FilterNode,
|
||||
}));
|
||||
} catch (err) {
|
||||
log.warn({ err }, "Failed to load fragments from D1");
|
||||
return [];
|
||||
}
|
||||
/**
|
||||
* Named filter fragments, optionally of one group. Without a usable D1
|
||||
* binding there are none; a D1 error propagates, because callers replace a
|
||||
* group's whole list and must never build that list from a failed read. An
|
||||
* unreadable row is skipped (logged) — or, with `strict`, an error: a write
|
||||
* replacing the group's list must never silently delete a row nobody saw.
|
||||
*/
|
||||
export async function loadFragments(
|
||||
db: D1Database,
|
||||
groupId?: string,
|
||||
strict = false,
|
||||
): Promise<NamedFragment[]> {
|
||||
if (!canUseD1(db)) return [];
|
||||
const stmt =
|
||||
groupId === undefined
|
||||
? db.prepare("SELECT id, group_id, name, node FROM d1_fragments ORDER BY id")
|
||||
: db
|
||||
.prepare(
|
||||
"SELECT id, group_id, name, node FROM d1_fragments WHERE group_id = ? ORDER BY id",
|
||||
)
|
||||
.bind(groupId);
|
||||
const { results } = await stmt.all<D1FragmentRow>();
|
||||
return (results ?? []).flatMap((r) => {
|
||||
try {
|
||||
return [
|
||||
{
|
||||
id: r.id,
|
||||
groupId: r.group_id || undefined,
|
||||
name: r.name,
|
||||
node: JSON.parse(r.node) as FilterNode,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
if (strict) {
|
||||
throw new Error(`filter fragment "${r.id}" is unreadable; repair the row before saving`);
|
||||
}
|
||||
log.warn({ err, id: r.id }, "Ignoring malformed filter fragment");
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveFragments(db: D1Database, fragments: NamedFragment[]): Promise<void> {
|
||||
/**
|
||||
* Replace one group's fragments in a single transaction; other groups are
|
||||
* untouched. `expect` sees the stored fragments first and may throw; the write
|
||||
* then commits only if nothing changed the group in between (version guard).
|
||||
*/
|
||||
export async function saveGroupFragments(
|
||||
db: D1Database,
|
||||
groupId: string,
|
||||
fragments: NamedFragment[],
|
||||
opts?: {
|
||||
expect?: (current: NamedFragment[]) => void | Promise<void>;
|
||||
/** Guard statements committed first in the write (see `GuardedWrite.guards`). */
|
||||
guards?: (db: D1Database) => D1PreparedStatement[];
|
||||
},
|
||||
): Promise<NamedFragment[]> {
|
||||
if (!canUseD1(db)) throw new Error("Filter fragments require the D1 binding");
|
||||
const version = await groupVersion(db, groupId);
|
||||
if (version == null) throw new ConfigConflictError(`group "${groupId}" does not exist`);
|
||||
// Loaded strictly even without `expect`: an unreadable row aborts here.
|
||||
const stored = await loadFragments(db, groupId, true);
|
||||
await opts?.expect?.(stored);
|
||||
const now = Date.now();
|
||||
|
||||
// Load existing fragments to determine what to delete
|
||||
const existing = await loadFragments(db);
|
||||
const existingKeys = new Set(existing.map((f) => `${f.id}:${f.groupId ?? ""}`));
|
||||
const newKeys = new Set(fragments.map((f) => `${f.id}:${f.groupId ?? ""}`));
|
||||
|
||||
const statements: D1PreparedStatement[] = [];
|
||||
|
||||
// Delete fragments that are no longer present
|
||||
for (const key of existingKeys) {
|
||||
if (!newKeys.has(key)) {
|
||||
const [id, groupId] = key.split(":");
|
||||
statements.push(
|
||||
db.prepare("DELETE FROM d1_fragments WHERE id = ? AND group_id = ?").bind(id, groupId),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Upsert all fragments
|
||||
for (const f of fragments) {
|
||||
statements.push(
|
||||
await runGuarded(db, [
|
||||
groupVersionGuard(db, groupId, version),
|
||||
...(opts?.guards?.(db) ?? []),
|
||||
groupVersionBump(db, groupId),
|
||||
db.prepare("DELETE FROM d1_fragments WHERE group_id = ?").bind(groupId),
|
||||
...fragments.map((f) =>
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO d1_fragments (id, group_id, name, node, version, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, 1, ?, ?)
|
||||
ON CONFLICT(id, group_id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
node = excluded.node,
|
||||
updated_at = excluded.updated_at`,
|
||||
VALUES (?, ?, ?, ?, 1, ?, ?)`,
|
||||
)
|
||||
.bind(f.id, f.groupId ?? "", f.name, JSON.stringify(f.node), now, now),
|
||||
);
|
||||
}
|
||||
|
||||
await db.batch(statements);
|
||||
.bind(f.id, groupId, f.name, JSON.stringify(f.node), now, now),
|
||||
),
|
||||
]);
|
||||
return loadFragments(db, groupId);
|
||||
}
|
||||
+1240
-217
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
import type { H3Event } from "h3";
|
||||
import { createError, getHeader } from "h3";
|
||||
import type { Group, GroupRole } from "../types";
|
||||
import { getAdminSession, isDebugMode, type AdminSession } from "./session";
|
||||
import { authLogin, getAdminSession, isDebugMode, type AdminSession } from "./session";
|
||||
import {
|
||||
loadGroups,
|
||||
resolveScope,
|
||||
@@ -28,14 +28,15 @@ const AUTH_KEY = "auth";
|
||||
export async function loadAuth(event: H3Event): Promise<AuthContext | null> {
|
||||
const env = cfEnv(event);
|
||||
initConfigStore(env);
|
||||
const groups = await loadGroups(env.KV);
|
||||
if (isDebugMode(env)) {
|
||||
const session: AdminSession = { userId: "debug", login: "debug" };
|
||||
return { session, scope: resolveScope(env, groups, session.userId, session.login), groups };
|
||||
}
|
||||
const session = await getAdminSession(env.KV, getHeader(event, "cookie"));
|
||||
// The session first: a request without one reads no configuration.
|
||||
const session: AdminSession | null = isDebugMode(env)
|
||||
? { userId: "debug", login: "debug" }
|
||||
: await getAdminSession(env.KV, getHeader(event, "cookie"), env.DB);
|
||||
if (!session) return null;
|
||||
const scope = resolveScope(env, groups, session.userId, session.login);
|
||||
// Access checks read the authoritative store: a membership revoked in
|
||||
// another isolate must not linger in this one's cache.
|
||||
const groups = await loadGroups(env.KV, { fresh: true });
|
||||
const scope = resolveScope(env, groups, session.userId, authLogin(session));
|
||||
return { session, scope, groups };
|
||||
}
|
||||
|
||||
|
||||
+86
-13
@@ -1,12 +1,28 @@
|
||||
import { log } from "../lib/log";
|
||||
import type { Group } from "../types";
|
||||
import { updateGroup } from "./groups";
|
||||
|
||||
/**
|
||||
* Per-group webhook tenant secrets. A group can opt into its own webhook
|
||||
* ingress (`POST /webhook/{groupId}`) with an independent secret, so SaaS
|
||||
* users can configure their own GitHub/Gitea/custom webhooks without sharing
|
||||
* (or even knowing) the operator's global secrets.
|
||||
*
|
||||
* Secrets are keyed by the group's immutable `instance`: a rename keeps the
|
||||
* secret without moving anything, and a group re-created under a former id
|
||||
* never inherits the old group's secret. A secret stored before instances
|
||||
* existed (`tenant:{groupId}`) is still read — only by the group that had that
|
||||
* id back then (`legacyId`) — until the secret is regenerated or removed. It is
|
||||
* never copied over: a lazy copy could race a rotation and resurrect the old
|
||||
* secret.
|
||||
*/
|
||||
const TENANT_KEY = (groupId: string): string => `tenant:${groupId}`;
|
||||
type TenantGroup = Pick<Group, "id" | "instance" | "legacyId" | "webhookSecret">;
|
||||
|
||||
const LEGACY_KEY = (groupId: string): string => `tenant:${groupId}`;
|
||||
const INSTANCE_KEY = (instance: string): string => `tenant:i:${instance}`;
|
||||
|
||||
function keyOf(group: TenantGroup): string {
|
||||
return group.instance ? INSTANCE_KEY(group.instance) : LEGACY_KEY(group.id);
|
||||
}
|
||||
|
||||
/** 32 random bytes → 64 hex chars. */
|
||||
export function generateTenantSecret(): string {
|
||||
@@ -17,22 +33,79 @@ export function generateTenantSecret(): string {
|
||||
.join("");
|
||||
}
|
||||
|
||||
export async function getTenantSecret(kv: KVNamespace, groupId: string): Promise<string | null> {
|
||||
try {
|
||||
return await kv.get(TENANT_KEY(groupId), "text");
|
||||
} catch (err) {
|
||||
log.warn({ err, groupId }, "Failed to read tenant webhook secret");
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* The group's webhook secret, or null when it has none. Read errors propagate:
|
||||
* a failed read must never pass for "no secret".
|
||||
*/
|
||||
export async function getTenantSecret(kv: KVNamespace, group: TenantGroup): Promise<string | null> {
|
||||
// Stored with the group (how secrets are written now); KV keys are read for
|
||||
// secrets set before that.
|
||||
// "" is an explicit "none" (removed): no older KV copy counts then.
|
||||
if (group.webhookSecret != null) return group.webhookSecret || null;
|
||||
const secret = await kv.get(keyOf(group), "text");
|
||||
// Only the group that had the id before instances may use a pre-instance
|
||||
// secret — not a group created since, nor one renamed to that id.
|
||||
if (secret || !group.instance || !group.legacyId) return secret;
|
||||
return kv.get(LEGACY_KEY(group.legacyId), "text");
|
||||
}
|
||||
|
||||
/**
|
||||
* The pre-instance key the group's secret may still be found under. Keys
|
||||
* under its current id are left alone: they may belong to the group that had
|
||||
* that id before instances (now under another id).
|
||||
*/
|
||||
function legacyKeys(group: TenantGroup): string[] {
|
||||
return group.legacyId ? [LEGACY_KEY(group.legacyId)] : [];
|
||||
}
|
||||
|
||||
/** Generate (or regenerate) the group's webhook secret. */
|
||||
export async function setTenantSecret(kv: KVNamespace, groupId: string): Promise<string> {
|
||||
export async function setTenantSecret(kv: KVNamespace, group: TenantGroup): Promise<string> {
|
||||
const secret = generateTenantSecret();
|
||||
await kv.put(TENANT_KEY(groupId), secret);
|
||||
await kv.put(keyOf(group), secret);
|
||||
// The new secret replaces the group's pre-instance one.
|
||||
if (group.instance) for (const key of legacyKeys(group)) await kv.delete(key);
|
||||
return secret;
|
||||
}
|
||||
|
||||
export async function deleteTenantSecret(kv: KVNamespace, groupId: string): Promise<void> {
|
||||
await kv.delete(TENANT_KEY(groupId));
|
||||
/**
|
||||
* Generate (or regenerate) the group's webhook secret, stored with the group
|
||||
* in a compare-and-swap: `check` sees the group as it is at that moment and
|
||||
* may throw (e.g. the writer is no longer an owner), so a request authorized
|
||||
* earlier can never overwrite a later rotation. Older KV copies are dropped.
|
||||
* Null when the group does not exist.
|
||||
*/
|
||||
export async function rotateTenantSecret(
|
||||
kv: KVNamespace,
|
||||
groupId: string,
|
||||
check: (current: Group) => void,
|
||||
): Promise<string | null> {
|
||||
const secret = generateTenantSecret();
|
||||
const saved = await updateGroup(kv, groupId, (g) => {
|
||||
check(g);
|
||||
return { ...g, webhookSecret: secret };
|
||||
});
|
||||
if (!saved) return null;
|
||||
await deleteTenantSecret(kv, saved).catch(() => undefined);
|
||||
return secret;
|
||||
}
|
||||
|
||||
/** Remove the group's webhook secret (the same compare-and-swap as rotation). */
|
||||
export async function removeTenantSecret(
|
||||
kv: KVNamespace,
|
||||
groupId: string,
|
||||
check: (current: Group) => void,
|
||||
): Promise<boolean> {
|
||||
const saved = await updateGroup(kv, groupId, (g) => {
|
||||
check(g);
|
||||
return { ...g, webhookSecret: null };
|
||||
});
|
||||
if (!saved) return false;
|
||||
await deleteTenantSecret(kv, saved);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drop the KV copies of a group's secret (from before secrets lived with the group). */
|
||||
export async function deleteTenantSecret(kv: KVNamespace, group: TenantGroup): Promise<void> {
|
||||
await kv.delete(keyOf(group));
|
||||
for (const key of legacyKeys(group)) await kv.delete(key);
|
||||
}
|
||||
@@ -43,7 +43,10 @@ export async function processWebhook(
|
||||
if (!groups.some((g) => g.id === tenantId)) {
|
||||
return { status: 404, body: { error: "Group not found" } };
|
||||
}
|
||||
const secret = await getTenantSecret(env.KV, tenantId);
|
||||
const secret = await getTenantSecret(
|
||||
env.KV,
|
||||
groups.find((g) => g.id === tenantId)!,
|
||||
);
|
||||
if (!secret) {
|
||||
return { status: 404, body: { error: "Webhook disabled for this group" } };
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
adminApiMe,
|
||||
adminApiGroupsGet,
|
||||
adminApiGroupsPut,
|
||||
adminGroupCreate,
|
||||
adminGroupUpdate,
|
||||
adminGroupDelete,
|
||||
adminApiRoutesGet,
|
||||
adminApiRoutesPut,
|
||||
adminApiLogs,
|
||||
@@ -40,6 +43,11 @@ export default defineEventHandler((event) => {
|
||||
if (seg[0] === "groups" && seg.length === 1) {
|
||||
if (method === "GET") return adminApiGroupsGet(event);
|
||||
if (method === "PUT") return adminApiGroupsPut(event);
|
||||
if (method === "POST") return adminGroupCreate(event);
|
||||
}
|
||||
if (seg[0] === "groups" && seg.length === 2) {
|
||||
if (method === "PUT") return adminGroupUpdate(event, seg[1]!);
|
||||
if (method === "DELETE") return adminGroupDelete(event, seg[1]!);
|
||||
}
|
||||
if (seg[0] === "routes" && seg.length === 1) {
|
||||
if (method === "GET") return adminApiRoutesGet(event);
|
||||
|
||||
Reference in new issue
Block a user