fix(ui): stop offering an organisation the binary cannot create (#2150)

The organisations page could create one, and POST /api/orgs is not served: the
binary resolves a single organisation from the credential. The dialog and the
client method go, and the page lists what exists.

The gateway test missed it because it compared paths, not methods. It now reads
each request the client makes with the method it asks for, so a call to a path
the binary serves for another verb fails the gate.
This commit is contained in:
sam committed 2026-11-27 19:40:21 +11:00
1 parent 61d486fdc0
commit bf17e2471b
4 files changed
+84 -128

No files matched your search

+1 -5
View File
@@ -185,7 +185,7 @@ async function request<T = unknown>(
export const api = { export const api = {
// The archie binary's module API; the wire types are below the object. // The archie binary's module API; the wire types are below the object.
runs: (limit = 200, workflowId?: string, sysQuery?: string) => runs: (limit = 50, workflowId?: string, sysQuery?: string) =>
request<Run[]>("/api/runs" + qs({ limit, workflow_id: workflowId, sys_query: sysQuery })), request<Run[]>("/api/runs" + qs({ limit, workflow_id: workflowId, sys_query: sysQuery })),
run: (id: string) => request<RunTrail>(`/api/runs/${encodeURIComponent(id)}`), run: (id: string) => request<RunTrail>(`/api/runs/${encodeURIComponent(id)}`),
/** Queues a parked run again from the step that parked it, or from `from`. */ /** Queues a parked run again from the step that parked it, or from `from`. */
@@ -401,10 +401,6 @@ export const api = {
deletePolicy: (policy: unknown) => deletePolicy: (policy: unknown) =>
request<void>("/api/access/policies", { method: "DELETE", body: policy, parse: false }), request<void>("/api/access/policies", { method: "DELETE", body: policy, parse: false }),
orgs: <T = unknown>() => request<T>("/api/orgs"), orgs: <T = unknown>() => request<T>("/api/orgs"),
// orgCreate makes an org with its default workspace and first owner; only
// an instance admin may.
orgCreate: <T = unknown>(org: { id: string; name: string; owner_identity: string }) =>
request<T>("/api/orgs", { method: "POST", body: org }),
org: <T = unknown>(id: string) => request<T>(`/api/orgs/${encodeURIComponent(id)}`), org: <T = unknown>(id: string) => request<T>(`/api/orgs/${encodeURIComponent(id)}`),
// renameOrg changes the org's display name; expected_version refuses a save // renameOrg changes the org's display name; expected_version refuses a save
// made from a name someone else has since changed. // made from a name someone else has since changed.
-105
View File
@@ -1,105 +0,0 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, ref } from "vue";
import { Plus } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useOrgStore } from "@/stores/org";
import type { Org } from "./org";
/** Creates an org with its default workspace and first owner, then opens it. */
const open = ref(false);
const id = ref("");
const name = ref("");
const owner = ref("");
const error = ref("");
const busy = ref(false);
const identities = useOrgStore();
// The owner has to be an identity that already exists, so the candidates are the
// members of the caller's organisation.
const people = computed(() =>
(identities.membersByOrg.get(identities.homeOrg) ?? []).filter((member) => member.kind !== "system" && member.status === "active"),
);
function opened(value: boolean): void {
open.value = value;
if (value) {
void identities.loadOrg()
.then(() => identities.readMembers(identities.homeOrg))
.catch((cause) => (error.value = describeError(cause, errors.common.unknown)));
}
}
async function create(): Promise<void> {
busy.value = true;
try {
const created = await api.orgCreate<{ org: Org }>({
id: id.value.trim(),
name: name.value.trim(),
owner_identity: owner.value,
});
await identities.loadOrg(true);
identities.viewOrg(created.org.id);
open.value = false;
id.value = name.value = owner.value = error.value = "";
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
</script>
<template>
<Dialog :open="open" @update:open="opened">
<DialogTrigger as-child>
<Button size="sm" variant="outline"><Plus data-icon="inline-start" />New org</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>New org</DialogTitle>
</DialogHeader>
<form id="new-org" class="flex flex-col gap-3" @submit.prevent="create">
<Input v-model="name" placeholder="Name" aria-label="Org name" required />
<Input v-model="id" class="font-mono" placeholder="id" aria-label="Org id" required />
<Select v-model="owner">
<SelectTrigger class="w-full" aria-label="Owner">
<SelectValue placeholder="Owner" />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="person in people" :key="person.identity_id" :value="person.identity_id">
{{ person.display_name }}
</SelectItem>
</SelectContent>
</Select>
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
</form>
<DialogFooter>
<Button
type="submit"
form="new-org"
:disabled="!id.trim() || !name.trim() || !owner || busy"
>Create</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
+1 -2
View File
@@ -20,7 +20,6 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty"; import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Item, ItemActions, ItemContent, ItemDescription, ItemGroup, ItemTitle } from "@/components/ui/item"; import { Item, ItemActions, ItemContent, ItemDescription, ItemGroup, ItemTitle } from "@/components/ui/item";
import NewOrgDialog from "@/org/NewOrgDialog.vue";
import { useOrgStore } from "@/stores/org"; import { useOrgStore } from "@/stores/org";
import { errors } from "@/copy/errors"; import { errors } from "@/copy/errors";
import { describeError } from "@/lib/api"; import { describeError } from "@/lib/api";
@@ -51,7 +50,7 @@ function open(id: string): void {
<template> <template>
<div> <div>
<PageHeader title="Organisations"><NewOrgDialog /></PageHeader> <PageHeader title="Organisations" />
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert> <Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert>
<Empty v-else-if="!orgs.length"><EmptyHeader><EmptyTitle>No organisations</EmptyTitle></EmptyHeader></Empty> <Empty v-else-if="!orgs.length"><EmptyHeader><EmptyTitle>No organisations</EmptyTitle></EmptyHeader></Empty>
<ItemGroup v-else class="gap-2"> <ItemGroup v-else class="gap-2">
+82 -16
View File
@@ -29,24 +29,73 @@ const TYPED_TEMPLATES: Record<string, string[]> = {
// normalise rewrites a written path into the shape the OpenAPI document uses: // normalise rewrites a written path into the shape the OpenAPI document uses:
// one parameter per substitution, no query string, no trailing punctuation. // one parameter per substitution, no query string, no trailing punctuation.
function normalise(path: string): string { function normalise(path: string): string {
let out = path let out = "";
.replace(/\$\{encodeURIComponent\([^)]*\)\}/g, "{}") for (let i = 0; i < path.length; i++) {
.replace(/\$\{[^}]*\}/g, "{}") if (path[i] !== "$" || path[i + 1] !== "{") {
.replace(/\{[^}]*\}/g, "{}"); out += path[i];
continue;
}
// A substitution is one parameter. One that builds a query (an `after`
// cursor, say) is not part of the path, so the path ends there.
let depth = 0;
let end = i + 1;
for (; end < path.length; end++) {
if (path[end] === "{") depth++;
else if (path[end] === "}" && --depth === 0) break;
}
// A line the scan cut short leaves the substitution unclosed: the path
// ends there.
if (end >= path.length) break;
const inner = path.slice(i + 2, end);
if (inner.includes("?") || inner.includes("qs(")) break;
out += "{}";
i = end;
}
const query = out.indexOf("?"); const query = out.indexOf("?");
if (query >= 0) out = out.slice(0, query); if (query >= 0) out = out.slice(0, query);
const partial = out.indexOf("$"); return out.replace(/\{[^}]*\}/g, "{}").replace(/[.,;:)]+$/, "").replace(/\/+$/, "");
if (partial >= 0) out = out.slice(0, partial);
return out.replace(/[.,;:)]+$/, "").replace(/\/+$/, "");
} }
function yamlPaths(yaml: string): Set<string> { interface Operation {
const served = new Set<string>(); method: string;
path: string;
}
// operations reads what the binary serves: every method under every path.
function operations(yaml: string): Operation[] {
const out: Operation[] = [];
let path = "";
for (const line of yaml.split("\n")) { for (const line of yaml.split("\n")) {
const m = /^ {2}(\/[A-Za-z0-9_\-{}/.]*):\s*$/.exec(line); const dir = /^ {2}(\/[A-Za-z0-9_\-{}/.]*):\s*$/.exec(line);
if (m) served.add(normalise(m[1])); if (dir) {
path = normalise(dir[1]);
continue;
} }
return served; const op = /^ {4}(get|post|put|delete|patch):\s*$/.exec(line);
if (op && path) out.push({ method: op[1].toUpperCase(), path });
}
return out;
}
// calls reads every request the client makes: the method it asks for and the
// path it asks it on. A call that names two paths (one per branch) is two
// requests, which is what a person pressing either button causes.
function calls(src: string): Operation[] {
const out: Operation[] = [];
for (const m of src.matchAll(/\b(request|send)\b/g)) {
const open = src.indexOf("(", m.index ?? 0);
if (open < 0) continue;
let depth = 0;
let end = open;
for (; end < src.length; end++) {
if (src[end] === "(") depth++;
else if (src[end] === ")" && --depth === 0) break;
}
const call = src.slice(open, end + 1);
const method = (/method:\s*"([A-Za-z]+)"/.exec(call)?.[1] ?? "GET").toUpperCase();
for (const p of call.matchAll(/["\'`](\/api\/[^"\'`]*)["\'`]/g)) out.push({ method, path: normalise(p[1]) });
}
return out;
} }
function sourceFiles(dir: string): string[] { function sourceFiles(dir: string): string[] {
@@ -60,19 +109,36 @@ function sourceFiles(dir: string): string[] {
} }
test("every typed template expands to a served operation", () => { test("every typed template expands to a served operation", () => {
const served = yamlPaths(readFileSync(OPENAPI, "utf8")); const served = new Set(operations(readFileSync(OPENAPI, "utf8")).map((o) => `${o.method} ${o.path}`));
for (const [template, values] of Object.entries(TYPED_TEMPLATES)) { for (const [template, values] of Object.entries(TYPED_TEMPLATES)) {
for (const value of values) { for (const value of values) {
const path = normalise(template.replace("{}", value));
for (const method of ["GET", "PUT"]) {
assert.ok( assert.ok(
served.has(normalise(template.replace("{}", value))), served.has(`${method} ${path}`),
`${template} expands to ${value}, which the binary does not serve`, `${method} ${template} expands to ${value}, which the binary does not serve`,
); );
} }
} }
}
});
// Guards the hole the first version of this test had: it compared paths, so a
// call asking for a method the binary does not serve on a path it does passed.
test("every operation the client asks for is served, with that method", () => {
const served = new Set(operations(readFileSync(OPENAPI, "utf8")).map((o) => `${o.method} ${o.path}`));
assert.ok(served.size > 100, `read ${served.size} served operations`);
const missing = calls(readFileSync(join(SRC, "lib", "api.ts"), "utf8"))
.filter((call) => !TEMPLATED_BY_SERVER.test(call.path) && !TYPED_TEMPLATES[call.path])
.filter((call) => !served.has(`${call.method} ${call.path}`))
.map((call) => `${call.method} ${call.path}`);
assert.deepEqual([...new Set(missing)].sort(), [], "the client asks for operations the binary does not serve");
}); });
test("every API path the dashboard calls is served", () => { test("every API path the dashboard calls is served", () => {
const served = yamlPaths(readFileSync(OPENAPI, "utf8")); const served = new Set(operations(readFileSync(OPENAPI, "utf8")).map((o) => o.path));
assert.ok(served.size > 100, `read ${served.size} served paths`); assert.ok(served.size > 100, `read ${served.size} served paths`);
const unserved = new Map<string, string[]>(); const unserved = new Map<string, string[]>();