diff --git a/changes/fix-kit-content-review.md b/changes/fix-kit-content-review.md new file mode 100644 index 0000000..58182a4 --- /dev/null +++ b/changes/fix-kit-content-review.md @@ -0,0 +1,12 @@ +### Fixed + +- **A content CLI from a config shows and checks its write keys.** `src/config.ts` passes cli-core's content write + keys and their `ask` levels, so `posts create --dry-run` no longer says `allow` for a write that asks, and + `--allow-delete` names `posts.delete.force`. The `api` group's create and update of the written route check + `posts.create` and `posts.update` too, so a deny on a `posts` command covers the raw write (WC-PERM-22). +- **A WordPress CLI never offers making an application password.** WordPress answers the new password in clear and + its index marks no field secret, so `scripts/spec-model.ts` leaves that route out. Writes that install a plugin or + change settings, users, comments, templates, widgets, menus or navigation ask by default. +- **The content and `api` tests check what they send.** `src/content-options.test.ts` checks each write's result, + and that `posts.create: deny` stops the `api` write. `src/api.test.ts` checks every option's value, reads a second + page with `--all`, and checks the WordPress writes that ask. diff --git a/kit/README.md b/kit/README.md index 9079777..dc2edb6 100644 --- a/kit/README.md +++ b/kit/README.md @@ -130,7 +130,13 @@ read before the CLI has `node_modules`: its import resolves to the kit's own cli `source.writes` `posts create|update|publish|unpublish|delete`) over `contentSourceFromManifest`. A write goes through the `api` group's own write path with its keys, and a key the `posts` command already asked is not asked again. `src/content-contracts.test.ts` runs the source, sync and write contracts and a sync through the CLI over - `contentManifestFake`, a fake built from the config and the generated API. + `contentManifestFake`, a fake built from the config and the generated API. With `source.writes`, `src/config.ts` + passes the content keys and their `ask` levels to `--dry-run`, and the `api` group's create and update of the + written route check `posts.create` and `posts.update` too, so a deny on a `posts` command covers the raw write. + `src/content-options.test.ts` checks what each write changed. +- A WordPress CLI (`wp-json`) leaves out the route that makes an application password, whose answer holds the new + password in clear, and its `api` writes that install a plugin, change settings, users, comments, templates, + widgets, menus or navigation ask by default. - `pnpm source:check` checks the source's operations and every path its map reads against the generated API, after `pnpm generate`. diff --git a/kit/seeds/config/src/content-options.test.ts b/kit/seeds/config/src/content-options.test.ts index 2cbc079..5f392fc 100644 --- a/kit/seeds/config/src/content-options.test.ts +++ b/kit/seeds/config/src/content-options.test.ts @@ -8,7 +8,7 @@ import { SOURCE } from "./generated/wirecat-config.js" import { FAKE_API_TOKEN, FAKE_SITE, fakeServiceApi } from "./testing/fake-api.js" import { runCli } from "./testing/harness.js" -// The fake answers example rows, so this proves every content command and option runs, not what a real post holds. +// Each write's answer is the post as the fake holds it after the write, read back through the source's map. it("every option of the content commands runs over a synced copy", async () => { const keyring = memoryKeyring() const [login, password] = FAKE_API_TOKEN.split(":") as [string, string] @@ -46,34 +46,78 @@ it("every option of the content commands runs over a synced copy", async () => { expect(service.refusals).toEqual([]) // A source without writes has no posts create, update, publish, unpublish or delete. if (!SOURCE.writes) return - for (const argv of [ - [ + type Answer = { item: { post?: Record } } + const wrote = async (argv: string[]) => { + const answer = await ran([...argv, "--yes"]) + expect(answer.code, `${argv.join(" ")}: ${answer.err}`).toBe(0) + return (answer.json() as Answer).item.post ?? {} + } + const created = await wrote([ + "posts", + "create", + "--title", + "Notes", + "--text-file", + text, + "--description", + "Short", + "--slug", + "notes", + "--tags", + tag, + "--type", + "post", + ]) + expect(created).toMatchObject({ status: "draft", title: "Notes", excerpt: "Short", slug: "notes", terms: [tag] }) + expect(created.body).toContain("A short post.") + expect( + await wrote([ "posts", - "create", - "--title", - "Notes", + "update", + first, "--text-file", text, "--description", - "Short", + "New", "--slug", - "notes", + "new", "--tags", tag, - "--type", - "post", - "--yes", - ], - ["posts", "update", first, "--text-file", text, "--description", "New", "--slug", "new", "--tags", tag, "--yes"], - ["posts", "update", first, "--text-file", text, "--replace-body", "--yes"], - ["posts", "publish", first, "--yes"], - ["posts", "unpublish", first, "--yes"], - ["posts", "publish", first, "--at-time", "2030-01-01T10:00:00Z", "--yes"], - ["posts", "delete", second, "--yes"], - ["posts", "delete", second, "--allow-delete", "--yes"], - ]) { - const answer = await ran(argv) - expect(answer.code, `${argv.join(" ")}: ${answer.err}`).toBe(0) - } + ]), + ).toMatchObject({ excerpt: "New", slug: "new", terms: [tag] }) + expect(await wrote(["posts", "update", first, "--text-file", text, "--replace-body"])).toMatchObject({ + body: expect.stringContaining("A short post."), + }) + expect(await wrote(["posts", "publish", first])).toMatchObject({ status: "published" }) + expect(await wrote(["posts", "unpublish", first])).toMatchObject({ status: "draft" }) + expect(await wrote(["posts", "publish", first, "--at-time", "2030-01-01T10:00:00Z"])).toMatchObject({ + status: "scheduled", + scheduled_for: "2030-01-01T10:00:00.000Z", + }) + expect(await wrote(["posts", "delete", second])).toMatchObject({ status: "trashed" }) + await wrote(["posts", "delete", second, "--allow-delete"]) + expect(service.ids("post")).not.toContain(second) expect(service.refusals).toEqual([]) + + // The same write through the api group checks the content command's key (WC-PERM-22). + const create = API.manifest.operations.find( + (operation) => operation.id === (SOURCE.writes as { create?: { operation: string } }).create?.operation, + ) + if (!create) return + // --dry-run names what the write checks: the content key at its built-in level, and the api key it sends through. + type Preview = { item: { permission: { key: string; level: string; also?: { key: string }[] } } } + const preview = async (argv: string[]) => ((await ran([...argv, "--dry-run"])).json() as Preview).item.permission + const drafted = await preview(["posts", "create", "--title", "Notes"]) + expect(drafted).toMatchObject({ key: "posts.create", level: "ask" }) + expect(drafted.also?.map(({ key }) => key)).toContain(`api.${create.command}`) + const erased = await preview(["posts", "delete", first, "--allow-delete"]) + expect(erased).toMatchObject({ key: "posts.delete", level: "ask" }) + expect(erased.also?.map(({ key }) => key)).toContain("posts.delete.force") + const trash = API.manifest.operations.find( + (operation) => operation.id === (SOURCE.writes as { trash?: { operation: string } }).trash?.operation, + ) + if (trash) expect(erased.also?.map(({ key }) => key)).toContain(`api.${trash.command}`) + expect((await ran(["config", "set", "permissions.posts.create", "deny"])).code).toBe(0) + const refused = await ran(["api", create.command, "--body", "{}", "--dry-run"]) + expect(refused.json()).toMatchObject({ error: { code: "permission_error", details: { permission: "posts.create" } } }) }) diff --git a/kit/seeds/wp-json/scripts/spec-model.ts b/kit/seeds/wp-json/scripts/spec-model.ts index 6b833cc..046582d 100644 --- a/kit/seeds/wp-json/scripts/spec-model.ts +++ b/kit/seeds/wp-json/scripts/spec-model.ts @@ -4,6 +4,7 @@ import { type ApiModel, adaptOpenApi, type Override, readWpJson, wpJsonToOpenApi // SAMPLE: the WordPress namespaces the CLI offers. A plugin's namespace belongs to the sites that run the plugin; // batch/v1 is never offered, as one batch call runs other routes' writes past their own keys. const NAMESPACES = ["wp/v2"] +const APPLICATION_PASSWORDS = "/wp/v2/users/(?P(?:[\\d]+|me))/application-passwords" /** * The index as committed; readWpJson refuses one whose hash no longer matches provenance.json. The routes left out, @@ -12,10 +13,16 @@ const NAMESPACES = ["wp/v2"] export const specModel = async ( root: string, ): Promise<{ model: ApiModel; notes: string[]; overrides: Record }> => { - const { document, omissions, overrides } = wpJsonToOpenApi(readWpJson(join(root, "spec/clidev")), { + const index = readWpJson(join(root, "spec/clidev")) as { routes?: Record } + const { document, omissions, overrides } = wpJsonToOpenApi(index, { namespaces: NAMESPACES, - // SAMPLE: route → why the CLI leaves it out. - exclude: {}, + // SAMPLE: route → why the CLI leaves it out. WordPress answers a new application password in clear and the index + // marks no field secret, so cli-core cannot leave that one out itself; its list and delete-all go with it. + exclude: Object.fromEntries( + [APPLICATION_PASSWORDS] + .filter((route) => index.routes?.[route]) + .map((route) => [route, "its POST answers a new application password in clear. Sign in with session start"]), + ), }) return { model: adaptOpenApi(document), notes: omissions, overrides } } diff --git a/kit/seeds/wp-json/src/api.test.ts b/kit/seeds/wp-json/src/api.test.ts index 20c580b..1664786 100644 --- a/kit/seeds/wp-json/src/api.test.ts +++ b/kit/seeds/wp-json/src/api.test.ts @@ -55,7 +55,7 @@ const argsOf = (operation: Operation) => [ ...(operation.request?.schema ? ["--body", JSON.stringify(sampleOf({ type: "ref", ref: operation.request.schema }, definitions))] : []), - ...(operation.effect === "destructive" ? ["--yes"] : []), + ...(operation.effect === "read" ? [] : ["--yes"]), ] it("the spec offers operations", () => { @@ -153,25 +153,75 @@ it.each(API.manifest.operations.map((operation) => [operation.command, operation const argv = [ ...options, ...(sendsBytes(operation) ? ["--body-file", upload] : body === undefined ? [] : ["--body-file", bodyFile]), - ...(operation.effect === "destructive" ? ["--yes"] : []), + ...(operation.effect === "read" ? [] : ["--yes"]), ] const ran = await runCli(["personal", "api", operation.command, ...argv, "--json"], { service, env }) expect(ran.code, ran.err).toBe(0) expect(service.refusals).toEqual([]) + const [call] = service.calls + for (const parameter of operation.parameters) { + const sent = parameter.in === "path" ? call?.path : parameter.in === "query" ? call?.query : undefined + if (sent) + expect([sent[parameter.name]].flat().join(","), `--${apiFlagOf(parameter.name)}`).toBe( + String(sampleOf(parameter.schema, definitions)), + ) + } + if (body !== undefined && !sendsBytes(operation)) expect(call?.body).toEqual(body) if (!operation.pagination) return - // WordPress names its page count in X-WP-TotalPages; with one page, --all stops after the first. - const onePage = { + // WordPress names its page count in X-WP-TotalPages: --all reads each page up to it. + const twoPages = fake() + const counted = { fetch: async (input: string | URL | Request, init?: RequestInit) => { - const answer = await service.fetch(input, init) + const answer = await twoPages.fetch(input, init) const headers = new Headers(answer.headers) - headers.set("x-wp-totalpages", "1") + headers.set("x-wp-totalpages", "2") return new Response(answer.body, { status: answer.status, headers }) }, } const all = await runCli(["personal", "api", operation.command, ...argv, "--all", "--json"], { - service: onePage, + service: counted, env, }) expect(all.code, all.err).toBe(0) + expect(twoPages.calls).toHaveLength(2) + }, +) + +// Installing a plugin runs code on the site; a new user, a role or a site setting reaches every visitor. An index +// without one of these routes has nothing to ask. +const ASKS = [ + "plugins-create", + "settings-create", + "users-create", + "users-update", + "users-me-create", + "comments-create", + "comments-update", + "templates-create", + "template-parts-create", + "sidebars-update", + "widgets-create", + "widgets-update", + "menus-create", + "menus-update", + "menu-items-create", + "menu-items-update", + "navigation-create", + "navigation-update", +] +it.each(ASKS.filter((command) => API.manifest.operations.some((operation) => operation.command === command)))( + "%s asks before it writes", + async (command) => { + const service = fake() + const operation = API.manifest.operations.find((one) => one.command === command) as Operation + const path = operation.parameters + .filter((parameter) => parameter.in === "path") + .flatMap((parameter) => [`--${apiFlagOf(parameter.name)}`, String(sampleOf(parameter.schema, definitions))]) + const body = JSON.stringify(sampleOf({ type: "ref", ref: operation.request?.schema ?? "" }, definitions)) + const ran = await runCli(["personal", "api", command, ...path, "--body", body, "--json"], { service, env }) + expect(ran.json()).toMatchObject({ + error: { reason: "confirmation.required", details: { permission: expect.stringContaining(`api.${command}`) } }, + }) + expect(service.calls).toEqual([]) }, ) diff --git a/kit/src/config-wiring.ts b/kit/src/config-wiring.ts index 0c61f08..0adece8 100644 --- a/kit/src/config-wiring.ts +++ b/kit/src/config-wiring.ts @@ -205,3 +205,128 @@ export const withSourceCommands = (text: string, kind: SourceKind = "crm"): stri /^( +)apiCommand\(\),\n/m, `$1apiCommand(),\n$1...${kind}Commands(),\n`, ) + +// WordPress writes that install code, change a role or change what every visitor sees: cli-core lets any api write +// but a delete run unasked, so these ask (WC-PERM-7: a CLI only tightens). Only the ones the index has are kept. +export const WORDPRESS_ASKS = [ + "plugins-create", + "settings-create", + "users-create", + "users-update", + "users-me-create", + "comments-create", + "comments-update", + "templates-create", + "template-parts-create", + "sidebars-update", + "widgets-create", + "widgets-update", + "menus-create", + "menus-update", + "menu-items-create", + "menu-items-update", + "navigation-create", + "navigation-update", +] + +const SITE_WIDE_WRITES = [ + "// cli-core lets every api write but a delete run unasked. These install code, give a user a role, or change", + "// what every visitor sees, so they ask (WC-PERM-7: a CLI only tightens). A new comment is public at once.", + "const SITE_WIDE_WRITES = Object.fromEntries(", + ` ${JSON.stringify(WORDPRESS_ASKS)}`, + " .filter((command) => API.manifest.operations.some((operation) => operation.command === command))", + ' .map((command) => [`api.${command}`, "ask" as const]),', + ")", + "", +] + +/** A WordPress CLI that does not write content: the api group's site-wide writes ask. */ +export const withWordPressAsks = (text: string): string => + replaceOnce( + "src/config.ts", + text, + "export const permissions = commandPermissions(serviceApiPermissions(API))\n", + [ + "const api = serviceApiPermissions(API)", + "", + ...SITE_WIDE_WRITES, + "export const permissions = commandPermissions({ ...api, defaults: { ...api.defaults, ...SITE_WIDE_WRITES } })", + "", + ].join("\n"), + ) + +const CONTENT_PERMISSIONS = (service: string, wordpress: boolean) => + [ + 'type Verb = "create" | "update" | "trash" | "delete"', + "const writes = (SOURCE.writes ?? {}) as Partial>", + "const commandOf = (verb: Verb) =>", + " manifest.operations.find((operation) => operation.id === writes[verb]?.operation)?.command", + "", + "/**", + " * The content command each raw write does the same as, from the source's writes: `posts.create: deny` also stops", + " * `api ` (WC-PERM-22). Deletes need no entry: the generator gave them `posts.delete` already.", + " */", + "const COMMAND_KEYS: Readonly> = Object.fromEntries(", + ' (["create", "update"] as const).flatMap((verb) => {', + " const command = commandOf(verb)", + " return command ? [[command, `posts.${verb}`]] : []", + " }),", + ")", + "", + "// SAMPLE: your service's name. The keys a delete or a share checks come from `permissions` in", + "// scripts/generate.ts. The operations the api group cannot offer are left out: one that answers with a", + "// credential (the CLI signs in through `session`) and a body it cannot send, such as a multipart form.", + "export const API = {", + " manifest: {", + " ...manifest,", + " operations: serviceApiOperations(manifest).offered.map((operation) => {", + " const key = COMMAND_KEYS[operation.command]", + " return key ? { ...operation, permissions: [...(operation.permissions ?? []), { key }] } : operation", + " }),", + " },", + ` service: ${JSON.stringify(service)},`, + "}", + "", + "const api = serviceApiPermissions(API)", + "", + "/** The content commands write through the api group's operations, whose own keys the run checks too. */", + "const API_KEYS: Readonly> = Object.fromEntries(", + " (", + " [", + ' ["posts.create", commandOf("create")],', + ' ["posts.update", commandOf("update")],', + ' ["posts.publish", commandOf("update")],', + ' ["posts.unpublish", commandOf("update")],', + ' ["posts.delete", commandOf("trash") ?? commandOf("delete")],', + " ] as const", + " ).flatMap(([key, command]) => (command ? [[key, `api.${command}`]] : [])),", + ")", + "", + ...(wordpress ? SITE_WIDE_WRITES : []), + "export const permissions = commandPermissions({", + " extra: [...new Set([...api.extra, ...CONTENT_WRITE_KEYS])],", + " alsoChecks: (path) => {", + ' const own = API_KEYS[path.join(".")]', + " return [...api.alsoChecks(path), ...contentAlsoChecks(path), ...(own ? [own] : [])]", + " },", + ` defaults: { ...api.defaults, ${wordpress ? "...SITE_WIDE_WRITES, " : ""}...CONTENT_WRITE_DEFAULTS },`, + "})", + "", + ].join("\n") + +/** + * A content CLI that writes: the content commands' keys and levels reach `--dry-run`, and the api group's raw writes + * check them too. Before, `posts create --dry-run` said `allow` for a write that asks (FIND-2820). + */ +export const withContentPermissions = (text: string, service: string, wordpress: boolean): string => + each("src/config.ts", text, [ + [ + 'import * as manifest from "./generated/manifest.js"\n', + 'import { CONTENT_WRITE_DEFAULTS, CONTENT_WRITE_KEYS, contentAlsoChecks } from "@wirecat/cli-core/content"\n' + + 'import * as manifest from "./generated/manifest.js"\nimport { SOURCE } from "./generated/wirecat-config.js"\n', + ], + [ + /\/\/ SAMPLE: your service's name\.[\s\S]*?export const permissions = commandPermissions\(serviceApiPermissions\(API\)\)\n/, + CONTENT_PERMISSIONS(service, wordpress), + ], + ]) diff --git a/kit/src/new.ts b/kit/src/new.ts index ee092a3..ca7c405 100644 --- a/kit/src/new.ts +++ b/kit/src/new.ts @@ -13,7 +13,9 @@ import { SOURCE_SEEDS, type SourceKind, withConfigRunScope, + withContentPermissions, withSourceCommands, + withWordPressAsks, } from "./config-wiring.js" import type { LoadedConfig } from "./from-config.js" import { @@ -832,7 +834,12 @@ export const runNew = async ( }, ...(spec ? { - "src/config.ts": (text: string) => withApiPermissions(text, service), + "src/config.ts": (text: string) => { + const api = withApiPermissions(text, service) + if (loaded?.config.source && sourceKind(loaded.config) === "content" && sourceFlags?.writes) + return withContentPermissions(api, service ?? "Example Comments", spec === "wp-json") + return spec === "wp-json" ? withWordPressAsks(api) : api + }, "scripts/commands.ts": withApiSkill, "src/run-scope.test.ts": (text: string) => loaded diff --git a/kit/test/from-config.test.ts b/kit/test/from-config.test.ts index 9a25575..199a23b 100644 --- a/kit/test/from-config.test.ts +++ b/kit/test/from-config.test.ts @@ -167,6 +167,7 @@ describe("new --from-config", () => { expect(read(dir, "scripts/sync-spec.ts")).toContain('version: "6.9.5"') expect(read(dir, "scripts/generate.ts")).toContain('also: ["date", "date_gmt", "password"]') expect(read(dir, "scripts/spec-model.ts")).toContain('const NAMESPACES = ["wp/v2"]') + expect(read(dir, "src/config.ts")).toContain("...api.defaults, ...SITE_WIDE_WRITES") expect(read(dir, "src/commands/session.ts")).toContain('site: { example: "blog.example.com" }') expect(read(dir, "src/commands/api.ts")).toContain("serverVariables: siteOf") // The site the CLI was made against is not one it serves: each profile's own is added at run time.