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
9 changes: 9 additions & 0 deletions changes/fix-api-empty-required.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Fixed

- **A generated `api` command refuses an empty required argument before it sends anything.** `linear api issue-delete
--id "" --yes` used to send the request, and Linear's answer left the write unconfirmed (exit 14,
`outcome.unknown`). Now a required path, query or header parameter, or a required GraphQL variable from a flag
or from `--body`, that is empty or only spaces stops the command with exit 2 (`validation_error`, reason `input.invalid`),
naming the flag, and nothing is sent. An empty path parameter could otherwise reach another endpoint (`/posts/`).
`serviceApiWriter` refuses the same for code. A bot API's body field is still sent empty: Telegram's `setWebhook`
takes an empty `url` to remove the hook.
8 changes: 7 additions & 1 deletion src/cli/bot/api-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ export const apiPlainJson = (value: unknown): unknown =>
) ?? "null",
)

/**
* An empty or all-space text in a required argument or parameter: the service may read it as no id at all, and an empty
* path segment can reach another endpoint, so it is refused before anything is sent.
*/
export const isBlank = (value: unknown): boolean => typeof value === "string" && value.trim() === ""

/** A JSON object with no lossless number at its top: what a GraphQL body of variables must be. */
const isVariables = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === "object" && !Array.isArray(value) && !isLosslessNumber(value)
Expand Down Expand Up @@ -194,7 +200,7 @@ export const graphqlVariables = (
sent: false,
})
const missing = Object.entries(binding.variables)
.filter(([name, type]) => type.endsWith("!") && variables[name] == null)
.filter(([name, type]) => type.endsWith("!") && (variables[name] == null || isBlank(variables[name])))
.map(([name]) => `--${apiFlagOf(name)}`)
if (missing.length > 0)
throw new CliError("validation_error", `${operation.command} needs ${missing.join(", ")}`, { sent: false })
Expand Down
13 changes: 13 additions & 0 deletions src/cli/bot/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,19 @@ describe("the shared native API command", () => {
expect(denied.calls).toEqual([])
})

it("refuses an empty required query parameter unsent, and leaves an empty required body field to the service", async () => {
const offset: ManifestOperation = {
...http,
parameters: [{ name: "offset", in: "query", required: true, schema: { type: "string" } }],
}
const blank = await call(["bot", "api", "get-updates", "--offset", " ", "--json"], [offset])
expect(blank.code).toBe(2)
expect(blank.err).toContain("--offset")
expect(blank.calls).toEqual([])
// Telegram documents setWebhook's required url as empty to remove the hook.
expect((await call(["bot", "api", "send-photo", "--chat-id", "", "--json"])).calls).toHaveLength(1)
})

it("does not offer sensitive field flags", async () => {
const result = await call(["bot", "api", "send-photo", "--secret-token", "private-value", "--json"])
expect(result.code).not.toBe(0)
Expand Down
7 changes: 7 additions & 0 deletions src/cli/bot/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
apiJson,
apiOptionKey,
graphqlVariables,
isBlank,
readApiBody,
readApiBytes,
sendsBytes,
Expand Down Expand Up @@ -130,6 +131,12 @@ export const generatedApiCommand = (api: ApiCommands): Command => {
for (const parameter of operation.parameters) {
const raw = options[apiOptionKey(parameter.name)]
if (raw === undefined) continue
// A body field may be empty on purpose (Telegram's setWebhook url removes the hook); GraphQL's are checked as
// variables.
if (parameter.required && parameter.in !== "body" && isBlank(raw))
throw new CliError("validation_error", `--${apiFlagOf(parameter.name)} of ${operation.command} is empty`, {
sent: false,
})
if (parameter.in !== "body") {
const problem = api.checkParameter(parameter.name, parameter.schema, raw)
if (problem) throw new CliError("validation_error", problem)
Expand Down
14 changes: 14 additions & 0 deletions src/cli/service-api-graphql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,20 @@ it("a flag of the wrong type or an undeclared variable is refused before anythin
expect(fake.calls).toEqual([])
})

it("an empty required argument is refused before anything is sent, from a flag or from --body", async () => {
const { cli, fake } = setup()
for (const given of [
["--id", ""],
["--id", " "],
["--body", '{"id":""}'],
]) {
const refused = await cli(["work", "api", "issue-delete", ...given, "--yes", "--json"])
expect(refused.code).toBe(2)
expect(refused.error).toMatchObject({ code: "validation_error", message: expect.stringContaining("--id") })
}
expect(fake.calls).toEqual([])
})

it("--all follows pageInfo.endCursor through after, one document per page", async () => {
const { cli, fake } = setup({
issues: ({ variables }) =>
Expand Down
12 changes: 12 additions & 0 deletions src/cli/service-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,18 @@ describe("the shared service api group", () => {
expect(wrong.error).toMatchObject({ code: "validation_error" })
})

it("**an empty required parameter is refused before anything is sent**, by the command and by the writer", async () => {
const { cli, sent } = fixture({ api: "allow", "posts.delete": "allow" })
for (const id of ["", " "]) {
const refused = await cli("work", "api", "delete-post", "--id", id, "--yes", "--json")
expect(refused.code).toBe(2)
expect(refused.error).toMatchObject({ code: "validation_error", message: expect.stringContaining("--id") })
}
const written = await cli("work", "write", "update-post", "--id", " ", "--json")
expect(written.error).toMatchObject({ code: "validation_error", message: expect.stringContaining("id") })
expect(sent).toEqual([])
})

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
3 changes: 3 additions & 0 deletions src/cli/service-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
checkApiBody,
checkApiParameter,
graphqlVariables,
isBlank,
parseApiJson,
readApiBody,
readApiBytes,
Expand Down Expand Up @@ -678,6 +679,8 @@ export const serviceApiWriter = (options: ServiceApiOptions): ServiceApiWrite =>
: parameter.in === "query" || parameter.in === "path"
? input[parameter.in][parameter.name]
: undefined
if (parameter.required && raw !== undefined && isBlank(flagText(raw)))
throw new CliError("validation_error", `${parameter.name} of ${operation.command} is empty`, { sent: false })
const problem =
raw === undefined ? undefined : checkApiParameter(parameter.name, parameter.schema, flagText(raw), schemas)
if (problem) throw new CliError("validation_error", problem)
Expand Down
Loading