Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions changes/feat-permission-values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
### Added

- **The `api` group checks a key by a field's value, as WordPress publishes by `status: "publish"`.** A manifest
permission with `values` (cli-base's `permissions.valueKeys`) applies when the call's JSON body or its query holds
one of those values: `{ key: "posts.publish", values: { status: ["publish", "future"] } }` asks for
`posts.publish` before `api post-wp-v2-posts --body '{"status":"publish"}'` and lets a draft through. Both places
count, because WordPress reads the same parameter from either. So a profile that denies publishing also stops an
agent that publishes through the raw `api` group. `--dry-run` and discovery show the key with
`with status publish or future`.

### Changed — may break callers

- **cli-core needs `@wirecat/cli-base` 0.118.0**, which carries the manifest's `values` and WordPress's
`wpJsonToOpenApi`. A CLI that pins an older cli-base raises it with this cli-core.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@
"@types/pngjs": "6.0.5",
"@types/ssh2": "1.15.5",
"@vitest/coverage-v8": "^5.0.5",
"@wirecat/cli-base": "0.117.0",
"@wirecat/cli-base": "0.118.0",
"@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
"ajv": "8.17.1",
"commander": "15.0.0",
Expand All @@ -342,7 +342,7 @@
},
"peerDependencies": {
"@napi-rs/canvas": ">=0.1.69 <2",
"@wirecat/cli-base": ">=0.117.0 <1.0.0",
"@wirecat/cli-base": ">=0.118.0 <1.0.0",
"commander": ">=15",
"mysql2": "^3.24.6",
"pg": "^8.23.1",
Expand Down
16 changes: 8 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 39 additions & 2 deletions src/cli/service-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ const operations: Operation[] = [
parameters: [page("block_id")],
permissions: [{ key: "documents.delete" }],
},
{
id: "create-post",
command: "create-post",
binding: { kind: "http", method: "POST", path: "/posts" },
effect: "write",
tags: ["Posts"],
parameters: [query("status")],
request: { required: false, confidence: "contract", schema: "PatchPage" },
permissions: [{ key: "posts.publish", values: { status: ["publish", "future"] } }],
},
{
id: "agent-batch",
command: "agent-batch",
Expand Down Expand Up @@ -477,6 +487,25 @@ describe("the shared service api group", () => {
expect(bare()).toEqual([{ method: "PATCH", url: "https://api.pages.test/v1/pages/p1", body: '{"in_trash":false}' }])
})

it("**a write whose field holds a publishing value checks its key**, in the body or the query, as WordPress", async () => {
const { cli, bare } = fixture({ "posts.publish": "deny", api: "allow" })
for (const call of [
["--body", '{"status":"publish","title":"t"}'],
["--body", '{"status":"future"}'],
["--status", "publish", "--body", '{"title":"t"}'],
]) {
const refused = await cli("work", "api", "create-post", ...call, "--json")
expect(refused.error).toMatchObject({ code: "permission_error" })
expect(refused.error?.message).toContain("posts.publish")
}
expect(bare()).toEqual([])
const draft = await cli("work", "api", "create-post", "--body", '{"status":"draft","title":"t"}', "--json")
expect(draft.code).toBe(0)
expect(bare()).toEqual([
{ method: "POST", url: "https://api.pages.test/v1/posts", body: '{"status":"draft","title":"t"}' },
])
})

it("**a read whose query flag deletes goes through the guard**, as an upload link that overwrites", async () => {
const { cli, bare } = fixture({ "documents.delete": "deny" })
const refused = await cli("work", "api", "upload-link", "--path", "/a.txt", "--overwrite", "true", "--json")
Expand Down Expand Up @@ -510,12 +539,20 @@ describe("the shared service api group", () => {
{ key: "documents.delete", when: "with in_trash or archived set" },
])
expect(alsoChecks(["api", "upload-link"])).toEqual([{ key: "documents.delete", when: "with overwrite set" }])
expect(alsoChecks(["api", "create-post"])).toEqual([
{ key: "posts.publish", when: "with status publish or future" },
])
expect(alsoChecks(["api", "agent-batch"])).toEqual([
{ key: "documents.delete", when: "an operation's action is delete" },
])
expect(alsoChecks(["api", "retrieve-a-page"])).toEqual([])
expect(defaults).toEqual({ "documents.delete": "ask", "documents.share": "ask", "api.delete-a-block": "ask" })
expect(extra).toEqual(["documents.delete", "documents.share"])
expect(defaults).toEqual({
"documents.delete": "ask",
"posts.publish": "ask",
"documents.share": "ask",
"api.delete-a-block": "ask",
})
expect(extra).toEqual(["documents.delete", "posts.publish", "documents.share"])
})

it("**--all reads every page** by the manifest's cursor, offset or link, in one run", async () => {
Expand Down
31 changes: 23 additions & 8 deletions src/cli/service-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,30 @@ const destructive = (operation: ManifestOperation) =>

const flagsOf = ({ body = [], query = [] }: OperationPermission) => [...body, ...query]

const valuesOf = ({ values = {} }: OperationPermission) => Object.entries(values)

/** Always, unless its flags or values name when; `with status publish or future`, `with archived set`. */
const whenOf = (permission: OperationPermission): string | undefined => {
const flags = flagsOf(permission)
const values = valuesOf(permission).map(([field, listed]) => `${field} ${listed.join(" or ")}`)
if (flags.length === 0 && values.length === 0) return undefined
return `with ${[...(flags.length > 0 ? [`${flags.join(" or ")} set`] : []), ...values].join(" or ")}`
}

/** A body field or query parameter holding one of the values: WordPress publishes from either. */
const holds = (value: unknown, listed: readonly string[]) => typeof value === "string" && listed.includes(value)

/** A flag counts unless it is absent or plainly false: a service may read `1` or `True` as true. */
const set = (value: unknown) => value !== undefined && value !== null && value !== false && value !== "false"

/** Whether a manifest key applies to this call: always, or when one of its flags is set. */
/** Whether a manifest key applies to this call: always, or when one of its flags is set or a field holds a value. */
const applies = (permission: OperationPermission, body: unknown, input: ApiCommandInput): boolean =>
flagsOf(permission).length === 0 ||
whenOf(permission) === undefined ||
(permission.body ?? []).some((field) => isObject(body) && set(body[field])) ||
(permission.query ?? []).some((name) => set(input.query[name]))
(permission.query ?? []).some((name) => set(input.query[name])) ||
valuesOf(permission).some(
([field, listed]) => (isObject(body) && holds(body[field], listed)) || holds(input.query[field], listed),
)

/** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
export const serviceApiKeys = (
Expand Down Expand Up @@ -155,11 +171,10 @@ export const serviceApiPermissions = (
const checks = new Map<string, (PermissionKey | ConditionalKey)[]>()
for (const operation of input.manifest.operations)
checks.set(operation.command, [
...permissionsOf(operation).map((permission) =>
flagsOf(permission).length === 0
? permission.key
: { key: permission.key, when: `with ${flagsOf(permission).join(" or ")} set` },
),
...permissionsOf(operation).map((permission) => {
const when = whenOf(permission)
return when === undefined ? permission.key : { key: permission.key, when }
}),
...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
])
const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))]
Expand Down
Loading