diff --git a/AGENTS.md b/AGENTS.md index b664c01..f5914af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,8 +19,9 @@ work here. - `schema`: [`Keyword`](crates/flowapi/src/schema/keyword.rs), every keyword of every dialect; where a schema holds schemas (`sub.rs`); the index of `$id`, `$anchor` and big objects. - `spec`: what a description names: components, a JSON Schema's root, operations - (`operations/reader.rs`, `responses.rs`, `style.rs` how a parameter is serialized; Swagger - 2.0's bodies, forms and media types lifted into the 3.x model in `swagger.rs`). + (`operations/reader.rs`, `responses.rs`, `style.rs` how a parameter is serialized, and a + request's form members by their Encoding Objects; Swagger 2.0's bodies, forms (an array + field by its `collectionFormat`) and media types lifted into the 3.x model in `swagger.rs`). - `graph`: schemas into types. `build.rs` (a queue, no recursion), `read.rs` (one keyword), `own.rs` (a schema's own values), `narrow.rs` and `literal.rs` (`enum`, `const`), `ops.rs` (operations as types). @@ -30,36 +31,46 @@ work here. that names every type. - `crates/flowapi-ts`: the TypeScript target. `tests/cases/*.json` and the `.ts` kept beside each. `src/sdk.rs` the opt-in SDK (`--sdk`): `sdk/request.rs`, `sdk/response.rs` and the runtime - printed once (`sdk/runtime.ts` writes requests, `sdk/multipart.ts` their `multipart/form-data` - bodies, `sdk/read.ts` reads responses); + printed once (`sdk/runtime.ts` writes requests, `sdk/form.ts` their form bodies by the + Encoding Objects, `sdk/multipart.ts` their `multipart` bodies, `sdk/read.ts` reads responses); `tests/sdk/*.json` kept like the cases. - `crates/flowapi-rust`: the Rust target (serde types). `tests/cases/*.rs`, kept like the TypeScript ones. - `src/sdk.rs` the opt-in SDK (`--target rust --sdk`): `sdk/request.rs`, `sdk/param.rs`, - `sdk/response.rs`, and the runtime printed once as `pub mod sdk` (`sdk/runtime.rs` and + `src/sdk.rs` the opt-in SDK (`--target rust --sdk`): `sdk/request.rs`, `sdk/param.rs` (a + parameter's style, and a form's members by the description's Encoding Objects, printed into each + call), `sdk/response.rs`, and the runtime printed once as `pub mod sdk` (`sdk/runtime.rs` and `sdk/errors.rs`, its modules `sdk/write.rs`, `sdk/expand.rs` and `sdk/finite.rs`, never compiled here: this crate has no serde); `src/print/integer.rs` the `Integer` type printed with the types; `tests/sdk/*.rs` kept for the TypeScript SDK's cases and `tests/sdk/names.json`. - `crates/flowapi-sdk`: the SDK layer, above the targets: what a client needs beside a target's SDK, which no type depends on. It reads the documents through the core's public modules (`doc.rs`: references followed, each endpoint's Operation Object found again), `servers.rs` - (3.x `servers` at three levels with variables; 2.0's `host`, `basePath`, `schemes` lifted) and - `security.rs` (`securitySchemes` or 2.0's `securityDefinitions`, `security`) into `model.rs`, + (3.x `servers` at three levels with variables, a relative URL of another document written from + the first; 2.0's `host`, `basePath`, `schemes` lifted) and + `security.rs` (`securitySchemes` or 2.0's `securityDefinitions`; `security/flows.rs` OAuth 2.0's + flows, `security/requirements.rs` `security` and its names) into `model.rs`, and `print.rs` prints the TypeScript table put after `--sdk`'s output (`flowapiServers`, `flowapiSecuritySchemes`, `flowapiOperations`), naming the functions as `flowapi-ts` does. No I/O (G5). `tests/cases/*.json` and the `.ts` kept beside each (`--test table`, each case's `x-flowapi-covers` the ledger's markers); `tests/tsc.mjs` type-checks and imports them after the `--sdk` output. The `flowapi-sdk.yml` config, also no I/O: `config/shape.rs` (and `shape/schemes.rs`) its format once, as tables that `config/read.rs` validates by, - `config/build.rs` reads into `config/model.rs` and `config/schema.rs` prints as JSON Schema; - `config/check.rs` and `config/names.rs` hold it to the description, `config/issue.rs` the + `config/build.rs` (`build/members.rs`) reads into `config/model.rs` and `config/schema.rs` + prints as JSON Schema (`shape/package.rs` the `package` and `readme` tables); + `config/check.rs` and `config/names.rs` hold it to the description (`config/auth.rs` and + `auth/usage.rs` its `auth` and `security`, also laid over the description's), `config/issue.rs` the issues; `ops.rs` the operations by id and route, `words.rs` names as words, `paging/` the - pagination a schema fits (`fit.rs`) or suggests (`suggest.rs`), `draft.rs` (`draft/naming.rs`) - a first config, `summary.rs` the compact summary. `tests/config/*.yml` with the issues kept + pagination a schema fits (`fit.rs`) or suggests (`suggest.rs`), `draft.rs` (`draft/naming.rs`, + a method's name without its resource's words in `draft/naming/trim.rs`) a first config, + `prose.rs` a description's CommonMark as plain text, `summary.rs` the compact summary. `tests/config/*.yml` with the issues kept beside each (`--test config`), `tests/schema.json` (`--test schema`, the reader and the schema agree both ways), `tests/draft/` (`--test draft`), `tests/summary/` (`--test summary`). - `encoding.rs` a `multipart/form-data` body's encoding, put in the table. `client.rs` the whole - TypeScript client from a config (`client_files`): `client/resources.rs` a class per resource, - `client/entry.rs` the client class and `index.ts`, `client/core/*.ts` the runtime, kept as + `encoding.rs` a form or `multipart` body's Encoding Objects, put in the table (`encoding/inspect.rs` + a part's type from its schema, `encoding/swagger.rs` 2.0's forms from the core's + `Media::encoding`, which alone reads `collectionFormat`; `encoding/print.rs` the table's literal). `client.rs` the whole + TypeScript client from a config (`client_files`): `client/resources.rs` a class per resource + (`client/comment.rs` each method's doc comment), + `client/entry.rs` the client class and `index.ts`, `client/core/*.ts` the runtime (`auth.ts` + the credentials, `token.ts` OAuth 2.0's client credentials grant), kept as TypeScript and printed as it is (each file held to 300 working lines by `tests/client.mjs`). `tests/client//` a config and a description with the client kept beside them (`--test client`); `tests/client.mjs` type-checks them and runs `tests/client/*.mjs` against a @@ -67,16 +78,19 @@ work here. client (`repo_files`): `repo/package.rs` `package.json`, the TypeScript configs and the license, `repo/texts.rs` the scripts, CI, release-please and the repository's `AGENTS.md`, `repo/mock.rs` the mock server's routes, `repo/suite.rs` a test per resource, `repo/readme.rs` - `README.md` and `api.md`, `repo/example.rs` a schema's example value, `repo/lock.rs` + `README.md` (its sections in `readme/sections.rs`, the servers' in `readme/servers.rs`) and `api.md` (`readme/api.rs`), `repo/example.rs` a schema's example value, `repo/lock.rs` `.flowapi/lock.json` (the shape the agent plugin reads), `repo/plan.rs` what writing the repository changes on disk (`plan`: by the lock and what the host found at each path; every host runs it, none decides alone); `repo/files/` the texts printed as they are (scripts, `server.mjs`, the licenses); `sha256.rs` our own SHA-256. - `tests/repo//` the repository of each client case but its `src/`, kept (`--test repo`). + `tests/repo//` the repository of each client case but its `src/`, kept (`--test repo`); + `tests/texts.mjs` compiles their README examples and `api.md` signatures against the client + and refuses a placeholder in their texts. - `crates/flowapi-cli`: the `flowapi` command, all of flowapi's I/O. `src/sdk.rs` the subcommands put before the path (`summary`, `config draft|schema|check`; `tests/sdk_cli.rs`); `src/generate.rs` `generate`, `generate/disk.rs` what is on disk for the SDK layer's `plan`, - `generate/apply.rs` the writes, staged first (`tests/generate_cli.rs`). + `generate/apply.rs` the writes, staged first (`tests/generate_cli.rs`; its warnings, the core's + and the SDK layer's, each once: `tests/generate_warnings_cli.rs`). - `crates/flowapi-yaml`: a description's text as the core reads it, shared by the command and the WebAssembly module: which document is YAML (`is_yaml`), YAML 1.2 read into JSON with each node's YAML place (`reader.rs`, `saphyr-parser`), and the line and column of an offset. No I/O (G5). @@ -144,6 +158,7 @@ cargo test -p flowapi-cli --test sdk_cli # summary and config as t cargo test -p flowapi-sdk --test repo # the repositories kept in tests/repo/ (FLOWAPI_BLESS=1) cargo test -p flowapi-cli --test generate_cli # generate's writing rules as the command runs them node crates/flowapi-sdk/tests/tsc.mjs # them type-checked after --sdk; after cargo build --release +node crates/flowapi-sdk/tests/texts.mjs # the kept READMEs and api.md compiled against their clients cargo run --release -p flowapi-cli -- -o types.ts (cd plugins/flowapi && npm test) # the agent plugin; its e2e on target/release/flowapi (cd plugins/flowapi && npm run docs) # the flowapi skill's references, after a docs change diff --git a/CHANGELOG.md b/CHANGELOG.md index 66e59bc..2989f71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,105 @@ ## Unreleased +## 0.3.0 — 2026-11-26 + +- `flowapi generate` prints the description's warnings as `flowapi ` does, not only + its errors. A Swagger 2.0 form field's `collectionFormat` is read once, by the core, and the + SDK's table takes the form's encoding from it: a format 2.0 does not have is reported once, as + `` `collectionFormat` commas is not one a parameter in `formData` takes ``, where it named a + `query` parameter; the table is written as before. +- Swagger 2.0's `collectionFormat` is written in every location 2.0 allows it: `ssv`, `tsv` and + `pipes` in a path and a header too (the delimiter percent-encoded in a URI, as written in a + header), and `tsv` in a query (`a%09b`), which was written as `csv` with a warning. An Items + Object's own `collectionFormat` joins the arrays inside an array, level by level + (`spec::Serialization::nested`, `spec::Style::TabDelimited`), in both SDKs, and in a `formData` + body of the TypeScript SDK (a form, or a `multipart/form-data` part): the table's Encoding + Object has `nested`, the styles of the inner arrays. `multi` outside a query, or a format 2.0 + does not have, is still `csv` with a warning. +- The SDK's client retries and redirects as RFC 9110 says. A request whose method is + not idempotent (POST, PATCH, QUERY; 9.2.2) is not retried on its own unless the server answers + `x-should-retry: true` or it carries an idempotency key; `defaults.idempotency_key` in + `flowapi-sdk.yml` names the header (`Idempotency-Key`), and each such call then sends a random + key in it, the same on all its attempts. The default `retries` is now 1 (it was 2), as a failed + retry is not retried again; more is the config's or the caller's choice. A 403 is never retried + (15.5.4). A status that is no status code is read as a 5xx, one no class is known for by its + class (15). Every 3xx with a `Location` is followed but 304, 305 and 306 (15.4): 303 as a GET, + 301 and 302 turn a POST into a GET, the rest keep the method and the content; a redirect loop is + refused at once, 20 redirects at most, and a `Location` without a fragment keeps the + request's (10.2.2). A GET or HEAD with content, and an OPTIONS with content but no + `Content-Type`, are refused before they are sent. +- Servers, as the client uses them: `serverVariables` gives values to the servers' variables over + their defaults, each checked against its `enum` (typed in the client's options by the + description's servers and the operations' own); `descriptionURL` says where the description is + served, and a relative server URL is resolved against it (OpenAPI 3.1 and 3.2, "Relative + References in API URLs"); a Server Object of another document is printed relative to the + first; a base URL, a `descriptionURL` or a redirect's `Location` with a user name or password + in it is refused (RFC 9110 4.2.4). Swagger 2.0's `schemes`, the description's and an + operation's, warn of a value that is not `http`, `https`, `ws` or `wss` under the requirement's + id and do not use it; an operation whose own list has none left is served by the description's. The table's cases now hold OpenAPI 3.0 and 3.2's servers + too, and two client cases (`hosts`, 3.2; `edge`, 3.1) hold the runtime to them: 56 ledger ids + that had no test have one, every in-scope RFC 9110 id among them. +- The SDK writes bodies by the description's Encoding Objects. The SDK layer reads them into the + operations table (`encoding` by name for a form and `multipart/form-data`, 3.2's + `prefixEncoding` and `itemEncoding` by position, nested ones to four levels, each field only + where its version and media type apply it, request bodies only), takes a part's missing type + from its schema (`contentEncoding`, 3.0's `format: binary` and `byte`, through `$ref` and + `allOf`), and reads Swagger 2.0's `formData` `collectionFormat` as a style; the client passes + them to `Request` when a call gives none. A form member with `style`, `explode` or + `allowReserved` is written by that style; 3.1 and 3.2's `multipart/form-data` members too. Any + other multipart type takes an array, a part per item; a part of a `multipart` type is written as + a body of its own; outside `multipart/form-data` a part with `contentEncoding` says + `Content-Transfer-Encoding` (3.2). A list of types is kept for the caller to pick from. +- The Rust SDK writes a form body's members by the description's Encoding Objects, printed into + each operation's `_request` (`sdk::form_body(v, &[...])`, `sdk::Part`): a member with + `style`, `explode` or `allowReserved` as a query parameter of that style (`a,b`, `a%20b`, + `filter%5Bcolor%5D=red`, `/a/b:c@d` with `allowReserved`), one whose `contentType` alone is + JSON as its JSON (`id=%22x%22`), and Swagger 2.0's array `formData` fields by their + `collectionFormat`, the arrays inside by their Items Objects'. Before, every member was written + by the form's defaults, and a 2.0 `formData` form not at all in O8. The core reads them into + `spec::Media::encoding` (request bodies only), from which the Rust target prints them. +- A form body written from its content is percent-encoded by WHATWG's rules, as OpenAPI 3.2 asks + and browsers send (`a b!` was `a%20b!`, is `a+b%21`), in the TypeScript and the Rust SDKs, and a + 3.2 `querystring` parameter with form content too. A member written by `style` keeps RFC 3986's. +- `flowapi-sdk`'s `Encoding` holds `Parts` (`by_name`, `prefix`, `item`) of `Part`s with + `style`, `explode`, `allowReserved` and nested parts, in place of its list of names and types. +- SDK authentication. The client sends each kind of security scheme: an API key in a header, a + query parameter or a cookie; HTTP bearer (RFC 6750 2.1's syntax) and basic (RFC 7617: UTF-8, no + `:` in the user-id, no control character); another HTTP scheme as ` `, + while one that answers a challenge (`digest`, ...) is refused with a diagnostic; OAuth 2.0 and + OpenID Connect tokens given as a string or a function; and OAuth 2.0's client credentials grant + run by the client (RFC 6749 4.4: a POST of the form, the client by HTTP basic, the token URL + relative to the server, `TokenError` for 5.2's errors, a cache with a margin, one request in + flight, a 401 that asks for another token once: the call made again with its idempotency key + and the retries it has left, a POST too, as a 401 says nothing was applied; the token request + itself is never retried nor followed to another origin). `mutualTLS` is the option `true` beside a + `fetch` that presents the certificate. `security` is read as written: alternatives in order, + the schemes of one together, `{}` and `[]`, an operation's own over the description's, and a + name in a referenced document read from the entry document (Appendix F). Credentials go only + over TLS or to a loopback host unless `allowInsecureCredentials: true` + (`InsecureCredentialError`, held to the call's base URL before a credential is read or a token + requested, so a refused call costs no token request); a call that cannot be met throws `CredentialError` before + sending, naming the options and variables. +- `flowapi-sdk.yml`: `auth.` declares a scheme the description lacks (`type`, `scheme`, + `in`, `name`, `token_url`, `description`) and takes `username_env_var`/`password_env_var`, + `client_id_env_var`/`client_secret_env_var` and `scopes`; a top-level `security` and a + method's `security` override the description's. `config check` errs with `config.auth.declared`, + `config.auth.unknown`, `config.auth.field`, `config.auth.type`, `config.auth.in`, + `config.auth.option` and `config.security.unknown`, and warns with `config.auth.none`, + `config.auth.unlisted`, `config.auth.env`, `config.auth.refused`, `config.auth.mutual_tls` and + `config.auth.deprecated`. `config draft` names a variable for every scheme and, for a + description without security, writes a commented example and leaves `security` unset, so that + `config check` warns `config.auth.none` until the person declares the API's credential, or + writes `security: []` for an API that takes none. The summary shows + the description's and each operation's own security and an OAuth 2.0 token URL. +- The generated repository: the mock answers 401 with JSON naming what is missing and serves a + token endpoint held to RFC 6749; `tests/auth.test.mjs` sends made-up credentials of each kind + and calls an operation that needs none without any; the README has a row for every scheme. +- The requirements ledger (`conformance/ledger`, O1) reads Swagger 2.0 and five RFCs (6749, 6750, + 7578, 7617 and 9110, pinned in `conformance/specs/`) beside OpenAPI 3.x and JSON Schema, and its + scope is decided for the SDK: servers, security, the Encoding Object and what the client sends + (`conformance/triage-3.md`). `report` also writes `conformance/MISSING.md`, every requirement + in scope that no test names yet. - The agent plugin `flowapi` (`plugins/flowapi`), installed from this repository as a marketplace (`claude plugin marketplace add localixai/flowapi`, then `claude plugin install flowapi@flowapi`). It is a Claude Code plugin and an Agent Plugins 1.1.0 @@ -11,6 +110,31 @@ build, the built types, the package, the tests). `/flowapi:refine`, `update` and `release` take it further, and a guard hook refuses hand edits of the files `.flowapi/lock.json` lists. Its version is flowapi's. +- `flowapi-sdk.yml` has `readme.title` (the README's heading), `package.description` + (`package.json`'s description, and the README's first paragraph unless `readme.intro` is given) + and `package.keywords`. Unless given, the heading is the description's `info.title` without a + last `API`, then `TypeScript SDK`, and the description is `TypeScript SDK for the API.` + with the first short sentence of `info.summary` or `info.description`, as plain text. +- `config draft` names a method without the words its resource already says + (`actions.get_cache_retention_limit_for_enterprise`, `repos.list_for_org`), keeps a run of them + that a word qualifies, maps a `POST` to an item that has no `PUT` or `PATCH` to `update`, and + where two names meet gives both their next longer name; a resource that meets a schema's name + takes its English plural (`activity` is `activities`, `address` `addresses`; it was `activitys`). +- The generated texts, rewritten: the README has a resources table linked to `api.md`, what a + method takes and gives, `withResponse()`, a table of error classes, the retry rule as the + runtime keeps it (with `retries: 0`, that nothing is retried by default, the rule said for a + caller who sets `maxRetries`), pagination with the input its method needs, logging, `client.request`, and no + example with a placeholder for its arguments; `api.md` writes every signature in types the + package exports (`Data`, `Input`, `ItemOf`, now exported, and `Stream<ServerSentEvent>`); each + method's doc comment is its operation's summary and description as plain text, with + `@see` for `externalDocs` and `@deprecated`; `AGENTS.md` says where things are and which key of + the config changes what; `CHANGELOG.md` is seeded with a line on how it is written. The + runtime's errors say what to do: a timeout names `timeout`, an unknown environment names the + config's, too many pages name `maxPages`, a cross-origin redirect names + `allowCrossOriginRedirects`. +- `crates/flowapi-sdk/tests/texts.mjs` compiles every README example and every `api.md` + signature of the kept repositories against their clients, and fails on a placeholder (`TODO`, + `"string"`, `/* … */`) or an empty section. ## 0.2.0 — 2026-11-26 diff --git a/Cargo.lock b/Cargo.lock index 2e57d7f..d30af88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,11 +10,11 @@ checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-cli" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", "flowapi-rust", @@ -25,14 +25,14 @@ dependencies = [ [[package]] name = "flowapi-rust" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] [[package]] name = "flowapi-sdk" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", "flowapi-ts", @@ -42,14 +42,14 @@ dependencies = [ [[package]] name = "flowapi-ts" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] [[package]] name = "flowapi-wasm" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", "flowapi-sdk", @@ -59,14 +59,14 @@ dependencies = [ [[package]] name = "flowapi-wasm-sdk" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi-wasm", ] [[package]] name = "flowapi-yaml" -version = "0.2.0" +version = "0.3.0" dependencies = [ "saphyr-parser", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 1b2013e..1ffe13f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ members = ["crates/flowapi", "crates/flowapi-ts", "crates/flowapi-cli", "crates/ exclude = ["bench", "conformance"] [workspace.package] -version = "0.2.0" +version = "0.3.0" edition = "2024" rust-version = "1.89" license = "MIT" diff --git a/README.md b/README.md index bd899ad..14c7d38 100644 --- a/README.md +++ b/README.md @@ -51,9 +51,11 @@ the whole suite), says which values are valid, and every valid one must type-che flowapi's type ([conformance/results/props.md](conformance/results/props.md)). And every valid example description the OAI keeps beside its schemas generates and type-checks ([conformance/results/oai.md](conformance/results/oai.md)). A requirements ledger lists every -MUST, SHOULD and MAY of OpenAPI 3.0.4, 3.1.2, 3.2.1 and JSON Schema 2020-12 that a types -generator answers to, each held by a test or named as something a type cannot state -([conformance/REPORT.md](conformance/REPORT.md)). +MUST, SHOULD and MAY of Swagger 2.0, OpenAPI 3.0.4, 3.1.2, 3.2.1, JSON Schema 2020-12 and the RFCs +the SDK's client follows (OAuth 2.0 and its bearer tokens, Basic, `multipart/form-data`, HTTP +semantics) that flowapi answers to, each held by a test or named as something a type cannot +state ([conformance/REPORT.md](conformance/REPORT.md)); those no test holds yet are listed in +[conformance/MISSING.md](conformance/MISSING.md). One TypeScript limit shows in rare cases: an object literal with a key named like a member every object inherits (`constructor`, `toString`) is checked against `Object`'s member when the @@ -91,7 +93,7 @@ the Rust command's output byte for byte, and `generate` (below) the same files, The Rust command, built from a release tag: ```sh -cargo install --locked --git https://github.com/localixai/flowapi --tag v0.2.0 flowapi-cli +cargo install --locked --git https://github.com/localixai/flowapi --tag v0.3.0 flowapi-cli flowapi openapi.json -o types.ts ``` @@ -99,8 +101,8 @@ The crates are not on crates.io. A program takes them from the repository at a t ```toml [dependencies] -flowapi = { git = "https://github.com/localixai/flowapi", tag = "v0.2.0" } -flowapi-ts = { git = "https://github.com/localixai/flowapi", tag = "v0.2.0" } +flowapi = { git = "https://github.com/localixai/flowapi", tag = "v0.3.0" } +flowapi-ts = { git = "https://github.com/localixai/flowapi", tag = "v0.3.0" } ``` In a checkout, `cargo run --release -p flowapi-cli -- openapi.json -o types.ts` does the same. @@ -180,24 +182,41 @@ const up = uploadPhotoRequest({ ``` Parameters are written as their `style`, `explode` and `allowReserved` say (`simple`, `label`, -`matrix`, `form`, `spaceDelimited`, `pipeDelimited`, `deepObject` and 3.2's `cookie`; Swagger -2.0's `collectionFormat` read as those), percent-encoded per RFC 3986 everywhere but headers and -`style: cookie`, which pass as given; a parameter with `content` as its media type's text; cookies +`matrix`, `form`, `spaceDelimited`, `pipeDelimited`, `deepObject` and 3.2's `cookie`), percent-encoded +per RFC 3986 everywhere but headers and `style: cookie`, which pass as given. Swagger 2.0's +`collectionFormat` is read as those in a path, a query and a header (`csv` `a,b`, `ssv` `a b`, +`tsv` `a<tab>b`, `pipes` `a|b`, the delimiter percent-encoded in a URI; `multi` a pair per item, in +a query), and an Items Object's own joins the arrays inside an array, level by level (`multi` and +`pipes` over `csv`: `grid=1,2%7C3&grid=4`); a parameter with `content` as its media type's text; cookies into one `cookie` header. The body is `{ contentType, value }` of one of the operation's media types: JSON, a form, text as given, or bytes (a `Uint8Array`, for a type neither JSON, text nor a -form, sent as they are). A `multipart/form-data` body is written from its members as the +form, sent as they are). A form (`application/x-www-form-urlencoded`) is percent-encoded by the +WHATWG rules 3.2 asks for, as a browser sends one: a space as `+`, all but letters, digits and +`*-._` encoded (`a b!` is `a+b%21`); a member whose Encoding Object gives `style`, `explode` or +`allowReserved` is written by that style as a query parameter is, with RFC 3986's encoding +(`ids=1%7C2`, `point%5Bx%5D=1`). A `multipart/form-data` body is written from its members as the Encoding Object's defaults say: a `Uint8Array` or a file a file part (`filename` its last path segment, `blob` when it has none; `application/octet-stream` when it has no type), a string, number or boolean a text part, an object JSON, an array's items one part each under its name, in order (RFC 7578, 4.3); `undefined` is left out, `null` refused. A file is `flowapiFile(bytes or text, name, type)`, or `await flowapiBlob(blobOrFile)`, the one step that -waits: `<op>Request` takes bytes and stays synchronous. The description's `encoding` is not read -yet: give it as the body's `encoding` (`{ photo: { contentType, headers } }`); its `contentType` -replaces the default (a file's own type replaces it, and a list or a range needs one) and its -`headers` go into the part. The boundary is the content type's (`; boundary=`), else 128 random -bits from `globalThis.crypto`, drawn again while a part holds them and added to the request's -`content-type`; `body` is then bytes. 3.2's array of objects is written as its parts in order; -another multipart type is yours to write, as a string or bytes. A response is picked +waits: `<op>Request` takes bytes and stays synchronous. Any other multipart type +(`multipart/mixed`, 3.2) takes an array, an unnamed part per item in order, or a string or bytes +sent as they are. The description's Encoding Objects go in the body: `encoding` by name, +3.2's `prefixEncoding` and `itemEncoding` by position (the SDK layer's table holds the +description's, and the client passes them when the call gives none). A part's `contentType` +replaces the default (a file's own type replaces it, and a list or a range needs one: nothing is +sniffed), its `headers` go into the part as given, `style` and `explode` write a member of a +`multipart/form-data` body (3.1, 3.2) as a form's, without percent-encoding, and a part whose type +is `multipart` is a body of its own by its nested Encoding Objects (3.2). Where an Encoding Object +gives no type, the table takes it from the schema, through `$ref` and `allOf`: a string with +`contentEncoding` (3.0: `format: binary` or `byte`) is `application/octet-stream`, and a part of +another multipart type also says `Content-Transfer-Encoding` (3.2). Swagger 2.0's `formData` +arrays are written by their `collectionFormat` (`csv`, `ssv`, `pipes`, `multi`, and `tsv` joined +by a tab), the arrays inside one by their Items Objects' (the Encoding Object's `nested`), a +`file` field making the body `multipart/form-data`. The boundary is the content +type's (`; boundary=`), else 128 random bits from `globalThis.crypto`, drawn again while a part +holds them and added to the request's `content-type`; `body` is then bytes. A response is picked by its status (the code, then `2XX`, then `default`) and its `Content-Type`, and its body, given as text or as bytes, read by the type sent as the Rust SDK reads it: JSON parsed (a leading byte order mark skipped), `text/*` a `string`, any other a `Uint8Array`, a media range any of those @@ -222,7 +241,8 @@ operation, with a warning. The output imports nothing: the runtime is a few func printed once. With `--sdk` the base URL and any authentication are still yours to add: the command does not print `servers`, `securitySchemes` or `security`. The SDK layer (`crates/flowapi-sdk`, the one `generate` writes a client with) reads them, Swagger 2.0's `host`, `basePath` and -`schemes` included, and prints a table to put after this output: the servers with their +`schemes` included (an operation's own its own servers; a scheme not `http`, `https`, `ws` or +`wss` warned of and not used), and prints a table to put after this output: the servers with their variables, the security schemes, and each operation's method, path, own servers, security and how each response body is read. Every row of the specification's Style Examples table, the pitfalls other generators fixed, and the SDKs of GitHub's, Stripe's and @@ -234,8 +254,11 @@ For Rust, `--target rust --sdk` prints the same after the serde types: per opera struct, `<op>_request(&input)`, which returns an `sdk::Request` (method, path, query, headers, and the body's content type and bytes) or an `sdk::RequestError` for what the TypeScript SDK refuses, with the same `reason` codes (`Reason::code()`), and `<op>_response(status, headers, body)`, which returns an -enum of the operation's responses or an `sdk::Error` holding the answer. No I/O, no async; the -runtime is a module printed once (`pub mod sdk`) and needs serde and serde_json, as the types do. +enum of the operation's responses or an `sdk::Error` holding the answer. A form body's members +are written by the description's Encoding Objects (and Swagger 2.0's `collectionFormat`), printed +into each `<op>_request`: there is no table to pass. A multipart body is given as its content type +and bytes. No I/O, no async; the runtime is a module printed once (`pub mod sdk`) and needs serde +and serde_json, as the types do. ```sh cargo run --release -p flowapi-cli -- openapi.json --target rust --sdk -o src/api.rs @@ -285,21 +308,98 @@ read one at a time with `--tag` or `--path`. `config check` holds the config to member it does not name is an error) and to the description: every operation is in a resource or in `skip` with a reason, every reference names an operation (a typo names the closest), names are compared as words (`list_all` and `listAll` are one name), a method's pagination fits its -operation's parameters and response schema, `auth` names the description's security schemes. -A draft passes the check, and the same description written in another order gives the same -draft. A description named `summary` or `config` is read by its path: `flowapi ./summary`. +operation's parameters and response schema, `auth` and `security` name schemes that exist +(below). A draft passes the check, but for the warnings of a scheme the client cannot send itself, and the same description written in another order gives the same +draft. A drafted method's name leaves out the words its resource already says +(`actions/get-actions-cache-retention-limit-for-enterprise` in `actions` is +`get_cache_retention_limit_for_enterprise`), keeps a word that qualifies it (`users`' +`list_followers_for_authenticated_user`), and where two names meet, both take a longer one. A description named `summary` or `config` is read by its path: `flowapi ./summary`. From a config that passes the check, the SDK layer prints the client itself in TypeScript (`flowapi_sdk::client_files`): `src/api.ts` (the `--sdk` output and the operations table), a class for each resource (`client.pets.photos.list(params, options)`), the client class with its options, and the runtime in `src/core/`, which needs no dependency and -type-checks with `lib: ["es2022"]` alone. The runtime retries by status and `x-should-retry`, -waits what `retry-after-ms` or `Retry-After` ask (and refuses a wait past `maxRetryDelay`), times -each attempt out with its body read, removes its listener from the caller's `AbortSignal`, sends -the credentials of the first security alternative it can meet, masks them in its logs, refuses a -redirect to another origin unless allowed, reads lists by each pagination scheme with a guard -against a server that loops, and reads server-sent events and JSON lines whatever the chunks. A -call is awaited for its data; `asResponse()` and `withResponse()` give the raw response. +type-checks with `lib: ["es2022"]` alone. A call goes to the call's `baseURL`, else the +client's, else the operation's own servers (an operation's over its Path Item's), else the +config's environment, else the description's first server: each `{name}` of a server's URL is the +caller's `serverVariables` value, checked against the variable's `enum`, or else its `default`, +and a relative server URL (`.`, `./v2`, `/v1`, one of another document written relative to the +first) is resolved against `descriptionURL`, where the description is served (OpenAPI 3.1 and +3.2, "Relative References in API URLs"); a URL with a user name or password in it is never sent. + +The runtime retries by RFC 9110 9.2.2: a failed connection, or a 408, 409, 429 or 5xx, is retried +when the request is idempotent (GET, HEAD, OPTIONS, TRACE, PUT, DELETE), when the server answers +`x-should-retry: true` (`false` stops any retry), or when it carries an idempotency key: with +`defaults.idempotency_key: Idempotency-Key` in `flowapi-sdk.yml`, every call of another method +(POST, PATCH) sends a random key in that header, the same on each of its attempts, so that the +server can apply it once. A POST without one is never sent twice on the client's own. A 403 is +not retried; a status that is no status code is read as a 5xx. `retries` is 1 unless the config +says more, as a retry that failed is not retried again; a larger `maxRetries` is the caller's +choice. The wait is what `retry-after-ms` or `Retry-After` ask (a wait past `maxRetryDelay` is +refused), else a backoff. Redirects are followed by the runtime, not by `fetch`: every 3xx with a +`Location` but 304, 305 and 306; a 303 as a GET with no content, a POST redirected by 301 or 302 +as a GET as browsers do, any other method and status with its method and content kept; a +`Location` with no fragment keeps the request's; a loop is refused at once and a chain after 20; a +redirect to another origin is refused unless `allowCrossOriginRedirects`, and then goes without +the credentials. A GET or HEAD with content, and an OPTIONS with content but no `Content-Type`, +are refused before anything is sent. + +It also times each attempt out with its body read, removes its listener from the caller's +`AbortSignal`, sends the credentials of the first security alternative it can meet, masks them in +its logs, reads lists by each pagination scheme with a guard against a server that loops, and +reads server-sent events and JSON lines whatever the chunks. A call is awaited for its data; +`asResponse()` and `withResponse()` give the raw response. + +#### Authentication + +The client sends what an operation's security says, as OpenAPI writes it: the alternatives in +order, the first it holds every credential of; the schemes of one alternative together; `{}` a +credential that is optional, `security: []` none; an operation's own over the description's, +and a name in a referenced document read from the entry document (Appendix F). Each scheme is an +option of the client, else read from the environment variables `auth` names: + +| Scheme | Sent as | +| --- | --- | +| `apiKey` | The key in its header, query parameter or cookie | +| `http` `bearer` | `Authorization: Bearer <token>`, the token held to RFC 6750's syntax | +| `http` `basic` | `Authorization: Basic <base64>` of the UTF-8 `user:password` (RFC 7617: no `:` in the user-id, no control character) | +| another `http` scheme | `Authorization: <scheme> <credential>`; one that answers a challenge (`digest`, `negotiate`, `hoba`, ...) is refused, and a call gives `Authorization` itself | +| `oauth2`, `openIdConnect` | `Authorization: Bearer <token>`, a token or a function that gives one | +| `oauth2` with a client credentials flow | The same, the token requested by the client (RFC 6749 4.4): a POST of the form to `tokenUrl` (relative to the server's URL where it is relative, its query kept), the client's id and secret by HTTP basic and never in the body, the scopes the operation needs; held until shortly before it expires, one request for the calls that wait on it, requested again once on a 401; an error answer is a `TokenError` | +| `mutualTLS` | Nothing a request carries: the option `true`, and a `fetch` that presents the certificate | + +A call none of whose alternatives can be met throws `CredentialError` before sending, naming the +options and variables that would meet each. Credentials go only over `https:` or to `localhost`, +`127.0.0.1` and `[::1]`; elsewhere `InsecureCredentialError`, unless `allowInsecureCredentials: +true`, thrown on the call's base URL before any credential is read or token requested. A deprecated scheme still works, its option marked `@deprecated`. + +The config declares what the description lacks, as the Security Scheme Object names it, and a +`security` over the operations' (the top level for those with none of their own, a method's over +everything): + +```yaml +auth: + Token: { type: http, scheme: bearer, env_var: GITHUB_TOKEN } # a scheme the description lacks + ApiKey: { env_var: ACME_KEY } # one it declares: options only + Admin: { type: http, scheme: basic, username_env_var: ACME_USER, password_env_var: ACME_PASSWORD } + Service: { type: oauth2, token_url: https://login.acme.com/token, client_id_env_var: ACME_ID, client_secret_env_var: ACME_SECRET, scopes: [read] } +security: [{ Token: [] }, {}] # a token, optional +``` + +`config check` errs on a scheme of the description given a `type` again (`config.auth.declared`), +a name no scheme has (`config.auth.unknown`, `config.security.unknown`), a missing or foreign +member (`config.auth.field`), a `type` or `in` no scheme has (`config.auth.type`, +`config.auth.in`) and an option of another kind or without its pair (`config.auth.option`). It +warns when no operation needs a credential (`config.auth.none`; `security: []` says so on +purpose), of a scheme an operation needs that `auth` does not list (`config.auth.unlisted`) or +that names no variable (`config.auth.env`), and of the description's own: a scheme that answers a +challenge (`config.auth.refused`), a client certificate (`config.auth.mutual_tls`), a deprecated +scheme (`config.auth.deprecated`). The draft lists every scheme with a variable named after the +API and the scheme, and, for a description without security, a commented example and no +`security`, so `config check` warns `config.auth.none` until it is declared or `security: []` is +written. The generated repository's mock answers 401 with what is missing, its token +endpoint holds the client to RFC 6749, its tests send made-up credentials of each kind, and its +README has a row for every scheme. `flowapi generate` writes the SDK's whole repository around that client: @@ -314,9 +414,15 @@ dependency: built by `tsc` twice, ES modules and CommonJS, each with its types ( `mock`); a mock server on `node:http` printed from the description, strict where a client goes wrong (a path, a method, a required parameter, a body's media type) and answering each operation with an example of its schema; a `node --test` file per resource calling every method against -it; `README.md` (its counts and examples written from the config, never typed), `api.md`, the -repository's `AGENTS.md`, the license (MIT or Apache-2.0), CI on Node 20, 22 and 24, and -release-please's config. `.flowapi/lock.json` holds the hash of every file written, of the +it; `README.md` (its counts and examples written from the config, never typed, and each example +compiled against the client by flowapi's tests), `api.md` (every method's signature in the +package's types), the repository's `AGENTS.md`, the license (MIT or Apache-2.0), CI on Node 20, 22 +and 24, and release-please's config. The README's heading is `readme.title`, else the +description's `info.title` with `TypeScript SDK` (`Twilio Studio API` is `Twilio Studio TypeScript +SDK`); its first paragraph is `readme.intro`, else `package.description`, which is also +`package.json`'s description and defaults to a sentence of `info`; `package.keywords` go to +`package.json`. Each method's doc comment is its operation's summary and description as plain +text, with a link to its `externalDocs` and `@deprecated` where the description says so. `.flowapi/lock.json` holds the hash of every file written, of the description and of the config. A generated file changed by hand since is a conflict: nothing is written and it exits 1; `src/lib/` and `examples/` are the user's, `CHANGELOG.md` is written once, and a file the lock does not list is never touched. A file no longer generated is deleted unless diff --git a/bench/Cargo.lock b/bench/Cargo.lock index cb995fc..7bfe41e 100644 --- a/bench/Cargo.lock +++ b/bench/Cargo.lock @@ -116,7 +116,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-bench" @@ -131,7 +131,7 @@ dependencies = [ [[package]] name = "flowapi-ts" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] diff --git a/bench/results/sdk.md b/bench/results/sdk.md index 20c8624..201fc4a 100644 --- a/bench/results/sdk.md +++ b/bench/results/sdk.md @@ -6,6 +6,6 @@ Written by `node bench/competitors/sdk.mjs`; do not edit. 2026-11-26, Node.js v2 | Shape | flowapi | per request | openapi-fetch | per request | flowapi faster by | | --- | ---: | ---: | ---: | ---: | ---: | -| path and a flag | 43.2 ms | 432 ns | 136.5 ms | 1365 ns | 3.2x | -| arrays and an object in the query | 82.1 ms | 821 ns | 128.5 ms | 1285 ns | 1.6x | -| path, query, header and a JSON body | 51.0 ms | 510 ns | 110.8 ms | 1108 ns | 2.2x | +| path and a flag | 43.3 ms | 433 ns | 137.2 ms | 1372 ns | 3.2x | +| arrays and an object in the query | 82.3 ms | 823 ns | 122.4 ms | 1224 ns | 1.5x | +| path, query, header and a JSON body | 54.4 ms | 544 ns | 122.2 ms | 1222 ns | 2.2x | diff --git a/bench/sdk-rust/Cargo.lock b/bench/sdk-rust/Cargo.lock index 28e006d..851666d 100644 --- a/bench/sdk-rust/Cargo.lock +++ b/bench/sdk-rust/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-bench-sdk-rust" @@ -21,7 +21,7 @@ dependencies = [ [[package]] name = "flowapi-rust" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] diff --git a/conformance/MISSING.md b/conformance/MISSING.md new file mode 100644 index 0000000..970627f --- /dev/null +++ b/conformance/MISSING.md @@ -0,0 +1,8 @@ +# Requirements missing a test + +Written by `cargo run --release --bin report` in `conformance/ledger/`, with `REPORT.md`. Do not edit by hand. +Every requirement `scope.json` puts in scope that no `req:` or `lossy:` marker names yet, per text and +section in the text's order. After each id, the scope rule that classifies it: its `note` names the +layer that answers for it. + +**0 missing.** diff --git a/conformance/README.md b/conformance/README.md index 6eb9370..8b808ad 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -94,7 +94,11 @@ the flowapi crates into one generated crate with the SDKs kept by `crates/flowapi-rust/tests/sdk.rs`, builds it once (`-j 1`; a warning about it is a difference), and runs every call, comparing as `run.mjs` does. An object with no named properties is a `BTreeMap` in Rust, its members in key order: the calls that changes are held to -[`sdk-rust/order.json`](sdk-rust/order.json). Its `corpus` binary times generating the SDK of +[`sdk-rust/order.json`](sdk-rust/order.json). The TypeScript SDK takes a form body's Encoding +Objects with the body (its client passes the description's); the Rust SDK prints them from the +description, so a call whose `encoding` differs from its case's runs against an operation of its +own, `c<i>e<j>`, with the call's Encoding Objects written in. Swagger 2.0's `formData` parameters +are given as the form body they are lifted into. Its `corpus` binary times generating the SDK of GitHub's, Stripe's and Cloudflare's descriptions (never compiled: rustc needs more than 16 GB for GitHub's types) and, with `--build`, builds Slack's under `/usr/bin/time -v`. diff --git a/conformance/REPORT.md b/conformance/REPORT.md index 520ee4b..c9f1aa8 100644 --- a/conformance/REPORT.md +++ b/conformance/REPORT.md @@ -3,27 +3,70 @@ Written by `cargo run --release --bin report` in `conformance/ledger/` from `requirements.json`, `scope.json` and the `req:` and `lossy:` markers under `crates/` and `conformance/`. Do not edit by hand. -**Answered: 555 of 555 requirements in scope (100.0%): 489 covered by a test, 66 lossy with a reason; 0 missing.** Out of scope: 1200. Total: 1755. -Scope: decided 2026-11-24 by the maintainers, owner delegated. +**Answered: 930 of 930 requirements in scope (100.0%): 831 covered by a test, 99 lossy with a reason; 0 missing.** Out of scope: 1787. Total: 2717. +Scope: decided 2026-11-24, the SDK stage 2026-11-26 (triage-3.md), by the maintainers, owner delegated. | Text | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| openapi 3.0.4 (`openapi/3.0.4.md`) | 429 | 131 | 298 | 114 | 17 | 0 | 100.0% | -| openapi 3.1.2 (`openapi/3.1.2.md`) | 436 | 146 | 290 | 144 | 2 | 0 | 100.0% | -| openapi 3.2.1 (`openapi/3.2.1.md`) | 522 | 141 | 381 | 135 | 6 | 0 | 100.0% | +| openapi 2.0 (`openapi/2.0.md`) | 231 | 126 | 105 | 94 | 32 | 0 | 100.0% | +| openapi 3.0.4 (`openapi/3.0.4.md`) | 429 | 186 | 243 | 169 | 17 | 0 | 100.0% | +| openapi 3.1.2 (`openapi/3.1.2.md`) | 436 | 184 | 252 | 182 | 2 | 0 | 100.0% | +| openapi 3.2.1 (`openapi/3.2.1.md`) | 522 | 225 | 297 | 219 | 6 | 0 | 100.0% | | json-schema 2020-12 (`json-schema-2020-12/jsonschema-core.xml`) | 241 | 90 | 151 | 66 | 24 | 0 | 100.0% | | json-schema 2020-12 (`json-schema-2020-12/jsonschema-validation.xml`) | 127 | 47 | 80 | 30 | 17 | 0 | 100.0% | -| **All** | 1755 | 555 | 1200 | 489 | 66 | 0 | 100.0% | +| rfc 6749 (`rfc/rfc6749.txt`) | 234 | 19 | 215 | 19 | 0 | 0 | 100.0% | +| rfc 6750 (`rfc/rfc6750.txt`) | 56 | 12 | 44 | 12 | 0 | 0 | 100.0% | +| rfc 7578 (`rfc/rfc7578.txt`) | 19 | 13 | 6 | 12 | 1 | 0 | 100.0% | +| rfc 7617 (`rfc/rfc7617.txt`) | 10 | 3 | 7 | 3 | 0 | 0 | 100.0% | +| rfc 9110 (`rfc/rfc9110.xml`) | 412 | 25 | 387 | 25 | 0 | 0 | 100.0% | +| **All** | 2717 | 930 | 1787 | 831 | 99 | 0 | 100.0% | ## By level | Text | MUST | SHOULD | MAY | field | keyword | | --- | ---: | ---: | ---: | ---: | ---: | +| openapi 2.0 (`openapi/2.0.md`) | 55 | 7 | 7 | 162 | 0 | | openapi 3.0.4 (`openapi/3.0.4.md`) | 115 | 53 | 84 | 150 | 27 | | openapi 3.1.2 (`openapi/3.1.2.md`) | 127 | 53 | 101 | 153 | 2 | | openapi 3.2.1 (`openapi/3.2.1.md`) | 185 | 54 | 105 | 176 | 2 | | json-schema 2020-12 (`json-schema-2020-12/jsonschema-core.xml`) | 108 | 67 | 40 | 0 | 26 | | json-schema 2020-12 (`json-schema-2020-12/jsonschema-validation.xml`) | 52 | 28 | 16 | 0 | 31 | +| rfc 6749 (`rfc/rfc6749.txt`) | 153 | 46 | 35 | 0 | 0 | +| rfc 6750 (`rfc/rfc6750.txt`) | 33 | 15 | 8 | 0 | 0 | +| rfc 7578 (`rfc/rfc7578.txt`) | 8 | 7 | 4 | 0 | 0 | +| rfc 7617 (`rfc/rfc7617.txt`) | 5 | 2 | 3 | 0 | 0 | +| rfc 9110 (`rfc/rfc9110.xml`) | 200 | 116 | 96 | 0 | 0 | + +## openapi 2.0 — `openapi/2.0.md` + +| Section (id after `oas-2.0.`) | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `contact-object` | 7 | 0 | 7 | 0 | 0 | 0 | — | +| `definitions-object` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `example-object` | 3 | 0 | 3 | 0 | 0 | 0 | — | +| `external-documentation-object` | 5 | 0 | 5 | 0 | 0 | 0 | — | +| `header-object` | 22 | 17 | 5 | 7 | 10 | 0 | 100.0% | +| `headers-object` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `info-object` | 8 | 0 | 8 | 0 | 0 | 0 | — | +| `items-object` | 21 | 18 | 3 | 8 | 10 | 0 | 100.0% | +| `license-object` | 5 | 0 | 5 | 0 | 0 | 0 | — | +| `operation-object` | 23 | 13 | 10 | 13 | 0 | 0 | 100.0% | +| `parameter-object` | 31 | 23 | 8 | 12 | 11 | 0 | 100.0% | +| `parameters-definitions-object` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `path-item-object` | 13 | 10 | 3 | 10 | 0 | 0 | 100.0% | +| `paths-object` | 4 | 2 | 2 | 2 | 0 | 0 | 100.0% | +| `reference-object` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `response-object` | 7 | 3 | 4 | 3 | 0 | 0 | 100.0% | +| `responses-definitions-object` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `responses-object` | 5 | 3 | 2 | 3 | 0 | 0 | 100.0% | +| `schema-object` | 14 | 4 | 10 | 3 | 1 | 0 | 100.0% | +| `scopes-object` | 3 | 2 | 1 | 2 | 0 | 0 | 100.0% | +| `security-definitions-object` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `security-requirement-object` | 3 | 1 | 2 | 1 | 0 | 0 | 100.0% | +| `security-scheme-object` | 12 | 8 | 4 | 8 | 0 | 0 | 100.0% | +| `swagger-object` | 25 | 16 | 9 | 16 | 0 | 0 | 100.0% | +| `tag-object` | 5 | 0 | 5 | 0 | 0 | 0 | — | +| `xml-object` | 9 | 0 | 9 | 0 | 0 | 0 | — | ## openapi 3.0.4 — `openapi/3.0.4.md` @@ -31,14 +74,14 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | `appendix-c-using-rfc6570-based-serialization` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `appendix-d-serializing-headers-and-cookies` | 1 | 0 | 1 | 0 | 0 | 0 | — | -| `appendix-f-resolving-security-requirements-in-a-referenced-document` | 1 | 0 | 1 | 0 | 0 | 0 | — | +| `appendix-f-resolving-security-requirements-in-a-referenced-document` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | | `callback-object` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `components-object` | 11 | 7 | 4 | 7 | 0 | 0 | 100.0% | | `conditions-for-using-the-discriminator-object` | 3 | 0 | 3 | 0 | 0 | 0 | — | | `contact-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `data-type-format` | 2 | 1 | 1 | 1 | 0 | 0 | 100.0% | | `discriminator-object` | 12 | 1 | 11 | 1 | 0 | 0 | 100.0% | -| `encoding-object` | 18 | 1 | 17 | 1 | 0 | 0 | 100.0% | +| `encoding-object` | 18 | 15 | 3 | 15 | 0 | 0 | 100.0% | | `example-object` | 10 | 0 | 10 | 0 | 0 | 0 | — | | `external-documentation-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `format` | 4 | 0 | 4 | 0 | 0 | 0 | — | @@ -46,19 +89,19 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `http-status-codes` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `info-object` | 12 | 0 | 12 | 0 | 0 | 0 | — | | `interoperability-with-historical-specifications` | 1 | 0 | 1 | 0 | 0 | 0 | — | -| `interoperability-with-web-browser-environments` | 2 | 0 | 2 | 0 | 0 | 0 | — | +| `interoperability-with-web-browser-environments` | 2 | 2 | 0 | 2 | 0 | 0 | 100.0% | | `license-object` | 5 | 0 | 5 | 0 | 0 | 0 | — | | `link-object` | 15 | 0 | 15 | 0 | 0 | 0 | — | -| `media-type-object` | 11 | 2 | 9 | 2 | 0 | 0 | 100.0% | +| `media-type-object` | 11 | 4 | 7 | 4 | 0 | 0 | 100.0% | | `media-types` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `non-rfc6570-field-values-and-combinations` | 3 | 2 | 1 | 2 | 0 | 0 | 100.0% | -| `oauth-flow-object` | 12 | 0 | 12 | 0 | 0 | 0 | — | -| `oauth-flows-object` | 5 | 0 | 5 | 0 | 0 | 0 | — | +| `oauth-flow-object` | 12 | 7 | 5 | 7 | 0 | 0 | 100.0% | +| `oauth-flows-object` | 5 | 2 | 3 | 2 | 0 | 0 | 100.0% | | `openapi-description-structure` | 2 | 1 | 1 | 1 | 0 | 0 | 100.0% | -| `openapi-object` | 17 | 6 | 11 | 6 | 0 | 0 | 100.0% | -| `operation-object` | 20 | 9 | 11 | 9 | 0 | 0 | 100.0% | +| `openapi-object` | 17 | 7 | 10 | 7 | 0 | 0 | 100.0% | +| `operation-object` | 20 | 10 | 10 | 10 | 0 | 0 | 100.0% | | `parameter-object` | 33 | 15 | 18 | 15 | 0 | 0 | 100.0% | -| `path-item-object` | 18 | 12 | 6 | 12 | 0 | 0 | 100.0% | +| `path-item-object` | 18 | 13 | 5 | 13 | 0 | 0 | 100.0% | | `path-templating` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `paths-object` | 5 | 3 | 2 | 3 | 0 | 0 | 100.0% | | `percent-encoding-and-illegal-or-reserved-delimiters` | 2 | 1 | 1 | 1 | 0 | 0 | 100.0% | @@ -71,10 +114,10 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `rich-text-formatting` | 4 | 0 | 4 | 0 | 0 | 0 | — | | `schema-object` | 57 | 35 | 22 | 18 | 17 | 0 | 100.0% | | `security-filtering` | 4 | 0 | 4 | 0 | 0 | 0 | — | -| `security-requirement-object` | 6 | 3 | 3 | 3 | 0 | 0 | 100.0% | -| `security-scheme-object` | 17 | 6 | 11 | 6 | 0 | 0 | 100.0% | -| `server-object` | 7 | 0 | 7 | 0 | 0 | 0 | — | -| `server-variable-object` | 9 | 0 | 9 | 0 | 0 | 0 | — | +| `security-requirement-object` | 6 | 4 | 2 | 4 | 0 | 0 | 100.0% | +| `security-scheme-object` | 17 | 15 | 2 | 15 | 0 | 0 | 100.0% | +| `server-object` | 7 | 6 | 1 | 6 | 0 | 0 | 100.0% | +| `server-variable-object` | 9 | 8 | 1 | 8 | 0 | 0 | 100.0% | | `specification` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `specification-extensions` | 4 | 2 | 2 | 2 | 0 | 0 | 100.0% | | `structural-interoperability` | 2 | 0 | 2 | 0 | 0 | 0 | — | @@ -90,29 +133,29 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | `appendix-c-using-rfc6570-based-serialization` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `appendix-e-percent-encoding-and-form-media-types` | 1 | 0 | 1 | 0 | 0 | 0 | — | -| `appendix-f-resolving-security-requirements-in-a-referenced-document` | 1 | 0 | 1 | 0 | 0 | 0 | — | +| `appendix-f-resolving-security-requirements-in-a-referenced-document` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | | `callback-object` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `components-object` | 12 | 8 | 4 | 8 | 0 | 0 | 100.0% | | `conditions-for-using-the-discriminator-object` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `contact-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `data-type-format` | 2 | 1 | 1 | 1 | 0 | 0 | 100.0% | | `discriminator-object` | 13 | 2 | 11 | 2 | 0 | 0 | 100.0% | -| `encoding-object` | 22 | 1 | 21 | 1 | 0 | 0 | 100.0% | +| `encoding-object` | 22 | 18 | 4 | 18 | 0 | 0 | 100.0% | | `example-object` | 10 | 0 | 10 | 0 | 0 | 0 | — | | `external-documentation-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `format` | 4 | 0 | 4 | 0 | 0 | 0 | — | -| `header-object` | 23 | 6 | 17 | 6 | 0 | 0 | 100.0% | +| `header-object` | 23 | 7 | 16 | 7 | 0 | 0 | 100.0% | | `http-status-codes` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `info-object` | 13 | 0 | 13 | 0 | 0 | 0 | — | | `interoperability-with-historical-specifications` | 1 | 0 | 1 | 0 | 0 | 0 | — | -| `interoperability-with-web-browser-environments` | 2 | 0 | 2 | 0 | 0 | 0 | — | +| `interoperability-with-web-browser-environments` | 2 | 2 | 0 | 2 | 0 | 0 | 100.0% | | `license-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `link-object` | 16 | 0 | 16 | 0 | 0 | 0 | — | -| `media-type-object` | 12 | 2 | 10 | 2 | 0 | 0 | 100.0% | +| `media-type-object` | 12 | 4 | 8 | 4 | 0 | 0 | 100.0% | | `media-types` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `non-rfc6570-field-values-and-combinations` | 3 | 2 | 1 | 2 | 0 | 0 | 100.0% | -| `oauth-flow-object` | 12 | 0 | 12 | 0 | 0 | 0 | — | -| `oauth-flows-object` | 5 | 0 | 5 | 0 | 0 | 0 | — | +| `oauth-flow-object` | 12 | 7 | 5 | 7 | 0 | 0 | 100.0% | +| `oauth-flows-object` | 5 | 2 | 3 | 2 | 0 | 0 | 100.0% | | `openapi-description` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `openapi-description-structure` | 2 | 1 | 1 | 1 | 0 | 0 | 100.0% | | `openapi-object` | 20 | 8 | 12 | 8 | 0 | 0 | 100.0% | @@ -127,7 +170,7 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `percent-encoding-and-illegal-or-reserved-delimiters` | 2 | 1 | 1 | 1 | 0 | 0 | 100.0% | | `reference-object` | 9 | 2 | 7 | 2 | 0 | 0 | 100.0% | | `relative-references-in-api-description-uris` | 4 | 3 | 1 | 3 | 0 | 0 | 100.0% | -| `relative-references-in-api-urls` | 2 | 0 | 2 | 0 | 0 | 0 | — | +| `relative-references-in-api-urls` | 2 | 2 | 0 | 2 | 0 | 0 | 100.0% | | `request-body-object` | 7 | 3 | 4 | 3 | 0 | 0 | 100.0% | | `resolving-implicit-connections` | 3 | 0 | 3 | 0 | 0 | 0 | — | | `response-object` | 8 | 4 | 4 | 4 | 0 | 0 | 100.0% | @@ -136,9 +179,9 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `schema-object` | 23 | 10 | 13 | 8 | 2 | 0 | 100.0% | | `security-filtering` | 4 | 0 | 4 | 0 | 0 | 0 | — | | `security-requirement-object` | 6 | 5 | 1 | 5 | 0 | 0 | 100.0% | -| `security-scheme-object` | 17 | 14 | 3 | 14 | 0 | 0 | 100.0% | -| `server-object` | 8 | 6 | 2 | 6 | 0 | 0 | 100.0% | -| `server-variable-object` | 9 | 6 | 3 | 6 | 0 | 0 | 100.0% | +| `security-scheme-object` | 17 | 15 | 2 | 15 | 0 | 0 | 100.0% | +| `server-object` | 8 | 7 | 1 | 7 | 0 | 0 | 100.0% | +| `server-variable-object` | 9 | 8 | 1 | 8 | 0 | 0 | 100.0% | | `specification` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `specification-extensions` | 4 | 2 | 2 | 2 | 0 | 0 | 100.0% | | `structural-interoperability` | 2 | 0 | 2 | 0 | 0 | 0 | — | @@ -157,28 +200,28 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `appendix-g-parsing-and-resolution-guidance` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | | `base-uri-within-content` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `callback-object` | 2 | 0 | 2 | 0 | 0 | 0 | — | -| `components-object` | 13 | 8 | 5 | 8 | 0 | 0 | 100.0% | +| `components-object` | 13 | 9 | 4 | 9 | 0 | 0 | 100.0% | | `conditions-for-using-the-discriminator-object` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `conflicts-between-field-types-and-reference-contexts` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `contact-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `discriminator-object` | 14 | 2 | 12 | 2 | 0 | 0 | 100.0% | -| `encoding-object` | 26 | 1 | 25 | 1 | 0 | 0 | 100.0% | +| `encoding-object` | 26 | 24 | 2 | 24 | 0 | 0 | 100.0% | | `example-object` | 23 | 0 | 23 | 0 | 0 | 0 | — | | `external-documentation-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `format` | 1 | 0 | 1 | 0 | 0 | 0 | — | | `guidance-regarding-implicit-connections` | 1 | 0 | 1 | 0 | 0 | 0 | — | -| `header-object` | 25 | 6 | 19 | 6 | 0 | 0 | 100.0% | +| `header-object` | 25 | 7 | 18 | 7 | 0 | 0 | 100.0% | | `info-object` | 13 | 0 | 13 | 0 | 0 | 0 | — | | `json-and-yaml-compatibility` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `license-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | | `link-object` | 16 | 0 | 16 | 0 | 0 | 0 | — | -| `media-type-object` | 38 | 8 | 30 | 4 | 4 | 0 | 100.0% | +| `media-type-object` | 38 | 21 | 17 | 17 | 4 | 0 | 100.0% | | `non-rfc6570-field-values-and-combinations` | 3 | 2 | 1 | 2 | 0 | 0 | 100.0% | -| `oauth-flow-object` | 15 | 0 | 15 | 0 | 0 | 0 | — | -| `oauth-flows-object` | 6 | 0 | 6 | 0 | 0 | 0 | — | +| `oauth-flow-object` | 15 | 7 | 8 | 7 | 0 | 0 | 100.0% | +| `oauth-flows-object` | 6 | 2 | 4 | 2 | 0 | 0 | 100.0% | | `objects-and-fields` | 2 | 0 | 2 | 0 | 0 | 0 | — | | `openapi-object` | 41 | 18 | 23 | 18 | 0 | 0 | 100.0% | -| `operation-object` | 19 | 8 | 11 | 8 | 0 | 0 | 100.0% | +| `operation-object` | 19 | 9 | 10 | 9 | 0 | 0 | 100.0% | | `parameter-object` | 44 | 26 | 18 | 26 | 0 | 0 | 100.0% | | `path-item-object` | 21 | 15 | 6 | 15 | 0 | 0 | 100.0% | | `paths-object` | 8 | 4 | 4 | 4 | 0 | 0 | 100.0% | @@ -190,13 +233,13 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `response-object` | 8 | 4 | 4 | 4 | 0 | 0 | 100.0% | | `responses-object` | 8 | 5 | 3 | 5 | 0 | 0 | 100.0% | | `rich-text-formatting` | 4 | 0 | 4 | 0 | 0 | 0 | — | -| `schema-object` | 31 | 14 | 17 | 12 | 2 | 0 | 100.0% | +| `schema-object` | 31 | 17 | 14 | 15 | 2 | 0 | 100.0% | | `security-filtering` | 4 | 0 | 4 | 0 | 0 | 0 | — | -| `security-requirement-object` | 8 | 1 | 7 | 1 | 0 | 0 | 100.0% | -| `security-scheme-object` | 20 | 5 | 15 | 5 | 0 | 0 | 100.0% | -| `security-schemes` | 1 | 0 | 1 | 0 | 0 | 0 | — | -| `server-object` | 11 | 2 | 9 | 2 | 0 | 0 | 100.0% | -| `server-variable-object` | 10 | 0 | 10 | 0 | 0 | 0 | — | +| `security-requirement-object` | 8 | 5 | 3 | 5 | 0 | 0 | 100.0% | +| `security-scheme-object` | 20 | 17 | 3 | 17 | 0 | 0 | 100.0% | +| `security-schemes` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | +| `server-object` | 11 | 10 | 1 | 10 | 0 | 0 | 100.0% | +| `server-variable-object` | 10 | 8 | 2 | 8 | 0 | 0 | 100.0% | | `specification-extensions` | 4 | 2 | 2 | 2 | 0 | 0 | 100.0% | | `tag-object` | 10 | 0 | 10 | 0 | 0 | 0 | — | | `undefined-and-implementation-defined-behavior` | 3 | 0 | 3 | 0 | 0 | 0 | — | @@ -314,23 +357,105 @@ Scope: decided 2026-11-24 by the maintainers, owner delegated. | `type` | 4 | 2 | 2 | 0 | 2 | 0 | 100.0% | | `uniqueItems` | 2 | 1 | 1 | 0 | 1 | 0 | 100.0% | +## rfc 6749 — `rfc/rfc6749.txt` + +| Section (id after `rfc6749.`) | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `1` | 1 | 0 | 1 | 0 | 0 | 0 | — | +| `10` | 45 | 4 | 41 | 4 | 0 | 0 | 100.0% | +| `11` | 2 | 0 | 2 | 0 | 0 | 0 | — | +| `2` | 21 | 4 | 17 | 4 | 0 | 0 | 100.0% | +| `3` | 44 | 4 | 40 | 4 | 0 | 0 | 100.0% | +| `4` | 71 | 4 | 67 | 4 | 0 | 0 | 100.0% | +| `5` | 17 | 1 | 16 | 1 | 0 | 0 | 100.0% | +| `6` | 10 | 0 | 10 | 0 | 0 | 0 | — | +| `7` | 8 | 1 | 7 | 1 | 0 | 0 | 100.0% | +| `8` | 13 | 0 | 13 | 0 | 0 | 0 | — | +| `9` | 1 | 0 | 1 | 0 | 0 | 0 | — | +| `B` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | + +## rfc 6750 — `rfc/rfc6750.txt` + +| Section (id after `rfc6750.`) | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `2` | 14 | 4 | 10 | 4 | 0 | 0 | 100.0% | +| `3` | 20 | 1 | 19 | 1 | 0 | 0 | 100.0% | +| `5` | 22 | 7 | 15 | 7 | 0 | 0 | 100.0% | + +## rfc 7578 — `rfc/rfc7578.txt` + +| Section (id after `rfc7578.`) | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `4` | 13 | 10 | 3 | 9 | 1 | 0 | 100.0% | +| `5` | 6 | 3 | 3 | 3 | 0 | 0 | 100.0% | + +## rfc 7617 — `rfc/rfc7617.txt` + +| Section (id after `rfc7617.`) | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `2` | 9 | 2 | 7 | 2 | 0 | 0 | 100.0% | +| `4` | 1 | 1 | 0 | 1 | 0 | 0 | 100.0% | + +## rfc 9110 — `rfc/rfc9110.xml` + +| Section (id after `rfc9110.`) | Total | In scope | Out of scope | Covered | Lossy | Missing | Answered share | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `10` | 33 | 1 | 32 | 1 | 0 | 0 | 100.0% | +| `11` | 11 | 0 | 11 | 0 | 0 | 0 | — | +| `12` | 12 | 0 | 12 | 0 | 0 | 0 | — | +| `13` | 40 | 0 | 40 | 0 | 0 | 0 | — | +| `14` | 23 | 0 | 23 | 0 | 0 | 0 | — | +| `15` | 75 | 15 | 60 | 15 | 0 | 0 | 100.0% | +| `16` | 17 | 0 | 17 | 0 | 0 | 0 | — | +| `2` | 7 | 0 | 7 | 0 | 0 | 0 | — | +| `3` | 2 | 0 | 2 | 0 | 0 | 0 | — | +| `4` | 19 | 1 | 18 | 1 | 0 | 0 | 100.0% | +| `5` | 29 | 0 | 29 | 0 | 0 | 0 | — | +| `6` | 19 | 0 | 19 | 0 | 0 | 0 | — | +| `7` | 45 | 0 | 45 | 0 | 0 | 0 | — | +| `8` | 34 | 2 | 32 | 2 | 0 | 0 | 100.0% | +| `9` | 46 | 6 | 40 | 6 | 0 | 0 | 100.0% | + ## Markers per file | File | Requirements | | --- | ---: | | `conformance/coverage/suite.md` | 134 | -| `conformance/sdk/cases.json` | 46 | +| `conformance/sdk/cases.json` | 124 | | `crates/flowapi-cli/tests/documents_cli.rs` | 8 | | `crates/flowapi-cli/tests/openapi_cli.rs` | 30 | | `crates/flowapi-sdk/tests/cases/defaults.json` | 12 | -| `crates/flowapi-sdk/tests/cases/encoding.json` | 1 | +| `crates/flowapi-sdk/tests/cases/encoding-v30.json` | 6 | +| `crates/flowapi-sdk/tests/cases/encoding-v32.json` | 19 | +| `crates/flowapi-sdk/tests/cases/encoding.json` | 8 | | `crates/flowapi-sdk/tests/cases/security.json` | 22 | -| `crates/flowapi-sdk/tests/cases/servers.json` | 15 | +| `crates/flowapi-sdk/tests/cases/security30.json` | 20 | +| `crates/flowapi-sdk/tests/cases/security31.json` | 10 | +| `crates/flowapi-sdk/tests/cases/security32.json` | 25 | +| `crates/flowapi-sdk/tests/cases/servers.json` | 17 | +| `crates/flowapi-sdk/tests/cases/servers30.json` | 15 | +| `crates/flowapi-sdk/tests/cases/servers32.json` | 17 | +| `crates/flowapi-sdk/tests/cases/swagger-forms.json` | 4 | +| `crates/flowapi-sdk/tests/cases/swagger-host.json` | 1 | +| `crates/flowapi-sdk/tests/cases/swagger-nohost.json` | 1 | +| `crates/flowapi-sdk/tests/cases/swagger20-oauth.json` | 6 | +| `crates/flowapi-sdk/tests/cases/swagger20.json` | 16 | | `crates/flowapi-sdk/tests/cases/v32.json` | 12 | -| `crates/flowapi-ts/tests/print.rs` | 267 | +| `crates/flowapi-sdk/tests/client/auth.mjs` | 4 | +| `crates/flowapi-sdk/tests/client/http.mjs` | 20 | +| `crates/flowapi-sdk/tests/client/layers.mjs` | 4 | +| `crates/flowapi-sdk/tests/client/runtime.mjs` | 1 | +| `crates/flowapi-sdk/tests/client/schemes.mjs` | 12 | +| `crates/flowapi-sdk/tests/client/servers.mjs` | 16 | +| `crates/flowapi-sdk/tests/client/tokens.mjs` | 21 | +| `crates/flowapi-sdk/tests/client/wire.mjs` | 2 | +| `crates/flowapi-sdk/tests/table.rs` | 5 | +| `crates/flowapi-ts/tests/print.rs` | 368 | +| `crates/flowapi/tests/collection_format.rs` | 2 | | `crates/flowapi/tests/documents.rs` | 14 | +| `crates/flowapi/tests/form_encoding.rs` | 2 | | `crates/flowapi/tests/repo.rs` | 2 | ## Markers on out-of-scope requirements -- `oas-3.1.encoding-object.contentType` in `crates/flowapi-sdk/tests/cases/encoding.json:61` +None. diff --git a/conformance/ledger/README.md b/conformance/ledger/README.md index 3e49385..66c3aa2 100644 --- a/conformance/ledger/README.md +++ b/conformance/ledger/README.md @@ -7,12 +7,14 @@ marker, and a script counts the rest as missing. | File | What it is | Written by | | --- | --- | --- | -| `../specs/` | OpenAPI 3.0.4, 3.1.2, 3.2.1 and JSON Schema 2020-12 (core, validation), byte for byte | By hand, from the authors' repositories | +| `../specs/` | OpenAPI 2.0, 3.0.4, 3.1.2, 3.2.1, JSON Schema 2020-12 (core, validation) and RFCs 6749, 6750, 7578, 7617 and 9110, byte for byte | By hand, from the authors' repositories and the RFC Editor | | `../requirements.json` | Every requirement: id, text, section, anchor, line | `extract` | | `../scope.json` | Which ids are in scope, and why the others are not | By hand | | `../REPORT.md` | Per text and per section: total, in scope, out of scope, covered, lossy, missing | `report` | +| `../MISSING.md` | Every id in scope that no marker names, per text and section, with its sentence and the rule that put it in scope | `report` | | `../coverage/` | Markers grouped by oracle (`suite.md`: O3's keyword files), and `triage.md`: what no marker answers yet | By hand | | `../triage-2.md` | The second pass (2026-11-24): the 3.2.1 id changes, the scope decided, violations found, what is left; holds no markers | By hand | +| `../triage-3.md` | The SDK stage (2026-11-26): Swagger 2.0 and the RFCs pinned, the scope decided again for the SDK, section by section; holds no markers | By hand | ## What a requirement is @@ -23,6 +25,8 @@ marker, and a script counts the rest as missing. examples (fenced code, `<artwork>`) and editors' comments (`<cref>`) are not read. - **A row of an OpenAPI field table** (a first header cell `Field Name` or `Field Pattern`: fixed fields, patterned fields, specification extensions): `level` `field`, `text` the description. + OpenAPI 2.0 writes its tables without a leading `|` (`Field Name | Type | Description`); they + are read alike. - **A JSON Schema keyword**: one per keyword of the 2020-12 vocabularies, at the section that defines it; and in OpenAPI, each keyword listed under "JSON Schema Keywords": `level` `keyword`. @@ -30,7 +34,15 @@ marker, and a script counts the rest as missing. paragraph, row or section starts in the pinned file; `anchor` is the fragment of the rendered specification (a field's own `<a name>`, else the heading's slug as ReSpec makes it, `-0`, `-1` on repeats; for JSON Schema the section's `anchor`, else `section-N.M` or `appendix-A.N` as -xml2rfc numbers it). +xml2rfc numbers it; for an RFC `section-N.M` or `appendix-A.N` as the RFC Editor's HTML renders +it). + +The RFCs are read by their numbered sections. RFC 9110 from its RFCXML v3 source +(`src/rfc_xml.rs`: each `<t>`, list item, definition and table cell; code, artwork and the index +not read); the others, which have no XML at the RFC Editor, from their text (`src/rfc_text.rs`: +headings at column 0, page breaks removed, a list item a unit of its own, a word broken at its +hyphen joined). Neither reads the boilerplate, the table of contents, the References or the +unnumbered sections at the end. `tests/readers.rs` holds each reader to a fixture. ## Ids @@ -41,19 +53,23 @@ oas-3.1.schema-object.discriminator a field oas-3.2.parameter-object.style.must-… a sentence in that field's row oas-3.1.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field oas-3.0.responses-object.pattern-http-status-code a patterned field +oas-2.0.swagger-object.basePath.must-value-start-leading-slash jsonschema-2020-12.core.$ref a keyword jsonschema-2020-12.core.$ref.must-value-ref-keyword-string-uri-reference +rfc6749.4.4.2.must-value-set-client-credentials a sentence of RFC 6749 section 4.4.2 +rfc9110.B.1.<term>-<slug> appendix B.1 ``` -- `<text>` is `oas-3.0`, `oas-3.1`, `oas-3.2`, `jsonschema-2020-12.core` or - `jsonschema-2020-12.validation`. +- `<text>` is `oas-2.0`, `oas-3.0`, `oas-3.1`, `oas-3.2`, `jsonschema-2020-12.core`, + `jsonschema-2020-12.validation`, or an RFC: `rfc6749`, `rfc6750`, `rfc7578`, `rfc7617`, `rfc9110`. +- In an RFC, `<section>` is the section's number (`4.4.2`, `A.1`), and each sentence follows it. - `<section>` starts at the nearest base: an OpenAPI Object (`schema-object`), a JSON Schema keyword section (`$ref`) or a section with an anchor (`fragments`); without one, at the nearest heading whose slug is unique in the text. Then the heading itself; the headings between are added only when two sections would otherwise share an id. - `<term>` is the strongest keyword (`must`, `must-not`, `should`, `not-recommended`, `may`, ...), `<slug>` the sentence's first six words that are neither keywords nor stop words. -- An id taken twice gets `-2`, `-3` in document order (none today). Ids only change when the text +- An id taken twice gets `-2`, `-3` in document order (18 today, all in the RFCs). Ids only change when the text they come from does: a reworded sentence is a new requirement. ## Classes @@ -69,19 +85,28 @@ requirement in one class: | `deviates` | Not allowed without the owner's decision; no marker for it exists. | `scope.json` rules: `match` is an id or a prefix ending at a `.`, `*` stands for a version -(`oas-*.server-object`), the longest match wins. A rule that fits no id, or an id no rule fits, -fails `report`. The current file was decided 2026-11-24 by the maintainers, owner delegated (its `status`). +(`oas-*.server-object`, which fits `oas-2.0` too), the longest match wins. A rule that fits no id, +or an id no rule fits, fails `report`. An in-scope rule's `note` names the layer that answers for +the ids. The current file was decided 2026-11-24 and for the SDK stage 2026-11-26 +(`../triage-3.md`) by the maintainers, owner delegated (its `status`). ## Markers A marker is `req: <id>` (a test covers it) or `lossy: <id> — <reason>` (the type is wider than the -schema there; the reason is required) in any `.rs`, `.ts` or `.json` file under `crates/` or +schema there; the reason is required) in any `.rs`, `.ts`, `.mjs` or `.json` file under `crates/` or `conformance/`, and in the `.md` files of `conformance/coverage/`; usually a comment beside the test: `// req: oas-3.1.schema-object.discriminator`. Build output, `node_modules/`, the pinned -texts and suites, and the ledger's own files are not read. Only ids that start with `oas-` or -`jsonschema-` are markers, so `req: Request` in code is not one. An id that is not in +texts and suites, and the ledger's own files are not read. Only ids that start with `oas-`, +`jsonschema-` or `rfc` and a digit are markers, so `req: Request` in code is not one. In a JSON +case the markers are strings of `x-flowapi-covers` (`crates/flowapi-sdk/tests/cases/`) or +`covers` (`../sdk/cases.json`). An id that is not in `requirements.json` fails `report` (G13), and so does a lossy marker without a reason. An id with -both markers counts as lossy; one with neither is missing. +both markers counts as lossy; one with neither is missing, and is listed in `../MISSING.md`. + +A missing id fails no check: it is counted and listed. `report --check` fails on an unknown id, a +lossy marker without a reason, an unclassified id, a stale rule, and a `REPORT.md` or +`MISSING.md` that is not what `report` writes. A gate on missing ids would be a budget (a number +`report` refuses to rise above); there is none yet. ## Running it @@ -90,12 +115,13 @@ In `conformance/ledger/`; each takes well under a second. ```sh cargo run --release --bin extract # write ../requirements.json cargo run --release --bin extract -- --check # fail when it is stale -cargo run --release --bin report # write ../REPORT.md -cargo run --release --bin report -- --check # also fail when REPORT.md is stale +cargo run --release --bin report # write ../REPORT.md and ../MISSING.md +cargo run --release --bin report -- --check # also fail when either is stale cargo run --release --bin classify # counts per text and class cargo run --release --bin classify -- oas-3.1.parameter-object # each id, class, why cargo run --release --bin classify -- --missing oas-3.1.schema-object # in scope, no marker cargo test --release --test ledger # the ledger's own rules +cargo test --release --test readers # the OpenAPI 2.0, RFC text and RFCXML readers ``` Updating a text: [`../specs/SOURCE.md`](../specs/SOURCE.md), "Updating a text". diff --git a/conformance/ledger/src/bin/extract.rs b/conformance/ledger/src/bin/extract.rs index c7cd922..f58c051 100644 --- a/conformance/ledger/src/bin/extract.rs +++ b/conformance/ledger/src/bin/extract.rs @@ -8,7 +8,7 @@ use flowapi_ledger::requirements::{Requirement, parse, render}; use flowapi_ledger::rfc::KEYWORDS; use flowapi_ledger::sources::{Format, SOURCES}; -use flowapi_ledger::{extract, markdown, paths, rfc, xml}; +use flowapi_ledger::{extract, markdown, paths, rfc, rfc_text, rfc_xml, xml}; use std::collections::BTreeSet; use std::process::ExitCode; @@ -33,6 +33,10 @@ fn run() -> Result<ExitCode, String> { Format::Rfc => { rfc::read(&xml::parse(&text).map_err(|e| format!("{}: {e}", source.file))?) } + Format::RfcXml => { + rfc_xml::read(&xml::parse(&text).map_err(|e| format!("{}: {e}", source.file))?) + } + Format::RfcText => rfc_text::read(&text), }; all.extend(extract::requirements(&doc, source)); } diff --git a/conformance/ledger/src/bin/report.rs b/conformance/ledger/src/bin/report.rs index 29a7639..f0d1cba 100644 --- a/conformance/ledger/src/bin/report.rs +++ b/conformance/ledger/src/bin/report.rs @@ -1,13 +1,16 @@ -//! Writes `conformance/REPORT.md` from `requirements.json`, `scope.json` and the `req:` and -//! `lossy:` markers. Fails on a marker that names no requirement, a lossy marker without a reason, +//! Writes `conformance/REPORT.md` and `conformance/MISSING.md` (the requirements in scope no +//! marker names yet) from `requirements.json`, `scope.json` and the `req:` and `lossy:` markers. Fails on a marker that names no requirement, a lossy marker without a reason, //! a requirement no scope rule classifies, and a scope rule that fits no requirement. //! -//! cargo run --release --bin report write REPORT.md -//! cargo run --release --bin report -- --check also fail when REPORT.md is stale +//! cargo run --release --bin report write REPORT.md and MISSING.md +//! cargo run --release --bin report -- --check also fail when either is stale +//! +//! A missing requirement fails nothing: it is counted and listed. What fails is an unknown id, +//! an unclassified one, a stale rule, a reason left out, or a file that does not match. use flowapi_ledger::markers::{Kind, Marker, scan}; use flowapi_ledger::report::{Ledger, render}; -use flowapi_ledger::{paths, requirements, scope}; +use flowapi_ledger::{missing, paths, requirements, scope}; use std::collections::BTreeSet; use std::process::ExitCode; @@ -80,22 +83,29 @@ fn run() -> Result<ExitCode, String> { if failed { return Ok(ExitCode::FAILURE); } - let written = render(&Ledger { + let ledger = Ledger { requirements: &all, classes: &classes, scope: &scope, markers: &markers, - }); - let target = paths::report(); - if std::env::args().any(|arg| arg == "--check") { - if std::fs::read_to_string(&target).unwrap_or_default() != written { + }; + let outputs = [ + (paths::report(), "REPORT.md", render(&ledger)), + (paths::missing(), "MISSING.md", missing::render(&ledger)), + ]; + let check = std::env::args().any(|arg| arg == "--check"); + for (target, name, written) in &outputs { + if !check { + std::fs::write(target, written).map_err(|e| format!("{}: {e}", target.display()))?; + } else if std::fs::read_to_string(target).unwrap_or_default() != *written { eprintln!( - "report: conformance/REPORT.md is stale; run `cargo run --release --bin report`." + "report: conformance/{name} is stale; run `cargo run --release --bin report`." ); - return Ok(ExitCode::FAILURE); + failed = true; } - } else { - std::fs::write(&target, &written).map_err(|e| format!("{}: {e}", target.display()))?; + } + if failed { + return Ok(ExitCode::FAILURE); } let named = |kind: Kind| { markers diff --git a/conformance/ledger/src/lib.rs b/conformance/ledger/src/lib.rs index 50dde08..99de0d1 100644 --- a/conformance/ledger/src/lib.rs +++ b/conformance/ledger/src/lib.rs @@ -1,20 +1,25 @@ //! The requirements ledger of flowapi (oracle O1). //! -//! Every normative statement of the pinned specification texts (`conformance/specs/`) becomes a -//! requirement with a stable id: each sentence carrying an RFC 2119 / RFC 8174 keyword, each row of -//! an OpenAPI field table, each JSON Schema keyword. `scope.json` classifies the ids, `req:` markers +//! Every normative statement of the pinned specification texts (`conformance/specs/`: OpenAPI, +//! JSON Schema and the RFCs the SDK follows) becomes a requirement with a stable id: each sentence +//! carrying an RFC 2119 / RFC 8174 keyword, each row of an OpenAPI field table, each JSON Schema +//! keyword. `scope.json` classifies the ids, `req:` markers //! in flowapi's tests cover them, `lossy:` markers say where the type is wider and why, and -//! `REPORT.md` counts what is covered, what is lossy and what is missing. +//! `REPORT.md` counts what is covered, what is lossy and what is missing; `MISSING.md` lists the +//! missing ones. pub mod doc; pub mod extract; pub mod ids; pub mod markdown; pub mod markers; +pub mod missing; pub mod paths; pub mod report; pub mod requirements; pub mod rfc; +pub mod rfc_text; +pub mod rfc_xml; pub mod scope; pub mod sources; pub mod terms; diff --git a/conformance/ledger/src/markdown.rs b/conformance/ledger/src/markdown.rs index 062291d..a802dee 100644 --- a/conformance/ledger/src/markdown.rs +++ b/conformance/ledger/src/markdown.rs @@ -3,8 +3,10 @@ //! Headings nest by level; the level-1 title is the document and is left out of paths. Fenced //! code is skipped: examples state no requirement. A table whose first header cell is //! `Field Name` or `Field Pattern` gives one field unit per row; any other table gives one prose -//! unit per cell. Under a heading "JSON Schema Keywords", a list item that opens with a keyword -//! gives a keyword unit. +//! unit per cell. A table's rows may leave out the leading `|` (OpenAPI 2.0 writes them so): a +//! paragraph line with a `|` followed by a delimiter row (`---|:---:|---`) is a table's header, +//! and the lines with a `|` after it are its rows. Under a heading "JSON Schema Keywords", a list +//! item that opens with a keyword gives a keyword unit. use crate::doc::{Doc, Heading, Unit, UnitKind}; use crate::text::{clean_inline, heading_slug}; @@ -48,9 +50,12 @@ impl Reader { self.heading(number, level, title); } else if trimmed.is_empty() { self.flush(); - } else if trimmed.starts_with('|') { + } else if trimmed.starts_with('|') || (!self.table.is_empty() && trimmed.contains('|')) { self.flush_block(); self.table.push((number, trimmed.to_owned())); + } else if let Some(header) = self.bare_header(trimmed) { + self.table.push(header); + self.table.push((number, trimmed.to_owned())); } else if let Some(item) = list_item(trimmed) { self.flush(); self.block = Some((number, vec![item.to_owned()], true)); @@ -98,6 +103,24 @@ impl Reader { anchor } + /// A delimiter row under a one-line paragraph with a `|`: that line, taken as a table's header. + fn bare_header(&mut self, line: &str) -> Option<(usize, String)> { + let delimiter = line.contains('|') + && line.contains('-') + && line.chars().all(|c| matches!(c, '-' | ':' | '|' | ' ')); + let header = match &self.block { + Some((start, lines, false)) if delimiter && lines.len() == 1 => lines + .first() + .filter(|l| l.contains('|')) + .map(|l| (*start, l.clone())), + _ => None, + }; + if header.is_some() { + self.block = None; + } + header + } + fn current(&self) -> Option<usize> { self.stack.last().map(|(_, index)| *index) } diff --git a/conformance/ledger/src/markers.rs b/conformance/ledger/src/markers.rs index 7b56106..da2c876 100644 --- a/conformance/ledger/src/markers.rs +++ b/conformance/ledger/src/markers.rs @@ -2,12 +2,13 @@ //! covers a requirement; `lossy: jsonschema-2020-12.validation.minLength — no TS type has a //! length` says the type is wider than the schema there, and why. A lossy marker needs its reason. //! -//! Every `.rs`, `.ts` and `.json` file under `crates/` and `conformance/` is read, and the `.md` +//! Every `.rs`, `.ts`, `.mjs` and `.json` file under `crates/` and `conformance/` is read (`.mjs`: +//! the SDK client's Node tests), and the `.md` //! files of `conformance/coverage/` (evidence grouped by oracle), except build output (`target/`, //! `out/`), installed packages (`node_modules/`), ignored work folders (`scratch/`), the pinned texts and suites //! (`conformance/specs/`, `conformance/suites/`) and the ledger's own files. A marker is `req:` or -//! `lossy:` followed by an id that starts with `oas-` or `jsonschema-`, so `req: Request` in code -//! is not one. +//! `lossy:` followed by an id that starts with `oas-`, `jsonschema-` or `rfc` and a digit +//! (`rfc6749.`), so `req: Request` in code is not one. use std::path::{Path, PathBuf}; @@ -35,7 +36,7 @@ pub struct Marker { pub reason: String, } -const EXTENSIONS: [&str; 3] = ["rs", "ts", "json"]; +const EXTENSIONS: [&str; 4] = ["rs", "ts", "mjs", "json"]; /// Where `.md` files are read too: the evidence grouped by oracle. const MARKDOWN_UNDER: &str = "conformance/coverage/"; /// Names of folders never read, wherever they are: build output, installed packages, git's own, @@ -112,6 +113,15 @@ fn walk(root: &Path, dir: &Path, files: &mut Vec<(String, PathBuf)>) -> Result<( Ok(()) } +/// Whether a word is a requirement id: one of OpenAPI (`oas-`), JSON Schema (`jsonschema-`) or +/// an RFC (`rfc` and its number). +fn is_spec_id(id: &str) -> bool { + let rfc = id + .strip_prefix("rfc") + .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())); + rfc || id.starts_with("oas-") || id.starts_with("jsonschema-") +} + /// The ids the `req:` markers of one line name. pub fn ids_in(line: &str) -> Vec<String> { markers_in(line) @@ -141,7 +151,7 @@ pub fn markers_in(line: &str) -> Vec<(Kind, String, String)> { .take_while(|c| c.is_ascii_alphanumeric() || "$._-".contains(*c)) .collect(); let id = id.trim_end_matches(['.', '-']).to_owned(); - if boundary && (id.starts_with("oas-") || id.starts_with("jsonschema-")) { + if boundary && is_spec_id(&id) { found.push((at, start + id.len(), kind, id)); } } diff --git a/conformance/ledger/src/missing.rs b/conformance/ledger/src/missing.rs new file mode 100644 index 0000000..7bf48ad --- /dev/null +++ b/conformance/ledger/src/missing.rs @@ -0,0 +1,99 @@ +//! `MISSING.md`: every requirement in scope that no marker names yet, per text and per section of +//! that text, in the text's own order, each with its sentence and the scope rule that put it in +//! scope (its `note` in `scope.json` names the layer that answers for it). The work list of what +//! flowapi answers for and no test shows yet; `REPORT.md` has the counts. + +use crate::report::Ledger; +use crate::requirements::Requirement; +use crate::scope::Class; +use crate::sources::SOURCES; +use std::collections::{BTreeMap, BTreeSet}; + +/// One section's missing requirements: where the section starts, its title, its anchor and the +/// requirements with the pattern of the rule that classifies each. +struct Section<'a> { + line: usize, + title: &'a str, + anchor: &'a str, + rows: Vec<(&'a Requirement, &'a str)>, +} + +/// Renders the list. +pub fn render(ledger: &Ledger<'_>) -> String { + let marked: BTreeSet<&str> = ledger.markers.iter().map(|m| m.id.as_str()).collect(); + let mut by_source: BTreeMap<&str, BTreeMap<&str, Section<'_>>> = BTreeMap::new(); + let mut total = 0; + for (requirement, rule) in ledger.requirements.iter().zip(ledger.classes) { + let Some(rule) = rule.filter(|r| r.class == Class::InScope) else { + continue; + }; + if marked.contains(requirement.id.as_str()) { + continue; + } + total += 1; + let section = by_source + .entry(&requirement.source) + .or_default() + .entry(&requirement.section) + .or_insert(Section { + line: requirement.line, + title: &requirement.section, + anchor: &requirement.anchor, + rows: Vec::new(), + }); + if requirement.line < section.line { + section.line = requirement.line; + section.anchor = &requirement.anchor; + } + section.rows.push((requirement, &rule.pattern)); + } + let mut out = vec![ + "# Requirements missing a test".to_owned(), + String::new(), + "Written by `cargo run --release --bin report` in `conformance/ledger/`, with `REPORT.md`. Do not edit by hand.".to_owned(), + "Every requirement `scope.json` puts in scope that no `req:` or `lossy:` marker names yet, per text and".to_owned(), + "section in the text's order. After each id, the scope rule that classifies it: its `note` names the".to_owned(), + "layer that answers for it.".to_owned(), + String::new(), + format!("**{total} missing.**"), + ]; + for source in &SOURCES { + let Some(sections) = by_source.get(source.file) else { + continue; + }; + let count: usize = sections.values().map(|s| s.rows.len()).sum(); + out.push(String::new()); + out.push(format!( + "## {} {} — `{}`: {count} missing", + source.spec, source.version, source.file + )); + let mut ordered: Vec<&Section<'_>> = sections.values().collect(); + ordered.sort_by_key(|s| s.line); + for section in ordered { + out.push(String::new()); + out.push(format!( + "### {} (`#{}`, line {})", + if section.title.is_empty() { + "(top)" + } else { + section.title + }, + section.anchor, + section.line + )); + out.push(String::new()); + let mut rows = section.rows.clone(); + rows.sort_by_key(|(r, _)| r.line); + out.extend(rows.iter().map(|(r, pattern)| { + format!( + "- `{}` ({}, by `{pattern}`): {}", + r.id, + r.level, + r.text.replace('\n', " ") + ) + })); + } + } + out.push(String::new()); + out.join("\n") +} diff --git a/conformance/ledger/src/paths.rs b/conformance/ledger/src/paths.rs index ba450fe..f40e937 100644 --- a/conformance/ledger/src/paths.rs +++ b/conformance/ledger/src/paths.rs @@ -31,3 +31,9 @@ pub fn scope() -> PathBuf { pub fn report() -> PathBuf { conformance().join("REPORT.md") } + +/// `conformance/MISSING.md`: the requirements in scope that no marker names yet. Beside +/// `REPORT.md`, not under `coverage/`: that folder holds the markers' Markdown, read by the scan. +pub fn missing() -> PathBuf { + conformance().join("MISSING.md") +} diff --git a/conformance/ledger/src/rfc_text.rs b/conformance/ledger/src/rfc_text.rs new file mode 100644 index 0000000..87842f3 --- /dev/null +++ b/conformance/ledger/src/rfc_text.rs @@ -0,0 +1,210 @@ +//! Reads an RFC's plain text, as the RFC Editor publishes it (`rfcNNNN.txt`), into a [`Doc`]. +//! +//! For the RFCs that have no XML source at the RFC Editor (those before RFCXML v3). A section +//! heading starts at column 0 with its number (`4.4.2. Access Token Response`, `Appendix A. ...`, +//! `A.1. ...`); its component is that number, so the ids are `rfc6749.4.4.2.<term>-<slug>` and +//! its anchor `section-4.4.2` or `appendix-A.1` as the RFC Editor's HTML renders them. Each run +//! of non-blank lines is a prose unit, and so is each bulleted item (`o `), its bullet left +//! out; a word the line breaks after its hyphen is joined again. Page breaks (the footer, the form feed and the running +//! header) are removed, and a paragraph cut by one is joined again. +//! +//! What states no requirement of the protocol is not read: everything before section 1 (the +//! abstract, Status of This Memo, the copyright notice, the table of contents), the References +//! sections, and the unnumbered sections at the end (Acknowledgements, Authors' Addresses). The +//! sentence that defines the keywords quotes them, so `terms` finds none in it. Only keywords in +//! capitals count, as BCP 14 says for these RFCs too (RFC 2119's own use is capitals). + +use crate::doc::{Doc, Heading, Unit, UnitKind}; +use crate::text::collapse; + +/// Reads an RFC's text. +pub fn read(source: &str) -> Doc { + let mut reader = Reader::default(); + for (number, line) in without_pages(source) { + reader.line(number, line); + } + reader.flush(); + reader.doc +} + +/// The lines of the text, page breaks removed: (line number, line). A paragraph a page break +/// cuts runs on: the line after the break is as indented as the one before it, and that one does +/// not end a sentence. Otherwise one blank line keeps the two apart. +fn without_pages(source: &str) -> Vec<(usize, &str)> { + let mut kept: Vec<(usize, &str)> = Vec::new(); + let mut header_next = false; + // After a break: the indent of the last line before it, when that line ends no sentence. + let mut cut: Option<Option<usize>> = None; + for (index, line) in source.lines().enumerate() { + let number = index + 1; + if std::mem::take(&mut header_next) && line.starts_with("RFC ") { + continue; + } + if line.starts_with('\u{c}') { + header_next = true; + continue; + } + if is_footer(line) { + while kept.last().is_some_and(|(_, l)| l.trim().is_empty()) { + kept.pop(); + } + let open = kept + .last() + .filter(|(_, l)| !l.trim_end().ends_with(['.', ':'])) + .map(|(_, l)| indent(l)); + cut = Some(open); + continue; + } + if line.trim().is_empty() && cut.is_some() { + continue; + } + if let Some(open) = cut.take() + && open != Some(indent(line)) + { + kept.push((number, "")); + } + kept.push((number, line)); + } + kept +} + +fn indent(line: &str) -> usize { + line.len() - line.trim_start().len() +} + +/// `Hardt Standards Track [Page 4]`. +fn is_footer(line: &str) -> bool { + let trimmed = line.trim_end(); + trimmed.ends_with(']') && trimmed.rfind("[Page ").is_some_and(|at| at > 0) +} + +#[derive(Default)] +struct Reader { + doc: Doc, + /// Whether the lines read belong to a section whose text is read. + reading: bool, + /// The open heading. + current: Option<usize>, + /// The paragraph being read: its first line and its lines. + block: Option<(usize, Vec<String>)>, + /// The indent of the paragraph's last line: a line less indented starts a new one (prose + /// after an example, a list's next term). + last_indent: usize, +} + +impl Reader { + fn line(&mut self, number: usize, line: &str) { + if let Some((label, title)) = heading(line) { + self.flush(); + self.heading(number, &label, title); + return; + } + let unnumbered = line.starts_with(|c: char| c.is_ascii_alphabetic()); + if unnumbered && !self.doc.headings.is_empty() { + self.flush(); + self.reading = false; + return; + } + if !self.reading { + return; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + self.flush(); + return; + } + let fell_back = indent(line) < std::mem::replace(&mut self.last_indent, indent(line)); + if fell_back { + self.flush(); + } + if let Some(item) = bullet(trimmed) { + self.flush(); + self.block = Some((number, vec![item.to_owned()])); + return; + } + match &mut self.block { + Some((_, lines)) => lines.push(trimmed.to_owned()), + None => self.block = Some((number, vec![trimmed.to_owned()])), + } + } + + fn heading(&mut self, number: usize, label: &str, title: &str) { + let parent_label = label.rsplit_once('.').map(|(head, _)| head); + let parent = parent_label.and_then(|wanted| { + self.doc + .headings + .iter() + .rposition(|h| h.component == wanted) + }); + let appendix = label.starts_with(|c: char| c.is_ascii_uppercase()); + let anchor = match appendix { + true => format!("appendix-{label}"), + false => format!("section-{label}"), + }; + let title = collapse(title); + self.reading = !is_references(&title); + self.current = Some(self.doc.headings.len()); + self.doc.headings.push(Heading { + title, + component: label.to_owned(), + base: true, + anchor, + parent, + line: number, + }); + } + + fn flush(&mut self) { + let Some((line, lines)) = self.block.take() else { + return; + }; + let mut text = String::new(); + for part in lines { + let hyphen = text.ends_with('-') + && text.chars().rev().nth(1).is_some_and(char::is_alphanumeric) + && part.starts_with(|c: char| c.is_ascii_alphanumeric()); + if !text.is_empty() && !hyphen { + text.push(' '); + } + text.push_str(&part); + } + self.doc.units.push(Unit { + heading: self.current, + line, + kind: UnitKind::Prose, + text: collapse(&text), + }); + } +} + +/// A list item's text without its bullet (`o `, `* `, `- `): each item is a unit of its own. +fn bullet(line: &str) -> Option<&str> { + ["o ", "* ", "- "] + .iter() + .find_map(|marker| line.strip_prefix(marker)) + .map(str::trim_start) +} + +fn is_references(title: &str) -> bool { + title.ends_with("References") +} + +/// A section heading at column 0: `4.4.2. Title` gives (`4.4.2`, `Title`), `Appendix A. Title` +/// gives (`A`, `Title`), `A.1. Title` gives (`A.1`, `Title`). +pub fn heading(line: &str) -> Option<(String, &str)> { + let (label, rest) = match line.strip_prefix("Appendix ") { + Some(rest) => rest.split_once(". ")?, + None => line.split_once(". ")?, + }; + let title = rest.trim(); + let mut parts = label.split('.'); + let first = parts.next()?; + let numbered = !first.is_empty() && first.chars().all(|c| c.is_ascii_digit()); + let lettered = first.len() == 1 && first.chars().all(|c| c.is_ascii_uppercase()); + let rest_numbers = parts.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit())); + let appendix_word = line.starts_with("Appendix "); + let shape = + (numbered && !appendix_word) || (lettered && (appendix_word || label.contains('.'))); + (shape && rest_numbers && !title.is_empty() && !title.ends_with(['.', ','])) + .then(|| (label.to_owned(), title)) +} diff --git a/conformance/ledger/src/rfc_xml.rs b/conformance/ledger/src/rfc_xml.rs new file mode 100644 index 0000000..ecfa20e --- /dev/null +++ b/conformance/ledger/src/rfc_xml.rs @@ -0,0 +1,191 @@ +//! Reads an RFC's RFCXML v3 source, as the RFC Editor publishes it (`rfcNNNN.xml`), into a [`Doc`]. +//! +//! The published v3 file is "prepped": every section carries its number in `pn` +//! (`section-11.6.1`, `section-appendix.b.1`). A section's component is that number (`11.6.1`, +//! `B.1`), so the ids are `rfc9110.11.6.1.<term>-<slug>`, as for an RFC read from its text +//! (`rfc_text`); its anchor is `section-11.6.1` or `appendix-B.1`, as the RFC Editor's HTML +//! renders it. Each `<t>`, list item, definition and table cell is a prose unit (a `<dt>`'s +//! text leads its `<dd>`); code and artwork (`<sourcecode>`, `<artwork>`) are examples and +//! grammar, and index entries (`<iref>`) are not text, so neither is read. `<bcp14>` holds a +//! keyword in capitals; `terms` finds it as it finds one in plain text. +//! +//! The boilerplate (`<front>`: Status of This Memo, the copyright notice) and `<references>` +//! are outside `<middle>` and `<back>`'s sections; the unnumbered sections (Acknowledgements, +//! the index, Authors' Addresses) are not read. + +use crate::doc::{Doc, Heading, Unit, UnitKind}; +use crate::text::collapse; +use crate::xml::{Element, Node}; + +/// Reads a prepped RFCXML v3 document. +pub fn read(root: &Element) -> Doc { + let mut doc = Doc::default(); + for part in root.elements() { + if matches!(part.name.as_str(), "middle" | "back") { + for section in part.elements().filter(|e| e.name == "section") { + read_section(&mut doc, section, None); + } + } + } + doc +} + +/// `section-11.6.1` gives `11.6.1`; `section-appendix.b.1` gives `B.1`. +pub fn number(pn: &str) -> Option<String> { + let rest = pn.strip_prefix("section-")?; + match rest.strip_prefix("appendix.") { + Some(appendix) => { + let (letter, tail) = appendix.split_at_checked(1)?; + Some(format!("{}{tail}", letter.to_ascii_uppercase())) + } + None => rest + .chars() + .all(|c| c.is_ascii_digit() || c == '.') + .then(|| rest.to_owned()), + } +} + +fn read_section(doc: &mut Doc, section: &Element, parent: Option<usize>) { + let numbered = section.attr("numbered") != Some("false"); + let Some(label) = section.attr("pn").and_then(number).filter(|_| numbered) else { + return; + }; + let title = section + .elements() + .find(|e| e.name == "name") + .map(|name| collapse(&inline_text(name)).replace('\n', " ")) + .unwrap_or_default(); + let anchor = match label.starts_with(|c: char| c.is_ascii_uppercase()) { + true => format!("appendix-{label}"), + false => format!("section-{label}"), + }; + let index = doc.headings.len(); + doc.headings.push(Heading { + title, + component: label, + base: true, + anchor, + parent, + line: section.line, + }); + for child in section.elements() { + match child.name.as_str() { + "section" => read_section(doc, child, Some(index)), + "name" => {} + _ => block(doc, child, index, ""), + } + } +} + +/// A block element: a paragraph is a unit; a list, a definition list, a table or an aside holds +/// blocks; code, artwork and index entries are not read. `label` leads the first unit (a `<dt>`). +fn block(doc: &mut Doc, element: &Element, heading: usize, label: &str) { + match element.name.as_str() { + "t" | "dt" | "td" | "th" => unit(doc, element, heading, label), + "li" | "dd" | "blockquote" | "aside" => { + let holds_blocks = element.elements().any(|e| is_block(&e.name)); + if holds_blocks { + let mut lead = label.to_owned(); + for child in element.elements() { + block(doc, child, heading, &lead); + lead.clear(); + } + } else { + unit(doc, element, heading, label); + } + } + "dl" => { + let mut term = String::new(); + for child in element.elements() { + match child.name.as_str() { + "dt" => term = collapse(&inline_text(child)).replace('\n', " "), + _ => block(doc, child, heading, &std::mem::take(&mut term)), + } + } + } + "ul" | "ol" | "table" | "thead" | "tbody" | "tfoot" | "tr" => { + for child in element.elements() { + block(doc, child, heading, ""); + } + } + _ => {} + } +} + +fn is_block(name: &str) -> bool { + matches!( + name, + "t" | "ul" + | "ol" + | "dl" + | "table" + | "figure" + | "sourcecode" + | "artwork" + | "aside" + | "blockquote" + ) +} + +fn unit(doc: &mut Doc, element: &Element, heading: usize, label: &str) { + let mut text = String::new(); + if !label.is_empty() { + text.push_str(label); + text.push(' '); + } + text.push_str(&inline_text(element)); + let text = collapse(&text.replace('\n', " ")); + if !text.is_empty() { + doc.units.push(Unit { + heading: Some(heading), + line: element.line, + kind: UnitKind::Prose, + text, + }); + } +} + +/// The text of inline content: references as the RFC renders them, index entries and examples +/// left out. +fn inline_text(element: &Element) -> String { + let mut out = String::new(); + for node in &element.children { + match node { + Node::Text(text) => out.push_str(text), + Node::Element(child) => match child.name.as_str() { + "iref" | "sourcecode" | "artwork" | "figure" | "cref" => {} + "br" => out.push(' '), + "xref" => out.push_str(&reference(child)), + "contact" => out.push_str(child.attr("fullname").unwrap_or_default()), + _ => out.push_str(&inline_text(child)), + }, + } + } + out +} + +/// An `<xref>`: its own text, else what xml2rfc derived (`Section 6.2`, `[RFC1952]`, `Section +/// 3.5 of [URI]`). +fn reference(xref: &Element) -> String { + let own = inline_text(xref); + if !own.trim().is_empty() { + return own; + } + let derived = xref.attr("derivedContent").unwrap_or_default(); + if let Some(section) = xref.attr("section") { + return match xref.attr("sectionFormat") { + Some("comma") => format!("[{derived}], Section {section}"), + Some("bare") => section.to_owned(), + Some("parens") => format!("[{derived}] (Section {section})"), + _ => format!("Section {section} of [{derived}]"), + }; + } + let plain = xref.attr("format") == Some("counter") + || derived.starts_with("Section") + || derived.starts_with("Appendix"); + match (plain, derived.is_empty()) { + (_, true) => String::new(), + (true, false) => derived.to_owned(), + (false, false) => format!("[{derived}]"), + } +} diff --git a/conformance/ledger/src/sources.rs b/conformance/ledger/src/sources.rs index bf8ae5b..73ab21f 100644 --- a/conformance/ledger/src/sources.rs +++ b/conformance/ledger/src/sources.rs @@ -7,14 +7,19 @@ pub enum Format { Markdown, /// An xml2rfc v2 source. Rfc, + /// An RFCXML v3 source, as the RFC Editor publishes it (`rfcNNNN.xml`). + RfcXml, + /// An RFC's plain text, as the RFC Editor publishes it (`rfcNNNN.txt`), for the RFCs that + /// have no XML there. + RfcText, } /// One pinned text. #[derive(Debug, Clone, Copy)] pub struct Source { - /// `openapi` or `json-schema`. + /// `openapi`, `json-schema` or `rfc`. pub spec: &'static str, - /// The release: `3.1.2`, `2020-12`. + /// The release: `3.1.2`, `2020-12`; an RFC's number. pub version: &'static str, /// The path under `conformance/specs/`. pub file: &'static str, @@ -25,7 +30,14 @@ pub struct Source { } /// Every text, in the order the report lists them. -pub const SOURCES: [Source; 5] = [ +pub const SOURCES: [Source; 11] = [ + Source { + spec: "openapi", + version: "2.0", + file: "openapi/2.0.md", + prefix: "oas-2.0", + format: Format::Markdown, + }, Source { spec: "openapi", version: "3.0.4", @@ -61,6 +73,41 @@ pub const SOURCES: [Source; 5] = [ prefix: "jsonschema-2020-12.validation", format: Format::Rfc, }, + Source { + spec: "rfc", + version: "6749", + file: "rfc/rfc6749.txt", + prefix: "rfc6749", + format: Format::RfcText, + }, + Source { + spec: "rfc", + version: "6750", + file: "rfc/rfc6750.txt", + prefix: "rfc6750", + format: Format::RfcText, + }, + Source { + spec: "rfc", + version: "7578", + file: "rfc/rfc7578.txt", + prefix: "rfc7578", + format: Format::RfcText, + }, + Source { + spec: "rfc", + version: "7617", + file: "rfc/rfc7617.txt", + prefix: "rfc7617", + format: Format::RfcText, + }, + Source { + spec: "rfc", + version: "9110", + file: "rfc/rfc9110.xml", + prefix: "rfc9110", + format: Format::RfcXml, + }, ]; /// The text a file under `conformance/specs/` is. diff --git a/conformance/ledger/tests/readers.rs b/conformance/ledger/tests/readers.rs new file mode 100644 index 0000000..3a131d4 --- /dev/null +++ b/conformance/ledger/tests/readers.rs @@ -0,0 +1,213 @@ +//! The readers of the texts the SDK follows, each on a small fixture: OpenAPI 2.0's Markdown +//! (tables without a leading `|`), an RFC's plain text and an RFCXML v3 source. + +use flowapi_ledger::markers::ids_in; +use flowapi_ledger::requirements::Requirement; +use flowapi_ledger::sources::{Format, SOURCES, Source}; +use flowapi_ledger::{extract, markdown, rfc_text, rfc_xml, xml}; + +fn source(format: Format, version: &str) -> Source { + SOURCES + .iter() + .find(|s| s.format == format && s.version == version) + .copied() + .unwrap() +} + +fn ids(found: &[Requirement]) -> Vec<&str> { + found.iter().map(|r| r.id.as_str()).collect() +} + +#[test] +fn openapi_2_tables_without_a_leading_pipe_give_fields() { + let text = "# OpenAPI Specification\n\n### Schema\n\n#### Security Scheme Object\n\n##### Fixed Fields\nField Name | Type | Validity | Description\n---|:---:|---|---\n<a name=\"securitySchemeType\"></a>type | `string` | Any | **Required.** The type. Valid values are `\"basic\"`.\n<a name=\"securitySchemeTokenUrl\"></a>tokenUrl | `string` | `oauth2` | **Required.** The token URL. This SHOULD be in the form of a URL.\n\nA plain line with a | in it is prose.\n"; + let found = extract::requirements(&markdown::read(text), &source(Format::Markdown, "2.0")); + assert_eq!( + ids(&found), + [ + "oas-2.0.security-scheme-object.type", + "oas-2.0.security-scheme-object.tokenUrl", + "oas-2.0.security-scheme-object.tokenUrl.should-form-url", + ] + ); + assert_eq!( + found.get(1).map(|r| r.anchor.as_str()), + Some("securitySchemeTokenUrl") + ); + assert_eq!(found.get(2).map(|r| r.line), Some(11)); +} + +const RFC_TEXT: &str = "Internet Engineering Task Force (IETF) A. Author +Request for Comments: 9999 + +Abstract + + This document MUST be ignored: it is the abstract. + +Status of This Memo + + The text of the memo SHALL not count. + +1. Introduction + + The key words \"MUST\", \"MUST NOT\" and \"MAY\" in this document are to be + interpreted as described in [RFC2119]. + +4.4. A Grant + + The client MUST send the user- + agent away. A client must not count in lower case. + + POST /token HTTP/1.1 + The server MAY answer. + + o The token is OPTIONAL. + + grant_type + REQUIRED. Value MUST be set to \"client_credentials\". The client + MUST keep the + + + +Author Standards Track [Page 4] +\u{c} +RFC 9999 A Grant October 2012 + + + secret. + +Appendix A. Syntax + + A.1 states nothing. + +A.1. The Name + + A name SHOULD be short. + +5. References + + [RFC2119] Bradner, S., \"Key words\" MUST be read. + +Author's Address + + A. Author MUST be reachable. +"; + +#[test] +fn an_rfc_text_gives_numbered_sections_and_skips_the_boilerplate() { + let doc = rfc_text::read(RFC_TEXT); + let found = extract::requirements(&doc, &source(Format::RfcText, "6749")); + assert_eq!( + ids(&found), + [ + "rfc6749.4.4.must-client-send-user-agent-away", + "rfc6749.4.4.may-server-answer", + "rfc6749.4.4.optional-token", + "rfc6749.4.4.required-grant-type", + "rfc6749.4.4.must-value-set-client-credentials", + "rfc6749.4.4.must-client-keep-secret", + "rfc6749.A.1.should-name-short", + ] + ); + let texts: Vec<&str> = found.iter().map(|r| r.text.as_str()).collect(); + assert_eq!( + texts.first(), + Some(&"The client MUST send the user-agent away.") + ); + assert_eq!(texts.get(5), Some(&"The client MUST keep the secret.")); + let last = found.last().unwrap(); + assert_eq!( + (last.anchor.as_str(), last.section.as_str()), + ("appendix-A.1", "Syntax > The Name") + ); + assert_eq!(found.first().map(|r| r.line), Some(19)); +} + +#[test] +fn an_rfc_heading_is_a_number_at_column_0() { + assert_eq!( + rfc_text::heading("4.4.2. Access Token Response"), + Some(("4.4.2".to_owned(), "Access Token Response")) + ); + assert_eq!( + rfc_text::heading("Appendix B. Use of a Media Type"), + Some(("B".to_owned(), "Use of a Media Type")) + ); + assert!(rfc_text::heading(" 4.4. Indented").is_none()); + assert!(rfc_text::heading("Request for Comments: 6749").is_none()); + assert!(rfc_text::heading("A. Author MUST be reachable.").is_none()); +} + +const RFC_XML: &str = r#"<?xml version='1.0' encoding='utf-8'?> +<rfc version="3" number="9110"> + <front> + <boilerplate> + <section numbered="false" pn="section-boilerplate.1"><name>Status of This Memo</name> + <t>This memo MUST not count.</t></section> + </boilerplate> + </front> + <middle> + <section anchor="auth" numbered="true" pn="section-11"> + <name slugifiedName="name-http-authentication">HTTP Authentication</name> + <section anchor="credentials" numbered="true" pn="section-11.4"> + <name>Credentials</name> + <iref item="Grammar" subitem="credentials"/> + <t>A user agent <bcp14>MUST</bcp14> send them as <xref target="RFC7617" format="default" derivedContent="RFC7617"/> says, per <xref target="field.authorization" format="default" derivedContent="Section 11.6.2"/>.</t> + <sourcecode type="abnf9110">credentials = auth-scheme MUST</sourcecode> + <ul><li><t>A token <bcp14>SHOULD NOT</bcp14> be reused.</t></li><li>Each list item <bcp14>MAY</bcp14> be read.</li></ul> + <dl><dt>realm:</dt><dd>The realm <bcp14>MUST</bcp14> be quoted.</dd></dl> + </section> + </section> + </middle> + <back> + <references pn="section-19"><name>References</name></references> + <section numbered="true" pn="section-appendix.b.1"><name>Changes</name> + <t>An appendix <bcp14>MAY</bcp14> state it.</t></section> + <section numbered="false" pn="section-appendix.e"><name>Authors' Addresses</name> + <t>An author <bcp14>MUST</bcp14> not count.</t></section> + </back> +</rfc> +"#; + +#[test] +fn an_rfcxml_v3_source_gives_its_numbered_sections() { + let root = xml::parse(RFC_XML).unwrap(); + let found = extract::requirements(&rfc_xml::read(&root), &source(Format::RfcXml, "9110")); + assert_eq!( + ids(&found), + [ + "rfc9110.11.4.must-user-agent-send-them-rfc7617-says", + "rfc9110.11.4.should-not-token-reused", + "rfc9110.11.4.may-each-list-item-read", + "rfc9110.11.4.must-realm-realm-quoted", + "rfc9110.B.1.may-appendix-state", + ] + ); + assert_eq!( + found.first().map(|r| r.text.as_str()), + Some("A user agent MUST send them as [RFC7617] says, per Section 11.6.2.") + ); + assert_eq!( + found + .first() + .map(|r| (r.anchor.as_str(), r.section.as_str())), + Some(("section-11.4", "HTTP Authentication > Credentials")) + ); + assert_eq!( + found.last().map(|r| r.anchor.as_str()), + Some("appendix-B.1") + ); + assert_eq!( + rfc_xml::number("section-appendix.b.1").as_deref(), + Some("B.1") + ); +} + +#[test] +fn markers_name_rfc_ids_too() { + assert_eq!( + ids_in("// req: rfc6750.2.1.must-clients-use-bearer-authentication-scheme — sent"), + ["rfc6750.2.1.must-clients-use-bearer-authentication-scheme"] + ); + assert!(ids_in("req: rfcs are texts").is_empty()); +} diff --git a/conformance/props/Cargo.lock b/conformance/props/Cargo.lock index 359081c..67c193a 100644 --- a/conformance/props/Cargo.lock +++ b/conformance/props/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-props" @@ -18,7 +18,7 @@ dependencies = [ [[package]] name = "flowapi-ts" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] diff --git a/conformance/requirements.json b/conformance/requirements.json index f16d65a..5ebbfcf 100644 --- a/conformance/requirements.json +++ b/conformance/requirements.json @@ -1,11 +1,17 @@ { "about": "Every normative statement of the pinned texts in specs/ (SOURCE.md). Written by `cargo run --release --bin extract` in conformance/ledger/; never edited by hand.", "sources": [ + { "spec": "openapi", "version": "2.0", "file": "openapi/2.0.md" }, { "spec": "openapi", "version": "3.0.4", "file": "openapi/3.0.4.md" }, { "spec": "openapi", "version": "3.1.2", "file": "openapi/3.1.2.md" }, { "spec": "openapi", "version": "3.2.1", "file": "openapi/3.2.1.md" }, { "spec": "json-schema", "version": "2020-12", "file": "json-schema-2020-12/jsonschema-core.xml" }, - { "spec": "json-schema", "version": "2020-12", "file": "json-schema-2020-12/jsonschema-validation.xml" } + { "spec": "json-schema", "version": "2020-12", "file": "json-schema-2020-12/jsonschema-validation.xml" }, + { "spec": "rfc", "version": "6749", "file": "rfc/rfc6749.txt" }, + { "spec": "rfc", "version": "6750", "file": "rfc/rfc6750.txt" }, + { "spec": "rfc", "version": "7578", "file": "rfc/rfc7578.txt" }, + { "spec": "rfc", "version": "7617", "file": "rfc/rfc7617.txt" }, + { "spec": "rfc", "version": "9110", "file": "rfc/rfc9110.xml" } ], "requirements": [ { @@ -4425,16648 +4431,28192 @@ "text": "The value of this keyword MUST be a boolean." }, { - "id": "oas-3.0.appendix-c-using-rfc6570-based-serialization.may-implementations-specification-use-implementation-rfc6570-perform", + "id": "oas-2.0.contact-object.email", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3914, - "section": "Appendix C: Using RFC6570-Based Serialization", - "anchor": "appendix-c-using-rfc6570-based-serialization", - "level": "MAY", - "terms": ["MAY"], - "text": "Implementations of this specification MAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 196, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contactEmail", + "level": "field", + "terms": [], + "text": "The email address of the contact person/organization. MUST be in the format of an email address." }, { - "id": "oas-3.0.appendix-d-serializing-headers-and-cookies.not-recommended-note-standard-base64-encoding-alphabet-includes", + "id": "oas-2.0.contact-object.email.must-format-email-address", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 4161, - "section": "Appendix D: Serializing Headers and Cookies", - "anchor": "appendix-d-serializing-headers-and-cookies", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Note that the standard base64-encoding alphabet includes non-URL-safe characters that are percent-encoded by RFC6570 expansion; serializing values through both encodings is NOT RECOMMENDED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 196, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contactEmail", + "level": "MUST", + "terms": ["MUST"], + "text": "MUST be in the format of an email address." }, { - "id": "oas-3.0.appendix-f-resolving-security-requirements-in-a-referenced-document.recommended-however-documented-section-tools-resolve-component", + "id": "oas-2.0.contact-object.name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 4360, - "section": "Appendix F: Resolving Security Requirements in a Referenced Document", - "anchor": "appendix-f-resolving-security-requirements-in-a-referenced-document", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, documented in that section, it is RECOMMENDED that tools resolve component names from the entry document." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 194, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contactName", + "level": "field", + "terms": [], + "text": "The identifying name of the contact person/organization." }, { - "id": "oas-3.0.callback-object.pattern-expression", + "id": "oas-2.0.contact-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2035, - "section": "Specification > Schema > Callback Object > Patterned Fields", - "anchor": "callback-expression", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 202, + "section": "Specification > Schema > Contact Object > Patterned Objects", + "anchor": "contactExtensions", "level": "field", "terms": [], - "text": "A Path Item Object used to define a callback request and expected responses. A complete example is available." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.callback-object.patterned-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.contact-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2037, - "section": "Specification > Schema > Callback Object > Patterned Fields", - "anchor": "patterned-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 202, + "section": "Specification > Schema > Contact Object > Patterned Objects", + "anchor": "contactExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.components-object.callbacks", + "id": "oas-2.0.contact-object.url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 517, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-callbacks", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 195, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contactUrl", "level": "field", "terms": [], - "text": "An object to hold reusable Callback Objects." + "text": "The URL pointing to the contact information. MUST be in the format of a URL." }, { - "id": "oas-3.0.components-object.examples", + "id": "oas-2.0.contact-object.url.must-format-url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 512, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-examples", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 195, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contactUrl", + "level": "MUST", + "terms": ["MUST"], + "text": "MUST be in the format of a URL." + }, + { + "id": "oas-2.0.definitions-object.pattern-name", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1942, + "section": "Specification > Schema > Definitions Object > Patterned Fields", + "anchor": "definitionsName", "level": "field", "terms": [], - "text": "An object to hold reusable Example Objects." + "text": "A single definition, mapping a \"name\" to the schema it defines." }, { - "id": "oas-3.0.components-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.example-object.pattern-mime-type", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 519, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "fixed-fields-5", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1047, + "section": "Specification > Schema > Example Object > Patterned Fields", + "anchor": "exampleMimeType", + "level": "field", + "terms": [], + "text": "The name of the property MUST be one of the Operation `produces` values (either implicit or inherited). The value SHOULD be an example of what such a response would look like." }, { - "id": "oas-3.0.components-object.fixed-fields.must-all-fixed-fields-declared-above-objects", + "id": "oas-2.0.example-object.pattern-mime-type.must-name-property-one-operation-produces-values", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 521, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "fixed-fields-5", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1047, + "section": "Specification > Schema > Example Object > Patterned Fields", + "anchor": "exampleMimeType", "level": "MUST", "terms": ["MUST"], - "text": "All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\\.\\-_]+$`." + "text": "The name of the property MUST be one of the Operation `produces` values (either implicit or inherited)." }, { - "id": "oas-3.0.components-object.headers", + "id": "oas-2.0.example-object.pattern-mime-type.should-value-example-what-response-would-look", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 514, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-headers", - "level": "field", - "terms": [], - "text": "An object to hold reusable Header Objects." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1047, + "section": "Specification > Schema > Example Object > Patterned Fields", + "anchor": "exampleMimeType", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The value SHOULD be an example of what such a response would look like." }, { - "id": "oas-3.0.components-object.links", + "id": "oas-2.0.external-documentation-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 516, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-links", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 538, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "externalDocDescription", "level": "field", "terms": [], - "text": "An object to hold reusable Link Objects." + "text": "A short description of the target documentation. GFM syntax can be used for rich text representation." }, { - "id": "oas-3.0.components-object.parameters", + "id": "oas-2.0.external-documentation-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 511, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-parameters", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 545, + "section": "Specification > Schema > External Documentation Object > Patterned Objects", + "anchor": "externalDocExtensions", "level": "field", "terms": [], - "text": "An object to hold reusable Parameter Objects." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.components-object.requestBodies", + "id": "oas-2.0.external-documentation-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 513, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-request-bodies", - "level": "field", - "terms": [], - "text": "An object to hold reusable Request Body Objects." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 545, + "section": "Specification > Schema > External Documentation Object > Patterned Objects", + "anchor": "externalDocExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.components-object.responses", + "id": "oas-2.0.external-documentation-object.url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 510, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-responses", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 539, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "externalDocUrl", "level": "field", "terms": [], - "text": "An object to hold reusable Response Objects." + "text": "Required. The URL for the target documentation. Value MUST be in the format of a URL." }, { - "id": "oas-3.0.components-object.schemas", + "id": "oas-2.0.external-documentation-object.url.must-value-format-url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 509, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-schemas", - "level": "field", - "terms": [], - "text": "An object to hold reusable Schema Objects." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 539, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "externalDocUrl", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be in the format of a URL." }, { - "id": "oas-3.0.components-object.securitySchemes", + "id": "oas-2.0.header-object.collectionFormat", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 515, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "security-scheme-object", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1082, + "section": "Specification > Schema > Header Object", + "anchor": "headerCollectionFormat", "level": "field", "terms": [], - "text": "An object to hold reusable Security Scheme Objects." + "text": "Determines the format of the array if type array is used. Possible values are: `csv` - comma separated values `foo,bar`. `ssv` - space separated values `foo bar`. `tsv` - tab separated values `foo\\tbar`. `pipes` - pipe separated values foo|bar. Default value is `csv`." }, { - "id": "oas-3.0.conditions-for-using-the-discriminator-object.may-avoid-redundancy-discriminator-added-parent-schema", + "id": "oas-2.0.header-object.default", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3059, - "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", - "level": "MAY", - "terms": ["MAY"], - "text": "To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas building on the parent schema via an `allOf` construct may be used as an alternate schema." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1083, + "section": "Specification > Schema > Header Object", + "anchor": "headerDefault", + "level": "field", + "terms": [], + "text": "Declares the value of the header that the server will use if none is provided. (Note: \"default\" has no meaning for required headers.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined `type` for the header." }, { - "id": "oas-3.0.conditions-for-using-the-discriminator-object.must-both-oneof-anyof-use-cases-keywords", + "id": "oas-2.0.header-object.default.must-unlike-json-schema-value-conform-defined", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3057, - "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1083, + "section": "Specification > Schema > Header Object", + "anchor": "headerDefault", "level": "MUST", "terms": ["MUST"], - "text": "In both the `oneOf` and `anyOf` use cases, where those keywords are adjacent to `discriminator`, all possible schemas MUST be listed explicitly." + "text": "Unlike JSON Schema this value MUST conform to the defined `type` for the header." }, { - "id": "oas-3.0.conditions-for-using-the-discriminator-object.recommended-however-search-all-named-schemas-components", + "id": "oas-2.0.header-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3059, - "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, it is RECOMMENDED to search all named schemas in the Components Object because it is common with the `allOf` usage for other parts of the API to only directly reference the parent schema." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1078, + "section": "Specification > Schema > Header Object", + "anchor": "headerDescription", + "level": "field", + "terms": [], + "text": "A short description of the header." }, { - "id": "oas-3.0.contact-object.email", + "id": "oas-2.0.header-object.enum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 333, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-email", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1094, + "section": "Specification > Schema > Header Object", + "anchor": "headerEnum", "level": "field", "terms": [], - "text": "The email address of the contact person/organization. This MUST be in the form of an email address." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1." }, { - "id": "oas-3.0.contact-object.email.must-form-email-address", + "id": "oas-2.0.header-object.exclusiveMaximum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 333, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-email", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of an email address." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1085, + "section": "Specification > Schema > Header Object", + "anchor": "headerMaximum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2." }, { - "id": "oas-3.0.contact-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.header-object.exclusiveMinimum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 335, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "fixed-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1087, + "section": "Specification > Schema > Header Object", + "anchor": "headerExclusiveMinimum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3." }, { - "id": "oas-3.0.contact-object.name", + "id": "oas-2.0.header-object.format", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 331, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-name", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1080, + "section": "Specification > Schema > Header Object", + "anchor": "headerFormat", "level": "field", "terms": [], - "text": "The identifying name of the contact person/organization." + "text": "The extending format for the previously mentioned `type`. See Data Type Formats for further details." }, { - "id": "oas-3.0.contact-object.url", + "id": "oas-2.0.header-object.items", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 332, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1081, + "section": "Specification > Schema > Header Object", + "anchor": "headerItems", "level": "field", "terms": [], - "text": "The URL for the contact information. This MUST be in the form of a URL." + "text": "Required if `type` is \"array\". Describes the type of items in the array." }, { - "id": "oas-3.0.contact-object.url.must-form-url", + "id": "oas-2.0.header-object.maxItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 332, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-url", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1091, + "section": "Specification > Schema > Header Object", + "anchor": "headerMaxItems", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2." }, { - "id": "oas-3.0.data-type-format.may-tools-do-not-recognize-specific-format", + "id": "oas-2.0.header-object.maxLength", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 195, - "section": "Specification > Data Types > Data Type Format", - "anchor": "data-type-format", - "level": "MAY", - "terms": ["MAY"], - "text": "Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1088, + "section": "Specification > Schema > Header Object", + "anchor": "headerMaxLength", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1." }, { - "id": "oas-3.0.data-type-format.optional-support-any-registered-format-strictly-support", + "id": "oas-2.0.header-object.maximum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 193, - "section": "Specification > Data Types > Data Type Format", - "anchor": "data-type-format", - "level": "MAY", - "terms": ["OPTIONAL"], - "text": "Support for any registered format is strictly OPTIONAL, and support for one registered format does not imply support for any others." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1084, + "section": "Specification > Schema > Header Object", + "anchor": "headerMaximum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2." }, { - "id": "oas-3.0.discriminator-object.examples.may-discriminator-used-hint-improve-efficiency-selection", + "id": "oas-2.0.header-object.minItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3093, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-1", - "level": "MAY", - "terms": ["MAY"], - "text": "A `discriminator` MAY be used as a \"hint\" to improve the efficiency of selection of the matching schema." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1092, + "section": "Specification > Schema > Header Object", + "anchor": "headerMinItems", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3." }, { - "id": "oas-3.0.discriminator-object.examples.may-oas-3-0-response-payload-described", + "id": "oas-2.0.header-object.minLength", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3083, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-1", - "level": "MAY", - "terms": ["MAY"], - "text": "In OAS 3.0, a response payload MAY be described to be exactly one of any number of types:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1089, + "section": "Specification > Schema > Header Object", + "anchor": "headerMinLength", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2." }, { - "id": "oas-3.0.discriminator-object.examples.may-scenarios-value-discriminator-field-does-not", + "id": "oas-2.0.header-object.minimum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3116, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-1", - "level": "MAY", - "terms": ["MAY"], - "text": "In scenarios where the value of the `discriminator` field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1086, + "section": "Specification > Schema > Header Object", + "anchor": "headerMinimum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3." }, { - "id": "oas-3.0.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", + "id": "oas-2.0.header-object.multipleOf", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3132, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-1", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1095, + "section": "Specification > Schema > Header Object", + "anchor": "headerMultipleOf", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1." }, { - "id": "oas-3.0.discriminator-object.mapping", + "id": "oas-2.0.header-object.pattern", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3051, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "discriminator-mapping", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1090, + "section": "Specification > Schema > Header Object", + "anchor": "headerPattern", "level": "field", "terms": [], - "text": "An object to hold mappings between payload values and schema names or URI references." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3." }, { - "id": "oas-3.0.discriminator-object.must-not-note-discriminator-change-validation-outcome-schema", + "id": "oas-2.0.header-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3044, - "section": "Specification > Schema > Discriminator Object", - "anchor": "discriminator-object", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "Note that `discriminator` MUST NOT change the validation outcome of the schema." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1101, + "section": "Specification > Schema > Header Object > Patterned Objects", + "anchor": "headerExtensions", + "level": "field", + "terms": [], + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.discriminator-object.options-for-mapping-values-to-schemas.must-ensure-ambiguous-value-e-g-foo", + "id": "oas-2.0.header-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3070, - "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1101, + "section": "Specification > Schema > Header Object > Patterned Objects", + "anchor": "headerExtensions", "level": "MUST", "terms": ["MUST"], - "text": "To ensure that an ambiguous value (e.g. `\"foo\"`) is treated as a relative URI reference by all implementations, authors MUST prefix it with the `\".\"` path segment (e.g. `\"./foo\"`)." + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.discriminator-object.options-for-mapping-values-to-schemas.must-mapping-keys-string-values-but-tooling", + "id": "oas-2.0.header-object.type", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3076, - "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1079, + "section": "Specification > Schema > Header Object", + "anchor": "headerType", + "level": "field", + "terms": [], + "text": "Required. The type of the object. The value MUST be one of `\"string\"`, `\"number\"`, `\"integer\"`, `\"boolean\"`, or `\"array\"`." + }, + { + "id": "oas-2.0.header-object.type.must-value-one-string-number-integer-boolean", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1079, + "section": "Specification > Schema > Header Object", + "anchor": "headerType", "level": "MUST", - "terms": ["MUST", "MAY"], - "text": "Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison." + "terms": ["MUST"], + "text": "The value MUST be one of `\"string\"`, `\"number\"`, `\"integer\"`, `\"boolean\"`, or `\"array\"`." }, { - "id": "oas-3.0.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-both-valid-schema", + "id": "oas-2.0.header-object.uniqueItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3070, - "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "The behavior of a `mapping` value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it is RECOMMENDED that it be treated as a schema name." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1093, + "section": "Specification > Schema > Header Object", + "anchor": "headerUniqueItems", + "level": "field", + "terms": [], + "text": "https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4." }, { - "id": "oas-3.0.discriminator-object.propertyName", + "id": "oas-2.0.headers-object.pattern-name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3050, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "property-name", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1005, + "section": "Specification > Schema > Headers Object > Patterned Fields", + "anchor": "headersName", "level": "field", "terms": [], - "text": "REQUIRED. The name of the property in the payload that will hold the discriminating value. This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." + "text": "The name of the property corresponds to the name of the header. The value describes the type of the header." }, { - "id": "oas-3.0.discriminator-object.propertyName.required", + "id": "oas-2.0.info-object.contact", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3050, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "property-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 142, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "infoContact", + "level": "field", + "terms": [], + "text": "The contact information for the exposed API." }, { - "id": "oas-3.0.discriminator-object.propertyName.should-property-required-payload-schema-behavior-property", + "id": "oas-2.0.info-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3050, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "property-name", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 140, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "infoDescription", + "level": "field", + "terms": [], + "text": "A short description of the application. GFM syntax can be used for rich text representation." }, { - "id": "oas-3.0.encoding-object.allowReserved", + "id": "oas-2.0.info-object.license", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1596, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 143, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "infoLicense", "level": "field", "terms": [], - "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see Appendices C and E for details. The default value is `false`. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." + "text": "The license information for the exposed API." }, { - "id": "oas-3.0.encoding-object.allowReserved.shall-field-ignored-request-body-media-type", + "id": "oas-2.0.info-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1596, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 150, + "section": "Specification > Schema > Info Object > Patterned Objects", + "anchor": "infoExtensions", + "level": "field", + "terms": [], + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", + "id": "oas-2.0.info-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1567, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-0", - "level": "MAY", - "terms": ["MAY"], - "text": "These fields MAY be used either with or without the RFC6570-style serialization fields defined in the next section below." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 150, + "section": "Specification > Schema > Info Object > Patterned Objects", + "anchor": "infoExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.encoding-object.common-fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.info-object.termsOfService", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1574, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-0", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 141, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "infoTermsOfService", + "level": "field", + "terms": [], + "text": "The Terms of Service for the API." }, { - "id": "oas-3.0.encoding-object.contentType", + "id": "oas-2.0.info-object.title", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1571, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-content-type", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 139, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "infoTitle", "level": "field", "terms": [], - "text": "The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a wildcard media type (e.g. `image/*`). Default value depends on the property type as shown in the table below." + "text": "Required. The title of the application." }, { - "id": "oas-3.0.encoding-object.encoding-multipart-media-types.may-not-currently-possible-correlate-schema-properties", + "id": "oas-2.0.info-object.version", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1709, - "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", - "anchor": "encoding-multipart-media-types", - "level": "MAY", - "terms": ["MAY"], - "text": "It is not currently possible to correlate schema properties with unnamed, ordered parts in media types such as `multipart/mixed`, but implementations MAY choose to support such types when `Content-Disposition: form-data` is used with a `name` parameter." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 144, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "infoVersion", + "level": "field", + "terms": [], + "text": "Required Provides the version of the application API (not to be confused with the specification version)." }, { - "id": "oas-3.0.encoding-object.encoding-multipart-media-types.required-contrast-openapi-2-0-schema-define", + "id": "oas-2.0.items-object.collectionFormat", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1703, - "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", - "anchor": "encoding-multipart-media-types", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "In contrast to OpenAPI 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 778, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsCollectionFormat", + "level": "field", + "terms": [], + "text": "Determines the format of the array if type array is used. Possible values are: `csv` - comma separated values `foo,bar`. `ssv` - space separated values `foo bar`. `tsv` - tab separated values `foo\\tbar`. `pipes` - pipe separated values foo|bar. Default value is `csv`." }, { - "id": "oas-3.0.encoding-object.encoding-the-x-www-form-urlencoded-media-type.must-configuration-means-request-body-encoded-per", + "id": "oas-2.0.items-object.default", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1616, - "section": "Specification > Schema > Encoding Object > Encoding the `x-www-form-urlencoded` Media Type", - "anchor": "encoding-the-x-www-form-urlencoded-media-type", - "level": "MUST", - "terms": ["MUST"], - "text": "This configuration means that the request body MUST be encoded per RFC1866 when passed to the server, after any complex objects have been serialized to a string representation." - }, - { - "id": "oas-3.0.encoding-object.explode", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1595, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 779, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsDefault", "level": "field", "terms": [], - "text": "When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." + "text": "Declares the value of the item that the server will use if none is provided. (Note: \"default\" has no meaning for required items.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined `type` for the data type." }, { - "id": "oas-3.0.encoding-object.explode.shall-field-ignored-request-body-media-type", + "id": "oas-2.0.items-object.default.must-unlike-json-schema-value-conform-defined", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1595, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 779, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsDefault", "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." + "terms": ["MUST"], + "text": "Unlike JSON Schema this value MUST conform to the defined `type` for the data type." }, { - "id": "oas-3.0.encoding-object.fixed-fields-for-rfc6570-style-serialization.recommended-however-all-three-style-explode-allowreserved", + "id": "oas-2.0.items-object.enum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1606, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "fixed-fields-for-rfc6570-style-serialization", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, if all three of `style`, `explode`, and `allowReserved` fields are absent, it is RECOMMENDED that:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 790, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsEnum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1." }, { - "id": "oas-3.0.encoding-object.fixed-fields-for-rfc6570-style-serialization.recommended-match-intent-fields-compatible-version-3", + "id": "oas-2.0.items-object.exclusiveMaximum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1600, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "fixed-fields-for-rfc6570-style-serialization", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "To match the intent of these fields and be compatible with version 3.1 of this specification, it is RECOMMENDED that whenever any of `style`, `explode`, or `allowReserved` are present with an explicit value:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 781, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMaximum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2." }, { - "id": "oas-3.0.encoding-object.headers", + "id": "oas-2.0.items-object.exclusiveMinimum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1572, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 783, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsExclusiveMinimum", "level": "field", "terms": [], - "text": "A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the request body media type is not a `multipart`." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3." }, { - "id": "oas-3.0.encoding-object.headers.shall-content-type-described-separately-ignored-section", + "id": "oas-2.0.items-object.format", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1572, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", - "level": "MUST", - "terms": ["SHALL"], - "text": "`Content-Type` is described separately and SHALL be ignored in this section." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 776, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsFormat", + "level": "field", + "terms": [], + "text": "The extending format for the previously mentioned `type`. See Data Type Formats for further details." }, { - "id": "oas-3.0.encoding-object.headers.shall-field-ignored-request-body-media-type", + "id": "oas-2.0.items-object.items", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1572, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not a `multipart`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 777, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsItems", + "level": "field", + "terms": [], + "text": "Required if `type` is \"array\". Describes the type of items in the array." }, { - "id": "oas-3.0.encoding-object.style", + "id": "oas-2.0.items-object.maxItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1594, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 787, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMaxItems", "level": "field", "terms": [], - "text": "Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the `style` field. The behavior follows the same values as `query` parameters, including default values. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2." }, { - "id": "oas-3.0.encoding-object.style.must-note-initial-used-query-strings-not", + "id": "oas-2.0.items-object.maxLength", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1594, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", - "level": "MUST", - "terms": ["MUST"], - "text": "Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually)." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 784, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMaxLength", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1." }, { - "id": "oas-3.0.encoding-object.style.shall-field-ignored-request-body-media-type", + "id": "oas-2.0.items-object.maximum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1594, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 780, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMaximum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2." }, { - "id": "oas-3.0.example-object.description", + "id": "oas-2.0.items-object.minItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2132, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 788, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMinItems", "level": "field", "terms": [], - "text": "Long description for the example. CommonMark syntax MAY be used for rich text representation." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3." }, { - "id": "oas-3.0.example-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.items-object.minLength", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2132, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 785, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMinLength", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2." }, { - "id": "oas-3.0.example-object.externalValue", + "id": "oas-2.0.items-object.minimum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2134, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-external-value", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 782, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMinimum", "level": "field", "terms": [], - "text": "A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving Relative References." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3." }, { - "id": "oas-3.0.example-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.items-object.multipleOf", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2136, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 791, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsMultipleOf", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1." }, { - "id": "oas-3.0.example-object.fixed-fields.may-tooling-implementations-choose-validate-compatibility-automatically", + "id": "oas-2.0.items-object.pattern", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2138, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", - "level": "MAY", - "terms": ["MAY"], - "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 786, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsPattern", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3." }, { - "id": "oas-3.0.example-object.fixed-fields.should-all-cases-example-value-compatible-schema", + "id": "oas-2.0.items-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2138, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "In all cases, the example value SHOULD be compatible with the schema of its associated value." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 797, + "section": "Specification > Schema > Items Object > Patterned Objects", + "anchor": "itemsExtensions", + "level": "field", + "terms": [], + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.example-object.summary", + "id": "oas-2.0.items-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2131, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-summary", - "level": "field", - "terms": [], - "text": "Short description for the example." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 797, + "section": "Specification > Schema > Items Object > Patterned Objects", + "anchor": "itemsExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.example-object.value", + "id": "oas-2.0.items-object.type", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2133, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-value", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 775, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsType", "level": "field", "terms": [], - "text": "Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary." + "text": "Required. The internal type of the array. The value MUST be one of `\"string\"`, `\"number\"`, `\"integer\"`, `\"boolean\"`, or `\"array\"`. Files and models are not allowed." }, { - "id": "oas-3.0.example-object.working-with-examples.shall-because-examples-using-fields-represent-final", + "id": "oas-2.0.items-object.type.must-value-one-string-number-integer-boolean", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2150, - "section": "Specification > Schema > Example Object > Working with Examples", - "anchor": "working-with-examples", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 775, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsType", "level": "MUST", - "terms": ["SHALL"], - "text": "Because examples using these fields represent the final serialized form of the data, they SHALL _override_ any `example` in the corresponding Schema Object." + "terms": ["MUST"], + "text": "The value MUST be one of `\"string\"`, `\"number\"`, `\"integer\"`, `\"boolean\"`, or `\"array\"`." }, { - "id": "oas-3.0.example-object.working-with-examples.should-mutually-exclusive-fields-parameter-media-type", + "id": "oas-2.0.items-object.uniqueItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2150, - "section": "Specification > Schema > Example Object > Working with Examples", - "anchor": "working-with-examples", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The mutually exclusive fields in the Parameter or Media Type Objects are used to show example values which SHOULD both match the schema and be formatted as they would appear as a serialized parameter or within a media type representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 789, + "section": "Specification > Schema > Items Object > Fixed Fields", + "anchor": "itemsUniqueItems", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4." }, { - "id": "oas-3.0.external-documentation-object.description", + "id": "oas-2.0.license-object.name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1031, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 228, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "licenseName", "level": "field", "terms": [], - "text": "A description of the target documentation. CommonMark syntax MAY be used for rich text representation." + "text": "Required. The license name used for the API." }, { - "id": "oas-3.0.external-documentation-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.license-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1031, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 235, + "section": "Specification > Schema > License Object > Patterned Objects", + "anchor": "licenseExtensions", + "level": "field", + "terms": [], + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.external-documentation-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.license-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1034, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "fixed-fields-8", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 235, + "section": "Specification > Schema > License Object > Patterned Objects", + "anchor": "licenseExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.external-documentation-object.url", + "id": "oas-2.0.license-object.url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1032, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 229, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "licenseUrl", "level": "field", "terms": [], - "text": "REQUIRED. The URL for the target documentation. This MUST be in the form of a URL." + "text": "A URL to the license used for the API. MUST be in the format of a URL." }, { - "id": "oas-3.0.external-documentation-object.url.must-form-url", + "id": "oas-2.0.license-object.url.must-format-url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1032, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 229, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "licenseUrl", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "MUST be in the format of a URL." }, { - "id": "oas-3.0.external-documentation-object.url.required", + "id": "oas-2.0.operation-object.consumes", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1032, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 418, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationConsumes", + "level": "field", + "terms": [], + "text": "A list of MIME types the operation can consume. This overrides the `consumes` definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.format.must-keys-used-yaml-maps-limited-scalar", + "id": "oas-2.0.operation-object.consumes.may-empty-value-used-clear-global-definition", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 118, - "section": "Specification > Format", - "anchor": "format", - "level": "MUST", - "terms": ["MUST"], - "text": "Keys used in YAML maps MUST be limited to a scalar string, as defined by the YAML Failsafe schema ruleset." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 418, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationConsumes", + "level": "MAY", + "terms": ["MAY"], + "text": "An empty value MAY be used to clear the global definition." }, { - "id": "oas-3.0.format.must-patterned-fields-have-unique-names-within", + "id": "oas-2.0.operation-object.consumes.must-value-described-under-mime-types", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 113, - "section": "Specification > Format", - "anchor": "format", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 418, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationConsumes", "level": "MUST", "terms": ["MUST"], - "text": "Patterned fields MUST have unique names within the containing object." + "text": "Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.format.must-tags-limited-allowed-yaml-s-json", + "id": "oas-2.0.operation-object.deprecated", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 117, - "section": "Specification > Format", - "anchor": "format", - "level": "MUST", - "terms": ["MUST"], - "text": "Tags MUST be limited to those allowed by YAML's JSON schema ruleset, which defines a subset of the YAML syntax and is unrelated to [JSON Schema]." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 423, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationDeprecated", + "level": "field", + "terms": [], + "text": "Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is `false`." }, { - "id": "oas-3.0.format.recommended-order-preserve-ability-round-trip-between", + "id": "oas-2.0.operation-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 115, - "section": "Specification > Format", - "anchor": "format", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with some additional constraints:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 415, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationDescription", + "level": "field", + "terms": [], + "text": "A verbose explanation of the operation behavior. GFM syntax can be used for rich text representation." }, { - "id": "oas-3.0.header-object.common-fixed-fields.may-fields-used-either-content-schema", + "id": "oas-2.0.operation-object.externalDocs", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2481, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "These fields MAY be used with either `content` or `schema`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 416, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationExternalDocs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this operation." }, { - "id": "oas-3.0.header-object.common-fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.operation-object.operationId", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2489, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-1", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 417, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationId", + "level": "field", + "terms": [], + "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions." + }, + { + "id": "oas-2.0.operation-object.operationId.may-tools-libraries-use-operationid-uniquely-identify", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 417, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationId", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions." }, { - "id": "oas-3.0.header-object.content", + "id": "oas-2.0.operation-object.operationId.must-id-unique-among-all-operations-described", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2518, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "header-content", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 417, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationId", + "level": "MUST", + "terms": ["MUST"], + "text": "The id MUST be unique among all operations described in the API." + }, + { + "id": "oas-2.0.operation-object.parameters", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 420, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationParameters", "level": "field", "terms": [], - "text": "A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry." + "text": "A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the Swagger Object's parameters. There can be one \"body\" parameter at most." }, { - "id": "oas-3.0.header-object.content.must-map-only-contain-one-entry", + "id": "oas-2.0.operation-object.parameters.must-not-list-include-duplicated-parameters", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2518, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "header-content", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 420, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationParameters", "level": "MUST", - "terms": ["MUST"], - "text": "The map MUST only contain one entry." + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." }, { - "id": "oas-3.0.header-object.deprecated", + "id": "oas-2.0.operation-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2487, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-deprecated", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 430, + "section": "Specification > Schema > Operation Object > Patterned Objects", + "anchor": "operationExtensions", "level": "field", "terms": [], - "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.header-object.deprecated.should-specifies-header-deprecated-transitioned-out-usage", + "id": "oas-2.0.operation-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2487, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-deprecated", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 430, + "section": "Specification > Schema > Operation Object > Patterned Objects", + "anchor": "operationExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.header-object.description", + "id": "oas-2.0.operation-object.produces", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2485, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 419, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationProduces", "level": "field", "terms": [], - "text": "A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "text": "A list of MIME types the operation can produce. This overrides the `produces` definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.header-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.operation-object.produces.may-empty-value-used-clear-global-definition", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2485, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 419, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationProduces", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "An empty value MAY be used to clear the global definition." }, { - "id": "oas-3.0.header-object.example", + "id": "oas-2.0.operation-object.produces.must-value-described-under-mime-types", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2506, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-example", - "level": "field", - "terms": [], - "text": "Example of the header's potential value; see Working With Examples." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 419, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationProduces", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.header-object.examples", + "id": "oas-2.0.operation-object.responses", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2507, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-examples", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 421, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationResponses", "level": "field", "terms": [], - "text": "Examples of the header's potential value; see Working With Examples." + "text": "Required. The list of possible responses as they are returned from executing this operation." }, { - "id": "oas-3.0.header-object.explode", + "id": "oas-2.0.operation-object.schemes", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2504, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-explode", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 422, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationSchemes", "level": "field", "terms": [], - "text": "When this is true, header values of type `array` or `object` generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is `false`." - }, - { - "id": "oas-3.0.header-object.fixed-fields-for-use-with-content.recommended-using-content-text-plain-media-type", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2513, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "fixed-fields-for-use-with-content-0", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "Using `content` with a `text/plain` media type is RECOMMENDED for headers where the `schema` strategy is not appropriate." + "text": "The transfer protocol for the operation. Values MUST be from the list: `\"http\"`, `\"https\"`, `\"ws\"`, `\"wss\"`. The value overrides the Swagger Object `schemes` definition." }, { - "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.must-example-examples-provided-conjunction-schema-field", + "id": "oas-2.0.operation-object.schemes.must-values-list-http-https-ws-wss", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2493, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 422, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationSchemes", "level": "MUST", "terms": ["MUST"], - "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example MUST follow the prescribed serialization strategy for the header." + "text": "Values MUST be from the list: `\"http\"`, `\"https\"`, `\"ws\"`, `\"wss\"`." }, { - "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-headers-parameters-name-value", + "id": "oas-2.0.operation-object.security", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2496, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Serializing with `schema` is NOT RECOMMENDED for headers with parameters (name=value pairs following a `;`) in their values, or where values might have non-URL-safe characters; see Appendix D for details." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 424, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationSecurity", + "level": "field", + "terms": [], + "text": "A declaration of which security schemes are applied for this operation. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." }, { - "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", + "id": "oas-2.0.operation-object.summary", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2498, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 414, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationSummary", + "level": "field", + "terms": [], + "text": "A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters." }, { - "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", + "id": "oas-2.0.operation-object.summary.should-maximum-readability-swagger-ui-field-less", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2498, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 414, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationSummary", "level": "SHOULD", "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the header." + "text": "For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters." }, { - "id": "oas-3.0.header-object.must-all-traits-affected-location-applicable-location", + "id": "oas-2.0.operation-object.tags", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2475, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", - "level": "MUST", - "terms": ["MUST"], - "text": "All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`)." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 413, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operationTags", + "level": "field", + "terms": [], + "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." }, { - "id": "oas-3.0.header-object.must-not-means-allowemptyvalue-allowreserved-used-style-used", + "id": "oas-2.0.parameter-object.allowEmptyValue", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2475, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", - "level": "MUST", - "terms": ["MUST NOT", "MUST"], - "text": "This means that `allowEmptyValue` and `allowReserved` MUST NOT be used, and `style`, if used, MUST be limited to `\"simple\"`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 596, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterAllowEmptyValue", + "level": "field", + "terms": [], + "text": "Sets the ability to pass empty-valued parameters. This is valid only for either `query` or `formData` parameters and allows you to send a parameter with a name only or an empty value. Default value is `false`." }, { - "id": "oas-3.0.header-object.must-not-name-specified-given-corresponding-headers-map", + "id": "oas-2.0.parameter-object.collectionFormat", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2473, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "`name` MUST NOT be specified, it is given in the corresponding `headers` map." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 598, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterCollectionFormat", + "level": "field", + "terms": [], + "text": "Determines the format of the array if type array is used. Possible values are: `csv` - comma separated values `foo,bar`. `ssv` - space separated values `foo bar`. `tsv` - tab separated values `foo\\tbar`. `pipes` - pipe separated values foo|bar. `multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters `in` \"query\" or \"formData\". Default value is `csv`." }, { - "id": "oas-3.0.header-object.must-not-specified-implicitly-header", + "id": "oas-2.0.parameter-object.default", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2474, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 599, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterDefault", + "level": "field", + "terms": [], + "text": "Declares the value of the parameter that the server will use if none is provided, for example a \"count\" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: \"default\" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined `type` for this parameter." + }, + { + "id": "oas-2.0.parameter-object.default.must-unlike-json-schema-value-conform-defined", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 599, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterDefault", "level": "MUST", - "terms": ["MUST NOT"], - "text": "`in` MUST NOT be specified, it is implicitly in `header`." + "terms": ["MUST"], + "text": "Unlike JSON Schema this value MUST conform to the defined `type` for this parameter." }, { - "id": "oas-3.0.header-object.required", + "id": "oas-2.0.parameter-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2486, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-required", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 581, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterDescription", "level": "field", "terms": [], - "text": "Determines whether this header is mandatory. The default value is `false`." + "text": "A brief description of the parameter. This could contain examples of use. GFM syntax can be used for rich text representation." }, { - "id": "oas-3.0.header-object.schema", + "id": "oas-2.0.parameter-object.enum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2505, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-schema", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 610, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterEnum", "level": "field", "terms": [], - "text": "The schema defining the type used for the header." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1." }, { - "id": "oas-3.0.header-object.style", + "id": "oas-2.0.parameter-object.exclusiveMaximum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2503, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-style", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 601, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterExclusiveMaximum", "level": "field", "terms": [], - "text": "Describes how the header value will be serialized. The default (and only legal value for headers) is `\"simple\"`." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2." }, { - "id": "oas-3.0.http-status-codes.should-status-codes-selected-available-status-codes", + "id": "oas-2.0.parameter-object.exclusiveMinimum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 67, - "section": "Definitions > HTTP Status Codes", - "anchor": "http-status-codes", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Status codes SHOULD be selected from the available status codes registered in the IANA Status Code Registry." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 603, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterExclusiveMinimum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3." }, { - "id": "oas-3.0.info-object.contact", + "id": "oas-2.0.parameter-object.format", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 283, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-contact", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 595, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterFormat", "level": "field", "terms": [], - "text": "The contact information for the exposed API." + "text": "The extending format for the previously mentioned `type`. See Data Type Formats for further details." }, { - "id": "oas-3.0.info-object.description", + "id": "oas-2.0.parameter-object.in", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 281, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 580, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterIn", "level": "field", "terms": [], - "text": "A description of the API. CommonMark syntax MAY be used for rich text representation." + "text": "Required. The location of the parameter. Possible values are \"query\", \"header\", \"path\", \"formData\" or \"body\"." }, { - "id": "oas-3.0.info-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.parameter-object.items", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 281, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 597, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterItems", + "level": "field", + "terms": [], + "text": "Required if `type` is \"array\". Describes the type of items in the array." }, { - "id": "oas-3.0.info-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.parameter-object.maxItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 287, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "fixed-fields-0", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 607, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMaxItems", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2." }, { - "id": "oas-3.0.info-object.license", + "id": "oas-2.0.parameter-object.maxLength", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 284, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-license", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 604, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMaxLength", "level": "field", "terms": [], - "text": "The license information for the exposed API." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1." }, { - "id": "oas-3.0.info-object.may-metadata-used-clients-needed-presented-editing", + "id": "oas-2.0.parameter-object.maximum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 273, - "section": "Specification > Schema > Info Object", - "anchor": "info-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 600, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMaximum", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2." }, { - "id": "oas-3.0.info-object.termsOfService", + "id": "oas-2.0.parameter-object.minItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 282, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-terms-of-service", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 608, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMinItems", "level": "field", "terms": [], - "text": "A URL for the Terms of Service for the API. This MUST be in the form of a URL." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3." }, { - "id": "oas-3.0.info-object.termsOfService.must-form-url", + "id": "oas-2.0.parameter-object.minLength", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 282, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-terms-of-service", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 605, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMinLength", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2." }, { - "id": "oas-3.0.info-object.title", + "id": "oas-2.0.parameter-object.minimum", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 280, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-title", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 602, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMinimum", "level": "field", "terms": [], - "text": "REQUIRED. The title of the API." + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3." }, { - "id": "oas-3.0.info-object.title.required", + "id": "oas-2.0.parameter-object.multipleOf", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 280, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-title", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 611, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterMultipleOf", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1." }, { - "id": "oas-3.0.info-object.version", + "id": "oas-2.0.parameter-object.name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 285, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-version", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 579, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterName", "level": "field", "terms": [], - "text": "REQUIRED. The version of the OpenAPI Document (which is distinct from the OpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description)." + "text": "Required. The name of the parameter. Parameter names are *case sensitive*. If `in` is `\"path\"`, the `name` field MUST correspond to the associated path segment from the path field in the Paths Object. See Path Templating for further information. For all other cases, the `name` corresponds to the parameter name used based on the `in` property." }, { - "id": "oas-3.0.info-object.version.required", + "id": "oas-2.0.parameter-object.name.must-path-name-field-correspond-associated-path", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 285, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-version", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 579, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterName", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "If `in` is `\"path\"`, the `name` field MUST correspond to the associated path segment from the path field in the Paths Object." }, { - "id": "oas-3.0.interoperability-with-historical-specifications.should-since-all-rfc1738-compliant-uris-compliant", + "id": "oas-2.0.parameter-object.pattern", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 4233, - "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Historical Specifications", - "anchor": "interoperability-with-historical-specifications", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Since all RFC1738-compliant URIs are compliant with RFC3986, applications needing to ensure historical interoperability SHOULD use RFC1738's rules." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 606, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterPattern", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3." }, { - "id": "oas-3.0.interoperability-with-web-browser-environments.should-implementations-needing-maximum-compatibility-web-browsers", + "id": "oas-2.0.parameter-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 4240, - "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", - "anchor": "interoperability-with-web-browser-environments", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Implementations needing maximum compatibility with web browsers SHOULD use WHATWG's `form-urlencoded` percent-encoding rules." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 617, + "section": "Specification > Schema > Parameter Object > Patterned Fields", + "anchor": "parameterExtensions", + "level": "field", + "terms": [], + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.interoperability-with-web-browser-environments.should-not-however-they-rely-whatwg-s-less", + "id": "oas-2.0.parameter-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 4240, - "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", - "anchor": "interoperability-with-web-browser-environments", - "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "However, they SHOULD NOT rely on WHATWG's less stringent generic query string rules, as the resulting URLs would fail RFC3986 validation, including JSON Schema's `format: uri` and `format: uri-reference`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 617, + "section": "Specification > Schema > Parameter Object > Patterned Fields", + "anchor": "parameterExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.license-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.parameter-object.required", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 364, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "fixed-fields-2", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 582, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterRequired", + "level": "field", + "terms": [], + "text": "Determines whether this parameter is mandatory. If the parameter is `in` \"path\", this property is required and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`." + }, + { + "id": "oas-2.0.parameter-object.required.may-otherwise-property-included-default-value-false", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 582, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterRequired", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Otherwise, the property MAY be included and its default value is `false`." }, { - "id": "oas-3.0.license-object.name", + "id": "oas-2.0.parameter-object.required.must-parameter-path-property-required-value-true", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 361, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The license name used for the API." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 582, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterRequired", + "level": "MUST", + "terms": ["MUST"], + "text": "If the parameter is `in` \"path\", this property is required and its value MUST be `true`." }, { - "id": "oas-3.0.license-object.name.required", + "id": "oas-2.0.parameter-object.schema", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 361, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 588, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterSchema", + "level": "field", + "terms": [], + "text": "Required. The schema defining the type used for the body parameter." }, { - "id": "oas-3.0.license-object.url", + "id": "oas-2.0.parameter-object.type", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 362, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 594, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterType", "level": "field", "terms": [], - "text": "A URL for the license used for the API. This MUST be in the form of a URL." + "text": "Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of `\"string\"`, `\"number\"`, `\"integer\"`, `\"boolean\"`, `\"array\"` or `\"file\"`. If `type` is `\"file\"`, the `consumes` MUST be either `\"multipart/form-data\"`, `\" application/x-www-form-urlencoded\"` or both and the parameter MUST be `in` `\"formData\"`." }, { - "id": "oas-3.0.license-object.url.must-form-url", + "id": "oas-2.0.parameter-object.type.must-type-file-consumes-either-multipart-form", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 362, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 594, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterType", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "If `type` is `\"file\"`, the `consumes` MUST be either `\"multipart/form-data\"`, `\" application/x-www-form-urlencoded\"` or both and the parameter MUST be `in` `\"formData\"`." }, { - "id": "oas-3.0.link-object.description", + "id": "oas-2.0.parameter-object.type.must-value-one-string-number-integer-boolean", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2311, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-description", - "level": "field", - "terms": [], - "text": "A description of the link. CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 594, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterType", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST be one of `\"string\"`, `\"number\"`, `\"integer\"`, `\"boolean\"`, `\"array\"` or `\"file\"`." }, { - "id": "oas-3.0.link-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.parameter-object.uniqueItems", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2311, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 609, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "parameterUniqueItems", + "level": "field", + "terms": [], + "text": "See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4." }, { - "id": "oas-3.0.link-object.examples-2.must-request-parameters-declared-parameters-section-parent", + "id": "oas-2.0.parameters-definitions-object.pattern-name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2458, - "section": "Specification > Schema > Link Object > Examples", - "anchor": "examples-0", - "level": "MUST", - "terms": ["MUST"], - "text": "Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2004, + "section": "Specification > Schema > Parameters Definitions Object > Patterned Fields", + "anchor": "pdName", + "level": "field", + "terms": [], + "text": "A single parameter definition, mapping a \"name\" to the parameter it defines." }, { - "id": "oas-3.0.link-object.fixed-fields.may-ambiguous-cases-resulting-behavior-implementation-defined", + "id": "oas-2.0.path-item-object.$ref", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2316, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MAY", - "terms": ["MAY"], - "text": "In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 313, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemRef", + "level": "field", + "terms": [], + "text": "Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path Item Object. If there are conflicts between the referenced definition and this Path Item's definition, the behavior is *undefined*." }, { - "id": "oas-3.0.link-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.path-item-object.$ref.must-referenced-structure-format-path-item-object", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2314, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 313, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemRef", + "level": "MUST", + "terms": ["MUST"], + "text": "The referenced structure MUST be in the format of a Path Item Object." }, { - "id": "oas-3.0.link-object.fixed-fields.must-identified-reference-operation-unique-case-operationid", + "id": "oas-2.0.path-item-object.delete", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2316, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MUST", - "terms": ["MUST"], - "text": "The identified or reference operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD)." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 317, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemDelete", + "level": "field", + "terms": [], + "text": "A definition of a DELETE operation on this path." }, { - "id": "oas-3.0.link-object.fixed-fields.must-linked-operation-identified-using-either-operationref", + "id": "oas-2.0.path-item-object.get", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2316, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MUST", - "terms": ["MUST"], - "text": "A linked operation MUST be identified using either an `operationRef` or `operationId`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 314, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemGet", + "level": "field", + "terms": [], + "text": "A definition of a GET operation on this path." }, { - "id": "oas-3.0.link-object.fixed-fields.not-recommended-possible-have-ambiguous-parameter-names-e", + "id": "oas-2.0.path-item-object.head", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2322, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED", "SHOULD"], - "text": "It is possible to have ambiguous parameter names, e.g. `name: \"id\", in: \"path\"` and `name: \"path.id\", in: \"query\"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter)." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 319, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemHead", + "level": "field", + "terms": [], + "text": "A definition of a HEAD operation on this path." }, { - "id": "oas-3.0.link-object.operationId", + "id": "oas-2.0.path-item-object.options", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2308, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-id", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 318, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemOptions", "level": "field", "terms": [], - "text": "The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field." + "text": "A definition of a OPTIONS operation on this path." }, { - "id": "oas-3.0.link-object.operationRef", + "id": "oas-2.0.path-item-object.parameters", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2307, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-ref", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 321, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemParameters", "level": "field", "terms": [], - "text": "A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." + "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the Swagger Object's parameters. There can be one \"body\" parameter at most." }, { - "id": "oas-3.0.link-object.operationRef.must-field-mutually-exclusive-operationid-field-point", + "id": "oas-2.0.path-item-object.parameters.must-not-list-include-duplicated-parameters", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2307, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-ref", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 321, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemParameters", "level": "MUST", - "terms": ["MUST"], - "text": "This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." }, { - "id": "oas-3.0.link-object.operationref-examples.may-references-operationid-possible-operationid-optional-field", + "id": "oas-2.0.path-item-object.patch", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2394, - "section": "Specification > Schema > Link Object > `operationRef` Examples", - "anchor": "operationref-examples", - "level": "MAY", - "terms": ["MAY"], - "text": "As references to `operationId` MAY NOT be possible (the `operationId` is an optional field in an Operation Object), references MAY also be made through a relative `operationRef`:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 320, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemPatch", + "level": "field", + "terms": [], + "text": "A definition of a PATCH operation on this path." }, { - "id": "oas-3.0.link-object.parameters", + "id": "oas-2.0.path-item-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2309, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-parameters", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 327, + "section": "Specification > Schema > Path Item Object > Patterned Fields", + "anchor": "pathItemExtensions", "level": "field", "terms": [], - "text": "A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.link-object.requestBody", + "id": "oas-2.0.path-item-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2310, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-request-body", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 327, + "section": "Specification > Schema > Path Item Object > Patterned Fields", + "anchor": "pathItemExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + }, + { + "id": "oas-2.0.path-item-object.post", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 316, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemPost", "level": "field", "terms": [], - "text": "A literal value or {expression} to use as a request body when calling the target operation." + "text": "A definition of a POST operation on this path." }, { - "id": "oas-3.0.link-object.server", + "id": "oas-2.0.path-item-object.put", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2312, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-server", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 315, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "pathItemPut", "level": "field", "terms": [], - "text": "A server object to be used by the target operation." + "text": "A definition of a PUT operation on this path." }, { - "id": "oas-3.0.media-type-object.considerations-for-file-uploads.may-addition-specific-media-types-specified", + "id": "oas-2.0.paths-object.pattern-path", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1526, - "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", - "level": "MAY", - "terms": ["MAY"], - "text": "In addition, specific media types MAY be specified:" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 260, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "pathsPath", + "level": "field", + "terms": [], + "text": "A relative path to an individual endpoint. The field name MUST begin with a slash. The path is appended to the `basePath` in order to construct the full URL. Path templating is allowed." }, { - "id": "oas-3.0.media-type-object.considerations-for-file-uploads.must-upload-multiple-files-multipart-media-type", + "id": "oas-2.0.paths-object.pattern-path.must-field-name-begin-slash", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1543, - "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 260, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "pathsPath", "level": "MUST", "terms": ["MUST"], - "text": "To upload multiple files, a `multipart` media type MUST be used as shown under Example: Multipart Form with Multiple Files." + "text": "The field name MUST begin with a slash." }, { - "id": "oas-3.0.media-type-object.encoding", + "id": "oas-2.0.paths-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1435, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 261, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "pathsExtensions", "level": "field", "terms": [], - "text": "A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.media-type-object.encoding.must-key-being-property-name-exist-schema", + "id": "oas-2.0.paths-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1435, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 261, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "pathsExtensions", "level": "MUST", "terms": ["MUST"], - "text": "The key, being the property name, MUST exist in the schema as a property." + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.media-type-object.encoding.shall-encoding-field-only-apply-request-body", + "id": "oas-2.0.reference-object.$ref", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1435, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1158, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "referenceRef", + "level": "field", + "terms": [], + "text": "Required. The reference string." }, { - "id": "oas-3.0.media-type-object.example", + "id": "oas-2.0.response-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1433, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-example", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 894, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "responseDescription", "level": "field", "terms": [], - "text": "Example of the media type; see Working With Examples." + "text": "Required. A short description of the response. GFM syntax can be used for rich text representation." }, { - "id": "oas-3.0.media-type-object.examples", + "id": "oas-2.0.response-object.examples", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1434, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-examples", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 897, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "responseExamples", "level": "field", "terms": [], - "text": "Examples of the media type; see Working With Examples." + "text": "An example of the response message." }, { - "id": "oas-3.0.media-type-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.response-object.headers", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1437, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "fixed-fields-11", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 896, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "responseHeaders", + "level": "field", + "terms": [], + "text": "A list of headers that are sent with the response." }, { - "id": "oas-3.0.media-type-object.schema", + "id": "oas-2.0.response-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1432, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-schema", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 903, + "section": "Specification > Schema > Response Object > Patterned Objects", + "anchor": "responseExtensions", "level": "field", "terms": [], - "text": "The schema defining the content of the request, response, parameter, or header." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.media-type-object.shall-example-examples-fields-mutually-exclusive-either", + "id": "oas-2.0.response-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1424, - "section": "Specification > Schema > Media Type Object", - "anchor": "media-type-object", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 903, + "section": "Specification > Schema > Response Object > Patterned Objects", + "anchor": "responseExtensions", "level": "MUST", - "terms": ["SHALL"], - "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.media-type-object.should-example-examples-provided-example-match-specified", + "id": "oas-2.0.response-object.schema", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1424, - "section": "Specification > Schema > Media Type Object", - "anchor": "media-type-object", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 895, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "responseSchema", + "level": "field", + "terms": [], + "text": "A definition of the response structure. It can be a primitive, an array or an object. If this field does not exist, it means no content is returned as part of the response. As an extension to the Schema Object, its root `type` value may also be `\"file\"`. This SHOULD be accompanied by a relevant `produces` mime-type." }, { - "id": "oas-3.0.media-types.should-media-type-definitions-compliance-rfc6838", + "id": "oas-2.0.response-object.schema.should-accompanied-relevant-produces-mime-type", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 47, - "section": "Definitions > Media Types", - "anchor": "media-types", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 895, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "responseSchema", "level": "SHOULD", "terms": ["SHOULD"], - "text": "The media type definitions SHOULD be in compliance with RFC6838." + "text": "This SHOULD be accompanied by a relevant `produces` mime-type." }, { - "id": "oas-3.0.non-rfc6570-field-values-and-combinations.may-implementations-create-properly-delimited-uri-template", + "id": "oas-2.0.responses-definitions-object.pattern-name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3967, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", - "level": "MAY", - "terms": ["MAY"], - "text": "Implementations MAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based on `allowReserved`)." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2057, + "section": "Specification > Schema > Responses Definitions Object > Patterned Fields", + "anchor": "rdName", + "level": "field", + "terms": [], + "text": "A single response definition, mapping a \"name\" to the response it defines." }, { - "id": "oas-3.0.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", + "id": "oas-2.0.responses-object.default", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3976, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 847, + "section": "Specification > Schema > Responses Object > Fixed Fields", + "anchor": "responsesDefault", + "level": "field", + "terms": [], + "text": "The documentation of responses other than the ones declared for specific HTTP response codes. It can be used to cover undeclared responses. Reference Object can be used to link to a response that is defined at the Swagger Object's responses section." + }, + { + "id": "oas-2.0.responses-object.must-responses-object-contain-least-one-response", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 842, + "section": "Specification > Schema > Responses Object", + "anchor": "responses-object", "level": "MUST", - "terms": ["MUST"], - "text": "A parameter name that includes characters outside of the allowed RFC6570 variable character set MUST be percent-encoded before it can be used in a URI Template." + "terms": ["MUST", "SHOULD"], + "text": "The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call." }, { - "id": "oas-3.0.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", + "id": "oas-2.0.responses-object.pattern-http-status-code", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3967, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Configurations with no direct RFC6570 equivalent SHOULD also be handled according to RFC6570." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 852, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responsesCode", + "level": "field", + "terms": [], + "text": "Any HTTP status code can be used as the property name (one property per HTTP status code). Describes the expected response for that HTTP status code. Reference Object can be used to link to a response that is defined at the Swagger Object's responses section." }, { - "id": "oas-3.0.oauth-flow-object.authorizationUrl", + "id": "oas-2.0.responses-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3678, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 853, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responsesExtensions", "level": "field", "terms": [], - "text": "REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.oauth-flow-object.authorizationUrl.must-form-url", + "id": "oas-2.0.responses-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3678, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 853, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responsesExtensions", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.oauth-flow-object.authorizationUrl.required", + "id": "oas-2.0.schema-object.composition-and-inheritance-polymorphism.must-discriminator-field-required-field", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3678, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1250, + "section": "Specification > Schema > Schema Object > Patterned Objects > Composition and Inheritance (Polymorphism)", + "anchor": "composition-and-inheritance-polymorphism", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "As such, the `discriminator` field MUST be a required field." }, { - "id": "oas-3.0.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.schema-object.discriminator", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3683, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "fixed-fields-25", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1234, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaDiscriminator", + "level": "field", + "terms": [], + "text": "Adds support for polymorphism. The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the `required` property list. When used, the value MUST be the name of this schema or any schema that inherits it." }, { - "id": "oas-3.0.oauth-flow-object.refreshUrl", + "id": "oas-2.0.schema-object.discriminator.must-property-name-used-defined-schema-required", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3680, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-refresh-url", - "level": "field", - "terms": [], - "text": "The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1234, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaDiscriminator", + "level": "MUST", + "terms": ["MUST"], + "text": "The property name used MUST be defined at this schema and it MUST be in the `required` property list." }, { - "id": "oas-3.0.oauth-flow-object.refreshUrl.must-form-url", + "id": "oas-2.0.schema-object.discriminator.must-used-value-name-schema-any-schema", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3680, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-refresh-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1234, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaDiscriminator", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "When used, the value MUST be the name of this schema or any schema that inherits it." }, { - "id": "oas-3.0.oauth-flow-object.scopes", + "id": "oas-2.0.schema-object.example", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3681, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1238, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaExample", "level": "field", "terms": [], - "text": "REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty." + "text": "A free-form property to include an example of an instance for this schema." }, { - "id": "oas-3.0.oauth-flow-object.scopes.may-map-empty", + "id": "oas-2.0.schema-object.externalDocs", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3681, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", - "level": "MAY", - "terms": ["MAY"], - "text": "The map MAY be empty." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1237, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaExternalDocs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this schema." }, { - "id": "oas-3.0.oauth-flow-object.scopes.required", + "id": "oas-2.0.schema-object.must-default-unlike-json-schema-value-conform", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3681, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1205, + "section": "Specification > Schema > Schema Object", + "anchor": "schema-object", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "default (Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object)" }, { - "id": "oas-3.0.oauth-flow-object.tokenUrl", + "id": "oas-2.0.schema-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3679, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1244, + "section": "Specification > Schema > Schema Object > Patterned Objects", + "anchor": "schemaExtensions", "level": "field", "terms": [], - "text": "REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.oauth-flow-object.tokenUrl.must-form-url", + "id": "oas-2.0.schema-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3679, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1244, + "section": "Specification > Schema > Schema Object > Patterned Objects", + "anchor": "schemaExtensions", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." - }, - { - "id": "oas-3.0.oauth-flow-object.tokenUrl.required", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3679, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.oauth-flows-object.authorizationCode", + "id": "oas-2.0.schema-object.readOnly", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3666, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-authorization-code", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1235, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaReadOnly", "level": "field", "terms": [], - "text": "Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0." + "text": "Relevant only for Schema `\"properties\"` definitions. Declares the property as \"read only\". This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request. Properties marked as `readOnly` being `true` SHOULD NOT be in the `required` list of the defined schema. Default value is `false`." }, { - "id": "oas-3.0.oauth-flows-object.clientCredentials", + "id": "oas-2.0.schema-object.readOnly.must-not-means-sent-part-response-but-sent", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3665, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-client-credentials", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0." - }, - { - "id": "oas-3.0.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3668, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "fixed-fields-24", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1235, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaReadOnly", + "level": "MUST", + "terms": ["MAY", "MUST NOT"], + "text": "This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request." }, { - "id": "oas-3.0.oauth-flows-object.implicit", + "id": "oas-2.0.schema-object.readOnly.should-not-properties-marked-readonly-being-true-required", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3663, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-implicit", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Implicit flow" + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1235, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaReadOnly", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Properties marked as `readOnly` being `true` SHOULD NOT be in the `required` list of the defined schema." }, { - "id": "oas-3.0.oauth-flows-object.password", + "id": "oas-2.0.schema-object.xml", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3664, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-password", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1236, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaXml", "level": "field", "terms": [], - "text": "Configuration for the OAuth Resource Owner Password flow" + "text": "This MAY be used only on properties schemas. It has no effect on root schemas. Adds Additional metadata to describe the XML representation format of this property." }, { - "id": "oas-3.0.openapi-description-structure.may-openapi-description-oad-made-up-single", + "id": "oas-2.0.schema-object.xml.may-used-only-properties-schemas", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 124, - "section": "Specification > OpenAPI Description Structure", - "anchor": "openapi-description-structure", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1236, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schemaXml", "level": "MAY", "terms": ["MAY"], - "text": "An OpenAPI Description (OAD) MAY be made up of a single JSON or YAML document or be divided into multiple, connected parts at the discretion of the author." - }, - { - "id": "oas-3.0.openapi-description-structure.recommended-entry-document-oad-named-openapi-json", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 128, - "section": "Specification > OpenAPI Description Structure", - "anchor": "openapi-description-structure", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is RECOMMENDED that the entry document of an OAD be named: `openapi.json` or `openapi.yaml`." + "text": "This MAY be used only on properties schemas." }, { - "id": "oas-3.0.openapi-object.components", + "id": "oas-2.0.scopes-object.pattern-name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 264, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-components", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2216, + "section": "Specification > Schema > Scopes Object > Patterned Fields", + "anchor": "scopesName", "level": "field", "terms": [], - "text": "An element to hold various Objects for the OpenAPI Description." + "text": "Maps between a name of a scope to a short description of it (as the value of the property)." }, { - "id": "oas-3.0.openapi-object.externalDocs", + "id": "oas-2.0.scopes-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 267, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-external-docs", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2222, + "section": "Specification > Schema > Scopes Object > Patterned Objects", + "anchor": "scopesExtensions", "level": "field", "terms": [], - "text": "Additional external documentation." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.openapi-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.scopes-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 269, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "fixed-fields", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2222, + "section": "Specification > Schema > Scopes Object > Patterned Objects", + "anchor": "scopesExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.openapi-object.info", + "id": "oas-2.0.security-definitions-object.pattern-name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 261, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2096, + "section": "Specification > Schema > Security Definitions Object > Patterned Fields", + "anchor": "sdName", "level": "field", "terms": [], - "text": "REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required." - }, - { - "id": "oas-3.0.openapi-object.info.may-metadata-used-tooling-required", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 261, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", - "level": "MAY", - "terms": ["MAY"], - "text": "The metadata MAY be used by tooling as required." + "text": "A single security scheme definition, mapping a \"name\" to the scheme it defines." }, { - "id": "oas-3.0.openapi-object.info.required", + "id": "oas-2.0.security-requirement-object.must-name-used-each-property-correspond-security", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 261, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2242, + "section": "Specification > Schema > Security Requirement Object", + "anchor": "security-requirement-object", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "The name used for each property MUST correspond to a security scheme declared in the Security Definitions." }, { - "id": "oas-3.0.openapi-object.openapi", + "id": "oas-2.0.security-requirement-object.pattern-name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 260, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2248, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "securityRequirementsName", "level": "field", "terms": [], - "text": "REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document. This is _not_ related to the API `info.version` string." + "text": "Each name must correspond to a security scheme which is declared in the Security Definitions. If the security scheme is of type `\"oauth2\"`, then the value is a list of scope names required for the execution. For other security scheme types, the array MUST be empty." }, { - "id": "oas-3.0.openapi-object.openapi.must-string-version-number-openapi-specification-openapi", + "id": "oas-2.0.security-requirement-object.pattern-name.must-other-security-scheme-types-array-empty", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 260, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2248, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "securityRequirementsName", "level": "MUST", "terms": ["MUST"], - "text": "This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses." + "text": "For other security scheme types, the array MUST be empty." }, { - "id": "oas-3.0.openapi-object.openapi.required", + "id": "oas-2.0.security-scheme-object.authorizationUrl", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 260, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2145, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeAuthorizationUrl", + "level": "field", + "terms": [], + "text": "Required. The authorization URL to be used for this flow. This SHOULD be in the form of a URL." }, { - "id": "oas-3.0.openapi-object.openapi.should-openapi-field-used-tooling-interpret-openapi", + "id": "oas-2.0.security-scheme-object.authorizationUrl.should-form-url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 260, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2145, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeAuthorizationUrl", "level": "SHOULD", "terms": ["SHOULD"], - "text": "The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document." + "text": "This SHOULD be in the form of a URL." }, { - "id": "oas-3.0.openapi-object.paths", + "id": "oas-2.0.security-scheme-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 263, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-paths", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2141, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeDescription", "level": "field", "terms": [], - "text": "REQUIRED. The available paths and operations for the API." + "text": "A short description for security scheme." }, { - "id": "oas-3.0.openapi-object.paths.required", + "id": "oas-2.0.security-scheme-object.flow", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 263, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-paths", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2144, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeFlow", + "level": "field", + "terms": [], + "text": "Required. The flow used by the OAuth2 security scheme. Valid values are `\"implicit\"`, `\"password\"`, `\"application\"` or `\"accessCode\"`." }, { - "id": "oas-3.0.openapi-object.security", + "id": "oas-2.0.security-scheme-object.in", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 265, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-security", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2143, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeIn", "level": "field", "terms": [], - "text": "A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array." + "text": "Required The location of the API key. Valid values are `\"query\"` or `\"header\"`." }, { - "id": "oas-3.0.openapi-object.servers", + "id": "oas-2.0.security-scheme-object.name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 262, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-servers", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2142, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeName", "level": "field", "terms": [], - "text": "An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be a Server Object with a url value of `/`." + "text": "Required. The name of the header or query parameter to be used." }, { - "id": "oas-3.0.openapi-object.tags", + "id": "oas-2.0.security-scheme-object.scopes", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 266, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2147, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeScopes", "level": "field", "terms": [], - "text": "A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." + "text": "Required. The available scopes for the OAuth2 security scheme." }, { - "id": "oas-3.0.openapi-object.tags.may-tags-not-declared-organized-randomly-based", + "id": "oas-2.0.security-scheme-object.tokenUrl", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 266, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", - "level": "MAY", - "terms": ["MAY"], - "text": "The tags that are not declared MAY be organized randomly or based on the tools' logic." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2146, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeTokenUrl", + "level": "field", + "terms": [], + "text": "Required. The token URL to be used for this flow. This SHOULD be in the form of a URL." }, { - "id": "oas-3.0.openapi-object.tags.must-each-tag-name-list-unique", + "id": "oas-2.0.security-scheme-object.tokenUrl.should-form-url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 266, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", - "level": "MUST", - "terms": ["MUST"], - "text": "Each tag name in the list MUST be unique." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2146, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeTokenUrl", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "This SHOULD be in the form of a URL." }, { - "id": "oas-3.0.operation-object.callbacks", + "id": "oas-2.0.security-scheme-object.type", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 911, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-callbacks", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2140, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "securitySchemeType", "level": "field", "terms": [], - "text": "A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses." + "text": "Required. The type of the security scheme. Valid values are `\"basic\"`, `\"apiKey\"` or `\"oauth2\"`." }, { - "id": "oas-3.0.operation-object.deprecated", + "id": "oas-2.0.security-scheme-object.x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 912, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-deprecated", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2153, + "section": "Specification > Schema > Security Scheme Object > Patterned Fields", + "anchor": "securitySchemeExtensions", "level": "field", "terms": [], - "text": "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.operation-object.deprecated.should-consumers-refrain-usage-declared-operation", + "id": "oas-2.0.security-scheme-object.x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 912, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-deprecated", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Consumers SHOULD refrain from usage of the declared operation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 2153, + "section": "Specification > Schema > Security Scheme Object > Patterned Fields", + "anchor": "securitySchemeExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.operation-object.description", + "id": "oas-2.0.swagger-object.basePath", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 905, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 112, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerBasePath", "level": "field", "terms": [], - "text": "A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation." + "text": "The base path on which the API is served, which is relative to the `host`. If it is not included, the API is served directly under the `host`. The value MUST start with a leading slash (`/`). The `basePath` does not support path templating." }, { - "id": "oas-3.0.operation-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.swagger-object.basePath.must-value-start-leading-slash", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 905, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 112, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerBasePath", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST start with a leading slash (`/`)." }, { - "id": "oas-3.0.operation-object.externalDocs", + "id": "oas-2.0.swagger-object.consumes", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 906, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-external-docs", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 114, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerConsumes", "level": "field", "terms": [], - "text": "Additional external documentation for this operation." + "text": "A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.operation-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.swagger-object.consumes.must-value-described-under-mime-types", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 916, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "fixed-fields-7", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 114, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerConsumes", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.operation-object.operationId", + "id": "oas-2.0.swagger-object.definitions", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 907, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-id", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 117, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerDefinitions", "level": "field", "terms": [], - "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + "text": "An object to hold data types produced and consumed by operations." }, { - "id": "oas-3.0.operation-object.operationId.must-id-unique-among-all-operations-described", + "id": "oas-2.0.swagger-object.externalDocs", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 907, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-id", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 123, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerExternalDocs", + "level": "field", + "terms": [], + "text": "Additional external documentation." + }, + { + "id": "oas-2.0.swagger-object.host", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 111, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerHost", + "level": "field", + "terms": [], + "text": "The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the `host` is not included, the host serving the documentation is to be used (including the port). The `host` does not support path templating." + }, + { + "id": "oas-2.0.swagger-object.host.may-include-port", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 111, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerHost", + "level": "MAY", + "terms": ["MAY"], + "text": "It MAY include a port." + }, + { + "id": "oas-2.0.swagger-object.host.must-host-only-does-not-include-scheme", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 111, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerHost", "level": "MUST", "terms": ["MUST"], - "text": "The id MUST be unique among all operations described in the API." + "text": "This MUST be the host only and does not include the scheme nor sub-paths." }, { - "id": "oas-3.0.operation-object.operationId.recommended-tools-libraries-use-operationid-uniquely-identify", + "id": "oas-2.0.swagger-object.info", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 907, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-id", - "level": "SHOULD", - "terms": ["MAY", "RECOMMENDED"], - "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 110, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerInfo", + "level": "field", + "terms": [], + "text": "Required. Provides metadata about the API. The metadata can be used by the clients if needed." }, { - "id": "oas-3.0.operation-object.parameters", + "id": "oas-2.0.swagger-object.parameters", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 908, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-parameters", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 118, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerParameters", "level": "field", "terms": [], - "text": "A list of parameters that are applicable for this operation. If a parameter is already defined in the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + "text": "An object to hold parameters that can be used across operations. This property *does not* define global parameters for all operations." }, { - "id": "oas-3.0.operation-object.parameters.must-not-list-include-duplicated-parameters", + "id": "oas-2.0.swagger-object.paths", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 908, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-parameters", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The list MUST NOT include duplicated parameters." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 116, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerPaths", + "level": "field", + "terms": [], + "text": "Required. The available paths and operations for the API." }, { - "id": "oas-3.0.operation-object.requestBody", + "id": "oas-2.0.swagger-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 909, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-request-body", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 129, + "section": "Specification > Schema > Swagger Object > Patterned Objects", + "anchor": "swaggerExtensions", "level": "field", "terms": [], - "text": "The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` SHALL be ignored by consumers." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.operation-object.requestBody.shall-other-cases-http-spec-vague-get", + "id": "oas-2.0.swagger-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 909, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-request-body", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 129, + "section": "Specification > Schema > Swagger Object > Patterned Objects", + "anchor": "swaggerExtensions", "level": "MUST", - "terms": ["SHALL"], - "text": "In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` SHALL be ignored by consumers." + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.operation-object.responses", + "id": "oas-2.0.swagger-object.produces", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 910, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-responses", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 115, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerProduces", "level": "field", "terms": [], - "text": "REQUIRED. The list of possible responses as they are returned from executing this operation." + "text": "A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.operation-object.responses.required", + "id": "oas-2.0.swagger-object.produces.must-value-described-under-mime-types", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 910, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-responses", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 115, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerProduces", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Value MUST be as described under Mime Types." }, { - "id": "oas-3.0.operation-object.security", + "id": "oas-2.0.swagger-object.responses", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 913, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-security", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 119, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerResponses", "level": "field", "terms": [], - "text": "A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." + "text": "An object to hold responses that can be used across operations. This property *does not* define global responses for all operations." }, { - "id": "oas-3.0.operation-object.servers", + "id": "oas-2.0.swagger-object.schemes", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 914, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-servers", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 113, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerSchemes", "level": "field", "terms": [], - "text": "An alternative `servers` array to service this operation. If a `servers` array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value." + "text": "The transfer protocol of the API. Values MUST be from the list: `\"http\"`, `\"https\"`, `\"ws\"`, `\"wss\"`. If the `schemes` is not included, the default scheme to be used is the one used to access the Swagger definition itself." }, { - "id": "oas-3.0.operation-object.summary", + "id": "oas-2.0.swagger-object.schemes.must-values-list-http-https-ws-wss", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 904, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-summary", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 113, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerSchemes", + "level": "MUST", + "terms": ["MUST"], + "text": "Values MUST be from the list: `\"http\"`, `\"https\"`, `\"ws\"`, `\"wss\"`." + }, + { + "id": "oas-2.0.swagger-object.security", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 121, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerSecurity", "level": "field", "terms": [], - "text": "A short summary of what the operation does." + "text": "A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition." }, { - "id": "oas-3.0.operation-object.tags", + "id": "oas-2.0.swagger-object.securityDefinitions", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 903, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-tags", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 120, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerSecurityDefinitions", "level": "field", "terms": [], - "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." + "text": "Security scheme definitions that can be used across the specification." }, { - "id": "oas-3.0.parameter-object.allowEmptyValue", + "id": "oas-2.0.swagger-object.swagger", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1084, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 109, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerSwagger", "level": "field", "terms": [], - "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for `query` parameters. Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + "text": "Required. Specifies the Swagger Specification version being used. It can be used by the Swagger UI and other clients to interpret the API listing. The value MUST be `\"2.0\"`." }, { - "id": "oas-3.0.parameter-object.allowEmptyValue.not-recommended-use-field-likely-removed-later-revision", + "id": "oas-2.0.swagger-object.swagger.must-value-2-0", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1084, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 109, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerSwagger", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST be `\"2.0\"`." }, { - "id": "oas-3.0.parameter-object.allowEmptyValue.shall-style-used-behavior-n-cannot-serialized", + "id": "oas-2.0.swagger-object.tags", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1084, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "MUST", - "terms": ["SHALL"], - "text": "If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 122, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerTags", + "level": "field", + "terms": [], + "text": "A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." }, { - "id": "oas-3.0.parameter-object.allowEmptyValue.should-true-clients-pass-zero-length-string", + "id": "oas-2.0.swagger-object.tags.must-each-tag-name-list-unique", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1084, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "SHOULD", - "terms": ["MAY", "SHOULD"], - "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 122, + "section": "Specification > Schema > Swagger Object > Fixed Fields", + "anchor": "swaggerTags", + "level": "MUST", + "terms": ["MUST"], + "text": "Each tag name in the list MUST be unique." }, { - "id": "oas-3.0.parameter-object.allowReserved", + "id": "oas-2.0.tag-object.description", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1102, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-allow-reserved", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1127, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tagDescription", "level": "field", "terms": [], - "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see Appendices C and E for details. This field only applies to parameters with an `in` value of `query`. The default value is `false`." + "text": "A short description for the tag. GFM syntax can be used for rich text representation." }, { - "id": "oas-3.0.parameter-object.common-fixed-fields.may-fields-used-either-content-schema", + "id": "oas-2.0.tag-object.externalDocs", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1075, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields", - "level": "MAY", - "terms": ["MAY"], - "text": "These fields MAY be used with either `content` or `schema`." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1128, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tagExternalDocs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this tag." }, { - "id": "oas-3.0.parameter-object.common-fixed-fields.may-object-extended-specification-extensions", + "id": "oas-2.0.tag-object.name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1086, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1126, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tagName", + "level": "field", + "terms": [], + "text": "Required. The name of the tag." }, { - "id": "oas-3.0.parameter-object.content", + "id": "oas-2.0.tag-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1116, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "parameter-content", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1133, + "section": "Specification > Schema > Tag Object > Patterned Fields", + "anchor": "tagExtensions", "level": "field", "terms": [], - "text": "A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.parameter-object.content.must-map-only-contain-one-entry", + "id": "oas-2.0.tag-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1116, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "parameter-content", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1133, + "section": "Specification > Schema > Tag Object > Patterned Fields", + "anchor": "tagExtensions", "level": "MUST", "terms": ["MUST"], - "text": "The map MUST only contain one entry." + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.0.parameter-object.deprecated", + "id": "oas-2.0.xml-object.attribute", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1083, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-deprecated", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1590, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlAttribute", "level": "field", "terms": [], - "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`." }, { - "id": "oas-3.0.parameter-object.deprecated.should-specifies-parameter-deprecated-transitioned-out-usage", + "id": "oas-2.0.xml-object.name", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1083, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-deprecated", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1587, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlName", + "level": "field", + "terms": [], + "text": "Replaces the name of the element/attribute used for the described schema property. When defined within the Items Object (`items`), it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored." }, { - "id": "oas-3.0.parameter-object.description", + "id": "oas-2.0.xml-object.namespace", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1081, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-description", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1588, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlNamespace", "level": "field", "terms": [], - "text": "A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "text": "The URL of the namespace definition. Value SHOULD be in the form of a URL." }, { - "id": "oas-3.0.parameter-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-2.0.xml-object.namespace.should-value-form-url", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1081, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1588, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlNamespace", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Value SHOULD be in the form of a URL." }, { - "id": "oas-3.0.parameter-object.example", + "id": "oas-2.0.xml-object.pattern-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1104, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-example", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1597, + "section": "Specification > Schema > XML Object > Patterned Objects", + "anchor": "xmlExtensions", "level": "field", "terms": [], - "text": "Example of the parameter's potential value; see Working With Examples." + "text": "Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See Vendor Extensions for further details." }, { - "id": "oas-3.0.parameter-object.examples", + "id": "oas-2.0.xml-object.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1105, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-examples", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1597, + "section": "Specification > Schema > XML Object > Patterned Objects", + "anchor": "xmlExtensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + }, + { + "id": "oas-2.0.xml-object.prefix", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1589, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlPrefix", "level": "field", "terms": [], - "text": "Examples of the parameter's potential value; see Working With Examples." + "text": "The prefix to be used for the name." }, { - "id": "oas-3.0.parameter-object.explode", + "id": "oas-2.0.xml-object.wrapped", "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1101, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-explode", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1591, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlWrapped", "level": "field", "terms": [], - "text": "When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined." + "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`)." }, { - "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-content.recommended-using-content-text-plain-media-type", + "id": "oas-2.0.xml-object.wrapped.may-used-only-array-definition", + "spec": "openapi", + "version": "2.0", + "source": "openapi/2.0.md", + "line": 1591, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xmlWrapped", + "level": "MAY", + "terms": ["MAY"], + "text": "MAY be used only for an array definition." + }, + { + "id": "oas-3.0.appendix-c-using-rfc6570-based-serialization.may-implementations-specification-use-implementation-rfc6570-perform", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1111, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "fixed-fields-for-use-with-content", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "Using `content` with a `text/plain` media type is RECOMMENDED for `in: \"header\"` and `in: \"cookie\"` parameters where the `schema` strategy is not appropriate." + "line": 3914, + "section": "Appendix C: Using RFC6570-Based Serialization", + "anchor": "appendix-c-using-rfc6570-based-serialization", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations of this specification MAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply." }, { - "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-header-parameters", + "id": "oas-3.0.appendix-d-serializing-headers-and-cookies.not-recommended-note-standard-base64-encoding-alphabet-includes", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1096, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "line": 4161, + "section": "Appendix D: Serializing Headers and Cookies", + "anchor": "appendix-d-serializing-headers-and-cookies", "level": "SHOULD", "terms": ["NOT RECOMMENDED"], - "text": "Serializing with `schema` is NOT RECOMMENDED for `in: \"cookie\"` parameters, `in: \"header\"` parameters that use HTTP header parameters (name=value pairs following a `;`) in their values, or `in: \"header\"` parameters where values might have non-URL-safe characters; see Appendix D for details." + "text": "Note that the standard base64-encoding alphabet includes non-URL-safe characters that are percent-encoded by RFC6570 expansion; serializing values through both encodings is NOT RECOMMENDED." }, { - "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", + "id": "oas-3.0.appendix-f-resolving-security-requirements-in-a-referenced-document.recommended-however-documented-section-tools-resolve-component", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1092, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + "line": 4360, + "section": "Appendix F: Resolving Security Requirements in a Referenced Document", + "anchor": "appendix-f-resolving-security-requirements-in-a-referenced-document", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, documented in that section, it is RECOMMENDED that tools resolve component names from the entry document." }, { - "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", + "id": "oas-3.0.callback-object.pattern-expression", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1092, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the parameter." + "line": 2035, + "section": "Specification > Schema > Callback Object > Patterned Fields", + "anchor": "callback-expression", + "level": "field", + "terms": [], + "text": "A Path Item Object used to define a callback request and expected responses. A complete example is available." }, { - "id": "oas-3.0.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field", + "id": "oas-3.0.callback-object.patterned-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1069, - "section": "Specification > Schema > Parameter Object > Fixed Fields", - "anchor": "fixed-fields-9", - "level": "MUST", - "terms": ["MUST"], - "text": "Parameter Objects MUST include either a `content` field or a `schema` field, but not both." + "line": 2037, + "section": "Specification > Schema > Callback Object > Patterned Fields", + "anchor": "patterned-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.parameter-object.in", + "id": "oas-3.0.components-object.callbacks", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1080, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-in", + "line": 517, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-callbacks", "level": "field", "terms": [], - "text": "REQUIRED. The location of the parameter. Possible values are `\"query\"`, `\"header\"`, `\"path\"` or `\"cookie\"`." + "text": "An object to hold reusable Callback Objects." }, { - "id": "oas-3.0.parameter-object.in.required", + "id": "oas-3.0.components-object.examples", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1080, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-in", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 512, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-examples", + "level": "field", + "terms": [], + "text": "An object to hold reusable Example Objects." }, { - "id": "oas-3.0.parameter-object.name", + "id": "oas-3.0.components-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1079, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the parameter. Parameter names are _case sensitive_. If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information. If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored. For all other cases, the `name` corresponds to the parameter name used by the `in` field." + "line": 519, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "fixed-fields-5", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.parameter-object.name.must-path-name-field-correspond-template-expression", + "id": "oas-3.0.components-object.fixed-fields.must-all-fixed-fields-declared-above-objects", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1079, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", + "line": 521, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "fixed-fields-5", "level": "MUST", "terms": ["MUST"], - "text": "If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object." + "text": "All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\\.\\-_]+$`." }, { - "id": "oas-3.0.parameter-object.name.required", + "id": "oas-3.0.components-object.headers", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1079, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 514, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-headers", + "level": "field", + "terms": [], + "text": "An object to hold reusable Header Objects." }, { - "id": "oas-3.0.parameter-object.name.shall-header-name-field-accept-content-type", + "id": "oas-3.0.components-object.links", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1079, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", - "level": "MUST", - "terms": ["SHALL"], - "text": "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored." + "line": 516, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-links", + "level": "field", + "terms": [], + "text": "An object to hold reusable Link Objects." }, { - "id": "oas-3.0.parameter-object.required", + "id": "oas-3.0.components-object.parameters", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1082, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", + "line": 511, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-parameters", "level": "field", "terms": [], - "text": "Determines whether this parameter is mandatory. If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`." + "text": "An object to hold reusable Parameter Objects." }, { - "id": "oas-3.0.parameter-object.required.may-otherwise-field-included-default-value-false", + "id": "oas-3.0.components-object.requestBodies", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1082, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", - "level": "MAY", - "terms": ["MAY"], - "text": "Otherwise, the field MAY be included and its default value is `false`." + "line": 513, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-request-bodies", + "level": "field", + "terms": [], + "text": "An object to hold reusable Request Body Objects." }, { - "id": "oas-3.0.parameter-object.required.required-parameter-location-path-field-value-true", + "id": "oas-3.0.components-object.responses", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1082, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", - "level": "MUST", - "terms": ["REQUIRED", "MUST"], - "text": "If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`." - }, - { - "id": "oas-3.0.parameter-object.schema", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1103, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-schema", + "line": 510, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-responses", "level": "field", "terms": [], - "text": "The schema defining the type used for the parameter." + "text": "An object to hold reusable Response Objects." }, { - "id": "oas-3.0.parameter-object.style", + "id": "oas-3.0.components-object.schemas", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1100, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-style", + "line": 509, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-schemas", "level": "field", "terms": [], - "text": "Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"`." + "text": "An object to hold reusable Schema Objects." }, { - "id": "oas-3.0.parameter-object.style-examples.must-note-prefix-not-appropriate-serializing-application", + "id": "oas-3.0.components-object.securitySchemes", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1150, - "section": "Specification > Schema > Parameter Object > Style Examples", - "anchor": "style-examples", - "level": "MUST", - "terms": ["MUST"], - "text": "Note that the `?` prefix is not appropriate for serializing `application/x-www-form-urlencoded` HTTP message bodies, and MUST be stripped or (if constructing the string manually) not added when used in that context; see the Encoding Object for more information" + "line": 515, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "security-scheme-object", + "level": "field", + "terms": [], + "text": "An object to hold reusable Security Scheme Objects." }, { - "id": "oas-3.0.path-item-object.$ref", + "id": "oas-3.0.conditions-for-using-the-discriminator-object.may-avoid-redundancy-discriminator-added-parent-schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 795, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-ref", - "level": "field", - "terms": [], - "text": "Allows for a referenced definition of this path item. The value MUST be in the form of a URL, and the referenced structure MUST be in the form of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving Relative References." + "line": 3059, + "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", + "level": "MAY", + "terms": ["MAY"], + "text": "To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas building on the parent schema via an `allOf` construct may be used as an alternate schema." }, { - "id": "oas-3.0.path-item-object.$ref.must-value-form-url-referenced-structure-form", + "id": "oas-3.0.conditions-for-using-the-discriminator-object.must-both-oneof-anyof-use-cases-keywords", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 795, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-ref", + "line": 3057, + "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", "level": "MUST", "terms": ["MUST"], - "text": "The value MUST be in the form of a URL, and the referenced structure MUST be in the form of a Path Item Object." + "text": "In both the `oneOf` and `anyOf` use cases, where those keywords are adjacent to `discriminator`, all possible schemas MUST be listed explicitly." }, { - "id": "oas-3.0.path-item-object.delete", + "id": "oas-3.0.conditions-for-using-the-discriminator-object.recommended-however-search-all-named-schemas-components", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 801, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-delete", - "level": "field", - "terms": [], - "text": "A definition of a DELETE operation on this path." + "line": 3059, + "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, it is RECOMMENDED to search all named schemas in the Components Object because it is common with the `allOf` usage for other parts of the API to only directly reference the parent schema." }, { - "id": "oas-3.0.path-item-object.description", + "id": "oas-3.0.contact-object.email", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 797, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-description", + "line": 333, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-email", "level": "field", "terms": [], - "text": "An optional string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation." + "text": "The email address of the contact person/organization. This MUST be in the form of an email address." }, { - "id": "oas-3.0.path-item-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.contact-object.email.must-form-email-address", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 797, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "line": 333, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-email", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of an email address." }, { - "id": "oas-3.0.path-item-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.contact-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 809, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "fixed-fields-6", + "line": 335, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "fixed-fields-1", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.path-item-object.get", + "id": "oas-3.0.contact-object.name", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 798, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-get", + "line": 331, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-name", "level": "field", "terms": [], - "text": "A definition of a GET operation on this path." + "text": "The identifying name of the contact person/organization." }, { - "id": "oas-3.0.path-item-object.head", + "id": "oas-3.0.contact-object.url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 803, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-head", + "line": 332, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-url", "level": "field", "terms": [], - "text": "A definition of a HEAD operation on this path." + "text": "The URL for the contact information. This MUST be in the form of a URL." }, { - "id": "oas-3.0.path-item-object.may-path-item-empty-due-acl-constraints", + "id": "oas-3.0.contact-object.url.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 787, - "section": "Specification > Schema > Path Item Object", - "anchor": "path-item-object", - "level": "MAY", - "terms": ["MAY"], - "text": "A Path Item MAY be empty, due to ACL constraints." + "line": 332, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.path-item-object.options", + "id": "oas-3.0.data-type-format.may-tools-do-not-recognize-specific-format", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 802, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-options", - "level": "field", - "terms": [], - "text": "A definition of a OPTIONS operation on this path." + "line": 195, + "section": "Specification > Data Types > Data Type Format", + "anchor": "data-type-format", + "level": "MAY", + "terms": ["MAY"], + "text": "Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified." }, { - "id": "oas-3.0.path-item-object.parameters", + "id": "oas-3.0.data-type-format.optional-support-any-registered-format-strictly-support", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 807, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-parameters", - "level": "field", - "terms": [], - "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + "line": 193, + "section": "Specification > Data Types > Data Type Format", + "anchor": "data-type-format", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Support for any registered format is strictly OPTIONAL, and support for one registered format does not imply support for any others." }, { - "id": "oas-3.0.path-item-object.parameters.must-not-list-include-duplicated-parameters", + "id": "oas-3.0.discriminator-object.examples.may-discriminator-used-hint-improve-efficiency-selection", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 807, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-parameters", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The list MUST NOT include duplicated parameters." + "line": 3093, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-1", + "level": "MAY", + "terms": ["MAY"], + "text": "A `discriminator` MAY be used as a \"hint\" to improve the efficiency of selection of the matching schema." }, { - "id": "oas-3.0.path-item-object.patch", + "id": "oas-3.0.discriminator-object.examples.may-oas-3-0-response-payload-described", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 804, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-patch", - "level": "field", - "terms": [], - "text": "A definition of a PATCH operation on this path." + "line": 3083, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-1", + "level": "MAY", + "terms": ["MAY"], + "text": "In OAS 3.0, a response payload MAY be described to be exactly one of any number of types:" }, { - "id": "oas-3.0.path-item-object.post", + "id": "oas-3.0.discriminator-object.examples.may-scenarios-value-discriminator-field-does-not", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 800, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-post", - "level": "field", - "terms": [], - "text": "A definition of a POST operation on this path." + "line": 3116, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-1", + "level": "MAY", + "terms": ["MAY"], + "text": "In scenarios where the value of the `discriminator` field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used:" }, { - "id": "oas-3.0.path-item-object.put", + "id": "oas-3.0.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 799, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-put", - "level": "field", - "terms": [], - "text": "A definition of a PUT operation on this path." + "line": 3132, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail." }, { - "id": "oas-3.0.path-item-object.servers", + "id": "oas-3.0.discriminator-object.mapping", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 806, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-servers", + "line": 3051, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "discriminator-mapping", "level": "field", "terms": [], - "text": "An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the OpenAPI Object level, it will be overridden by this value." + "text": "An object to hold mappings between payload values and schema names or URI references." }, { - "id": "oas-3.0.path-item-object.summary", + "id": "oas-3.0.discriminator-object.must-not-note-discriminator-change-validation-outcome-schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 796, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-summary", - "level": "field", - "terms": [], - "text": "An optional string summary, intended to apply to all operations in this path." + "line": 3044, + "section": "Specification > Schema > Discriminator Object", + "anchor": "discriminator-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Note that `discriminator` MUST NOT change the validation outcome of the schema." }, { - "id": "oas-3.0.path-item-object.trace", + "id": "oas-3.0.discriminator-object.options-for-mapping-values-to-schemas.must-ensure-ambiguous-value-e-g-foo", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 805, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-trace", - "level": "field", - "terms": [], - "text": "A definition of a TRACE operation on this path." + "line": 3070, + "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "MUST", + "terms": ["MUST"], + "text": "To ensure that an ambiguous value (e.g. `\"foo\"`) is treated as a relative URI reference by all implementations, authors MUST prefix it with the `\".\"` path segment (e.g. `\"./foo\"`)." }, { - "id": "oas-3.0.path-templating.must-each-template-expression-path-correspond-path", + "id": "oas-3.0.discriminator-object.options-for-mapping-values-to-schemas.must-mapping-keys-string-values-but-tooling", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 43, - "section": "Definitions > Path Templating", - "anchor": "path-templating", + "line": 3076, + "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", "level": "MUST", - "terms": ["MUST"], - "text": "Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations." + "terms": ["MUST", "MAY"], + "text": "Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison." }, { - "id": "oas-3.0.paths-object.may-paths-object-empty-due-access-control", + "id": "oas-3.0.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-both-valid-schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 709, - "section": "Specification > Schema > Paths Object", - "anchor": "paths-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The Paths Object MAY be empty, due to Access Control List (ACL) constraints." + "line": 3070, + "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "The behavior of a `mapping` value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it is RECOMMENDED that it be treated as a schema name." }, { - "id": "oas-3.0.paths-object.pattern-path", + "id": "oas-3.0.discriminator-object.propertyName", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 716, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "paths-path", + "line": 3050, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "property-name", "level": "field", "terms": [], - "text": "A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is appended (no relative URL resolution) to the expanded URL from the Server Object's `url` field in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use." + "text": "REQUIRED. The name of the property in the payload that will hold the discriminating value. This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." }, { - "id": "oas-3.0.paths-object.pattern-path.must-field-name-begin-forward-slash", + "id": "oas-3.0.discriminator-object.propertyName.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 716, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "paths-path", + "line": 3050, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "property-name", "level": "MUST", - "terms": ["MUST"], - "text": "The field name MUST begin with a forward slash (`/`)." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.paths-object.pattern-path.must-not-templated-paths-same-hierarchy-but-different", + "id": "oas-3.0.discriminator-object.propertyName.should-property-required-payload-schema-behavior-property", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 716, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "paths-path", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical." + "line": 3050, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." }, { - "id": "oas-3.0.paths-object.patterned-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.encoding-object.allowReserved", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 718, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "patterned-fields", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "line": 1596, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "field", + "terms": [], + "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see Appendices C and E for details. The default value is `false`. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", + "id": "oas-3.0.encoding-object.allowReserved.shall-field-ignored-request-body-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 4253, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", - "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "line": 1596, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", "level": "MUST", - "terms": ["MUST"], - "text": "The `[`, `]`, `|`, and space characters, which are used as delimiters for the `deepObject`, `pipeDelimited`, and `spaceDelimited` styles, respectively, all MUST be percent-encoded to comply with [RFC3986]." + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", + "id": "oas-3.0.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 4262, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", - "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For maximum interoperability, it is RECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely." + "line": 1567, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used either with or without the RFC6570-style serialization fields defined in the next section below." }, { - "id": "oas-3.0.reference-object.$ref", + "id": "oas-3.0.encoding-object.common-fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2607, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-ref", - "level": "field", - "terms": [], - "text": "REQUIRED. The reference string." + "line": 1574, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.reference-object.$ref.required", + "id": "oas-3.0.encoding-object.contentType", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2607, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-ref", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 1571, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-content-type", + "level": "field", + "terms": [], + "text": "The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a wildcard media type (e.g. `image/*`). Default value depends on the property type as shown in the table below." }, { - "id": "oas-3.0.reference-object.fixed-fields.shall-object-cannot-extended-additional-properties-any", + "id": "oas-3.0.encoding-object.encoding-multipart-media-types.may-not-currently-possible-correlate-schema-properties", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2609, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "fixed-fields-19", - "level": "MUST", - "terms": ["SHALL"], - "text": "This object cannot be extended with additional properties, and any properties added SHALL be ignored." + "line": 1709, + "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", + "anchor": "encoding-multipart-media-types", + "level": "MAY", + "terms": ["MAY"], + "text": "It is not currently possible to correlate schema properties with unnamed, ordered parts in media types such as `multipart/mixed`, but implementations MAY choose to support such types when `Content-Disposition: form-data` is used with a `name` parameter." }, { - "id": "oas-3.0.relative-references-in-urls.may-unless-specified-otherwise-all-fields-urls", + "id": "oas-3.0.encoding-object.encoding-multipart-media-types.required-contrast-openapi-2-0-schema-define", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 233, - "section": "Specification > Relative References in URLs", - "anchor": "relative-references-in-urls", - "level": "MAY", - "terms": ["MAY"], - "text": "Unless specified otherwise, all fields that are URLs MAY be relative references as defined by RFC3986." + "line": 1703, + "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", + "anchor": "encoding-multipart-media-types", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "In contrast to OpenAPI 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content." }, { - "id": "oas-3.0.relative-references-in-urls.recommended-compatibility-future-versions-specification-ref-process", + "id": "oas-3.0.encoding-object.encoding-the-x-www-form-urlencoded-media-type.must-configuration-means-request-body-encoded-per", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 239, - "section": "Specification > Relative References in URLs", - "anchor": "relative-references-in-urls", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For compatibility with future versions of this specification, the `$ref` process is RECOMMENDED for all of these fields." + "line": 1616, + "section": "Specification > Schema > Encoding Object > Encoding the `x-www-form-urlencoded` Media Type", + "anchor": "encoding-the-x-www-form-urlencoded-media-type", + "level": "MUST", + "terms": ["MUST"], + "text": "This configuration means that the request body MUST be encoded per RFC1866 when passed to the server, after any complex objects have been serialized to a string representation." }, { - "id": "oas-3.0.request-body-object.content", + "id": "oas-3.0.encoding-object.explode", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1336, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-content", + "line": 1595, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", "level": "field", "terms": [], - "text": "REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + "text": "When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.request-body-object.content.required", + "id": "oas-3.0.encoding-object.explode.shall-field-ignored-request-body-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1336, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-content", + "line": 1595, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.request-body-object.description", + "id": "oas-3.0.encoding-object.fixed-fields-for-rfc6570-style-serialization.recommended-however-all-three-style-explode-allowreserved", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1335, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-description", - "level": "field", - "terms": [], - "text": "A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "line": 1606, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "fixed-fields-for-rfc6570-style-serialization", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, if all three of `style`, `explode`, and `allowReserved` fields are absent, it is RECOMMENDED that:" }, { - "id": "oas-3.0.request-body-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.encoding-object.fixed-fields-for-rfc6570-style-serialization.recommended-match-intent-fields-compatible-version-3", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1335, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "line": 1600, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "fixed-fields-for-rfc6570-style-serialization", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "To match the intent of these fields and be compatible with version 3.1 of this specification, it is RECOMMENDED that whenever any of `style`, `explode`, or `allowReserved` are present with an explicit value:" }, { - "id": "oas-3.0.request-body-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.encoding-object.headers", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1339, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "fixed-fields-10", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "line": 1572, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "field", + "terms": [], + "text": "A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the request body media type is not a `multipart`." }, { - "id": "oas-3.0.request-body-object.required", + "id": "oas-3.0.encoding-object.headers.shall-content-type-described-separately-ignored-section", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1337, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-required", - "level": "field", - "terms": [], - "text": "Determines if the request body is required in the request. Defaults to `false`." + "line": 1572, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "`Content-Type` is described separately and SHALL be ignored in this section." }, { - "id": "oas-3.0.resolving-implicit-connections.recommended-consider-all-operation-objects-all-parsed", + "id": "oas-3.0.encoding-object.headers.shall-field-ignored-request-body-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 157, - "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is RECOMMENDED to consider all Operation Objects from all parsed documents when resolving any Link Object `operationId`." + "line": 1572, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not a `multipart`." }, { - "id": "oas-3.0.resolving-implicit-connections.recommended-resolving-component-tag-name-connections-referenced", + "id": "oas-3.0.encoding-object.style", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 165, - "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For resolving component and tag name connections from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + "line": 1594, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "field", + "terms": [], + "text": "Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the `style` field. The behavior follows the same values as `query` parameters, including default values. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.resolving-implicit-connections.recommended-some-cases-unambiguous-uri-based-alternative", + "id": "oas-3.0.encoding-object.style.must-note-initial-used-query-strings-not", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 144, - "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "In some cases, an unambiguous URI-based alternative is available, and OAD authors are RECOMMENDED to always use the alternative:" + "line": 1594, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["MUST"], + "text": "Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually)." }, { - "id": "oas-3.0.response-object.content", + "id": "oas-3.0.encoding-object.style.shall-field-ignored-request-body-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1897, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-content", - "level": "field", - "terms": [], - "text": "A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + "line": 1594, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.response-object.description", + "id": "oas-3.0.example-object.description", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1895, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-description", + "line": 2132, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-description", "level": "field", "terms": [], - "text": "REQUIRED. A description of the response. CommonMark syntax MAY be used for rich text representation." + "text": "Long description for the example. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.response-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.example-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1895, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-description", + "line": 2132, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-description", "level": "MAY", "terms": ["MAY"], "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.response-object.description.required", + "id": "oas-3.0.example-object.externalValue", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1895, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-description", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 2134, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-external-value", + "level": "field", + "terms": [], + "text": "A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving Relative References." }, { - "id": "oas-3.0.response-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.example-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1900, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "fixed-fields-14", + "line": 2136, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.response-object.headers", + "id": "oas-3.0.example-object.fixed-fields.may-tooling-implementations-choose-validate-compatibility-automatically", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1896, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-headers", - "level": "field", - "terms": [], - "text": "Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + "line": 2138, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "MAY", + "terms": ["MAY"], + "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." }, { - "id": "oas-3.0.response-object.headers.shall-response-header-defined-name-content-type", + "id": "oas-3.0.example-object.fixed-fields.should-all-cases-example-value-compatible-schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1896, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-headers", - "level": "MUST", - "terms": ["SHALL"], - "text": "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + "line": 2138, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In all cases, the example value SHOULD be compatible with the schema of its associated value." }, { - "id": "oas-3.0.response-object.links", + "id": "oas-3.0.example-object.summary", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1898, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-links", + "line": 2131, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-summary", "level": "field", "terms": [], - "text": "A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects." + "text": "Short description for the example." }, { - "id": "oas-3.0.responses-object.default", + "id": "oas-3.0.example-object.value", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1832, - "section": "Specification > Schema > Responses Object > Fixed Fields", - "anchor": "responses-default", + "line": 2133, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-value", "level": "field", "terms": [], - "text": "The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A Reference Object can link to a response that the OpenAPI Object's `components.responses` section defines." + "text": "Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary." }, { - "id": "oas-3.0.responses-object.may-default-used-default-response-object-all", + "id": "oas-3.0.example-object.working-with-examples.shall-because-examples-using-fields-represent-final", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1821, - "section": "Specification > Schema > Responses Object", - "anchor": "responses-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object." + "line": 2150, + "section": "Specification > Schema > Example Object > Working with Examples", + "anchor": "working-with-examples", + "level": "MUST", + "terms": ["SHALL"], + "text": "Because examples using these fields represent the final serialized form of the data, they SHALL _override_ any `example` in the corresponding Schema Object." }, { - "id": "oas-3.0.responses-object.must-responses-object-contain-least-one-response", + "id": "oas-3.0.example-object.working-with-examples.should-mutually-exclusive-fields-parameter-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1824, - "section": "Specification > Schema > Responses Object", - "anchor": "responses-object", - "level": "MUST", - "terms": ["MUST", "SHOULD"], - "text": "The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call." + "line": 2150, + "section": "Specification > Schema > Example Object > Working with Examples", + "anchor": "working-with-examples", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The mutually exclusive fields in the Parameter or Media Type Objects are used to show example values which SHOULD both match the schema and be formatted as they would appear as a serialized parameter or within a media type representation." }, { - "id": "oas-3.0.responses-object.pattern-http-status-code", + "id": "oas-3.0.external-documentation-object.description", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1838, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "responses-code", + "line": 1031, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-description", "level": "field", "terms": [], - "text": "Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A Reference Object can link to a response that is defined in the OpenAPI Object's `components.responses` section. This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code." + "text": "A description of the target documentation. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.responses-object.pattern-http-status-code.may-define-range-response-codes-field-contain", + "id": "oas-3.0.external-documentation-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1838, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "responses-code", + "line": 1031, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-description", "level": "MAY", "terms": ["MAY"], - "text": "To define a range of response codes, this field MAY contain the uppercase wildcard character `X`." - }, - { - "id": "oas-3.0.responses-object.pattern-http-status-code.must-field-enclosed-quotation-marks-example-200", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 1838, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "responses-code", - "level": "MUST", - "terms": ["MUST"], - "text": "This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.responses-object.patterned-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.external-documentation-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 1840, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "patterned-fields-0", + "line": 1034, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "fixed-fields-8", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.rich-text-formatting.may-tooling-choose-ignore-some-commonmark-extension", + "id": "oas-3.0.external-documentation-object.url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 225, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", - "level": "MAY", - "terms": ["MAY"], - "text": "Tooling MAY choose to ignore some CommonMark or extension features to address security concerns." + "line": 1032, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The URL for the target documentation. This MUST be in the form of a URL." }, { - "id": "oas-3.0.rich-text-formatting.may-while-framing-commonmark-0-27-minimum", + "id": "oas-3.0.external-documentation-object.url.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 228, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", - "level": "MAY", - "terms": ["MAY"], - "text": "While the framing of CommonMark 0.27 as a minimum requirement means that tooling MAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable." + "line": 1032, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.rich-text-formatting.must-openapi-tooling-renders-rich-text-support", + "id": "oas-3.0.external-documentation-object.url.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 225, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", + "line": 1032, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", "level": "MUST", - "terms": ["MUST"], - "text": "Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27." - }, - { - "id": "oas-3.0.rich-text-formatting.should-openapi-description-authors-consider-how-text", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 228, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "OpenAPI Description authors SHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support." - }, - { - "id": "oas-3.0.schema-object.additionalProperties", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2686, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.schema-object.additionalProperties.must-inline-referenced-schema-schema-object-not", + "id": "oas-3.0.format.must-keys-used-yaml-maps-limited-scalar", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2686, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 118, + "section": "Specification > Format", + "anchor": "format", "level": "MUST", "terms": ["MUST"], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "text": "Keys used in YAML maps MUST be limited to a scalar string, as defined by the YAML Failsafe schema ruleset." }, { - "id": "oas-3.0.schema-object.allOf", + "id": "oas-3.0.format.must-patterned-fields-have-unique-names-within", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2680, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "line": 113, + "section": "Specification > Format", + "anchor": "format", + "level": "MUST", + "terms": ["MUST"], + "text": "Patterned fields MUST have unique names within the containing object." }, { - "id": "oas-3.0.schema-object.allOf.must-inline-referenced-schema-schema-object-not", + "id": "oas-3.0.format.must-tags-limited-allowed-yaml-s-json", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2680, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 117, + "section": "Specification > Format", + "anchor": "format", "level": "MUST", "terms": ["MUST"], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "text": "Tags MUST be limited to those allowed by YAML's JSON schema ruleset, which defines a subset of the YAML syntax and is unrelated to [JSON Schema]." }, { - "id": "oas-3.0.schema-object.anyOf", + "id": "oas-3.0.format.recommended-order-preserve-ability-round-trip-between", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2682, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "line": 115, + "section": "Specification > Format", + "anchor": "format", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with some additional constraints:" }, { - "id": "oas-3.0.schema-object.anyOf.must-inline-referenced-schema-schema-object-not", + "id": "oas-3.0.header-object.common-fixed-fields.may-fields-used-either-content-schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2682, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MUST", - "terms": ["MUST"], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "line": 2481, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used with either `content` or `schema`." }, { - "id": "oas-3.0.schema-object.composition-and-inheritance-polymorphism.must-discriminator-field-required-field", + "id": "oas-3.0.header-object.common-fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2717, - "section": "Specification > Schema > Schema Object > Fixed Fields > Composition and Inheritance (Polymorphism)", - "anchor": "composition-and-inheritance-polymorphism", - "level": "MUST", - "terms": ["MUST"], - "text": "As such, the `discriminator` field MUST be a required field." + "line": 2489, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.schema-object.default", + "id": "oas-3.0.header-object.content", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2689, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 2518, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "header-content", + "level": "field", "terms": [], - "text": "The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined `type` for the Schema Object defined at the same level. For example, if `type` is `\"string\"`, then `default` can be `\"foo\"` but cannot be `1`." + "text": "A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry." }, { - "id": "oas-3.0.schema-object.default.must-unlike-json-schema-value-conform-defined", + "id": "oas-3.0.header-object.content.must-map-only-contain-one-entry", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2689, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 2518, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "header-content", "level": "MUST", "terms": ["MUST"], - "text": "Unlike JSON Schema, the value MUST conform to the defined `type` for the Schema Object defined at the same level." + "text": "The map MUST only contain one entry." }, { - "id": "oas-3.0.schema-object.deprecated", + "id": "oas-3.0.header-object.deprecated", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2708, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-deprecated", + "line": 2487, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-deprecated", "level": "field", "terms": [], - "text": "Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is `false`." }, { - "id": "oas-3.0.schema-object.deprecated.should-specifies-schema-deprecated-transitioned-out-usage", + "id": "oas-3.0.header-object.deprecated.should-specifies-header-deprecated-transitioned-out-usage", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2708, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-deprecated", + "line": 2487, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-deprecated", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Specifies that a schema is deprecated and SHOULD be transitioned out of usage." + "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage." }, { - "id": "oas-3.0.schema-object.description", + "id": "oas-3.0.header-object.description", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2687, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 2485, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-description", + "level": "field", "terms": [], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.schema-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.header-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2687, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 2485, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-description", "level": "MAY", "terms": ["MAY"], "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.schema-object.discriminator", + "id": "oas-3.0.header-object.example", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2702, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-discriminator", + "line": 2506, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-example", "level": "field", "terms": [], - "text": "Adds support for polymorphism. The discriminator is used to determine which of a set of schemas a payload is expected to satisfy. See Composition and Inheritance for more details." + "text": "Example of the header's potential value; see Working With Examples." }, { - "id": "oas-3.0.schema-object.enum", + "id": "oas-3.0.header-object.examples", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2675, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 2507, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-examples", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "Examples of the header's potential value; see Working With Examples." }, { - "id": "oas-3.0.schema-object.example", + "id": "oas-3.0.header-object.explode", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2707, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-example", + "line": 2504, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-explode", "level": "field", "terms": [], - "text": "A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary." + "text": "When this is true, header values of type `array` or `object` generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is `false`." }, { - "id": "oas-3.0.schema-object.exclusiveMaximum", + "id": "oas-3.0.header-object.fixed-fields-for-use-with-content.recommended-using-content-text-plain-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2663, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 2513, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "fixed-fields-for-use-with-content-0", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "Using `content` with a `text/plain` media type is RECOMMENDED for headers where the `schema` strategy is not appropriate." }, { - "id": "oas-3.0.schema-object.exclusiveMinimum", + "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.must-example-examples-provided-conjunction-schema-field", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2665, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 2493, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["MUST"], + "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example MUST follow the prescribed serialization strategy for the header." }, { - "id": "oas-3.0.schema-object.externalDocs", + "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-headers-parameters-name-value", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2706, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this schema." + "line": 2496, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Serializing with `schema` is NOT RECOMMENDED for headers with parameters (name=value pairs following a `;`) in their values, or where values might have non-URL-safe characters; see Appendix D for details." }, { - "id": "oas-3.0.schema-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2710, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "fixed-fields-20", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "line": 2498, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." }, { - "id": "oas-3.0.schema-object.format", + "id": "oas-3.0.header-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2688, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats." + "line": 2498, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the header." }, { - "id": "oas-3.0.schema-object.items", + "id": "oas-3.0.header-object.must-all-traits-affected-location-applicable-location", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2684, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. `items` MUST be present if `type` is `\"array\"`." + "line": 2475, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST"], + "text": "All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`)." }, { - "id": "oas-3.0.schema-object.items.must-inline-referenced-schema-schema-object-not", + "id": "oas-3.0.header-object.must-not-means-allowemptyvalue-allowreserved-used-style-used", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2684, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 2475, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", "level": "MUST", - "terms": ["MUST"], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "terms": ["MUST NOT", "MUST"], + "text": "This means that `allowEmptyValue` and `allowReserved` MUST NOT be used, and `style`, if used, MUST be limited to `\"simple\"`." }, { - "id": "oas-3.0.schema-object.items.must-items-present-type-array", + "id": "oas-3.0.header-object.must-not-name-specified-given-corresponding-headers-map", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2684, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 2473, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", "level": "MUST", - "terms": ["MUST"], - "text": "`items` MUST be present if `type` is `\"array\"`." + "terms": ["MUST NOT"], + "text": "`name` MUST NOT be specified, it is given in the corresponding `headers` map." }, { - "id": "oas-3.0.schema-object.items.must-value-object-not-array", + "id": "oas-3.0.header-object.must-not-specified-implicitly-header", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2684, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 2474, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", "level": "MUST", - "terms": ["MUST"], - "text": "Value MUST be an object and not an array." + "terms": ["MUST NOT"], + "text": "`in` MUST NOT be specified, it is implicitly in `header`." }, { - "id": "oas-3.0.schema-object.json-schema-keywords.may-other-json-schema-subset-fields-following", + "id": "oas-3.0.header-object.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2695, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MAY", - "terms": ["MAY"], - "text": "Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation:" + "line": 2486, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-required", + "level": "field", + "terms": [], + "text": "Determines whether this header is mandatory. The default value is `false`." }, { - "id": "oas-3.0.schema-object.maxItems", + "id": "oas-3.0.header-object.schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2669, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 2505, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-schema", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "The schema defining the type used for the header." }, { - "id": "oas-3.0.schema-object.maxLength", + "id": "oas-3.0.header-object.style", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2666, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 2503, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-style", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "Describes how the header value will be serialized. The default (and only legal value for headers) is `\"simple\"`." }, { - "id": "oas-3.0.schema-object.maxProperties", + "id": "oas-3.0.http-status-codes.should-status-codes-selected-available-status-codes", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2672, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 67, + "section": "Definitions > HTTP Status Codes", + "anchor": "http-status-codes", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Status codes SHOULD be selected from the available status codes registered in the IANA Status Code Registry." }, { - "id": "oas-3.0.schema-object.maximum", + "id": "oas-3.0.info-object.contact", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2662, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 283, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-contact", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "The contact information for the exposed API." }, { - "id": "oas-3.0.schema-object.minItems", + "id": "oas-3.0.info-object.description", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2670, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 281, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-description", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "A description of the API. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.schema-object.minLength", + "id": "oas-3.0.info-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2667, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 281, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.schema-object.minProperties", + "id": "oas-3.0.info-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2673, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 287, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.schema-object.minimum", + "id": "oas-3.0.info-object.license", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2664, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 284, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-license", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "The license information for the exposed API." }, { - "id": "oas-3.0.schema-object.multipleOf", + "id": "oas-3.0.info-object.may-metadata-used-clients-needed-presented-editing", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2661, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 273, + "section": "Specification > Schema > Info Object", + "anchor": "info-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience." }, { - "id": "oas-3.0.schema-object.not", + "id": "oas-3.0.info-object.termsOfService", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2683, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 282, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-terms-of-service", + "level": "field", "terms": [], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "text": "A URL for the Terms of Service for the API. This MUST be in the form of a URL." }, { - "id": "oas-3.0.schema-object.not.must-inline-referenced-schema-schema-object-not", + "id": "oas-3.0.info-object.termsOfService.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2683, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 282, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-terms-of-service", "level": "MUST", "terms": ["MUST"], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.schema-object.nullable", + "id": "oas-3.0.info-object.title", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2701, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-nullable", + "line": 280, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-title", "level": "field", "terms": [], - "text": "This keyword only takes effect if `type` is explicitly defined within the same Schema Object. A `true` value indicates that both `null` values and values of the type specified by `type` are allowed. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`." + "text": "REQUIRED. The title of the API." }, { - "id": "oas-3.0.schema-object.oneOf", + "id": "oas-3.0.info-object.title.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2681, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "line": 280, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-title", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.schema-object.oneOf.must-inline-referenced-schema-schema-object-not", + "id": "oas-3.0.info-object.version", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2681, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MUST", - "terms": ["MUST"], - "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + "line": 285, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-version", + "level": "field", + "terms": [], + "text": "REQUIRED. The version of the OpenAPI Document (which is distinct from the OpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description)." }, { - "id": "oas-3.0.schema-object.pattern", + "id": "oas-3.0.info-object.version.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2668, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect" + "line": 285, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-version", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.schema-object.pattern.should-string-valid-regular-expression-according-ecma", + "id": "oas-3.0.interoperability-with-historical-specifications.should-since-all-rfc1738-compliant-uris-compliant", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2668, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 4233, + "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Historical Specifications", + "anchor": "interoperability-with-historical-specifications", "level": "SHOULD", "terms": ["SHOULD"], - "text": "This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect" + "text": "Since all RFC1738-compliant URIs are compliant with RFC3986, applications needing to ensure historical interoperability SHOULD use RFC1738's rules." }, { - "id": "oas-3.0.schema-object.properties", + "id": "oas-3.0.interoperability-with-web-browser-environments.should-implementations-needing-maximum-compatibility-web-browsers", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2685, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced)." + "line": 4240, + "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", + "anchor": "interoperability-with-web-browser-environments", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Implementations needing maximum compatibility with web browsers SHOULD use WHATWG's `form-urlencoded` percent-encoding rules." }, { - "id": "oas-3.0.schema-object.properties.must-property-definitions-schema-object-not-standard", + "id": "oas-3.0.interoperability-with-web-browser-environments.should-not-however-they-rely-whatwg-s-less", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2685, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MUST", - "terms": ["MUST"], - "text": "Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced)." + "line": 4240, + "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", + "anchor": "interoperability-with-web-browser-environments", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "However, they SHOULD NOT rely on WHATWG's less stringent generic query string rules, as the resulting URLs would fail RFC3986 validation, including JSON Schema's `format: uri` and `format: uri-reference`." }, { - "id": "oas-3.0.schema-object.readOnly", + "id": "oas-3.0.license-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2703, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-read-only", + "line": 364, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "fixed-fields-2", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.0.license-object.name", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 361, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-name", "level": "field", "terms": [], - "text": "Relevant only for Schema Object `properties` definitions. Declares the property as \"read only\". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`." + "text": "REQUIRED. The license name used for the API." }, { - "id": "oas-3.0.schema-object.readOnly.must-not-property-marked-both-readonly-writeonly-being", + "id": "oas-3.0.license-object.name.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2703, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-read-only", + "line": 361, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-name", "level": "MUST", - "terms": ["MUST NOT"], - "text": "A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.schema-object.readOnly.should-not-means-sent-part-response-but-sent", + "id": "oas-3.0.license-object.url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2703, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-read-only", - "level": "SHOULD", - "terms": ["MAY", "SHOULD NOT"], - "text": "This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request." + "line": 362, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-url", + "level": "field", + "terms": [], + "text": "A URL for the license used for the API. This MUST be in the form of a URL." }, { - "id": "oas-3.0.schema-object.required", + "id": "oas-3.0.license-object.url.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2674, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 362, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.schema-object.title", + "id": "oas-3.0.link-object.description", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2660, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "line": 2311, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-description", + "level": "field", "terms": [], - "text": "JSON Schema Keywords" + "text": "A description of the link. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.schema-object.type", + "id": "oas-3.0.link-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2679, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "Value MUST be a string. Multiple types via an array are not supported." + "line": 2311, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.schema-object.type.must-value-string", + "id": "oas-3.0.link-object.examples-2.must-request-parameters-declared-parameters-section-parent", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2679, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", + "line": 2458, + "section": "Specification > Schema > Link Object > Examples", + "anchor": "examples-0", "level": "MUST", "terms": ["MUST"], - "text": "Value MUST be a string." + "text": "Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated." }, { - "id": "oas-3.0.schema-object.uniqueItems", + "id": "oas-3.0.link-object.fixed-fields.may-ambiguous-cases-resulting-behavior-implementation-defined", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2671, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "JSON Schema Keywords" + "line": 2316, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MAY", + "terms": ["MAY"], + "text": "In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error." }, { - "id": "oas-3.0.schema-object.writeOnly", + "id": "oas-3.0.link-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2704, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-write-only", - "level": "field", - "terms": [], - "text": "Relevant only for Schema Object `properties` definitions. Declares the property as \"write only\". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`." + "line": 2314, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.schema-object.writeOnly.must-not-property-marked-both-readonly-writeonly-being", + "id": "oas-3.0.link-object.fixed-fields.must-identified-reference-operation-unique-case-operationid", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2704, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-write-only", + "line": 2316, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", "level": "MUST", - "terms": ["MUST NOT"], - "text": "A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`." + "terms": ["MUST"], + "text": "The identified or reference operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD)." }, { - "id": "oas-3.0.schema-object.writeOnly.should-not-therefore-sent-part-request-but-sent", + "id": "oas-3.0.link-object.fixed-fields.must-linked-operation-identified-using-either-operationref", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2704, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-write-only", + "line": 2316, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MUST", + "terms": ["MUST"], + "text": "A linked operation MUST be identified using either an `operationRef` or `operationId`." + }, + { + "id": "oas-3.0.link-object.fixed-fields.not-recommended-possible-have-ambiguous-parameter-names-e", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2322, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", "level": "SHOULD", - "terms": ["MAY", "SHOULD NOT"], - "text": "Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response." + "terms": ["NOT RECOMMENDED", "SHOULD"], + "text": "It is possible to have ambiguous parameter names, e.g. `name: \"id\", in: \"path\"` and `name: \"path.id\", in: \"query\"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter)." }, { - "id": "oas-3.0.schema-object.xml", + "id": "oas-3.0.link-object.operationId", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2705, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-xml", + "line": 2308, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-id", "level": "field", "terms": [], - "text": "This MAY be used only on property schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property." + "text": "The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field." }, { - "id": "oas-3.0.schema-object.xml.may-used-only-property-schemas", + "id": "oas-3.0.link-object.operationRef", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2705, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-xml", - "level": "MAY", - "terms": ["MAY"], - "text": "This MAY be used only on property schemas." + "line": 2307, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "field", + "terms": [], + "text": "A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." }, { - "id": "oas-3.0.security-filtering.may-path-item-object-empty", + "id": "oas-3.0.link-object.operationRef.must-field-mutually-exclusive-operationid-field-point", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3825, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "The Path Item Object MAY be empty." + "line": 2307, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." }, { - "id": "oas-3.0.security-filtering.may-paths-object-present-but-empty", + "id": "oas-3.0.link-object.operationref-examples.may-references-operationid-possible-operationid-optional-field", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3824, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", + "line": 2394, + "section": "Specification > Schema > Link Object > `operationRef` Examples", + "anchor": "operationref-examples", "level": "MAY", "terms": ["MAY"], - "text": "The Paths Object MAY be present but empty." + "text": "As references to `operationId` MAY NOT be possible (the `operationId` is an optional field in an Operation Object), references MAY also be made through a relative `operationRef`:" }, { - "id": "oas-3.0.security-filtering.may-some-objects-openapi-specification-declared-remain", + "id": "oas-3.0.link-object.parameters", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3817, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation." + "line": 2309, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-parameters", + "level": "field", + "terms": [], + "text": "A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation." }, { - "id": "oas-3.0.security-filtering.may-while-not-part-specification-itself-certain", + "id": "oas-3.0.link-object.requestBody", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3819, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization." + "line": 2310, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-request-body", + "level": "field", + "terms": [], + "text": "A literal value or {expression} to use as a request body when calling the target operation." }, { - "id": "oas-3.0.security-requirement-object.must-name-used-each-property-correspond-security", + "id": "oas-3.0.link-object.server", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3728, - "section": "Specification > Schema > Security Requirement Object", - "anchor": "security-requirement-object", - "level": "MUST", - "terms": ["MUST"], - "text": "The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object." + "line": 2312, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-server", + "level": "field", + "terms": [], + "text": "A server object to be used by the target operation." }, { - "id": "oas-3.0.security-requirement-object.must-security-requirement-object-refer-multiple-security", + "id": "oas-3.0.media-type-object.considerations-for-file-uploads.may-addition-specific-media-types-specified", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3731, - "section": "Specification > Schema > Security Requirement Object", - "anchor": "security-requirement-object", - "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized." + "line": 1526, + "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MAY", + "terms": ["MAY"], + "text": "In addition, specific media types MAY be specified:" }, { - "id": "oas-3.0.security-requirement-object.pattern-name", + "id": "oas-3.0.media-type-object.considerations-for-file-uploads.must-upload-multiple-files-multipart-media-type", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3743, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", - "level": "field", - "terms": [], - "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object. If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty." + "line": 1543, + "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MUST", + "terms": ["MUST"], + "text": "To upload multiple files, a `multipart` media type MUST be used as shown under Example: Multipart Form with Multiple Files." }, { - "id": "oas-3.0.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value", + "id": "oas-3.0.media-type-object.encoding", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3743, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", - "level": "MAY", - "terms": ["MAY"], - "text": "If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope." + "line": 1435, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "field", + "terms": [], + "text": "A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object." }, { - "id": "oas-3.0.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared", + "id": "oas-3.0.media-type-object.encoding.must-key-being-property-name-exist-schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3743, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "line": 1435, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", "level": "MUST", "terms": ["MUST"], - "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object." + "text": "The key, being the property name, MUST exist in the schema as a property." }, { - "id": "oas-3.0.security-requirement-object.pattern-name.must-other-security-scheme-types-array-empty", + "id": "oas-3.0.media-type-object.encoding.shall-encoding-field-only-apply-request-body", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3743, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "line": 1435, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", "level": "MUST", - "terms": ["MUST"], - "text": "For other security scheme types, the array MUST be empty." + "terms": ["SHALL"], + "text": "The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`." }, { - "id": "oas-3.0.security-scheme-object.bearerFormat", + "id": "oas-3.0.media-type-object.example", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3574, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-bearer-format", + "line": 1433, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-example", "level": "field", "terms": [], - "text": "A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes." + "text": "Example of the media type; see Working With Examples." }, { - "id": "oas-3.0.security-scheme-object.description", + "id": "oas-3.0.media-type-object.examples", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3570, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-description", + "line": 1434, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-examples", "level": "field", "terms": [], - "text": "A description for security scheme. CommonMark syntax MAY be used for rich text representation." - }, - { - "id": "oas-3.0.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 3570, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "Examples of the media type; see Working With Examples." }, { - "id": "oas-3.0.security-scheme-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.media-type-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3578, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "fixed-fields-23", + "line": 1437, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "fixed-fields-11", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.security-scheme-object.flows", + "id": "oas-3.0.media-type-object.schema", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3575, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-flows", + "line": 1432, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-schema", "level": "field", "terms": [], - "text": "REQUIRED. An object containing configuration information for the flow types supported." + "text": "The schema defining the content of the request, response, parameter, or header." }, { - "id": "oas-3.0.security-scheme-object.flows.required", + "id": "oas-3.0.media-type-object.shall-example-examples-fields-mutually-exclusive-either", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3575, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-flows", + "line": 1424, + "section": "Specification > Schema > Media Type Object", + "anchor": "media-type-object", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["SHALL"], + "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." }, { - "id": "oas-3.0.security-scheme-object.in", + "id": "oas-3.0.media-type-object.should-example-examples-provided-example-match-specified", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3572, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-in", - "level": "field", - "terms": [], - "text": "REQUIRED. The location of the API key. Valid values are `\"query\"`, `\"header\"`, or `\"cookie\"`." + "line": 1424, + "section": "Specification > Schema > Media Type Object", + "anchor": "media-type-object", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding." }, { - "id": "oas-3.0.security-scheme-object.in.required", + "id": "oas-3.0.media-types.should-media-type-definitions-compliance-rfc6838", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3572, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-in", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 47, + "section": "Definitions > Media Types", + "anchor": "media-types", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The media type definitions SHOULD be in compliance with RFC6838." }, { - "id": "oas-3.0.security-scheme-object.name", + "id": "oas-3.0.non-rfc6570-field-values-and-combinations.may-implementations-create-properly-delimited-uri-template", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3571, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the header, query or cookie parameter to be used." + "line": 3967, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based on `allowReserved`)." }, { - "id": "oas-3.0.security-scheme-object.name.required", + "id": "oas-3.0.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3571, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-name", + "line": 3976, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "A parameter name that includes characters outside of the allowed RFC6570 variable character set MUST be percent-encoded before it can be used in a URI Template." }, { - "id": "oas-3.0.security-scheme-object.openIdConnectUrl", + "id": "oas-3.0.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3576, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-open-id-connect-url", - "level": "field", - "terms": [], - "text": "REQUIRED. Well-known URL to discover the [OpenID-Connect-Discovery] provider metadata." + "line": 3967, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Configurations with no direct RFC6570 equivalent SHOULD also be handled according to RFC6570." }, { - "id": "oas-3.0.security-scheme-object.openIdConnectUrl.required", + "id": "oas-3.0.oauth-flow-object.authorizationUrl", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3576, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-open-id-connect-url", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 3678, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." }, { - "id": "oas-3.0.security-scheme-object.scheme", + "id": "oas-3.0.oauth-flow-object.authorizationUrl.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3573, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry. The value is case-insensitive, as defined in RFC7235." + "line": 3678, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.security-scheme-object.scheme.required", + "id": "oas-3.0.oauth-flow-object.authorizationUrl.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3573, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", + "line": 3678, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", "level": "MUST", "terms": ["REQUIRED"], "text": "REQUIRED." }, { - "id": "oas-3.0.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", + "id": "oas-3.0.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3573, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The values used SHOULD be registered in the IANA Authentication Scheme registry." + "line": 3683, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "fixed-fields-25", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.security-scheme-object.type", + "id": "oas-3.0.oauth-flow-object.refreshUrl", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3569, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-type", + "line": 3680, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-refresh-url", "level": "field", "terms": [], - "text": "REQUIRED. The type of the security scheme. Valid values are `\"apiKey\"`, `\"http\"`, `\"oauth2\"`, `\"openIdConnect\"`." + "text": "The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." }, { - "id": "oas-3.0.security-scheme-object.type.required", + "id": "oas-3.0.oauth-flow-object.refreshUrl.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3569, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-type", + "line": 3680, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-refresh-url", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.server-object.description", + "id": "oas-3.0.oauth-flow-object.scopes", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 389, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-description", + "line": 3681, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", "level": "field", "terms": [], - "text": "An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation." + "text": "REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty." }, { - "id": "oas-3.0.server-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.oauth-flow-object.scopes.may-map-empty", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 389, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-description", + "line": 3681, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "The map MAY be empty." }, { - "id": "oas-3.0.server-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.oauth-flow-object.scopes.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 392, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "fixed-fields-3", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "line": 3681, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.server-object.url", + "id": "oas-3.0.oauth-flow-object.tokenUrl", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 388, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", + "line": 3679, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", "level": "field", "terms": [], - "text": "REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Variable substitutions will be made when a variable is named in `{`braces`}`." + "text": "REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." }, { - "id": "oas-3.0.server-object.url.may-url-supports-server-variables-relative-indicate", + "id": "oas-3.0.oauth-flow-object.tokenUrl.must-form-url", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 388, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", - "level": "MAY", - "terms": ["MAY"], - "text": "This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served." + "line": 3679, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." }, { - "id": "oas-3.0.server-object.url.required", + "id": "oas-3.0.oauth-flow-object.tokenUrl.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 388, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", + "line": 3679, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", "level": "MUST", "terms": ["REQUIRED"], "text": "REQUIRED." }, { - "id": "oas-3.0.server-object.variables", + "id": "oas-3.0.oauth-flows-object.authorizationCode", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 390, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-variables", + "line": 3666, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-authorization-code", "level": "field", "terms": [], - "text": "A map between a variable name and its value. The value is used for substitution in the server's URL template." + "text": "Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0." }, { - "id": "oas-3.0.server-variable-object.default", + "id": "oas-3.0.oauth-flows-object.clientCredentials", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 495, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "line": 3665, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-client-credentials", "level": "field", "terms": [], - "text": "REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the `enum` is defined, the value SHOULD exist in the enum's values. Note that this behavior is different from the Schema Object's `default` keyword, which documents the receiver's behavior rather than inserting the value into the data." + "text": "Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0." }, { - "id": "oas-3.0.server-variable-object.default.required", + "id": "oas-3.0.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 495, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 3668, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "fixed-fields-24", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", + "id": "oas-3.0.oauth-flows-object.implicit", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 495, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", - "level": "MUST", - "terms": ["SHALL"], - "text": "The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied." + "line": 3663, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-implicit", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Implicit flow" }, { - "id": "oas-3.0.server-variable-object.default.should-enum-defined-value-exist-enum-s", + "id": "oas-3.0.oauth-flows-object.password", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 495, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If the `enum` is defined, the value SHOULD exist in the enum's values." + "line": 3664, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-password", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Resource Owner Password flow" }, { - "id": "oas-3.0.server-variable-object.description", + "id": "oas-3.0.openapi-description-structure.may-openapi-description-oad-made-up-single", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 496, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-description", - "level": "field", - "terms": [], - "text": "An optional description for the server variable. CommonMark syntax MAY be used for rich text representation." + "line": 124, + "section": "Specification > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "MAY", + "terms": ["MAY"], + "text": "An OpenAPI Description (OAD) MAY be made up of a single JSON or YAML document or be divided into multiple, connected parts at the discretion of the author." }, { - "id": "oas-3.0.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.openapi-description-structure.recommended-entry-document-oad-named-openapi-json", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 496, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "line": 128, + "section": "Specification > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is RECOMMENDED that the entry document of an OAD be named: `openapi.json` or `openapi.yaml`." }, { - "id": "oas-3.0.server-variable-object.enum", + "id": "oas-3.0.openapi-object.components", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 494, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-enum", + "line": 264, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-components", "level": "field", "terms": [], - "text": "An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty." + "text": "An element to hold various Objects for the OpenAPI Description." }, { - "id": "oas-3.0.server-variable-object.enum.should-not-array-empty", + "id": "oas-3.0.openapi-object.externalDocs", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 494, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-enum", - "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "The array SHOULD NOT be empty." + "line": 267, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation." }, { - "id": "oas-3.0.server-variable-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.openapi-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 498, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "fixed-fields-4", + "line": 269, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "fixed-fields", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.specification-extensions.optional-support-any-one-extension-support-one", + "id": "oas-3.0.openapi-object.info", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3813, - "section": "Specification > Specification Extensions", - "anchor": "specification-extensions", - "level": "MAY", - "terms": ["OPTIONAL"], - "text": "Support for any one extension is OPTIONAL, and support for one extension does not imply support for others." + "line": 261, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "field", + "terms": [], + "text": "REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required." }, { - "id": "oas-3.0.specification-extensions.pattern-x", + "id": "oas-3.0.openapi-object.info.may-metadata-used-tooling-required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3806, - "section": "Specification > Specification Extensions", - "anchor": "info-extensions", - "level": "field", - "terms": [], - "text": "Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be any valid JSON value (`null`, a primitive, an array, or an object.)" + "line": 261, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "MAY", + "terms": ["MAY"], + "text": "The metadata MAY be used by tooling as required." }, { - "id": "oas-3.0.specification-extensions.pattern-x.must-field-name-begin-x-example-x", + "id": "oas-3.0.openapi-object.info.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3806, - "section": "Specification > Specification Extensions", - "anchor": "info-extensions", + "line": 261, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", "level": "MUST", - "terms": ["MUST"], - "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.specification-extensions.recommended-therefore-implementations-designed-extensibility-support-community", + "id": "oas-3.0.openapi-object.openapi", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3810, - "section": "Specification > Specification Extensions", - "anchor": "specification-extensions", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is therefore RECOMMENDED that implementations be designed for extensibility to support community experimentation." + "line": 260, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "field", + "terms": [], + "text": "REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document. This is _not_ related to the API `info.version` string." }, { - "id": "oas-3.0.specification.schema.must-json-schema-differs-section-section-considered", + "id": "oas-3.0.openapi-object.openapi.must-string-version-number-openapi-specification-openapi", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 245, - "section": "Specification > Schema", - "anchor": "schema-0", + "line": 260, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", "level": "MUST", "terms": ["MUST"], - "text": "If the JSON Schema differs from this section, then this section MUST be considered authoritative." + "text": "This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses." }, { - "id": "oas-3.0.specification.schema.required-following-description-field-not-explicitly-described", + "id": "oas-3.0.openapi-object.openapi.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 250, - "section": "Specification > Schema", - "anchor": "schema-0", + "line": 260, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", "level": "MUST", - "terms": ["REQUIRED", "MUST", "SHALL", "OPTIONAL"], - "text": "In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL." - }, - { - "id": "oas-3.0.structural-interoperability.may-same-json-yaml-object-parsed-multiple", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 138, - "section": "Specification > OpenAPI Description Structure > Structural Interoperability", - "anchor": "structural-interoperability", - "level": "MAY", - "terms": ["MAY"], - "text": "If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed as _different_ Object types, the resulting behavior is _implementation defined_, and MAY be treated as an error if detected." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.structural-interoperability.recommended-maximum-interoperability-openapi-description-authors-avoid", + "id": "oas-3.0.openapi-object.openapi.should-openapi-field-used-tooling-interpret-openapi", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 138, - "section": "Specification > OpenAPI Description Structure > Structural Interoperability", - "anchor": "structural-interoperability", + "line": 260, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For maximum interoperability, it is RECOMMENDED that OpenAPI Description authors avoid such scenarios." + "terms": ["SHOULD"], + "text": "The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document." }, { - "id": "oas-3.0.tag-object.description", + "id": "oas-3.0.openapi-object.paths", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2576, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-description", + "line": 263, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-paths", "level": "field", "terms": [], - "text": "A description for the tag. CommonMark syntax MAY be used for rich text representation." + "text": "REQUIRED. The available paths and operations for the API." }, { - "id": "oas-3.0.tag-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.openapi-object.paths.required", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2576, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "line": 263, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-paths", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.0.tag-object.externalDocs", + "id": "oas-3.0.openapi-object.security", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2577, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-external-docs", + "line": 265, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-security", "level": "field", "terms": [], - "text": "Additional external documentation for this tag." - }, - { - "id": "oas-3.0.tag-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.0.4", - "source": "openapi/3.0.4.md", - "line": 2579, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "fixed-fields-18", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array." }, { - "id": "oas-3.0.tag-object.name", + "id": "oas-3.0.openapi-object.servers", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2575, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-name", + "line": 262, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-servers", "level": "field", "terms": [], - "text": "REQUIRED. The name of the tag." + "text": "An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be a Server Object with a url value of `/`." }, { - "id": "oas-3.0.tag-object.name.required", + "id": "oas-3.0.openapi-object.tags", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 2575, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "line": 266, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "field", + "terms": [], + "text": "A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." }, { - "id": "oas-3.0.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", + "id": "oas-3.0.openapi-object.tags.may-tags-not-declared-organized-randomly-based", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 79, - "section": "Definitions > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", + "line": 266, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification." + "text": "The tags that are not declared MAY be organized randomly or based on the tools' logic." }, { - "id": "oas-3.0.undefined-and-implementation-defined-behavior.not-recommended-support-might-produce-correct-outcomes-many", + "id": "oas-3.0.openapi-object.tags.must-each-tag-name-list-unique", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 79, - "section": "Definitions > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "This support might produce correct outcomes in many cases, but relying on it is NOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one." + "line": 266, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "MUST", + "terms": ["MUST"], + "text": "Each tag name in the list MUST be unique." }, { - "id": "oas-3.0.undefined-and-implementation-defined-behavior.recommended-documents-ambiguous-requirements-api-description-authors", + "id": "oas-3.0.operation-object.callbacks", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 84, - "section": "Definitions > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "This documents ambiguous requirements that API description authors are RECOMMENDED to avoid in order to maximize interoperability." + "line": 911, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-callbacks", + "level": "field", + "terms": [], + "text": "A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses." }, { - "id": "oas-3.0.versions.shall-major-minor-portion-version-string-example", + "id": "oas-3.0.operation-object.deprecated", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 92, - "section": "Specification > Versions", - "anchor": "versions", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set." + "line": 912, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-deprecated", + "level": "field", + "terms": [], + "text": "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`." }, { - "id": "oas-3.0.versions.should-not-patch-version-considered-tooling-making-no", + "id": "oas-3.0.operation-object.deprecated.should-consumers-refrain-usage-declared-operation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 92, - "section": "Specification > Versions", - "anchor": "versions", + "line": 912, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-deprecated", "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example." + "terms": ["SHOULD"], + "text": "Consumers SHOULD refrain from usage of the declared operation." }, { - "id": "oas-3.0.versions.should-tooling-supports-oas-3-1-compatible", + "id": "oas-3.0.operation-object.description", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 92, - "section": "Specification > Versions", - "anchor": "versions", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.* versions." + "line": 905, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-description", + "level": "field", + "terms": [], + "text": "A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.working-with-binary-data.may-maxlength-keyword-used-set-expected-upper", + "id": "oas-3.0.operation-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 219, - "section": "Specification > Data Types > Working with Binary Data", - "anchor": "working-with-binary-data", + "line": 905, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-description", "level": "MAY", "terms": ["MAY"], - "text": "The `maxLength` keyword MAY be used to set an expected upper bound on the length of a streaming payload." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.0.xml-object.attribute", + "id": "oas-3.0.operation-object.externalDocs", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3212, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-attribute", + "line": 906, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-external-docs", "level": "field", "terms": [], - "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`." + "text": "Additional external documentation for this operation." }, { - "id": "oas-3.0.xml-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.operation-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3215, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "fixed-fields-22", + "line": 916, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "fixed-fields-7", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.0.xml-object.name", + "id": "oas-3.0.operation-object.operationId", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3209, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-name", + "line": 907, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-id", "level": "field", "terms": [], - "text": "Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `\"array\"` (outside the `items`), it will affect the wrapping element if and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored." + "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." }, { - "id": "oas-3.0.xml-object.namespace", + "id": "oas-3.0.operation-object.operationId.must-id-unique-among-all-operations-described", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3210, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-namespace", - "level": "field", - "terms": [], - "text": "The URI of the namespace definition. Value MUST be in the form of a non-relative URI." + "line": 907, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "MUST", + "terms": ["MUST"], + "text": "The id MUST be unique among all operations described in the API." }, { - "id": "oas-3.0.xml-object.namespace.must-value-form-non-relative-uri", + "id": "oas-3.0.operation-object.operationId.recommended-tools-libraries-use-operationid-uniquely-identify", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3210, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-namespace", - "level": "MUST", - "terms": ["MUST"], - "text": "Value MUST be in the form of a non-relative URI." + "line": 907, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "SHOULD", + "terms": ["MAY", "RECOMMENDED"], + "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." }, { - "id": "oas-3.0.xml-object.prefix", + "id": "oas-3.0.operation-object.parameters", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3211, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-prefix", + "line": 908, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-parameters", "level": "field", "terms": [], - "text": "The prefix to be used for the name." + "text": "A list of parameters that are applicable for this operation. If a parameter is already defined in the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." }, { - "id": "oas-3.0.xml-object.should-using-arrays-xml-element-names-not", + "id": "oas-3.0.operation-object.parameters.must-not-list-include-duplicated-parameters", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3202, - "section": "Specification > Schema > XML Object", - "anchor": "xml-object", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` field SHOULD be used to add that information." + "line": 908, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-parameters", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." }, { - "id": "oas-3.0.xml-object.wrapped", + "id": "oas-3.0.operation-object.requestBody", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3213, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-wrapped", + "line": 909, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-request-body", "level": "field", "terms": [], - "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `\"array\"` (outside the `items`)." + "text": "The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` SHALL be ignored by consumers." }, { - "id": "oas-3.0.xml-object.wrapped.may-used-only-array-definition", + "id": "oas-3.0.operation-object.requestBody.shall-other-cases-http-spec-vague-get", "spec": "openapi", "version": "3.0.4", "source": "openapi/3.0.4.md", - "line": 3213, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-wrapped", - "level": "MAY", - "terms": ["MAY"], - "text": "MAY be used only for an array definition." + "line": 909, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-request-body", + "level": "MUST", + "terms": ["SHALL"], + "text": "In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` SHALL be ignored by consumers." }, { - "id": "oas-3.1.appendix-c-using-rfc6570-based-serialization.may-implementations-specification-use-implementation-rfc6570-perform", + "id": "oas-3.0.operation-object.responses", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4319, - "section": "Appendix C: Using RFC6570-Based Serialization", - "anchor": "appendix-c-using-rfc6570-based-serialization", - "level": "MAY", - "terms": ["MAY"], - "text": "Implementations of this specification MAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 910, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-responses", + "level": "field", + "terms": [], + "text": "REQUIRED. The list of possible responses as they are returned from executing this operation." }, { - "id": "oas-3.1.appendix-e-percent-encoding-and-form-media-types.must-set-characters-encoded-varies-depending-version", + "id": "oas-3.0.operation-object.responses.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4598, - "section": "Appendix E: Percent-Encoding and Form Media Types", - "anchor": "appendix-e-percent-encoding-and-form-media-types", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 910, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-responses", "level": "MUST", - "terms": ["MUST"], - "text": "The set of characters that MUST be encoded varies depending on which version of which specification you use, and (for URIs) in which part of the URI the character appears." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.appendix-f-resolving-security-requirements-in-a-referenced-document.recommended-however-documented-section-tools-resolve-component", + "id": "oas-3.0.operation-object.security", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4786, - "section": "Appendix F: Resolving Security Requirements in a Referenced Document", - "anchor": "appendix-f-resolving-security-requirements-in-a-referenced-document", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, documented in that section, it is RECOMMENDED that tools resolve component names from the entry document." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 913, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-security", + "level": "field", + "terms": [], + "text": "A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." }, { - "id": "oas-3.1.callback-object.pattern-expression", + "id": "oas-3.0.operation-object.servers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2152, - "section": "Specification > Schema > Callback Object > Patterned Fields", - "anchor": "callback-expression", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 914, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-servers", "level": "field", "terms": [], - "text": "A Path Item Object used to define a callback request and expected responses. A complete example is available." + "text": "An alternative `servers` array to service this operation. If a `servers` array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value." }, { - "id": "oas-3.1.callback-object.patterned-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.operation-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2154, - "section": "Specification > Schema > Callback Object > Patterned Fields", - "anchor": "patterned-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 904, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-summary", + "level": "field", + "terms": [], + "text": "A short summary of what the operation does." }, { - "id": "oas-3.1.components-object.callbacks", + "id": "oas-3.0.operation-object.tags", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 588, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-callbacks", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 903, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-tags", "level": "field", "terms": [], - "text": "An object to hold reusable Callback Objects." + "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." }, { - "id": "oas-3.1.components-object.examples", + "id": "oas-3.0.parameter-object.allowEmptyValue", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 583, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-examples", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1084, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", "level": "field", "terms": [], - "text": "An object to hold reusable Example Objects." + "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for `query` parameters. Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." }, { - "id": "oas-3.1.components-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.parameter-object.allowEmptyValue.not-recommended-use-field-likely-removed-later-revision", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 591, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "fixed-fields-5", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1084, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." }, { - "id": "oas-3.1.components-object.fixed-fields.must-all-fixed-fields-declared-above-objects", + "id": "oas-3.0.parameter-object.allowEmptyValue.shall-style-used-behavior-n-cannot-serialized", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 593, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "fixed-fields-5", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1084, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", "level": "MUST", - "terms": ["MUST"], - "text": "All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\\.\\-_]+$`." + "terms": ["SHALL"], + "text": "If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored." }, { - "id": "oas-3.1.components-object.headers", + "id": "oas-3.0.parameter-object.allowEmptyValue.should-true-clients-pass-zero-length-string", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 585, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-headers", - "level": "field", - "terms": [], - "text": "An object to hold reusable Header Objects." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1084, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "SHOULD", + "terms": ["MAY", "SHOULD"], + "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused." }, { - "id": "oas-3.1.components-object.links", + "id": "oas-3.0.parameter-object.allowReserved", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 587, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-links", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1102, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-allow-reserved", "level": "field", "terms": [], - "text": "An object to hold reusable Link Objects." + "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see Appendices C and E for details. This field only applies to parameters with an `in` value of `query`. The default value is `false`." }, { - "id": "oas-3.1.components-object.parameters", + "id": "oas-3.0.parameter-object.common-fixed-fields.may-fields-used-either-content-schema", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 582, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-parameters", - "level": "field", - "terms": [], - "text": "An object to hold reusable Parameter Objects." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1075, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used with either `content` or `schema`." }, { - "id": "oas-3.1.components-object.pathItems", + "id": "oas-3.0.parameter-object.common-fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 589, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-path-items", - "level": "field", - "terms": [], - "text": "An object to hold reusable Path Item Objects." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1086, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.components-object.requestBodies", + "id": "oas-3.0.parameter-object.content", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 584, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-request-bodies", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1116, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "parameter-content", "level": "field", "terms": [], - "text": "An object to hold reusable Request Body Objects." + "text": "A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry." }, { - "id": "oas-3.1.components-object.responses", + "id": "oas-3.0.parameter-object.content.must-map-only-contain-one-entry", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 581, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-responses", - "level": "field", - "terms": [], - "text": "An object to hold reusable Response Objects." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1116, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "parameter-content", + "level": "MUST", + "terms": ["MUST"], + "text": "The map MUST only contain one entry." }, { - "id": "oas-3.1.components-object.schemas", + "id": "oas-3.0.parameter-object.deprecated", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 580, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-schemas", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1083, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-deprecated", "level": "field", "terms": [], - "text": "An object to hold reusable Schema Objects." + "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`." }, { - "id": "oas-3.1.components-object.securitySchemes", + "id": "oas-3.0.parameter-object.deprecated.should-specifies-parameter-deprecated-transitioned-out-usage", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 586, - "section": "Specification > Schema > Components Object > Fixed Fields", - "anchor": "components-security-schemes", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1083, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage." + }, + { + "id": "oas-3.0.parameter-object.description", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1081, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-description", "level": "field", "terms": [], - "text": "An object to hold reusable Security Scheme Objects." + "text": "A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.conditions-for-using-the-discriminator-object.may-avoid-redundancy-discriminator-added-parent-schema", + "id": "oas-3.0.parameter-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3345, - "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1081, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-description", "level": "MAY", "terms": ["MAY"], - "text": "To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas building on the parent schema via an `allOf` construct may be used as an alternate schema." - }, - { - "id": "oas-3.1.conditions-for-using-the-discriminator-object.must-both-oneof-anyof-use-cases-keywords", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3343, - "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", - "level": "MUST", - "terms": ["MUST"], - "text": "In both the `oneOf` and `anyOf` use cases, where those keywords are adjacent to `discriminator`, all possible schemas MUST be listed explicitly." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.contact-object.email", + "id": "oas-3.0.parameter-object.example", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 403, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-email", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1104, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-example", "level": "field", "terms": [], - "text": "The email address of the contact person/organization. This MUST be in the form of an email address." - }, - { - "id": "oas-3.1.contact-object.email.must-form-email-address", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 403, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-email", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of an email address." - }, - { - "id": "oas-3.1.contact-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 405, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "fixed-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Example of the parameter's potential value; see Working With Examples." }, { - "id": "oas-3.1.contact-object.name", + "id": "oas-3.0.parameter-object.examples", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 401, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-name", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1105, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-examples", "level": "field", "terms": [], - "text": "The identifying name of the contact person/organization." + "text": "Examples of the parameter's potential value; see Working With Examples." }, { - "id": "oas-3.1.contact-object.url", + "id": "oas-3.0.parameter-object.explode", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 402, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-url", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1101, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-explode", "level": "field", "terms": [], - "text": "The URI for the contact information. This MUST be in the form of a URI." + "text": "When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined." }, { - "id": "oas-3.1.contact-object.url.must-form-uri", + "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-content.recommended-using-content-text-plain-media-type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 402, - "section": "Specification > Schema > Contact Object > Fixed Fields", - "anchor": "contact-url", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1111, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "fixed-fields-for-use-with-content", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "Using `content` with a `text/plain` media type is RECOMMENDED for `in: \"header\"` and `in: \"cookie\"` parameters where the `schema` strategy is not appropriate." }, { - "id": "oas-3.1.data-type-format.may-tools-do-not-recognize-specific-format", + "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-header-parameters", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 222, - "section": "Specification > Data Types > Data Type Format", - "anchor": "data-type-format", - "level": "MAY", - "terms": ["MAY"], - "text": "Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1096, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Serializing with `schema` is NOT RECOMMENDED for `in: \"cookie\"` parameters, `in: \"header\"` parameters that use HTTP header parameters (name=value pairs following a `;`) in their values, or `in: \"header\"` parameters where values might have non-URL-safe characters; see Appendix D for details." }, { - "id": "oas-3.1.data-type-format.optional-support-any-registered-format-strictly-support", + "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 220, - "section": "Specification > Data Types > Data Type Format", - "anchor": "data-type-format", - "level": "MAY", - "terms": ["OPTIONAL"], - "text": "Support for any registered format is strictly OPTIONAL, and support for one registered format does not imply support for any others." - }, - { - "id": "oas-3.1.discriminator-object.examples.may-discriminator-used-hint-improve-efficiency-selection", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3377, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-0", - "level": "MAY", - "terms": ["MAY"], - "text": "A `discriminator` MAY be used as a \"hint\" to improve the efficiency of selection of the matching schema." - }, - { - "id": "oas-3.1.discriminator-object.examples.may-oas-3-x-response-payload-described", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3367, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-0", - "level": "MAY", - "terms": ["MAY"], - "text": "In OAS 3.x, a response payload MAY be described to be exactly one of any number of types:" - }, - { - "id": "oas-3.1.discriminator-object.examples.may-scenarios-value-discriminator-field-does-not", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3400, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-0", - "level": "MAY", - "terms": ["MAY"], - "text": "In scenarios where the value of the `discriminator` field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used:" + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1092, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." }, { - "id": "oas-3.1.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", + "id": "oas-3.0.parameter-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3416, - "section": "Specification > Schema > Discriminator Object > Examples", - "anchor": "examples-0", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1092, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", "level": "SHOULD", "terms": ["SHOULD"], - "text": "If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail." + "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the parameter." }, { - "id": "oas-3.1.discriminator-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3337, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "fixed-fields-21", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1069, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "fixed-fields-9", + "level": "MUST", + "terms": ["MUST"], + "text": "Parameter Objects MUST include either a `content` field or a `schema` field, but not both." }, { - "id": "oas-3.1.discriminator-object.mapping", + "id": "oas-3.0.parameter-object.in", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3335, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "discriminator-mapping", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1080, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-in", "level": "field", "terms": [], - "text": "An object to hold mappings between payload values and schema names or URI references." + "text": "REQUIRED. The location of the parameter. Possible values are `\"query\"`, `\"header\"`, `\"path\"` or `\"cookie\"`." }, { - "id": "oas-3.1.discriminator-object.must-not-note-discriminator-change-validation-outcome-schema", + "id": "oas-3.0.parameter-object.in.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3328, - "section": "Specification > Schema > Discriminator Object", - "anchor": "discriminator-object", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1080, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-in", "level": "MUST", - "terms": ["MUST NOT"], - "text": "Note that `discriminator` MUST NOT change the validation outcome of the schema." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.discriminator-object.options-for-mapping-values-to-schemas.must-ensure-ambiguous-value-e-g-foo", + "id": "oas-3.0.parameter-object.name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3354, - "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1079, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the parameter. Parameter names are _case sensitive_. If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information. If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored. For all other cases, the `name` corresponds to the parameter name used by the `in` field." + }, + { + "id": "oas-3.0.parameter-object.name.must-path-name-field-correspond-template-expression", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1079, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", "level": "MUST", "terms": ["MUST"], - "text": "To ensure that an ambiguous value (e.g. `\"foo\"`) is treated as a relative URI reference by all implementations, authors MUST prefix it with the `\".\"` path segment (e.g. `\"./foo\"`)." + "text": "If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object." }, { - "id": "oas-3.1.discriminator-object.options-for-mapping-values-to-schemas.must-mapping-keys-string-values-but-tooling", + "id": "oas-3.0.parameter-object.name.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3360, - "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1079, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", "level": "MUST", - "terms": ["MUST", "MAY"], - "text": "Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-both-valid-schema", + "id": "oas-3.0.parameter-object.name.shall-header-name-field-accept-content-type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3354, - "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "The behavior of a `mapping` value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it is RECOMMENDED that it be treated as a schema name." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1079, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "MUST", + "terms": ["SHALL"], + "text": "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored." }, { - "id": "oas-3.1.discriminator-object.propertyName", + "id": "oas-3.0.parameter-object.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3334, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "property-name", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1082, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", "level": "field", "terms": [], - "text": "REQUIRED. The name of the property in the payload that will hold the discriminating value. This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." + "text": "Determines whether this parameter is mandatory. If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`." }, { - "id": "oas-3.1.discriminator-object.propertyName.required", + "id": "oas-3.0.parameter-object.required.may-otherwise-field-included-default-value-false", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3334, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "property-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1082, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", + "level": "MAY", + "terms": ["MAY"], + "text": "Otherwise, the field MAY be included and its default value is `false`." }, { - "id": "oas-3.1.discriminator-object.propertyName.should-property-required-payload-schema-behavior-property", + "id": "oas-3.0.parameter-object.required.required-parameter-location-path-field-value-true", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3334, - "section": "Specification > Schema > Discriminator Object > Fixed Fields", - "anchor": "property-name", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1082, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", + "level": "MUST", + "terms": ["REQUIRED", "MUST"], + "text": "If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`." }, { - "id": "oas-3.1.encoding-object.allowReserved", + "id": "oas-3.0.parameter-object.schema", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1720, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1103, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-schema", "level": "field", "terms": [], - "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see URL Percent-Encoding for details. The default value is `false`. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "text": "The schema defining the type used for the parameter." }, { - "id": "oas-3.1.encoding-object.allowReserved.shall-field-ignored-request-body-media-type", + "id": "oas-3.0.parameter-object.style", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1720, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1100, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-style", + "level": "field", + "terms": [], + "text": "Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"`." }, { - "id": "oas-3.1.encoding-object.allowReserved.shall-value-explicitly-defined-value-contenttype-implicit", + "id": "oas-3.0.parameter-object.style-examples.must-note-prefix-not-appropriate-serializing-application", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1720, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1150, + "section": "Specification > Schema > Parameter Object > Style Examples", + "anchor": "style-examples", "level": "MUST", - "terms": ["SHALL"], - "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "terms": ["MUST"], + "text": "Note that the `?` prefix is not appropriate for serializing `application/x-www-form-urlencoded` HTTP message bodies, and MUST be stripped or (if constructing the string manually) not added when used in that context; see the Encoding Object for more information" }, { - "id": "oas-3.1.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", + "id": "oas-3.0.path-item-object.$ref", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1690, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-0", - "level": "MAY", - "terms": ["MAY"], - "text": "These fields MAY be used either with or without the RFC6570-style serialization fields defined in the next section below." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 795, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-ref", + "level": "field", + "terms": [], + "text": "Allows for a referenced definition of this path item. The value MUST be in the form of a URL, and the referenced structure MUST be in the form of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving Relative References." }, { - "id": "oas-3.1.encoding-object.common-fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.path-item-object.$ref.must-value-form-url-referenced-structure-form", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1697, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-0", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 795, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST be in the form of a URL, and the referenced structure MUST be in the form of a Path Item Object." }, { - "id": "oas-3.1.encoding-object.contentType", + "id": "oas-3.0.path-item-object.delete", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1694, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-content-type", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 801, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-delete", "level": "field", "terms": [], - "text": "The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a wildcard media type (e.g. `image/*`). Default value depends on the property type as shown in the table below." + "text": "A definition of a DELETE operation on this path." }, { - "id": "oas-3.1.encoding-object.encoding-multipart-media-types.may-not-currently-possible-correlate-schema-properties", + "id": "oas-3.0.path-item-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1824, - "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", - "anchor": "encoding-multipart-media-types", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 797, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-description", + "level": "field", + "terms": [], + "text": "An optional string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.path-item-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 797, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-description", "level": "MAY", "terms": ["MAY"], - "text": "It is not currently possible to correlate schema properties with unnamed, ordered parts in media types such as `multipart/mixed`, but implementations MAY choose to support such types when `Content-Disposition: form-data` is used with a `name` parameter." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.encoding-object.encoding-multipart-media-types.not-recommended-because-because-encoding-object-s-contenttype", + "id": "oas-3.0.path-item-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1834, - "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", - "anchor": "encoding-multipart-media-types", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Because of this, and because the Encoding Object's `contentType` defaulting rules do not take the Schema Object's`contentMediaType` into account, the use of `contentMediaType` with an Encoding Object is NOT RECOMMENDED." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 809, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "fixed-fields-6", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.encoding-object.encoding-multipart-media-types.required-contrast-openapi-2-0-schema-define", + "id": "oas-3.0.path-item-object.get", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1818, - "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", - "anchor": "encoding-multipart-media-types", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "In contrast to OpenAPI 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 798, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-get", + "level": "field", + "terms": [], + "text": "A definition of a GET operation on this path." }, { - "id": "oas-3.1.encoding-object.encoding-multipart-media-types.shall-note-stated-working-binary-data-encoding", + "id": "oas-3.0.path-item-object.head", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1834, - "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", - "anchor": "encoding-multipart-media-types", - "level": "MUST", - "terms": ["SHALL"], - "text": "Note that as stated in Working with Binary Data, if the Encoding Object's `contentType`, whether set explicitly or implicitly through its default value rules, disagrees with the `contentMediaType` in a Schema Object, the `contentMediaType` SHALL be ignored." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 803, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-head", + "level": "field", + "terms": [], + "text": "A definition of a HEAD operation on this path." }, { - "id": "oas-3.1.encoding-object.encoding-the-x-www-form-urlencoded-media-type.must-configuration-means-request-body-encoded-per", + "id": "oas-3.0.path-item-object.may-path-item-empty-due-acl-constraints", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1730, - "section": "Specification > Schema > Encoding Object > Encoding the `x-www-form-urlencoded` Media Type", - "anchor": "encoding-the-x-www-form-urlencoded-media-type", - "level": "MUST", - "terms": ["MUST"], - "text": "This configuration means that the request body MUST be encoded per RFC1866 when passed to the server, after any complex objects have been serialized to a string representation." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 787, + "section": "Specification > Schema > Path Item Object", + "anchor": "path-item-object", + "level": "MAY", + "terms": ["MAY"], + "text": "A Path Item MAY be empty, due to ACL constraints." }, { - "id": "oas-3.1.encoding-object.explode", + "id": "oas-3.0.path-item-object.options", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1719, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 802, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-options", "level": "field", "terms": [], - "text": "When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." - }, - { - "id": "oas-3.1.encoding-object.explode.shall-field-ignored-request-body-media-type", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1719, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + "text": "A definition of a OPTIONS operation on this path." }, { - "id": "oas-3.1.encoding-object.explode.shall-value-explicitly-defined-value-contenttype-implicit", + "id": "oas-3.0.path-item-object.parameters", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1719, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", - "level": "MUST", - "terms": ["SHALL"], - "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 807, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-parameters", + "level": "field", + "terms": [], + "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." }, { - "id": "oas-3.1.encoding-object.fixed-fields-for-rfc6570-style-serialization.must-not-using-rfc6570-style-serialization-multipart-form", + "id": "oas-3.0.path-item-object.parameters.must-not-list-include-duplicated-parameters", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1722, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "fixed-fields-for-rfc6570-style-serialization", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 807, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-parameters", "level": "MUST", "terms": ["MUST NOT"], - "text": "When using RFC6570-style serialization for `multipart/form-data`, URI percent-encoding MUST NOT be applied, and the value of `allowReserved` has no effect." + "text": "The list MUST NOT include duplicated parameters." }, { - "id": "oas-3.1.encoding-object.headers", + "id": "oas-3.0.path-item-object.patch", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1695, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 804, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-patch", "level": "field", "terms": [], - "text": "A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the request body media type is not a `multipart`." + "text": "A definition of a PATCH operation on this path." }, { - "id": "oas-3.1.encoding-object.headers.shall-content-type-described-separately-ignored-section", + "id": "oas-3.0.path-item-object.post", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1695, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", - "level": "MUST", - "terms": ["SHALL"], - "text": "`Content-Type` is described separately and SHALL be ignored in this section." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 800, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-post", + "level": "field", + "terms": [], + "text": "A definition of a POST operation on this path." }, { - "id": "oas-3.1.encoding-object.headers.shall-field-ignored-request-body-media-type", + "id": "oas-3.0.path-item-object.put", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1695, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not a `multipart`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 799, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-put", + "level": "field", + "terms": [], + "text": "A definition of a PUT operation on this path." }, { - "id": "oas-3.1.encoding-object.style", + "id": "oas-3.0.path-item-object.servers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1718, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 806, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-servers", "level": "field", "terms": [], - "text": "Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the `style` field. The behavior follows the same values as `query` parameters, including the default value of `\"form\"` which applies only when `contentType` is _not_ being used due to one or both of `explode` or `allowReserved` being explicitly specified. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "text": "An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the OpenAPI Object level, it will be overridden by this value." }, { - "id": "oas-3.1.encoding-object.style.must-note-initial-used-query-strings-not", + "id": "oas-3.0.path-item-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1718, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", - "level": "MUST", - "terms": ["MUST"], - "text": "Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually)." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 796, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-summary", + "level": "field", + "terms": [], + "text": "An optional string summary, intended to apply to all operations in this path." }, { - "id": "oas-3.1.encoding-object.style.shall-field-ignored-request-body-media-type", + "id": "oas-3.0.path-item-object.trace", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1718, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 805, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-trace", + "level": "field", + "terms": [], + "text": "A definition of a TRACE operation on this path." }, { - "id": "oas-3.1.encoding-object.style.shall-value-explicitly-defined-value-contenttype-implicit", + "id": "oas-3.0.path-templating.must-each-template-expression-path-correspond-path", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1718, - "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 43, + "section": "Definitions > Path Templating", + "anchor": "path-templating", "level": "MUST", - "terms": ["SHALL"], - "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "terms": ["MUST"], + "text": "Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations." }, { - "id": "oas-3.1.example-object.description", + "id": "oas-3.0.paths-object.may-paths-object-empty-due-access-control", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2249, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-description", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 709, + "section": "Specification > Schema > Paths Object", + "anchor": "paths-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The Paths Object MAY be empty, due to Access Control List (ACL) constraints." + }, + { + "id": "oas-3.0.paths-object.pattern-path", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 716, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "paths-path", "level": "field", "terms": [], - "text": "Long description for the example. CommonMark syntax MAY be used for rich text representation." + "text": "A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is appended (no relative URL resolution) to the expanded URL from the Server Object's `url` field in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use." }, { - "id": "oas-3.1.example-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.paths-object.pattern-path.must-field-name-begin-forward-slash", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2249, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 716, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with a forward slash (`/`)." }, { - "id": "oas-3.1.example-object.externalValue", + "id": "oas-3.0.paths-object.pattern-path.must-not-templated-paths-same-hierarchy-but-different", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2251, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-external-value", - "level": "field", - "terms": [], - "text": "A URI that identifies the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving Relative References." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 716, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical." }, { - "id": "oas-3.1.example-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.paths-object.patterned-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2253, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 718, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "patterned-fields", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.example-object.fixed-fields.may-tooling-implementations-choose-validate-compatibility-automatically", + "id": "oas-3.0.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2255, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", - "level": "MAY", - "terms": ["MAY"], - "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 4253, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", + "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "level": "MUST", + "terms": ["MUST"], + "text": "The `[`, `]`, `|`, and space characters, which are used as delimiters for the `deepObject`, `pipeDelimited`, and `spaceDelimited` styles, respectively, all MUST be percent-encoded to comply with [RFC3986]." }, { - "id": "oas-3.1.example-object.fixed-fields.should-all-cases-example-value-compatible-schema", + "id": "oas-3.0.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2255, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 4262, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", + "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "In all cases, the example value SHOULD be compatible with the schema of its associated value." + "terms": ["RECOMMENDED"], + "text": "For maximum interoperability, it is RECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely." }, { - "id": "oas-3.1.example-object.summary", + "id": "oas-3.0.reference-object.$ref", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2248, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-summary", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2607, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-ref", "level": "field", "terms": [], - "text": "Short description for the example." + "text": "REQUIRED. The reference string." }, { - "id": "oas-3.1.example-object.value", + "id": "oas-3.0.reference-object.$ref.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2250, - "section": "Specification > Schema > Example Object > Fixed Fields", - "anchor": "example-value", - "level": "field", - "terms": [], - "text": "Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2607, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-ref", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.example-object.working-with-examples.shall-because-examples-using-fields-represent-final", + "id": "oas-3.0.reference-object.fixed-fields.shall-object-cannot-extended-additional-properties-any", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2268, - "section": "Specification > Schema > Example Object > Working with Examples", - "anchor": "working-with-examples", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2609, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "fixed-fields-19", "level": "MUST", "terms": ["SHALL"], - "text": "Because examples using these fields represent the final serialized form of the data, they SHALL _override_ any `example` in the corresponding Schema Object." + "text": "This object cannot be extended with additional properties, and any properties added SHALL be ignored." }, { - "id": "oas-3.1.example-object.working-with-examples.should-mutually-exclusive-fields-parameter-header-media", + "id": "oas-3.0.relative-references-in-urls.may-unless-specified-otherwise-all-fields-urls", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2268, - "section": "Specification > Schema > Example Object > Working with Examples", - "anchor": "working-with-examples", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The mutually exclusive fields in the Parameter, Header, or Media Type Objects are used to show example values which SHOULD both match the schema and be formatted as they would appear as a serialized parameter, serialized header, or within a media type representation." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 233, + "section": "Specification > Relative References in URLs", + "anchor": "relative-references-in-urls", + "level": "MAY", + "terms": ["MAY"], + "text": "Unless specified otherwise, all fields that are URLs MAY be relative references as defined by RFC3986." }, { - "id": "oas-3.1.external-documentation-object.description", + "id": "oas-3.0.relative-references-in-urls.recommended-compatibility-future-versions-specification-ref-process", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1103, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-description", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 239, + "section": "Specification > Relative References in URLs", + "anchor": "relative-references-in-urls", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For compatibility with future versions of this specification, the `$ref` process is RECOMMENDED for all of these fields." + }, + { + "id": "oas-3.0.request-body-object.content", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1336, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-content", "level": "field", "terms": [], - "text": "A description of the target documentation. CommonMark syntax MAY be used for rich text representation." + "text": "REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" }, { - "id": "oas-3.1.external-documentation-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.request-body-object.content.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1103, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-description", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1336, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-content", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.request-body-object.description", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1335, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-description", + "level": "field", + "terms": [], + "text": "A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.request-body-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1335, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-description", "level": "MAY", "terms": ["MAY"], "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.external-documentation-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.request-body-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1106, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "fixed-fields-8", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1339, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "fixed-fields-10", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.external-documentation-object.url", + "id": "oas-3.0.request-body-object.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1104, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1337, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-required", "level": "field", "terms": [], - "text": "REQUIRED. The URI for the target documentation. This MUST be in the form of a URI." + "text": "Determines if the request body is required in the request. Defaults to `false`." }, { - "id": "oas-3.1.external-documentation-object.url.must-form-uri", + "id": "oas-3.0.resolving-implicit-connections.recommended-consider-all-operation-objects-all-parsed", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1104, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 157, + "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is RECOMMENDED to consider all Operation Objects from all parsed documents when resolving any Link Object `operationId`." }, { - "id": "oas-3.1.external-documentation-object.url.required", + "id": "oas-3.0.resolving-implicit-connections.recommended-resolving-component-tag-name-connections-referenced", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1104, - "section": "Specification > Schema > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 165, + "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For resolving component and tag name connections from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." }, { - "id": "oas-3.1.format.must-keys-used-yaml-maps-limited-scalar", + "id": "oas-3.0.resolving-implicit-connections.recommended-some-cases-unambiguous-uri-based-alternative", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 121, - "section": "Specification > Format", - "anchor": "format", - "level": "MUST", - "terms": ["MUST"], - "text": "Keys used in YAML maps MUST be limited to a scalar string, as defined by the YAML Failsafe schema ruleset." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 144, + "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "In some cases, an unambiguous URI-based alternative is available, and OAD authors are RECOMMENDED to always use the alternative:" }, { - "id": "oas-3.1.format.must-patterned-fields-have-unique-names-within", + "id": "oas-3.0.response-object.content", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 116, - "section": "Specification > Format", - "anchor": "format", - "level": "MUST", - "terms": ["MUST"], - "text": "Patterned fields MUST have unique names within the containing object." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1897, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-content", + "level": "field", + "terms": [], + "text": "A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" }, { - "id": "oas-3.1.format.must-tags-limited-allowed-yaml-s-json", + "id": "oas-3.0.response-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 120, - "section": "Specification > Format", - "anchor": "format", - "level": "MUST", - "terms": ["MUST"], - "text": "Tags MUST be limited to those allowed by YAML's JSON schema ruleset, which defines a subset of the YAML syntax and is unrelated to [JSON Schema]." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1895, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "field", + "terms": [], + "text": "REQUIRED. A description of the response. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.format.recommended-order-preserve-ability-round-trip-between", + "id": "oas-3.0.response-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 118, - "section": "Specification > Format", - "anchor": "format", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with some additional constraints:" + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1895, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.header-object.common-fixed-fields.may-fields-used-either-content-schema", + "id": "oas-3.0.response-object.description.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2600, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "These fields MAY be used with either `content` or `schema`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1895, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.header-object.common-fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.response-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2608, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-1", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1900, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "fixed-fields-14", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.header-object.content", + "id": "oas-3.0.response-object.headers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2637, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "header-content", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1896, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-headers", "level": "field", "terms": [], - "text": "A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry." + "text": "Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." }, { - "id": "oas-3.1.header-object.content.must-map-only-contain-one-entry", + "id": "oas-3.0.response-object.headers.shall-response-header-defined-name-content-type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2637, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "header-content", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1896, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-headers", "level": "MUST", - "terms": ["MUST"], - "text": "The map MUST only contain one entry." + "terms": ["SHALL"], + "text": "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." }, { - "id": "oas-3.1.header-object.deprecated", + "id": "oas-3.0.response-object.links", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2606, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-deprecated", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1898, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-links", "level": "field", "terms": [], - "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is `false`." - }, - { - "id": "oas-3.1.header-object.deprecated.should-specifies-header-deprecated-transitioned-out-usage", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2606, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-deprecated", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage." + "text": "A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects." }, { - "id": "oas-3.1.header-object.description", + "id": "oas-3.0.responses-object.default", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2604, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-description", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1832, + "section": "Specification > Schema > Responses Object > Fixed Fields", + "anchor": "responses-default", "level": "field", "terms": [], - "text": "A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "text": "The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A Reference Object can link to a response that the OpenAPI Object's `components.responses` section defines." }, { - "id": "oas-3.1.header-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.responses-object.may-default-used-default-response-object-all", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2604, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-description", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1821, + "section": "Specification > Schema > Responses Object", + "anchor": "responses-object", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object." }, { - "id": "oas-3.1.header-object.example", + "id": "oas-3.0.responses-object.must-responses-object-contain-least-one-response", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2626, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-example", - "level": "field", - "terms": [], - "text": "Example of the header's potential value; see Working With Examples." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1824, + "section": "Specification > Schema > Responses Object", + "anchor": "responses-object", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call." }, { - "id": "oas-3.1.header-object.examples", + "id": "oas-3.0.responses-object.pattern-http-status-code", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2627, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-examples", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1838, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responses-code", "level": "field", "terms": [], - "text": "Examples of the header's potential value; see Working With Examples." + "text": "Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A Reference Object can link to a response that is defined in the OpenAPI Object's `components.responses` section. This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code." }, { - "id": "oas-3.1.header-object.explode", + "id": "oas-3.0.responses-object.pattern-http-status-code.may-define-range-response-codes-field-contain", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2624, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-explode", - "level": "field", - "terms": [], - "text": "When this is true, header values of type `array` or `object` generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is `false`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1838, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responses-code", + "level": "MAY", + "terms": ["MAY"], + "text": "To define a range of response codes, this field MAY contain the uppercase wildcard character `X`." }, { - "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.must-example-examples-provided-conjunction-schema-field", + "id": "oas-3.0.responses-object.pattern-http-status-code.must-field-enclosed-quotation-marks-example-200", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2612, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1838, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responses-code", "level": "MUST", "terms": ["MUST"], - "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example MUST follow the prescribed serialization strategy for the header." + "text": "This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML." }, { - "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", + "id": "oas-3.0.responses-object.patterned-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2615, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", - "level": "MUST", - "terms": ["MUST"], - "text": "Implementations MUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; see Appendix D for guidance on quoting and escaping." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 1840, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "patterned-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.must-not-serializing-headers-schema-uri-percent-encoding", + "id": "oas-3.0.rich-text-formatting.may-tooling-choose-ignore-some-commonmark-extension", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2615, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", - "level": "MUST", - "terms": ["MUST NOT", "MUST"], - "text": "When serializing headers with `schema`, URI percent-encoding MUST NOT be applied; if using an RFC6570 implementation that automatically applies it, it MUST be removed before use." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 225, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "MAY", + "terms": ["MAY"], + "text": "Tooling MAY choose to ignore some CommonMark or extension features to address security concerns." }, { - "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", + "id": "oas-3.0.rich-text-formatting.may-while-framing-commonmark-0-27-minimum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2618, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 228, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "MAY", + "terms": ["MAY"], + "text": "While the framing of CommonMark 0.27 as a minimum requirement means that tooling MAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable." + }, + { + "id": "oas-3.0.rich-text-formatting.must-openapi-tooling-renders-rich-text-support", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 225, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", "level": "MUST", - "terms": ["SHALL"], - "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + "terms": ["MUST"], + "text": "Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27." }, { - "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", + "id": "oas-3.0.rich-text-formatting.should-openapi-description-authors-consider-how-text", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2618, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 228, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", "level": "SHOULD", "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the header." + "text": "OpenAPI Description authors SHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support." }, { - "id": "oas-3.1.header-object.must-all-traits-affected-location-applicable-location", + "id": "oas-3.0.schema-object.additionalProperties", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2594, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2686, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`." + }, + { + "id": "oas-3.0.schema-object.additionalProperties.must-inline-referenced-schema-schema-object-not", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2686, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "MUST", "terms": ["MUST"], - "text": "All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`)." + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.header-object.must-not-means-allowemptyvalue-allowreserved-used-style-used", + "id": "oas-3.0.schema-object.allOf", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2594, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", - "level": "MUST", - "terms": ["MUST NOT", "MUST"], - "text": "This means that `allowEmptyValue` and `allowReserved` MUST NOT be used, and `style`, if used, MUST be limited to `\"simple\"`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2680, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.header-object.must-not-name-specified-given-corresponding-headers-map", + "id": "oas-3.0.schema-object.allOf.must-inline-referenced-schema-schema-object-not", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2592, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2680, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "MUST", - "terms": ["MUST NOT"], - "text": "`name` MUST NOT be specified, it is given in the corresponding `headers` map." + "terms": ["MUST"], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.header-object.must-not-specified-implicitly-header", + "id": "oas-3.0.schema-object.anyOf", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2593, - "section": "Specification > Schema > Header Object", - "anchor": "header-object", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "`in` MUST NOT be specified, it is implicitly in `header`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2682, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.header-object.required", + "id": "oas-3.0.schema-object.anyOf.must-inline-referenced-schema-schema-object-not", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2605, - "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-required", - "level": "field", - "terms": [], - "text": "Determines whether this header is mandatory. The default value is `false`." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2682, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.header-object.schema", + "id": "oas-3.0.schema-object.composition-and-inheritance-polymorphism.must-discriminator-field-required-field", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2625, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-schema", - "level": "field", - "terms": [], - "text": "The schema defining the type used for the header." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2717, + "section": "Specification > Schema > Schema Object > Fixed Fields > Composition and Inheritance (Polymorphism)", + "anchor": "composition-and-inheritance-polymorphism", + "level": "MUST", + "terms": ["MUST"], + "text": "As such, the `discriminator` field MUST be a required field." }, { - "id": "oas-3.1.header-object.style", + "id": "oas-3.0.schema-object.default", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2623, - "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-style", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2689, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "Describes how the header value will be serialized. The default (and only legal value for headers) is `\"simple\"`." + "text": "The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined `type` for the Schema Object defined at the same level. For example, if `type` is `\"string\"`, then `default` can be `\"foo\"` but cannot be `1`." }, { - "id": "oas-3.1.http-status-codes.should-status-codes-selected-available-status-codes", + "id": "oas-3.0.schema-object.default.must-unlike-json-schema-value-conform-defined", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 70, - "section": "Definitions > HTTP Status Codes", - "anchor": "http-status-codes", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Status codes SHOULD be selected from the available status codes registered in the IANA Status Code Registry." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2689, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "Unlike JSON Schema, the value MUST conform to the defined `type` for the Schema Object defined at the same level." }, { - "id": "oas-3.1.info-object.contact", + "id": "oas-3.0.schema-object.deprecated", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 351, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-contact", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2708, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-deprecated", "level": "field", "terms": [], - "text": "The contact information for the exposed API." + "text": "Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`." }, { - "id": "oas-3.1.info-object.description", + "id": "oas-3.0.schema-object.deprecated.should-specifies-schema-deprecated-transitioned-out-usage", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 349, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-description", - "level": "field", - "terms": [], - "text": "A description of the API. CommonMark syntax MAY be used for rich text representation." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2708, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifies that a schema is deprecated and SHOULD be transitioned out of usage." }, { - "id": "oas-3.1.info-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.schema-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 349, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-description", - "level": "MAY", - "terms": ["MAY"], + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2687, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.info-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.schema-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 355, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "fixed-fields-0", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2687, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.info-object.license", + "id": "oas-3.0.schema-object.discriminator", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 352, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-license", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2702, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-discriminator", "level": "field", "terms": [], - "text": "The license information for the exposed API." + "text": "Adds support for polymorphism. The discriminator is used to determine which of a set of schemas a payload is expected to satisfy. See Composition and Inheritance for more details." }, { - "id": "oas-3.1.info-object.may-metadata-used-clients-needed-presented-editing", + "id": "oas-3.0.schema-object.enum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 340, - "section": "Specification > Schema > Info Object", - "anchor": "info-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2675, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.info-object.summary", + "id": "oas-3.0.schema-object.example", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 348, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-summary", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2707, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-example", "level": "field", "terms": [], - "text": "A short summary of the API." + "text": "A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary." }, { - "id": "oas-3.1.info-object.termsOfService", + "id": "oas-3.0.schema-object.exclusiveMaximum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 350, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-terms-of-service", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2663, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "A URI for the Terms of Service for the API. This MUST be in the form of a URI." + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.info-object.termsOfService.must-form-uri", + "id": "oas-3.0.schema-object.exclusiveMinimum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 350, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-terms-of-service", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2665, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.info-object.title", + "id": "oas-3.0.schema-object.externalDocs", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 347, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-title", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2706, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-external-docs", "level": "field", "terms": [], - "text": "REQUIRED. The title of the API." + "text": "Additional external documentation for this schema." }, { - "id": "oas-3.1.info-object.title.required", + "id": "oas-3.0.schema-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 347, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-title", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2710, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "fixed-fields-20", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.info-object.version", + "id": "oas-3.0.schema-object.format", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 353, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-version", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2688, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "REQUIRED. The version of the OpenAPI Document (which is distinct from the OpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description)." + "text": "See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats." }, { - "id": "oas-3.1.info-object.version.required", + "id": "oas-3.0.schema-object.items", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 353, - "section": "Specification > Schema > Info Object > Fixed Fields", - "anchor": "info-version", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2684, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. `items` MUST be present if `type` is `\"array\"`." }, { - "id": "oas-3.1.interoperability-with-historical-specifications.should-since-all-rfc1738-compliant-uris-compliant", + "id": "oas-3.0.schema-object.items.must-inline-referenced-schema-schema-object-not", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4657, - "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Historical Specifications", - "anchor": "interoperability-with-historical-specifications", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Since all RFC1738-compliant URIs are compliant with RFC3986, applications needing to ensure historical interoperability SHOULD use RFC1738's rules." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2684, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.interoperability-with-web-browser-environments.should-implementations-needing-maximum-compatibility-web-browsers", + "id": "oas-3.0.schema-object.items.must-items-present-type-array", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4664, - "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", - "anchor": "interoperability-with-web-browser-environments", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Implementations needing maximum compatibility with web browsers SHOULD use WHATWG's `form-urlencoded` percent-encoding rules." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2684, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "`items` MUST be present if `type` is `\"array\"`." }, { - "id": "oas-3.1.interoperability-with-web-browser-environments.should-not-however-they-rely-whatwg-s-less", + "id": "oas-3.0.schema-object.items.must-value-object-not-array", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4664, - "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", - "anchor": "interoperability-with-web-browser-environments", - "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "However, they SHOULD NOT rely on WHATWG's less stringent generic query string rules, as the resulting URLs would fail RFC3986 validation, including JSON Schema's `format: uri` and `format: uri-reference` (when `format` validation is endabled)." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2684, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be an object and not an array." }, { - "id": "oas-3.1.license-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.schema-object.json-schema-keywords.may-other-json-schema-subset-fields-following", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 435, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "fixed-fields-2", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2695, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation:" }, { - "id": "oas-3.1.license-object.identifier", + "id": "oas-3.0.schema-object.maxItems", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 432, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-identifier", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2669, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "An SPDX license expression for the API. The `identifier` field is mutually exclusive of the `url` field." + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.license-object.name", + "id": "oas-3.0.schema-object.maxLength", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 431, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-name", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2666, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "REQUIRED. The license name used for the API." + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.license-object.name.required", + "id": "oas-3.0.schema-object.maxProperties", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 431, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2672, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.license-object.url", + "id": "oas-3.0.schema-object.maximum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 433, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-url", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2662, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "A URI for the license used for the API. This MUST be in the form of a URI. The `url` field is mutually exclusive of the `identifier` field." + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.license-object.url.must-form-uri", + "id": "oas-3.0.schema-object.minItems", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 433, - "section": "Specification > Schema > License Object > Fixed Fields", - "anchor": "license-url", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2670, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.link-object.description", + "id": "oas-3.0.schema-object.minLength", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2429, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-description", - "level": "field", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2667, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "A description of the link. CommonMark syntax MAY be used for rich text representation." + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.link-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.0.schema-object.minProperties", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2429, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2673, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.link-object.example-expressions.must-request-parameters-declared-parameters-section-parent", + "id": "oas-3.0.schema-object.minimum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2577, - "section": "Specification > Schema > Link Object > Runtime Expressions > Example Expressions", - "anchor": "example-expressions", - "level": "MUST", - "terms": ["MUST"], - "text": "Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2664, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.link-object.fixed-fields.may-ambiguous-cases-resulting-behavior-implementation-defined", + "id": "oas-3.0.schema-object.multipleOf", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2434, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MAY", - "terms": ["MAY"], - "text": "In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2661, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" }, { - "id": "oas-3.1.link-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.0.schema-object.not", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2432, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2683, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.link-object.fixed-fields.must-identified-referenced-operation-unique-case-operationid", + "id": "oas-3.0.schema-object.not.must-inline-referenced-schema-schema-object-not", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2434, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2683, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "MUST", "terms": ["MUST"], - "text": "The identified or referenced operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD)." + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.link-object.fixed-fields.must-linked-operation-identified-using-either-operationref", + "id": "oas-3.0.schema-object.nullable", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2434, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2701, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-nullable", + "level": "field", + "terms": [], + "text": "This keyword only takes effect if `type` is explicitly defined within the same Schema Object. A `true` value indicates that both `null` values and values of the type specified by `type` are allowed. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`." + }, + { + "id": "oas-3.0.schema-object.oneOf", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2681, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." + }, + { + "id": "oas-3.0.schema-object.oneOf.must-inline-referenced-schema-schema-object-not", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2681, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "MUST", "terms": ["MUST"], - "text": "A linked operation MUST be identified using either an `operationRef` or `operationId`." + "text": "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema." }, { - "id": "oas-3.1.link-object.fixed-fields.not-recommended-possible-have-ambiguous-parameter-names-e", + "id": "oas-3.0.schema-object.pattern", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2440, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2668, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect" + }, + { + "id": "oas-3.0.schema-object.pattern.should-string-valid-regular-expression-according-ecma", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2668, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", "level": "SHOULD", - "terms": ["NOT RECOMMENDED", "SHOULD"], - "text": "It is possible to have ambiguous parameter names, e.g. `name: \"id\", in: \"path\"` and `name: \"path.id\", in: \"query\"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter)." + "terms": ["SHOULD"], + "text": "This string SHOULD be a valid regular expression, according to the Ecma-262 Edition 5.1 regular expression dialect" }, { - "id": "oas-3.1.link-object.operationId", + "id": "oas-3.0.schema-object.properties", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2426, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-id", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2685, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced)." + }, + { + "id": "oas-3.0.schema-object.properties.must-property-definitions-schema-object-not-standard", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2685, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced)." + }, + { + "id": "oas-3.0.schema-object.readOnly", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2703, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-read-only", "level": "field", "terms": [], - "text": "The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field." + "text": "Relevant only for Schema Object `properties` definitions. Declares the property as \"read only\". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`." }, { - "id": "oas-3.1.link-object.operationRef", + "id": "oas-3.0.schema-object.readOnly.must-not-property-marked-both-readonly-writeonly-being", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2425, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-ref", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2703, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-read-only", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`." + }, + { + "id": "oas-3.0.schema-object.readOnly.should-not-means-sent-part-response-but-sent", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2703, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-read-only", + "level": "SHOULD", + "terms": ["MAY", "SHOULD NOT"], + "text": "This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request." + }, + { + "id": "oas-3.0.schema-object.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2674, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" + }, + { + "id": "oas-3.0.schema-object.title", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2660, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" + }, + { + "id": "oas-3.0.schema-object.type", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2679, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "Value MUST be a string. Multiple types via an array are not supported." + }, + { + "id": "oas-3.0.schema-object.type.must-value-string", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2679, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be a string." + }, + { + "id": "oas-3.0.schema-object.uniqueItems", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2671, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "JSON Schema Keywords" + }, + { + "id": "oas-3.0.schema-object.writeOnly", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2704, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-write-only", + "level": "field", + "terms": [], + "text": "Relevant only for Schema Object `properties` definitions. Declares the property as \"write only\". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`." + }, + { + "id": "oas-3.0.schema-object.writeOnly.must-not-property-marked-both-readonly-writeonly-being", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2704, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-write-only", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`." + }, + { + "id": "oas-3.0.schema-object.writeOnly.should-not-therefore-sent-part-request-but-sent", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2704, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-write-only", + "level": "SHOULD", + "terms": ["MAY", "SHOULD NOT"], + "text": "Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response." + }, + { + "id": "oas-3.0.schema-object.xml", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2705, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-xml", + "level": "field", + "terms": [], + "text": "This MAY be used only on property schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property." + }, + { + "id": "oas-3.0.schema-object.xml.may-used-only-property-schemas", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2705, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-xml", + "level": "MAY", + "terms": ["MAY"], + "text": "This MAY be used only on property schemas." + }, + { + "id": "oas-3.0.security-filtering.may-path-item-object-empty", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3825, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "The Path Item Object MAY be empty." + }, + { + "id": "oas-3.0.security-filtering.may-paths-object-present-but-empty", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3824, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "The Paths Object MAY be present but empty." + }, + { + "id": "oas-3.0.security-filtering.may-some-objects-openapi-specification-declared-remain", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3817, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation." + }, + { + "id": "oas-3.0.security-filtering.may-while-not-part-specification-itself-certain", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3819, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization." + }, + { + "id": "oas-3.0.security-requirement-object.must-name-used-each-property-correspond-security", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3728, + "section": "Specification > Schema > Security Requirement Object", + "anchor": "security-requirement-object", + "level": "MUST", + "terms": ["MUST"], + "text": "The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object." + }, + { + "id": "oas-3.0.security-requirement-object.must-security-requirement-object-refer-multiple-security", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3731, + "section": "Specification > Schema > Security Requirement Object", + "anchor": "security-requirement-object", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized." + }, + { + "id": "oas-3.0.security-requirement-object.pattern-name", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3743, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "field", + "terms": [], + "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object. If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty." + }, + { + "id": "oas-3.0.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3743, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MAY", + "terms": ["MAY"], + "text": "If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope." + }, + { + "id": "oas-3.0.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3743, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MUST", + "terms": ["MUST"], + "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object." + }, + { + "id": "oas-3.0.security-requirement-object.pattern-name.must-other-security-scheme-types-array-empty", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3743, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MUST", + "terms": ["MUST"], + "text": "For other security scheme types, the array MUST be empty." + }, + { + "id": "oas-3.0.security-scheme-object.bearerFormat", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3574, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-bearer-format", + "level": "field", + "terms": [], + "text": "A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes." + }, + { + "id": "oas-3.0.security-scheme-object.description", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3570, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-description", + "level": "field", + "terms": [], + "text": "A description for security scheme. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3570, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.security-scheme-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3578, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "fixed-fields-23", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.0.security-scheme-object.flows", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3575, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-flows", + "level": "field", + "terms": [], + "text": "REQUIRED. An object containing configuration information for the flow types supported." + }, + { + "id": "oas-3.0.security-scheme-object.flows.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3575, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-flows", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.security-scheme-object.in", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3572, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-in", + "level": "field", + "terms": [], + "text": "REQUIRED. The location of the API key. Valid values are `\"query\"`, `\"header\"`, or `\"cookie\"`." + }, + { + "id": "oas-3.0.security-scheme-object.in.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3572, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-in", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.security-scheme-object.name", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3571, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the header, query or cookie parameter to be used." + }, + { + "id": "oas-3.0.security-scheme-object.name.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3571, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.security-scheme-object.openIdConnectUrl", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3576, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-open-id-connect-url", + "level": "field", + "terms": [], + "text": "REQUIRED. Well-known URL to discover the [OpenID-Connect-Discovery] provider metadata." + }, + { + "id": "oas-3.0.security-scheme-object.openIdConnectUrl.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3576, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-open-id-connect-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.security-scheme-object.scheme", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3573, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry. The value is case-insensitive, as defined in RFC7235." + }, + { + "id": "oas-3.0.security-scheme-object.scheme.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3573, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3573, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The values used SHOULD be registered in the IANA Authentication Scheme registry." + }, + { + "id": "oas-3.0.security-scheme-object.type", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3569, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-type", + "level": "field", + "terms": [], + "text": "REQUIRED. The type of the security scheme. Valid values are `\"apiKey\"`, `\"http\"`, `\"oauth2\"`, `\"openIdConnect\"`." + }, + { + "id": "oas-3.0.security-scheme-object.type.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3569, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-type", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.server-object.description", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 389, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-description", + "level": "field", + "terms": [], + "text": "An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.server-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 389, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.server-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 392, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "fixed-fields-3", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.0.server-object.url", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 388, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "field", + "terms": [], + "text": "REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Variable substitutions will be made when a variable is named in `{`braces`}`." + }, + { + "id": "oas-3.0.server-object.url.may-url-supports-server-variables-relative-indicate", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 388, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "MAY", + "terms": ["MAY"], + "text": "This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served." + }, + { + "id": "oas-3.0.server-object.url.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 388, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.server-object.variables", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 390, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-variables", + "level": "field", + "terms": [], + "text": "A map between a variable name and its value. The value is used for substitution in the server's URL template." + }, + { + "id": "oas-3.0.server-variable-object.default", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 495, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "field", + "terms": [], + "text": "REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the `enum` is defined, the value SHOULD exist in the enum's values. Note that this behavior is different from the Schema Object's `default` keyword, which documents the receiver's behavior rather than inserting the value into the data." + }, + { + "id": "oas-3.0.server-variable-object.default.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 495, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 495, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["SHALL"], + "text": "The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied." + }, + { + "id": "oas-3.0.server-variable-object.default.should-enum-defined-value-exist-enum-s", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 495, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the `enum` is defined, the value SHOULD exist in the enum's values." + }, + { + "id": "oas-3.0.server-variable-object.description", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 496, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-description", + "level": "field", + "terms": [], + "text": "An optional description for the server variable. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 496, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.server-variable-object.enum", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 494, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-enum", + "level": "field", + "terms": [], + "text": "An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty." + }, + { + "id": "oas-3.0.server-variable-object.enum.should-not-array-empty", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 494, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-enum", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The array SHOULD NOT be empty." + }, + { + "id": "oas-3.0.server-variable-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 498, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "fixed-fields-4", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.0.specification-extensions.optional-support-any-one-extension-support-one", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3813, + "section": "Specification > Specification Extensions", + "anchor": "specification-extensions", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Support for any one extension is OPTIONAL, and support for one extension does not imply support for others." + }, + { + "id": "oas-3.0.specification-extensions.pattern-x", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3806, + "section": "Specification > Specification Extensions", + "anchor": "info-extensions", + "level": "field", + "terms": [], + "text": "Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be any valid JSON value (`null`, a primitive, an array, or an object.)" + }, + { + "id": "oas-3.0.specification-extensions.pattern-x.must-field-name-begin-x-example-x", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3806, + "section": "Specification > Specification Extensions", + "anchor": "info-extensions", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + }, + { + "id": "oas-3.0.specification-extensions.recommended-therefore-implementations-designed-extensibility-support-community", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3810, + "section": "Specification > Specification Extensions", + "anchor": "specification-extensions", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is therefore RECOMMENDED that implementations be designed for extensibility to support community experimentation." + }, + { + "id": "oas-3.0.specification.schema.must-json-schema-differs-section-section-considered", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 245, + "section": "Specification > Schema", + "anchor": "schema-0", + "level": "MUST", + "terms": ["MUST"], + "text": "If the JSON Schema differs from this section, then this section MUST be considered authoritative." + }, + { + "id": "oas-3.0.specification.schema.required-following-description-field-not-explicitly-described", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 250, + "section": "Specification > Schema", + "anchor": "schema-0", + "level": "MUST", + "terms": ["REQUIRED", "MUST", "SHALL", "OPTIONAL"], + "text": "In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL." + }, + { + "id": "oas-3.0.structural-interoperability.may-same-json-yaml-object-parsed-multiple", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 138, + "section": "Specification > OpenAPI Description Structure > Structural Interoperability", + "anchor": "structural-interoperability", + "level": "MAY", + "terms": ["MAY"], + "text": "If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed as _different_ Object types, the resulting behavior is _implementation defined_, and MAY be treated as an error if detected." + }, + { + "id": "oas-3.0.structural-interoperability.recommended-maximum-interoperability-openapi-description-authors-avoid", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 138, + "section": "Specification > OpenAPI Description Structure > Structural Interoperability", + "anchor": "structural-interoperability", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For maximum interoperability, it is RECOMMENDED that OpenAPI Description authors avoid such scenarios." + }, + { + "id": "oas-3.0.tag-object.description", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2576, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-description", + "level": "field", + "terms": [], + "text": "A description for the tag. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.tag-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2576, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.0.tag-object.externalDocs", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2577, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this tag." + }, + { + "id": "oas-3.0.tag-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2579, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "fixed-fields-18", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.0.tag-object.name", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2575, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the tag." + }, + { + "id": "oas-3.0.tag-object.name.required", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 2575, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.0.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 79, + "section": "Definitions > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification." + }, + { + "id": "oas-3.0.undefined-and-implementation-defined-behavior.not-recommended-support-might-produce-correct-outcomes-many", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 79, + "section": "Definitions > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "This support might produce correct outcomes in many cases, but relying on it is NOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one." + }, + { + "id": "oas-3.0.undefined-and-implementation-defined-behavior.recommended-documents-ambiguous-requirements-api-description-authors", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 84, + "section": "Definitions > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "This documents ambiguous requirements that API description authors are RECOMMENDED to avoid in order to maximize interoperability." + }, + { + "id": "oas-3.0.versions.shall-major-minor-portion-version-string-example", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 92, + "section": "Specification > Versions", + "anchor": "versions", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set." + }, + { + "id": "oas-3.0.versions.should-not-patch-version-considered-tooling-making-no", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 92, + "section": "Specification > Versions", + "anchor": "versions", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example." + }, + { + "id": "oas-3.0.versions.should-tooling-supports-oas-3-1-compatible", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 92, + "section": "Specification > Versions", + "anchor": "versions", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.* versions." + }, + { + "id": "oas-3.0.working-with-binary-data.may-maxlength-keyword-used-set-expected-upper", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 219, + "section": "Specification > Data Types > Working with Binary Data", + "anchor": "working-with-binary-data", + "level": "MAY", + "terms": ["MAY"], + "text": "The `maxLength` keyword MAY be used to set an expected upper bound on the length of a streaming payload." + }, + { + "id": "oas-3.0.xml-object.attribute", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3212, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-attribute", + "level": "field", + "terms": [], + "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`." + }, + { + "id": "oas-3.0.xml-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3215, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "fixed-fields-22", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.0.xml-object.name", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3209, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-name", + "level": "field", + "terms": [], + "text": "Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `\"array\"` (outside the `items`), it will affect the wrapping element if and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored." + }, + { + "id": "oas-3.0.xml-object.namespace", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3210, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-namespace", + "level": "field", + "terms": [], + "text": "The URI of the namespace definition. Value MUST be in the form of a non-relative URI." + }, + { + "id": "oas-3.0.xml-object.namespace.must-value-form-non-relative-uri", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3210, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-namespace", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be in the form of a non-relative URI." + }, + { + "id": "oas-3.0.xml-object.prefix", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3211, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-prefix", + "level": "field", + "terms": [], + "text": "The prefix to be used for the name." + }, + { + "id": "oas-3.0.xml-object.should-using-arrays-xml-element-names-not", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3202, + "section": "Specification > Schema > XML Object", + "anchor": "xml-object", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` field SHOULD be used to add that information." + }, + { + "id": "oas-3.0.xml-object.wrapped", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3213, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-wrapped", + "level": "field", + "terms": [], + "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `\"array\"` (outside the `items`)." + }, + { + "id": "oas-3.0.xml-object.wrapped.may-used-only-array-definition", + "spec": "openapi", + "version": "3.0.4", + "source": "openapi/3.0.4.md", + "line": 3213, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-wrapped", + "level": "MAY", + "terms": ["MAY"], + "text": "MAY be used only for an array definition." + }, + { + "id": "oas-3.1.appendix-c-using-rfc6570-based-serialization.may-implementations-specification-use-implementation-rfc6570-perform", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4319, + "section": "Appendix C: Using RFC6570-Based Serialization", + "anchor": "appendix-c-using-rfc6570-based-serialization", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations of this specification MAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply." + }, + { + "id": "oas-3.1.appendix-e-percent-encoding-and-form-media-types.must-set-characters-encoded-varies-depending-version", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4598, + "section": "Appendix E: Percent-Encoding and Form Media Types", + "anchor": "appendix-e-percent-encoding-and-form-media-types", + "level": "MUST", + "terms": ["MUST"], + "text": "The set of characters that MUST be encoded varies depending on which version of which specification you use, and (for URIs) in which part of the URI the character appears." + }, + { + "id": "oas-3.1.appendix-f-resolving-security-requirements-in-a-referenced-document.recommended-however-documented-section-tools-resolve-component", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4786, + "section": "Appendix F: Resolving Security Requirements in a Referenced Document", + "anchor": "appendix-f-resolving-security-requirements-in-a-referenced-document", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, documented in that section, it is RECOMMENDED that tools resolve component names from the entry document." + }, + { + "id": "oas-3.1.callback-object.pattern-expression", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2152, + "section": "Specification > Schema > Callback Object > Patterned Fields", + "anchor": "callback-expression", + "level": "field", + "terms": [], + "text": "A Path Item Object used to define a callback request and expected responses. A complete example is available." + }, + { + "id": "oas-3.1.callback-object.patterned-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2154, + "section": "Specification > Schema > Callback Object > Patterned Fields", + "anchor": "patterned-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.components-object.callbacks", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 588, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-callbacks", + "level": "field", + "terms": [], + "text": "An object to hold reusable Callback Objects." + }, + { + "id": "oas-3.1.components-object.examples", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 583, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-examples", + "level": "field", + "terms": [], + "text": "An object to hold reusable Example Objects." + }, + { + "id": "oas-3.1.components-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 591, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "fixed-fields-5", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.components-object.fixed-fields.must-all-fixed-fields-declared-above-objects", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 593, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "fixed-fields-5", + "level": "MUST", + "terms": ["MUST"], + "text": "All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\\.\\-_]+$`." + }, + { + "id": "oas-3.1.components-object.headers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 585, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-headers", + "level": "field", + "terms": [], + "text": "An object to hold reusable Header Objects." + }, + { + "id": "oas-3.1.components-object.links", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 587, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-links", + "level": "field", + "terms": [], + "text": "An object to hold reusable Link Objects." + }, + { + "id": "oas-3.1.components-object.parameters", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 582, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-parameters", + "level": "field", + "terms": [], + "text": "An object to hold reusable Parameter Objects." + }, + { + "id": "oas-3.1.components-object.pathItems", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 589, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-path-items", + "level": "field", + "terms": [], + "text": "An object to hold reusable Path Item Objects." + }, + { + "id": "oas-3.1.components-object.requestBodies", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 584, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-request-bodies", + "level": "field", + "terms": [], + "text": "An object to hold reusable Request Body Objects." + }, + { + "id": "oas-3.1.components-object.responses", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 581, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-responses", + "level": "field", + "terms": [], + "text": "An object to hold reusable Response Objects." + }, + { + "id": "oas-3.1.components-object.schemas", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 580, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-schemas", + "level": "field", + "terms": [], + "text": "An object to hold reusable Schema Objects." + }, + { + "id": "oas-3.1.components-object.securitySchemes", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 586, + "section": "Specification > Schema > Components Object > Fixed Fields", + "anchor": "components-security-schemes", + "level": "field", + "terms": [], + "text": "An object to hold reusable Security Scheme Objects." + }, + { + "id": "oas-3.1.conditions-for-using-the-discriminator-object.may-avoid-redundancy-discriminator-added-parent-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3345, + "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", + "level": "MAY", + "terms": ["MAY"], + "text": "To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas building on the parent schema via an `allOf` construct may be used as an alternate schema." + }, + { + "id": "oas-3.1.conditions-for-using-the-discriminator-object.must-both-oneof-anyof-use-cases-keywords", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3343, + "section": "Specification > Schema > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", + "level": "MUST", + "terms": ["MUST"], + "text": "In both the `oneOf` and `anyOf` use cases, where those keywords are adjacent to `discriminator`, all possible schemas MUST be listed explicitly." + }, + { + "id": "oas-3.1.contact-object.email", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 403, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-email", + "level": "field", + "terms": [], + "text": "The email address of the contact person/organization. This MUST be in the form of an email address." + }, + { + "id": "oas-3.1.contact-object.email.must-form-email-address", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 403, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-email", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of an email address." + }, + { + "id": "oas-3.1.contact-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 405, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.contact-object.name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 401, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-name", + "level": "field", + "terms": [], + "text": "The identifying name of the contact person/organization." + }, + { + "id": "oas-3.1.contact-object.url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 402, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-url", + "level": "field", + "terms": [], + "text": "The URI for the contact information. This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.contact-object.url.must-form-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 402, + "section": "Specification > Schema > Contact Object > Fixed Fields", + "anchor": "contact-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.data-type-format.may-tools-do-not-recognize-specific-format", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 222, + "section": "Specification > Data Types > Data Type Format", + "anchor": "data-type-format", + "level": "MAY", + "terms": ["MAY"], + "text": "Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified." + }, + { + "id": "oas-3.1.data-type-format.optional-support-any-registered-format-strictly-support", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 220, + "section": "Specification > Data Types > Data Type Format", + "anchor": "data-type-format", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Support for any registered format is strictly OPTIONAL, and support for one registered format does not imply support for any others." + }, + { + "id": "oas-3.1.discriminator-object.examples.may-discriminator-used-hint-improve-efficiency-selection", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3377, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-0", + "level": "MAY", + "terms": ["MAY"], + "text": "A `discriminator` MAY be used as a \"hint\" to improve the efficiency of selection of the matching schema." + }, + { + "id": "oas-3.1.discriminator-object.examples.may-oas-3-x-response-payload-described", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3367, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-0", + "level": "MAY", + "terms": ["MAY"], + "text": "In OAS 3.x, a response payload MAY be described to be exactly one of any number of types:" + }, + { + "id": "oas-3.1.discriminator-object.examples.may-scenarios-value-discriminator-field-does-not", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3400, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-0", + "level": "MAY", + "terms": ["MAY"], + "text": "In scenarios where the value of the `discriminator` field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used:" + }, + { + "id": "oas-3.1.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3416, + "section": "Specification > Schema > Discriminator Object > Examples", + "anchor": "examples-0", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail." + }, + { + "id": "oas-3.1.discriminator-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3337, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "fixed-fields-21", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.discriminator-object.mapping", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3335, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "discriminator-mapping", + "level": "field", + "terms": [], + "text": "An object to hold mappings between payload values and schema names or URI references." + }, + { + "id": "oas-3.1.discriminator-object.must-not-note-discriminator-change-validation-outcome-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3328, + "section": "Specification > Schema > Discriminator Object", + "anchor": "discriminator-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Note that `discriminator` MUST NOT change the validation outcome of the schema." + }, + { + "id": "oas-3.1.discriminator-object.options-for-mapping-values-to-schemas.must-ensure-ambiguous-value-e-g-foo", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3354, + "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "MUST", + "terms": ["MUST"], + "text": "To ensure that an ambiguous value (e.g. `\"foo\"`) is treated as a relative URI reference by all implementations, authors MUST prefix it with the `\".\"` path segment (e.g. `\"./foo\"`)." + }, + { + "id": "oas-3.1.discriminator-object.options-for-mapping-values-to-schemas.must-mapping-keys-string-values-but-tooling", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3360, + "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison." + }, + { + "id": "oas-3.1.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-both-valid-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3354, + "section": "Specification > Schema > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "The behavior of a `mapping` value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it is RECOMMENDED that it be treated as a schema name." + }, + { + "id": "oas-3.1.discriminator-object.propertyName", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3334, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the property in the payload that will hold the discriminating value. This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." + }, + { + "id": "oas-3.1.discriminator-object.propertyName.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3334, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.discriminator-object.propertyName.should-property-required-payload-schema-behavior-property", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3334, + "section": "Specification > Schema > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "This property SHOULD be required in the payload schema, as the behavior when the property is absent is undefined." + }, + { + "id": "oas-3.1.encoding-object.allowReserved", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1720, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "field", + "terms": [], + "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see URL Percent-Encoding for details. The default value is `false`. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.1.encoding-object.allowReserved.shall-field-ignored-request-body-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1720, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + }, + { + "id": "oas-3.1.encoding-object.allowReserved.shall-value-explicitly-defined-value-contenttype-implicit", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1720, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.1.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1690, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used either with or without the RFC6570-style serialization fields defined in the next section below." + }, + { + "id": "oas-3.1.encoding-object.common-fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1697, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.encoding-object.contentType", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1694, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-content-type", + "level": "field", + "terms": [], + "text": "The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a wildcard media type (e.g. `image/*`). Default value depends on the property type as shown in the table below." + }, + { + "id": "oas-3.1.encoding-object.encoding-multipart-media-types.may-not-currently-possible-correlate-schema-properties", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1824, + "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", + "anchor": "encoding-multipart-media-types", + "level": "MAY", + "terms": ["MAY"], + "text": "It is not currently possible to correlate schema properties with unnamed, ordered parts in media types such as `multipart/mixed`, but implementations MAY choose to support such types when `Content-Disposition: form-data` is used with a `name` parameter." + }, + { + "id": "oas-3.1.encoding-object.encoding-multipart-media-types.not-recommended-because-because-encoding-object-s-contenttype", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1834, + "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", + "anchor": "encoding-multipart-media-types", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Because of this, and because the Encoding Object's `contentType` defaulting rules do not take the Schema Object's`contentMediaType` into account, the use of `contentMediaType` with an Encoding Object is NOT RECOMMENDED." + }, + { + "id": "oas-3.1.encoding-object.encoding-multipart-media-types.required-contrast-openapi-2-0-schema-define", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1818, + "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", + "anchor": "encoding-multipart-media-types", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "In contrast to OpenAPI 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content." + }, + { + "id": "oas-3.1.encoding-object.encoding-multipart-media-types.shall-note-stated-working-binary-data-encoding", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1834, + "section": "Specification > Schema > Encoding Object > Encoding `multipart` Media Types", + "anchor": "encoding-multipart-media-types", + "level": "MUST", + "terms": ["SHALL"], + "text": "Note that as stated in Working with Binary Data, if the Encoding Object's `contentType`, whether set explicitly or implicitly through its default value rules, disagrees with the `contentMediaType` in a Schema Object, the `contentMediaType` SHALL be ignored." + }, + { + "id": "oas-3.1.encoding-object.encoding-the-x-www-form-urlencoded-media-type.must-configuration-means-request-body-encoded-per", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1730, + "section": "Specification > Schema > Encoding Object > Encoding the `x-www-form-urlencoded` Media Type", + "anchor": "encoding-the-x-www-form-urlencoded-media-type", + "level": "MUST", + "terms": ["MUST"], + "text": "This configuration means that the request body MUST be encoded per RFC1866 when passed to the server, after any complex objects have been serialized to a string representation." + }, + { + "id": "oas-3.1.encoding-object.explode", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1719, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", + "level": "field", + "terms": [], + "text": "When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined. This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.1.encoding-object.explode.shall-field-ignored-request-body-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1719, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + }, + { + "id": "oas-3.1.encoding-object.explode.shall-value-explicitly-defined-value-contenttype-implicit", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1719, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.1.encoding-object.fixed-fields-for-rfc6570-style-serialization.must-not-using-rfc6570-style-serialization-multipart-form", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1722, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "fixed-fields-for-rfc6570-style-serialization", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "When using RFC6570-style serialization for `multipart/form-data`, URI percent-encoding MUST NOT be applied, and the value of `allowReserved` has no effect." + }, + { + "id": "oas-3.1.encoding-object.headers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1695, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "field", + "terms": [], + "text": "A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the request body media type is not a `multipart`." + }, + { + "id": "oas-3.1.encoding-object.headers.shall-content-type-described-separately-ignored-section", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1695, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "`Content-Type` is described separately and SHALL be ignored in this section." + }, + { + "id": "oas-3.1.encoding-object.headers.shall-field-ignored-request-body-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1695, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not a `multipart`." + }, + { + "id": "oas-3.1.encoding-object.style", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1718, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "field", + "terms": [], + "text": "Describes how a specific property value will be serialized depending on its type. See Parameter Object for details on the `style` field. The behavior follows the same values as `query` parameters, including the default value of `\"form\"` which applies only when `contentType` is _not_ being used due to one or both of `explode` or `allowReserved` being explicitly specified. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.1.encoding-object.style.must-note-initial-used-query-strings-not", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1718, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["MUST"], + "text": "Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually)." + }, + { + "id": "oas-3.1.encoding-object.style.shall-field-ignored-request-body-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1718, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + }, + { + "id": "oas-3.1.encoding-object.style.shall-value-explicitly-defined-value-contenttype-implicit", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1718, + "section": "Specification > Schema > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.1.example-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2249, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-description", + "level": "field", + "terms": [], + "text": "Long description for the example. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.example-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2249, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.example-object.externalValue", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2251, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-external-value", + "level": "field", + "terms": [], + "text": "A URI that identifies the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving Relative References." + }, + { + "id": "oas-3.1.example-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2253, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.example-object.fixed-fields.may-tooling-implementations-choose-validate-compatibility-automatically", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2255, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "MAY", + "terms": ["MAY"], + "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + }, + { + "id": "oas-3.1.example-object.fixed-fields.should-all-cases-example-value-compatible-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2255, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In all cases, the example value SHOULD be compatible with the schema of its associated value." + }, + { + "id": "oas-3.1.example-object.summary", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2248, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-summary", + "level": "field", + "terms": [], + "text": "Short description for the example." + }, + { + "id": "oas-3.1.example-object.value", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2250, + "section": "Specification > Schema > Example Object > Fixed Fields", + "anchor": "example-value", + "level": "field", + "terms": [], + "text": "Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary." + }, + { + "id": "oas-3.1.example-object.working-with-examples.shall-because-examples-using-fields-represent-final", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2268, + "section": "Specification > Schema > Example Object > Working with Examples", + "anchor": "working-with-examples", + "level": "MUST", + "terms": ["SHALL"], + "text": "Because examples using these fields represent the final serialized form of the data, they SHALL _override_ any `example` in the corresponding Schema Object." + }, + { + "id": "oas-3.1.example-object.working-with-examples.should-mutually-exclusive-fields-parameter-header-media", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2268, + "section": "Specification > Schema > Example Object > Working with Examples", + "anchor": "working-with-examples", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The mutually exclusive fields in the Parameter, Header, or Media Type Objects are used to show example values which SHOULD both match the schema and be formatted as they would appear as a serialized parameter, serialized header, or within a media type representation." + }, + { + "id": "oas-3.1.external-documentation-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1103, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-description", + "level": "field", + "terms": [], + "text": "A description of the target documentation. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.external-documentation-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1103, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.external-documentation-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1106, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "fixed-fields-8", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.external-documentation-object.url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1104, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The URI for the target documentation. This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.external-documentation-object.url.must-form-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1104, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.external-documentation-object.url.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1104, + "section": "Specification > Schema > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.format.must-keys-used-yaml-maps-limited-scalar", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 121, + "section": "Specification > Format", + "anchor": "format", + "level": "MUST", + "terms": ["MUST"], + "text": "Keys used in YAML maps MUST be limited to a scalar string, as defined by the YAML Failsafe schema ruleset." + }, + { + "id": "oas-3.1.format.must-patterned-fields-have-unique-names-within", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 116, + "section": "Specification > Format", + "anchor": "format", + "level": "MUST", + "terms": ["MUST"], + "text": "Patterned fields MUST have unique names within the containing object." + }, + { + "id": "oas-3.1.format.must-tags-limited-allowed-yaml-s-json", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 120, + "section": "Specification > Format", + "anchor": "format", + "level": "MUST", + "terms": ["MUST"], + "text": "Tags MUST be limited to those allowed by YAML's JSON schema ruleset, which defines a subset of the YAML syntax and is unrelated to [JSON Schema]." + }, + { + "id": "oas-3.1.format.recommended-order-preserve-ability-round-trip-between", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 118, + "section": "Specification > Format", + "anchor": "format", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with some additional constraints:" + }, + { + "id": "oas-3.1.header-object.common-fixed-fields.may-fields-used-either-content-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2600, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used with either `content` or `schema`." + }, + { + "id": "oas-3.1.header-object.common-fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2608, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.header-object.content", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2637, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "header-content", + "level": "field", + "terms": [], + "text": "A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry." + }, + { + "id": "oas-3.1.header-object.content.must-map-only-contain-one-entry", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2637, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "header-content", + "level": "MUST", + "terms": ["MUST"], + "text": "The map MUST only contain one entry." + }, + { + "id": "oas-3.1.header-object.deprecated", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2606, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-deprecated", + "level": "field", + "terms": [], + "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + }, + { + "id": "oas-3.1.header-object.deprecated.should-specifies-header-deprecated-transitioned-out-usage", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2606, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage." + }, + { + "id": "oas-3.1.header-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2604, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-description", + "level": "field", + "terms": [], + "text": "A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.header-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2604, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.header-object.example", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2626, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-example", + "level": "field", + "terms": [], + "text": "Example of the header's potential value; see Working With Examples." + }, + { + "id": "oas-3.1.header-object.examples", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2627, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-examples", + "level": "field", + "terms": [], + "text": "Examples of the header's potential value; see Working With Examples." + }, + { + "id": "oas-3.1.header-object.explode", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2624, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-explode", + "level": "field", + "terms": [], + "text": "When this is true, header values of type `array` or `object` generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is `false`." + }, + { + "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.must-example-examples-provided-conjunction-schema-field", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2612, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["MUST"], + "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example MUST follow the prescribed serialization strategy for the header." + }, + { + "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2615, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["MUST"], + "text": "Implementations MUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; see Appendix D for guidance on quoting and escaping." + }, + { + "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.must-not-serializing-headers-schema-uri-percent-encoding", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2615, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "When serializing headers with `schema`, URI percent-encoding MUST NOT be applied; if using an RFC6570 implementation that automatically applies it, it MUST be removed before use." + }, + { + "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2618, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + }, + { + "id": "oas-3.1.header-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2618, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the header." + }, + { + "id": "oas-3.1.header-object.must-all-traits-affected-location-applicable-location", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2594, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST"], + "text": "All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`)." + }, + { + "id": "oas-3.1.header-object.must-not-means-allowemptyvalue-allowreserved-used-style-used", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2594, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "This means that `allowEmptyValue` and `allowReserved` MUST NOT be used, and `style`, if used, MUST be limited to `\"simple\"`." + }, + { + "id": "oas-3.1.header-object.must-not-name-specified-given-corresponding-headers-map", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2592, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "`name` MUST NOT be specified, it is given in the corresponding `headers` map." + }, + { + "id": "oas-3.1.header-object.must-not-specified-implicitly-header", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2593, + "section": "Specification > Schema > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "`in` MUST NOT be specified, it is implicitly in `header`." + }, + { + "id": "oas-3.1.header-object.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2605, + "section": "Specification > Schema > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-required", + "level": "field", + "terms": [], + "text": "Determines whether this header is mandatory. The default value is `false`." + }, + { + "id": "oas-3.1.header-object.schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2625, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-schema", + "level": "field", + "terms": [], + "text": "The schema defining the type used for the header." + }, + { + "id": "oas-3.1.header-object.style", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2623, + "section": "Specification > Schema > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-style", + "level": "field", + "terms": [], + "text": "Describes how the header value will be serialized. The default (and only legal value for headers) is `\"simple\"`." + }, + { + "id": "oas-3.1.http-status-codes.should-status-codes-selected-available-status-codes", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 70, + "section": "Definitions > HTTP Status Codes", + "anchor": "http-status-codes", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Status codes SHOULD be selected from the available status codes registered in the IANA Status Code Registry." + }, + { + "id": "oas-3.1.info-object.contact", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 351, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-contact", + "level": "field", + "terms": [], + "text": "The contact information for the exposed API." + }, + { + "id": "oas-3.1.info-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 349, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-description", + "level": "field", + "terms": [], + "text": "A description of the API. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.info-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 349, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.info-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 355, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.info-object.license", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 352, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-license", + "level": "field", + "terms": [], + "text": "The license information for the exposed API." + }, + { + "id": "oas-3.1.info-object.may-metadata-used-clients-needed-presented-editing", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 340, + "section": "Specification > Schema > Info Object", + "anchor": "info-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience." + }, + { + "id": "oas-3.1.info-object.summary", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 348, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-summary", + "level": "field", + "terms": [], + "text": "A short summary of the API." + }, + { + "id": "oas-3.1.info-object.termsOfService", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 350, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-terms-of-service", + "level": "field", + "terms": [], + "text": "A URI for the Terms of Service for the API. This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.info-object.termsOfService.must-form-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 350, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-terms-of-service", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.info-object.title", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 347, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-title", + "level": "field", + "terms": [], + "text": "REQUIRED. The title of the API." + }, + { + "id": "oas-3.1.info-object.title.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 347, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-title", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.info-object.version", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 353, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-version", + "level": "field", + "terms": [], + "text": "REQUIRED. The version of the OpenAPI Document (which is distinct from the OpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description)." + }, + { + "id": "oas-3.1.info-object.version.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 353, + "section": "Specification > Schema > Info Object > Fixed Fields", + "anchor": "info-version", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.interoperability-with-historical-specifications.should-since-all-rfc1738-compliant-uris-compliant", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4657, + "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Historical Specifications", + "anchor": "interoperability-with-historical-specifications", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Since all RFC1738-compliant URIs are compliant with RFC3986, applications needing to ensure historical interoperability SHOULD use RFC1738's rules." + }, + { + "id": "oas-3.1.interoperability-with-web-browser-environments.should-implementations-needing-maximum-compatibility-web-browsers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4664, + "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", + "anchor": "interoperability-with-web-browser-environments", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Implementations needing maximum compatibility with web browsers SHOULD use WHATWG's `form-urlencoded` percent-encoding rules." + }, + { + "id": "oas-3.1.interoperability-with-web-browser-environments.should-not-however-they-rely-whatwg-s-less", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4664, + "section": "Appendix E: Percent-Encoding and Form Media Types > Generating and Validating URIs and `form-urlencoded` Strings > Interoperability with Web Browser Environments", + "anchor": "interoperability-with-web-browser-environments", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "However, they SHOULD NOT rely on WHATWG's less stringent generic query string rules, as the resulting URLs would fail RFC3986 validation, including JSON Schema's `format: uri` and `format: uri-reference` (when `format` validation is endabled)." + }, + { + "id": "oas-3.1.license-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 435, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "fixed-fields-2", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.license-object.identifier", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 432, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-identifier", + "level": "field", + "terms": [], + "text": "An SPDX license expression for the API. The `identifier` field is mutually exclusive of the `url` field." + }, + { + "id": "oas-3.1.license-object.name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 431, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The license name used for the API." + }, + { + "id": "oas-3.1.license-object.name.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 431, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.license-object.url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 433, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-url", + "level": "field", + "terms": [], + "text": "A URI for the license used for the API. This MUST be in the form of a URI. The `url` field is mutually exclusive of the `identifier` field." + }, + { + "id": "oas-3.1.license-object.url.must-form-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 433, + "section": "Specification > Schema > License Object > Fixed Fields", + "anchor": "license-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.link-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2429, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-description", + "level": "field", + "terms": [], + "text": "A description of the link. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.link-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2429, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.link-object.example-expressions.must-request-parameters-declared-parameters-section-parent", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2577, + "section": "Specification > Schema > Link Object > Runtime Expressions > Example Expressions", + "anchor": "example-expressions", + "level": "MUST", + "terms": ["MUST"], + "text": "Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated." + }, + { + "id": "oas-3.1.link-object.fixed-fields.may-ambiguous-cases-resulting-behavior-implementation-defined", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2434, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MAY", + "terms": ["MAY"], + "text": "In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error." + }, + { + "id": "oas-3.1.link-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2432, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.link-object.fixed-fields.must-identified-referenced-operation-unique-case-operationid", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2434, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MUST", + "terms": ["MUST"], + "text": "The identified or referenced operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD)." + }, + { + "id": "oas-3.1.link-object.fixed-fields.must-linked-operation-identified-using-either-operationref", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2434, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MUST", + "terms": ["MUST"], + "text": "A linked operation MUST be identified using either an `operationRef` or `operationId`." + }, + { + "id": "oas-3.1.link-object.fixed-fields.not-recommended-possible-have-ambiguous-parameter-names-e", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2440, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED", "SHOULD"], + "text": "It is possible to have ambiguous parameter names, e.g. `name: \"id\", in: \"path\"` and `name: \"path.id\", in: \"query\"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter)." + }, + { + "id": "oas-3.1.link-object.operationId", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2426, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-id", + "level": "field", + "terms": [], + "text": "The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field." + }, + { + "id": "oas-3.1.link-object.operationRef", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2425, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "field", + "terms": [], + "text": "A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object. Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + }, + { + "id": "oas-3.1.link-object.operationRef.may-relative-operationref-values-used-locate-existing", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2425, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "MAY", + "terms": ["MAY"], + "text": "Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + }, + { + "id": "oas-3.1.link-object.operationRef.must-field-mutually-exclusive-operationid-field-point", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2425, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." + }, + { + "id": "oas-3.1.link-object.operationref-examples.may-operationid-optional-field-operation-object-references", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2512, + "section": "Specification > Schema > Link Object > Examples > `operationRef` Examples", + "anchor": "operationref-examples", + "level": "MAY", + "terms": ["MAY"], + "text": "As the `operationId` is an optional field in an Operation Object, references MAY instead be made through a URI-reference with `operationRef`." + }, + { + "id": "oas-3.1.link-object.parameters", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2427, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-parameters", + "level": "field", + "terms": [], + "text": "A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation." + }, + { + "id": "oas-3.1.link-object.requestBody", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2428, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-request-body", + "level": "field", + "terms": [], + "text": "A literal value or {expression} to use as a request body when calling the target operation." + }, + { + "id": "oas-3.1.link-object.server", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2430, + "section": "Specification > Schema > Link Object > Fixed Fields", + "anchor": "link-server", + "level": "field", + "terms": [], + "text": "A server object to be used by the target operation." + }, + { + "id": "oas-3.1.media-type-object.considerations-for-file-uploads.may-addition-specific-media-types-specified", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1655, + "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MAY", + "terms": ["MAY"], + "text": "In addition, specific media types MAY be specified:" + }, + { + "id": "oas-3.1.media-type-object.considerations-for-file-uploads.may-content-transferred-binary-octet-stream-omit", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1625, + "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MAY", + "terms": ["MAY"], + "text": "Content transferred in binary (octet-stream) MAY omit `schema`:" + }, + { + "id": "oas-3.1.media-type-object.considerations-for-file-uploads.must-upload-multiple-files-multipart-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1666, + "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MUST", + "terms": ["MUST"], + "text": "To upload multiple files, a `multipart` media type MUST be used as shown under Example: Multipart Form with Multiple Files." + }, + { + "id": "oas-3.1.media-type-object.encoding", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1551, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "field", + "terms": [], + "text": "A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object." + }, + { + "id": "oas-3.1.media-type-object.encoding.must-key-being-property-name-exist-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1551, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "MUST", + "terms": ["MUST"], + "text": "The key, being the property name, MUST exist in the schema as a property." + }, + { + "id": "oas-3.1.media-type-object.encoding.shall-encoding-field-only-apply-request-body", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1551, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`." + }, + { + "id": "oas-3.1.media-type-object.example", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1549, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-example", + "level": "field", + "terms": [], + "text": "Example of the media type; see Working With Examples." + }, + { + "id": "oas-3.1.media-type-object.examples", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1550, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-examples", + "level": "field", + "terms": [], + "text": "Examples of the media type; see Working With Examples." + }, + { + "id": "oas-3.1.media-type-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1553, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "fixed-fields-11", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.media-type-object.schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1548, + "section": "Specification > Schema > Media Type Object > Fixed Fields", + "anchor": "media-type-schema", + "level": "field", + "terms": [], + "text": "The schema defining the content of the request, response, parameter, or header." + }, + { + "id": "oas-3.1.media-type-object.shall-example-examples-fields-mutually-exclusive-either", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1540, + "section": "Specification > Schema > Media Type Object", + "anchor": "media-type-object", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + }, + { + "id": "oas-3.1.media-type-object.should-example-examples-provided-example-match-specified", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1540, + "section": "Specification > Schema > Media Type Object", + "anchor": "media-type-object", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding." + }, + { + "id": "oas-3.1.media-types.should-media-type-definitions-compliance-rfc6838", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 50, + "section": "Definitions > Media Types", + "anchor": "media-types", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The media type definitions SHOULD be in compliance with RFC6838." + }, + { + "id": "oas-3.1.non-rfc6570-field-values-and-combinations.may-implementations-create-properly-delimited-uri-template", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4376, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based on `allowReserved`)." + }, + { + "id": "oas-3.1.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4385, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "MUST", + "terms": ["MUST"], + "text": "A parameter name that includes characters outside of the allowed RFC6570 variable character set MUST be percent-encoded before it can be used in a URI Template." + }, + { + "id": "oas-3.1.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4376, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Configurations with no direct RFC6570 equivalent SHOULD also be handled according to RFC6570." + }, + { + "id": "oas-3.1.oauth-flow-object.authorizationUrl", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4078, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.1.oauth-flow-object.authorizationUrl.must-form-url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4078, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.1.oauth-flow-object.authorizationUrl.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4078, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4083, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "fixed-fields-25", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.oauth-flow-object.refreshUrl", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4080, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-refresh-url", + "level": "field", + "terms": [], + "text": "The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.1.oauth-flow-object.refreshUrl.must-form-url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4080, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-refresh-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.1.oauth-flow-object.scopes", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4081, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "field", + "terms": [], + "text": "REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty." + }, + { + "id": "oas-3.1.oauth-flow-object.scopes.may-map-empty", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4081, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "MAY", + "terms": ["MAY"], + "text": "The map MAY be empty." + }, + { + "id": "oas-3.1.oauth-flow-object.scopes.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4081, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.oauth-flow-object.tokenUrl", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4079, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.1.oauth-flow-object.tokenUrl.must-form-url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4079, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.1.oauth-flow-object.tokenUrl.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4079, + "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.oauth-flows-object.authorizationCode", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4066, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-authorization-code", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0." + }, + { + "id": "oas-3.1.oauth-flows-object.clientCredentials", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4065, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-client-credentials", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0." + }, + { + "id": "oas-3.1.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4068, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "fixed-fields-24", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.oauth-flows-object.implicit", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4063, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-implicit", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Implicit flow" + }, + { + "id": "oas-3.1.oauth-flows-object.password", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4064, + "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-password", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Resource Owner Password flow" + }, + { + "id": "oas-3.1.openapi-description-structure.may-openapi-description-oad-made-up-single", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 127, + "section": "Specification > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "MAY", + "terms": ["MAY"], + "text": "An OpenAPI Description (OAD) MAY be made up of a single JSON or YAML document or be divided into multiple, connected parts at the discretion of the author." + }, + { + "id": "oas-3.1.openapi-description-structure.recommended-entry-document-oad-named-openapi-json", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 131, + "section": "Specification > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is RECOMMENDED that the entry document of an OAD be named: `openapi.json` or `openapi.yaml`." + }, + { + "id": "oas-3.1.openapi-description.must-oad-uses-conforms-openapi-specification-contain", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 23, + "section": "Definitions > OpenAPI Description", + "anchor": "openapi-description", + "level": "MUST", + "terms": ["MUST"], + "text": "An OAD uses and conforms to the OpenAPI Specification, and MUST contain at least one paths field, components field, or webhooks field." + }, + { + "id": "oas-3.1.openapi-object.components", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 331, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-components", + "level": "field", + "terms": [], + "text": "An element to hold various Objects for the OpenAPI Description." + }, + { + "id": "oas-3.1.openapi-object.externalDocs", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 334, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation." + }, + { + "id": "oas-3.1.openapi-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 336, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.openapi-object.info", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 326, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "field", + "terms": [], + "text": "REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required." + }, + { + "id": "oas-3.1.openapi-object.info.may-metadata-used-tooling-required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 326, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "MAY", + "terms": ["MAY"], + "text": "The metadata MAY be used by tooling as required." + }, + { + "id": "oas-3.1.openapi-object.info.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 326, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.openapi-object.jsonSchemaDialect", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 327, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-json-schema-dialect", + "level": "field", + "terms": [], + "text": "The default value for the `$schema` keyword within Schema Objects contained within this OAS document. This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.openapi-object.jsonSchemaDialect.must-form-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 327, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-json-schema-dialect", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.openapi-object.openapi", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 325, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "field", + "terms": [], + "text": "REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document. This is _not_ related to the `info.version` string, which is the version of the OpenAPI Document." + }, + { + "id": "oas-3.1.openapi-object.openapi.must-string-version-number-openapi-specification-openapi", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 325, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "MUST", + "terms": ["MUST"], + "text": "This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses." + }, + { + "id": "oas-3.1.openapi-object.openapi.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 325, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.openapi-object.openapi.should-openapi-field-used-tooling-interpret-openapi", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 325, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document." + }, + { + "id": "oas-3.1.openapi-object.paths", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 329, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-paths", + "level": "field", + "terms": [], + "text": "The available paths and operations for the API." + }, + { + "id": "oas-3.1.openapi-object.security", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 332, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-security", + "level": "field", + "terms": [], + "text": "A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array." + }, + { + "id": "oas-3.1.openapi-object.servers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 328, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-servers", + "level": "field", + "terms": [], + "text": "An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be a Server Object with a url value of `/`." + }, + { + "id": "oas-3.1.openapi-object.tags", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 333, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "field", + "terms": [], + "text": "A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." + }, + { + "id": "oas-3.1.openapi-object.tags.may-tags-not-declared-organized-randomly-based", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 333, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "MAY", + "terms": ["MAY"], + "text": "The tags that are not declared MAY be organized randomly or based on the tools' logic." + }, + { + "id": "oas-3.1.openapi-object.tags.must-each-tag-name-list-unique", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 333, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "MUST", + "terms": ["MUST"], + "text": "Each tag name in the list MUST be unique." + }, + { + "id": "oas-3.1.openapi-object.webhooks", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 330, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-webhooks", + "level": "field", + "terms": [], + "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An example is available." + }, + { + "id": "oas-3.1.openapi-object.webhooks.may-incoming-webhooks-received-part-api-api", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 330, + "section": "Specification > Schema > OpenAPI Object > Fixed Fields", + "anchor": "oas-webhooks", + "level": "MAY", + "terms": ["MAY"], + "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement." + }, + { + "id": "oas-3.1.operation-object.callbacks", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 983, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-callbacks", + "level": "field", + "terms": [], + "text": "A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses." + }, + { + "id": "oas-3.1.operation-object.deprecated", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 984, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-deprecated", + "level": "field", + "terms": [], + "text": "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`." + }, + { + "id": "oas-3.1.operation-object.deprecated.should-consumers-refrain-usage-declared-operation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 984, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Consumers SHOULD refrain from usage of the declared operation." + }, + { + "id": "oas-3.1.operation-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 977, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-description", + "level": "field", + "terms": [], + "text": "A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.operation-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 977, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.operation-object.externalDocs", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 978, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this operation." + }, + { + "id": "oas-3.1.operation-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 988, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "fixed-fields-7", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.operation-object.operationId", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 979, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "field", + "terms": [], + "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + }, + { + "id": "oas-3.1.operation-object.operationId.must-id-unique-among-all-operations-described", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 979, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "MUST", + "terms": ["MUST"], + "text": "The id MUST be unique among all operations described in the API." + }, + { + "id": "oas-3.1.operation-object.operationId.recommended-tools-libraries-use-operationid-uniquely-identify", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 979, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "SHOULD", + "terms": ["MAY", "RECOMMENDED"], + "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + }, + { + "id": "oas-3.1.operation-object.parameters", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 980, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-parameters", + "level": "field", + "terms": [], + "text": "A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + }, + { + "id": "oas-3.1.operation-object.parameters.must-not-list-include-duplicated-parameters", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 980, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-parameters", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." + }, + { + "id": "oas-3.1.operation-object.requestBody", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 981, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-request-body", + "level": "field", + "terms": [], + "text": "The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." + }, + { + "id": "oas-3.1.operation-object.requestBody.should-other-cases-http-spec-vague-get", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 981, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-request-body", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." + }, + { + "id": "oas-3.1.operation-object.responses", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 982, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-responses", + "level": "field", + "terms": [], + "text": "The list of possible responses as they are returned from executing this operation." + }, + { + "id": "oas-3.1.operation-object.security", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 985, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-security", + "level": "field", + "terms": [], + "text": "A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." + }, + { + "id": "oas-3.1.operation-object.servers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 986, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-servers", + "level": "field", + "terms": [], + "text": "An alternative `servers` array to service this operation. If a `servers` array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value." + }, + { + "id": "oas-3.1.operation-object.summary", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 976, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-summary", + "level": "field", + "terms": [], + "text": "A short summary of what the operation does." + }, + { + "id": "oas-3.1.operation-object.tags", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 975, + "section": "Specification > Schema > Operation Object > Fixed Fields", + "anchor": "operation-tags", + "level": "field", + "terms": [], + "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." + }, + { + "id": "oas-3.1.parameter-object.allowEmptyValue", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1156, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "field", + "terms": [], + "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for `query` parameters. Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + }, + { + "id": "oas-3.1.parameter-object.allowEmptyValue.not-recommended-use-field-likely-removed-later-revision", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1156, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + }, + { + "id": "oas-3.1.parameter-object.allowEmptyValue.shall-style-used-behavior-n-cannot-serialized", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1156, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "MUST", + "terms": ["SHALL"], + "text": "If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored." + }, + { + "id": "oas-3.1.parameter-object.allowEmptyValue.should-true-clients-pass-zero-length-string", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1156, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "SHOULD", + "terms": ["MAY", "SHOULD"], + "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused." + }, + { + "id": "oas-3.1.parameter-object.allowReserved", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1177, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-allow-reserved", + "level": "field", + "terms": [], + "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see URL Percent-Encoding for details. This field only applies to parameters with an `in` value of `query`. The default value is `false`." + }, + { + "id": "oas-3.1.parameter-object.common-fixed-fields.may-fields-used-either-content-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1147, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used with either `content` or `schema`." + }, + { + "id": "oas-3.1.parameter-object.common-fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1158, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.parameter-object.content", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1191, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "parameter-content", + "level": "field", + "terms": [], + "text": "A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry." + }, + { + "id": "oas-3.1.parameter-object.content.must-map-only-contain-one-entry", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1191, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "parameter-content", + "level": "MUST", + "terms": ["MUST"], + "text": "The map MUST only contain one entry." + }, + { + "id": "oas-3.1.parameter-object.deprecated", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1155, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-deprecated", + "level": "field", + "terms": [], + "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + }, + { + "id": "oas-3.1.parameter-object.deprecated.should-specifies-parameter-deprecated-transitioned-out-usage", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1155, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage." + }, + { + "id": "oas-3.1.parameter-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1153, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-description", + "level": "field", + "terms": [], + "text": "A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.parameter-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1153, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.parameter-object.example", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1179, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-example", + "level": "field", + "terms": [], + "text": "Example of the parameter's potential value; see Working With Examples." + }, + { + "id": "oas-3.1.parameter-object.examples", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1180, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-examples", + "level": "field", + "terms": [], + "text": "Examples of the parameter's potential value; see Working With Examples." + }, + { + "id": "oas-3.1.parameter-object.explode", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1176, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-explode", + "level": "field", + "terms": [], + "text": "When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-content.recommended-using-content-text-plain-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1186, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "fixed-fields-for-use-with-content", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "Using `content` with a `text/plain` media type is RECOMMENDED for `in: \"cookie\"` parameters where the `schema` strategy's percent-encoding and/or delimiter rules are not appropriate." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1168, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["MUST"], + "text": "Implementations MUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; see Appendix D for guidance on quoting and escaping." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.must-not-serializing-header-parameters-schema-uri-percent", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1168, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "When serializing `in: \"header\"` parameters with `schema`, URI percent-encoding MUST NOT be applied; if using an RFC6570 implementation that automatically applies it, it MUST be removed before use." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-see-appendix", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1171, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Serializing with `schema` is NOT RECOMMENDED for `in: \"cookie\"` parameters; see Appendix D for details." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1164, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1164, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the parameter." + }, + { + "id": "oas-3.1.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1141, + "section": "Specification > Schema > Parameter Object > Fixed Fields", + "anchor": "fixed-fields-9", + "level": "MUST", + "terms": ["MUST"], + "text": "Parameter Objects MUST include either a `content` field or a `schema` field, but not both." + }, + { + "id": "oas-3.1.parameter-object.in", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1152, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-in", + "level": "field", + "terms": [], + "text": "REQUIRED. The location of the parameter. Possible values are `\"query\"`, `\"header\"`, `\"path\"` or `\"cookie\"`." + }, + { + "id": "oas-3.1.parameter-object.in.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1152, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-in", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.parameter-object.name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1151, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the parameter. Parameter names are _case sensitive_. If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information. If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored. For all other cases, the `name` corresponds to the parameter name used by the `in` field." + }, + { + "id": "oas-3.1.parameter-object.name.must-path-name-field-correspond-template-expression", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1151, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "MUST", + "terms": ["MUST"], + "text": "If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object." + }, + { + "id": "oas-3.1.parameter-object.name.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1151, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.parameter-object.name.shall-header-name-field-accept-content-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1151, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "MUST", + "terms": ["SHALL"], + "text": "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored." + }, + { + "id": "oas-3.1.parameter-object.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1154, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", + "level": "field", + "terms": [], + "text": "Determines whether this parameter is mandatory. If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`." + }, + { + "id": "oas-3.1.parameter-object.required.may-otherwise-field-included-default-value-false", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1154, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", + "level": "MAY", + "terms": ["MAY"], + "text": "Otherwise, the field MAY be included and its default value is `false`." + }, + { + "id": "oas-3.1.parameter-object.required.required-parameter-location-path-field-value-true", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1154, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", + "level": "MUST", + "terms": ["REQUIRED", "MUST"], + "text": "If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`." + }, + { + "id": "oas-3.1.parameter-object.schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1178, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-schema", + "level": "field", + "terms": [], + "text": "The schema defining the type used for the parameter." + }, + { + "id": "oas-3.1.parameter-object.serialization-and-examples.must-cases-name-inherent-part-constructing-serialization", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1239, + "section": "Specification > Schema > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", + "level": "MUST", + "terms": ["MUST"], + "text": "In cases where the name is an inherent part of constructing the serialization, such as the `name=value` pairs produced by `style: \"form\"` or the combination of `style: \"simple\", explode: true`, the name and any delimiter between the name and value MUST be included." + }, + { + "id": "oas-3.1.parameter-object.serialization-and-examples.must-matrix-label-styles-produce-leading-delimiter", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1241, + "section": "Specification > Schema > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", + "level": "MUST", + "terms": ["MUST"], + "text": "The `matrix` and `label` styles produce a leading delimiter which is always a valid part of the serialization and MUST be included." + }, + { + "id": "oas-3.1.parameter-object.serialization-and-examples.must-not-headers-header-name-included-part-serialization", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1246, + "section": "Specification > Schema > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "For headers, the header name MUST NOT be included as part of the serialization, as it is never part of the RFC6570-derived result." + }, + { + "id": "oas-3.1.parameter-object.serialization-and-examples.must-not-suitability-either-delimiter-depends-query-string", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1241, + "section": "Specification > Schema > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "As the suitability of either delimiter depends on where in the query string the parameter occurs, as well as whether it is in a URI or in `application/x-www-form-urlencoded` content, this leading delimiter MUST NOT be included in examples of individual parameters or media type documents." + }, + { + "id": "oas-3.1.parameter-object.style", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1175, + "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-style", + "level": "field", + "terms": [], + "text": "Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"`." + }, + { + "id": "oas-3.1.parameter-object.url-percent-encoding.must-all-api-urls-successfully-parse-percent", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1209, + "section": "Specification > Schema > Parameter Object > URL Percent-Encoding", + "anchor": "url-percent-encoding", + "level": "MUST", + "terms": ["MUST"], + "text": "All API URLs MUST successfully parse and percent-decode using [RFC3986] rules." + }, + { + "id": "oas-3.1.parameter-object.url-percent-encoding.must-content-application-x-www-form-urlencoded", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1211, + "section": "Specification > Schema > Parameter Object > URL Percent-Encoding", + "anchor": "url-percent-encoding", + "level": "MUST", + "terms": ["MUST"], + "text": "Content in the `application/x-www-form-urlencoded` format, including query strings produced by Parameter Objects with `in: \"query\"`, MUST also successfully parse and percent-decode using [RFC1866] rules, including treating non-percent-encoded `+` as an escaped space character." + }, + { + "id": "oas-3.1.parameter-object.url-percent-encoding.must-not-reserved-characters-percent-encoded-being-used", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1227, + "section": "Specification > Schema > Parameter Object > URL Percent-Encoding", + "anchor": "url-percent-encoding", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Reserved characters MUST NOT be percent-encoded when being used for reserved purposes such as `&=+` for `form-urlencoded` or `,` for delimiting non-exploded array and object values in RFC6570 expansions." + }, + { + "id": "oas-3.1.parsing-documents.may-implementations-support-complete-document-parsing-any", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 139, + "section": "Specification > OpenAPI Description Structure > Parsing Documents", + "anchor": "parsing-documents", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support complete-document parsing in any of the following ways:" + }, + { + "id": "oas-3.1.parsing-documents.not-recommended-while-possible-structure-certain-openapi-descriptions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 151, + "section": "Specification > OpenAPI Description Structure > Parsing Documents", + "anchor": "parsing-documents", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "While it is possible to structure certain OpenAPI Descriptions to ensure that they will behave correctly when references are parsed as isolated fragments, depending on this is NOT RECOMMENDED." + }, + { + "id": "oas-3.1.path-item-object.$ref", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 867, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-ref", + "level": "field", + "terms": [], + "text": "Allows for a referenced definition of this path item. The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving Relative References. _Note: The behavior of `$ref` with adjacent properties is likely to change in future versions of this specification to bring it into closer alignment with the behavior of the Reference Object._" + }, + { + "id": "oas-3.1.path-item-object.$ref.must-value-form-uri-referenced-structure-form", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 867, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object." + }, + { + "id": "oas-3.1.path-item-object.delete", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 873, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-delete", + "level": "field", + "terms": [], + "text": "A definition of a DELETE operation on this path." + }, + { + "id": "oas-3.1.path-item-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 869, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-description", + "level": "field", + "terms": [], + "text": "An optional string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.path-item-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 869, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.path-item-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 881, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "fixed-fields-6", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.path-item-object.get", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 870, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-get", + "level": "field", + "terms": [], + "text": "A definition of a GET operation on this path." + }, + { + "id": "oas-3.1.path-item-object.head", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 875, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-head", + "level": "field", + "terms": [], + "text": "A definition of a HEAD operation on this path." + }, + { + "id": "oas-3.1.path-item-object.may-path-item-empty-due-acl-constraints", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 859, + "section": "Specification > Schema > Path Item Object", + "anchor": "path-item-object", + "level": "MAY", + "terms": ["MAY"], + "text": "A Path Item MAY be empty, due to ACL constraints." + }, + { + "id": "oas-3.1.path-item-object.options", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 874, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-options", + "level": "field", + "terms": [], + "text": "A definition of a OPTIONS operation on this path." + }, + { + "id": "oas-3.1.path-item-object.parameters", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 879, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-parameters", + "level": "field", + "terms": [], + "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + }, + { + "id": "oas-3.1.path-item-object.parameters.must-not-list-include-duplicated-parameters", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 879, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-parameters", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." + }, + { + "id": "oas-3.1.path-item-object.patch", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 876, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-patch", + "level": "field", + "terms": [], + "text": "A definition of a PATCH operation on this path." + }, + { + "id": "oas-3.1.path-item-object.post", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 872, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-post", + "level": "field", + "terms": [], + "text": "A definition of a POST operation on this path." + }, + { + "id": "oas-3.1.path-item-object.put", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 871, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-put", + "level": "field", + "terms": [], + "text": "A definition of a PUT operation on this path." + }, + { + "id": "oas-3.1.path-item-object.servers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 878, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-servers", + "level": "field", + "terms": [], + "text": "An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the OpenAPI Object level, it will be overridden by this value." + }, + { + "id": "oas-3.1.path-item-object.summary", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 868, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-summary", + "level": "field", + "terms": [], + "text": "An optional string summary, intended to apply to all operations in this path." + }, + { + "id": "oas-3.1.path-item-object.trace", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 877, + "section": "Specification > Schema > Path Item Object > Fixed Fields", + "anchor": "path-item-trace", + "level": "field", + "terms": [], + "text": "A definition of a TRACE operation on this path." + }, + { + "id": "oas-3.1.path-templating.must-each-template-expression-path-correspond-path", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 43, + "section": "Definitions > Path Templating", + "anchor": "path-templating", + "level": "MUST", + "terms": ["MUST"], + "text": "Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations." + }, + { + "id": "oas-3.1.path-templating.must-not-value-path-parameters-contain-any-unescaped", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 45, + "section": "Definitions > Path Templating", + "anchor": "path-templating", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The value for these path parameters MUST NOT contain any unescaped \"generic syntax\" characters described by RFC3986: forward slashes (`/`), question marks (`?`), or hashes (`#`)." + }, + { + "id": "oas-3.1.paths-object.may-paths-object-empty-due-access-control", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 781, + "section": "Specification > Schema > Paths Object", + "anchor": "paths-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The Paths Object MAY be empty, due to Access Control List (ACL) constraints." + }, + { + "id": "oas-3.1.paths-object.pattern-path", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 788, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "field", + "terms": [], + "text": "A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is appended (no relative URL resolution) to the expanded URL from the Server Object's `url` field in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use." + }, + { + "id": "oas-3.1.paths-object.pattern-path.must-field-name-begin-forward-slash", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 788, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with a forward slash (`/`)." + }, + { + "id": "oas-3.1.paths-object.pattern-path.must-not-templated-paths-same-hierarchy-but-different", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 788, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical." + }, + { + "id": "oas-3.1.paths-object.patterned-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 790, + "section": "Specification > Schema > Paths Object > Patterned Fields", + "anchor": "patterned-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.percent-encoding-and-cookies.not-recommended-note-standard-base64-encoding-alphabet-includes", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4583, + "section": "Appendix D: Serializing Headers and Cookies > Percent-Encoding and Cookies", + "anchor": "percent-encoding-and-cookies", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Note that the standard base64-encoding alphabet includes non-URL-safe characters that are percent-encoded by RFC6570 expansion; serializing values through both encodings is NOT RECOMMENDED." + }, + { + "id": "oas-3.1.percent-encoding-and-form-data.must-users-wishing-use-percent-encoding-way", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4627, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and `form-data`", + "anchor": "percent-encoding-and-form-data", + "level": "MUST", + "terms": ["MUST"], + "text": "Users wishing to use percent-encoding in this way MUST provide the data in percent-encoded form, as percent-encoding is not automatically applied for this media type regardless of which Encoding Object fields are used." + }, + { + "id": "oas-3.1.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4677, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", + "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "level": "MUST", + "terms": ["MUST"], + "text": "The `[`, `]`, `|`, and space characters, which are used as delimiters for the `deepObject`, `pipeDelimited`, and `spaceDelimited` styles, respectively, all MUST be percent-encoded to comply with [RFC3986]." + }, + { + "id": "oas-3.1.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4688, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", + "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For maximum interoperability, it is RECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely." + }, + { + "id": "oas-3.1.reference-object.$ref", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2720, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-ref", + "level": "field", + "terms": [], + "text": "REQUIRED. The reference identifier. This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.reference-object.$ref.must-form-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2720, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.1.reference-object.$ref.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2720, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-ref", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.reference-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2722, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-description", + "level": "field", + "terms": [], + "text": "A description which by default SHOULD override that of the referenced component. CommonMark syntax MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect." + }, + { + "id": "oas-3.1.reference-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2722, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.reference-object.description.should-description-default-override-referenced-component", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2722, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-description", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A description which by default SHOULD override that of the referenced component." + }, + { + "id": "oas-3.1.reference-object.fixed-fields.shall-object-cannot-extended-additional-properties-any", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2724, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "fixed-fields-19", + "level": "MUST", + "terms": ["SHALL"], + "text": "This object cannot be extended with additional properties, and any properties added SHALL be ignored." + }, + { + "id": "oas-3.1.reference-object.summary", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2721, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-summary", + "level": "field", + "terms": [], + "text": "A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect." + }, + { + "id": "oas-3.1.reference-object.summary.should-short-summary-default-override-referenced-component", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2721, + "section": "Specification > Schema > Reference Object > Fixed Fields", + "anchor": "reference-summary", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A short summary which by default SHOULD override that of the referenced component." + }, + { + "id": "oas-3.1.relative-references-in-api-description-uris.may-practice-usually-retrieval-uri-document-determined", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 294, + "section": "Specification > Relative References in API Description URIs", + "anchor": "relative-references-in-api-description-uris", + "level": "MAY", + "terms": ["MAY"], + "text": "In practice, this is usually the retrieval URI of the document, which MAY be determined based on either its current actual location or a user-supplied expected location." + }, + { + "id": "oas-3.1.relative-references-in-api-description-uris.may-unless-specified-otherwise-all-fields-uris", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 290, + "section": "Specification > Relative References in API Description URIs", + "anchor": "relative-references-in-api-description-uris", + "level": "MAY", + "terms": ["MAY"], + "text": "Unless specified otherwise, all fields that are URIs MAY be relative references as defined by RFC3986." + }, + { + "id": "oas-3.1.relative-references-in-api-description-uris.must-relative-uri-references-other-objects-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 294, + "section": "Specification > Relative References in API Description URIs", + "anchor": "relative-references-in-api-description-uris", + "level": "MUST", + "terms": ["MUST"], + "text": "Relative URI references in other Objects, and in Schema Objects where no parent schema contains an `$id`, MUST be resolved using the referring document's base URI, which is determined in accordance with [RFC3986] Section 5.1.2 – 5.1.4." + }, + { + "id": "oas-3.1.relative-references-in-api-description-uris.should-representation-referenced-document-json-yaml-fragment", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 297, + "section": "Specification > Relative References in API Description URIs", + "anchor": "relative-references-in-api-description-uris", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON-Pointer as per RFC6901." + }, + { + "id": "oas-3.1.relative-references-in-api-urls.may-note-themselves-relative-referring-document", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 305, + "section": "Specification > Relative References in API URLs", + "anchor": "relative-references-in-api-urls", + "level": "MAY", + "terms": ["MAY"], + "text": "Note that these themselves MAY be relative to the referring document." + }, + { + "id": "oas-3.1.relative-references-in-api-urls.may-unless-specified-otherwise-all-fields-urls", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 305, + "section": "Specification > Relative References in API URLs", + "anchor": "relative-references-in-api-urls", + "level": "MAY", + "terms": ["MAY"], + "text": "Unless specified otherwise, all fields that are URLs MAY be relative references as defined by RFC3986." + }, + { + "id": "oas-3.1.request-body-object.content", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1452, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-content", + "level": "field", + "terms": [], + "text": "REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined. For requests that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + }, + { + "id": "oas-3.1.request-body-object.content.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1452, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-content", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.request-body-object.content.should-map-have-least-one-entry-does", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1452, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-content", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined." + }, + { + "id": "oas-3.1.request-body-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1451, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-description", + "level": "field", + "terms": [], + "text": "A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.request-body-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1451, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.request-body-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1455, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "fixed-fields-10", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.request-body-object.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1453, + "section": "Specification > Schema > Request Body Object > Fixed Fields", + "anchor": "request-body-required", + "level": "field", + "terms": [], + "text": "Determines if the request body is required in the request. Defaults to `false`." + }, + { + "id": "oas-3.1.resolving-implicit-connections.recommended-consider-all-operation-objects-all-parsed", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 185, + "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is RECOMMENDED to consider all Operation Objects from all parsed documents when resolving any Link Object `operationId`." + }, + { + "id": "oas-3.1.resolving-implicit-connections.recommended-resolving-component-tag-name-connections-referenced", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 193, + "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For resolving component and tag name connections from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + }, + { + "id": "oas-3.1.resolving-implicit-connections.recommended-some-cases-unambiguous-uri-based-alternative", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 172, + "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "In some cases, an unambiguous URI-based alternative is available, and OAD authors are RECOMMENDED to always use the alternative:" + }, + { + "id": "oas-3.1.response-object.content", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2012, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-content", + "level": "field", + "terms": [], + "text": "A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + }, + { + "id": "oas-3.1.response-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2010, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "field", + "terms": [], + "text": "REQUIRED. A description of the response. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.response-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2010, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.response-object.description.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2010, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.response-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2015, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "fixed-fields-14", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.response-object.headers", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2011, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-headers", + "level": "field", + "terms": [], + "text": "Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + }, + { + "id": "oas-3.1.response-object.headers.shall-response-header-defined-name-content-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2011, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + }, + { + "id": "oas-3.1.response-object.links", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2013, + "section": "Specification > Schema > Response Object > Fixed Fields", + "anchor": "response-links", + "level": "field", + "terms": [], + "text": "A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects." + }, + { + "id": "oas-3.1.responses-object.default", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1947, + "section": "Specification > Schema > Responses Object > Fixed Fields", + "anchor": "responses-default", + "level": "field", + "terms": [], + "text": "The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses." + }, + { + "id": "oas-3.1.responses-object.may-default-used-default-response-object-all", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1936, + "section": "Specification > Schema > Responses Object", + "anchor": "responses-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object." + }, + { + "id": "oas-3.1.responses-object.must-responses-object-contain-least-one-response", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1939, + "section": "Specification > Schema > Responses Object", + "anchor": "responses-object", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call." + }, + { + "id": "oas-3.1.responses-object.pattern-http-status-code", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1953, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responses-code", + "level": "field", + "terms": [], + "text": "Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code." + }, + { + "id": "oas-3.1.responses-object.pattern-http-status-code.may-define-range-response-codes-field-contain", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1953, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responses-code", + "level": "MAY", + "terms": ["MAY"], + "text": "To define a range of response codes, this field MAY contain the uppercase wildcard character `X`." + }, + { + "id": "oas-3.1.responses-object.pattern-http-status-code.must-field-enclosed-quotation-marks-example-200", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1953, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "responses-code", + "level": "MUST", + "terms": ["MUST"], + "text": "This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML." + }, + { + "id": "oas-3.1.responses-object.patterned-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 1955, + "section": "Specification > Schema > Responses Object > Patterned Fields", + "anchor": "patterned-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.rich-text-formatting.may-tooling-choose-ignore-some-commonmark-extension", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 276, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "MAY", + "terms": ["MAY"], + "text": "Tooling MAY choose to ignore some CommonMark or extension features to address security concerns." + }, + { + "id": "oas-3.1.rich-text-formatting.may-while-framing-commonmark-0-27-minimum", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 279, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "MAY", + "terms": ["MAY"], + "text": "While the framing of CommonMark 0.27 as a minimum requirement means that tooling MAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable." + }, + { + "id": "oas-3.1.rich-text-formatting.must-openapi-tooling-renders-rich-text-support", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 276, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "MUST", + "terms": ["MUST"], + "text": "Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27." + }, + { + "id": "oas-3.1.rich-text-formatting.should-openapi-description-authors-consider-how-text", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 279, + "section": "Specification > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "OpenAPI Description authors SHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support." + }, + { + "id": "oas-3.1.schema-object.annotated-enumerations.may-implementations-support-recognizing-oneof-anyof-each", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2853, + "section": "Specification > Schema > Schema Object > Data Modeling Techniques > Annotated Enumerations", + "anchor": "annotated-enumerations", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support recognizing a `oneOf` or `anyOf` where each subschema in the keyword's array consists of a `const` keyword and annotations such as `title` or `description` as an enumerated type with additional information." + }, + { + "id": "oas-3.1.schema-object.composition-and-inheritance-polymorphism.must-discriminator-field-required-field", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2831, + "section": "Specification > Schema > Schema Object > Data Modeling Techniques > Composition and Inheritance (Polymorphism)", + "anchor": "composition-and-inheritance-polymorphism", + "level": "MUST", + "terms": ["MUST"], + "text": "As such, the `discriminator` field MUST be a required field." + }, + { + "id": "oas-3.1.schema-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2782, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.schema-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2782, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.schema-object.discriminator", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2794, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-discriminator", + "level": "field", + "terms": [], + "text": "Adds support for polymorphism. The discriminator is used to determine which of a set of schemas a payload is expected to satisfy. See Composition and Inheritance for more details." + }, + { + "id": "oas-3.1.schema-object.example", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2797, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-example", + "level": "field", + "terms": [], + "text": "A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. Deprecated: The `example` field has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it." + }, + { + "id": "oas-3.1.schema-object.extended-validation-with-annotations.may-oas-implementations-use-annotations-including-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2803, + "section": "Specification > Schema > Schema Object > Extended Validation with Annotations", + "anchor": "extended-validation-with-annotations", + "level": "MAY", + "terms": ["MAY"], + "text": "OAS implementations MAY use such annotations, including extensions not recognized as part of a declared JSON Schema vocabulary, as the basis for further validation." + }, + { + "id": "oas-3.1.schema-object.externalDocs", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2796, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this schema." + }, + { + "id": "oas-3.1.schema-object.fixed-fields.may-object-extended-specification-extensions-though-noted", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2799, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "fixed-fields-20", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions, though as noted, additional properties MAY omit the `x-` prefix within this object." + }, + { + "id": "oas-3.1.schema-object.format", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2783, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", + "terms": [], + "text": "See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats." + }, + { + "id": "oas-3.1.schema-object.generic-template-data-structures.may-implementations-support-defining-generic-template-data", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2842, + "section": "Specification > Schema > Schema Object > Data Modeling Techniques > Generic (Template) Data Structures", + "anchor": "generic-template-data-structures", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support defining generic or template data structures using JSON Schema's dynamic referencing feature:" + }, + { + "id": "oas-3.1.schema-object.json-schema-keywords.may-json-schema-implementations-choose-treat-keywords", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2787, + "section": "Specification > Schema > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MAY", + "terms": ["MAY"], + "text": "JSON Schema implementations MAY choose to treat keywords defined by the OpenAPI Specification's base vocabulary as unknown keywords, due to its inclusion in the OAS dialect with a `$vocabulary` value of `false`." + }, + { + "id": "oas-3.1.schema-object.may-empty-schema-allows-any-instance-validate", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2766, + "section": "Specification > Schema > Schema Object", + "anchor": "schema-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The empty schema (which allows any instance to validate) MAY be represented by the boolean value `true` and a schema which allows no instance to validate MAY be represented by the boolean value `false`." + }, + { + "id": "oas-3.1.schema-object.non-validating-constraint-keywords.may-extended-validation-one-way-constraints-enforced", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2809, + "section": "Specification > Schema > Schema Object > Extended Validation with Annotations > Non-validating constraint keywords", + "anchor": "non-validating-constraint-keywords", + "level": "MAY", + "terms": ["MAY"], + "text": "Extended validation is one way that these constraints MAY be enforced." + }, + { + "id": "oas-3.1.schema-object.specifying-schema-dialects.must-default-not-set-oas-dialect-schema", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2866, + "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "MUST", + "terms": ["MUST"], + "text": "If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects." + }, + { + "id": "oas-3.1.schema-object.specifying-schema-dialects.must-schema-keyword-present-any-schema-object", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2864, + "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "The `$schema` keyword MAY be present in any Schema Object that is a schema resource root, and if present MUST be used to determine which dialect should be used when processing the schema." + }, + { + "id": "oas-3.1.schema-object.specifying-schema-dialects.must-tooling-support-oas-dialect-schema-id", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2864, + "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`." + }, + { + "id": "oas-3.1.schema-object.specifying-schema-dialects.recommended-however-maximum-interoperability-openapi-description-authors", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2868, + "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, for maximum interoperability, it is RECOMMENDED that OpenAPI description authors explicitly set the dialect through `$schema` in such documents." + }, + { + "id": "oas-3.1.schema-object.specifying-schema-dialects.should-standalone-json-schema-documents-do-not", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2868, + "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "For standalone JSON Schema documents that do not set `$schema`, or for Schema Objects in OpenAPI description documents that are _not_ complete documents, the dialect SHOULD be assumed to be the OAS dialect." + }, + { + "id": "oas-3.1.schema-object.validating-readonly-and-writeonly.may-json-schema-validation-draft-2020-12", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2814, + "section": "Specification > Schema > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", + "anchor": "validating-readonly-and-writeonly", + "level": "MAY", + "terms": ["MAY"], + "text": "JSON Schema Validation Draft 2020-12 §9.4 defines the expectations of these keywords, including that a resource (described as the \"owning authority\") MAY either ignore a `readOnly` field or treat it as an error." + }, + { + "id": "oas-3.1.schema-object.validating-readonly-and-writeonly.may-validation-keywords-done-checking-annotation-read", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2814, + "section": "Specification > Schema > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", + "anchor": "validating-readonly-and-writeonly", + "level": "MAY", + "terms": ["MAY"], + "text": "Validation of these keywords MAY be done by checking the annotation, the read or write direction, and (if relevant) the current value of the field." + }, + { + "id": "oas-3.1.schema-object.xml", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2795, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-xml", + "level": "field", + "terms": [], + "text": "This MAY be used only on property schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property." + }, + { + "id": "oas-3.1.schema-object.xml.may-used-only-property-schemas", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2795, + "section": "Specification > Schema > Schema Object > Fixed Fields", + "anchor": "schema-xml", + "level": "MAY", + "terms": ["MAY"], + "text": "This MAY be used only on property schemas." + }, + { + "id": "oas-3.1.security-filtering.may-path-item-object-empty", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4225, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "The Path Item Object MAY be empty." + }, + { + "id": "oas-3.1.security-filtering.may-paths-object-present-but-empty", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4224, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "The Paths Object MAY be present but empty." + }, + { + "id": "oas-3.1.security-filtering.may-some-objects-openapi-specification-declared-remain", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4217, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation." + }, + { + "id": "oas-3.1.security-filtering.may-while-not-part-specification-itself-certain", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4219, + "section": "Specification > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization." + }, + { + "id": "oas-3.1.security-requirement-object.must-name-used-each-property-correspond-security", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4128, + "section": "Specification > Schema > Security Requirement Object", + "anchor": "security-requirement-object", + "level": "MUST", + "terms": ["MUST"], + "text": "The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object." + }, + { + "id": "oas-3.1.security-requirement-object.must-security-requirement-object-refer-multiple-security", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4131, + "section": "Specification > Schema > Security Requirement Object", + "anchor": "security-requirement-object", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized." + }, + { + "id": "oas-3.1.security-requirement-object.pattern-name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4143, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "field", + "terms": [], + "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object. If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + }, + { + "id": "oas-3.1.security-requirement-object.pattern-name.may-other-security-scheme-types-array-contain", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4143, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MAY", + "terms": ["MAY"], + "text": "For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + }, + { + "id": "oas-3.1.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4143, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MAY", + "terms": ["MAY"], + "text": "If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope." + }, + { + "id": "oas-3.1.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4143, + "section": "Specification > Schema > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MUST", + "terms": ["MUST"], + "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object." + }, + { + "id": "oas-3.1.security-scheme-object.bearerFormat", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3960, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-bearer-format", + "level": "field", + "terms": [], + "text": "A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes." + }, + { + "id": "oas-3.1.security-scheme-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3956, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-description", + "level": "field", + "terms": [], + "text": "A description for security scheme. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3956, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.security-scheme-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3964, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "fixed-fields-23", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.security-scheme-object.flows", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3961, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-flows", + "level": "field", + "terms": [], + "text": "REQUIRED. An object containing configuration information for the flow types supported." + }, + { + "id": "oas-3.1.security-scheme-object.flows.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3961, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-flows", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.security-scheme-object.in", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3958, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-in", + "level": "field", + "terms": [], + "text": "REQUIRED. The location of the API key. Valid values are `\"query\"`, `\"header\"`, or `\"cookie\"`." + }, + { + "id": "oas-3.1.security-scheme-object.in.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3958, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-in", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.security-scheme-object.name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3957, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the header, query or cookie parameter to be used." + }, + { + "id": "oas-3.1.security-scheme-object.name.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3957, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.security-scheme-object.openIdConnectUrl", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3962, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-open-id-connect-url", + "level": "field", + "terms": [], + "text": "REQUIRED. Well-known URL to discover the [OpenID-Connect-Discovery] provider metadata." + }, + { + "id": "oas-3.1.security-scheme-object.openIdConnectUrl.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3962, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-open-id-connect-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.security-scheme-object.scheme", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3959, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry. The value is case-insensitive, as defined in RFC7235." + }, + { + "id": "oas-3.1.security-scheme-object.scheme.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3959, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3959, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The values used SHOULD be registered in the IANA Authentication Scheme registry." + }, + { + "id": "oas-3.1.security-scheme-object.type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3955, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-type", + "level": "field", + "terms": [], + "text": "REQUIRED. The type of the security scheme. Valid values are `\"apiKey\"`, `\"http\"`, `\"mutualTLS\"`, `\"oauth2\"`, `\"openIdConnect\"`." + }, + { + "id": "oas-3.1.security-scheme-object.type.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3955, + "section": "Specification > Schema > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-type", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.server-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 460, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-description", + "level": "field", + "terms": [], + "text": "An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.server-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 460, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.server-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 463, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "fixed-fields-3", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.server-object.url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 459, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "field", + "terms": [], + "text": "REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Query and fragment MUST NOT be part of this URL. Variable substitutions will be made when a variable is named in `{`braces`}`." + }, + { + "id": "oas-3.1.server-object.url.may-url-supports-server-variables-relative-indicate", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 459, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "MAY", + "terms": ["MAY"], + "text": "This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served." + }, + { + "id": "oas-3.1.server-object.url.must-not-query-fragment-part-url", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 459, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Query and fragment MUST NOT be part of this URL." + }, + { + "id": "oas-3.1.server-object.url.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 459, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.server-object.variables", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 461, + "section": "Specification > Schema > Server Object > Fixed Fields", + "anchor": "server-variables", + "level": "field", + "terms": [], + "text": "A map between a variable name and its value. The value is used for substitution in the server's URL template." + }, + { + "id": "oas-3.1.server-variable-object.default", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 566, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "field", + "terms": [], + "text": "REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the `enum` is defined, the value MUST exist in the enum's values. Note that this behavior is different from the Schema Object's `default` keyword, which documents the receiver's behavior rather than inserting the value into the data." + }, + { + "id": "oas-3.1.server-variable-object.default.must-enum-defined-value-exist-enum-s", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 566, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["MUST"], + "text": "If the `enum` is defined, the value MUST exist in the enum's values." + }, + { + "id": "oas-3.1.server-variable-object.default.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 566, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 566, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["SHALL"], + "text": "The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied." + }, + { + "id": "oas-3.1.server-variable-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 567, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-description", + "level": "field", + "terms": [], + "text": "An optional description for the server variable. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 567, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.server-variable-object.enum", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 565, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-enum", + "level": "field", + "terms": [], + "text": "An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty." + }, + { + "id": "oas-3.1.server-variable-object.enum.must-not-array-empty", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 565, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "server-variable-enum", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The array MUST NOT be empty." + }, + { + "id": "oas-3.1.server-variable-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 569, + "section": "Specification > Schema > Server Variable Object > Fixed Fields", + "anchor": "fixed-fields-4", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.specification-extensions.optional-support-any-one-extension-support-one", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4213, + "section": "Specification > Specification Extensions", + "anchor": "specification-extensions", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Support for any one extension is OPTIONAL, and support for one extension does not imply support for others." + }, + { + "id": "oas-3.1.specification-extensions.pattern-x", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4206, + "section": "Specification > Specification Extensions", + "anchor": "extension-properties", + "level": "field", + "terms": [], + "text": "Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the OpenAPI Initiative. The value can be any valid JSON value (`null`, a primitive, an array, or an object.)" + }, + { + "id": "oas-3.1.specification-extensions.pattern-x.must-field-name-begin-x-example-x", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4206, + "section": "Specification > Specification Extensions", + "anchor": "extension-properties", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + }, + { + "id": "oas-3.1.specification-extensions.recommended-therefore-implementations-designed-extensibility-support-community", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 4210, + "section": "Specification > Specification Extensions", + "anchor": "specification-extensions", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is therefore RECOMMENDED that implementations be designed for extensibility to support community experimentation." + }, + { + "id": "oas-3.1.specification.schema.must-json-schema-differs-section-section-considered", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 310, + "section": "Specification > Schema", + "anchor": "schema-0", + "level": "MUST", + "terms": ["MUST"], + "text": "If the JSON Schema differs from this section, then this section MUST be considered authoritative." + }, + { + "id": "oas-3.1.specification.schema.required-following-description-field-not-explicitly-described", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 315, + "section": "Specification > Schema", + "anchor": "schema-0", + "level": "MUST", + "terms": ["REQUIRED", "MUST", "SHALL", "OPTIONAL"], + "text": "In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL." + }, + { + "id": "oas-3.1.structural-interoperability.may-same-json-yaml-object-parsed-multiple", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 166, + "section": "Specification > OpenAPI Description Structure > Structural Interoperability", + "anchor": "structural-interoperability", + "level": "MAY", + "terms": ["MAY"], + "text": "If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed as _different_ Object types, the resulting behavior is _implementation defined_, and MAY be treated as an error if detected." + }, + { + "id": "oas-3.1.structural-interoperability.recommended-maximum-interoperability-openapi-description-authors-avoid", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 166, + "section": "Specification > OpenAPI Description Structure > Structural Interoperability", + "anchor": "structural-interoperability", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For maximum interoperability, it is RECOMMENDED that OpenAPI Description authors avoid such scenarios." + }, + { + "id": "oas-3.1.tag-object.description", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2689, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-description", + "level": "field", + "terms": [], + "text": "A description for the tag. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.tag-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2689, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.1.tag-object.externalDocs", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2690, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this tag." + }, + { + "id": "oas-3.1.tag-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2692, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "fixed-fields-18", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.tag-object.name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2688, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the tag." + }, + { + "id": "oas-3.1.tag-object.name.required", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 2688, + "section": "Specification > Schema > Tag Object > Fixed Fields", + "anchor": "tag-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.1.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 82, + "section": "Definitions > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification." + }, + { + "id": "oas-3.1.undefined-and-implementation-defined-behavior.not-recommended-support-might-produce-correct-outcomes-many", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 82, + "section": "Definitions > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "This support might produce correct outcomes in many cases, but relying on it is NOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one." + }, + { + "id": "oas-3.1.undefined-and-implementation-defined-behavior.recommended-documents-ambiguous-requirements-api-description-authors", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 87, + "section": "Definitions > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "This documents ambiguous requirements that API description authors are RECOMMENDED to avoid in order to maximize interoperability." + }, + { + "id": "oas-3.1.versions.shall-major-minor-portion-version-string-example", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 95, + "section": "Specification > Versions", + "anchor": "versions", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set." + }, + { + "id": "oas-3.1.versions.should-not-patch-version-considered-tooling-making-no", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 95, + "section": "Specification > Versions", + "anchor": "versions", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example." + }, + { + "id": "oas-3.1.versions.should-tooling-supports-oas-3-1-compatible", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 95, + "section": "Specification > Versions", + "anchor": "versions", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.* versions." + }, + { + "id": "oas-3.1.working-with-binary-data.may-maxlength-keyword-used-set-expected-upper", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 263, + "section": "Specification > Data Types > Working with Binary Data", + "anchor": "working-with-binary-data", + "level": "MAY", + "terms": ["MAY"], + "text": "The `maxLength` keyword MAY be used to set an expected upper bound on the length of a streaming payload." + }, + { + "id": "oas-3.1.working-with-binary-data.shall-however-contentmediatype-contradicts-relevant-media-type", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 261, + "section": "Specification > Data Types > Working with Binary Data", + "anchor": "working-with-binary-data", + "level": "MUST", + "terms": ["SHALL"], + "text": "However, if `contentMediaType` contradicts a relevant Media Type Object or Encoding Object, then `contentMediaType` SHALL be ignored." + }, + { + "id": "oas-3.1.xml-object.attribute", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3496, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-attribute", + "level": "field", + "terms": [], + "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`." + }, + { + "id": "oas-3.1.xml-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3499, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "fixed-fields-22", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.1.xml-object.handling-null-values.recommended-however-because-no-distinct-way-represent", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3518, + "section": "Specification > Schema > XML Object > Handling `null` Values", + "anchor": "handling-null-values", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, because there is no distinct way to represent `null` as an attribute, it is RECOMMENDED to make attribute properties optional rather than use `null`." + }, + { + "id": "oas-3.1.xml-object.handling-null-values.should-ensure-correct-round-trip-behavior-parsing", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3522, + "section": "Specification > Schema > XML Object > Handling `null` Values", + "anchor": "handling-null-values", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "To ensure correct round-trip behavior, when parsing an element that omits an attribute, implementations SHOULD set the corresponding property to `null` if the schema allows for that value (e.g. `type: [\"number\", \"null\"]`), and omit the property otherwise (e.g.`type: \"number\"`)." + }, + { + "id": "oas-3.1.xml-object.handling-null-values.should-however-implementations-handle-null-values-follows", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3513, + "section": "Specification > Schema > XML Object > Handling `null` Values", + "anchor": "handling-null-values", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "However, implementations SHOULD handle `null` values as follows:" + }, + { + "id": "oas-3.1.xml-object.name", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3493, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-name", + "level": "field", + "terms": [], + "text": "Replaces the inferred name of the element/attribute used for the described schema property. For the root schema object of a schema component, the inferred name is the name of the component; for other schemas the name is inferred from the parent property name. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `\"array\"` (outside the `items`), it will affect the wrapping element if and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored." + }, + { + "id": "oas-3.1.xml-object.namespace", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3494, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-namespace", + "level": "field", + "terms": [], + "text": "The URI of the namespace definition. Value MUST be in the form of a non-relative URI." + }, + { + "id": "oas-3.1.xml-object.namespace.must-value-form-non-relative-uri", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3494, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-namespace", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be in the form of a non-relative URI." + }, + { + "id": "oas-3.1.xml-object.prefix", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3495, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-prefix", + "level": "field", + "terms": [], + "text": "The prefix to be used for the name." + }, + { + "id": "oas-3.1.xml-object.should-using-arrays-xml-element-names-not", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3486, + "section": "Specification > Schema > XML Object", + "anchor": "xml-object", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` field SHOULD be used to add that information." + }, + { + "id": "oas-3.1.xml-object.wrapped", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3497, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-wrapped", + "level": "field", + "terms": [], + "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `\"array\"` (outside the `items`)." + }, + { + "id": "oas-3.1.xml-object.wrapped.may-used-only-array-definition", + "spec": "openapi", + "version": "3.1.2", + "source": "openapi/3.1.2.md", + "line": 3497, + "section": "Specification > Schema > XML Object > Fixed Fields", + "anchor": "xml-wrapped", + "level": "MAY", + "terms": ["MAY"], + "text": "MAY be used only for an array definition." + }, + { + "id": "oas-3.2.appendix-c-using-rfc6570-based-serialization.may-implementations-specification-use-implementation-rfc6570-perform", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4893, + "section": "Appendix C: Using RFC6570-Based Serialization", + "anchor": "appendix-c-using-rfc6570-based-serialization", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations of this specification MAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply." + }, + { + "id": "oas-3.2.appendix-e-percent-encoding-and-form-media-types.must-set-characters-encoded-varies-depending-version", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5170, + "section": "Appendix E: Percent-Encoding and Form Media Types", + "anchor": "appendix-e-percent-encoding-and-form-media-types", + "level": "MUST", + "terms": ["MUST"], + "text": "The set of characters that MUST be encoded varies depending on which version of which specification you use, and (for URIs) in which part of the URI the character appears." + }, + { + "id": "oas-3.2.appendix-g-parsing-and-resolution-guidance.may-implementations-support-complete-document-parsing-any", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5482, + "section": "Appendix G: Parsing and Resolution Guidance", + "anchor": "appendix-g-parsing-and-resolution-guidance", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support complete-document parsing in any of the following ways:" + }, + { + "id": "oas-3.2.base-uri-within-content.must-guarantee-interoperability-schema-objects-containing-id", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5324, + "section": "Appendix F: Examples of Base URI Determination and Reference Resolution > Base URI Within Content", + "anchor": "base-uri-within-content", + "level": "MUST", + "terms": ["MUST"], + "text": "To guarantee interoperability, Schema Objects containing an `$id`, or that are under a schema containing an `$id`, MUST be referenced by the nearest such `$id` for the non-fragment part of the reference." + }, + { + "id": "oas-3.2.callback-object.pattern-expression", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2259, + "section": "Objects and Fields > Callback Object > Patterned Fields", + "anchor": "callback-expression", + "level": "field", + "terms": [], + "text": "A Path Item Object used to define a callback request and expected responses. A complete example is available." + }, + { + "id": "oas-3.2.callback-object.patterned-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2261, + "section": "Objects and Fields > Callback Object > Patterned Fields", + "anchor": "patterned-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.components-object.callbacks", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 412, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-callbacks", + "level": "field", + "terms": [], + "text": "An object to hold reusable Callback Objects." + }, + { + "id": "oas-3.2.components-object.examples", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 407, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-examples", + "level": "field", + "terms": [], + "text": "An object to hold reusable Example Objects." + }, + { + "id": "oas-3.2.components-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 416, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "fixed-fields-5", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.components-object.fixed-fields.must-all-fixed-fields-declared-above-objects", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 418, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "fixed-fields-5", + "level": "MUST", + "terms": ["MUST"], + "text": "All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\\.\\-_]+$`." + }, + { + "id": "oas-3.2.components-object.headers", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 409, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-headers", + "level": "field", + "terms": [], + "text": "An object to hold reusable Header Objects." + }, + { + "id": "oas-3.2.components-object.links", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 411, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-links", + "level": "field", + "terms": [], + "text": "An object to hold reusable Link Objects." + }, + { + "id": "oas-3.2.components-object.mediaTypes", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 414, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-media-types", + "level": "field", + "terms": [], + "text": "An object to hold reusable Media Type Objects." + }, + { + "id": "oas-3.2.components-object.parameters", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 406, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-parameters", + "level": "field", + "terms": [], + "text": "An object to hold reusable Parameter Objects." + }, + { + "id": "oas-3.2.components-object.pathItems", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 413, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-path-items", + "level": "field", + "terms": [], + "text": "An object to hold reusable Path Item Objects." + }, + { + "id": "oas-3.2.components-object.requestBodies", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 408, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-request-bodies", + "level": "field", + "terms": [], + "text": "An object to hold reusable Request Body Objects." + }, + { + "id": "oas-3.2.components-object.responses", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 405, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-responses", + "level": "field", + "terms": [], + "text": "An object to hold reusable Response Objects." + }, + { + "id": "oas-3.2.components-object.schemas", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 404, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-schemas", + "level": "field", + "terms": [], + "text": "An object to hold reusable Schema Objects." + }, + { + "id": "oas-3.2.components-object.securitySchemes", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 410, + "section": "Objects and Fields > Components Object > Fixed Fields", + "anchor": "components-security-schemes", + "level": "field", + "terms": [], + "text": "An object to hold reusable Security Scheme Objects." + }, + { + "id": "oas-3.2.conditions-for-using-the-discriminator-object.may-avoid-redundancy-discriminator-added-parent-schema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3652, + "section": "Objects and Fields > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", + "level": "MAY", + "terms": ["MAY"], + "text": "To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas building on the parent schema via an `allOf` construct may be used as an alternate schema." + }, + { + "id": "oas-3.2.conditions-for-using-the-discriminator-object.must-both-oneof-anyof-use-cases-keywords", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3650, + "section": "Objects and Fields > Discriminator Object > Conditions for Using the Discriminator Object", + "anchor": "conditions-for-using-the-discriminator-object", + "level": "MUST", + "terms": ["MUST"], + "text": "In both the `oneOf` and `anyOf` use cases, where those keywords are adjacent to `discriminator`, all possible schemas MUST be listed explicitly." + }, + { + "id": "oas-3.2.conflicts-between-field-types-and-reference-contexts.may-same-json-yaml-object-parsed-multiple", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5510, + "section": "Appendix G: Parsing and Resolution Guidance > Conflicts Between Field Types and Reference Contexts", + "anchor": "conflicts-between-field-types-and-reference-contexts", + "level": "MAY", + "terms": ["MAY"], + "text": "If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed as _different_ Object types, the resulting behavior is _implementation defined_, and MAY be treated as an error if detected." + }, + { + "id": "oas-3.2.conflicts-between-field-types-and-reference-contexts.recommended-maximum-interoperability-openapi-description-authors-avoid", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5510, + "section": "Appendix G: Parsing and Resolution Guidance > Conflicts Between Field Types and Reference Contexts", + "anchor": "conflicts-between-field-types-and-reference-contexts", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For maximum interoperability, it is RECOMMENDED that OpenAPI Description authors avoid such scenarios." + }, + { + "id": "oas-3.2.contact-object.email", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 229, + "section": "Objects and Fields > Contact Object > Fixed Fields", + "anchor": "contact-email", + "level": "field", + "terms": [], + "text": "The email address of the contact person/organization. This MUST be in the form of an email address." + }, + { + "id": "oas-3.2.contact-object.email.must-form-email-address", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 229, + "section": "Objects and Fields > Contact Object > Fixed Fields", + "anchor": "contact-email", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of an email address." + }, + { + "id": "oas-3.2.contact-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 231, + "section": "Objects and Fields > Contact Object > Fixed Fields", + "anchor": "fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.contact-object.name", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 227, + "section": "Objects and Fields > Contact Object > Fixed Fields", + "anchor": "contact-name", + "level": "field", + "terms": [], + "text": "The identifying name of the contact person/organization." + }, + { + "id": "oas-3.2.contact-object.url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 228, + "section": "Objects and Fields > Contact Object > Fixed Fields", + "anchor": "contact-url", + "level": "field", + "terms": [], + "text": "The URI for the contact information. This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.contact-object.url.must-form-uri", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 228, + "section": "Objects and Fields > Contact Object > Fixed Fields", + "anchor": "contact-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.discriminator-object.defaultMapping", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3642, + "section": "Objects and Fields > Discriminator Object > Fixed Fields", + "anchor": "discriminator-default-mapping", + "level": "field", + "terms": [], + "text": "The schema name or URI reference to a schema that is expected to validate the structure of the model when the discriminating property is not present in the payload or contains a value for which there is no explicit or implicit mapping." + }, + { + "id": "oas-3.2.discriminator-object.examples.may-oas-3-x-response-payload-described", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3695, + "section": "Objects and Fields > Discriminator Object > Examples", + "anchor": "examples-0", + "level": "MAY", + "terms": ["MAY"], + "text": "In OAS 3.x, a response payload MAY be described to be exactly one of any number of types:" + }, + { + "id": "oas-3.2.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3744, + "section": "Objects and Fields > Discriminator Object > Examples", + "anchor": "examples-0", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail." + }, + { + "id": "oas-3.2.discriminator-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3644, + "section": "Objects and Fields > Discriminator Object > Fixed Fields", + "anchor": "fixed-fields-21", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.discriminator-object.mapping", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3641, + "section": "Objects and Fields > Discriminator Object > Fixed Fields", + "anchor": "discriminator-mapping", + "level": "field", + "terms": [], + "text": "An object to hold mappings between payload values and schema names or URI references." + }, + { + "id": "oas-3.2.discriminator-object.may-polymorphic-schema-include-discriminator-object-defines", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3630, + "section": "Objects and Fields > Discriminator Object", + "anchor": "discriminator-object", + "level": "MAY", + "terms": ["MAY"], + "text": "A polymorphic schema MAY include a Discriminator Object, which defines the name of the property that may be used as a hint for which schema of the `anyOf` or `oneOf`, or which schema that references the current schema in an `allOf`, is expected to validate the structure of the model." + }, + { + "id": "oas-3.2.discriminator-object.must-not-note-discriminator-change-validation-outcome-schema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3634, + "section": "Objects and Fields > Discriminator Object", + "anchor": "discriminator-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Note that `discriminator` MUST NOT change the validation outcome of the schema." + }, + { + "id": "oas-3.2.discriminator-object.optional-discriminating-property.must-discriminating-property-defined-optional-discriminator-object", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3672, + "section": "Objects and Fields > Discriminator Object > Optional Discriminating Property", + "anchor": "optional-discriminating-property", + "level": "MUST", + "terms": ["MUST"], + "text": "When the discriminating property is defined as optional, the Discriminator Object MUST include a `defaultMapping` field that specifies a schema that is expected to validate the structure of the model when the discriminating property is not present in the payload or contains a value for which there is no explicit or implicit mapping." + }, + { + "id": "oas-3.2.discriminator-object.options-for-mapping-values-to-schemas.must-ensure-ambiguous-value-e-g-foo", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3661, + "section": "Objects and Fields > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "MUST", + "terms": ["MUST"], + "text": "To ensure that an ambiguous value (e.g. `\"foo\"`) is treated as a relative URI reference by all implementations, authors MUST prefix it with the `\".\"` path segment (e.g. `\"./foo\"`)." + }, + { + "id": "oas-3.2.discriminator-object.options-for-mapping-values-to-schemas.must-mapping-keys-string-values-but-tooling", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3667, + "section": "Objects and Fields > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison." + }, + { + "id": "oas-3.2.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-defaultmapping-value-both", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3661, + "section": "Objects and Fields > Discriminator Object > Options for Mapping Values to Schemas", + "anchor": "options-for-mapping-values-to-schemas", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "The behavior of a `mapping` value or `defaultMapping` value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it is RECOMMENDED that it be treated as a schema name." + }, + { + "id": "oas-3.2.discriminator-object.propertyName", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3640, + "section": "Objects and Fields > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the discriminating property in the payload that will hold the discriminating value. The discriminating property MAY be defined as required or optional, but when defined as optional the Discriminator Object MUST include a `defaultMapping` field that specifies which schema is expected to validate the structure of the model when the discriminating property is not present." + }, + { + "id": "oas-3.2.discriminator-object.propertyName.must-discriminating-property-defined-required-optional-but", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3640, + "section": "Objects and Fields > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "The discriminating property MAY be defined as required or optional, but when defined as optional the Discriminator Object MUST include a `defaultMapping` field that specifies which schema is expected to validate the structure of the model when the discriminating property is not present." + }, + { + "id": "oas-3.2.discriminator-object.propertyName.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3640, + "section": "Objects and Fields > Discriminator Object > Fixed Fields", + "anchor": "property-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.encoding-object.allowReserved", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1763, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "field", + "terms": [], + "text": "When this is true, values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the target media type; see URL Percent-Encoding for details. The default value is `false`. This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.2.encoding-object.allowReserved.shall-field-ignored-media-type-not-application", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1763, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + }, + { + "id": "oas-3.2.encoding-object.allowReserved.shall-value-explicitly-defined-value-contenttype-implicit", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1763, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-allow-reserved", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.2.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1719, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used either with or without the RFC6570-style serialization fields defined in the next section below." + }, + { + "id": "oas-3.2.encoding-object.common-fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1729, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.encoding-object.content-transfer-encoding-and-contentencoding.not-recommended-because-because-encoding-object-s-contenttype", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1881, + "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > `Content-Transfer-Encoding` and `contentEncoding`", + "anchor": "content-transfer-encoding-and-contentencoding", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Because of this, and because the Encoding Object's `contentType` defaulting rules do not take the Schema Object's `contentMediaType` into account, the use of `contentMediaType` with an Encoding Object is NOT RECOMMENDED." + }, + { + "id": "oas-3.2.encoding-object.content-transfer-encoding-and-contentencoding.shall-note-stated-working-binary-data-encoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1881, + "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > `Content-Transfer-Encoding` and `contentEncoding`", + "anchor": "content-transfer-encoding-and-contentencoding", + "level": "MUST", + "terms": ["SHALL"], + "text": "Note that as stated in Working with Binary Data, if the Encoding Object's `contentType`, whether set explicitly or implicitly through its default value rules, disagrees with the `contentMediaType` in a Schema Object, the `contentMediaType` SHALL be ignored." + }, + { + "id": "oas-3.2.encoding-object.contentType", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1723, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-content-type", + "level": "field", + "terms": [], + "text": "The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a media type range (e.g. `image/*`). The default value depends on the type as shown in the table below." + }, + { + "id": "oas-3.2.encoding-object.encoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1725, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-encoding", + "level": "field", + "terms": [], + "text": "Applies nested Encoding Objects in the same manner as the Media Type Object's `encoding` field." + }, + { + "id": "oas-3.2.encoding-object.encoding-the-x-www-form-urlencoded-media-type.must-configuration-means-content-percent-encoded-per", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1778, + "section": "Objects and Fields > Encoding Object > Encoding the `x-www-form-urlencoded` Media Type", + "anchor": "encoding-the-x-www-form-urlencoded-media-type", + "level": "MUST", + "terms": ["MUST"], + "text": "This configuration means that the content MUST be percent-encoded per [WHATWG-URL]'s rules for that media type, after any complex objects have been serialized to a string representation." + }, + { + "id": "oas-3.2.encoding-object.explode", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1762, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", + "level": "field", + "terms": [], + "text": "When this is true, values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties, or when `style` is `\"deepObject\"`, this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.2.encoding-object.explode.shall-field-ignored-media-type-not-application", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1762, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + }, + { + "id": "oas-3.2.encoding-object.explode.shall-value-explicitly-defined-value-contenttype-implicit", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1762, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-explode", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.2.encoding-object.fixed-fields-for-rfc6570-style-serialization.must-not-using-rfc6570-style-serialization-multipart-form", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1765, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "fixed-fields-for-rfc6570-style-serialization", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "When using RFC6570-style serialization for `multipart/form-data`, URI percent-encoding MUST NOT be applied, and the value of `allowReserved` has no effect." + }, + { + "id": "oas-3.2.encoding-object.handling-multiple-contenttype-values.must-encoding-serialization-implementations-provide-mechanism-applications", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1873, + "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > Handling Multiple `contentType` Values", + "anchor": "handling-multiple-contenttype-values", + "level": "MUST", + "terms": ["MUST"], + "text": "For encoding and serialization, implementations MUST provide a mechanism for applications to indicate which media type is intended." + }, + { + "id": "oas-3.2.encoding-object.handling-multiple-contenttype-values.must-not-implementations-choose-offer-media-type-sniffing", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1873, + "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > Handling Multiple `contentType` Values", + "anchor": "handling-multiple-contenttype-values", + "level": "MUST", + "terms": ["MAY", "MUST NOT"], + "text": "Implementations MAY choose to offer media type sniffing ([SNIFF]) as an alternative, but this MUST NOT be the default behavior due to the security risks inherent in the process." + }, + { + "id": "oas-3.2.encoding-object.headers", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1724, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "field", + "terms": [], + "text": "A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the media type is not a `multipart`." + }, + { + "id": "oas-3.2.encoding-object.headers.shall-content-type-described-separately-ignored-section", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1724, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "`Content-Type` is described separately and SHALL be ignored in this section." + }, + { + "id": "oas-3.2.encoding-object.headers.shall-field-ignored-media-type-not-multipart", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1724, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-headers", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the media type is not a `multipart`." + }, + { + "id": "oas-3.2.encoding-object.itemEncoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1727, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-item-encoding", + "level": "field", + "terms": [], + "text": "Applies nested Encoding Objects in the same manner as the Media Type Object's `itemEncoding` field." + }, + { + "id": "oas-3.2.encoding-object.nested-encoding.must-implementations-support-one-level-nesting-support", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1773, + "section": "Objects and Fields > Encoding Object > Nested Encoding", + "anchor": "nested-encoding", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "Implementations MUST support one level of nesting, and MAY support additional levels." + }, + { + "id": "oas-3.2.encoding-object.prefixEncoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1726, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", + "anchor": "encoding-prefix-encoding", + "level": "field", + "terms": [], + "text": "Applies nested Encoding Objects in the same manner as the Media Type Object's `prefixEncoding` field." + }, + { + "id": "oas-3.2.encoding-object.style", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1761, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "field", + "terms": [], + "text": "Describes how a specific value will be serialized depending on its type. See Parameter Object for details on the `style` field. The behavior follows the same values as `query` parameters, including the default value of `\"form\"` which applies only when `contentType` is _not_ being used due to one or both of `explode` or `allowReserved` being explicitly specified. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.2.encoding-object.style.must-note-initial-used-query-strings-not", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1761, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["MUST"], + "text": "Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually)." + }, + { + "id": "oas-3.2.encoding-object.style.shall-field-ignored-media-type-not-application", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1761, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + }, + { + "id": "oas-3.2.encoding-object.style.shall-value-explicitly-defined-value-contenttype-implicit", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1761, + "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", + "anchor": "encoding-style", + "level": "MUST", + "terms": ["SHALL"], + "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + }, + { + "id": "oas-3.2.example-object.choosing-which-field-s-to-use.must-serializedvalue-externalvalue-fields-both-show-serialized", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2403, + "section": "Objects and Fields > Example Object > Working with Examples > Choosing Which Field(s) to Use", + "anchor": "choosing-which-field-s-to-use", + "level": "MUST", + "terms": ["MUST"], + "text": "The `serializedValue` and `externalValue` fields both MUST show the serialized form of the data." + }, + { + "id": "oas-3.2.example-object.criteria-for-serializedvalue.should-externalvalue-character-set-neither-explicitly-stated", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2417, + "section": "Objects and Fields > Example Object > Working with Examples > Criteria for `serializedValue`", + "anchor": "criteria-for-serializedvalue", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "For `externalValue`, if the character set is neither explicitly stated nor determined by the format or media type specification, implementations SHOULD assume UTF-8." + }, + { + "id": "oas-3.2.example-object.dataValue", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2357, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-data-value", + "level": "field", + "terms": [], + "text": "An example of the data structure that MUST be valid according to the relevant Schema Object. If this field is present, `value` MUST be absent." + }, + { + "id": "oas-3.2.example-object.dataValue.must-example-data-structure-valid-according-relevant", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2357, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-data-value", + "level": "MUST", + "terms": ["MUST"], + "text": "An example of the data structure that MUST be valid according to the relevant Schema Object." + }, + { + "id": "oas-3.2.example-object.dataValue.must-field-present-value-absent", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2357, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-data-value", + "level": "MUST", + "terms": ["MUST"], + "text": "If this field is present, `value` MUST be absent." + }, + { + "id": "oas-3.2.example-object.description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2356, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-description", + "level": "field", + "terms": [], + "text": "Long description for the example. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.example-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2356, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.example-object.externalValue", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2359, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-external-value", + "level": "field", + "terms": [], + "text": "A URI that identifies the serialized example in a separate document, allowing for values not easily or readably expressed as a Unicode string. If `dataValue` is present, then this field SHOULD identify a serialization of the given data. Otherwise, the value SHOULD identify the valid serialization of a data value that itself MUST be valid as described for `dataValue`. If this field is present, `serializedValue` and `value` MUST be absent. See also the rules for resolving Relative References." + }, + { + "id": "oas-3.2.example-object.externalValue.must-field-present-serializedvalue-value-absent", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2359, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-external-value", + "level": "MUST", + "terms": ["MUST"], + "text": "If this field is present, `serializedValue` and `value` MUST be absent." + }, + { + "id": "oas-3.2.example-object.externalValue.must-otherwise-value-identify-valid-serialization-data", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2359, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-external-value", + "level": "MUST", + "terms": ["SHOULD", "MUST"], + "text": "Otherwise, the value SHOULD identify the valid serialization of a data value that itself MUST be valid as described for `dataValue`." + }, + { + "id": "oas-3.2.example-object.externalValue.should-datavalue-present-field-identify-serialization-given", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2359, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-external-value", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If `dataValue` is present, then this field SHOULD identify a serialization of the given data." + }, + { + "id": "oas-3.2.example-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2362, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.example-object.fixed-fields.may-tooling-implementations-choose-validate-compatibility-automatically", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2364, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "MAY", + "terms": ["MAY"], + "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + }, + { + "id": "oas-3.2.example-object.fixed-fields.should-all-cases-example-value-compatible-schema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2364, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "fixed-fields-15", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In all cases, the example value SHOULD be compatible with the schema of its associated value." + }, + { + "id": "oas-3.2.example-object.json-compatible-and-value-safe-examples.should-practice-resulted-value-shorthand-example-fields", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2383, + "section": "Objects and Fields > Example Object > Working with Examples > JSON-Compatible and `value`-Safe Examples", + "anchor": "json-compatible-and-value-safe-examples", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In practice, this has resulted in the `value` and shorthand `example` fields having implementation-defined behavior for non-JSON targets; OAD authors SHOULD use other fields to ensure interoperability." + }, + { + "id": "oas-3.2.example-object.serializedValue", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2358, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-serialized-value", + "level": "field", + "terms": [], + "text": "An example of the serialized form of the value, including encoding and escaping as described under Validating Examples. If `dataValue` is present, then this field SHOULD contain the serialization of the given data. Otherwise, it SHOULD be the valid serialization of a data value that itself MUST be valid as described for `dataValue`. This field SHOULD NOT be used if the serialization format is JSON, as the data form is easier to work with. If this field is present, `value`, and `externalValue` MUST be absent." + }, + { + "id": "oas-3.2.example-object.serializedValue.must-field-present-value-externalvalue-absent", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2358, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-serialized-value", + "level": "MUST", + "terms": ["MUST"], + "text": "If this field is present, `value`, and `externalValue` MUST be absent." + }, + { + "id": "oas-3.2.example-object.serializedValue.must-otherwise-valid-serialization-data-value-itself", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2358, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-serialized-value", + "level": "MUST", + "terms": ["SHOULD", "MUST"], + "text": "Otherwise, it SHOULD be the valid serialization of a data value that itself MUST be valid as described for `dataValue`." + }, + { + "id": "oas-3.2.example-object.serializedValue.should-datavalue-present-field-contain-serialization-given", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2358, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-serialized-value", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If `dataValue` is present, then this field SHOULD contain the serialization of the given data." + }, + { + "id": "oas-3.2.example-object.serializedValue.should-not-field-used-serialization-format-json-data", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2358, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-serialized-value", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "This field SHOULD NOT be used if the serialization format is JSON, as the data form is easier to work with." + }, + { + "id": "oas-3.2.example-object.summary", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2355, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-summary", + "level": "field", + "terms": [], + "text": "Short description for the example." + }, + { + "id": "oas-3.2.example-object.validating-examples.may-tooling-implementations-choose-validate-compatibility-automatically", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2421, + "section": "Objects and Fields > Example Object > Working with Examples > Validating Examples", + "anchor": "validating-examples", + "level": "MAY", + "terms": ["MAY"], + "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + }, + { + "id": "oas-3.2.example-object.value", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2360, + "section": "Objects and Fields > Example Object > Fixed Fields", + "anchor": "example-value", + "level": "field", + "terms": [], + "text": "Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally be represented in JSON or YAML, use a string value to contain the example, escaping where necessary. Deprecated for non-JSON serialization targets: Use `dataValue` and/or `serializedValue`, which both have unambiguous syntax and semantics, instead." + }, + { + "id": "oas-3.2.external-documentation-object.description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 747, + "section": "Objects and Fields > External Documentation Object > Fixed Fields", + "anchor": "external-doc-description", + "level": "field", + "terms": [], + "text": "A description of the target documentation. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.external-documentation-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 747, + "section": "Objects and Fields > External Documentation Object > Fixed Fields", + "anchor": "external-doc-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.external-documentation-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 750, + "section": "Objects and Fields > External Documentation Object > Fixed Fields", + "anchor": "fixed-fields-8", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.external-documentation-object.url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 748, + "section": "Objects and Fields > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The URI for the target documentation. This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.external-documentation-object.url.must-form-uri", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 748, + "section": "Objects and Fields > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.external-documentation-object.url.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 748, + "section": "Objects and Fields > External Documentation Object > Fixed Fields", + "anchor": "external-doc-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.format.must-patterned-fields-have-unique-names-within", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 54, + "section": "Format", + "anchor": "format", + "level": "MUST", + "terms": ["MUST"], + "text": "Patterned fields MUST have unique names within the containing object." + }, + { + "id": "oas-3.2.guidance-regarding-implicit-connections.recommended-resolving-component-tag-name-connections-referenced", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5531, + "section": "Appendix G: Parsing and Resolution Guidance > Guidance Regarding Implicit Connections", + "anchor": "guidance-regarding-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For resolving component and tag name connections from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + }, + { + "id": "oas-3.2.header-object.common-fixed-fields.may-fields-used-either-content-schema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2695, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "These fields MAY be used with either `content` or `schema`." + }, + { + "id": "oas-3.2.header-object.common-fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2707, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields-1", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.header-object.content", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2730, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "header-content", + "level": "field", + "terms": [], + "text": "A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry." + }, + { + "id": "oas-3.2.header-object.content.must-map-only-contain-one-entry", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2730, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "header-content", + "level": "MUST", + "terms": ["MUST"], + "text": "The map MUST only contain one entry." + }, + { + "id": "oas-3.2.header-object.deprecated", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2703, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-deprecated", + "level": "field", + "terms": [], + "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + }, + { + "id": "oas-3.2.header-object.deprecated.should-specifies-header-deprecated-transitioned-out-usage", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2703, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage." + }, + { + "id": "oas-3.2.header-object.description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2701, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-description", + "level": "field", + "terms": [], + "text": "A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.header-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2701, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.header-object.example", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2704, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-example", + "level": "field", + "terms": [], + "text": "Example of the header's potential value; see Working With Examples." + }, + { + "id": "oas-3.2.header-object.examples", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2705, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-examples", + "level": "field", + "terms": [], + "text": "Examples of the header's potential value; see Working With Examples." + }, + { + "id": "oas-3.2.header-object.explode", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2719, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-explode", + "level": "field", + "terms": [], + "text": "When this is true, header values of type `array` or `object` generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is `false`." + }, + { + "id": "oas-3.2.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2713, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["MUST"], + "text": "Implementations MUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; see Appendix D for guidance on quoting and escaping." + }, + { + "id": "oas-3.2.header-object.fixed-fields-for-use-with-schema.must-not-serializing-headers-schema-uri-percent-encoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2713, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema-0", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "When serializing headers with `schema`, URI percent-encoding MUST NOT be applied; if using an RFC6570 implementation that automatically applies it, it MUST be removed before use." + }, + { + "id": "oas-3.2.header-object.modeling-link-headers.must-application-linkset-media-type-object-used", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2737, + "section": "Objects and Fields > Header Object > Modeling Link Headers", + "anchor": "modeling-link-headers", + "level": "MUST", + "terms": ["MUST"], + "text": "If the `application/linkset` Media Type Object is used in the `content` field of a Header Object (or a Parameter Object with `in: \"header\"`), the serialization MUST be made compatible with the HTTP field syntax as described by [RFC9264] Section 4.1." + }, + { + "id": "oas-3.2.header-object.modeling-link-headers.must-media-type-object-s-parent-key", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2737, + "section": "Objects and Fields > Header Object > Modeling Link Headers", + "anchor": "modeling-link-headers", + "level": "MUST", + "terms": ["MUST"], + "text": "If the Media Type Object's parent key is `application/linkset`, then the serialization MUST be the equivalent representation of the `schema`-modeled links in the `application/linkset` format." + }, + { + "id": "oas-3.2.header-object.modeling-link-headers.must-use-either-media-types-schema-media", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2737, + "section": "Objects and Fields > Header Object > Modeling Link Headers", + "anchor": "modeling-link-headers", + "level": "MUST", + "terms": ["MUST"], + "text": "To use either of these media types, the `schema` in the Media Type Object MUST describe the links as they would be structured in the `application/linkset+json` format." + }, + { + "id": "oas-3.2.header-object.must-all-traits-affected-location-applicable-location", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2689, + "section": "Objects and Fields > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST"], + "text": "All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`)." + }, + { + "id": "oas-3.2.header-object.must-not-means-allowemptyvalue-used-style-used-limited", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2689, + "section": "Objects and Fields > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "This means that `allowEmptyValue` MUST NOT be used, and `style`, if used, MUST be limited to `\"simple\"`." + }, + { + "id": "oas-3.2.header-object.must-not-name-specified-given-corresponding-headers-map", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2687, + "section": "Objects and Fields > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "`name` MUST NOT be specified, it is given in the corresponding `headers` map." + }, + { + "id": "oas-3.2.header-object.must-not-specified-implicitly-header", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2688, + "section": "Objects and Fields > Header Object", + "anchor": "header-object", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "`in` MUST NOT be specified, it is implicitly in `header`." + }, + { + "id": "oas-3.2.header-object.representing-the-set-cookie-header.must-however-because-examples-values-modeled-content", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2815, + "section": "Objects and Fields > Header Object > Representing the `Set-Cookie` Header", + "anchor": "representing-the-set-cookie-header", + "level": "MUST", + "terms": ["MUST"], + "text": "However, because examples and values modeled with `content` do not incorporate the header name, for these fields `Set-Cookie` MUST be handled by placing each value on a separate line, without the header name or the `:` delimiter." + }, + { + "id": "oas-3.2.header-object.representing-the-set-cookie-header.must-note-any-uri-percent-encoding-base64", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2817, + "section": "Objects and Fields > Header Object > Representing the `Set-Cookie` Header", + "anchor": "representing-the-set-cookie-header", + "level": "MUST", + "terms": ["MUST"], + "text": "Note also that any URI percent-encoding, base64 encoding, or other escaping MUST be performed prior to supplying the data to OAS tooling; see Appendix D for details." + }, + { + "id": "oas-3.2.header-object.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2702, + "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", + "anchor": "header-required", + "level": "field", + "terms": [], + "text": "Determines whether this header is mandatory. The default value is `false`." + }, + { + "id": "oas-3.2.header-object.schema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2720, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-schema", + "level": "field", + "terms": [], + "text": "The schema defining the type used for the header." + }, + { + "id": "oas-3.2.header-object.style", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2718, + "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "header-style", + "level": "field", + "terms": [], + "text": "Describes how the header value will be serialized. The default (and only legal value for headers) is `\"simple\"`." + }, + { + "id": "oas-3.2.info-object.contact", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 196, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-contact", + "level": "field", + "terms": [], + "text": "The contact information for the exposed API." + }, + { + "id": "oas-3.2.info-object.description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 194, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-description", + "level": "field", + "terms": [], + "text": "A description of the API. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.info-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 194, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.info-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 200, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "fixed-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.info-object.license", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 197, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-license", + "level": "field", + "terms": [], + "text": "The license information for the exposed API." + }, + { + "id": "oas-3.2.info-object.may-metadata-used-clients-needed-presented-editing", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 185, + "section": "Objects and Fields > Info Object", + "anchor": "info-object", + "level": "MAY", + "terms": ["MAY"], + "text": "The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience." + }, + { + "id": "oas-3.2.info-object.summary", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 193, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-summary", + "level": "field", + "terms": [], + "text": "A short summary of the API." + }, + { + "id": "oas-3.2.info-object.termsOfService", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 195, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-terms-of-service", + "level": "field", + "terms": [], + "text": "A URI for the Terms of Service for the API. This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.info-object.termsOfService.must-form-uri", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 195, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-terms-of-service", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.info-object.title", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 192, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-title", + "level": "field", + "terms": [], + "text": "REQUIRED. The title of the API." + }, + { + "id": "oas-3.2.info-object.title.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 192, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-title", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.info-object.version", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 198, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-version", + "level": "field", + "terms": [], + "text": "REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description)." + }, + { + "id": "oas-3.2.info-object.version.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 198, + "section": "Objects and Fields > Info Object > Fixed Fields", + "anchor": "info-version", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.json-and-yaml-compatibility.recommended-order-preserve-ability-round-trip-between", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 60, + "section": "Format > JSON and YAML Compatibility", + "anchor": "json-and-yaml-compatibility", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with the additional constraints listed in [RFC9512] Section 3.4." + }, + { + "id": "oas-3.2.json-and-yaml-compatibility.should-not-oad-authors-rely-any-json-incompatible", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 62, + "section": "Format > JSON and YAML Compatibility", + "anchor": "json-and-yaml-compatibility", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "OAD authors SHOULD NOT rely on any such JSON-incompatible YAML values." + }, + { + "id": "oas-3.2.license-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 253, + "section": "Objects and Fields > License Object > Fixed Fields", + "anchor": "fixed-fields-2", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.license-object.identifier", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 250, + "section": "Objects and Fields > License Object > Fixed Fields", + "anchor": "license-identifier", + "level": "field", + "terms": [], + "text": "An SPDX license expression for the API. The `identifier` field is mutually exclusive of the `url` field." + }, + { + "id": "oas-3.2.license-object.name", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 249, + "section": "Objects and Fields > License Object > Fixed Fields", + "anchor": "license-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The license name used for the API." + }, + { + "id": "oas-3.2.license-object.name.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 249, + "section": "Objects and Fields > License Object > Fixed Fields", + "anchor": "license-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.license-object.url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 251, + "section": "Objects and Fields > License Object > Fixed Fields", + "anchor": "license-url", + "level": "field", + "terms": [], + "text": "A URI for the license used for the API. This MUST be in the form of a URI. The `url` field is mutually exclusive of the `identifier` field." + }, + { + "id": "oas-3.2.license-object.url.must-form-uri", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 251, + "section": "Objects and Fields > License Object > Fixed Fields", + "anchor": "license-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.link-object.description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2522, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-description", + "level": "field", + "terms": [], + "text": "A description of the link. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.link-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2522, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.link-object.example-expressions.must-request-parameters-declared-parameters-section-parent", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2672, + "section": "Objects and Fields > Link Object > Runtime Expressions > Example Expressions", + "anchor": "example-expressions", + "level": "MUST", + "terms": ["MUST"], + "text": "Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated." + }, + { + "id": "oas-3.2.link-object.fixed-fields.may-ambiguous-cases-resulting-behavior-implementation-defined", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2527, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MAY", + "terms": ["MAY"], + "text": "In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error." + }, + { + "id": "oas-3.2.link-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2525, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.link-object.fixed-fields.must-identified-referenced-operation-unique-case-operationid", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2527, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MUST", + "terms": ["MUST"], + "text": "The identified or referenced operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD)." + }, + { + "id": "oas-3.2.link-object.fixed-fields.must-linked-operation-identified-using-either-operationref", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2527, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "MUST", + "terms": ["MUST"], + "text": "A linked operation MUST be identified using either an `operationRef` or `operationId`." + }, + { + "id": "oas-3.2.link-object.fixed-fields.not-recommended-possible-have-ambiguous-parameter-names-e", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2533, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "fixed-fields-16", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED", "SHOULD"], + "text": "It is possible to have ambiguous parameter names, e.g. `name: \"id\", in: \"path\"` and `name: \"path.id\", in: \"query\"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter)." + }, + { + "id": "oas-3.2.link-object.operationId", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2519, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-operation-id", + "level": "field", + "terms": [], + "text": "The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field." + }, + { + "id": "oas-3.2.link-object.operationRef", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2518, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "field", + "terms": [], + "text": "A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object. Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + }, + { + "id": "oas-3.2.link-object.operationRef.may-relative-operationref-values-used-locate-existing", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2518, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "MAY", + "terms": ["MAY"], + "text": "Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + }, + { + "id": "oas-3.2.link-object.operationRef.must-field-mutually-exclusive-operationid-field-point", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2518, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-operation-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." + }, + { + "id": "oas-3.2.link-object.operationref-examples.may-operationid-optional-field-operation-object-references", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2605, + "section": "Objects and Fields > Link Object > Examples > `operationRef` Examples", + "anchor": "operationref-examples", + "level": "MAY", + "terms": ["MAY"], + "text": "As the `operationId` is an optional field in an Operation Object, references MAY instead be made through a URI reference with `operationRef`." + }, + { + "id": "oas-3.2.link-object.parameters", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2520, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-parameters", + "level": "field", + "terms": [], + "text": "A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation." + }, + { + "id": "oas-3.2.link-object.requestBody", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2521, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-request-body", + "level": "field", + "terms": [], + "text": "A literal value or {expression} to use as a request body when calling the target operation." + }, + { + "id": "oas-3.2.link-object.server", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2523, + "section": "Objects and Fields > Link Object > Fixed Fields", + "anchor": "link-server", + "level": "field", + "terms": [], + "text": "A server object to be used by the target operation." + }, + { + "id": "oas-3.2.media-type-object.additional-encoding-approaches.may-implementations-choose-support-workaround-but-usage", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1411, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Additional Encoding Approaches", + "anchor": "additional-encoding-approaches", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY choose to support this workaround, but as this usage is not common, implementations of non-`form-data` `multipart` media types are unlikely to support it." + }, + { + "id": "oas-3.2.media-type-object.binary-streams.may-maxlength-keyword-used-set-expected-upper", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1336, + "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Binary Streams", + "anchor": "binary-streams", + "level": "MAY", + "terms": ["MAY"], + "text": "The `maxLength` keyword MAY be used to set an expected upper bound on the length of a streaming payload that consists of either string data, including encoded binary data, or unencoded binary data." + }, + { + "id": "oas-3.2.media-type-object.binary-streams.may-use-case-maxlength-implemented-outside-regular", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1336, + "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Binary Streams", + "anchor": "binary-streams", + "level": "MAY", + "terms": ["MAY"], + "text": "For this use case, `maxLength` MAY be implemented outside of regular JSON Schema evaluation as JSON Schema does not directly apply to binary data, and an encoded binary stream may be impractical to store in memory in its entirety." + }, + { + "id": "oas-3.2.media-type-object.complete-vs-streaming-content.must-schema-field-applied-complete-content-defined", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1296, + "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content", + "anchor": "complete-vs-streaming-content", + "level": "MUST", + "terms": ["MUST"], + "text": "The `schema` field MUST be applied to the complete content, as defined by the media type and the context (Request Body Object, Response Object, Parameter Object, or Header Object." + }, + { + "id": "oas-3.2.media-type-object.considerations-for-file-uploads.may-addition-specific-media-types-specified", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1694, + "section": "Objects and Fields > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MAY", + "terms": ["MAY"], + "text": "In addition, specific media types MAY be specified:" + }, + { + "id": "oas-3.2.media-type-object.considerations-for-file-uploads.may-content-transferred-binary-octet-stream-omit", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1664, + "section": "Objects and Fields > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MAY", + "terms": ["MAY"], + "text": "Content transferred in binary (octet-stream) MAY omit `schema`:" + }, + { + "id": "oas-3.2.media-type-object.considerations-for-file-uploads.must-upload-multiple-files-multipart-media-type", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1705, + "section": "Objects and Fields > Media Type Object > Considerations for File Uploads", + "anchor": "considerations-for-file-uploads", + "level": "MUST", + "terms": ["MUST"], + "text": "To upload multiple files, a `multipart` media type MUST be used as shown under Example: Multipart Form with Multiple Files." + }, + { + "id": "oas-3.2.media-type-object.encoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1274, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "field", + "terms": [], + "text": "A map between a property name and its encoding information, as defined under Encoding By Name. The `encoding` field SHALL only apply when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object. This field MUST NOT be present if `prefixEncoding` or `itemEncoding` are present." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-name.must-all-other-value-types-both-top", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1377, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", + "anchor": "encoding-by-name", + "level": "MUST", + "terms": ["MUST"], + "text": "For all other value types for both top-level non-array property values and for other values, including items of the array type within a top-level array, the Encoding Object MUST be applied to the entire value." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-name.must-application-x-www-form-urlencoded-encoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1384, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", + "anchor": "encoding-by-name", + "level": "MUST", + "terms": ["MUST"], + "text": "For `application/x-www-form-urlencoded`, the `encoding` keys MUST map to parameter names, with the serialized values produced according to the rules of the Encoding Object." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-name.must-deserialization-object-multiple-values-same-name", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1377, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", + "anchor": "encoding-by-name", + "level": "MUST", + "terms": ["MUST"], + "text": "For deserialization to an object, multiple values with the same `name` MUST be collapsed into an array value for that named property, with one item per value, in order." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-name.must-multipart-types-decode-object-multipart-form", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1387, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", + "anchor": "encoding-by-name", + "level": "MUST", + "terms": ["MUST"], + "text": "For `multipart` types that decode to an object, such as `multipart/form-data`, the `encoding` keys MUST map to the `name` parameter of the `Content-Disposition: form-data` header of each part, as is defined for `multipart/form-data` in [RFC7578]." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-name.must-serializing-property-values-array-type-handled", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1377, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", + "anchor": "encoding-by-name", + "level": "MUST", + "terms": ["MUST"], + "text": "When serializing, property values of the array type MUST be handled by applying the given Encoding Object to produce one encoded value per array item, each with the same `name`, as is recommended by [RFC7578] Section 4.3 for supplying multiple values per form field; when deserializing, the Encoding Object is applied to each item of the array property of the same name." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-name.must-use-encoding-field-each-key-under", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1377, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", + "anchor": "encoding-by-name", + "level": "MUST", + "terms": ["MUST", "SHALL"], + "text": "To use the `encoding` field, each key under the field MUST exist in the data instance as a property; `encoding` entries with no corresponding property SHALL be ignored." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-position.must-use-prefixencoding-itemencoding-fields-each-item", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1399, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Position", + "anchor": "encoding-by-position", + "level": "MUST", + "terms": ["MUST", "SHALL"], + "text": "To use the `prefixEncoding` and/or `itemEncoding` fields, each item referenced by the field MUST exist in the data instance; `prefixEncoding` and `itemEncoding` entries with no corresponding item SHALL be ignored." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-position.shall-applications-wish-preserve-part-order-multipart", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1397, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Position", + "anchor": "encoding-by-position", + "level": "MUST", + "terms": ["SHALL"], + "text": "For applications that wish to preserve part order, `multipart/form-data` content may also be modelled as an array, with one item per part, in order (where each item consists of an object containing the name/value pair); the `schema` SHALL be used to determine whether deserializing to an `object` or an `array` is preferred." + }, + { + "id": "oas-3.2.media-type-object.encoding-by-position.shall-prefixitems-not-error-instance-array-shorter", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1401, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Position", + "anchor": "encoding-by-position", + "level": "MUST", + "terms": ["SHALL"], + "text": "As with `prefixItems`, it is _not_ an error if the instance array is shorter than the `prefixEncoding` array; the additional Encoding Objects SHALL be ignored." + }, + { + "id": "oas-3.2.media-type-object.encoding-usage-and-restrictions.shall-each-field-own-set-media-types", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1370, + "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions", + "anchor": "encoding-usage-and-restrictions", + "level": "MUST", + "terms": ["SHALL"], + "text": "Each field has its own set of media types with which it can be used; for all other media types all three fields SHALL be ignored." + }, + { + "id": "oas-3.2.media-type-object.encoding.must-not-field-present-prefixencoding-itemencoding-present", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1274, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "This field MUST NOT be present if `prefixEncoding` or `itemEncoding` are present." + }, + { + "id": "oas-3.2.media-type-object.encoding.shall-encoding-field-only-apply-media-type", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1274, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-encoding", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `encoding` field SHALL only apply when the media type is `multipart` or `application/x-www-form-urlencoded`." + }, + { + "id": "oas-3.2.media-type-object.example", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1272, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-example", + "level": "field", + "terms": [], + "text": "Example of the media type; see Working With Examples." + }, + { + "id": "oas-3.2.media-type-object.examples", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1273, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-examples", + "level": "field", + "terms": [], + "text": "Examples of the media type; see Working With Examples." + }, + { + "id": "oas-3.2.media-type-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1278, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "fixed-fields-11", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.media-type-object.itemEncoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1276, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-item-encoding", + "level": "field", + "terms": [], + "text": "A single Encoding Object that provides encoding information for multiple array items, as defined under Encoding By Position. The `itemEncoding` field SHALL only apply when the media type is `multipart`. If no Encoding Object is provided for an item, the behavior is determined by the default values documented for the Encoding Object. This field MUST NOT be present if `encoding` is present." + }, + { + "id": "oas-3.2.media-type-object.itemEncoding.must-not-field-present-encoding-present", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1276, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-item-encoding", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "This field MUST NOT be present if `encoding` is present." + }, + { + "id": "oas-3.2.media-type-object.itemEncoding.shall-itemencoding-field-only-apply-media-type", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1276, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-item-encoding", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `itemEncoding` field SHALL only apply when the media type is `multipart`." + }, + { + "id": "oas-3.2.media-type-object.itemSchema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1271, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-item-schema", + "level": "field", + "terms": [], + "text": "A schema describing each item within a sequential media type." + }, + { + "id": "oas-3.2.media-type-object.openapi-media-type-registry.may-any-additional-media-types-added-registry", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1290, + "section": "Objects and Fields > Media Type Object > Media Types > OpenAPI Media Type Registry", + "anchor": "openapi-media-type-registry", + "level": "MAY", + "terms": ["MAY"], + "text": "Any additional media types added to this registry as extensions or for later versions of this or other OpenAPI specifications MAY be supported by implementations of this version of the OAS." + }, + { + "id": "oas-3.2.media-type-object.prefixEncoding", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1275, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-prefix-encoding", + "level": "field", + "terms": [], + "text": "An array of positional encoding information, as defined under Encoding By Position. The `prefixEncoding` field SHALL only apply when the media type is `multipart`. If no Encoding Object is provided for an item, the behavior is determined by the default values documented for the Encoding Object. This field MUST NOT be present if `encoding` is present." + }, + { + "id": "oas-3.2.media-type-object.prefixEncoding.must-not-field-present-encoding-present", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1275, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-prefix-encoding", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "This field MUST NOT be present if `encoding` is present." + }, + { + "id": "oas-3.2.media-type-object.prefixEncoding.shall-prefixencoding-field-only-apply-media-type", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1275, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-prefix-encoding", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `prefixEncoding` field SHALL only apply when the media type is `multipart`." + }, + { + "id": "oas-3.2.media-type-object.schema", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1270, + "section": "Objects and Fields > Media Type Object > Fixed Fields", + "anchor": "media-type-schema", + "level": "field", + "terms": [], + "text": "A schema describing the complete content of the request, response, parameter, or header." + }, + { + "id": "oas-3.2.media-type-object.sequential-media-types.must-implementations-support-mapping-sequential-media-types", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1320, + "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Sequential Media Types", + "anchor": "sequential-media-types", + "level": "MUST", + "terms": ["MUST"], + "text": "Implementations MUST support mapping sequential media types into the JSON Schema data model by treating them as if the values were in an array in the same order." + }, + { + "id": "oas-3.2.media-type-object.should-example-examples-provided-example-match-specified", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1262, + "section": "Objects and Fields > Media Type Object", + "anchor": "media-type-object", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding." + }, + { + "id": "oas-3.2.media-type-object.special-considerations-for-server-sent-events.must-field-value-types-handled-specified-text", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1344, + "section": "Objects and Fields > Media Type Object > Special Considerations for Server-Sent Events", + "anchor": "special-considerations-for-server-sent-events", + "level": "MUST", + "terms": ["MUST"], + "text": "Field value types MUST be handled as specified by the `text/event-stream` specification (e.g. the `retry` field value is modeled as a JSON number that is expected to be of JSON Schema `type: integer`), and fields not given an explicit value type MUST be handled as strings." + }, + { + "id": "oas-3.2.media-type-object.special-considerations-for-server-sent-events.must-text-event-stream-implementations-work-event", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1342, + "section": "Objects and Fields > Media Type Object > Special Considerations for Server-Sent Events", + "anchor": "special-considerations-for-server-sent-events", + "level": "MUST", + "terms": ["MUST"], + "text": "For `text/event-stream`, implementations MUST work with event data after it has been parsed according to the `text/event-stream` specification, including all guidance on ignoring certain fields (including comments) and/or values, and on combining values split across multiple lines." + }, + { + "id": "oas-3.2.media-type-object.streaming-sequential-media-types.may-both-schema-itemschema-used-same-media", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1331, + "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Sequential Media Types > Streaming Sequential Media Types", + "anchor": "streaming-sequential-media-types", + "level": "MAY", + "terms": ["MAY"], + "text": "Both `schema` and `itemSchema` MAY be used in the same Media Type Object." + }, + { + "id": "oas-3.2.media-type-object.streaming-sequential-media-types.must-unlike-schema-applied-complete-content-treated", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1329, + "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Sequential Media Types > Streaming Sequential Media Types", + "anchor": "streaming-sequential-media-types", + "level": "MUST", + "terms": ["MUST"], + "text": "Unlike `schema`, which is applied to the complete content (treated as an array as described in the sequential media types section), `itemSchema` MUST be applied to each item in the stream independently, which supports processing each item as it is read from the stream." + }, + { + "id": "oas-3.2.non-rfc6570-field-values-and-combinations.may-implementations-create-properly-delimited-uri-template", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4950, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based on `allowReserved`)." + }, + { + "id": "oas-3.2.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4959, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "MUST", + "terms": ["MUST"], + "text": "A parameter name that includes characters outside of the allowed RFC6570 variable character set MUST be percent-encoded before it can be used in a URI Template." + }, + { + "id": "oas-3.2.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4950, + "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", + "anchor": "non-rfc6570-field-values-and-combinations", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Configurations with no direct RFC6570 equivalent SHOULD also be handled according to RFC6570." + }, + { + "id": "oas-3.2.oauth-flow-object.authorizationUrl", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4681, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.2.oauth-flow-object.authorizationUrl.must-form-url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4681, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.2.oauth-flow-object.authorizationUrl.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4681, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-authorization-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.oauth-flow-object.deviceAuthorizationUrl", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4682, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-device-authorization-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The device authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.2.oauth-flow-object.deviceAuthorizationUrl.must-form-url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4682, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-device-authorization-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.2.oauth-flow-object.deviceAuthorizationUrl.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4682, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-device-authorization-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4687, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "fixed-fields-25", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.oauth-flow-object.refreshUrl", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4684, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-refresh-url", + "level": "field", + "terms": [], + "text": "The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.2.oauth-flow-object.refreshUrl.must-form-url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4684, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-refresh-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.2.oauth-flow-object.scopes", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4685, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "field", + "terms": [], + "text": "REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty." + }, + { + "id": "oas-3.2.oauth-flow-object.scopes.may-map-empty", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4685, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "MAY", + "terms": ["MAY"], + "text": "The map MAY be empty." + }, + { + "id": "oas-3.2.oauth-flow-object.scopes.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4685, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-scopes", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.oauth-flow-object.tokenUrl", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4683, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "field", + "terms": [], + "text": "REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + }, + { + "id": "oas-3.2.oauth-flow-object.tokenUrl.must-form-url", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4683, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URL." + }, + { + "id": "oas-3.2.oauth-flow-object.tokenUrl.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4683, + "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", + "anchor": "oauth-flow-token-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.oauth-flows-object.authorizationCode", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4668, + "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-authorization-code", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0." + }, + { + "id": "oas-3.2.oauth-flows-object.clientCredentials", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4667, + "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-client-credentials", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0." + }, + { + "id": "oas-3.2.oauth-flows-object.deviceAuthorization", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4669, + "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-device-authorization", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Device Authorization flow." + }, + { + "id": "oas-3.2.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4671, + "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", + "anchor": "fixed-fields-24", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.oauth-flows-object.implicit", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4665, + "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-implicit", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Implicit flow" + }, + { + "id": "oas-3.2.oauth-flows-object.password", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4666, + "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", + "anchor": "oauth-flows-password", + "level": "field", + "terms": [], + "text": "Configuration for the OAuth Resource Owner Password flow" + }, + { + "id": "oas-3.2.objects-and-fields.must-json-schema-differs-section-section-considered", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 80, + "section": "Objects and Fields", + "anchor": "objects-and-fields", + "level": "MUST", + "terms": ["MUST"], + "text": "If the JSON Schema differs from this section, then this section MUST be considered authoritative." + }, + { + "id": "oas-3.2.objects-and-fields.required-following-description-field-not-explicitly-described", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 85, + "section": "Objects and Fields", + "anchor": "objects-and-fields", + "level": "MUST", + "terms": ["REQUIRED", "MUST", "SHALL", "OPTIONAL"], + "text": "In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL." + }, + { + "id": "oas-3.2.openapi-object.$self", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 98, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-self", + "level": "field", + "terms": [], + "text": "This string MUST be in the form of a URI reference as defined by [RFC3986] Section 4.1. The `$self` field provides the self-assigned URI of this document, which also serves as its base URI in accordance with [RFC3986] Section 5.1.1. Implementations MUST support identifying the targets of API description URIs using the URI defined by this field when it is present. See Establishing the Base URI for the base URI behavior when `$self` is absent or relative, and see Appendix F for examples of using `$self` to resolve references." + }, + { + "id": "oas-3.2.openapi-object.$self.must-implementations-support-identifying-targets-api-description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 98, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-self", + "level": "MUST", + "terms": ["MUST"], + "text": "Implementations MUST support identifying the targets of API description URIs using the URI defined by this field when it is present." + }, + { + "id": "oas-3.2.openapi-object.$self.must-string-form-uri-reference-defined-rfc3986", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 98, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-self", + "level": "MUST", + "terms": ["MUST"], + "text": "This string MUST be in the form of a URI reference as defined by [RFC3986] Section 4.1." + }, + { + "id": "oas-3.2.openapi-object.components", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 104, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-components", + "level": "field", + "terms": [], + "text": "An element to hold various Objects for the OpenAPI Description." + }, + { + "id": "oas-3.2.openapi-object.establishing-the-base-uri.may-implementations-support-document-retrieval-although-see", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 156, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Establishing the Base URI", + "anchor": "establishing-the-base-uri", + "level": "MAY", + "terms": ["MAY"], + "text": "Implementations MAY support document retrieval, although see the Security Considerations sections for additional guidance." + }, + { + "id": "oas-3.2.openapi-object.establishing-the-base-uri.must-relative-uri-references-resolved-using-appropriate", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 152, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Establishing the Base URI", + "anchor": "establishing-the-base-uri", + "level": "MUST", + "terms": ["MUST"], + "text": "Relative URI references are resolved using the appropriate base URI, which MUST be determined in accordance with [RFC3986] Section 5.1.1 – 5.1.4 and, for Schema objects, JSON Schema draft 2020-12 Section 8.2, as illustrated by the examples in Appendix F: Examples of Base URI Determination and Reference Resolution." + }, + { + "id": "oas-3.2.openapi-object.establishing-the-base-uri.should-therefore-all-implementations-allow-users-provide", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 156, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Establishing the Base URI", + "anchor": "establishing-the-base-uri", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Therefore, all implementations SHOULD allow users to provide documents with their intended retrieval URIs so that references can be resolved as if retrievals were performed." + }, + { + "id": "oas-3.2.openapi-object.externalDocs", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 107, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation." + }, + { + "id": "oas-3.2.openapi-object.fixed-fields.may-object-extended-specification-extensions", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 109, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." + }, + { + "id": "oas-3.2.openapi-object.fixed-fields.must-addition-required-fields-least-one-components", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 93, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "fixed-fields", + "level": "MUST", + "terms": ["MUST"], + "text": "In addition to the required fields, at least one of the `components`, `paths`, or `webhooks` fields MUST be present." + }, + { + "id": "oas-3.2.openapi-object.fixed-fields.must-ensure-interoperability-references-use-target-document", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 111, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "fixed-fields", + "level": "MUST", + "terms": ["MUST"], + "text": "To ensure interoperability, references MUST use the target document's `$self` URI if the `$self` field is present." + }, + { + "id": "oas-3.2.openapi-object.fixed-fields.not-recommended-implementations-choose-support-referencing-other-uris", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 111, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "fixed-fields", + "level": "SHOULD", + "terms": ["MAY", "NOT RECOMMENDED"], + "text": "Implementations MAY choose to support referencing by other URIs such as the retrieval URI even when `$self` is present, however this behavior is not interoperable and relying on it is NOT RECOMMENDED." + }, + { + "id": "oas-3.2.openapi-object.info", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 99, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "field", + "terms": [], + "text": "REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required." + }, + { + "id": "oas-3.2.openapi-object.info.may-metadata-used-tooling-required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 99, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "MAY", + "terms": ["MAY"], + "text": "The metadata MAY be used by tooling as required." + }, + { + "id": "oas-3.2.openapi-object.info.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 99, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-info", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.openapi-object.jsonSchemaDialect", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 100, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-json-schema-dialect", + "level": "field", + "terms": [], + "text": "The default value for the `$schema` keyword within Schema Objects contained within this OAS document. This MUST be in the form of a URI. See JSON Schema Keywords to determine the default value." + }, + { + "id": "oas-3.2.openapi-object.jsonSchemaDialect.must-form-uri", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 100, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-json-schema-dialect", + "level": "MUST", + "terms": ["MUST"], + "text": "This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.openapi-object.openapi", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 97, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "field", + "terms": [], + "text": "REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is _not_ related to the `info.version` string, which describes the OpenAPI document's version." + }, + { + "id": "oas-3.2.openapi-object.openapi-description-structure.may-documents-different-object-root-mix-oad", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 121, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "MAY", + "terms": ["MAY"], + "text": "Documents with a different Object at the root, or that mix OAD content with other content, MAY be supported, but will have implementation-defined or, potentially, undefined behavior as described in Appendix G: Parsing and Resolution Guidance." + }, + { + "id": "oas-3.2.openapi-object.openapi-description-structure.may-oad-made-up-single-document-distributed", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 116, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "MAY", + "terms": ["MAY"], + "text": "An OAD MAY be made up of a single document, or be distributed across multiple documents that are connected by various fields using URI references and implicit connections." + }, + { + "id": "oas-3.2.openapi-object.openapi-description-structure.may-openapi-object-embedded-another-format-called", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 127, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "MAY", + "terms": ["MAY"], + "text": "An OpenAPI Object MAY be embedded in another format, called the embedding format, just as JSON Schema is embedded in the OAS in the form of Schema Objects." + }, + { + "id": "oas-3.2.openapi-object.openapi-description-structure.must-order-parsing-behavior-well-defined-all", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 119, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "MUST", + "terms": ["MUST"], + "text": "In order for parsing behavior to be well-defined, all documents in an OAD MUST have either an OpenAPI Object or a Schema Object at the root, and MUST be parsed as complete documents, as described in the next section." + }, + { + "id": "oas-3.2.openapi-object.openapi-description-structure.recommended-entry-document-oad-named-openapi-json", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 124, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", + "anchor": "openapi-description-structure", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is RECOMMENDED that the entry document of an OAD be named `openapi.json` or `openapi.yaml`." + }, + { + "id": "oas-3.2.openapi-object.openapi.must-string-version-number-openapi-specification-openapi", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 97, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "MUST", + "terms": ["MUST"], + "text": "This string MUST be the version number of the OpenAPI Specification that the OpenAPI document uses." + }, + { + "id": "oas-3.2.openapi-object.openapi.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 97, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.openapi-object.openapi.should-openapi-field-used-tooling-interpret-openapi", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 97, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-version", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document." + }, + { + "id": "oas-3.2.openapi-object.parsing-documents.must-each-document-oad-fully-parsed-order", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 132, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Parsing Documents", + "anchor": "parsing-documents", + "level": "MUST", + "terms": ["MUST"], + "text": "Each document in an OAD MUST be fully parsed in order to locate possible reference targets." + }, + { + "id": "oas-3.2.openapi-object.parsing-documents.must-not-implementations-treat-reference-unresolvable-before-completely", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 136, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Parsing Documents", + "anchor": "parsing-documents", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Implementations MUST NOT treat a reference as unresolvable before completely parsing all documents provided to the implementation as possible parts of the OAD." + }, + { + "id": "oas-3.2.openapi-object.paths", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 102, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-paths", + "level": "field", + "terms": [], + "text": "The available paths and operations for the API." + }, + { + "id": "oas-3.2.openapi-object.relative-references-in-api-description-uris.may-unless-specified-otherwise-all-fields-uris", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 148, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs", + "anchor": "relative-references-in-api-description-uris", + "level": "MAY", + "terms": ["MAY"], + "text": "Unless specified otherwise, all fields that are URIs MAY be relative references as defined by [RFC3986] Section 4.2." + }, + { + "id": "oas-3.2.openapi-object.resolving-implicit-connections.recommended-resolving-components-object-tag-object-names", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 176, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For resolving Components Object and Tag Object names from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + }, + { + "id": "oas-3.2.openapi-object.resolving-implicit-connections.recommended-resolving-operation-object-based-operationid-consider", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 176, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "For resolving an Operation Object based on an `operationId`, it is RECOMMENDED to consider all Operation Objects from all parsed documents." + }, + { + "id": "oas-3.2.openapi-object.resolving-implicit-connections.recommended-some-cases-unambiguous-uri-based-alternative", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 173, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Resolving Implicit Connections", + "anchor": "resolving-implicit-connections", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "In some cases, an unambiguous URI-based alternative is available, and OAD authors are RECOMMENDED to use the alternative to maximize interoperability." + }, + { + "id": "oas-3.2.openapi-object.resolving-uri-fragments.should-representation-referenced-document-json-yaml-fragment", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 163, + "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Resolving URI fragments", + "anchor": "resolving-uri-fragments", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON Pointer as per RFC6901." + }, + { + "id": "oas-3.2.openapi-object.security", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 105, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-security", + "level": "field", + "terms": [], + "text": "A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array." + }, + { + "id": "oas-3.2.openapi-object.servers", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 101, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-servers", + "level": "field", + "terms": [], + "text": "An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be an array consisting of a single Server Object with a url value of `/`." + }, + { + "id": "oas-3.2.openapi-object.tags", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 106, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "field", + "terms": [], + "text": "A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." + }, + { + "id": "oas-3.2.openapi-object.tags.may-tags-not-declared-organized-randomly-based", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 106, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "MAY", + "terms": ["MAY"], + "text": "The tags that are not declared MAY be organized randomly or based on the tools' logic." + }, + { + "id": "oas-3.2.openapi-object.tags.must-each-tag-name-list-unique", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 106, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-tags", + "level": "MUST", + "terms": ["MUST"], + "text": "Each tag name in the list MUST be unique." + }, + { + "id": "oas-3.2.openapi-object.webhooks", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 103, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-webhooks", + "level": "field", + "terms": [], + "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An example is available." + }, + { + "id": "oas-3.2.openapi-object.webhooks.may-incoming-webhooks-received-part-api-api", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 103, + "section": "Objects and Fields > OpenAPI Object > Fixed Fields", + "anchor": "oas-webhooks", + "level": "MAY", + "terms": ["MAY"], + "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement." + }, + { + "id": "oas-3.2.operation-object.callbacks", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 687, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-callbacks", + "level": "field", + "terms": [], + "text": "A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses." + }, + { + "id": "oas-3.2.operation-object.deprecated", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 688, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-deprecated", + "level": "field", + "terms": [], + "text": "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`." + }, + { + "id": "oas-3.2.operation-object.deprecated.should-consumers-refrain-usage-declared-operation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 688, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Consumers SHOULD refrain from usage of the declared operation." + }, + { + "id": "oas-3.2.operation-object.description", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 681, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-description", "level": "field", "terms": [], - "text": "A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object. Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + "text": "A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.link-object.operationRef.may-relative-operationref-values-used-locate-existing", + "id": "oas-3.2.operation-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2425, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-ref", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 681, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-description", "level": "MAY", "terms": ["MAY"], - "text": "Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.link-object.operationRef.must-field-mutually-exclusive-operationid-field-point", + "id": "oas-3.2.operation-object.externalDocs", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2425, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-operation-ref", - "level": "MUST", - "terms": ["MUST"], - "text": "This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 682, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this operation." }, { - "id": "oas-3.1.link-object.operationref-examples.may-operationid-optional-field-operation-object-references", + "id": "oas-3.2.operation-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2512, - "section": "Specification > Schema > Link Object > Examples > `operationRef` Examples", - "anchor": "operationref-examples", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 692, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "fixed-fields-7", "level": "MAY", "terms": ["MAY"], - "text": "As the `operationId` is an optional field in an Operation Object, references MAY instead be made through a URI-reference with `operationRef`." + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.link-object.parameters", + "id": "oas-3.2.operation-object.operationId", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2427, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-parameters", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 683, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-id", "level": "field", "terms": [], - "text": "A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation." + "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." }, { - "id": "oas-3.1.link-object.requestBody", + "id": "oas-3.2.operation-object.operationId.must-id-unique-among-all-operations-described", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2428, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-request-body", - "level": "field", - "terms": [], - "text": "A literal value or {expression} to use as a request body when calling the target operation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 683, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "MUST", + "terms": ["MUST"], + "text": "The id MUST be unique among all operations described in the API." }, { - "id": "oas-3.1.link-object.server", + "id": "oas-3.2.operation-object.operationId.recommended-tools-libraries-use-operationid-uniquely-identify", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2430, - "section": "Specification > Schema > Link Object > Fixed Fields", - "anchor": "link-server", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 683, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-id", + "level": "SHOULD", + "terms": ["MAY", "RECOMMENDED"], + "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + }, + { + "id": "oas-3.2.operation-object.parameters", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 684, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-parameters", "level": "field", "terms": [], - "text": "A server object to be used by the target operation." + "text": "A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." }, { - "id": "oas-3.1.media-type-object.considerations-for-file-uploads.may-addition-specific-media-types-specified", + "id": "oas-3.2.operation-object.parameters.must-not-list-include-duplicated-parameters", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1655, - "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", - "level": "MAY", - "terms": ["MAY"], - "text": "In addition, specific media types MAY be specified:" + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 684, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-parameters", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." }, { - "id": "oas-3.1.media-type-object.considerations-for-file-uploads.may-content-transferred-binary-octet-stream-omit", + "id": "oas-3.2.operation-object.requestBody", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1625, - "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", - "level": "MAY", - "terms": ["MAY"], - "text": "Content transferred in binary (octet-stream) MAY omit `schema`:" + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 685, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-request-body", + "level": "field", + "terms": [], + "text": "The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP specification RFC9110 has explicitly defined semantics for request bodies. In other cases where the HTTP spec discourages message content (such as GET and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." }, { - "id": "oas-3.1.media-type-object.considerations-for-file-uploads.must-upload-multiple-files-multipart-media-type", + "id": "oas-3.2.operation-object.requestBody.should-other-cases-http-spec-discourages-message", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1666, - "section": "Specification > Schema > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", - "level": "MUST", - "terms": ["MUST"], - "text": "To upload multiple files, a `multipart` media type MUST be used as shown under Example: Multipart Form with Multiple Files." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 685, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-request-body", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In other cases where the HTTP spec discourages message content (such as GET and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." }, { - "id": "oas-3.1.media-type-object.encoding", + "id": "oas-3.2.operation-object.responses", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1551, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 686, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-responses", "level": "field", "terms": [], - "text": "A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object." - }, - { - "id": "oas-3.1.media-type-object.encoding.must-key-being-property-name-exist-schema", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1551, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", - "level": "MUST", - "terms": ["MUST"], - "text": "The key, being the property name, MUST exist in the schema as a property." + "text": "The list of possible responses as they are returned from executing this operation." }, { - "id": "oas-3.1.media-type-object.encoding.shall-encoding-field-only-apply-request-body", + "id": "oas-3.2.operation-object.security", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1551, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `encoding` field SHALL only apply to Request Body Objects, and only when the media type is `multipart` or `application/x-www-form-urlencoded`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 689, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-security", + "level": "field", + "terms": [], + "text": "A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." }, { - "id": "oas-3.1.media-type-object.example", + "id": "oas-3.2.operation-object.servers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1549, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-example", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 690, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-servers", "level": "field", "terms": [], - "text": "Example of the media type; see Working With Examples." + "text": "An alternative `servers` array to service this operation. If a `servers` array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value." }, { - "id": "oas-3.1.media-type-object.examples", + "id": "oas-3.2.operation-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1550, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-examples", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 680, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-summary", "level": "field", "terms": [], - "text": "Examples of the media type; see Working With Examples." + "text": "A short summary of what the operation does." }, { - "id": "oas-3.1.media-type-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.operation-object.tags", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1553, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "fixed-fields-11", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 679, + "section": "Objects and Fields > Operation Object > Fixed Fields", + "anchor": "operation-tags", + "level": "field", + "terms": [], + "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." }, { - "id": "oas-3.1.media-type-object.schema", + "id": "oas-3.2.parameter-object.allowEmptyValue", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1548, - "section": "Specification > Schema > Media Type Object > Fixed Fields", - "anchor": "media-type-schema", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 796, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", "level": "field", "terms": [], - "text": "The schema defining the content of the request, response, parameter, or header." + "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for `query` parameters. Deprecated: Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." }, { - "id": "oas-3.1.media-type-object.shall-example-examples-fields-mutually-exclusive-either", + "id": "oas-3.2.parameter-object.allowEmptyValue.not-recommended-deprecated-use-field-likely-removed-later", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1540, - "section": "Specification > Schema > Media Type Object", - "anchor": "media-type-object", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 796, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "Deprecated: Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + }, + { + "id": "oas-3.2.parameter-object.allowEmptyValue.shall-style-used-behavior-n-cannot-serialized", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 796, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", "level": "MUST", "terms": ["SHALL"], - "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + "text": "If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored." }, { - "id": "oas-3.1.media-type-object.should-example-examples-provided-example-match-specified", + "id": "oas-3.2.parameter-object.allowEmptyValue.should-true-clients-pass-zero-length-string", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1540, - "section": "Specification > Schema > Media Type Object", - "anchor": "media-type-object", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 796, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-allow-empty-value", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding." + "terms": ["MAY", "SHOULD"], + "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused." }, { - "id": "oas-3.1.media-types.should-media-type-definitions-compliance-rfc6838", + "id": "oas-3.2.parameter-object.allowReserved", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 50, - "section": "Definitions > Media Types", - "anchor": "media-types", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The media type definitions SHOULD be in compliance with RFC6838." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 825, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-allow-reserved", + "level": "field", + "terms": [], + "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed by the rules of the `in` destination or media type, or are not allowed in the path by this specification; see URL Percent-Encoding for details. The default value is `false`. This field only applies to `in` and `style` values that automatically percent-encode (that is: `in: path`, `in: query`, and `in: cookie` with `style: form`)." }, { - "id": "oas-3.1.non-rfc6570-field-values-and-combinations.may-implementations-create-properly-delimited-uri-template", + "id": "oas-3.2.parameter-object.common-fixed-fields.may-fields-used-either-content-schema", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4376, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 785, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based on `allowReserved`)." - }, - { - "id": "oas-3.1.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4385, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", - "level": "MUST", - "terms": ["MUST"], - "text": "A parameter name that includes characters outside of the allowed RFC6570 variable character set MUST be percent-encoded before it can be used in a URI Template." + "text": "These fields MAY be used with either `content` or `schema`." }, { - "id": "oas-3.1.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", + "id": "oas-3.2.parameter-object.common-fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4376, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Configurations with no direct RFC6570 equivalent SHOULD also be handled according to RFC6570." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 800, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "common-fixed-fields", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.oauth-flow-object.authorizationUrl", + "id": "oas-3.2.parameter-object.content", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4078, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 838, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "parameter-content", "level": "field", "terms": [], - "text": "REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "text": "A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry." }, { - "id": "oas-3.1.oauth-flow-object.authorizationUrl.must-form-url", + "id": "oas-3.2.parameter-object.content.must-map-only-contain-one-entry", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4078, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 838, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", + "anchor": "parameter-content", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "The map MUST only contain one entry." }, { - "id": "oas-3.1.oauth-flow-object.authorizationUrl.required", + "id": "oas-3.2.parameter-object.deprecated", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4078, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 795, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-deprecated", + "level": "field", + "terms": [], + "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`." }, { - "id": "oas-3.1.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.parameter-object.deprecated.should-specifies-parameter-deprecated-transitioned-out-usage", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4083, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "fixed-fields-25", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 795, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-deprecated", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage." }, { - "id": "oas-3.1.oauth-flow-object.refreshUrl", + "id": "oas-3.2.parameter-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4080, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-refresh-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 793, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-description", "level": "field", "terms": [], - "text": "The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "text": "A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.oauth-flow-object.refreshUrl.must-form-url", + "id": "oas-3.2.parameter-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4080, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-refresh-url", - "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 793, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.oauth-flow-object.scopes", + "id": "oas-3.2.parameter-object.example", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4081, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 797, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-example", "level": "field", "terms": [], - "text": "REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty." - }, - { - "id": "oas-3.1.oauth-flow-object.scopes.may-map-empty", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4081, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", - "level": "MAY", - "terms": ["MAY"], - "text": "The map MAY be empty." + "text": "Example of the parameter's potential value; see Working With Examples." }, { - "id": "oas-3.1.oauth-flow-object.scopes.required", + "id": "oas-3.2.parameter-object.examples", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4081, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 798, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-examples", + "level": "field", + "terms": [], + "text": "Examples of the parameter's potential value; see Working With Examples." }, { - "id": "oas-3.1.oauth-flow-object.tokenUrl", + "id": "oas-3.2.parameter-object.explode", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4079, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 824, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-explode", "level": "field", "terms": [], - "text": "REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "text": "When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters, or when `style` is `\"deepObject\"`, this field has no effect. When `style` is `\"form\"` or `\"cookie\"`, the default value is `true`. For all other styles, the default value is `false`." }, { - "id": "oas-3.1.oauth-flow-object.tokenUrl.must-form-url", + "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-cases-implementations-pass-values-through-unchanged", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4079, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 819, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "In these cases, implementations MUST pass values through unchanged rather than attempting to quote or escape them, as the quoting rules for headers and escaping conventions for cookies vary too widely to be performed automatically; see Appendix D for guidance on quoting and escaping." }, { - "id": "oas-3.1.oauth-flow-object.tokenUrl.required", + "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-not-fields-used-querystring", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4079, - "section": "Specification > Schema > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 808, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "These fields MUST NOT be used with `in: \"querystring\"`." }, { - "id": "oas-3.1.oauth-flows-object.authorizationCode", + "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-not-parsing-parameters-any-apparent-percent-encoding", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4066, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-authorization-code", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 816, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "When parsing these parameters, any apparent percent-encoding MUST NOT be decoded." }, { - "id": "oas-3.1.oauth-flows-object.clientCredentials", + "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-not-serializing-values-uri-percent-encoding-applied", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4065, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-client-credentials", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 812, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "When serializing these values, URI percent-encoding MUST NOT be applied." }, { - "id": "oas-3.1.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-using-rfc6570-implementation-automatically-performs-encoding", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4068, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "fixed-fields-24", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 817, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "fixed-fields-for-use-with-schema", + "level": "MUST", + "terms": ["MUST"], + "text": "If using an RFC6570 implementation that automatically performs encoding or decoding steps, the steps MUST be undone before use." }, { - "id": "oas-3.1.oauth-flows-object.implicit", + "id": "oas-3.2.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4063, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-implicit", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Implicit flow" + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 779, + "section": "Objects and Fields > Parameter Object > Fixed Fields", + "anchor": "fixed-fields-9", + "level": "MUST", + "terms": ["MUST"], + "text": "Parameter Objects MUST include either a `content` field or a `schema` field, but not both." }, { - "id": "oas-3.1.oauth-flows-object.password", + "id": "oas-3.2.parameter-object.in", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4064, - "section": "Specification > Schema > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-password", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 792, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-in", "level": "field", "terms": [], - "text": "Configuration for the OAuth Resource Owner Password flow" + "text": "REQUIRED. The location of the parameter. Possible values are `\"query\"`, `\"querystring\"`, `\"header\"`, `\"path\"` or `\"cookie\"`." }, { - "id": "oas-3.1.openapi-description-structure.may-openapi-description-oad-made-up-single", + "id": "oas-3.2.parameter-object.in.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 127, - "section": "Specification > OpenAPI Description Structure", - "anchor": "openapi-description-structure", - "level": "MAY", - "terms": ["MAY"], - "text": "An OpenAPI Description (OAD) MAY be made up of a single JSON or YAML document or be divided into multiple, connected parts at the discretion of the author." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 792, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-in", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.openapi-description-structure.recommended-entry-document-oad-named-openapi-json", + "id": "oas-3.2.parameter-object.name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 131, - "section": "Specification > OpenAPI Description Structure", - "anchor": "openapi-description-structure", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is RECOMMENDED that the entry document of an OAD be named: `openapi.json` or `openapi.yaml`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 791, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the parameter. Parameter names are _case-sensitive_. If `in` is `\"path\"`, the `name` field MUST correspond to a single template expression occurring within the path field in the Paths Object. See Path Templating for further information. If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored. If `in` is `\"querystring\"`, or for certain combinations of `style` and `explode`, the value of `name` is not used in the parameter serialization. For all other cases, the `name` corresponds to the parameter name used by the `in` field." }, { - "id": "oas-3.1.openapi-description.must-oad-uses-conforms-openapi-specification-contain", + "id": "oas-3.2.parameter-object.name.must-path-name-field-correspond-single-template", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 23, - "section": "Definitions > OpenAPI Description", - "anchor": "openapi-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 791, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", "level": "MUST", "terms": ["MUST"], - "text": "An OAD uses and conforms to the OpenAPI Specification, and MUST contain at least one paths field, components field, or webhooks field." + "text": "If `in` is `\"path\"`, the `name` field MUST correspond to a single template expression occurring within the path field in the Paths Object." }, { - "id": "oas-3.1.openapi-object.components", + "id": "oas-3.2.parameter-object.name.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 331, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-components", - "level": "field", - "terms": [], - "text": "An element to hold various Objects for the OpenAPI Description." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 791, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.openapi-object.externalDocs", + "id": "oas-3.2.parameter-object.name.shall-header-name-field-accept-content-type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 334, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 791, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-name", + "level": "MUST", + "terms": ["SHALL"], + "text": "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored." }, { - "id": "oas-3.1.openapi-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.parameter-object.parameter-locations.must-not-query-parameters-appended-url-character-subsequent", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 336, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "fixed-fields", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 772, + "section": "Objects and Fields > Parameter Object > Parameter Locations", + "anchor": "parameter-locations", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "query - Parameters that are appended to the URL with the `?` character (or for subsequent query parameters, with the `&` character); MUST NOT appear in the same operation (or in the operation's path-item) as an `in: \"querystring\"` parameter." }, { - "id": "oas-3.1.openapi-object.info", + "id": "oas-3.2.parameter-object.parameter-locations.must-querystring-parameter-treats-entire-url-query", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 326, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 773, + "section": "Objects and Fields > Parameter Object > Parameter Locations", + "anchor": "parameter-locations", + "level": "MUST", + "terms": ["MUST", "MUST NOT"], + "text": "querystring - A parameter that treats the entire URL query string as a value which MUST be specified using the `content` field, most often with media type `application/x-www-form-urlencoded` using Encoding Objects in the same way as with request bodies of that media type; MUST NOT appear more than once, and MUST NOT appear in the same operation (or in the operation's path-item) as any `in: \"query\"` parameters." + }, + { + "id": "oas-3.2.parameter-object.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 794, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", "level": "field", "terms": [], - "text": "REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required." + "text": "Determines whether this parameter is mandatory. If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`." }, { - "id": "oas-3.1.openapi-object.info.may-metadata-used-tooling-required", + "id": "oas-3.2.parameter-object.required.may-otherwise-field-included-default-value-false", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 326, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 794, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", "level": "MAY", "terms": ["MAY"], - "text": "The metadata MAY be used by tooling as required." + "text": "Otherwise, the field MAY be included and its default value is `false`." }, { - "id": "oas-3.1.openapi-object.info.required", + "id": "oas-3.2.parameter-object.required.required-parameter-location-path-field-value-true", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 326, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 794, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", + "anchor": "parameter-required", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["REQUIRED", "MUST"], + "text": "If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`." }, { - "id": "oas-3.1.openapi-object.jsonSchemaDialect", + "id": "oas-3.2.parameter-object.schema", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 327, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-json-schema-dialect", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 826, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-schema", "level": "field", "terms": [], - "text": "The default value for the `$schema` keyword within Schema Objects contained within this OAS document. This MUST be in the form of a URI." + "text": "The schema defining the type and other constraints used for the parameter." }, { - "id": "oas-3.1.openapi-object.jsonSchemaDialect.must-form-uri", + "id": "oas-3.2.parameter-object.serialization-and-examples.must-cases-parameter-name-inherent-part-constructing", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 327, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-json-schema-dialect", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 891, + "section": "Objects and Fields > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URI." - }, - { - "id": "oas-3.1.openapi-object.openapi", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 325, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", - "level": "field", - "terms": [], - "text": "REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document. This is _not_ related to the `info.version` string, which is the version of the OpenAPI Document." + "text": "In cases where the parameter name is an inherent part of constructing the serialization, such as the `name=value` pairs produced by the combination of `style: \"form\", explode: false`, the name and any delimiter between the name and value MUST be included." }, { - "id": "oas-3.1.openapi-object.openapi.must-string-version-number-openapi-specification-openapi", + "id": "oas-3.2.parameter-object.serialization-and-examples.must-matrix-label-styles-produce-leading-delimiter", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 325, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 893, + "section": "Objects and Fields > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", "level": "MUST", "terms": ["MUST"], - "text": "This string MUST be the version number of the OpenAPI Specification that the OpenAPI Document uses." + "text": "The `matrix` and `label` styles produce a leading delimiter which is always a valid part of the serialization and MUST be included." }, { - "id": "oas-3.1.openapi-object.openapi.required", + "id": "oas-3.2.parameter-object.serialization-and-examples.must-not-headers-header-name-included-part-serialization", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 325, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 898, + "section": "Objects and Fields > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "For headers, the header name MUST NOT be included as part of the serialization, as it is never part of the RFC6570-derived result." }, { - "id": "oas-3.1.openapi-object.openapi.should-openapi-field-used-tooling-interpret-openapi", + "id": "oas-3.2.parameter-object.serialization-and-examples.must-not-suitability-either-delimiter-depends-query-string", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 325, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The `openapi` field SHOULD be used by tooling to interpret the OpenAPI Document." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 893, + "section": "Objects and Fields > Parameter Object > Serialization and Examples", + "anchor": "serialization-and-examples", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "As the suitability of either delimiter depends on where in the query string the parameter occurs, as well as whether it is in a URI or in `application/x-www-form-urlencoded` content, this leading delimiter MUST NOT be included in examples of individual parameters or media type documents." }, { - "id": "oas-3.1.openapi-object.paths", + "id": "oas-3.2.parameter-object.style", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 329, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-paths", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 823, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-style", "level": "field", "terms": [], - "text": "The available paths and operations for the API." + "text": "Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"` (for compatibility reasons; note that `style: \"cookie\"` SHOULD be used with `in: \"cookie\"`; see Appendix D for details)." }, { - "id": "oas-3.1.openapi-object.security", + "id": "oas-3.2.parameter-object.style-values.must-analogous-form-but-following-rfc6265-cookie", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 332, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-security", - "level": "field", - "terms": [], - "text": "A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 853, + "section": "Objects and Fields > Parameter Object > Style Values", + "anchor": "style-values", + "level": "MUST", + "terms": ["MUST"], + "text": "Analogous to `form`, but following [RFC6265] `Cookie` syntax rules, meaning that name-value pairs are separated by a semicolon followed by a single space (e.g. `n1=v1; n2=v2`), and no percent-encoding or other escaping is applied; data values that require any sort of escaping MUST be provided in escaped form." }, { - "id": "oas-3.1.openapi-object.servers", + "id": "oas-3.2.parameter-object.style.should-default-values-based-value-query-form", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 328, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-servers", - "level": "field", - "terms": [], - "text": "An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be a Server Object with a url value of `/`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 823, + "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", + "anchor": "parameter-style", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"` (for compatibility reasons; note that `style: \"cookie\"` SHOULD be used with `in: \"cookie\"`; see Appendix D for details)." }, { - "id": "oas-3.1.openapi-object.tags", + "id": "oas-3.2.parameter-object.url-percent-encoding.must-all-api-urls-successfully-parse-percent", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 333, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", - "level": "field", - "terms": [], - "text": "A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 857, + "section": "Objects and Fields > Parameter Object > URL Percent-Encoding", + "anchor": "url-percent-encoding", + "level": "MUST", + "terms": ["MUST"], + "text": "All API URLs MUST successfully parse and percent-decode using [RFC3986] rules." }, { - "id": "oas-3.1.openapi-object.tags.may-tags-not-declared-organized-randomly-based", + "id": "oas-3.2.parameter-object.url-percent-encoding.must-content-application-x-www-form-urlencoded", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 333, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", - "level": "MAY", - "terms": ["MAY"], - "text": "The tags that are not declared MAY be organized randomly or based on the tools' logic." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 859, + "section": "Objects and Fields > Parameter Object > URL Percent-Encoding", + "anchor": "url-percent-encoding", + "level": "MUST", + "terms": ["MUST"], + "text": "Content in the `application/x-www-form-urlencoded` format, including query strings produced by Parameter Objects with `in: \"query\"`, MUST also successfully parse and percent-decode using [WHATWG-URL] rules, including treating non-percent-encoded `+` as an escaped space character." }, { - "id": "oas-3.1.openapi-object.tags.must-each-tag-name-list-unique", + "id": "oas-3.2.parameter-object.url-percent-encoding.must-not-reserved-characters-percent-encoded-being-used", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 333, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 875, + "section": "Objects and Fields > Parameter Object > URL Percent-Encoding", + "anchor": "url-percent-encoding", "level": "MUST", - "terms": ["MUST"], - "text": "Each tag name in the list MUST be unique." + "terms": ["MUST NOT"], + "text": "Reserved characters MUST NOT be percent-encoded when being used for reserved purposes such as `&=+` for `form-urlencoded` or `,` for delimiting non-exploded array and object values in RFC6570 expansions." }, { - "id": "oas-3.1.openapi-object.webhooks", + "id": "oas-3.2.path-item-object.$ref", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 330, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-webhooks", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 599, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-ref", "level": "field", "terms": [], - "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An example is available." + "text": "Allows for a referenced definition of this path item. The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving Relative References. _Note: The behavior of `$ref` with adjacent properties is likely to change in future versions of this specification to bring it into closer alignment with the behavior of the Reference Object._" }, { - "id": "oas-3.1.openapi-object.webhooks.may-incoming-webhooks-received-part-api-api", + "id": "oas-3.2.path-item-object.$ref.must-value-form-uri-referenced-structure-form", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 330, - "section": "Specification > Schema > OpenAPI Object > Fixed Fields", - "anchor": "oas-webhooks", - "level": "MAY", - "terms": ["MAY"], - "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 599, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-ref", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object." }, { - "id": "oas-3.1.operation-object.callbacks", + "id": "oas-3.2.path-item-object.additionalOperations", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 983, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-callbacks", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 611, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-additional-operations", "level": "field", "terms": [], - "text": "A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses." + "text": "A map of additional operations on this path. The map key is the HTTP method with the same capitalization that is to be sent in the request. This map MUST NOT contain any entry for the methods that can be defined by other fixed fields with Operation Object values (e.g. no `POST` entry, as the `post` field is used for this method)." }, { - "id": "oas-3.1.operation-object.deprecated", + "id": "oas-3.2.path-item-object.additionalOperations.must-not-map-contain-any-entry-methods-defined", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 984, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-deprecated", - "level": "field", - "terms": [], - "text": "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 611, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-additional-operations", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "This map MUST NOT contain any entry for the methods that can be defined by other fixed fields with Operation Object values (e.g. no `POST` entry, as the `post` field is used for this method)." }, { - "id": "oas-3.1.operation-object.deprecated.should-consumers-refrain-usage-declared-operation", + "id": "oas-3.2.path-item-object.delete", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 984, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-deprecated", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Consumers SHOULD refrain from usage of the declared operation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 605, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-delete", + "level": "field", + "terms": [], + "text": "A definition of a DELETE operation on this path." }, { - "id": "oas-3.1.operation-object.description", + "id": "oas-3.2.path-item-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 977, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 601, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-description", "level": "field", "terms": [], - "text": "A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation." + "text": "An optional string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.operation-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.path-item-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 977, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 601, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-description", "level": "MAY", "terms": ["MAY"], "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.operation-object.externalDocs", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 978, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this operation." - }, - { - "id": "oas-3.1.operation-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.path-item-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 988, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "fixed-fields-7", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 615, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "fixed-fields-6", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.operation-object.operationId", + "id": "oas-3.2.path-item-object.get", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 979, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-id", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 602, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-get", "level": "field", "terms": [], - "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." - }, - { - "id": "oas-3.1.operation-object.operationId.must-id-unique-among-all-operations-described", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 979, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-id", - "level": "MUST", - "terms": ["MUST"], - "text": "The id MUST be unique among all operations described in the API." - }, - { - "id": "oas-3.1.operation-object.operationId.recommended-tools-libraries-use-operationid-uniquely-identify", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 979, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-id", - "level": "SHOULD", - "terms": ["MAY", "RECOMMENDED"], - "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + "text": "A definition of a GET operation on this path." }, { - "id": "oas-3.1.operation-object.parameters", + "id": "oas-3.2.path-item-object.head", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 980, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-parameters", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 607, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-head", "level": "field", "terms": [], - "text": "A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + "text": "A definition of a HEAD operation on this path." }, { - "id": "oas-3.1.operation-object.parameters.must-not-list-include-duplicated-parameters", + "id": "oas-3.2.path-item-object.may-path-item-empty-due-acl-constraints", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 980, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-parameters", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The list MUST NOT include duplicated parameters." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 591, + "section": "Objects and Fields > Path Item Object", + "anchor": "path-item-object", + "level": "MAY", + "terms": ["MAY"], + "text": "A Path Item MAY be empty, due to ACL constraints." }, { - "id": "oas-3.1.operation-object.requestBody", + "id": "oas-3.2.path-item-object.options", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 981, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-request-body", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 606, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-options", "level": "field", "terms": [], - "text": "The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." - }, - { - "id": "oas-3.1.operation-object.requestBody.should-other-cases-http-spec-vague-get", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 981, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-request-body", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "In other cases where the HTTP spec is vague (such as GET, HEAD and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." + "text": "A definition of a OPTIONS operation on this path." }, { - "id": "oas-3.1.operation-object.responses", + "id": "oas-3.2.path-item-object.parameters", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 982, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-responses", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 613, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-parameters", "level": "field", "terms": [], - "text": "The list of possible responses as they are returned from executing this operation." + "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." }, { - "id": "oas-3.1.operation-object.security", + "id": "oas-3.2.path-item-object.parameters.must-not-list-include-duplicated-parameters", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 985, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-security", - "level": "field", - "terms": [], - "text": "A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 613, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-parameters", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The list MUST NOT include duplicated parameters." }, { - "id": "oas-3.1.operation-object.servers", + "id": "oas-3.2.path-item-object.patch", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 986, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-servers", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 608, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-patch", "level": "field", "terms": [], - "text": "An alternative `servers` array to service this operation. If a `servers` array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value." + "text": "A definition of a PATCH operation on this path." }, { - "id": "oas-3.1.operation-object.summary", + "id": "oas-3.2.path-item-object.post", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 976, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-summary", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 604, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-post", "level": "field", "terms": [], - "text": "A short summary of what the operation does." + "text": "A definition of a POST operation on this path." }, { - "id": "oas-3.1.operation-object.tags", + "id": "oas-3.2.path-item-object.put", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 975, - "section": "Specification > Schema > Operation Object > Fixed Fields", - "anchor": "operation-tags", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 603, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-put", "level": "field", "terms": [], - "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." + "text": "A definition of a PUT operation on this path." }, { - "id": "oas-3.1.parameter-object.allowEmptyValue", + "id": "oas-3.2.path-item-object.query", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1156, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 610, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-query", "level": "field", "terms": [], - "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for `query` parameters. Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." - }, - { - "id": "oas-3.1.parameter-object.allowEmptyValue.not-recommended-use-field-likely-removed-later-revision", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1156, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + "text": "A definition of a QUERY operation, as defined in RFC10008, on this path." }, { - "id": "oas-3.1.parameter-object.allowEmptyValue.shall-style-used-behavior-n-cannot-serialized", + "id": "oas-3.2.path-item-object.servers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1156, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "MUST", - "terms": ["SHALL"], - "text": "If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 612, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-servers", + "level": "field", + "terms": [], + "text": "An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the OpenAPI Object level, it will be overridden by this value." }, { - "id": "oas-3.1.parameter-object.allowEmptyValue.should-true-clients-pass-zero-length-string", + "id": "oas-3.2.path-item-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1156, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "SHOULD", - "terms": ["MAY", "SHOULD"], - "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 600, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-summary", + "level": "field", + "terms": [], + "text": "An optional string summary, intended to apply to all operations in this path." }, { - "id": "oas-3.1.parameter-object.allowReserved", + "id": "oas-3.2.path-item-object.trace", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1177, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-allow-reserved", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 609, + "section": "Objects and Fields > Path Item Object > Fixed Fields", + "anchor": "path-item-trace", "level": "field", "terms": [], - "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the query string (`[`, `]`, `#`), or have a special meaning in `application/x-www-form-urlencoded` (`-`, `&`, `+`); see URL Percent-Encoding for details. This field only applies to parameters with an `in` value of `query`. The default value is `false`." + "text": "A definition of a TRACE operation on this path." }, { - "id": "oas-3.1.parameter-object.common-fixed-fields.may-fields-used-either-content-schema", + "id": "oas-3.2.paths-object.may-paths-object-empty-due-access-control", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1147, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 504, + "section": "Objects and Fields > Paths Object", + "anchor": "paths-object", "level": "MAY", "terms": ["MAY"], - "text": "These fields MAY be used with either `content` or `schema`." + "text": "The Paths Object MAY be empty, due to Access Control List (ACL) constraints." }, { - "id": "oas-3.1.parameter-object.common-fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.paths-object.path-templating.must-each-template-expression-path-correspond-path", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1158, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 519, + "section": "Objects and Fields > Paths Object > Path Templating", + "anchor": "path-templating", + "level": "MUST", + "terms": ["MUST"], + "text": "Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations." }, { - "id": "oas-3.1.parameter-object.content", + "id": "oas-3.2.paths-object.path-templating.must-not-each-template-expression-appear-more-once", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1191, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "parameter-content", - "level": "field", - "terms": [], - "text": "A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 545, + "section": "Objects and Fields > Paths Object > Path Templating", + "anchor": "path-templating", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Each template expression MUST NOT appear more than once in a single path template." }, { - "id": "oas-3.1.parameter-object.content.must-map-only-contain-one-entry", + "id": "oas-3.2.paths-object.path-templating.must-not-value-path-parameters-contain-any-unescaped", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1191, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "parameter-content", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 521, + "section": "Objects and Fields > Paths Object > Path Templating", + "anchor": "path-templating", "level": "MUST", - "terms": ["MUST"], - "text": "The map MUST only contain one entry." + "terms": ["MUST NOT"], + "text": "The value for these path parameters MUST NOT contain any unescaped \"generic syntax\" characters described by RFC3986: forward slashes (`/`), question marks (`?`), or hashes (`#`)." }, { - "id": "oas-3.1.parameter-object.deprecated", + "id": "oas-3.2.paths-object.pattern-path", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1155, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-deprecated", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 511, + "section": "Objects and Fields > Paths Object > Patterned Fields", + "anchor": "paths-path", "level": "field", "terms": [], - "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + "text": "A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The URL from the Server Object's `url` field, resolved and with template variables substituted, has the path appended (no relative URL resolution) to it in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use." }, { - "id": "oas-3.1.parameter-object.deprecated.should-specifies-parameter-deprecated-transitioned-out-usage", + "id": "oas-3.2.paths-object.pattern-path.must-field-name-begin-forward-slash", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1155, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-deprecated", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 511, + "section": "Objects and Fields > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with a forward slash (`/`)." }, { - "id": "oas-3.1.parameter-object.description", + "id": "oas-3.2.paths-object.pattern-path.must-not-templated-paths-same-hierarchy-but-different", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1153, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-description", - "level": "field", - "terms": [], - "text": "A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 511, + "section": "Objects and Fields > Paths Object > Patterned Fields", + "anchor": "paths-path", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical." }, { - "id": "oas-3.1.parameter-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.paths-object.patterned-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1153, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 513, + "section": "Objects and Fields > Paths Object > Patterned Fields", + "anchor": "patterned-fields", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.parameter-object.example", + "id": "oas-3.2.percent-encoding-and-cookies.must-not-while-percent-encoding-seems-more-common", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1179, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-example", - "level": "field", - "terms": [], - "text": "Example of the parameter's potential value; see Working With Examples." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5152, + "section": "Appendix D: Serializing Headers and Cookies > Percent-Encoding and Cookies", + "anchor": "percent-encoding-and-cookies", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "While percent-encoding seems more common as an escaping mechanism than the base64 encoding (`contentEncoding`: \"base64\") recommended by [RFC6265], section 5.6 of draft-ietf-httpbis-rfc6265bis-20, the proposed update to that RFC notes that cookies sent in the `Set-Cookie` response header that appear to be percent-encoded MUST NOT be decoded when stored by the client, which would mean that they are already encoded when retrieved from that storage for use in the `Cookie` request header." }, { - "id": "oas-3.1.parameter-object.examples", + "id": "oas-3.2.percent-encoding-and-form-data.must-users-wishing-use-percent-encoding-way", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1180, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-examples", - "level": "field", - "terms": [], - "text": "Examples of the parameter's potential value; see Working With Examples." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5199, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and `form-data`", + "anchor": "percent-encoding-and-form-data", + "level": "MUST", + "terms": ["MUST"], + "text": "Users wishing to use percent-encoding in this way MUST provide the data in percent-encoded form, as percent-encoding is not automatically applied for this media type regardless of which Encoding Object fields are used." }, { - "id": "oas-3.1.parameter-object.explode", + "id": "oas-3.2.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1176, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-explode", - "level": "field", - "terms": [], - "text": "When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. Note that despite `false` being the default for `deepObject`, the combination of `false` with `deepObject` is undefined." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5250, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", + "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "level": "MUST", + "terms": ["MUST"], + "text": "The `[`, `]`, `|`, and space characters, which are used as delimiters for the `deepObject`, `pipeDelimited`, and `spaceDelimited` styles, respectively, all MUST be percent-encoded to comply with [RFC3986]." }, { - "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-content.recommended-using-content-text-plain-media-type", + "id": "oas-3.2.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1186, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "fixed-fields-for-use-with-content", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5261, + "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", + "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", "level": "SHOULD", "terms": ["RECOMMENDED"], - "text": "Using `content` with a `text/plain` media type is RECOMMENDED for `in: \"cookie\"` parameters where the `schema` strategy's percent-encoding and/or delimiter rules are not appropriate." + "text": "For maximum interoperability, it is RECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely." }, { - "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", + "id": "oas-3.2.reference-object.$ref", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1168, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2963, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-ref", + "level": "field", + "terms": [], + "text": "REQUIRED. The reference identifier. This MUST be in the form of a URI." + }, + { + "id": "oas-3.2.reference-object.$ref.must-form-uri", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2963, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-ref", "level": "MUST", "terms": ["MUST"], - "text": "Implementations MUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; see Appendix D for guidance on quoting and escaping." + "text": "This MUST be in the form of a URI." }, { - "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.must-not-serializing-header-parameters-schema-uri-percent", + "id": "oas-3.2.reference-object.$ref.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1168, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2963, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-ref", "level": "MUST", - "terms": ["MUST NOT", "MUST"], - "text": "When serializing `in: \"header\"` parameters with `schema`, URI percent-encoding MUST NOT be applied; if using an RFC6570 implementation that automatically applies it, it MUST be removed before use." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-see-appendix", + "id": "oas-3.2.reference-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1171, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Serializing with `schema` is NOT RECOMMENDED for `in: \"cookie\"` parameters; see Appendix D for details." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2965, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-description", + "level": "field", + "terms": [], + "text": "A description which by default SHOULD override that of the referenced component. CommonMark syntax MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect." }, { - "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", + "id": "oas-3.2.reference-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1164, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `example` and `examples` fields are mutually exclusive, and if either is present it SHALL _override_ any `example` in the schema." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2965, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.parameter-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", + "id": "oas-3.2.reference-object.description.should-description-default-override-referenced-component", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1164, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2965, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-description", "level": "SHOULD", "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided in conjunction with the `schema` field, the example SHOULD match the specified schema and follow the prescribed serialization strategy for the parameter." + "text": "A description which by default SHOULD override that of the referenced component." }, { - "id": "oas-3.1.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field", + "id": "oas-3.2.reference-object.fixed-fields.shall-object-cannot-extended-additional-properties-any", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1141, - "section": "Specification > Schema > Parameter Object > Fixed Fields", - "anchor": "fixed-fields-9", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2967, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "fixed-fields-19", "level": "MUST", - "terms": ["MUST"], - "text": "Parameter Objects MUST include either a `content` field or a `schema` field, but not both." + "terms": ["SHALL"], + "text": "This object cannot be extended with additional properties, and any properties added SHALL be ignored." }, { - "id": "oas-3.1.parameter-object.in", + "id": "oas-3.2.reference-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1152, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-in", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2964, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-summary", "level": "field", "terms": [], - "text": "REQUIRED. The location of the parameter. Possible values are `\"query\"`, `\"header\"`, `\"path\"` or `\"cookie\"`." + "text": "A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect." }, { - "id": "oas-3.1.parameter-object.in.required", + "id": "oas-3.2.reference-object.summary.should-short-summary-default-override-referenced-component", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1152, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-in", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2964, + "section": "Objects and Fields > Reference Object > Fixed Fields", + "anchor": "reference-summary", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A short summary which by default SHOULD override that of the referenced component." }, { - "id": "oas-3.1.parameter-object.name", + "id": "oas-3.2.request-body-object.content", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1151, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1219, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "request-body-content", "level": "field", "terms": [], - "text": "REQUIRED. The name of the parameter. Parameter names are _case sensitive_. If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object. See Path Templating for further information. If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored. For all other cases, the `name` corresponds to the parameter name used by the `in` field." - }, - { - "id": "oas-3.1.parameter-object.name.must-path-name-field-correspond-template-expression", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1151, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", - "level": "MUST", - "terms": ["MUST"], - "text": "If `in` is `\"path\"`, the `name` field MUST correspond to a template expression occurring within the path field in the Paths Object." + "text": "REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined. For requests that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" }, { - "id": "oas-3.1.parameter-object.name.required", + "id": "oas-3.2.request-body-object.content.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1151, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1219, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "request-body-content", "level": "MUST", "terms": ["REQUIRED"], "text": "REQUIRED." }, { - "id": "oas-3.1.parameter-object.name.shall-header-name-field-accept-content-type", + "id": "oas-3.2.request-body-object.content.should-map-have-least-one-entry-does", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1151, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", - "level": "MUST", - "terms": ["SHALL"], - "text": "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1219, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "request-body-content", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined." }, { - "id": "oas-3.1.parameter-object.required", + "id": "oas-3.2.request-body-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1154, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1218, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "request-body-description", "level": "field", "terms": [], - "text": "Determines whether this parameter is mandatory. If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`." + "text": "A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + }, + { + "id": "oas-3.2.request-body-object.description.may-commonmark-syntax-used-rich-text-representation", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1218, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "request-body-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.parameter-object.required.may-otherwise-field-included-default-value-false", + "id": "oas-3.2.request-body-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1154, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1222, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "fixed-fields-10", "level": "MAY", "terms": ["MAY"], - "text": "Otherwise, the field MAY be included and its default value is `false`." + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.parameter-object.required.required-parameter-location-path-field-value-true", + "id": "oas-3.2.request-body-object.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1154, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", - "level": "MUST", - "terms": ["REQUIRED", "MUST"], - "text": "If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 1220, + "section": "Objects and Fields > Request Body Object > Fixed Fields", + "anchor": "request-body-required", + "level": "field", + "terms": [], + "text": "Determines if the request body is required in the request. Defaults to `false`." }, { - "id": "oas-3.1.parameter-object.schema", + "id": "oas-3.2.response-object.content", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1178, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-schema", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2188, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-content", "level": "field", "terms": [], - "text": "The schema defining the type used for the parameter." + "text": "A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" }, { - "id": "oas-3.1.parameter-object.serialization-and-examples.must-cases-name-inherent-part-constructing-serialization", + "id": "oas-3.2.response-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1239, - "section": "Specification > Schema > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", - "level": "MUST", - "terms": ["MUST"], - "text": "In cases where the name is an inherent part of constructing the serialization, such as the `name=value` pairs produced by `style: \"form\"` or the combination of `style: \"simple\", explode: true`, the name and any delimiter between the name and value MUST be included." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2186, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "field", + "terms": [], + "text": "A description of the response. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.parameter-object.serialization-and-examples.must-matrix-label-styles-produce-leading-delimiter", + "id": "oas-3.2.response-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1241, - "section": "Specification > Schema > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", - "level": "MUST", - "terms": ["MUST"], - "text": "The `matrix` and `label` styles produce a leading delimiter which is always a valid part of the serialization and MUST be included." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2186, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-description", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.parameter-object.serialization-and-examples.must-not-headers-header-name-included-part-serialization", + "id": "oas-3.2.response-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1246, - "section": "Specification > Schema > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "For headers, the header name MUST NOT be included as part of the serialization, as it is never part of the RFC6570-derived result." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2191, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "fixed-fields-14", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.parameter-object.serialization-and-examples.must-not-suitability-either-delimiter-depends-query-string", + "id": "oas-3.2.response-object.headers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1241, - "section": "Specification > Schema > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2187, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-headers", + "level": "field", + "terms": [], + "text": "Maps a header name to its definition. RFC9110 states header names are case-insensitive. If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + }, + { + "id": "oas-3.2.response-object.headers.shall-response-header-defined-name-content-type", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2187, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-headers", "level": "MUST", - "terms": ["MUST NOT"], - "text": "As the suitability of either delimiter depends on where in the query string the parameter occurs, as well as whether it is in a URI or in `application/x-www-form-urlencoded` content, this leading delimiter MUST NOT be included in examples of individual parameters or media type documents." + "terms": ["SHALL"], + "text": "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." }, { - "id": "oas-3.1.parameter-object.style", + "id": "oas-3.2.response-object.links", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1175, - "section": "Specification > Schema > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-style", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2189, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-links", "level": "field", "terms": [], - "text": "Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"`." + "text": "A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects." }, { - "id": "oas-3.1.parameter-object.url-percent-encoding.must-all-api-urls-successfully-parse-percent", + "id": "oas-3.2.response-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1209, - "section": "Specification > Schema > Parameter Object > URL Percent-Encoding", - "anchor": "url-percent-encoding", - "level": "MUST", - "terms": ["MUST"], - "text": "All API URLs MUST successfully parse and percent-decode using [RFC3986] rules." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2185, + "section": "Objects and Fields > Response Object > Fixed Fields", + "anchor": "response-summary", + "level": "field", + "terms": [], + "text": "A short summary of the meaning of the response." }, { - "id": "oas-3.1.parameter-object.url-percent-encoding.must-content-application-x-www-form-urlencoded", + "id": "oas-3.2.responses-object.default", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1211, - "section": "Specification > Schema > Parameter Object > URL Percent-Encoding", - "anchor": "url-percent-encoding", - "level": "MUST", - "terms": ["MUST"], - "text": "Content in the `application/x-www-form-urlencoded` format, including query strings produced by Parameter Objects with `in: \"query\"`, MUST also successfully parse and percent-decode using [RFC1866] rules, including treating non-percent-encoded `+` as an escaped space character." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2142, + "section": "Objects and Fields > Responses Object > Fixed Fields", + "anchor": "responses-default", + "level": "field", + "terms": [], + "text": "The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses." }, { - "id": "oas-3.1.parameter-object.url-percent-encoding.must-not-reserved-characters-percent-encoded-being-used", + "id": "oas-3.2.responses-object.http-status-codes.should-status-codes-selected-available-status-codes", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1227, - "section": "Specification > Schema > Parameter Object > URL Percent-Encoding", - "anchor": "url-percent-encoding", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "Reserved characters MUST NOT be percent-encoded when being used for reserved purposes such as `&=+` for `form-urlencoded` or `,` for delimiting non-exploded array and object values in RFC6570 expansions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2154, + "section": "Objects and Fields > Responses Object > HTTP Status Codes", + "anchor": "http-status-codes", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Status codes SHOULD be selected from the available status codes registered in the IANA Status Code Registry." }, { - "id": "oas-3.1.parsing-documents.may-implementations-support-complete-document-parsing-any", + "id": "oas-3.2.responses-object.may-default-used-default-response-object-all", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 139, - "section": "Specification > OpenAPI Description Structure > Parsing Documents", - "anchor": "parsing-documents", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2131, + "section": "Objects and Fields > Responses Object", + "anchor": "responses-object", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support complete-document parsing in any of the following ways:" + "text": "The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object." }, { - "id": "oas-3.1.parsing-documents.not-recommended-while-possible-structure-certain-openapi-descriptions", + "id": "oas-3.2.responses-object.must-responses-object-contain-least-one-response", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 151, - "section": "Specification > OpenAPI Description Structure > Parsing Documents", - "anchor": "parsing-documents", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "While it is possible to structure certain OpenAPI Descriptions to ensure that they will behave correctly when references are parsed as isolated fragments, depending on this is NOT RECOMMENDED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2134, + "section": "Objects and Fields > Responses Object", + "anchor": "responses-object", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call." }, { - "id": "oas-3.1.path-item-object.$ref", + "id": "oas-3.2.responses-object.pattern-http-status-code", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 867, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-ref", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2148, + "section": "Objects and Fields > Responses Object > Patterned Fields", + "anchor": "responses-code", "level": "field", "terms": [], - "text": "Allows for a referenced definition of this path item. The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving Relative References. _Note: The behavior of `$ref` with adjacent properties is likely to change in future versions of this specification to bring it into closer alignment with the behavior of the Reference Object._" + "text": "Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be represented by a string (for example, `\"200\"` enclosed in quotes in YAML) for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code." }, { - "id": "oas-3.1.path-item-object.$ref.must-value-form-uri-referenced-structure-form", + "id": "oas-3.2.responses-object.pattern-http-status-code.may-define-range-response-codes-field-contain", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 867, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-ref", - "level": "MUST", - "terms": ["MUST"], - "text": "The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2148, + "section": "Objects and Fields > Responses Object > Patterned Fields", + "anchor": "responses-code", + "level": "MAY", + "terms": ["MAY"], + "text": "To define a range of response codes, this field MAY contain the uppercase wildcard character `X`." }, { - "id": "oas-3.1.path-item-object.delete", + "id": "oas-3.2.responses-object.pattern-http-status-code.must-field-represented-string-example-200-enclosed", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 873, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-delete", - "level": "field", - "terms": [], - "text": "A definition of a DELETE operation on this path." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2148, + "section": "Objects and Fields > Responses Object > Patterned Fields", + "anchor": "responses-code", + "level": "MUST", + "terms": ["MUST"], + "text": "This field MUST be represented by a string (for example, `\"200\"` enclosed in quotes in YAML) for compatibility between JSON and YAML." }, { - "id": "oas-3.1.path-item-object.description", + "id": "oas-3.2.responses-object.patterned-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 869, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-description", - "level": "field", - "terms": [], - "text": "An optional string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2150, + "section": "Objects and Fields > Responses Object > Patterned Fields", + "anchor": "patterned-fields-0", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.path-item-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.rich-text-formatting.may-tooling-choose-ignore-some-commonmark-extension", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 869, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 72, + "section": "Format > Rich Text Formatting", + "anchor": "rich-text-formatting", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "Tooling MAY choose to ignore some CommonMark or extension features to address security concerns." }, { - "id": "oas-3.1.path-item-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.rich-text-formatting.may-while-framing-commonmark-0-27-minimum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 881, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "fixed-fields-6", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 75, + "section": "Format > Rich Text Formatting", + "anchor": "rich-text-formatting", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "While the framing of CommonMark 0.27 as a minimum requirement means that tooling MAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable." }, { - "id": "oas-3.1.path-item-object.get", + "id": "oas-3.2.rich-text-formatting.must-openapi-tooling-renders-rich-text-support", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 870, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-get", - "level": "field", - "terms": [], - "text": "A definition of a GET operation on this path." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 72, + "section": "Format > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "MUST", + "terms": ["MUST"], + "text": "Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27." }, { - "id": "oas-3.1.path-item-object.head", + "id": "oas-3.2.rich-text-formatting.should-openapi-description-authors-consider-how-text", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 875, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-head", - "level": "field", - "terms": [], - "text": "A definition of a HEAD operation on this path." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 75, + "section": "Format > Rich Text Formatting", + "anchor": "rich-text-formatting", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "OpenAPI Description authors SHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support." }, { - "id": "oas-3.1.path-item-object.may-path-item-empty-due-acl-constraints", + "id": "oas-3.2.schema-object.annotated-enumerations.may-implementations-support-recognizing-oneof-anyof-each", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 859, - "section": "Specification > Schema > Path Item Object", - "anchor": "path-item-object", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3299, + "section": "Objects and Fields > Schema Object > Data Modeling Techniques > Annotated Enumerations", + "anchor": "annotated-enumerations", "level": "MAY", "terms": ["MAY"], - "text": "A Path Item MAY be empty, due to ACL constraints." + "text": "Implementations MAY support recognizing a `oneOf` or `anyOf` where each subschema in the keyword's array consists of a `const` keyword and annotations such as `title` or `description` as an enumerated type with additional information." }, { - "id": "oas-3.1.path-item-object.options", + "id": "oas-3.2.schema-object.composition-and-inheritance-polymorphism.must-discriminating-property-defined-required-optional-but", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 874, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-options", - "level": "field", - "terms": [], - "text": "A definition of a OPTIONS operation on this path." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3277, + "section": "Objects and Fields > Schema Object > Data Modeling Techniques > Composition and Inheritance (Polymorphism)", + "anchor": "composition-and-inheritance-polymorphism", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "The discriminating property MAY be defined as required or optional, but when defined as an optional property the Discriminator Object MUST include a `defaultMapping` field that specifies which schema of the `anyOf` or `oneOf`, or which schema that references the current schema in an `allOf`, is expected to validate the structure of the model when the discriminating property is not present." }, { - "id": "oas-3.1.path-item-object.parameters", + "id": "oas-3.2.schema-object.data-type-format.may-tools-do-not-recognize-specific-format", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 879, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-parameters", - "level": "field", - "terms": [], - "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3043, + "section": "Objects and Fields > Schema Object > Data Types > Data Type Format", + "anchor": "data-type-format", + "level": "MAY", + "terms": ["MAY"], + "text": "Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified." }, { - "id": "oas-3.1.path-item-object.parameters.must-not-list-include-duplicated-parameters", + "id": "oas-3.2.schema-object.data-type-format.optional-support-any-registered-format-strictly-support", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 879, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-parameters", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The list MUST NOT include duplicated parameters." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3041, + "section": "Objects and Fields > Schema Object > Data Types > Data Type Format", + "anchor": "data-type-format", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Support for any registered format is strictly OPTIONAL, and support for one registered format does not imply support for any others." }, { - "id": "oas-3.1.path-item-object.patch", + "id": "oas-3.2.schema-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 876, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-patch", - "level": "field", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3008, + "section": "Objects and Fields > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "A definition of a PATCH operation on this path." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.path-item-object.post", + "id": "oas-3.2.schema-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 872, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-post", - "level": "field", - "terms": [], - "text": "A definition of a POST operation on this path." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3008, + "section": "Objects and Fields > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MAY", + "terms": ["MAY"], + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.path-item-object.put", + "id": "oas-3.2.schema-object.discriminator", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 871, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-put", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3020, + "section": "Objects and Fields > Schema Object > Fixed Fields", + "anchor": "schema-discriminator", "level": "field", "terms": [], - "text": "A definition of a PUT operation on this path." + "text": "The discriminator provides a \"hint\" for which of a set of schemas a payload is expected to satisfy. See Composition and Inheritance for more details." }, { - "id": "oas-3.1.path-item-object.servers", + "id": "oas-3.2.schema-object.example", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 878, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-servers", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3023, + "section": "Objects and Fields > Schema Object > Fixed Fields", + "anchor": "schema-example", "level": "field", "terms": [], - "text": "An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the OpenAPI Object level, it will be overridden by this value." + "text": "A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. Deprecated: The `example` field has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it." }, { - "id": "oas-3.1.path-item-object.summary", + "id": "oas-3.2.schema-object.extended-validation-with-annotations.may-oas-implementations-use-annotations-including-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 868, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-summary", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3243, + "section": "Objects and Fields > Schema Object > Extended Validation with Annotations", + "anchor": "extended-validation-with-annotations", + "level": "MAY", + "terms": ["MAY"], + "text": "OAS implementations MAY use such annotations, including extensions not recognized as part of a declared JSON Schema vocabulary, as the basis for further validation." + }, + { + "id": "oas-3.2.schema-object.externalDocs", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3022, + "section": "Objects and Fields > Schema Object > Fixed Fields", + "anchor": "schema-external-docs", "level": "field", "terms": [], - "text": "An optional string summary, intended to apply to all operations in this path." + "text": "Additional external documentation for this schema." }, { - "id": "oas-3.1.path-item-object.trace", + "id": "oas-3.2.schema-object.fixed-fields.may-object-extended-specification-extensions-though-noted", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 877, - "section": "Specification > Schema > Path Item Object > Fixed Fields", - "anchor": "path-item-trace", - "level": "field", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3025, + "section": "Objects and Fields > Schema Object > Fixed Fields", + "anchor": "fixed-fields-20", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions, though as noted, additional properties MAY omit the `x-` prefix within this object." + }, + { + "id": "oas-3.2.schema-object.format", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3009, + "section": "Objects and Fields > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "keyword", "terms": [], - "text": "A definition of a TRACE operation on this path." + "text": "See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats." }, { - "id": "oas-3.1.path-templating.must-each-template-expression-path-correspond-path", + "id": "oas-3.2.schema-object.generic-template-data-structures.should-implementations-support-defining-generic-template-data", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 43, - "section": "Definitions > Path Templating", - "anchor": "path-templating", - "level": "MUST", - "terms": ["MUST"], - "text": "Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3288, + "section": "Objects and Fields > Schema Object > Data Modeling Techniques > Generic (Template) Data Structures", + "anchor": "generic-template-data-structures", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Implementations SHOULD support defining generic or template data structures using JSON Schema's dynamic referencing feature:" }, { - "id": "oas-3.1.path-templating.must-not-value-path-parameters-contain-any-unescaped", + "id": "oas-3.2.schema-object.json-schema-keywords.may-json-schema-implementations-choose-treat-keywords", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 45, - "section": "Definitions > Path Templating", - "anchor": "path-templating", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The value for these path parameters MUST NOT contain any unescaped \"generic syntax\" characters described by RFC3986: forward slashes (`/`), question marks (`?`), or hashes (`#`)." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3013, + "section": "Objects and Fields > Schema Object > JSON Schema Keywords", + "anchor": "json-schema-keywords", + "level": "MAY", + "terms": ["MAY"], + "text": "JSON Schema implementations MAY choose to treat keywords defined by the OpenAPI Specification's base vocabulary as unknown keywords, due to its inclusion in the OAS dialect with a `$vocabulary` value of `false`." }, { - "id": "oas-3.1.paths-object.may-paths-object-empty-due-access-control", + "id": "oas-3.2.schema-object.may-empty-schema-allows-any-instance-validate", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 781, - "section": "Specification > Schema > Paths Object", - "anchor": "paths-object", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2993, + "section": "Objects and Fields > Schema Object", + "anchor": "schema-object", "level": "MAY", "terms": ["MAY"], - "text": "The Paths Object MAY be empty, due to Access Control List (ACL) constraints." + "text": "The empty schema (which allows any instance to validate) MAY be represented by the boolean value `true` and a schema which allows no instance to validate MAY be represented by the boolean value `false`." }, { - "id": "oas-3.1.paths-object.pattern-path", + "id": "oas-3.2.schema-object.non-json-data.must-due-limited-requirements-searching-schemas-serializers", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 788, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "paths-path", - "level": "field", - "terms": [], - "text": "A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is appended (no relative URL resolution) to the expanded URL from the Server Object's `url` field in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3120, + "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", + "anchor": "non-json-data", + "level": "MUST", + "terms": ["MUST"], + "text": "Due to these limited requirements for searching schemas, serializers that have access to validated data MUST inspect the data if possible; implementations that either do not work with runtime data (such as code generators) or cannot access validated data for some reason MUST fall back to schema inspection." }, { - "id": "oas-3.1.paths-object.pattern-path.must-field-name-begin-forward-slash", + "id": "oas-3.2.schema-object.non-json-data.must-inspecting-schemas-given-starting-point-schema", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 788, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "paths-path", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3094, + "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", + "anchor": "non-json-data", "level": "MUST", "terms": ["MUST"], - "text": "The field name MUST begin with a forward slash (`/`)." + "text": "When inspecting schemas, given a starting point schema, implementations MUST examine that schema and all schemas that can be reached from it by following only `$ref` and `allOf` keywords." }, { - "id": "oas-3.1.paths-object.pattern-path.must-not-templated-paths-same-hierarchy-but-different", + "id": "oas-3.2.schema-object.non-json-data.must-not-implementations-inspect-subschemas-possible-reference-targets", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 788, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "paths-path", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3099, + "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", + "anchor": "non-json-data", "level": "MUST", - "terms": ["MUST NOT"], - "text": "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical." + "terms": ["MAY", "MUST NOT"], + "text": "Implementations MAY inspect subschemas or possible reference targets of other keywords such as `oneOf` or `$dynamicRef`, but MUST NOT attempt to resolve ambiguities." }, { - "id": "oas-3.1.paths-object.patterned-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.schema-object.non-json-data.must-schema-objects-do-not-contain-type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 790, - "section": "Specification > Schema > Paths Object > Patterned Fields", - "anchor": "patterned-fields", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3094, + "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", + "anchor": "non-json-data", + "level": "MUST", + "terms": ["MUST"], + "text": "Schema Objects that do not contain `type` MUST be considered to allow all types, regardless of which other keywords are present (e.g. `maximum` applies to numbers, but _does not_ require the instance to be a number)." + }, + { + "id": "oas-3.2.schema-object.non-validating-constraint-keywords.may-extended-validation-one-way-constraints-enforced", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3249, + "section": "Objects and Fields > Schema Object > Extended Validation with Annotations > Non-Validating Constraint Keywords", + "anchor": "non-validating-constraint-keywords", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Extended validation is one way that these constraints MAY be enforced." }, { - "id": "oas-3.1.percent-encoding-and-cookies.not-recommended-note-standard-base64-encoding-alphabet-includes", + "id": "oas-3.2.schema-object.parsing-and-serializing.may-application-form-incorporates-any-additional-information", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4583, - "section": "Appendix D: Serializing Headers and Cookies > Percent-Encoding and Cookies", - "anchor": "percent-encoding-and-cookies", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Note that the standard base64-encoding alphabet includes non-URL-safe characters that are percent-encoded by RFC6570 expansion; serializing values through both encodings is NOT RECOMMENDED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3064, + "section": "Objects and Fields > Schema Object > Parsing and Serializing", + "anchor": "parsing-and-serializing", + "level": "MAY", + "terms": ["MAY"], + "text": "The application form, which incorporates any additional information conveyed by JSON Schema keywords such as `format` and `contentMediaType`, and possibly additional information such as class hierarchies that are beyond the scope of this specification, although they MAY be based on specification elements such as the Discriminator Object or guidance regarding Data Modeling Techniques." }, { - "id": "oas-3.1.percent-encoding-and-form-data.must-users-wishing-use-percent-encoding-way", + "id": "oas-3.2.schema-object.schema-evaluation-and-binary-data.must-oas-implementations-do-not-have-access", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4627, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and `form-data`", - "anchor": "percent-encoding-and-form-data", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3224, + "section": "Objects and Fields > Schema Object > Parsing and Serializing > Working with Binary Data > Schema Evaluation and Binary Data", + "anchor": "schema-evaluation-and-binary-data", "level": "MUST", "terms": ["MUST"], - "text": "Users wishing to use percent-encoding in this way MUST provide the data in percent-encoded form, as percent-encoding is not automatically applied for this media type regardless of which Encoding Object fields are used." + "text": "OAS Implementations that do not have access to a binary-instance-supporting JSON Schema implementation MUST examine schemas and apply them in accordance with Working with Binary Data." }, { - "id": "oas-3.1.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", + "id": "oas-3.2.schema-object.specifying-schema-dialects.must-default-not-set-oas-dialect-schema", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4677, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", - "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3312, + "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", "level": "MUST", "terms": ["MUST"], - "text": "The `[`, `]`, `|`, and space characters, which are used as delimiters for the `deepObject`, `pipeDelimited`, and `spaceDelimited` styles, respectively, all MUST be percent-encoded to comply with [RFC3986]." - }, - { - "id": "oas-3.1.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4688, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", - "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For maximum interoperability, it is RECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely." - }, - { - "id": "oas-3.1.reference-object.$ref", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2720, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-ref", - "level": "field", - "terms": [], - "text": "REQUIRED. The reference identifier. This MUST be in the form of a URI." + "text": "If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects." }, { - "id": "oas-3.1.reference-object.$ref.must-form-uri", + "id": "oas-3.2.schema-object.specifying-schema-dialects.must-schema-keyword-present-any-schema-object", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2720, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-ref", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3310, + "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "terms": ["MAY", "MUST"], + "text": "The `$schema` keyword MAY be present in any Schema Object that is a schema resource root, and if present MUST be used to determine which dialect should be used when processing the schema." }, { - "id": "oas-3.1.reference-object.$ref.required", + "id": "oas-3.2.schema-object.specifying-schema-dialects.must-tooling-support-oas-dialect-schema-id", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2720, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-ref", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3310, + "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST", "MAY"], + "text": "Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`." }, { - "id": "oas-3.1.reference-object.description", + "id": "oas-3.2.schema-object.specifying-schema-dialects.recommended-however-maximum-interoperability-openapi-description-authors", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2722, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-description", - "level": "field", - "terms": [], - "text": "A description which by default SHOULD override that of the referenced component. CommonMark syntax MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3314, + "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, for maximum interoperability, it is RECOMMENDED that OpenAPI description authors explicitly set the dialect through `$schema` in such documents." }, { - "id": "oas-3.1.reference-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.schema-object.specifying-schema-dialects.should-standalone-json-schema-documents-do-not", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2722, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3314, + "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", + "anchor": "specifying-schema-dialects", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "For standalone JSON Schema documents that do not set `$schema`, or for Schema Objects in OpenAPI description documents that are _not_ complete documents, the dialect SHOULD be assumed to be the OAS dialect." + }, + { + "id": "oas-3.2.schema-object.validating-readonly-and-writeonly.may-json-schema-validation-draft-2020-12", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3254, + "section": "Objects and Fields > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", + "anchor": "validating-readonly-and-writeonly", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "JSON Schema Validation Draft 2020-12 Section 9.4 defines the expectations of these keywords, including that a resource (described as the \"owning authority\") MAY either ignore a `readOnly` field or treat it as an error." }, { - "id": "oas-3.1.reference-object.description.should-description-default-override-referenced-component", + "id": "oas-3.2.schema-object.validating-readonly-and-writeonly.may-validation-keywords-done-checking-annotation-read", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2722, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-description", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "A description which by default SHOULD override that of the referenced component." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3254, + "section": "Objects and Fields > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", + "anchor": "validating-readonly-and-writeonly", + "level": "MAY", + "terms": ["MAY"], + "text": "Validation of these keywords MAY be done by checking the annotation, the read or write direction, and (if relevant) the current value of the field." }, { - "id": "oas-3.1.reference-object.fixed-fields.shall-object-cannot-extended-additional-properties-any", + "id": "oas-3.2.schema-object.working-with-binary-data.shall-however-contentmediatype-contradicts-relevant-media-type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2724, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "fixed-fields-19", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3216, + "section": "Objects and Fields > Schema Object > Parsing and Serializing > Working with Binary Data", + "anchor": "working-with-binary-data", "level": "MUST", "terms": ["SHALL"], - "text": "This object cannot be extended with additional properties, and any properties added SHALL be ignored." + "text": "However, if `contentMediaType` contradicts a relevant Media Type Object or Encoding Object, then `contentMediaType` SHALL be ignored." }, { - "id": "oas-3.1.reference-object.summary", + "id": "oas-3.2.schema-object.xml", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2721, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-summary", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3021, + "section": "Objects and Fields > Schema Object > Fixed Fields", + "anchor": "schema-xml", "level": "field", "terms": [], - "text": "A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect." + "text": "Adds additional metadata to describe the XML representation of this schema." }, { - "id": "oas-3.1.reference-object.summary.should-short-summary-default-override-referenced-component", + "id": "oas-3.2.security-filtering.may-path-item-object-empty", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2721, - "section": "Specification > Schema > Reference Object > Fixed Fields", - "anchor": "reference-summary", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "A short summary which by default SHOULD override that of the referenced component." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4816, + "section": "Security Considerations > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "The Path Item Object MAY be empty." }, { - "id": "oas-3.1.relative-references-in-api-description-uris.may-practice-usually-retrieval-uri-document-determined", + "id": "oas-3.2.security-filtering.may-paths-object-present-but-empty", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 294, - "section": "Specification > Relative References in API Description URIs", - "anchor": "relative-references-in-api-description-uris", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4815, + "section": "Security Considerations > Security Filtering", + "anchor": "security-filtering", "level": "MAY", "terms": ["MAY"], - "text": "In practice, this is usually the retrieval URI of the document, which MAY be determined based on either its current actual location or a user-supplied expected location." + "text": "The Paths Object MAY be present but empty." }, { - "id": "oas-3.1.relative-references-in-api-description-uris.may-unless-specified-otherwise-all-fields-uris", + "id": "oas-3.2.security-filtering.may-some-objects-openapi-specification-declared-remain", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 290, - "section": "Specification > Relative References in API Description URIs", - "anchor": "relative-references-in-api-description-uris", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4808, + "section": "Security Considerations > Security Filtering", + "anchor": "security-filtering", "level": "MAY", "terms": ["MAY"], - "text": "Unless specified otherwise, all fields that are URIs MAY be relative references as defined by RFC3986." + "text": "Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation." }, { - "id": "oas-3.1.relative-references-in-api-description-uris.must-relative-uri-references-other-objects-schema", + "id": "oas-3.2.security-filtering.may-while-not-part-specification-itself-certain", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 294, - "section": "Specification > Relative References in API Description URIs", - "anchor": "relative-references-in-api-description-uris", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4810, + "section": "Security Considerations > Security Filtering", + "anchor": "security-filtering", + "level": "MAY", + "terms": ["MAY"], + "text": "While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization." + }, + { + "id": "oas-3.2.security-requirement-object.must-name-used-each-property-either-correspond", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4711, + "section": "Objects and Fields > Security Requirement Object", + "anchor": "security-requirement-object", "level": "MUST", "terms": ["MUST"], - "text": "Relative URI references in other Objects, and in Schema Objects where no parent schema contains an `$id`, MUST be resolved using the referring document's base URI, which is determined in accordance with [RFC3986] Section 5.1.2 – 5.1.4." + "text": "The name used for each property MUST either correspond to a security scheme declared in the Security Schemes under the Components Object, or be the URI of a Security Scheme Object." }, { - "id": "oas-3.1.relative-references-in-api-description-uris.should-representation-referenced-document-json-yaml-fragment", + "id": "oas-3.2.security-requirement-object.must-property-names-identical-component-name-under", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 297, - "section": "Specification > Relative References in API Description URIs", - "anchor": "relative-references-in-api-description-uris", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4711, + "section": "Objects and Fields > Security Requirement Object", + "anchor": "security-requirement-object", + "level": "MUST", + "terms": ["MUST"], + "text": "Property names that are identical to a component name under the Components Object MUST be treated as a component name." + }, + { + "id": "oas-3.2.security-requirement-object.must-security-requirement-object-refer-multiple-security", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4717, + "section": "Objects and Fields > Security Requirement Object", + "anchor": "security-requirement-object", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized." + }, + { + "id": "oas-3.2.security-requirement-object.not-recommended-using-security-scheme-component-name-appears", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4715, + "section": "Objects and Fields > Security Requirement Object", + "anchor": "security-requirement-object", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON-Pointer as per RFC6901." + "terms": ["NOT RECOMMENDED"], + "text": "Using a Security Scheme component name that appears to be a URI is NOT RECOMMENDED, as the precedence of component-name-matching over URI resolution, which is necessary to maintain compatibility with prior OAS versions, is counter-intuitive." }, { - "id": "oas-3.1.relative-references-in-api-urls.may-note-themselves-relative-referring-document", + "id": "oas-3.2.security-requirement-object.pattern-name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 305, - "section": "Specification > Relative References in API URLs", - "anchor": "relative-references-in-api-urls", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4729, + "section": "Objects and Fields > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "field", + "terms": [], + "text": "Each name or URI MUST correspond to a security scheme as described above. If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + }, + { + "id": "oas-3.2.security-requirement-object.pattern-name.may-other-security-scheme-types-array-contain", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4729, + "section": "Objects and Fields > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", "level": "MAY", "terms": ["MAY"], - "text": "Note that these themselves MAY be relative to the referring document." + "text": "For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." }, { - "id": "oas-3.1.relative-references-in-api-urls.may-unless-specified-otherwise-all-fields-urls", + "id": "oas-3.2.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 305, - "section": "Specification > Relative References in API URLs", - "anchor": "relative-references-in-api-urls", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4729, + "section": "Objects and Fields > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", "level": "MAY", "terms": ["MAY"], - "text": "Unless specified otherwise, all fields that are URLs MAY be relative references as defined by RFC3986." + "text": "If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope." + }, + { + "id": "oas-3.2.security-requirement-object.pattern-name.must-each-name-uri-correspond-security-scheme", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4729, + "section": "Objects and Fields > Security Requirement Object > Patterned Fields", + "anchor": "security-requirements-name", + "level": "MUST", + "terms": ["MUST"], + "text": "Each name or URI MUST correspond to a security scheme as described above." }, { - "id": "oas-3.1.request-body-object.content", + "id": "oas-3.2.security-scheme-object.bearerFormat", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1452, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-content", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4605, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-bearer-format", "level": "field", "terms": [], - "text": "REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined. For requests that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + "text": "A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes." }, { - "id": "oas-3.1.request-body-object.content.required", + "id": "oas-3.2.security-scheme-object.deprecated", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1452, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-content", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4609, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-deprecated", + "level": "field", + "terms": [], + "text": "Declares this security scheme to be deprecated. Consumers SHOULD refrain from usage of the declared scheme. Default value is `false`." }, { - "id": "oas-3.1.request-body-object.content.should-map-have-least-one-entry-does", + "id": "oas-3.2.security-scheme-object.deprecated.should-consumers-refrain-usage-declared-scheme", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1452, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-content", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4609, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-deprecated", "level": "SHOULD", "terms": ["SHOULD"], - "text": "The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined." + "text": "Consumers SHOULD refrain from usage of the declared scheme." }, { - "id": "oas-3.1.request-body-object.description", + "id": "oas-3.2.security-scheme-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1451, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4601, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-description", "level": "field", "terms": [], - "text": "A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "text": "A description for security scheme. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.request-body-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1451, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4601, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-description", "level": "MAY", "terms": ["MAY"], "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.request-body-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.security-scheme-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1455, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "fixed-fields-10", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4611, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "fixed-fields-23", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.request-body-object.required", + "id": "oas-3.2.security-scheme-object.flows", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1453, - "section": "Specification > Schema > Request Body Object > Fixed Fields", - "anchor": "request-body-required", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4606, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-flows", "level": "field", "terms": [], - "text": "Determines if the request body is required in the request. Defaults to `false`." + "text": "REQUIRED. An object containing configuration information for the flow types supported." }, { - "id": "oas-3.1.resolving-implicit-connections.recommended-consider-all-operation-objects-all-parsed", + "id": "oas-3.2.security-scheme-object.flows.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 185, - "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is RECOMMENDED to consider all Operation Objects from all parsed documents when resolving any Link Object `operationId`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4606, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-flows", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.resolving-implicit-connections.recommended-resolving-component-tag-name-connections-referenced", + "id": "oas-3.2.security-scheme-object.in", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 193, - "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For resolving component and tag name connections from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4603, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-in", + "level": "field", + "terms": [], + "text": "REQUIRED. The location of the API key. Valid values are `\"query\"`, `\"header\"`, or `\"cookie\"`." }, { - "id": "oas-3.1.resolving-implicit-connections.recommended-some-cases-unambiguous-uri-based-alternative", + "id": "oas-3.2.security-scheme-object.in.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 172, - "section": "Specification > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "In some cases, an unambiguous URI-based alternative is available, and OAD authors are RECOMMENDED to always use the alternative:" + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4603, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-in", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.response-object.content", + "id": "oas-3.2.security-scheme-object.name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2012, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-content", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4602, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-name", "level": "field", "terms": [], - "text": "A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + "text": "REQUIRED. The name of the header, query or cookie parameter to be used." }, { - "id": "oas-3.1.response-object.description", + "id": "oas-3.2.security-scheme-object.name.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2010, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4602, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-name", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." + }, + { + "id": "oas-3.2.security-scheme-object.oauth2MetadataUrl", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4608, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-oauth2-metadata-url", "level": "field", "terms": [], - "text": "REQUIRED. A description of the response. CommonMark syntax MAY be used for rich text representation." + "text": "URL to the OAuth2 authorization server metadata RFC8414. TLS is required." }, { - "id": "oas-3.1.response-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.security-scheme-object.openIdConnectUrl", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2010, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4607, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-open-id-connect-url", + "level": "field", + "terms": [], + "text": "REQUIRED. Well-known URL to discover the [OpenID-Connect-Discovery] provider metadata." }, { - "id": "oas-3.1.response-object.description.required", + "id": "oas-3.2.security-scheme-object.openIdConnectUrl.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2010, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4607, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-open-id-connect-url", "level": "MUST", "terms": ["REQUIRED"], "text": "REQUIRED." }, { - "id": "oas-3.1.response-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2015, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "fixed-fields-14", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." - }, - { - "id": "oas-3.1.response-object.headers", + "id": "oas-3.2.security-scheme-object.scheme", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2011, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-headers", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4604, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", "level": "field", "terms": [], - "text": "Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + "text": "REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in RFC9110. The values used SHOULD be registered in the IANA Authentication Scheme registry. The value is case-insensitive, as defined in RFC9110." }, - { - "id": "oas-3.1.response-object.headers.shall-response-header-defined-name-content-type", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2011, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-headers", + { + "id": "oas-3.2.security-scheme-object.scheme.required", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4604, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", "level": "MUST", - "terms": ["SHALL"], - "text": "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.response-object.links", + "id": "oas-3.2.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2013, - "section": "Specification > Schema > Response Object > Fixed Fields", - "anchor": "response-links", - "level": "field", - "terms": [], - "text": "A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4604, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-scheme", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The values used SHOULD be registered in the IANA Authentication Scheme registry." }, { - "id": "oas-3.1.responses-object.default", + "id": "oas-3.2.security-scheme-object.type", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1947, - "section": "Specification > Schema > Responses Object > Fixed Fields", - "anchor": "responses-default", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4600, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-type", "level": "field", "terms": [], - "text": "The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses." + "text": "REQUIRED. The type of the security scheme. Valid values are `\"apiKey\"`, `\"http\"`, `\"mutualTLS\"`, `\"oauth2\"`, `\"openIdConnect\"`." }, { - "id": "oas-3.1.responses-object.may-default-used-default-response-object-all", + "id": "oas-3.2.security-scheme-object.type.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1936, - "section": "Specification > Schema > Responses Object", - "anchor": "responses-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4600, + "section": "Objects and Fields > Security Scheme Object > Fixed Fields", + "anchor": "security-scheme-type", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.responses-object.must-responses-object-contain-least-one-response", + "id": "oas-3.2.security-schemes.recommended-implementation-defined-whether-component-name-used", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1939, - "section": "Specification > Schema > Responses Object", - "anchor": "responses-object", - "level": "MUST", - "terms": ["MUST", "SHOULD"], - "text": "The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4803, + "section": "Security Considerations > Security Schemes", + "anchor": "security-schemes", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is implementation-defined whether a component name used by a Security Requirement Object in a referenced document is resolved from the entry document (RECOMMENDED) or the referenced document." }, { - "id": "oas-3.1.responses-object.pattern-http-status-code", + "id": "oas-3.2.server-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1953, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "responses-code", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 271, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-description", "level": "field", "terms": [], - "text": "Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code." + "text": "An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.responses-object.pattern-http-status-code.may-define-range-response-codes-field-contain", + "id": "oas-3.2.server-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1953, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "responses-code", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 271, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-description", "level": "MAY", "terms": ["MAY"], - "text": "To define a range of response codes, this field MAY contain the uppercase wildcard character `X`." - }, - { - "id": "oas-3.1.responses-object.pattern-http-status-code.must-field-enclosed-quotation-marks-example-200", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1953, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "responses-code", - "level": "MUST", - "terms": ["MUST"], - "text": "This field MUST be enclosed in quotation marks (for example, \"200\") for compatibility between JSON and YAML." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.responses-object.patterned-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.server-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 1955, - "section": "Specification > Schema > Responses Object > Patterned Fields", - "anchor": "patterned-fields-0", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 275, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "fixed-fields-3", "level": "MAY", "terms": ["MAY"], "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.rich-text-formatting.may-tooling-choose-ignore-some-commonmark-extension", + "id": "oas-3.2.server-object.name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 276, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", - "level": "MAY", - "terms": ["MAY"], - "text": "Tooling MAY choose to ignore some CommonMark or extension features to address security concerns." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 272, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-name", + "level": "field", + "terms": [], + "text": "An optional unique string to refer to the host designated by the URL." }, { - "id": "oas-3.1.rich-text-formatting.may-while-framing-commonmark-0-27-minimum", + "id": "oas-3.2.server-object.relative-references-in-api-urls.may-note-themselves-relative-referring-document", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 279, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 283, + "section": "Objects and Fields > Server Object > Relative References in API URLs", + "anchor": "relative-references-in-api-urls", "level": "MAY", "terms": ["MAY"], - "text": "While the framing of CommonMark 0.27 as a minimum requirement means that tooling MAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable." + "text": "Note that these themselves MAY be relative to the referring document." }, { - "id": "oas-3.1.rich-text-formatting.must-openapi-tooling-renders-rich-text-support", + "id": "oas-3.2.server-object.relative-references-in-api-urls.may-unless-specified-otherwise-all-fields-urls", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 276, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", - "level": "MUST", - "terms": ["MUST"], - "text": "Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 281, + "section": "Objects and Fields > Server Object > Relative References in API URLs", + "anchor": "relative-references-in-api-urls", + "level": "MAY", + "terms": ["MAY"], + "text": "Unless specified otherwise, all fields that are URLs MAY be relative references as defined by RFC3986." }, { - "id": "oas-3.1.rich-text-formatting.should-openapi-description-authors-consider-how-text", + "id": "oas-3.2.server-object.url", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 279, - "section": "Specification > Rich Text Formatting", - "anchor": "rich-text-formatting", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "OpenAPI Description authors SHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 270, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "field", + "terms": [], + "text": "REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Query and fragment MUST NOT be part of this URL. Variable substitutions will be made when a variable is named in `{`braces`}`." }, { - "id": "oas-3.1.schema-object.annotated-enumerations.may-implementations-support-recognizing-oneof-anyof-each", + "id": "oas-3.2.server-object.url.may-url-supports-server-variables-relative-indicate", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2853, - "section": "Specification > Schema > Schema Object > Data Modeling Techniques > Annotated Enumerations", - "anchor": "annotated-enumerations", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 270, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-url", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support recognizing a `oneOf` or `anyOf` where each subschema in the keyword's array consists of a `const` keyword and annotations such as `title` or `description` as an enumerated type with additional information." + "text": "This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served." }, { - "id": "oas-3.1.schema-object.composition-and-inheritance-polymorphism.must-discriminator-field-required-field", + "id": "oas-3.2.server-object.url.must-not-query-fragment-part-url", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2831, - "section": "Specification > Schema > Schema Object > Data Modeling Techniques > Composition and Inheritance (Polymorphism)", - "anchor": "composition-and-inheritance-polymorphism", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 270, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-url", "level": "MUST", - "terms": ["MUST"], - "text": "As such, the `discriminator` field MUST be a required field." - }, - { - "id": "oas-3.1.schema-object.description", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2782, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "CommonMark syntax MAY be used for rich text representation." + "terms": ["MUST NOT"], + "text": "Query and fragment MUST NOT be part of this URL." }, { - "id": "oas-3.1.schema-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.server-object.url.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2782, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 270, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-url", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.schema-object.discriminator", + "id": "oas-3.2.server-object.variables", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2794, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-discriminator", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 273, + "section": "Objects and Fields > Server Object > Fixed Fields", + "anchor": "server-variables", "level": "field", "terms": [], - "text": "Adds support for polymorphism. The discriminator is used to determine which of a set of schemas a payload is expected to satisfy. See Composition and Inheritance for more details." + "text": "A map between a variable name and its value. The value is used for substitution in the server's URL template." }, { - "id": "oas-3.1.schema-object.example", + "id": "oas-3.2.server-variable-object.default", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2797, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-example", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 390, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", "level": "field", "terms": [], - "text": "A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. Deprecated: The `example` field has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it." + "text": "REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the `enum` is defined, the value MUST exist in the enum's values. Note that this behavior is different from the Schema Object's `default` keyword, which documents the receiver's behavior rather than inserting the value into the data." }, { - "id": "oas-3.1.schema-object.extended-validation-with-annotations.may-oas-implementations-use-annotations-including-extensions", + "id": "oas-3.2.server-variable-object.default.must-enum-defined-value-exist-enum-s", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2803, - "section": "Specification > Schema > Schema Object > Extended Validation with Annotations", - "anchor": "extended-validation-with-annotations", - "level": "MAY", - "terms": ["MAY"], - "text": "OAS implementations MAY use such annotations, including extensions not recognized as part of a declared JSON Schema vocabulary, as the basis for further validation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 390, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["MUST"], + "text": "If the `enum` is defined, the value MUST exist in the enum's values." }, { - "id": "oas-3.1.schema-object.externalDocs", + "id": "oas-3.2.server-variable-object.default.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2796, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this schema." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 390, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.schema-object.fixed-fields.may-object-extended-specification-extensions-though-noted", + "id": "oas-3.2.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2799, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "fixed-fields-20", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions, though as noted, additional properties MAY omit the `x-` prefix within this object." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 390, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-default", + "level": "MUST", + "terms": ["SHALL"], + "text": "The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied." }, { - "id": "oas-3.1.schema-object.format", + "id": "oas-3.2.server-variable-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2783, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 391, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-description", + "level": "field", "terms": [], - "text": "See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats." + "text": "An optional description for the server variable. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.schema-object.generic-template-data-structures.may-implementations-support-defining-generic-template-data", + "id": "oas-3.2.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2842, - "section": "Specification > Schema > Schema Object > Data Modeling Techniques > Generic (Template) Data Structures", - "anchor": "generic-template-data-structures", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 391, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-description", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support defining generic or template data structures using JSON Schema's dynamic referencing feature:" + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.schema-object.json-schema-keywords.may-json-schema-implementations-choose-treat-keywords", + "id": "oas-3.2.server-variable-object.enum", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2787, - "section": "Specification > Schema > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MAY", - "terms": ["MAY"], - "text": "JSON Schema implementations MAY choose to treat keywords defined by the OpenAPI Specification's base vocabulary as unknown keywords, due to its inclusion in the OAS dialect with a `$vocabulary` value of `false`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 389, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-enum", + "level": "field", + "terms": [], + "text": "An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty." }, { - "id": "oas-3.1.schema-object.may-empty-schema-allows-any-instance-validate", + "id": "oas-3.2.server-variable-object.enum.must-not-array-empty", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2766, - "section": "Specification > Schema > Schema Object", - "anchor": "schema-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The empty schema (which allows any instance to validate) MAY be represented by the boolean value `true` and a schema which allows no instance to validate MAY be represented by the boolean value `false`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 389, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "server-variable-enum", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The array MUST NOT be empty." }, { - "id": "oas-3.1.schema-object.non-validating-constraint-keywords.may-extended-validation-one-way-constraints-enforced", + "id": "oas-3.2.server-variable-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2809, - "section": "Specification > Schema > Schema Object > Extended Validation with Annotations > Non-validating constraint keywords", - "anchor": "non-validating-constraint-keywords", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 393, + "section": "Objects and Fields > Server Variable Object > Fixed Fields", + "anchor": "fixed-fields-4", "level": "MAY", "terms": ["MAY"], - "text": "Extended validation is one way that these constraints MAY be enforced." - }, - { - "id": "oas-3.1.schema-object.specifying-schema-dialects.must-default-not-set-oas-dialect-schema", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2866, - "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", - "level": "MUST", - "terms": ["MUST"], - "text": "If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects." - }, - { - "id": "oas-3.1.schema-object.specifying-schema-dialects.must-schema-keyword-present-any-schema-object", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2864, - "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", - "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "The `$schema` keyword MAY be present in any Schema Object that is a schema resource root, and if present MUST be used to determine which dialect should be used when processing the schema." + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.schema-object.specifying-schema-dialects.must-tooling-support-oas-dialect-schema-id", + "id": "oas-3.2.server-variable-object.must-not-each-server-variable-appear-more-once", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2864, - "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 381, + "section": "Objects and Fields > Server Variable Object", + "anchor": "server-variable-object", "level": "MUST", - "terms": ["MUST", "MAY"], - "text": "Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`." + "terms": ["MUST NOT"], + "text": "Each server variable MUST NOT appear more than once in the URL template." }, { - "id": "oas-3.1.schema-object.specifying-schema-dialects.recommended-however-maximum-interoperability-openapi-description-authors", + "id": "oas-3.2.specification-extensions.optional-support-any-one-extension-support-one", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2868, - "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, for maximum interoperability, it is RECOMMENDED that OpenAPI description authors explicitly set the dialect through `$schema` in such documents." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4780, + "section": "Specification Extensions", + "anchor": "specification-extensions", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Support for any one extension is OPTIONAL, and support for one extension does not imply support for others." }, { - "id": "oas-3.1.schema-object.specifying-schema-dialects.should-standalone-json-schema-documents-do-not", + "id": "oas-3.2.specification-extensions.pattern-x", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2868, - "section": "Specification > Schema > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "For standalone JSON Schema documents that do not set `$schema`, or for Schema Objects in OpenAPI description documents that are _not_ complete documents, the dialect SHOULD be assumed to be the OAS dialect." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4773, + "section": "Specification Extensions", + "anchor": "extension-properties", + "level": "field", + "terms": [], + "text": "Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the OpenAPI Initiative. The value can be any valid JSON value (`null`, a primitive, an array, or an object.)" }, { - "id": "oas-3.1.schema-object.validating-readonly-and-writeonly.may-json-schema-validation-draft-2020-12", + "id": "oas-3.2.specification-extensions.pattern-x.must-field-name-begin-x-example-x", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2814, - "section": "Specification > Schema > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", - "anchor": "validating-readonly-and-writeonly", - "level": "MAY", - "terms": ["MAY"], - "text": "JSON Schema Validation Draft 2020-12 §9.4 defines the expectations of these keywords, including that a resource (described as the \"owning authority\") MAY either ignore a `readOnly` field or treat it as an error." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4773, + "section": "Specification Extensions", + "anchor": "extension-properties", + "level": "MUST", + "terms": ["MUST"], + "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." }, { - "id": "oas-3.1.schema-object.validating-readonly-and-writeonly.may-validation-keywords-done-checking-annotation-read", + "id": "oas-3.2.specification-extensions.recommended-therefore-implementations-designed-extensibility-support-community", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2814, - "section": "Specification > Schema > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", - "anchor": "validating-readonly-and-writeonly", - "level": "MAY", - "terms": ["MAY"], - "text": "Validation of these keywords MAY be done by checking the annotation, the read or write direction, and (if relevant) the current value of the field." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 4777, + "section": "Specification Extensions", + "anchor": "specification-extensions", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "It is therefore RECOMMENDED that implementations be designed for extensibility to support community experimentation." }, { - "id": "oas-3.1.schema-object.xml", + "id": "oas-3.2.tag-object.description", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2795, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-xml", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2923, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-description", "level": "field", "terms": [], - "text": "This MAY be used only on property schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property." + "text": "A description for the tag. CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.schema-object.xml.may-used-only-property-schemas", + "id": "oas-3.2.tag-object.description.may-commonmark-syntax-used-rich-text-representation", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2795, - "section": "Specification > Schema > Schema Object > Fixed Fields", - "anchor": "schema-xml", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2923, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-description", "level": "MAY", "terms": ["MAY"], - "text": "This MAY be used only on property schemas." + "text": "CommonMark syntax MAY be used for rich text representation." }, { - "id": "oas-3.1.security-filtering.may-path-item-object-empty", + "id": "oas-3.2.tag-object.externalDocs", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4225, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "The Path Item Object MAY be empty." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2924, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-external-docs", + "level": "field", + "terms": [], + "text": "Additional external documentation for this tag." }, { - "id": "oas-3.1.security-filtering.may-paths-object-present-but-empty", + "id": "oas-3.2.tag-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4224, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2928, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "fixed-fields-18", "level": "MAY", "terms": ["MAY"], - "text": "The Paths Object MAY be present but empty." + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.security-filtering.may-some-objects-openapi-specification-declared-remain", + "id": "oas-3.2.tag-object.kind", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4217, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2926, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-kind", + "level": "field", + "terms": [], + "text": "A machine-readable string to categorize what sort of tag it is. Any string value can be used; common uses are `nav` for Navigation, `badge` for visible badges, `audience` for APIs used by different groups. A registry of the most commonly used values is available." }, { - "id": "oas-3.1.security-filtering.may-while-not-part-specification-itself-certain", + "id": "oas-3.2.tag-object.name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4219, - "section": "Specification > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2921, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-name", + "level": "field", + "terms": [], + "text": "REQUIRED. The name of the tag. Use this value in the `tags` array of an Operation." }, { - "id": "oas-3.1.security-requirement-object.must-name-used-each-property-correspond-security", + "id": "oas-3.2.tag-object.name.required", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4128, - "section": "Specification > Schema > Security Requirement Object", - "anchor": "security-requirement-object", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2921, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-name", "level": "MUST", - "terms": ["MUST"], - "text": "The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object." + "terms": ["REQUIRED"], + "text": "REQUIRED." }, { - "id": "oas-3.1.security-requirement-object.must-security-requirement-object-refer-multiple-security", + "id": "oas-3.2.tag-object.parent", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4131, - "section": "Specification > Schema > Security Requirement Object", - "anchor": "security-requirement-object", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2925, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-parent", + "level": "field", + "terms": [], + "text": "The `name` of a tag that this tag is nested under. The named tag MUST exist in the API description, and circular references between parent and child tags MUST NOT be used." + }, + { + "id": "oas-3.2.tag-object.parent.must-named-tag-exist-api-description-circular", + "spec": "openapi", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2925, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-parent", "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized." + "terms": ["MUST", "MUST NOT"], + "text": "The named tag MUST exist in the API description, and circular references between parent and child tags MUST NOT be used." }, { - "id": "oas-3.1.security-requirement-object.pattern-name", + "id": "oas-3.2.tag-object.summary", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4143, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 2922, + "section": "Objects and Fields > Tag Object > Fixed Fields", + "anchor": "tag-summary", "level": "field", "terms": [], - "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object. If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + "text": "A short summary of the tag, used for display purposes." }, { - "id": "oas-3.1.security-requirement-object.pattern-name.may-other-security-scheme-types-array-contain", + "id": "oas-3.2.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4143, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 35, + "section": "Introduction > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", "level": "MAY", "terms": ["MAY"], - "text": "For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + "text": "Implementations MAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification." }, { - "id": "oas-3.1.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value", + "id": "oas-3.2.undefined-and-implementation-defined-behavior.not-recommended-support-might-produce-correct-outcomes-many", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4143, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", - "level": "MAY", - "terms": ["MAY"], - "text": "If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 35, + "section": "Introduction > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "This support might produce correct outcomes in many cases, but relying on it is NOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one." }, { - "id": "oas-3.1.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared", + "id": "oas-3.2.undefined-and-implementation-defined-behavior.recommended-documents-ambiguous-requirements-api-description-authors", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4143, - "section": "Specification > Schema > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", - "level": "MUST", - "terms": ["MUST"], - "text": "Each name MUST correspond to a security scheme which is declared in the Security Schemes under the Components Object." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 40, + "section": "Introduction > Undefined and Implementation-Defined Behavior", + "anchor": "undefined-and-implementation-defined-behavior", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "This documents ambiguous requirements that API description authors are RECOMMENDED to avoid in order to maximize interoperability." }, { - "id": "oas-3.1.security-scheme-object.bearerFormat", + "id": "oas-3.2.versions-and-deprecation.shall-major-minor-portion-version-string-example", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3960, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-bearer-format", - "level": "field", - "terms": [], - "text": "A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 21, + "section": "Introduction > Versions and Deprecation", + "anchor": "versions-and-deprecation", + "level": "MUST", + "terms": ["SHALL"], + "text": "The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set." }, { - "id": "oas-3.1.security-scheme-object.description", + "id": "oas-3.2.versions-and-deprecation.should-not-patch-version-considered-tooling-making-no", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3956, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-description", - "level": "field", - "terms": [], - "text": "A description for security scheme. CommonMark syntax MAY be used for rich text representation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 21, + "section": "Introduction > Versions and Deprecation", + "anchor": "versions-and-deprecation", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example." }, { - "id": "oas-3.1.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.versions-and-deprecation.should-tooling-supports-oas-3-1-compatible", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3956, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 21, + "section": "Introduction > Versions and Deprecation", + "anchor": "versions-and-deprecation", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.* versions." }, { - "id": "oas-3.1.security-scheme-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.warnings-regarding-fragmentary-parsing.not-recommended-while-possible-structure-certain-openapi-descriptions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3964, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "fixed-fields-23", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 5499, + "section": "Appendix G: Parsing and Resolution Guidance > Warnings Regarding Fragmentary Parsing", + "anchor": "warnings-regarding-fragmentary-parsing", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED"], + "text": "While it is possible to structure certain OpenAPI Descriptions to ensure that they will behave correctly when references are parsed as isolated fragments, depending on this is NOT RECOMMENDED." }, { - "id": "oas-3.1.security-scheme-object.flows", + "id": "oas-3.2.xml-object.attribute", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3961, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-flows", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3847, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-attribute", "level": "field", "terms": [], - "text": "REQUIRED. An object containing configuration information for the flow types supported." + "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. If `nodeType` is present, this field MUST NOT be present. Deprecated: Use `nodeType: \"attribute\"` instead of `attribute: true`" }, { - "id": "oas-3.1.security-scheme-object.flows.required", + "id": "oas-3.2.xml-object.attribute.must-not-nodetype-present-field-present", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3961, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-flows", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3847, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-attribute", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "If `nodeType` is present, this field MUST NOT be present." }, { - "id": "oas-3.1.security-scheme-object.in", + "id": "oas-3.2.xml-object.fixed-fields.may-object-extended-specification-extensions", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3958, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-in", - "level": "field", - "terms": [], - "text": "REQUIRED. The location of the API key. Valid values are `\"query\"`, `\"header\"`, or `\"cookie\"`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3855, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "fixed-fields-22", + "level": "MAY", + "terms": ["MAY"], + "text": "This object MAY be extended with Specification Extensions." }, { - "id": "oas-3.1.security-scheme-object.in.required", + "id": "oas-3.2.xml-object.handling-null-values.recommended-however-because-no-distinct-way-represent", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3958, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-in", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3914, + "section": "Objects and Fields > XML Object > Handling `null` Values", + "anchor": "handling-null-values", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "However, because there is no distinct way to represent `null` as an attribute, it is RECOMMENDED to make attribute properties optional rather than use `null`." }, { - "id": "oas-3.1.security-scheme-object.name", + "id": "oas-3.2.xml-object.handling-null-values.should-ensure-correct-round-trip-behavior-parsing", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3957, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the header, query or cookie parameter to be used." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3918, + "section": "Objects and Fields > XML Object > Handling `null` Values", + "anchor": "handling-null-values", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "To ensure correct round-trip behavior, when parsing an element that omits an attribute, implementations SHOULD set the corresponding property to `null` if the schema allows for that value (e.g. `type: [\"number\", \"null\"]`), and omit the property otherwise (e.g.`type: \"number\"`)." }, { - "id": "oas-3.1.security-scheme-object.name.required", + "id": "oas-3.2.xml-object.handling-null-values.should-however-implementations-handle-null-values-follows", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3957, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3908, + "section": "Objects and Fields > XML Object > Handling `null` Values", + "anchor": "handling-null-values", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "However, implementations SHOULD handle `null` values as follows:" }, { - "id": "oas-3.1.security-scheme-object.openIdConnectUrl", + "id": "oas-3.2.xml-object.name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3962, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-open-id-connect-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3844, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-name", "level": "field", "terms": [], - "text": "REQUIRED. Well-known URL to discover the [OpenID-Connect-Discovery] provider metadata." + "text": "Sets the name of the element/attribute corresponding to the schema, replacing the name that was inferred as described under XML Node Names. This field SHALL be ignored if the `nodeType` is `text`, `cdata`, or `none`." }, { - "id": "oas-3.1.security-scheme-object.openIdConnectUrl.required", + "id": "oas-3.2.xml-object.name.shall-field-ignored-nodetype-text-cdata-none", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3962, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-open-id-connect-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3844, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-name", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["SHALL"], + "text": "This field SHALL be ignored if the `nodeType` is `text`, `cdata`, or `none`." }, { - "id": "oas-3.1.security-scheme-object.scheme", + "id": "oas-3.2.xml-object.namespace", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3959, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3845, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-namespace", "level": "field", "terms": [], - "text": "REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry. The value is case-insensitive, as defined in RFC7235." + "text": "The IRI ([RFC3987]) of the namespace definition. Value MUST be in the form of a non-relative IRI." }, { - "id": "oas-3.1.security-scheme-object.scheme.required", + "id": "oas-3.2.xml-object.namespace.must-value-form-non-relative-iri", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3959, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3845, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-namespace", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." - }, - { - "id": "oas-3.1.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3959, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The values used SHOULD be registered in the IANA Authentication Scheme registry." + "terms": ["MUST"], + "text": "Value MUST be in the form of a non-relative IRI." }, { - "id": "oas-3.1.security-scheme-object.type", + "id": "oas-3.2.xml-object.nodeType", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3955, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-type", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3843, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-node-type", "level": "field", "terms": [], - "text": "REQUIRED. The type of the security scheme. Valid values are `\"apiKey\"`, `\"http\"`, `\"mutualTLS\"`, `\"oauth2\"`, `\"openIdConnect\"`." + "text": "One of `element`, `attribute`, `text`, `cdata`, or `none`, as explained under XML Node Types. The default value is `none` if `$ref`, `$dynamicRef`, or `type: \"array\"` is present in the Schema Object containing the XML Object, and `element` otherwise." }, { - "id": "oas-3.1.security-scheme-object.type.required", + "id": "oas-3.2.xml-object.prefix", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3955, - "section": "Specification > Schema > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-type", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3846, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-prefix", + "level": "field", + "terms": [], + "text": "The prefix to be used for the name." }, { - "id": "oas-3.1.server-object.description", + "id": "oas-3.2.xml-object.wrapped", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 460, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3848, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-wrapped", "level": "field", "terms": [], - "text": "An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation." + "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `\"array\"` (outside the `items`). If `nodeType` is present, this field MUST NOT be present. Deprecated: Use `nodeType: \"element\"` instead of `wrapped: true`" }, { - "id": "oas-3.1.server-object.description.may-commonmark-syntax-used-rich-text-representation", + "id": "oas-3.2.xml-object.wrapped.may-used-only-array-definition", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 460, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-description", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3848, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-wrapped", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "MAY be used only for an array definition." }, { - "id": "oas-3.1.server-object.fixed-fields.may-object-extended-specification-extensions", + "id": "oas-3.2.xml-object.wrapped.must-not-nodetype-present-field-present", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 463, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "fixed-fields-3", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3848, + "section": "Objects and Fields > XML Object > Fixed Fields", + "anchor": "xml-wrapped", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "If `nodeType` is present, this field MUST NOT be present." }, { - "id": "oas-3.1.server-object.url", + "id": "oas-3.2.xml-object.xml-node-names.must-all-other-cases-inline-schema-under", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 459, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", - "level": "field", - "terms": [], - "text": "REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Query and fragment MUST NOT be part of this URL. Variable substitutions will be made when a variable is named in `{`braces`}`." + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3893, + "section": "Objects and Fields > XML Object > XML Node Names", + "anchor": "xml-node-names", + "level": "MUST", + "terms": ["MUST"], + "text": "In all other cases, such as an inline schema under a Media Type Object's `schema` field, no name can be inferred and an XML Object with a `name` field MUST be present." }, { - "id": "oas-3.1.server-object.url.may-url-supports-server-variables-relative-indicate", + "id": "oas-3.2.xml-object.xml-node-names.must-element-attribute-node-types-require-name", "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 459, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", + "version": "3.2.1", + "source": "openapi/3.2.1.md", + "line": 3889, + "section": "Objects and Fields > XML Object > XML Node Names", + "anchor": "xml-node-names", + "level": "MUST", + "terms": ["MUST"], + "text": "The `element` and `attribute` node types require a name, which MUST be inferred from the schema as follows, unless overridden by the `name` field:" + }, + { + "id": "rfc6749.1.6.may-implementations-support-additional-transport-layer-security", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 646, + "section": "Introduction > TLS Version", + "anchor": "section-1.6", "level": "MAY", "terms": ["MAY"], - "text": "This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served." + "text": "Implementations MAY also support additional transport-layer security mechanisms that meet their security requirements." }, { - "id": "oas-3.1.server-object.url.must-not-query-fragment-part-url", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 459, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", + "id": "rfc6749.10.1.may-authorization-server-issue-client-password-other", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2975, + "section": "Security Considerations > Client Authentication", + "anchor": "section-10.1", + "level": "MAY", + "terms": ["MAY"], + "text": "The authorization server MAY issue a client password or other credentials for a specific installation of a native application client on a specific device." + }, + { + "id": "rfc6749.10.1.must-not-authorization-server-issue-client-passwords-other", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2975, + "section": "Security Considerations > Client Authentication", + "anchor": "section-10.1", "level": "MUST", "terms": ["MUST NOT"], - "text": "Query and fragment MUST NOT be part of this URL." + "text": "The authorization server MUST NOT issue client passwords or other client credentials to native application or user-agent-based application clients for the purpose of client authentication." }, { - "id": "oas-3.1.server-object.url.required", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 459, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-url", + "id": "rfc6749.10.1.must-web-application-clients-ensure-confidentiality-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2958, + "section": "Security Considerations > Client Authentication", + "anchor": "section-10.1", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Web application clients MUST ensure confidentiality of client passwords and other client credentials." }, { - "id": "oas-3.1.server-object.variables", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 461, - "section": "Specification > Schema > Server Object > Fixed Fields", - "anchor": "server-variables", - "level": "field", - "terms": [], - "text": "A map between a variable name and its value. The value is used for substitution in the server's URL template." + "id": "rfc6749.10.1.should-client-authentication-not-possible-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2982, + "section": "Security Considerations > Client Authentication", + "anchor": "section-10.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When client authentication is not possible, the authorization server SHOULD employ other means to validate the client's identity -- for example, by requiring the registration of the client redirection URI or enlisting the resource owner to confirm identity." }, { - "id": "oas-3.1.server-variable-object.default", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 566, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", - "level": "field", - "terms": [], - "text": "REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the `enum` is defined, the value MUST exist in the enum's values. Note that this behavior is different from the Schema Object's `default` keyword, which documents the receiver's behavior rather than inserting the value into the data." + "id": "rfc6749.10.10.must-authorization-server-prevent-attackers-guessing-access", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3220, + "section": "Security Considerations > Credentials-Guessing Attacks", + "anchor": "section-10.10", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST prevent attackers from guessing access tokens, authorization codes, refresh tokens, resource owner passwords, and client credentials." }, { - "id": "oas-3.1.server-variable-object.default.must-enum-defined-value-exist-enum-s", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 566, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "id": "rfc6749.10.10.must-authorization-server-utilize-other-means-protect", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3228, + "section": "Security Considerations > Credentials-Guessing Attacks", + "anchor": "section-10.10", "level": "MUST", "terms": ["MUST"], - "text": "If the `enum` is defined, the value MUST exist in the enum's values." + "text": "The authorization server MUST utilize other means to protect credentials intended for end-user usage." }, { - "id": "oas-3.1.server-variable-object.default.required", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 566, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "id": "rfc6749.10.10.must-probability-attacker-guessing-generated-tokens-other", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3224, + "section": "Security Considerations > Credentials-Guessing Attacks", + "anchor": "section-10.10", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST", "SHOULD"], + "text": "The probability of an attacker guessing generated tokens (and other credentials not intended for handling by end-users) MUST be less than or equal to 2^(-128) and SHOULD be less than or equal to 2^(-160)." }, { - "id": "oas-3.1.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 566, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "id": "rfc6749.10.11.must-reduce-risk-phishing-attacks-authorization-servers", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3255, + "section": "Security Considerations > Phishing Attacks", + "anchor": "section-10.11", "level": "MUST", - "terms": ["SHALL"], - "text": "The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied." + "terms": ["MUST"], + "text": "To reduce the risk of phishing attacks, the authorization servers MUST require the use of TLS on every endpoint used for end-user interaction." }, { - "id": "oas-3.1.server-variable-object.description", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 567, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-description", - "level": "field", - "terms": [], - "text": "An optional description for the server variable. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.10.12.must-authorization-server-implement-csrf-protection-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3298, + "section": "Security Considerations > Cross-Site Request Forgery", + "anchor": "section-10.12", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST implement CSRF protection for its authorization endpoint and ensure that a malicious client cannot obtain authorization without the awareness and explicit consent of the resource owner." }, { - "id": "oas-3.1.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 567, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.10.12.must-binding-value-used-csrf-protection-contain", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3282, + "section": "Security Considerations > Cross-Site Request Forgery", + "anchor": "section-10.12", + "level": "MUST", + "terms": ["MUST"], + "text": "The binding value used for CSRF protection MUST contain a non-guessable value (as described in Section 10.10), and the user-agent's authenticated state (e.g., session cookie, HTML5 local storage) MUST be kept in a location accessible only to the client and the user-agent (i.e., protected by same-origin policy)." }, { - "id": "oas-3.1.server-variable-object.enum", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 565, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-enum", - "level": "field", - "terms": [], - "text": "An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty." + "id": "rfc6749.10.12.must-client-implement-csrf-protection-redirection-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3274, + "section": "Security Considerations > Cross-Site Request Forgery", + "anchor": "section-10.12", + "level": "MUST", + "terms": ["MUST"], + "text": "The client MUST implement CSRF protection for its redirection URI." }, { - "id": "oas-3.1.server-variable-object.enum.must-not-array-empty", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 565, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "server-variable-enum", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The array MUST NOT be empty." + "id": "rfc6749.10.12.should-client-utilize-state-request-parameter-deliver", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3274, + "section": "Security Considerations > Cross-Site Request Forgery", + "anchor": "section-10.12", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The client SHOULD utilize the \"state\" request parameter to deliver this value to the authorization server when making an authorization request." }, { - "id": "oas-3.1.server-variable-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 569, - "section": "Specification > Schema > Server Variable Object > Fixed Fields", - "anchor": "fixed-fields-4", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.10.13.should-prevent-form-attack-native-applications-use", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3324, + "section": "Security Considerations > Clickjacking", + "anchor": "section-10.13", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "To prevent this form of attack, native applications SHOULD use external browsers instead of embedding browsers within the application when requesting end-user authorization." }, { - "id": "oas-3.1.specification-extensions.optional-support-any-one-extension-support-one", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4213, - "section": "Specification > Specification Extensions", - "anchor": "specification-extensions", - "level": "MAY", - "terms": ["OPTIONAL"], - "text": "Support for any one extension is OPTIONAL, and support for one extension does not imply support for others." + "id": "rfc6749.10.14.must-authorization-server-client-sanitize-validate-possible", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3342, + "section": "Security Considerations > Code Injection and Input Validation", + "anchor": "section-10.14", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server and client MUST sanitize (and validate when possible) any value received -- in particular, the value of the \"state\" and \"redirect_uri\" parameters." }, { - "id": "oas-3.1.specification-extensions.pattern-x", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4206, - "section": "Specification > Specification Extensions", - "anchor": "extension-properties", - "level": "field", - "terms": [], - "text": "Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the OpenAPI Initiative. The value can be any valid JSON value (`null`, a primitive, an array, or an object.)" + "id": "rfc6749.10.16.must-not-any-specification-uses-authorization-process-form", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3406, + "section": "Security Considerations > Misuse of Access Token to Impersonate Resource Owner in Implicit", + "anchor": "section-10.16", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience-restricting the access token)." }, { - "id": "oas-3.1.specification-extensions.pattern-x.must-field-name-begin-x-example-x", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4206, - "section": "Specification > Specification Extensions", - "anchor": "extension-properties", + "id": "rfc6749.10.2.must-authorization-server-authenticate-client-whenever-possible", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3002, + "section": "Security Considerations > Client Impersonation", + "anchor": "section-10.2", "level": "MUST", "terms": ["MUST"], - "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + "text": "The authorization server MUST authenticate the client whenever possible." }, { - "id": "oas-3.1.specification-extensions.recommended-therefore-implementations-designed-extensibility-support-community", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 4210, - "section": "Specification > Specification Extensions", - "anchor": "specification-extensions", + "id": "rfc6749.10.2.must-authorization-server-cannot-authenticate-client-due", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3002, + "section": "Security Considerations > Client Impersonation", + "anchor": "section-10.2", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "If the authorization server cannot authenticate the client due to the client's nature, the authorization server MUST require the registration of any redirection URI used for receiving authorization responses and SHOULD utilize other means to protect resource owners from such potentially malicious clients." + }, + { + "id": "rfc6749.10.2.should-authorization-server-enforce-explicit-resource-owner", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3011, + "section": "Security Considerations > Client Impersonation", + "anchor": "section-10.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The authorization server SHOULD enforce explicit resource owner authentication and provide the resource owner with information about the client and the requested authorization scope and lifetime." + }, + { + "id": "rfc6749.10.2.should-not-authorization-server-process-repeated-authorization-requests", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3017, + "section": "Security Considerations > Client Impersonation", + "anchor": "section-10.2", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is therefore RECOMMENDED that implementations be designed for extensibility to support community experimentation." + "terms": ["SHOULD NOT"], + "text": "The authorization server SHOULD NOT process repeated authorization requests automatically (without active resource owner interaction) without authenticating the client or relying on other measures to ensure that the repeated request comes from the original client and not an impersonator." }, { - "id": "oas-3.1.specification.schema.must-json-schema-differs-section-section-considered", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 310, - "section": "Specification > Schema", - "anchor": "schema-0", + "id": "rfc6749.10.3.must-access-token-credentials-only-transmitted-using", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3033, + "section": "Security Considerations > Access Tokens", + "anchor": "section-10.3", "level": "MUST", "terms": ["MUST"], - "text": "If the JSON Schema differs from this section, then this section MUST be considered authoritative." + "text": "Access token credentials MUST only be transmitted using TLS as described in Section 1.6 with server authentication as defined by [RFC2818]." }, { - "id": "oas-3.1.specification.schema.required-following-description-field-not-explicitly-described", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 315, - "section": "Specification > Schema", - "anchor": "schema-0", + "id": "rfc6749.10.3.must-access-token-credentials-well-any-confidential", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3033, + "section": "Security Considerations > Access Tokens", + "anchor": "section-10.3", "level": "MUST", - "terms": ["REQUIRED", "MUST", "SHALL", "OPTIONAL"], - "text": "In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL." + "terms": ["MUST"], + "text": "Access token credentials (as well as any confidential access token attributes) MUST be kept confidential in transit and storage, and only shared among the authorization server, the resource servers the access token is valid for, and the client to whom the access token is issued." }, { - "id": "oas-3.1.structural-interoperability.may-same-json-yaml-object-parsed-multiple", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 166, - "section": "Specification > OpenAPI Description Structure > Structural Interoperability", - "anchor": "structural-interoperability", - "level": "MAY", - "terms": ["MAY"], - "text": "If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed as _different_ Object types, the resulting behavior is _implementation defined_, and MAY be treated as an error if detected." + "id": "rfc6749.10.3.must-authorization-server-ensure-access-tokens-cannot", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3044, + "section": "Security Considerations > Access Tokens", + "anchor": "section-10.3", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST ensure that access tokens cannot be generated, modified, or guessed to produce valid access tokens by unauthorized parties." }, { - "id": "oas-3.1.structural-interoperability.recommended-maximum-interoperability-openapi-description-authors-avoid", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 166, - "section": "Specification > OpenAPI Description Structure > Structural Interoperability", - "anchor": "structural-interoperability", + "id": "rfc6749.10.3.should-authorization-server-take-client-identity-account", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3048, + "section": "Security Considerations > Access Tokens", + "anchor": "section-10.3", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For maximum interoperability, it is RECOMMENDED that OpenAPI Description authors avoid such scenarios." + "terms": ["SHOULD", "MAY"], + "text": "The authorization server SHOULD take the client identity into account when choosing how to honor the requested scope and MAY issue an access token with less rights than requested." }, { - "id": "oas-3.1.tag-object.description", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2689, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-description", - "level": "field", - "terms": [], - "text": "A description for the tag. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.10.3.should-client-request-access-tokens-minimal-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3048, + "section": "Security Considerations > Access Tokens", + "anchor": "section-10.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The client SHOULD request access tokens with the minimal scope necessary." }, { - "id": "oas-3.1.tag-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2689, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-description", + "id": "rfc6749.10.4.may-authorization-servers-issue-refresh-tokens-web", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3059, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "Authorization servers MAY issue refresh tokens to web application clients and native application clients." }, { - "id": "oas-3.1.tag-object.externalDocs", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2690, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this tag." + "id": "rfc6749.10.4.must-authorization-server-ensure-refresh-tokens-cannot", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3092, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST ensure that refresh tokens cannot be generated, modified, or guessed to produce valid refresh tokens by unauthorized parties." }, { - "id": "oas-3.1.tag-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2692, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "fixed-fields-18", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.10.4.must-authorization-server-maintain-binding-between-refresh", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3062, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST maintain the binding between a refresh token and the client to whom it was issued." }, { - "id": "oas-3.1.tag-object.name", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2688, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the tag." + "id": "rfc6749.10.4.must-authorization-server-verify-binding-between-refresh", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3070, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST verify the binding between the refresh token and client identity whenever the client identity can be authenticated." }, { - "id": "oas-3.1.tag-object.name.required", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 2688, - "section": "Specification > Schema > Tag Object > Fixed Fields", - "anchor": "tag-name", + "id": "rfc6749.10.4.must-refresh-tokens-kept-confidential-transit-storage", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3062, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Refresh tokens MUST be kept confidential in transit and storage, and shared only among the authorization server and the client to whom the refresh tokens were issued." }, { - "id": "oas-3.1.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 82, - "section": "Definitions > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", - "level": "MAY", - "terms": ["MAY"], - "text": "Implementations MAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification." + "id": "rfc6749.10.4.must-refresh-tokens-only-transmitted-using-tls", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3062, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", + "level": "MUST", + "terms": ["MUST"], + "text": "Refresh tokens MUST only be transmitted using TLS as described in Section 1.6 with server authentication as defined by [RFC2818]." }, { - "id": "oas-3.1.undefined-and-implementation-defined-behavior.not-recommended-support-might-produce-correct-outcomes-many", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 82, - "section": "Definitions > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", + "id": "rfc6749.10.4.should-client-authentication-not-possible-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3070, + "section": "Security Considerations > Refresh Tokens", + "anchor": "section-10.4", "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "This support might produce correct outcomes in many cases, but relying on it is NOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one." + "terms": ["SHOULD"], + "text": "When client authentication is not possible, the authorization server SHOULD deploy other means to detect refresh token abuse." }, { - "id": "oas-3.1.undefined-and-implementation-defined-behavior.recommended-documents-ambiguous-requirements-api-description-authors", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 87, - "section": "Definitions > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "This documents ambiguous requirements that API description authors are RECOMMENDED to avoid in order to maximize interoperability." + "id": "rfc6749.10.5.must-authorization-codes-short-lived-single-use", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3112, + "section": "Security Considerations > Authorization Codes", + "anchor": "section-10.5", + "level": "MUST", + "terms": ["MUST"], + "text": "Authorization codes MUST be short lived and single-use." }, { - "id": "oas-3.1.versions.shall-major-minor-portion-version-string-example", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 95, - "section": "Specification > Versions", - "anchor": "versions", + "id": "rfc6749.10.5.must-client-authenticated-authorization-servers-authenticate-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3118, + "section": "Security Considerations > Authorization Codes", + "anchor": "section-10.5", "level": "MUST", - "terms": ["SHALL"], - "text": "The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set." + "terms": ["MUST"], + "text": "If the client can be authenticated, the authorization servers MUST authenticate the client and ensure that the authorization code was issued to the same client." }, { - "id": "oas-3.1.versions.should-not-patch-version-considered-tooling-making-no", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 95, - "section": "Specification > Versions", - "anchor": "versions", - "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example." + "id": "rfc6749.10.5.must-therefore-client-relies-authorization-code-own", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3105, + "section": "Security Considerations > Authorization Codes", + "anchor": "section-10.5", + "level": "MUST", + "terms": ["MUST"], + "text": "Therefore, if the client relies on the authorization code for its own resource owner authentication, the client redirection endpoint MUST require the use of TLS." }, { - "id": "oas-3.1.versions.should-tooling-supports-oas-3-1-compatible", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 95, - "section": "Specification > Versions", - "anchor": "versions", + "id": "rfc6749.10.5.should-authorization-server-observes-multiple-attempts-exchange", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3112, + "section": "Security Considerations > Authorization Codes", + "anchor": "section-10.5", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.* versions." + "text": "If the authorization server observes multiple attempts to exchange an authorization code for an access token, the authorization server SHOULD attempt to revoke all access tokens already granted based on the compromised authorization code." }, { - "id": "oas-3.1.working-with-binary-data.may-maxlength-keyword-used-set-expected-upper", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 263, - "section": "Specification > Data Types > Working with Binary Data", - "anchor": "working-with-binary-data", - "level": "MAY", - "terms": ["MAY"], - "text": "The `maxLength` keyword MAY be used to set an expected upper bound on the length of a streaming payload." + "id": "rfc6749.10.5.should-transmission-authorization-codes-made-over-secure", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3098, + "section": "Security Considerations > Authorization Codes", + "anchor": "section-10.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The transmission of authorization codes SHOULD be made over a secure channel, and the client SHOULD require the use of TLS with its redirection URI if the URI identifies a network resource." }, { - "id": "oas-3.1.working-with-binary-data.shall-however-contentmediatype-contradicts-relevant-media-type", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 261, - "section": "Specification > Data Types > Working with Binary Data", - "anchor": "working-with-binary-data", + "id": "rfc6749.10.6.must-authorization-server-require-public-clients-require", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3158, + "section": "Security Considerations > Authorization Code Redirection URI Manipulation", + "anchor": "section-10.6", "level": "MUST", - "terms": ["SHALL"], - "text": "However, if `contentMediaType` contradicts a relevant Media Type Object or Encoding Object, then `contentMediaType` SHALL be ignored." + "terms": ["MUST", "SHOULD"], + "text": "The authorization server MUST require public clients and SHOULD require confidential clients to register their redirection URIs." }, { - "id": "oas-3.1.xml-object.attribute", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3496, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-attribute", - "level": "field", - "terms": [], - "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`." + "id": "rfc6749.10.6.must-order-prevent-attack-authorization-server-ensure", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3158, + "section": "Security Considerations > Authorization Code Redirection URI Manipulation", + "anchor": "section-10.6", + "level": "MUST", + "terms": ["MUST"], + "text": "In order to prevent such an attack, the authorization server MUST ensure that the redirection URI used to obtain the authorization code is identical to the redirection URI provided when exchanging the authorization code for an access token." }, { - "id": "oas-3.1.xml-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3499, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "fixed-fields-22", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.10.6.must-redirection-uri-provided-request-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3158, + "section": "Security Considerations > Authorization Code Redirection URI Manipulation", + "anchor": "section-10.6", + "level": "MUST", + "terms": ["MUST"], + "text": "If a redirection URI is provided in the request, the authorization server MUST validate it against the registered value." }, { - "id": "oas-3.1.xml-object.handling-null-values.recommended-however-because-no-distinct-way-represent", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3518, - "section": "Specification > Schema > XML Object > Handling `null` Values", - "anchor": "handling-null-values", + "id": "rfc6749.10.7.should-authorization-server-client-minimize-use-grant", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3187, + "section": "Security Considerations > Resource Owner Password Credentials", + "anchor": "section-10.7", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, because there is no distinct way to represent `null` as an attribute, it is RECOMMENDED to make attribute properties optional rather than use `null`." + "terms": ["SHOULD"], + "text": "The authorization server and client SHOULD minimize use of this grant type and utilize other grant types whenever possible." }, { - "id": "oas-3.1.xml-object.handling-null-values.should-ensure-correct-round-trip-behavior-parsing", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3522, - "section": "Specification > Schema > XML Object > Handling `null` Values", - "anchor": "handling-null-values", + "id": "rfc6749.10.8.must-not-access-tokens-refresh-tokens-resource-owner", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3201, + "section": "Security Considerations > Request Confidentiality", + "anchor": "section-10.8", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Access tokens, refresh tokens, resource owner passwords, and client credentials MUST NOT be transmitted in the clear." + }, + { + "id": "rfc6749.10.8.should-not-authorization-codes-transmitted-clear", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3201, + "section": "Security Considerations > Request Confidentiality", + "anchor": "section-10.8", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "To ensure correct round-trip behavior, when parsing an element that omits an attribute, implementations SHOULD set the corresponding property to `null` if the schema allows for that value (e.g. `type: [\"number\", \"null\"]`), and omit the property otherwise (e.g.`type: \"number\"`)." + "terms": ["SHOULD NOT"], + "text": "Authorization codes SHOULD NOT be transmitted in the clear." }, { - "id": "oas-3.1.xml-object.handling-null-values.should-however-implementations-handle-null-values-follows", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3513, - "section": "Specification > Schema > XML Object > Handling `null` Values", - "anchor": "handling-null-values", + "id": "rfc6749.10.8.should-not-state-scope-parameters-include-sensitive-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3205, + "section": "Security Considerations > Request Confidentiality", + "anchor": "section-10.8", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "However, implementations SHOULD handle `null` values as follows:" + "terms": ["SHOULD NOT"], + "text": "The \"state\" and \"scope\" parameters SHOULD NOT include sensitive client or resource owner information in plain text, as they can be transmitted over insecure channels or stored insecurely." }, { - "id": "oas-3.1.xml-object.name", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3493, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-name", - "level": "field", - "terms": [], - "text": "Replaces the inferred name of the element/attribute used for the described schema property. For the root schema object of a schema component, the inferred name is the name of the component; for other schemas the name is inferred from the parent property name. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `\"array\"` (outside the `items`), it will affect the wrapping element if and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored." + "id": "rfc6749.10.9.must-client-validate-authorization-server-s-tls", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3211, + "section": "Security Considerations > Ensuring Endpoint Authenticity", + "anchor": "section-10.9", + "level": "MUST", + "terms": ["MUST"], + "text": "The client MUST validate the authorization server's TLS certificate as defined by [RFC6125] and in accordance with its requirements for server identity authentication." }, { - "id": "oas-3.1.xml-object.namespace", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3494, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-namespace", - "level": "field", - "terms": [], - "text": "The URI of the namespace definition. Value MUST be in the form of a non-relative URI." + "id": "rfc6749.10.9.must-order-prevent-man-middle-attacks-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3211, + "section": "Security Considerations > Ensuring Endpoint Authenticity", + "anchor": "section-10.9", + "level": "MUST", + "terms": ["MUST"], + "text": "In order to prevent man-in-the-middle attacks, the authorization server MUST require the use of TLS with server authentication as defined by [RFC2818] for any request sent to the authorization and token endpoints." }, { - "id": "oas-3.1.xml-object.namespace.must-value-form-non-relative-uri", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3494, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-namespace", + "id": "rfc6749.11.1.1.must-new-parameters-separately-registered-oauth-parameters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3456, + "section": "IANA Considerations > OAuth Access Token Types Registry > Registration Template", + "anchor": "section-11.1.1", "level": "MUST", "terms": ["MUST"], - "text": "Value MUST be in the form of a non-relative URI." + "text": "New parameters MUST be separately registered in the OAuth Parameters registry as described by Section 11.2." }, { - "id": "oas-3.1.xml-object.prefix", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3495, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-prefix", - "level": "field", - "terms": [], - "text": "The prefix to be used for the name." + "id": "rfc6749.11.4.1.must-not-values-error-name-include-characters-outside", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 3761, + "section": "IANA Considerations > OAuth Extensions Error Registry > Registration Template", + "anchor": "section-11.4.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Values for the error name MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.1.xml-object.should-using-arrays-xml-element-names-not", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3486, - "section": "Specification > Schema > XML Object", - "anchor": "xml-object", + "id": "rfc6749.2.1.should-authorization-server-does-not-provide-support", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 770, + "section": "Client Registration > Client Types", + "anchor": "section-2.1", "level": "SHOULD", "terms": ["SHOULD"], - "text": "When using arrays, XML element names are _not_ inferred (for singular/plural forms) and the `name` field SHOULD be used to add that information." + "text": "If the authorization server does not provide support for such clients or does not provide guidance with regard to their registration, the client SHOULD register each component as a separate client." }, { - "id": "oas-3.1.xml-object.wrapped", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3497, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-wrapped", - "level": "field", - "terms": [], - "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `\"array\"` (outside the `items`)." + "id": "rfc6749.2.1.should-not-authorization-server-make-assumptions-about-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 765, + "section": "Client Registration > Client Types", + "anchor": "section-2.1", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The authorization server SHOULD NOT make assumptions about the client type." }, { - "id": "oas-3.1.xml-object.wrapped.may-used-only-array-definition", - "spec": "openapi", - "version": "3.1.2", - "source": "openapi/3.1.2.md", - "line": 3497, - "section": "Specification > Schema > XML Object > Fixed Fields", - "anchor": "xml-wrapped", + "id": "rfc6749.2.2.must-not-client-identifier-not-secret-exposed-resource", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 826, + "section": "Client Registration > Client Identifier", + "anchor": "section-2.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The client identifier is not a secret; it is exposed to the resource owner and MUST NOT be used alone for client authentication." + }, + { + "id": "rfc6749.2.2.should-authorization-server-document-size-any-identifier", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 833, + "section": "Client Registration > Client Identifier", + "anchor": "section-2.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The authorization server SHOULD document the size of any identifier it issues." + }, + { + "id": "rfc6749.2.3.1.may-alternatively-authorization-server-support-including-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 883, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", "level": "MAY", "terms": ["MAY"], - "text": "MAY be used only for an array definition." + "text": "Alternatively, the authorization server MAY support including the client credentials in the request-body using the following parameters:" }, { - "id": "oas-3.2.appendix-c-using-rfc6570-based-serialization.may-implementations-specification-use-implementation-rfc6570-perform", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4893, - "section": "Appendix C: Using RFC6570-Based Serialization", - "anchor": "appendix-c-using-rfc6570-based-serialization", + "id": "rfc6749.2.3.1.may-client-omit-parameter-client-secret-empty", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 891, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", "level": "MAY", "terms": ["MAY"], - "text": "Implementations of this specification MAY use an implementation of RFC6570 to perform variable expansion, however, some caveats apply." + "text": "The client MAY omit the parameter if the client secret is an empty string." }, { - "id": "oas-3.2.appendix-e-percent-encoding-and-form-media-types.must-set-characters-encoded-varies-depending-version", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5170, - "section": "Appendix E: Percent-Encoding and Form Media Types", - "anchor": "appendix-e-percent-encoding-and-form-media-types", + "id": "rfc6749.2.3.1.may-clients-possession-client-password-use-http", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 869, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "MAY", + "terms": ["MAY"], + "text": "Clients in possession of a client password MAY use the HTTP Basic authentication scheme as defined in [RFC2617] to authenticate with the authorization server." + }, + { + "id": "rfc6749.2.3.1.must-authorization-server-require-use-tls-described", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 921, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", "level": "MUST", "terms": ["MUST"], - "text": "The set of characters that MUST be encoded varies depending on which version of which specification you use, and (for URIs) in which part of the URI the character appears." + "text": "The authorization server MUST require the use of TLS as described in Section 1.6 when sending requests using password authentication." }, { - "id": "oas-3.2.appendix-g-parsing-and-resolution-guidance.may-implementations-support-complete-document-parsing-any", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5482, - "section": "Appendix G: Parsing and Resolution Guidance", - "anchor": "appendix-g-parsing-and-resolution-guidance", + "id": "rfc6749.2.3.1.must-authorization-server-support-http-basic-authentication", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 869, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST support the HTTP Basic authentication scheme for authenticating clients that were issued a client password." + }, + { + "id": "rfc6749.2.3.1.must-not-parameters-only-transmitted-request-body-included", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 903, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The parameters can only be transmitted in the request-body and MUST NOT be included in the request URI." + }, + { + "id": "rfc6749.2.3.1.must-since-client-authentication-method-involves-password", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 924, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Since this client authentication method involves a password, the authorization server MUST protect any endpoint utilizing it against brute force attacks." + }, + { + "id": "rfc6749.2.3.1.not-recommended-including-client-credentials-request-body-using", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 903, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "SHOULD", + "terms": ["NOT RECOMMENDED", "SHOULD"], + "text": "Including the client credentials in the request-body using the two parameters is NOT RECOMMENDED and SHOULD be limited to clients unable to directly utilize the HTTP Basic authentication scheme (or other password-based HTTP authentication schemes)." + }, + { + "id": "rfc6749.2.3.1.required-client-id", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 887, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "client_id REQUIRED." + }, + { + "id": "rfc6749.2.3.1.required-client-secret", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 891, + "section": "Client Registration > Client Authentication > Client Password", + "anchor": "section-2.3.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "client_secret REQUIRED." + }, + { + "id": "rfc6749.2.3.2.may-authorization-server-support-any-suitable-http", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 930, + "section": "Client Registration > Client Authentication > Other Authentication Methods", + "anchor": "section-2.3.2", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support complete-document parsing in any of the following ways:" + "text": "The authorization server MAY support any suitable HTTP authentication scheme matching its security requirements." }, { - "id": "oas-3.2.base-uri-within-content.must-guarantee-interoperability-schema-objects-containing-id", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5324, - "section": "Appendix F: Examples of Base URI Determination and Reference Resolution > Base URI Within Content", - "anchor": "base-uri-within-content", + "id": "rfc6749.2.3.2.must-using-other-authentication-methods-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 930, + "section": "Client Registration > Client Authentication > Other Authentication Methods", + "anchor": "section-2.3.2", "level": "MUST", "terms": ["MUST"], - "text": "To guarantee interoperability, Schema Objects containing an `$id`, or that are under a schema containing an `$id`, MUST be referenced by the nearest such `$id` for the non-fragment part of the reference." + "text": "When using other authentication methods, the authorization server MUST define a mapping between the client identifier (registration record) and authentication scheme." }, { - "id": "oas-3.2.callback-object.pattern-expression", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2259, - "section": "Objects and Fields > Callback Object > Patterned Fields", - "anchor": "callback-expression", - "level": "field", - "terms": [], - "text": "A Path Item Object used to define a callback request and expected responses. A complete example is available." + "id": "rfc6749.2.3.may-authorization-server-accept-any-form-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 849, + "section": "Client Registration > Client Authentication", + "anchor": "section-2.3", + "level": "MAY", + "terms": ["MAY"], + "text": "The authorization server MAY accept any form of client authentication meeting its security requirements." }, { - "id": "oas-3.2.callback-object.patterned-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2261, - "section": "Objects and Fields > Callback Object > Patterned Fields", - "anchor": "patterned-fields-1", + "id": "rfc6749.2.3.may-authorization-server-establish-client-authentication-method", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 859, + "section": "Client Registration > Client Authentication", + "anchor": "section-2.3", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "The authorization server MAY establish a client authentication method with public clients." }, { - "id": "oas-3.2.components-object.callbacks", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 412, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-callbacks", - "level": "field", - "terms": [], - "text": "An object to hold reusable Callback Objects." + "id": "rfc6749.2.3.must-not-client-use-more-one-authentication-method", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 864, + "section": "Client Registration > Client Authentication", + "anchor": "section-2.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The client MUST NOT use more than one authentication method in each request." }, { - "id": "oas-3.2.components-object.examples", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 407, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-examples", - "level": "field", - "terms": [], - "text": "An object to hold reusable Example Objects." + "id": "rfc6749.2.3.must-not-however-authorization-server-rely-public-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 859, + "section": "Client Registration > Client Authentication", + "anchor": "section-2.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "However, the authorization server MUST NOT rely on public client authentication for the purpose of identifying the client." }, { - "id": "oas-3.2.components-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 416, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "fixed-fields-5", + "id": "rfc6749.2.shall-registering-client-client-developer", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 735, + "section": "Client Registration", + "anchor": "section-2", + "level": "MUST", + "terms": ["SHALL"], + "text": "When registering a client, the client developer SHALL:" + }, + { + "id": "rfc6749.3.1.1.may-extension-response-types-contain-space-delimited", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1034, + "section": "Protocol Endpoints > Authorization Endpoint > Response Type", + "anchor": "section-3.1.1", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Extension response types MAY contain a space-delimited (%x20) list of values, where the order of values does not matter (e.g., response type \"a b\" is the same as \"b a\")." }, { - "id": "oas-3.2.components-object.fixed-fields.must-all-fixed-fields-declared-above-objects", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 418, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "fixed-fields-5", + "id": "rfc6749.3.1.1.must-authorization-request-missing-response-type-parameter", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1039, + "section": "Protocol Endpoints > Authorization Endpoint > Response Type", + "anchor": "section-3.1.1", "level": "MUST", "terms": ["MUST"], - "text": "All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\\.\\-_]+$`." + "text": "If an authorization request is missing the \"response_type\" parameter, or if the response type is not understood, the authorization server MUST return an error response as described in Section 4.1.2.1." }, { - "id": "oas-3.2.components-object.headers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 409, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-headers", - "level": "field", - "terms": [], - "text": "An object to hold reusable Header Objects." + "id": "rfc6749.3.1.1.must-value-one-code-requesting-authorization-code", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1027, + "section": "Protocol Endpoints > Authorization Endpoint > Response Type", + "anchor": "section-3.1.1", + "level": "MUST", + "terms": ["MUST"], + "text": "The value MUST be one of \"code\" for requesting an authorization code as described by Section 4.1.1, \"token\" for requesting an access token (implicit grant) as described by Section 4.2.1, or a registered extension value as described by Section 8.4." }, { - "id": "oas-3.2.components-object.links", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 411, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-links", - "level": "field", - "terms": [], - "text": "An object to hold reusable Link Objects." + "id": "rfc6749.3.1.1.required-response-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1027, + "section": "Protocol Endpoints > Authorization Endpoint > Response Type", + "anchor": "section-3.1.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "response_type REQUIRED." }, { - "id": "oas-3.2.components-object.mediaTypes", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 414, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-media-types", - "level": "field", - "terms": [], - "text": "An object to hold reusable Media Type Objects." + "id": "rfc6749.3.1.2.1.should-redirection-endpoint-require-use-tls-described", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1073, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Endpoint Request Confidentiality", + "anchor": "section-3.1.2.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The redirection endpoint SHOULD require the use of TLS as described in Section 1.6 when the requested response type is \"code\" or \"token\", or when the redirection request will result in the transmission of sensitive credentials over an open network." + }, + { + "id": "rfc6749.3.1.2.1.should-tls-not-available-authorization-server-warn", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1073, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Endpoint Request Confidentiality", + "anchor": "section-3.1.2.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If TLS is not available, the authorization server SHOULD warn the resource owner about the insecure endpoint prior to redirection (e.g., display a message during the authorization request)." }, { - "id": "oas-3.2.components-object.parameters", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 406, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-parameters", - "level": "field", - "terms": [], - "text": "An object to hold reusable Parameter Objects." + "id": "rfc6749.3.1.2.2.may-authorization-server-allow-client-register-multiple", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1112, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Registration Requirements", + "anchor": "section-3.1.2.2", + "level": "MAY", + "terms": ["MAY"], + "text": "The authorization server MAY allow the client to register multiple redirection endpoints." }, { - "id": "oas-3.2.components-object.pathItems", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 413, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-path-items", - "level": "field", - "terms": [], - "text": "An object to hold reusable Path Item Objects." + "id": "rfc6749.3.1.2.2.must-authorization-server-require-following-clients-register", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1093, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Registration Requirements", + "anchor": "section-3.1.2.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST require the following clients to register their redirection endpoint:" }, { - "id": "oas-3.2.components-object.requestBodies", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 408, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-request-bodies", - "level": "field", - "terms": [], - "text": "An object to hold reusable Request Body Objects." + "id": "rfc6749.3.1.2.2.should-authorization-server-require-all-clients-register", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1100, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Registration Requirements", + "anchor": "section-3.1.2.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The authorization server SHOULD require all clients to register their redirection endpoint prior to utilizing the authorization endpoint." }, { - "id": "oas-3.2.components-object.responses", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 405, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-responses", - "level": "field", - "terms": [], - "text": "An object to hold reusable Response Objects." + "id": "rfc6749.3.1.2.2.should-authorization-server-require-client-provide-complete", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1103, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Registration Requirements", + "anchor": "section-3.1.2.2", + "level": "SHOULD", + "terms": ["SHOULD", "MAY"], + "text": "The authorization server SHOULD require the client to provide the complete redirection URI (the client MAY use the \"state\" request parameter to achieve per-request customization)." }, { - "id": "oas-3.2.components-object.schemas", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 404, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-schemas", - "level": "field", - "terms": [], - "text": "An object to hold reusable Schema Objects." + "id": "rfc6749.3.1.2.2.should-requiring-registration-complete-redirection-uri-not", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1103, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Registration Requirements", + "anchor": "section-3.1.2.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If requiring the registration of the complete redirection URI is not possible, the authorization server SHOULD require the registration of the URI scheme, authority, and path (allowing the client to dynamically vary only the query component of the redirection URI when requesting authorization)." }, { - "id": "oas-3.2.components-object.securitySchemes", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 410, - "section": "Objects and Fields > Components Object > Fixed Fields", - "anchor": "components-security-schemes", - "level": "field", - "terms": [], - "text": "An object to hold reusable Security Scheme Objects." + "id": "rfc6749.3.1.2.3.must-client-registration-included-full-redirection-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1134, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Dynamic Configuration", + "anchor": "section-3.1.2.3", + "level": "MUST", + "terms": ["MUST"], + "text": "If the client registration included the full redirection URI, the authorization server MUST compare the two URIs using simple string comparison as defined in [RFC3986] Section 6.2.1." }, { - "id": "oas-3.2.conditions-for-using-the-discriminator-object.may-avoid-redundancy-discriminator-added-parent-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3652, - "section": "Objects and Fields > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", - "level": "MAY", - "terms": ["MAY"], - "text": "To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas building on the parent schema via an `allOf` construct may be used as an alternate schema." + "id": "rfc6749.3.1.2.3.must-multiple-redirection-uris-have-registered-only", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1129, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Dynamic Configuration", + "anchor": "section-3.1.2.3", + "level": "MUST", + "terms": ["MUST"], + "text": "If multiple redirection URIs have been registered, if only part of the redirection URI has been registered, or if no redirection URI has been registered, the client MUST include a redirection URI with the authorization request using the \"redirect_uri\" request parameter." }, { - "id": "oas-3.2.conditions-for-using-the-discriminator-object.must-both-oneof-anyof-use-cases-keywords", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3650, - "section": "Objects and Fields > Discriminator Object > Conditions for Using the Discriminator Object", - "anchor": "conditions-for-using-the-discriminator-object", + "id": "rfc6749.3.1.2.3.must-redirection-uri-included-authorization-request-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1134, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Dynamic Configuration", + "anchor": "section-3.1.2.3", "level": "MUST", "terms": ["MUST"], - "text": "In both the `oneOf` and `anyOf` use cases, where those keywords are adjacent to `discriminator`, all possible schemas MUST be listed explicitly." + "text": "When a redirection URI is included in an authorization request, the authorization server MUST compare and match the value received against at least one of the registered redirection URIs (or URI components) as defined in [RFC3986] Section 6, if any redirection URIs were registered." }, { - "id": "oas-3.2.conflicts-between-field-types-and-reference-contexts.may-same-json-yaml-object-parsed-multiple", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5510, - "section": "Appendix G: Parsing and Resolution Guidance > Conflicts Between Field Types and Reference Contexts", - "anchor": "conflicts-between-field-types-and-reference-contexts", - "level": "MAY", - "terms": ["MAY"], - "text": "If the same JSON/YAML object is parsed multiple times and the respective contexts require it to be parsed as _different_ Object types, the resulting behavior is _implementation defined_, and MAY be treated as an error if detected." + "id": "rfc6749.3.1.2.4.must-not-authorization-request-fails-validation-due-missing", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1144, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Invalid Endpoint", + "anchor": "section-3.1.2.4", + "level": "MUST", + "terms": ["SHOULD", "MUST NOT"], + "text": "If an authorization request fails validation due to a missing, invalid, or mismatching redirection URI, the authorization server SHOULD inform the resource owner of the error and MUST NOT automatically redirect the user-agent to the invalid redirection URI." }, { - "id": "oas-3.2.conflicts-between-field-types-and-reference-contexts.recommended-maximum-interoperability-openapi-description-authors-avoid", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5510, - "section": "Appendix G: Parsing and Resolution Guidance > Conflicts Between Field Types and Reference Contexts", - "anchor": "conflicts-between-field-types-and-reference-contexts", + "id": "rfc6749.3.1.2.5.must-third-party-scripts-included-client-ensure", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1157, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Endpoint Content", + "anchor": "section-3.1.2.5", + "level": "MUST", + "terms": ["MUST"], + "text": "If third-party scripts are included, the client MUST ensure that its own scripts (used to extract and remove the credentials from the URI) will execute first." + }, + { + "id": "rfc6749.3.1.2.5.should-instead-extract-credentials-uri-redirect-user", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1157, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Endpoint Content", + "anchor": "section-3.1.2.5", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For maximum interoperability, it is RECOMMENDED that OpenAPI Description authors avoid such scenarios." + "terms": ["SHOULD"], + "text": "Instead, it SHOULD extract the credentials from the URI and redirect the user-agent again to another endpoint without exposing the credentials (in the URI or elsewhere)." }, { - "id": "oas-3.2.contact-object.email", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 229, - "section": "Objects and Fields > Contact Object > Fixed Fields", - "anchor": "contact-email", - "level": "field", - "terms": [], - "text": "The email address of the contact person/organization. This MUST be in the form of an email address." + "id": "rfc6749.3.1.2.5.should-not-client-include-any-third-party-scripts", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1157, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint > Endpoint Content", + "anchor": "section-3.1.2.5", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The client SHOULD NOT include any third-party scripts (e.g., third-party analytics, social plug-ins, ad networks) in the redirection endpoint response." }, { - "id": "oas-3.2.contact-object.email.must-form-email-address", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 229, - "section": "Objects and Fields > Contact Object > Fixed Fields", - "anchor": "contact-email", + "id": "rfc6749.3.1.2.must-endpoint-uri-include-application-x-www", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1052, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint", + "anchor": "section-3.1.2", "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of an email address." + "terms": ["MAY", "MUST"], + "text": "The endpoint URI MAY include an \"application/x-www-form-urlencoded\" formatted (per Appendix B) query component ([RFC3986] Section 3.4), which MUST be retained when adding additional query parameters." }, { - "id": "oas-3.2.contact-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 231, - "section": "Objects and Fields > Contact Object > Fixed Fields", - "anchor": "fixed-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.3.1.2.must-not-endpoint-uri-include-fragment-component", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1052, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint", + "anchor": "section-3.1.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The endpoint URI MUST NOT include a fragment component." }, { - "id": "oas-3.2.contact-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 227, - "section": "Objects and Fields > Contact Object > Fixed Fields", - "anchor": "contact-name", - "level": "field", - "terms": [], - "text": "The identifying name of the contact person/organization." + "id": "rfc6749.3.1.2.must-redirection-endpoint-uri-absolute-uri-defined", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1052, + "section": "Protocol Endpoints > Authorization Endpoint > Redirection Endpoint", + "anchor": "section-3.1.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The redirection endpoint URI MUST be an absolute URI as defined by [RFC3986] Section 4.3." }, { - "id": "oas-3.2.contact-object.url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 228, - "section": "Objects and Fields > Contact Object > Fixed Fields", - "anchor": "contact-url", - "level": "field", - "terms": [], - "text": "The URI for the contact information. This MUST be in the form of a URI." + "id": "rfc6749.3.1.must-authorization-server-first-verify-identity-resource", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 981, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST first verify the identity of the resource owner." }, { - "id": "oas-3.2.contact-object.url.must-form-uri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 228, - "section": "Objects and Fields > Contact Object > Fixed Fields", - "anchor": "contact-url", + "id": "rfc6749.3.1.must-authorization-server-ignore-unrecognized-request-parameters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1015, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "text": "The authorization server MUST ignore unrecognized request parameters." }, { - "id": "oas-3.2.discriminator-object.defaultMapping", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3642, - "section": "Objects and Fields > Discriminator Object > Fixed Fields", - "anchor": "discriminator-default-mapping", - "level": "field", - "terms": [], - "text": "The schema name or URI reference to a schema that is expected to validate the structure of the model when the discriminating property is not present in the payload or contains a value for which there is no explicit or implicit mapping." + "id": "rfc6749.3.1.must-authorization-server-support-use-http-get", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1003, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "The authorization server MUST support the use of the HTTP \"GET\" method [RFC2616] for the authorization endpoint and MAY support the use of the \"POST\" method as well." }, { - "id": "oas-3.2.discriminator-object.examples.may-oas-3-x-response-payload-described", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3695, - "section": "Objects and Fields > Discriminator Object > Examples", - "anchor": "examples-0", - "level": "MAY", - "terms": ["MAY"], - "text": "In OAS 3.x, a response payload MAY be described to be exactly one of any number of types:" + "id": "rfc6749.3.1.must-endpoint-uri-include-application-x-www", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 992, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "The endpoint URI MAY include an \"application/x-www-form-urlencoded\" formatted (per Appendix B) query component ([RFC3986] Section 3.4), which MUST be retained when adding additional query parameters." }, { - "id": "oas-3.2.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3744, - "section": "Objects and Fields > Discriminator Object > Examples", - "anchor": "examples-0", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If the discriminating value does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail." + "id": "rfc6749.3.1.must-not-endpoint-uri-include-fragment-component", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 992, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The endpoint URI MUST NOT include a fragment component." }, { - "id": "oas-3.2.discriminator-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3644, - "section": "Objects and Fields > Discriminator Object > Fixed Fields", - "anchor": "fixed-fields-21", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.3.1.must-not-request-response-parameters-included-more-once", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1015, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Request and response parameters MUST NOT be included more than once." }, { - "id": "oas-3.2.discriminator-object.mapping", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3641, - "section": "Objects and Fields > Discriminator Object > Fixed Fields", - "anchor": "discriminator-mapping", - "level": "field", - "terms": [], - "text": "An object to hold mappings between payload values and schema names or URI references." + "id": "rfc6749.3.1.must-parameters-sent-without-value-treated-they", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1015, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Parameters sent without a value MUST be treated as if they were omitted from the request." }, { - "id": "oas-3.2.discriminator-object.may-polymorphic-schema-include-discriminator-object-defines", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3630, - "section": "Objects and Fields > Discriminator Object", - "anchor": "discriminator-object", + "id": "rfc6749.3.1.must-since-requests-authorization-endpoint-result-user", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 997, + "section": "Protocol Endpoints > Authorization Endpoint", + "anchor": "section-3.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Since requests to the authorization endpoint result in user authentication and the transmission of clear-text credentials (in the HTTP response), the authorization server MUST require the use of TLS as described in Section 1.6 when sending requests to the authorization endpoint." + }, + { + "id": "rfc6749.3.2.1.may-client-use-client-id-request-parameter", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1239, + "section": "Protocol Endpoints > Token Endpoint > Client Authentication", + "anchor": "section-3.2.1", "level": "MAY", "terms": ["MAY"], - "text": "A polymorphic schema MAY include a Discriminator Object, which defines the name of the property that may be used as a hint for which schema of the `anyOf` or `oneOf`, or which schema that references the current schema in an `allOf`, is expected to validate the structure of the model." + "text": "A client MAY use the \"client_id\" request parameter to identify itself when sending requests to the token endpoint." }, { - "id": "oas-3.2.discriminator-object.must-not-note-discriminator-change-validation-outcome-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3634, - "section": "Objects and Fields > Discriminator Object", - "anchor": "discriminator-object", + "id": "rfc6749.3.2.1.must-authorization-code-grant-type-request-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1239, + "section": "Protocol Endpoints > Token Endpoint > Client Authentication", + "anchor": "section-3.2.1", "level": "MUST", - "terms": ["MUST NOT"], - "text": "Note that `discriminator` MUST NOT change the validation outcome of the schema." + "terms": ["MUST"], + "text": "In the \"authorization_code\" \"grant_type\" request to the token endpoint, an unauthenticated client MUST send its \"client_id\" to prevent itself from inadvertently accepting a code intended for a client with a different \"client_id\"." }, { - "id": "oas-3.2.discriminator-object.optional-discriminating-property.must-discriminating-property-defined-optional-discriminator-object", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3672, - "section": "Objects and Fields > Discriminator Object > Optional Discriminating Property", - "anchor": "optional-discriminating-property", + "id": "rfc6749.3.2.1.must-confidential-clients-other-clients-issued-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1207, + "section": "Protocol Endpoints > Token Endpoint > Client Authentication", + "anchor": "section-3.2.1", "level": "MUST", "terms": ["MUST"], - "text": "When the discriminating property is defined as optional, the Discriminator Object MUST include a `defaultMapping` field that specifies a schema that is expected to validate the structure of the model when the discriminating property is not present in the payload or contains a value for which there is no explicit or implicit mapping." + "text": "Confidential clients or other clients issued client credentials MUST authenticate with the authorization server as described in Section 2.3 when making requests to the token endpoint." }, { - "id": "oas-3.2.discriminator-object.options-for-mapping-values-to-schemas.must-ensure-ambiguous-value-e-g-foo", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3661, - "section": "Objects and Fields > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", + "id": "rfc6749.3.2.must-authorization-server-ignore-unrecognized-request-parameters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1200, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", "level": "MUST", "terms": ["MUST"], - "text": "To ensure that an ambiguous value (e.g. `\"foo\"`) is treated as a relative URI reference by all implementations, authors MUST prefix it with the `\".\"` path segment (e.g. `\"./foo\"`)." + "text": "The authorization server MUST ignore unrecognized request parameters." }, { - "id": "oas-3.2.discriminator-object.options-for-mapping-values-to-schemas.must-mapping-keys-string-values-but-tooling", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3667, - "section": "Objects and Fields > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", + "id": "rfc6749.3.2.must-client-use-http-post-method-making", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1197, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", "level": "MUST", - "terms": ["MUST", "MAY"], - "text": "Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison." + "terms": ["MUST"], + "text": "The client MUST use the HTTP \"POST\" method when making access token requests." }, { - "id": "oas-3.2.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-defaultmapping-value-both", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3661, - "section": "Objects and Fields > Discriminator Object > Options for Mapping Values to Schemas", - "anchor": "options-for-mapping-values-to-schemas", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "The behavior of a `mapping` value or `defaultMapping` value that is both a valid schema name and a valid relative URI reference is implementation-defined, but it is RECOMMENDED that it be treated as a schema name." + "id": "rfc6749.3.2.must-endpoint-uri-include-application-x-www", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1187, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "The endpoint URI MAY include an \"application/x-www-form-urlencoded\" formatted (per Appendix B) query component ([RFC3986] Section 3.4), which MUST be retained when adding additional query parameters." }, { - "id": "oas-3.2.discriminator-object.propertyName", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3640, - "section": "Objects and Fields > Discriminator Object > Fixed Fields", - "anchor": "property-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the discriminating property in the payload that will hold the discriminating value. The discriminating property MAY be defined as required or optional, but when defined as optional the Discriminator Object MUST include a `defaultMapping` field that specifies which schema is expected to validate the structure of the model when the discriminating property is not present." + "id": "rfc6749.3.2.must-not-endpoint-uri-include-fragment-component", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1187, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The endpoint URI MUST NOT include a fragment component." }, { - "id": "oas-3.2.discriminator-object.propertyName.must-discriminating-property-defined-required-optional-but", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3640, - "section": "Objects and Fields > Discriminator Object > Fixed Fields", - "anchor": "property-name", + "id": "rfc6749.3.2.must-not-request-response-parameters-included-more-once", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1200, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "The discriminating property MAY be defined as required or optional, but when defined as optional the Discriminator Object MUST include a `defaultMapping` field that specifies which schema is expected to validate the structure of the model when the discriminating property is not present." + "terms": ["MUST NOT"], + "text": "Request and response parameters MUST NOT be included more than once." }, { - "id": "oas-3.2.discriminator-object.propertyName.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3640, - "section": "Objects and Fields > Discriminator Object > Fixed Fields", - "anchor": "property-name", + "id": "rfc6749.3.2.must-parameters-sent-without-value-treated-they", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1200, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Parameters sent without a value MUST be treated as if they were omitted from the request." }, { - "id": "oas-3.2.encoding-object.allowReserved", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1763, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", - "level": "field", - "terms": [], - "text": "When this is true, values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed in the target media type; see URL Percent-Encoding for details. The default value is `false`. This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "id": "rfc6749.3.2.must-since-requests-token-endpoint-result-transmission", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1192, + "section": "Protocol Endpoints > Token Endpoint", + "anchor": "section-3.2", + "level": "MUST", + "terms": ["MUST"], + "text": "Since requests to the token endpoint result in the transmission of clear-text credentials (in the HTTP request and response), the authorization server MUST require the use of TLS as described in Section 1.6 when sending requests to the token endpoint." }, { - "id": "oas-3.2.encoding-object.allowReserved.shall-field-ignored-media-type-not-application", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1763, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", + "id": "rfc6749.3.3.may-authorization-server-fully-partially-ignore-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1264, + "section": "Protocol Endpoints > Access Token Scope", + "anchor": "section-3.3", + "level": "MAY", + "terms": ["MAY"], + "text": "The authorization server MAY fully or partially ignore the scope requested by the client, based on the authorization server policy or the resource owner's instructions." + }, + { + "id": "rfc6749.3.3.must-client-omits-scope-parameter-requesting-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1271, + "section": "Protocol Endpoints > Access Token Scope", + "anchor": "section-3.3", "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + "terms": ["MUST"], + "text": "If the client omits the scope parameter when requesting authorization, the authorization server MUST either process the request using a pre-defined default value or fail the request indicating an invalid scope." }, { - "id": "oas-3.2.encoding-object.allowReserved.shall-value-explicitly-defined-value-contenttype-implicit", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1763, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-allow-reserved", + "id": "rfc6749.3.3.must-issued-access-token-scope-different-one", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1264, + "section": "Protocol Endpoints > Access Token Scope", + "anchor": "section-3.3", "level": "MUST", - "terms": ["SHALL"], - "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "terms": ["MUST"], + "text": "If the issued access token scope is different from the one requested by the client, the authorization server MUST include the \"scope\" response parameter to inform the client of the actual scope granted." }, { - "id": "oas-3.2.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1719, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-0", + "id": "rfc6749.3.3.should-authorization-server-document-scope-requirements-default", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1271, + "section": "Protocol Endpoints > Access Token Scope", + "anchor": "section-3.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The authorization server SHOULD document its scope requirements and default value (if defined)." + }, + { + "id": "rfc6749.3.may-extension-grant-types-define-additional-endpoints", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 976, + "section": "Protocol Endpoints", + "anchor": "section-3", "level": "MAY", "terms": ["MAY"], - "text": "These fields MAY be used either with or without the RFC6570-style serialization fields defined in the next section below." + "text": "Extension grant types MAY define additional endpoints as needed." }, { - "id": "oas-3.2.encoding-object.common-fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1729, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-0", + "id": "rfc6749.4.1.1.must-value-set-code", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1389, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be set to \"code\"." + }, + { + "id": "rfc6749.4.1.1.optional-redirect-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1395, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "terms": ["OPTIONAL"], + "text": "redirect_uri OPTIONAL." }, { - "id": "oas-3.2.encoding-object.content-transfer-encoding-and-contentencoding.not-recommended-because-because-encoding-object-s-contenttype", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1881, - "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > `Content-Transfer-Encoding` and `contentEncoding`", - "anchor": "content-transfer-encoding-and-contentencoding", + "id": "rfc6749.4.1.1.optional-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1407, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "scope OPTIONAL." + }, + { + "id": "rfc6749.4.1.1.recommended-state", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1411, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Because of this, and because the Encoding Object's `contentType` defaulting rules do not take the Schema Object's `contentMediaType` into account, the use of `contentMediaType` with an Encoding Object is NOT RECOMMENDED." + "terms": ["RECOMMENDED"], + "text": "state RECOMMENDED." }, { - "id": "oas-3.2.encoding-object.content-transfer-encoding-and-contentencoding.shall-note-stated-working-binary-data-encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1881, - "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > `Content-Transfer-Encoding` and `contentEncoding`", - "anchor": "content-transfer-encoding-and-contentencoding", + "id": "rfc6749.4.1.1.required-client-id", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1392, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", "level": "MUST", - "terms": ["SHALL"], - "text": "Note that as stated in Working with Binary Data, if the Encoding Object's `contentType`, whether set explicitly or implicitly through its default value rules, disagrees with the `contentMediaType` in a Schema Object, the `contentMediaType` SHALL be ignored." + "terms": ["REQUIRED"], + "text": "client_id REQUIRED." }, { - "id": "oas-3.2.encoding-object.contentType", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1723, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-content-type", - "level": "field", - "terms": [], - "text": "The `Content-Type` for encoding a specific property. The value is a comma-separated list, each element of which is either a specific media type (e.g. `image/png`) or a media type range (e.g. `image/*`). The default value depends on the type as shown in the table below." + "id": "rfc6749.4.1.1.required-response-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1389, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "response_type REQUIRED." }, { - "id": "oas-3.2.encoding-object.encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1725, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-encoding", - "level": "field", - "terms": [], - "text": "Applies nested Encoding Objects in the same manner as the Media Type Object's `encoding` field." + "id": "rfc6749.4.1.1.should-parameter-used-preventing-cross-site-request", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1411, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Request", + "anchor": "section-4.1.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The parameter SHOULD be used for preventing cross-site request forgery as described in Section 10.12." }, { - "id": "oas-3.2.encoding-object.encoding-the-x-www-form-urlencoded-media-type.must-configuration-means-content-percent-encoded-per", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1778, - "section": "Objects and Fields > Encoding Object > Encoding the `x-www-form-urlencoded` Media Type", - "anchor": "encoding-the-x-www-form-urlencoded-media-type", + "id": "rfc6749.4.1.2.1.must-not-request-fails-due-missing-invalid-mismatching", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1489, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", "level": "MUST", - "terms": ["MUST"], - "text": "This configuration means that the content MUST be percent-encoded per [WHATWG-URL]'s rules for that media type, after any complex objects have been serialized to a string representation." + "terms": ["SHOULD", "MUST NOT"], + "text": "If the request fails due to a missing, invalid, or mismatching redirection URI, or if the client identifier is missing or invalid, the authorization server SHOULD inform the resource owner of the error and MUST NOT automatically redirect the user-agent to the invalid redirection URI." }, { - "id": "oas-3.2.encoding-object.explode", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1762, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", - "level": "field", - "terms": [], - "text": "When this is true, values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties, or when `style` is `\"deepObject\"`, this field has no effect. When `style` is `\"form\"`, the default value is `true`. For all other styles, the default value is `false`. This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "id": "rfc6749.4.1.2.1.must-not-values-error-description-parameter-include-characters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1551, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Values for the \"error_description\" parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." + }, + { + "id": "rfc6749.4.1.2.1.must-not-values-error-parameter-include-characters-outside", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1548, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Values for the \"error\" parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." + }, + { + "id": "rfc6749.4.1.2.1.must-values-error-uri-parameter-conform-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1558, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MUST", + "terms": ["MUST", "MUST NOT"], + "text": "Values for the \"error_uri\" parameter MUST conform to the URI-reference syntax and thus MUST NOT include characters outside the set %x21 / %x23-5B / %x5D-7E." + }, + { + "id": "rfc6749.4.1.2.1.optional-error-description", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1551, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "error_description OPTIONAL." + }, + { + "id": "rfc6749.4.1.2.1.optional-error-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1558, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "error_uri OPTIONAL." + }, + { + "id": "rfc6749.4.1.2.1.required-error", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1501, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "error REQUIRED." + }, + { + "id": "rfc6749.4.1.2.1.required-state-state-parameter-present-client-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1575, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response > Error Response", + "anchor": "section-4.1.2.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "state REQUIRED if a \"state\" parameter was present in the client authorization request." + }, + { + "id": "rfc6749.4.1.2.must-authorization-code-expire-shortly-after-issued", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1449, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization code MUST expire shortly after it is issued to mitigate the risk of leaks." }, { - "id": "oas-3.2.encoding-object.explode.shall-field-ignored-media-type-not-application", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1762, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", + "id": "rfc6749.4.1.2.must-authorization-code-used-more-once-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1449, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + "terms": ["MUST", "SHOULD"], + "text": "If an authorization code is used more than once, the authorization server MUST deny the request and SHOULD revoke (when possible) all tokens previously issued based on that authorization code." }, { - "id": "oas-3.2.encoding-object.explode.shall-value-explicitly-defined-value-contenttype-implicit", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1762, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-explode", + "id": "rfc6749.4.1.2.must-client-ignore-unrecognized-response-parameters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1481, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", "level": "MUST", - "terms": ["SHALL"], - "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "terms": ["MUST"], + "text": "The client MUST ignore unrecognized response parameters." }, { - "id": "oas-3.2.encoding-object.fixed-fields-for-rfc6570-style-serialization.must-not-using-rfc6570-style-serialization-multipart-form", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1765, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "fixed-fields-for-rfc6570-style-serialization", + "id": "rfc6749.4.1.2.must-not-client-use-authorization-code-more-once", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1449, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", "level": "MUST", "terms": ["MUST NOT"], - "text": "When using RFC6570-style serialization for `multipart/form-data`, URI percent-encoding MUST NOT be applied, and the value of `allowReserved` has no effect." + "text": "The client MUST NOT use the authorization code more than once." }, { - "id": "oas-3.2.encoding-object.handling-multiple-contenttype-values.must-encoding-serialization-implementations-provide-mechanism-applications", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1873, - "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > Handling Multiple `contentType` Values", - "anchor": "handling-multiple-contenttype-values", + "id": "rfc6749.4.1.2.recommended-maximum-authorization-code-lifetime-10-minutes", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1449, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "A maximum authorization code lifetime of 10 minutes is RECOMMENDED." + }, + { + "id": "rfc6749.4.1.2.required-code", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1449, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", "level": "MUST", - "terms": ["MUST"], - "text": "For encoding and serialization, implementations MUST provide a mechanism for applications to indicate which media type is intended." + "terms": ["REQUIRED"], + "text": "code REQUIRED." }, { - "id": "oas-3.2.encoding-object.handling-multiple-contenttype-values.must-not-implementations-choose-offer-media-type-sniffing", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1873, - "section": "Objects and Fields > Encoding Object > Encoding `multipart` Media Types > Handling Multiple `contentType` Values", - "anchor": "handling-multiple-contenttype-values", + "id": "rfc6749.4.1.2.required-state-state-parameter-present-client-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1469, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", "level": "MUST", - "terms": ["MAY", "MUST NOT"], - "text": "Implementations MAY choose to offer media type sniffing ([SNIFF]) as an alternative, but this MUST NOT be the default behavior due to the security risks inherent in the process." + "terms": ["REQUIRED"], + "text": "state REQUIRED if the \"state\" parameter was present in the client authorization request." }, { - "id": "oas-3.2.encoding-object.headers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1724, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", - "level": "field", - "terms": [], - "text": "A map allowing additional information to be provided as headers. `Content-Type` is described separately and SHALL be ignored in this section. This field SHALL be ignored if the media type is not a `multipart`." + "id": "rfc6749.4.1.2.should-authorization-server-document-size-any-value", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1481, + "section": "Obtaining Authorization > Authorization Code Grant > Authorization Response", + "anchor": "section-4.1.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The authorization server SHOULD document the size of any value it issues." }, { - "id": "oas-3.2.encoding-object.headers.shall-content-type-described-separately-ignored-section", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1724, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", + "id": "rfc6749.4.1.3.must-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1642, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", "level": "MUST", - "terms": ["SHALL"], - "text": "`Content-Type` is described separately and SHALL be ignored in this section." + "terms": ["MUST"], + "text": "The authorization server MUST:" }, { - "id": "oas-3.2.encoding-object.headers.shall-field-ignored-media-type-not-multipart", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1724, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-headers", + "id": "rfc6749.4.1.3.must-client-type-confidential-client-issued-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1609, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the media type is not a `multipart`." + "terms": ["MUST"], + "text": "If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in Section 3.2.1." }, { - "id": "oas-3.2.encoding-object.itemEncoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1727, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-item-encoding", - "level": "field", - "terms": [], - "text": "Applies nested Encoding Objects in the same manner as the Media Type Object's `itemEncoding` field." + "id": "rfc6749.4.1.3.must-value-set-authorization-code", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1593, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be set to \"authorization_code\"." }, { - "id": "oas-3.2.encoding-object.nested-encoding.must-implementations-support-one-level-nesting-support", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1773, - "section": "Objects and Fields > Encoding Object > Nested Encoding", - "anchor": "nested-encoding", + "id": "rfc6749.4.1.3.required-client-id-client-not-authenticating-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1605, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", "level": "MUST", - "terms": ["MUST", "MAY"], - "text": "Implementations MUST support one level of nesting, and MAY support additional levels." + "terms": ["REQUIRED"], + "text": "client_id REQUIRED, if the client is not authenticating with the authorization server as described in Section 3.2.1." }, { - "id": "oas-3.2.encoding-object.prefixEncoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1726, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Common Fixed Fields", - "anchor": "encoding-prefix-encoding", - "level": "field", - "terms": [], - "text": "Applies nested Encoding Objects in the same manner as the Media Type Object's `prefixEncoding` field." + "id": "rfc6749.4.1.3.required-code", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1596, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "code REQUIRED." }, { - "id": "oas-3.2.encoding-object.style", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1761, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", - "level": "field", - "terms": [], - "text": "Describes how a specific value will be serialized depending on its type. See Parameter Object for details on the `style` field. The behavior follows the same values as `query` parameters, including the default value of `\"form\"` which applies only when `contentType` is _not_ being used due to one or both of `explode` or `allowReserved` being explicitly specified. Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually). This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "id": "rfc6749.4.1.3.required-grant-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1593, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "grant_type REQUIRED." }, { - "id": "oas-3.2.encoding-object.style.must-note-initial-used-query-strings-not", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1761, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", + "id": "rfc6749.4.1.3.required-redirect-uri-redirect-uri-parameter-included", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1600, + "section": "Obtaining Authorization > Authorization Code Grant > Access Token Request", + "anchor": "section-4.1.3", + "level": "MUST", + "terms": ["REQUIRED", "MUST"], + "text": "redirect_uri REQUIRED, if the \"redirect_uri\" parameter was included in the authorization request as described in Section 4.1.1, and their values MUST be identical." + }, + { + "id": "rfc6749.4.2.1.must-authorization-server-verify-redirection-uri-will", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1881, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", "level": "MUST", "terms": ["MUST"], - "text": "Note that the initial `?` used in query strings is not used in `application/x-www-form-urlencoded` message bodies, and MUST be removed (if using an RFC6570 implementation) or simply not added (if constructing the string manually)." + "text": "The authorization server MUST verify that the redirection URI to which it will redirect the access token matches a redirection URI registered by the client as described in Section 3.1.2." }, { - "id": "oas-3.2.encoding-object.style.shall-field-ignored-media-type-not-application", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1761, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", + "id": "rfc6749.4.2.1.must-value-set-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1842, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`." + "terms": ["MUST"], + "text": "Value MUST be set to \"token\"." }, { - "id": "oas-3.2.encoding-object.style.shall-value-explicitly-defined-value-contenttype-implicit", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1761, - "section": "Objects and Fields > Encoding Object > Fixed Fields > Fixed Fields for RFC6570-style Serialization", - "anchor": "encoding-style", + "id": "rfc6749.4.2.1.optional-redirect-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1855, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "redirect_uri OPTIONAL." + }, + { + "id": "rfc6749.4.2.1.optional-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1858, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "scope OPTIONAL." + }, + { + "id": "rfc6749.4.2.1.recommended-state", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1862, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "state RECOMMENDED." + }, + { + "id": "rfc6749.4.2.1.required-client-id", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1845, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", "level": "MUST", - "terms": ["SHALL"], - "text": "If a value is explicitly defined, then the value of `contentType` (implicit or explicit) SHALL be ignored." + "terms": ["REQUIRED"], + "text": "client_id REQUIRED." }, { - "id": "oas-3.2.example-object.choosing-which-field-s-to-use.must-serializedvalue-externalvalue-fields-both-show-serialized", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2403, - "section": "Objects and Fields > Example Object > Working with Examples > Choosing Which Field(s) to Use", - "anchor": "choosing-which-field-s-to-use", + "id": "rfc6749.4.2.1.required-response-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1842, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", "level": "MUST", - "terms": ["MUST"], - "text": "The `serializedValue` and `externalValue` fields both MUST show the serialized form of the data." + "terms": ["REQUIRED"], + "text": "response_type REQUIRED." }, { - "id": "oas-3.2.example-object.criteria-for-serializedvalue.should-externalvalue-character-set-neither-explicitly-stated", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2417, - "section": "Objects and Fields > Example Object > Working with Examples > Criteria for `serializedValue`", - "anchor": "criteria-for-serializedvalue", + "id": "rfc6749.4.2.1.should-parameter-used-preventing-cross-site-request", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1862, + "section": "Obtaining Authorization > Implicit Grant > Authorization Request", + "anchor": "section-4.2.1", "level": "SHOULD", "terms": ["SHOULD"], - "text": "For `externalValue`, if the character set is neither explicitly stated nor determined by the format or media type specification, implementations SHOULD assume UTF-8." + "text": "The parameter SHOULD be used for preventing cross-site request forgery as described in Section 10.12." }, { - "id": "oas-3.2.example-object.dataValue", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2357, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-data-value", - "level": "field", - "terms": [], - "text": "An example of the data structure that MUST be valid according to the relevant Schema Object. If this field is present, `value` MUST be absent." + "id": "rfc6749.4.2.2.1.must-not-request-fails-due-missing-invalid-mismatching", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1974, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", + "level": "MUST", + "terms": ["SHOULD", "MUST NOT"], + "text": "If the request fails due to a missing, invalid, or mismatching redirection URI, or if the client identifier is missing or invalid, the authorization server SHOULD inform the resource owner of the error and MUST NOT automatically redirect the user-agent to the invalid redirection URI." }, { - "id": "oas-3.2.example-object.dataValue.must-example-data-structure-valid-according-relevant", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2357, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-data-value", + "id": "rfc6749.4.2.2.1.must-not-values-error-description-parameter-include-characters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2040, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", "level": "MUST", - "terms": ["MUST"], - "text": "An example of the data structure that MUST be valid according to the relevant Schema Object." + "terms": ["MUST NOT"], + "text": "Values for the \"error_description\" parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.2.example-object.dataValue.must-field-present-value-absent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2357, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-data-value", + "id": "rfc6749.4.2.2.1.must-not-values-error-parameter-include-characters-outside", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2037, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", "level": "MUST", - "terms": ["MUST"], - "text": "If this field is present, `value` MUST be absent." + "terms": ["MUST NOT"], + "text": "Values for the \"error\" parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.2.example-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2356, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-description", - "level": "field", - "terms": [], - "text": "Long description for the example. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.4.2.2.1.must-values-error-uri-parameter-conform-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2047, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", + "level": "MUST", + "terms": ["MUST", "MUST NOT"], + "text": "Values for the \"error_uri\" parameter MUST conform to the URI-reference syntax and thus MUST NOT include characters outside the set %x21 / %x23-5B / %x5D-7E." + }, + { + "id": "rfc6749.4.2.2.1.optional-error-description", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2040, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "error_description OPTIONAL." + }, + { + "id": "rfc6749.4.2.2.1.optional-error-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2047, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "error_uri OPTIONAL." }, { - "id": "oas-3.2.example-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2356, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.4.2.2.1.required-error", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1986, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "error REQUIRED." }, { - "id": "oas-3.2.example-object.externalValue", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2359, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-external-value", - "level": "field", - "terms": [], - "text": "A URI that identifies the serialized example in a separate document, allowing for values not easily or readably expressed as a Unicode string. If `dataValue` is present, then this field SHOULD identify a serialization of the given data. Otherwise, the value SHOULD identify the valid serialization of a data value that itself MUST be valid as described for `dataValue`. If this field is present, `serializedValue` and `value` MUST be absent. See also the rules for resolving Relative References." + "id": "rfc6749.4.2.2.1.required-state-state-parameter-present-client-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2055, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response > Error Response", + "anchor": "section-4.2.2.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "state REQUIRED if a \"state\" parameter was present in the client authorization request." }, { - "id": "oas-3.2.example-object.externalValue.must-field-present-serializedvalue-value-absent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2359, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-external-value", + "id": "rfc6749.4.2.2.must-client-ignore-unrecognized-response-parameters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1967, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", "level": "MUST", "terms": ["MUST"], - "text": "If this field is present, `serializedValue` and `value` MUST be absent." + "text": "The client MUST ignore unrecognized response parameters." }, { - "id": "oas-3.2.example-object.externalValue.must-otherwise-value-identify-valid-serialization-data", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2359, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-external-value", + "id": "rfc6749.4.2.2.must-not-authorization-server-issue-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1943, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", "level": "MUST", - "terms": ["SHOULD", "MUST"], - "text": "Otherwise, the value SHOULD identify the valid serialization of a data value that itself MUST be valid as described for `dataValue`." + "terms": ["MUST NOT"], + "text": "The authorization server MUST NOT issue a refresh token." }, { - "id": "oas-3.2.example-object.externalValue.should-datavalue-present-field-identify-serialization-given", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2359, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-external-value", + "id": "rfc6749.4.2.2.recommended-expires", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1926, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If `dataValue` is present, then this field SHOULD identify a serialization of the given data." + "terms": ["RECOMMENDED"], + "text": "expires_in RECOMMENDED." }, { - "id": "oas-3.2.example-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2362, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.4.2.2.required-access-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1919, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "access_token REQUIRED." }, { - "id": "oas-3.2.example-object.fixed-fields.may-tooling-implementations-choose-validate-compatibility-automatically", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2364, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", - "level": "MAY", - "terms": ["MAY"], - "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + "id": "rfc6749.4.2.2.required-scope-identical-scope-requested-client-otherwise", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1933, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["OPTIONAL", "REQUIRED"], + "text": "scope OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED." }, { - "id": "oas-3.2.example-object.fixed-fields.should-all-cases-example-value-compatible-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2364, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "fixed-fields-15", + "id": "rfc6749.4.2.2.required-state-state-parameter-present-client-authorization", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1938, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "state REQUIRED if the \"state\" parameter was present in the client authorization request." + }, + { + "id": "rfc6749.4.2.2.required-token-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1922, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "token_type REQUIRED." + }, + { + "id": "rfc6749.4.2.2.should-authorization-server-document-size-any-value", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1967, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "In all cases, the example value SHOULD be compatible with the schema of its associated value." + "text": "The authorization server SHOULD document the size of any value it issues." }, { - "id": "oas-3.2.example-object.json-compatible-and-value-safe-examples.should-practice-resulted-value-shorthand-example-fields", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2383, - "section": "Objects and Fields > Example Object > Working with Examples > JSON-Compatible and `value`-Safe Examples", - "anchor": "json-compatible-and-value-safe-examples", + "id": "rfc6749.4.2.2.should-omitted-authorization-server-provide-expiration-time", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 1926, + "section": "Obtaining Authorization > Implicit Grant > Access Token Response", + "anchor": "section-4.2.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "In practice, this has resulted in the `value` and shorthand `example` fields having implementation-defined behavior for non-JSON targets; OAD authors SHOULD use other fields to ensure interoperability." + "text": "If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value." }, { - "id": "oas-3.2.example-object.serializedValue", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2358, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-serialized-value", - "level": "field", - "terms": [], - "text": "An example of the serialized form of the value, including encoding and escaping as described under Validating Examples. If `dataValue` is present, then this field SHOULD contain the serialization of the given data. Otherwise, it SHOULD be the valid serialization of a data value that itself MUST be valid as described for `dataValue`. This field SHOULD NOT be used if the serialization format is JSON, as the data form is easier to work with. If this field is present, `value`, and `externalValue` MUST be absent." + "id": "rfc6749.4.3.1.must-client-discard-credentials-once-access-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2137, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Authorization Request and Response", + "anchor": "section-4.3.1", + "level": "MUST", + "terms": ["MUST"], + "text": "The client MUST discard the credentials once an access token has been obtained." }, { - "id": "oas-3.2.example-object.serializedValue.must-field-present-value-externalvalue-absent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2358, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-serialized-value", + "id": "rfc6749.4.3.2.must-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2191, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", "level": "MUST", "terms": ["MUST"], - "text": "If this field is present, `value`, and `externalValue` MUST be absent." + "text": "The authorization server MUST:" }, { - "id": "oas-3.2.example-object.serializedValue.must-otherwise-valid-serialization-data-value-itself", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2358, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-serialized-value", + "id": "rfc6749.4.3.2.must-client-type-confidential-client-issued-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2161, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", "level": "MUST", - "terms": ["SHOULD", "MUST"], - "text": "Otherwise, it SHOULD be the valid serialization of a data value that itself MUST be valid as described for `dataValue`." + "terms": ["MUST"], + "text": "If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in Section 3.2.1." }, { - "id": "oas-3.2.example-object.serializedValue.should-datavalue-present-field-contain-serialization-given", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2358, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-serialized-value", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If `dataValue` is present, then this field SHOULD contain the serialization of the given data." + "id": "rfc6749.4.3.2.must-since-access-token-request-utilizes-resource", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2202, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", + "level": "MUST", + "terms": ["MUST"], + "text": "Since this access token request utilizes the resource owner's password, the authorization server MUST protect the endpoint against brute force attacks (e.g., using rate-limitation or generating alerts)." }, { - "id": "oas-3.2.example-object.serializedValue.should-not-field-used-serialization-format-json-data", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2358, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-serialized-value", - "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "This field SHOULD NOT be used if the serialization format is JSON, as the data form is easier to work with." + "id": "rfc6749.4.3.2.must-value-set-password", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2148, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be set to \"password\"." }, { - "id": "oas-3.2.example-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2355, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-summary", - "level": "field", - "terms": [], - "text": "Short description for the example." + "id": "rfc6749.4.3.2.optional-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2157, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "scope OPTIONAL." }, { - "id": "oas-3.2.example-object.validating-examples.may-tooling-implementations-choose-validate-compatibility-automatically", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2421, - "section": "Objects and Fields > Example Object > Working with Examples > Validating Examples", - "anchor": "validating-examples", - "level": "MAY", - "terms": ["MAY"], - "text": "Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible." + "id": "rfc6749.4.3.2.required-grant-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2148, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "grant_type REQUIRED." }, { - "id": "oas-3.2.example-object.value", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2360, - "section": "Objects and Fields > Example Object > Fixed Fields", - "anchor": "example-value", - "level": "field", - "terms": [], - "text": "Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally be represented in JSON or YAML, use a string value to contain the example, escaping where necessary. Deprecated for non-JSON serialization targets: Use `dataValue` and/or `serializedValue`, which both have unambiguous syntax and semantics, instead." + "id": "rfc6749.4.3.2.required-password", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2154, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "password REQUIRED." }, { - "id": "oas-3.2.external-documentation-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 747, - "section": "Objects and Fields > External Documentation Object > Fixed Fields", - "anchor": "external-doc-description", - "level": "field", - "terms": [], - "text": "A description of the target documentation. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.4.3.2.required-username", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2151, + "section": "Obtaining Authorization > Resource Owner Password Credentials Grant > Access Token Request", + "anchor": "section-4.3.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "username REQUIRED." }, { - "id": "oas-3.2.external-documentation-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 747, - "section": "Objects and Fields > External Documentation Object > Fixed Fields", - "anchor": "external-doc-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.4.4.2.must-authorization-server-authenticate-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2314, + "section": "Obtaining Authorization > Client Credentials Grant > Access Token Request", + "anchor": "section-4.4.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The authorization server MUST authenticate the client." }, { - "id": "oas-3.2.external-documentation-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 750, - "section": "Objects and Fields > External Documentation Object > Fixed Fields", - "anchor": "fixed-fields-8", + "id": "rfc6749.4.4.2.must-client-authenticate-authorization-server-described-section", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2287, + "section": "Obtaining Authorization > Client Credentials Grant > Access Token Request", + "anchor": "section-4.4.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The client MUST authenticate with the authorization server as described in Section 3.2.1." + }, + { + "id": "rfc6749.4.4.2.must-value-set-client-credentials", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2280, + "section": "Obtaining Authorization > Client Credentials Grant > Access Token Request", + "anchor": "section-4.4.2", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be set to \"client_credentials\"." + }, + { + "id": "rfc6749.4.4.2.optional-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2283, + "section": "Obtaining Authorization > Client Credentials Grant > Access Token Request", + "anchor": "section-4.4.2", "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "terms": ["OPTIONAL"], + "text": "scope OPTIONAL." }, { - "id": "oas-3.2.external-documentation-object.url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 748, - "section": "Objects and Fields > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", - "level": "field", - "terms": [], - "text": "REQUIRED. The URI for the target documentation. This MUST be in the form of a URI." + "id": "rfc6749.4.4.2.required-grant-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2280, + "section": "Obtaining Authorization > Client Credentials Grant > Access Token Request", + "anchor": "section-4.4.2", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "grant_type REQUIRED." + }, + { + "id": "rfc6749.4.4.3.should-not-refresh-token-included", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2318, + "section": "Obtaining Authorization > Client Credentials Grant > Access Token Response", + "anchor": "section-4.4.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A refresh token SHOULD NOT be included." }, { - "id": "oas-3.2.external-documentation-object.url.must-form-uri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 748, - "section": "Objects and Fields > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", + "id": "rfc6749.4.4.must-client-credentials-grant-type-only-used", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2247, + "section": "Obtaining Authorization > Client Credentials Grant", + "anchor": "section-4.4", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "text": "The client credentials grant type MUST only be used by confidential clients." }, { - "id": "oas-3.2.external-documentation-object.url.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 748, - "section": "Objects and Fields > External Documentation Object > Fixed Fields", - "anchor": "external-doc-url", + "id": "rfc6749.5.1.must-authorization-server-include-http-cache-control", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2433, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "The authorization server MUST include the HTTP \"Cache-Control\" response header field [RFC2616] with a value of \"no-store\" in any response containing tokens, credentials, or other sensitive information, as well as the \"Pragma\" response header field [RFC2616] with a value of \"no-cache\"." }, { - "id": "oas-3.2.format.must-patterned-fields-have-unique-names-within", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 54, - "section": "Format", - "anchor": "format", + "id": "rfc6749.5.1.must-client-ignore-unrecognized-value-names-response", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2454, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", "level": "MUST", "terms": ["MUST"], - "text": "Patterned fields MUST have unique names within the containing object." - }, - { - "id": "oas-3.2.guidance-regarding-implicit-connections.recommended-resolving-component-tag-name-connections-referenced", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5531, - "section": "Appendix G: Parsing and Resolution Guidance > Guidance Regarding Implicit Connections", - "anchor": "guidance-regarding-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For resolving component and tag name connections from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + "text": "The client MUST ignore unrecognized value names in the response." }, { - "id": "oas-3.2.header-object.common-fixed-fields.may-fields-used-either-content-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2695, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-1", + "id": "rfc6749.5.1.optional-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2415, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", "level": "MAY", - "terms": ["MAY"], - "text": "These fields MAY be used with either `content` or `schema`." + "terms": ["OPTIONAL"], + "text": "refresh_token OPTIONAL." }, { - "id": "oas-3.2.header-object.common-fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2707, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields-1", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6749.5.1.recommended-expires", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2399, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "expires_in RECOMMENDED." }, { - "id": "oas-3.2.header-object.content", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2730, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "header-content", - "level": "field", - "terms": [], - "text": "A map containing the representations for the header. The key is the media type and the value describes it. The map MUST only contain one entry." + "id": "rfc6749.5.1.required-access-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2392, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "access_token REQUIRED." }, { - "id": "oas-3.2.header-object.content.must-map-only-contain-one-entry", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2730, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "header-content", + "id": "rfc6749.5.1.required-scope-identical-scope-requested-client-otherwise", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2420, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", "level": "MUST", - "terms": ["MUST"], - "text": "The map MUST only contain one entry." + "terms": ["OPTIONAL", "REQUIRED"], + "text": "scope OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED." }, { - "id": "oas-3.2.header-object.deprecated", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2703, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-deprecated", - "level": "field", - "terms": [], - "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + "id": "rfc6749.5.1.required-token-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2395, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "token_type REQUIRED." }, { - "id": "oas-3.2.header-object.deprecated.should-specifies-header-deprecated-transitioned-out-usage", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2703, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-deprecated", + "id": "rfc6749.5.1.should-authorization-server-document-size-any-value", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2454, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Specifies that the header is deprecated and SHOULD be transitioned out of usage." + "text": "The authorization server SHOULD document the size of any value it issues." }, { - "id": "oas-3.2.header-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2701, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-description", - "level": "field", - "terms": [], - "text": "A brief description of the header. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.5.1.should-omitted-authorization-server-provide-expiration-time", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2399, + "section": "Issuing an Access Token > Successful Response", + "anchor": "section-5.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value." }, { - "id": "oas-3.2.header-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2701, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-description", + "id": "rfc6749.5.2.may-authorization-server-return-http-401-unauthorized", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2488, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." - }, - { - "id": "oas-3.2.header-object.example", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2704, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-example", - "level": "field", - "terms": [], - "text": "Example of the header's potential value; see Working With Examples." - }, - { - "id": "oas-3.2.header-object.examples", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2705, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-examples", - "level": "field", - "terms": [], - "text": "Examples of the header's potential value; see Working With Examples." - }, - { - "id": "oas-3.2.header-object.explode", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2719, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-explode", - "level": "field", - "terms": [], - "text": "When this is true, header values of type `array` or `object` generate a single header whose value is a comma-separated list of the array items or key-value pairs of the map, see Style Examples. For other data types this field has no effect. The default value is `false`." + "text": "The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported." }, { - "id": "oas-3.2.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2713, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "id": "rfc6749.5.2.must-client-attempted-authenticate-via-authorization-request", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2488, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", "level": "MUST", "terms": ["MUST"], - "text": "Implementations MUST pass header values through unchanged rather than attempting to automatically quote header values, as the quoting rules vary too widely among different headers; see Appendix D for guidance on quoting and escaping." + "text": "If the client attempted to authenticate via the \"Authorization\" request header field, the authorization server MUST respond with an HTTP 401 (Unauthorized) status code and include the \"WWW-Authenticate\" response header field matching the authentication scheme used by the client." }, { - "id": "oas-3.2.header-object.fixed-fields-for-use-with-schema.must-not-serializing-headers-schema-uri-percent-encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2713, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema-0", + "id": "rfc6749.5.2.must-not-values-error-description-parameter-include-characters", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2534, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST NOT", "MUST"], - "text": "When serializing headers with `schema`, URI percent-encoding MUST NOT be applied; if using an RFC6570 implementation that automatically applies it, it MUST be removed before use." + "terms": ["MUST NOT"], + "text": "Values for the \"error_description\" parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.2.header-object.modeling-link-headers.must-application-linkset-media-type-object-used", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2737, - "section": "Objects and Fields > Header Object > Modeling Link Headers", - "anchor": "modeling-link-headers", + "id": "rfc6749.5.2.must-not-values-error-parameter-include-characters-outside", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2531, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST"], - "text": "If the `application/linkset` Media Type Object is used in the `content` field of a Header Object (or a Parameter Object with `in: \"header\"`), the serialization MUST be made compatible with the HTTP field syntax as described by [RFC9264] Section 4.1." + "terms": ["MUST NOT"], + "text": "Values for the \"error\" parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.2.header-object.modeling-link-headers.must-media-type-object-s-parent-key", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2737, - "section": "Objects and Fields > Header Object > Modeling Link Headers", - "anchor": "modeling-link-headers", + "id": "rfc6749.5.2.must-values-error-uri-parameter-conform-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2541, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST"], - "text": "If the Media Type Object's parent key is `application/linkset`, then the serialization MUST be the equivalent representation of the `schema`-modeled links in the `application/linkset` format." + "terms": ["MUST", "MUST NOT"], + "text": "Values for the \"error_uri\" parameter MUST conform to the URI-reference syntax and thus MUST NOT include characters outside the set %x21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.2.header-object.modeling-link-headers.must-use-either-media-types-schema-media", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2737, - "section": "Objects and Fields > Header Object > Modeling Link Headers", - "anchor": "modeling-link-headers", - "level": "MUST", - "terms": ["MUST"], - "text": "To use either of these media types, the `schema` in the Media Type Object MUST describe the links as they would be structured in the `application/linkset+json` format." + "id": "rfc6749.5.2.optional-error-description", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2534, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "error_description OPTIONAL." }, { - "id": "oas-3.2.header-object.must-all-traits-affected-location-applicable-location", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2689, - "section": "Objects and Fields > Header Object", - "anchor": "header-object", - "level": "MUST", - "terms": ["MUST"], - "text": "All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`)." + "id": "rfc6749.5.2.optional-error-uri", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2541, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "error_uri OPTIONAL." }, { - "id": "oas-3.2.header-object.must-not-means-allowemptyvalue-used-style-used-limited", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2689, - "section": "Objects and Fields > Header Object", - "anchor": "header-object", + "id": "rfc6749.5.2.required-error", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2477, + "section": "Issuing an Access Token > Error Response", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST NOT", "MUST"], - "text": "This means that `allowEmptyValue` MUST NOT be used, and `style`, if used, MUST be limited to `\"simple\"`." + "terms": ["REQUIRED"], + "text": "error REQUIRED." }, { - "id": "oas-3.2.header-object.must-not-name-specified-given-corresponding-headers-map", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2687, - "section": "Objects and Fields > Header Object", - "anchor": "header-object", + "id": "rfc6749.6.may-authorization-server-revoke-old-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2656, + "section": "Refreshing an Access Token", + "anchor": "section-6", + "level": "MAY", + "terms": ["MAY"], + "text": "The authorization server MAY revoke the old refresh token after issuing a new refresh token to the client." + }, + { + "id": "rfc6749.6.must-authorization-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2639, + "section": "Refreshing an Access Token", + "anchor": "section-6", "level": "MUST", - "terms": ["MUST NOT"], - "text": "`name` MUST NOT be specified, it is given in the corresponding `headers` map." + "terms": ["MUST"], + "text": "The authorization server MUST:" }, { - "id": "oas-3.2.header-object.must-not-specified-implicitly-header", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2688, - "section": "Objects and Fields > Header Object", - "anchor": "header-object", + "id": "rfc6749.6.must-authorization-server-issue-new-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2656, + "section": "Refreshing an Access Token", + "anchor": "section-6", "level": "MUST", - "terms": ["MUST NOT"], - "text": "`in` MUST NOT be specified, it is implicitly in `header`." + "terms": ["MAY", "MUST"], + "text": "The authorization server MAY issue a new refresh token, in which case the client MUST discard the old refresh token and replace it with the new refresh token." }, { - "id": "oas-3.2.header-object.representing-the-set-cookie-header.must-however-because-examples-values-modeled-content", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2815, - "section": "Objects and Fields > Header Object > Representing the `Set-Cookie` Header", - "anchor": "representing-the-set-cookie-header", + "id": "rfc6749.6.must-client-type-confidential-client-issued-client", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2604, + "section": "Refreshing an Access Token", + "anchor": "section-6", "level": "MUST", "terms": ["MUST"], - "text": "However, because examples and values modeled with `content` do not incorporate the header name, for these fields `Set-Cookie` MUST be handled by placing each value on a separate line, without the header name or the `:` delimiter." + "text": "If the client type is confidential or the client was issued client credentials (or assigned other authentication requirements), the client MUST authenticate with the authorization server as described in Section 3.2.1." }, { - "id": "oas-3.2.header-object.representing-the-set-cookie-header.must-note-any-uri-percent-encoding-base64", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2817, - "section": "Objects and Fields > Header Object > Representing the `Set-Cookie` Header", - "anchor": "representing-the-set-cookie-header", + "id": "rfc6749.6.must-new-refresh-token-issued-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2656, + "section": "Refreshing an Access Token", + "anchor": "section-6", "level": "MUST", "terms": ["MUST"], - "text": "Note also that any URI percent-encoding, base64 encoding, or other escaping MUST be performed prior to supplying the data to OAS tooling; see Appendix D for details." + "text": "If a new refresh token is issued, the refresh token scope MUST be identical to that of the refresh token included by the client in the request." }, { - "id": "oas-3.2.header-object.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2702, - "section": "Objects and Fields > Header Object > Fixed Fields > Common Fixed Fields", - "anchor": "header-required", - "level": "field", - "terms": [], - "text": "Determines whether this header is mandatory. The default value is `false`." + "id": "rfc6749.6.must-not-requested-scope-include-any-scope-not", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2597, + "section": "Refreshing an Access Token", + "anchor": "section-6", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The requested scope MUST NOT include any scope not originally granted by the resource owner, and if omitted is treated as equal to the scope originally granted by the resource owner." }, { - "id": "oas-3.2.header-object.schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2720, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-schema", - "level": "field", - "terms": [], - "text": "The schema defining the type used for the header." + "id": "rfc6749.6.must-value-set-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2591, + "section": "Refreshing an Access Token", + "anchor": "section-6", + "level": "MUST", + "terms": ["MUST"], + "text": "Value MUST be set to \"refresh_token\"." }, { - "id": "oas-3.2.header-object.style", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2718, - "section": "Objects and Fields > Header Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "header-style", - "level": "field", - "terms": [], - "text": "Describes how the header value will be serialized. The default (and only legal value for headers) is `\"simple\"`." + "id": "rfc6749.6.optional-scope", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2597, + "section": "Refreshing an Access Token", + "anchor": "section-6", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "scope OPTIONAL." }, { - "id": "oas-3.2.info-object.contact", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 196, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-contact", - "level": "field", - "terms": [], - "text": "The contact information for the exposed API." + "id": "rfc6749.6.required-grant-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2591, + "section": "Refreshing an Access Token", + "anchor": "section-6", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "grant_type REQUIRED." }, { - "id": "oas-3.2.info-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 194, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-description", - "level": "field", - "terms": [], - "text": "A description of the API. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.6.required-refresh-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2594, + "section": "Refreshing an Access Token", + "anchor": "section-6", + "level": "MUST", + "terms": ["REQUIRED"], + "text": "refresh_token REQUIRED." }, { - "id": "oas-3.2.info-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 194, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc6749.7.1.must-not-client-use-access-token-does-not", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2697, + "section": "Accessing Protected Resources > Access Token Types", + "anchor": "section-7.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The client MUST NOT use an access token if it does not understand the token type." }, { - "id": "oas-3.2.info-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 200, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "fixed-fields-0", + "id": "rfc6749.7.2.may-new-authentication-schemes-choose-specify-use", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2759, + "section": "Accessing Protected Resources > Error Response", + "anchor": "section-7.2", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "New authentication schemes MAY choose to also specify the use of the \"error_description\" and \"error_uri\" parameters to return error information in a manner parallel to their usage in this specification." }, { - "id": "oas-3.2.info-object.license", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 197, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-license", - "level": "field", - "terms": [], - "text": "The license information for the exposed API." + "id": "rfc6749.7.2.may-other-schemes-capable-being-used-oauth", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2755, + "section": "Accessing Protected Resources > Error Response", + "anchor": "section-7.2", + "level": "MAY", + "terms": ["MAY"], + "text": "Other schemes capable of being used for OAuth token authentication, but not primarily designed for that purpose, MAY bind their error values to the registry in the same manner." }, { - "id": "oas-3.2.info-object.may-metadata-used-clients-needed-presented-editing", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 185, - "section": "Objects and Fields > Info Object", - "anchor": "info-object", + "id": "rfc6749.7.2.may-schemes-limit-set-valid-error-codes", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2751, + "section": "Accessing Protected Resources > Error Response", + "anchor": "section-7.2", "level": "MAY", "terms": ["MAY"], - "text": "The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience." + "text": "Such schemes MAY limit the set of valid error codes to a subset of the registered values." }, { - "id": "oas-3.2.info-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 193, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-summary", - "level": "field", - "terms": [], - "text": "A short summary of the API." + "id": "rfc6749.7.2.should-error-code-returned-using-named-parameter", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2751, + "section": "Accessing Protected Resources > Error Response", + "anchor": "section-7.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the error code is returned using a named parameter, the parameter name SHOULD be \"error\"." }, { - "id": "oas-3.2.info-object.termsOfService", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 195, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-terms-of-service", - "level": "field", - "terms": [], - "text": "A URI for the Terms of Service for the API. This MUST be in the form of a URI." + "id": "rfc6749.7.2.should-new-authentication-schemes-designed-primarily-oauth", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2738, + "section": "Accessing Protected Resources > Error Response", + "anchor": "section-7.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "New authentication schemes designed primarily for OAuth token authentication SHOULD define a mechanism for providing an error status code to the client, in which the error values allowed are registered in the error registry established by this specification." }, { - "id": "oas-3.2.info-object.termsOfService.must-form-uri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 195, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-terms-of-service", + "id": "rfc6749.7.2.should-resource-access-request-fails-resource-server", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2732, + "section": "Accessing Protected Resources > Error Response", + "anchor": "section-7.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If a resource access request fails, the resource server SHOULD inform the client of the error." + }, + { + "id": "rfc6749.7.must-resource-server-validate-access-token-ensure", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2666, + "section": "Accessing Protected Resources", + "anchor": "section-7", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "text": "The resource server MUST validate the access token and ensure that it has not expired and that its scope covers the requested resource." }, { - "id": "oas-3.2.info-object.title", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 192, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-title", - "level": "field", - "terms": [], - "text": "REQUIRED. The title of the API." + "id": "rfc6749.8.1.must-all-other-types-registered", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2777, + "section": "Extensibility > Defining Access Token Types", + "anchor": "section-8.1", + "level": "MUST", + "terms": ["MUST"], + "text": "All other types MUST be registered." }, { - "id": "oas-3.2.info-object.title.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 192, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-title", + "id": "rfc6749.8.1.must-type-names-conform-type-name-abnf", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2777, + "section": "Extensibility > Defining Access Token Types", + "anchor": "section-8.1", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Type names MUST conform to the type-name ABNF." }, { - "id": "oas-3.2.info-object.version", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 198, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-version", - "level": "field", - "terms": [], - "text": "REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the version of the API being described or the version of the OpenAPI Description)." + "id": "rfc6749.8.1.should-type-definition-includes-new-http-authentication", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2777, + "section": "Extensibility > Defining Access Token Types", + "anchor": "section-8.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the type definition includes a new HTTP authentication scheme, the type name SHOULD be identical to the HTTP authentication scheme name (as defined by [RFC2617])." }, { - "id": "oas-3.2.info-object.version.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 198, - "section": "Objects and Fields > Info Object > Fixed Fields", - "anchor": "info-version", + "id": "rfc6749.8.1.should-types-utilizing-uri-name-limited-vendor", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2772, + "section": "Extensibility > Defining Access Token Types", + "anchor": "section-8.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Types utilizing a URI name SHOULD be limited to vendor-specific implementations that are not commonly applicable, and are specific to the implementation details of the resource server where they are used." + }, + { + "id": "rfc6749.8.2.must-parameter-names-conform-param-name-abnf", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2792, + "section": "Extensibility > Defining New Endpoint Parameters", + "anchor": "section-8.2", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Parameter names MUST conform to the param-name ABNF, and parameter values syntax MUST be well-defined (e.g., using ABNF, or a reference to the syntax of an existing parameter)." }, { - "id": "oas-3.2.json-and-yaml-compatibility.recommended-order-preserve-ability-round-trip-between", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 60, - "section": "Format > JSON and YAML Compatibility", - "anchor": "json-and-yaml-compatibility", + "id": "rfc6749.8.2.should-unregistered-vendor-specific-parameter-extensions-not", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2807, + "section": "Extensibility > Defining New Endpoint Parameters", + "anchor": "section-8.2", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "In order to preserve the ability to round-trip between YAML and JSON formats, YAML version 1.2 is RECOMMENDED along with the additional constraints listed in [RFC9512] Section 3.4." + "terms": ["SHOULD"], + "text": "Unregistered vendor-specific parameter extensions that are not commonly applicable and that are specific to the implementation details of the authorization server where they are used SHOULD utilize a vendor-specific prefix that is not likely to conflict with other registered values (e.g., begin with 'companyname_')." }, { - "id": "oas-3.2.json-and-yaml-compatibility.should-not-oad-authors-rely-any-json-incompatible", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 62, - "section": "Format > JSON and YAML Compatibility", - "anchor": "json-and-yaml-compatibility", - "level": "SHOULD", - "terms": ["SHOULD NOT"], - "text": "OAD authors SHOULD NOT rely on any such JSON-incompatible YAML values." + "id": "rfc6749.8.3.must-extension-grant-type-requires-additional-token", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2815, + "section": "Extensibility > Defining New Authorization Grant Types", + "anchor": "section-8.3", + "level": "MUST", + "terms": ["MUST"], + "text": "If the extension grant type requires additional token endpoint parameters, they MUST be registered in the OAuth Parameters registry as described by Section 11.2." + }, + { + "id": "rfc6749.8.4.must-response-type-names-conform-response-type", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2823, + "section": "Extensibility > Defining New Authorization Endpoint Response Types", + "anchor": "section-8.4", + "level": "MUST", + "terms": ["MUST"], + "text": "Response type names MUST conform to the response-type ABNF." }, { - "id": "oas-3.2.license-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 253, - "section": "Objects and Fields > License Object > Fixed Fields", - "anchor": "fixed-fields-2", + "id": "rfc6749.8.5.may-cases-protocol-extensions-i-e-access", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2845, + "section": "Extensibility > Defining Additional Error Codes", + "anchor": "section-8.5", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "In cases where protocol extensions (i.e., access token types, extension parameters, or extension grant types) require additional error codes to be used with the authorization code grant error response (Section 4.1.2.1), the implicit grant error response (Section 4.2.2.1), the token error response (Section 5.2), or the resource access error response (Section 7.2), such error codes MAY be defined." }, { - "id": "oas-3.2.license-object.identifier", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 250, - "section": "Objects and Fields > License Object > Fixed Fields", - "anchor": "license-identifier", - "level": "field", - "terms": [], - "text": "An SPDX license expression for the API. The `identifier` field is mutually exclusive of the `url` field." + "id": "rfc6749.8.5.may-error-codes-used-unregistered-extensions-registered", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2863, + "section": "Extensibility > Defining Additional Error Codes", + "anchor": "section-8.5", + "level": "MAY", + "terms": ["MAY"], + "text": "Error codes used with unregistered extensions MAY be registered." }, { - "id": "oas-3.2.license-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 249, - "section": "Objects and Fields > License Object > Fixed Fields", - "anchor": "license-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The license name used for the API." + "id": "rfc6749.8.5.must-error-codes-conform-error-abnf-prefixed", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2869, + "section": "Extensibility > Defining Additional Error Codes", + "anchor": "section-8.5", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "Error codes MUST conform to the error ABNF and SHOULD be prefixed by an identifying name when possible." }, { - "id": "oas-3.2.license-object.name.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 249, - "section": "Objects and Fields > License Object > Fixed Fields", - "anchor": "license-name", + "id": "rfc6749.8.5.must-extension-error-codes-registered-following-procedures", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2863, + "section": "Extensibility > Defining Additional Error Codes", + "anchor": "section-8.5", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Extension error codes MUST be registered (following the procedures in Section 11.4) if the extension they are used in conjunction with is a registered access token type, a registered endpoint parameter, or an extension grant type." }, { - "id": "oas-3.2.license-object.url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 251, - "section": "Objects and Fields > License Object > Fixed Fields", - "anchor": "license-url", - "level": "field", - "terms": [], - "text": "A URI for the license used for the API. This MUST be in the form of a URI. The `url` field is mutually exclusive of the `identifier` field." + "id": "rfc6749.8.5.should-example-error-identifying-invalid-value-set", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2869, + "section": "Extensibility > Defining Additional Error Codes", + "anchor": "section-8.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "For example, an error identifying an invalid value set to the extension parameter \"example\" SHOULD be named \"example_invalid\"." }, { - "id": "oas-3.2.license-object.url.must-form-uri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 251, - "section": "Objects and Fields > License Object > Fixed Fields", - "anchor": "license-url", + "id": "rfc6749.9.should-native-applications-use-authorization-code-grant", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 2936, + "section": "Native Applications", + "anchor": "section-9", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Native applications that use the authorization code grant type SHOULD do so without using client credentials, due to the native application's inability to keep client credentials confidential." + }, + { + "id": "rfc6749.B.must-address-shortcoming-generating-payloads-using-media", + "spec": "rfc", + "version": "6749", + "source": "rfc/rfc6749.txt", + "line": 4118, + "section": "Use of application/x-www-form-urlencoded Media Type", + "anchor": "appendix-B", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "text": "To address this shortcoming when generating payloads using this media type, names and values MUST be encoded using the UTF-8 character encoding scheme [RFC3629] first; the resulting octet sequence then needs to be further encoded using the escaping rules defined in [W3C.REC-html401-19991224]." }, { - "id": "oas-3.2.link-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2522, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-description", - "level": "field", - "terms": [], - "text": "A description of the link. CommonMark syntax MAY be used for rich text representation." + "id": "rfc6750.2.1.must-resource-servers-support-method", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 256, + "section": "Authenticated Requests > Authorization Request Header Field", + "anchor": "section-2.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Resource servers MUST support this method." }, { - "id": "oas-3.2.link-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2522, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-description", + "id": "rfc6750.2.1.should-clients-make-authenticated-requests-bearer-token", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 256, + "section": "Authenticated Requests > Authorization Request Header Field", + "anchor": "section-2.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Clients SHOULD make authenticated requests with a bearer token using the \"Authorization\" request header field with the \"Bearer\" HTTP authorization scheme." + }, + { + "id": "rfc6750.2.2.may-resource-servers-support-method", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 308, + "section": "Authenticated Requests > Form-Encoded Body Parameter", + "anchor": "section-2.2", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "Resource servers MAY support this method." }, { - "id": "oas-3.2.link-object.example-expressions.must-request-parameters-declared-parameters-section-parent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2672, - "section": "Objects and Fields > Link Object > Runtime Expressions > Example Expressions", - "anchor": "example-expressions", + "id": "rfc6750.2.2.must-content-encoded-entity-body-consist-entirely", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 287, + "section": "Authenticated Requests > Form-Encoded Body Parameter", + "anchor": "section-2.2", "level": "MUST", "terms": ["MUST"], - "text": "Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated." + "text": "The content to be encoded in the entity-body MUST consist entirely of ASCII [USASCII] characters." }, { - "id": "oas-3.2.link-object.fixed-fields.may-ambiguous-cases-resulting-behavior-implementation-defined", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2527, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MAY", - "terms": ["MAY"], - "text": "In such ambiguous cases, the resulting behavior is implementation-defined and MAY result in an error." + "id": "rfc6750.2.2.must-entity-body-include-other-request-specific", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 294, + "section": "Authenticated Requests > Form-Encoded Body Parameter", + "anchor": "section-2.2", + "level": "MUST", + "terms": ["MAY", "MUST"], + "text": "The entity-body MAY include other request-specific parameters, in which case the \"access_token\" parameter MUST be properly separated from the request-specific parameters using \"&\" character(s) (ASCII code 38)." }, { - "id": "oas-3.2.link-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2525, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", + "id": "rfc6750.2.2.must-not-client-use-method-unless-all-following", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 262, + "section": "Authenticated Requests > Form-Encoded Body Parameter", + "anchor": "section-2.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The client MUST NOT use this method unless all of the following conditions are met:" + }, + { + "id": "rfc6750.2.2.must-not-particular-means-get-method-used", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 290, + "section": "Authenticated Requests > Form-Encoded Body Parameter", + "anchor": "section-2.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "In particular, this means that the \"GET\" method MUST NOT be used." + }, + { + "id": "rfc6750.2.2.should-not-application-x-www-form-urlencoded-method", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 308, + "section": "Authenticated Requests > Form-Encoded Body Parameter", + "anchor": "section-2.2", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The \"application/x-www-form-urlencoded\" method SHOULD NOT be used except in application contexts where participating browsers do not have access to the \"Authorization\" request header field." + }, + { + "id": "rfc6750.2.3.may-resource-servers-support-method", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 352, + "section": "Authenticated Requests > URI Query Parameter", + "anchor": "section-2.3", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Resource servers MAY support this method." }, { - "id": "oas-3.2.link-object.fixed-fields.must-identified-referenced-operation-unique-case-operationid", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2527, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", + "id": "rfc6750.2.3.must-http-request-uri-query-include-other", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 326, + "section": "Authenticated Requests > URI Query Parameter", + "anchor": "section-2.3", "level": "MUST", "terms": ["MUST"], - "text": "The identified or referenced operation MUST be unique, and in the case of an `operationId`, it MUST be resolved within the scope of the OpenAPI Description (OAD)." + "text": "The HTTP request URI query can include other request-specific parameters, in which case the \"access_token\" parameter MUST be properly separated from the request-specific parameters using \"&\" character(s) (ASCII code 38)." }, { - "id": "oas-3.2.link-object.fixed-fields.must-linked-operation-identified-using-either-operationref", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2527, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", - "level": "MUST", - "terms": ["MUST"], - "text": "A linked operation MUST be identified using either an `operationRef` or `operationId`." + "id": "rfc6750.2.3.should-clients-using-uri-query-parameter-method", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 347, + "section": "Authenticated Requests > URI Query Parameter", + "anchor": "section-2.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Clients using the URI Query Parameter method SHOULD also send a Cache-Control header containing the \"no-store\" option." }, { - "id": "oas-3.2.link-object.fixed-fields.not-recommended-possible-have-ambiguous-parameter-names-e", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2533, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "fixed-fields-16", + "id": "rfc6750.2.3.should-not-because-security-weaknesses-associated-uri-method", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 352, + "section": "Authenticated Requests > URI Query Parameter", + "anchor": "section-2.3", "level": "SHOULD", - "terms": ["NOT RECOMMENDED", "SHOULD"], - "text": "It is possible to have ambiguous parameter names, e.g. `name: \"id\", in: \"path\"` and `name: \"path.id\", in: \"query\"`; this is NOT RECOMMENDED and the behavior is implementation-defined, however implementations SHOULD prefer the qualified interpretation (`path.id` as a path parameter), as the names can always be qualified to disambiguate them (e.g. using `query.path.id` for the query parameter)." + "terms": ["SHOULD NOT"], + "text": "Because of the security weaknesses associated with the URI method (see Section 5), including the high likelihood that the URL containing the access token will be logged, it SHOULD NOT be used unless it is impossible to transport the access token in the \"Authorization\" request header field or the HTTP request entity-body." }, { - "id": "oas-3.2.link-object.operationId", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2519, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-operation-id", - "level": "field", - "terms": [], - "text": "The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field." + "id": "rfc6750.2.3.should-server-success-2xx-status-responses-requests", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 347, + "section": "Authenticated Requests > URI Query Parameter", + "anchor": "section-2.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Server success (2XX status) responses to these requests SHOULD contain a Cache-Control header with the \"private\" option." }, { - "id": "oas-3.2.link-object.operationRef", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2518, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-operation-ref", - "level": "field", - "terms": [], - "text": "A URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object. Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + "id": "rfc6750.2.must-not-clients-use-more-one-method-transmit", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 218, + "section": "Authenticated Requests", + "anchor": "section-2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Clients MUST NOT use more than one method to transmit the token in each request." }, { - "id": "oas-3.2.link-object.operationRef.may-relative-operationref-values-used-locate-existing", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2518, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-operation-ref", + "id": "rfc6750.3.1.may-client-request-new-access-token-retry", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 476, + "section": "The WWW-Authenticate Response Header Field > Error Codes", + "anchor": "section-3.1", "level": "MAY", "terms": ["MAY"], - "text": "Relative `operationRef` values MAY be used to locate an existing Operation Object in the OpenAPI Description." + "text": "The client MAY request a new access token and retry the protected resource request." }, { - "id": "oas-3.2.link-object.operationRef.must-field-mutually-exclusive-operationid-field-point", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2518, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-operation-ref", - "level": "MUST", - "terms": ["MUST"], - "text": "This field is mutually exclusive of the `operationId` field, and MUST point to an Operation Object." + "id": "rfc6750.3.1.should-not-request-lacks-any-authentication-information-e", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 490, + "section": "The WWW-Authenticate Response Header Field > Error Codes", + "anchor": "section-3.1", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "If the request lacks any authentication information (e.g., the client was unaware that authentication is necessary or attempted using an unsupported authentication method), the resource server SHOULD NOT include an error code or other error information." }, { - "id": "oas-3.2.link-object.operationref-examples.may-operationid-optional-field-operation-object-references", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2605, - "section": "Objects and Fields > Link Object > Examples > `operationRef` Examples", - "anchor": "operationref-examples", - "level": "MAY", - "terms": ["MAY"], - "text": "As the `operationId` is an optional field in an Operation Object, references MAY instead be made through a URI reference with `operationRef`." + "id": "rfc6750.3.1.should-resource-respond-http-401-unauthorized-status", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 476, + "section": "The WWW-Authenticate Response Header Field > Error Codes", + "anchor": "section-3.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The resource SHOULD respond with the HTTP 401 (Unauthorized) status code." }, { - "id": "oas-3.2.link-object.parameters", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2520, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-parameters", - "level": "field", - "terms": [], - "text": "A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used (optionally qualified with the parameter location, e.g. `path.id` for an `id` parameter in the path), whereas the value can be a constant or an expression to be evaluated and passed to the linked operation." + "id": "rfc6750.3.1.should-resource-server-respond-http-400-bad", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 469, + "section": "The WWW-Authenticate Response Header Field > Error Codes", + "anchor": "section-3.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The resource server SHOULD respond with the HTTP 400 (Bad Request) status code." }, { - "id": "oas-3.2.link-object.requestBody", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2521, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-request-body", - "level": "field", - "terms": [], - "text": "A literal value or {expression} to use as a request body when calling the target operation." + "id": "rfc6750.3.1.should-resource-server-respond-http-403-forbidden", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 483, + "section": "The WWW-Authenticate Response Header Field > Error Codes", + "anchor": "section-3.1", + "level": "SHOULD", + "terms": ["SHOULD", "MAY"], + "text": "The resource server SHOULD respond with the HTTP 403 (Forbidden) status code and MAY include the \"scope\" attribute with the scope necessary to access the protected resource." }, { - "id": "oas-3.2.link-object.server", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2523, - "section": "Objects and Fields > Link Object > Fixed Fields", - "anchor": "link-server", - "level": "field", - "terms": [], - "text": "A server object to be used by the target operation." + "id": "rfc6750.3.may-addition-resource-server-include-error-description", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 413, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MAY", + "terms": ["MAY"], + "text": "In addition, the resource server MAY include the \"error_description\" attribute to provide developers a human-readable explanation that is not meant to be displayed to end-users." }, { - "id": "oas-3.2.media-type-object.additional-encoding-approaches.may-implementations-choose-support-workaround-but-usage", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1411, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Additional Encoding Approaches", - "anchor": "additional-encoding-approaches", + "id": "rfc6750.3.may-include-error-uri-attribute-absolute-uri", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 413, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY choose to support this workaround, but as this usage is not common, implementations of non-`form-data` `multipart` media types are unlikely to support it." + "text": "It also MAY include the \"error_uri\" attribute with an absolute URI identifying a human-readable web page explaining the error." }, { - "id": "oas-3.2.media-type-object.binary-streams.may-maxlength-keyword-used-set-expected-upper", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1336, - "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Binary Streams", - "anchor": "binary-streams", + "id": "rfc6750.3.may-other-auth-param-attributes-used-well", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 374, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MAY", "terms": ["MAY"], - "text": "The `maxLength` keyword MAY be used to set an expected upper bound on the length of a streaming payload that consists of either string data, including encoded binary data, or unencoded binary data." + "text": "Other auth-param attributes MAY be used as well." }, { - "id": "oas-3.2.media-type-object.binary-streams.may-use-case-maxlength-implemented-outside-regular", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1336, - "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Binary Streams", - "anchor": "binary-streams", + "id": "rfc6750.3.may-realm-attribute-included-indicate-scope-protection", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 380, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MAY", "terms": ["MAY"], - "text": "For this use case, `maxLength` MAY be implemented outside of regular JSON Schema evaluation as JSON Schema does not directly apply to binary data, and an encoded binary stream may be impractical to store in memory in its entirety." + "text": "A \"realm\" attribute MAY be included to indicate the scope of protection in the manner described in HTTP/1.1 [RFC2617]." }, { - "id": "oas-3.2.media-type-object.complete-vs-streaming-content.must-schema-field-applied-complete-content-defined", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1296, - "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content", - "anchor": "complete-vs-streaming-content", + "id": "rfc6750.3.must-all-challenges-defined-specification-use-auth", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 374, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MUST", "terms": ["MUST"], - "text": "The `schema` field MUST be applied to the complete content, as defined by the media type and the context (Request Body Object, Response Object, Parameter Object, or Header Object." + "text": "All challenges defined by this specification MUST use the auth-scheme value \"Bearer\"." }, { - "id": "oas-3.2.media-type-object.considerations-for-file-uploads.may-addition-specific-media-types-specified", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1694, - "section": "Objects and Fields > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", - "level": "MAY", - "terms": ["MAY"], - "text": "In addition, specific media types MAY be specified:" + "id": "rfc6750.3.must-not-error-error-description-error-uri-attributes", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 413, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The \"error\", \"error_description\", and \"error_uri\" attributes MUST NOT appear more than once." }, { - "id": "oas-3.2.media-type-object.considerations-for-file-uploads.may-content-transferred-binary-octet-stream-omit", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1664, - "section": "Objects and Fields > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", - "level": "MAY", - "terms": ["MAY"], - "text": "Content transferred in binary (octet-stream) MAY omit `schema`:" + "id": "rfc6750.3.must-not-realm-attribute-appear-more-once", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 380, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The \"realm\" attribute MUST NOT appear more than once." }, { - "id": "oas-3.2.media-type-object.considerations-for-file-uploads.must-upload-multiple-files-multipart-media-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1705, - "section": "Objects and Fields > Media Type Object > Considerations for File Uploads", - "anchor": "considerations-for-file-uploads", + "id": "rfc6750.3.must-not-scope-attribute-appear-more-once", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 384, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MUST", - "terms": ["MUST"], - "text": "To upload multiple files, a `multipart` media type MUST be used as shown under Example: Multipart Form with Multiple Files." + "terms": ["MUST NOT"], + "text": "The \"scope\" attribute MUST NOT appear more than once." }, { - "id": "oas-3.2.media-type-object.encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1274, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", - "level": "field", - "terms": [], - "text": "A map between a property name and its encoding information, as defined under Encoding By Name. The `encoding` field SHALL only apply when the media type is `multipart` or `application/x-www-form-urlencoded`. If no Encoding Object is provided for a property, the behavior is determined by the default values documented for the Encoding Object. This field MUST NOT be present if `prefixEncoding` or `itemEncoding` are present." + "id": "rfc6750.3.must-not-values-error-error-description-attributes-specified", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 425, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Values for the \"error\" and \"error_description\" attributes (specified in Appendixes A.7 and A.8 of [RFC6749]) MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E." }, { - "id": "oas-3.2.media-type-object.encoding-by-name.must-all-other-value-types-both-top", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1377, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", - "anchor": "encoding-by-name", + "id": "rfc6750.3.must-not-values-scope-attribute-specified-appendix-4", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 425, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MUST", - "terms": ["MUST"], - "text": "For all other value types for both top-level non-array property values and for other values, including items of the array type within a top-level array, the Encoding Object MUST be applied to the entire value." + "terms": ["MUST NOT"], + "text": "Values for the \"scope\" attribute (specified in Appendix A.4 of [RFC6749]) MUST NOT include characters outside the set %x21 / %x23-5B / %x5D-7E for representing scope values and %x20 for delimiters between scope values." }, { - "id": "oas-3.2.media-type-object.encoding-by-name.must-application-x-www-form-urlencoded-encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1384, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", - "anchor": "encoding-by-name", + "id": "rfc6750.3.must-protected-resource-request-does-not-include", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 367, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP \"WWW-Authenticate\" response header field; it MAY include it in response to other conditions as well." + }, + { + "id": "rfc6750.3.must-scheme-followed-one-more-auth-param", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 374, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", "level": "MUST", "terms": ["MUST"], - "text": "For `application/x-www-form-urlencoded`, the `encoding` keys MUST map to parameter names, with the serialized values produced according to the rules of the Encoding Object." + "text": "This scheme MUST be followed by one or more auth-param values." }, { - "id": "oas-3.2.media-type-object.encoding-by-name.must-deserialization-object-multiple-values-same-name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1377, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", - "anchor": "encoding-by-name", + "id": "rfc6750.3.must-values-error-uri-attribute-specified-appendix", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 425, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MUST", + "terms": ["MUST", "MUST NOT"], + "text": "Values for the \"error_uri\" attribute (specified in Appendix A.9 of [RFC6749]) MUST conform to the URI-reference syntax and thus MUST NOT include characters outside the set %x21 / %x23-5B / %x5D-7E." + }, + { + "id": "rfc6750.3.optional-use-scope-attribute", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 384, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Use of the \"scope\" attribute is OPTIONAL." + }, + { + "id": "rfc6750.3.should-protected-resource-request-included-access-token", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 413, + "section": "The WWW-Authenticate Response Header Field", + "anchor": "section-3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the protected resource request included an access token and failed authentication, the resource server SHOULD include the \"error\" attribute to provide the client with the reason why the access request was declined." + }, + { + "id": "rfc6750.5.2.must-authorization-server-implement-tls", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 598, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", "terms": ["MUST"], - "text": "For deserialization to an object, multiple values with the same `name` MUST be collapsed into an array value for that named property, with one item per value, in order." + "text": "The authorization server MUST implement TLS." }, { - "id": "oas-3.2.media-type-object.encoding-by-name.must-multipart-types-decode-object-multipart-form", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1387, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", - "anchor": "encoding-by-name", + "id": "rfc6750.5.2.must-cases-client-prevented-observing-contents-token", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 607, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", "terms": ["MUST"], - "text": "For `multipart` types that decode to an object, such as `multipart/form-data`, the `encoding` keys MUST map to the `name` parameter of the `Content-Disposition: form-data` header of each part, as is defined for `multipart/form-data` in [RFC7578]." + "text": "For those cases where the client is prevented from observing the contents of the token, token encryption MUST be applied in addition to the usage of TLS protection." }, { - "id": "oas-3.2.media-type-object.encoding-by-name.must-serializing-property-values-array-type-handled", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1377, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", - "anchor": "encoding-by-name", + "id": "rfc6750.5.2.must-deal-token-capture-replay-following-recommendations", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 646, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", "terms": ["MUST"], - "text": "When serializing, property values of the array type MUST be handled by applying the given Encoding Object to produce one encoded value per array item, each with the same `name`, as is recommended by [RFC7578] Section 4.3 for supplying multiple values per form field; when deserializing, the Encoding Object is applied to each item of the array property of the same name." + "text": "To deal with token capture and replay, the following recommendations are made: First, the lifetime of the token MUST be limited; one means of achieving this is by putting a validity time field inside the protected part of the token." }, { - "id": "oas-3.2.media-type-object.encoding-by-name.must-use-encoding-field-each-key-under", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1377, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Name", - "anchor": "encoding-by-name", + "id": "rfc6750.5.2.must-deployments-sufficient-measures-employed-ensure-confidentiality", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 637, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST", "SHALL"], - "text": "To use the `encoding` field, each key under the field MUST exist in the data instance as a property; `encoding` entries with no corresponding property SHALL be ignored." + "terms": ["MUST"], + "text": "In such deployments, sufficient measures MUST be employed to ensure confidentiality of the token between the front-end and back-end servers; encryption of the token is one such possible measure." }, { - "id": "oas-3.2.media-type-object.encoding-by-position.must-use-prefixencoding-itemencoding-fields-each-item", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1399, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Position", - "anchor": "encoding-by-position", + "id": "rfc6750.5.2.must-further-defense-against-token-disclosure-client", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 607, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST", "SHALL"], - "text": "To use the `prefixEncoding` and/or `itemEncoding` fields, each item referenced by the field MUST exist in the data instance; `prefixEncoding` and `itemEncoding` entries with no corresponding item SHALL be ignored." + "terms": ["MUST"], + "text": "As a further defense against token disclosure, the client MUST validate the TLS certificate chain when making requests to protected resources, including checking the Certificate Revocation List (CRL) [RFC5280]." }, { - "id": "oas-3.2.media-type-object.encoding-by-position.shall-applications-wish-preserve-part-order-multipart", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1397, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Position", - "anchor": "encoding-by-position", + "id": "rfc6750.5.2.must-furthermore-presenting-token-resource-server-client", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 646, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["SHALL"], - "text": "For applications that wish to preserve part order, `multipart/form-data` content may also be modelled as an array, with one item per part, in order (where each item consists of an object containing the name/value pair); the `schema` SHALL be used to determine whether deserializing to an `object` or an `array` is preferred." + "terms": ["MUST"], + "text": "Furthermore, when presenting the token to a resource server, the client MUST verify the identity of that resource server, as per Section 3.1 of \"HTTP Over TLS\" [RFC2818]." }, { - "id": "oas-3.2.media-type-object.encoding-by-position.shall-prefixitems-not-error-instance-array-shorter", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1401, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions > Encoding By Position", - "anchor": "encoding-by-position", + "id": "rfc6750.5.2.must-not-therefore-bearer-tokens-stored-cookies-sent", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 631, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["SHALL"], - "text": "As with `prefixItems`, it is _not_ an error if the instance array is shorter than the `prefixEncoding` array; the additional Encoding Objects SHALL be ignored." + "terms": ["MUST NOT"], + "text": "Therefore, bearer tokens MUST NOT be stored in cookies that can be sent in the clear." }, { - "id": "oas-3.2.media-type-object.encoding-usage-and-restrictions.shall-each-field-own-set-media-types", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1370, - "section": "Objects and Fields > Media Type Object > Encoding Usage and Restrictions", - "anchor": "encoding-usage-and-restrictions", + "id": "rfc6750.5.2.must-note-client-validate-tls-certificate-chain", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 646, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["SHALL"], - "text": "Each field has its own set of media types with which it can be used; for all other media types all three fields SHALL be ignored." + "terms": ["MUST"], + "text": "Note that the client MUST validate the TLS certificate chain when making these requests to protected resources." }, { - "id": "oas-3.2.media-type-object.encoding.must-not-field-present-prefixencoding-itemencoding-present", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1274, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", + "id": "rfc6750.5.2.must-protect-against-token-disclosure-confidentiality-protection", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 607, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST NOT"], - "text": "This field MUST NOT be present if `prefixEncoding` or `itemEncoding` are present." + "terms": ["MUST"], + "text": "To protect against token disclosure, confidentiality protection MUST be applied using TLS [RFC5246] with a ciphersuite that provides confidentiality and integrity protection." }, { - "id": "oas-3.2.media-type-object.encoding.shall-encoding-field-only-apply-media-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1274, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-encoding", + "id": "rfc6750.5.2.must-references-infeasible-attacker-guess-using-reference", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 576, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", "level": "MUST", - "terms": ["SHALL"], - "text": "The `encoding` field SHALL only apply when the media type is `multipart` or `application/x-www-form-urlencoded`." + "terms": ["MUST"], + "text": "Such references MUST be infeasible for an attacker to guess; using a reference may require an extra interaction between a server and the token issuer to resolve the reference to the authorization information." }, { - "id": "oas-3.2.media-type-object.example", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1272, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-example", - "level": "field", - "terms": [], - "text": "Example of the media type; see Working With Examples." + "id": "rfc6750.5.2.must-second-confidentiality-protection-exchanges-between-client", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 646, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", + "level": "MUST", + "terms": ["MUST"], + "text": "Second, confidentiality protection of the exchanges between the client and the authorization server and between the client and the resource server MUST be applied." + }, + { + "id": "rfc6750.5.2.must-token-integrity-protection-sufficient-prevent-token", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 586, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The token integrity protection MUST be sufficient to prevent the token from being modified." }, { - "id": "oas-3.2.media-type-object.examples", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1273, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-examples", - "level": "field", - "terms": [], - "text": "Examples of the media type; see Working With Examples." + "id": "rfc6750.5.2.recommended-restricting-use-token-specific-scope", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 592, + "section": "Security Considerations > Threat Mitigation", + "anchor": "section-5.2", + "level": "SHOULD", + "terms": ["RECOMMENDED"], + "text": "Restricting the use of the token to a specific scope is also RECOMMENDED." }, { - "id": "oas-3.2.media-type-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1278, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "fixed-fields-11", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc6750.5.3.must-always-use-tls-https-clients-always", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 692, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "MUST", + "terms": ["MUST"], + "text": "Always use TLS (https): Clients MUST always use TLS [RFC5246] (https) or equivalent transport security when making requests with bearer tokens." }, { - "id": "oas-3.2.media-type-object.itemEncoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1276, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-item-encoding", - "level": "field", - "terms": [], - "text": "A single Encoding Object that provides encoding information for multiple array items, as defined under Encoding By Position. The `itemEncoding` field SHALL only apply when the media type is `multipart`. If no Encoding Object is provided for an item, the behavior is determined by the default values documented for the Encoding Object. This field MUST NOT be present if `encoding` is present." + "id": "rfc6750.5.3.must-implementations-do-store-bearer-tokens-cookies", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 697, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "MUST", + "terms": ["MUST"], + "text": "Implementations that do store bearer tokens in cookies MUST take precautions against cross-site request forgery." }, { - "id": "oas-3.2.media-type-object.itemEncoding.must-not-field-present-encoding-present", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1276, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-item-encoding", + "id": "rfc6750.5.3.must-not-don-t-store-bearer-tokens-cookies", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 697, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", "level": "MUST", "terms": ["MUST NOT"], - "text": "This field MUST NOT be present if `encoding` is present." + "text": "Don't store bearer tokens in cookies: Implementations MUST NOT store bearer tokens within cookies that can be sent in the clear (which is the default transmission mode for cookies)." }, { - "id": "oas-3.2.media-type-object.itemEncoding.shall-itemencoding-field-only-apply-media-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1276, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-item-encoding", + "id": "rfc6750.5.3.must-safeguard-bearer-tokens-client-implementations-ensure", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 681, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", "level": "MUST", - "terms": ["SHALL"], - "text": "The `itemEncoding` field SHALL only apply when the media type is `multipart`." + "terms": ["MUST"], + "text": "Safeguard bearer tokens: Client implementations MUST ensure that bearer tokens are not leaked to unintended parties, as they will be able to use them to gain access to protected resources." }, { - "id": "oas-3.2.media-type-object.itemSchema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1271, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-item-schema", - "level": "field", - "terms": [], - "text": "A schema describing each item within a sequential media type." + "id": "rfc6750.5.3.must-validate-tls-certificate-chains-client-validate", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 687, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "MUST", + "terms": ["MUST"], + "text": "Validate TLS certificate chains: The client MUST validate the TLS certificate chain when making requests to protected resources." }, { - "id": "oas-3.2.media-type-object.openapi-media-type-registry.may-any-additional-media-types-added-registry", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1290, - "section": "Objects and Fields > Media Type Object > Media Types > OpenAPI Media Type Registry", - "anchor": "openapi-media-type-registry", - "level": "MAY", - "terms": ["MAY"], - "text": "Any additional media types added to this registry as extensions or for later versions of this or other OpenAPI specifications MAY be supported by implementations of this version of the OAS." + "id": "rfc6750.5.3.should-instead-bearer-tokens-passed-http-message", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 714, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Instead, bearer tokens SHOULD be passed in HTTP message headers or message bodies for which confidentiality measures are taken." }, { - "id": "oas-3.2.media-type-object.prefixEncoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1275, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-prefix-encoding", - "level": "field", - "terms": [], - "text": "An array of positional encoding information, as defined under Encoding By Position. The `prefixEncoding` field SHALL only apply when the media type is `multipart`. If no Encoding Object is provided for an item, the behavior is determined by the default values documented for the Encoding Object. This field MUST NOT be present if `encoding` is present." + "id": "rfc6750.5.3.should-issue-scoped-bearer-tokens-token-servers", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 710, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Issue scoped bearer tokens: Token servers SHOULD issue bearer tokens that contain an audience restriction, scoping their use to the intended relying party or set of relying parties." }, { - "id": "oas-3.2.media-type-object.prefixEncoding.must-not-field-present-encoding-present", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1275, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-prefix-encoding", + "id": "rfc6750.5.3.should-issue-short-lived-bearer-tokens-token", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 703, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Issue short-lived bearer tokens: Token servers SHOULD issue short-lived (one hour or less) bearer tokens, particularly when issuing tokens to clients that run within a web browser or other environments where information leakage may occur." + }, + { + "id": "rfc6750.5.3.should-not-don-t-pass-bearer-tokens-page", + "spec": "rfc", + "version": "6750", + "source": "rfc/rfc6750.txt", + "line": 714, + "section": "Security Considerations > Summary of Recommendations", + "anchor": "section-5.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Don't pass bearer tokens in page URLs: Bearer tokens SHOULD NOT be passed in page URLs (for example, as query string parameters)." + }, + { + "id": "rfc7578.4.1.must-not-noted-section-5-1-rfc2046-boundary", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 186, + "section": "Definition of multipart/form-data > \"Boundary\" Parameter of multipart/form-data", + "anchor": "section-4.1", "level": "MUST", "terms": ["MUST NOT"], - "text": "This field MUST NOT be present if `encoding` is present." + "text": "As noted in Section 5.1 of [RFC2046], the boundary delimiter MUST NOT appear inside any of the encapsulated parts, and it is often necessary to enclose the \"boundary\" parameter values in quotes in the Content-Type header field." }, { - "id": "oas-3.2.media-type-object.prefixEncoding.shall-prefixencoding-field-only-apply-media-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1275, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-prefix-encoding", - "level": "MUST", - "terms": ["SHALL"], - "text": "The `prefixEncoding` field SHALL only apply when the media type is `multipart`." + "id": "rfc7578.4.2.may-most-multipart-types-mime-header-fields", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 231, + "section": "Definition of multipart/form-data > Content-Disposition Header Field for Each Part", + "anchor": "section-4.2", + "level": "MAY", + "terms": ["MAY"], + "text": "In most multipart types, the MIME header fields in each part are restricted to US-ASCII; for compatibility with those systems, file names normally visible to users MAY be encoded using the percent-encoding method in Section 2, following how a \"file:\" URI [URI-SCHEME] might be encoded." }, { - "id": "oas-3.2.media-type-object.schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1270, - "section": "Objects and Fields > Media Type Object > Fixed Fields", - "anchor": "media-type-schema", - "level": "field", - "terms": [], - "text": "A schema describing the complete content of the request, response, parameter, or header." + "id": "rfc7578.4.2.must-content-disposition-header-field-contain-additional", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 197, + "section": "Definition of multipart/form-data > Content-Disposition Header Field for Each Part", + "anchor": "section-4.2", + "level": "MUST", + "terms": ["MUST"], + "text": "The Content-Disposition header field MUST also contain an additional parameter of \"name\"; the value of the \"name\" parameter is the original field name from the form (possibly encoded; see Section 5.1)." }, { - "id": "oas-3.2.media-type-object.sequential-media-types.must-implementations-support-mapping-sequential-media-types", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1320, - "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Sequential Media Types", - "anchor": "sequential-media-types", + "id": "rfc7578.4.2.must-each-part-contain-content-disposition-header", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 197, + "section": "Definition of multipart/form-data > Content-Disposition Header Field for Each Part", + "anchor": "section-4.2", "level": "MUST", "terms": ["MUST"], - "text": "Implementations MUST support mapping sequential media types into the JSON Schema data model by treating them as if the values were in an array in the same order." + "text": "Each part MUST contain a Content-Disposition header field [RFC2183] where the disposition type is \"form-data\"." }, { - "id": "oas-3.2.media-type-object.should-example-examples-provided-example-match-specified", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1262, - "section": "Objects and Fields > Media Type Object", - "anchor": "media-type-object", + "id": "rfc7578.4.2.must-not-note-encoding-method-described-rfc5987-would", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 237, + "section": "Definition of multipart/form-data > Content-Disposition Header Field for Each Part", + "anchor": "section-4.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "NOTE: The encoding method described in [RFC5987], which would add a \"filename*\" parameter to the Content-Disposition header field, MUST NOT be used." + }, + { + "id": "rfc7578.4.2.should-form-data-represents-content-file-name", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 207, + "section": "Definition of multipart/form-data > Content-Disposition Header Field for Each Part", + "anchor": "section-4.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "When `example` or `examples` are provided, the example SHOULD match the specified schema and be in the correct format as specified by the media type and its encoding." + "text": "For form data that represents the content of a file, a name for the file SHOULD be supplied as well, by using a \"filename\" parameter of the Content-Disposition header field." }, { - "id": "oas-3.2.media-type-object.special-considerations-for-server-sent-events.must-field-value-types-handled-specified-text", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1344, - "section": "Objects and Fields > Media Type Object > Special Considerations for Server-Sent Events", - "anchor": "special-considerations-for-server-sent-events", + "id": "rfc7578.4.3.must-match-widely-deployed-implementations-multiple-files", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 254, + "section": "Definition of multipart/form-data > Multiple Files for One Form Field", + "anchor": "section-4.3", "level": "MUST", "terms": ["MUST"], - "text": "Field value types MUST be handled as specified by the `text/event-stream` specification (e.g. the `retry` field value is modeled as a JSON number that is expected to be of JSON Schema `type: integer`), and fields not given an explicit value type MUST be handled as strings." + "text": "To match widely deployed implementations, multiple files MUST be sent by supplying each file in a separate part but all with the same \"name\" parameter." }, { - "id": "oas-3.2.media-type-object.special-considerations-for-server-sent-events.must-text-event-stream-implementations-work-event", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1342, - "section": "Objects and Fields > Media Type Object > Special Considerations for Server-Sent Events", - "anchor": "special-considerations-for-server-sent-events", - "level": "MUST", - "terms": ["MUST"], - "text": "For `text/event-stream`, implementations MUST work with event data after it has been parsed according to the `text/event-stream` specification, including all guidance on ignoring certain fields (including comments) and/or values, and on combining values split across multiple lines." + "id": "rfc7578.4.3.should-receiving-applications-intended-wide-applicability-e", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 258, + "section": "Definition of multipart/form-data > Multiple Files for One Form Field", + "anchor": "section-4.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Receiving applications intended for wide applicability (e.g., multipart/form-data parsing libraries) SHOULD also support the older method of supplying multiple files." }, { - "id": "oas-3.2.media-type-object.streaming-sequential-media-types.may-both-schema-itemschema-used-same-media", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1331, - "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Sequential Media Types > Streaming Sequential Media Types", - "anchor": "streaming-sequential-media-types", + "id": "rfc7578.4.4.may-each-part-have-optional-content-type", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 264, + "section": "Definition of multipart/form-data > Content-Type Header Field for Each Part", + "anchor": "section-4.4", "level": "MAY", "terms": ["MAY"], - "text": "Both `schema` and `itemSchema` MAY be used in the same Media Type Object." + "text": "Each part MAY have an (optional) \"Content-Type\" header field, which defaults to \"text/plain\"." }, { - "id": "oas-3.2.media-type-object.streaming-sequential-media-types.must-unlike-schema-applied-complete-content-treated", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1329, - "section": "Objects and Fields > Media Type Object > Complete vs Streaming Content > Sequential Media Types > Streaming Sequential Media Types", - "anchor": "streaming-sequential-media-types", + "id": "rfc7578.4.4.should-contents-file-sent-file-data-labeled", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 264, + "section": "Definition of multipart/form-data > Content-Type Header Field for Each Part", + "anchor": "section-4.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the contents of a file are to be sent, the file data SHOULD be labeled with an appropriate media type, if known, or \"application/octet-stream\"." + }, + { + "id": "rfc7578.4.5.may-case-form-data-text-charset-parameter", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 271, + "section": "Definition of multipart/form-data > The Charset Parameter for \"text/plain\" Form Data", + "anchor": "section-4.5", + "level": "MAY", + "terms": ["MAY"], + "text": "In the case where the form data is text, the charset parameter for the \"text/plain\" Content-Type MAY be used to indicate the character encoding used in that part." + }, + { + "id": "rfc7578.4.7.should-not-senders-generate-any-parts-content-transfer", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 323, + "section": "Definition of multipart/form-data > Content-Transfer-Encoding Deprecated", + "anchor": "section-4.7", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Senders SHOULD NOT generate any parts with a Content-Transfer-Encoding header field." + }, + { + "id": "rfc7578.4.8.must-not-other-header-fields-included-ignored", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 345, + "section": "Definition of multipart/form-data > Other \"Content-\" Header Fields", + "anchor": "section-4.8", "level": "MUST", - "terms": ["MUST"], - "text": "Unlike `schema`, which is applied to the complete content (treated as an array as described in the sequential media types section), `itemSchema` MUST be applied to each item in the stream independently, which supports processing each item as it is read from the stream." + "terms": ["MUST NOT", "MUST"], + "text": "Other header fields MUST NOT be included and MUST be ignored." }, { - "id": "oas-3.2.non-rfc6570-field-values-and-combinations.may-implementations-create-properly-delimited-uri-template", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4950, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", + "id": "rfc7578.5.1.1.should-broadest-interoperability-existing-deployed-software-creating", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 365, + "section": "Operability Considerations > Non-ASCII Field Names and Values > Avoid Non-ASCII Field Names", + "anchor": "section-5.1.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "For broadest interoperability with existing deployed software, those creating forms SHOULD avoid non-ASCII field names." + }, + { + "id": "rfc7578.5.1.1.should-non-ascii-field-names-unavoidable-form", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 371, + "section": "Operability Considerations > Non-ASCII Field Names and Values > Avoid Non-ASCII Field Names", + "anchor": "section-5.1.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If non-ASCII field names are unavoidable, form or application creators SHOULD use UTF-8 uniformly." + }, + { + "id": "rfc7578.5.1.2.may-any-text-whether-field-name-field", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 399, + "section": "Operability Considerations > Non-ASCII Field Names and Values > Interpreting Forms and Creating multipart/form-data Data", + "anchor": "section-5.1.2", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY create a properly delimited URI Template with variables for individual names and values using RFC6570 regular or reserved expansion (based on `allowReserved`)." + "text": "Any text, whether field name, field value, or (\"text/plain\") form data that uses characters outside the ASCII range MAY be represented directly encoded in the form-charset." }, { - "id": "oas-3.2.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4959, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", + "id": "rfc7578.5.2.must-not-form-parts-identical-field-names-coalesced", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 428, + "section": "Operability Considerations > Ordered Fields and Duplicated Field Names", + "anchor": "section-5.2", "level": "MUST", - "terms": ["MUST"], - "text": "A parameter name that includes characters outside of the allowed RFC6570 variable character set MUST be percent-encoded before it can be used in a URI Template." + "terms": ["MUST NOT"], + "text": "Form parts with identical field names MUST NOT be coalesced." }, { - "id": "oas-3.2.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4950, - "section": "Appendix C: Using RFC6570-Based Serialization > Non-RFC6570 Field Values and Combinations", - "anchor": "non-rfc6570-field-values-and-combinations", + "id": "rfc7578.5.2.must-not-intermediaries-reorder-results", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 428, + "section": "Operability Considerations > Ordered Fields and Duplicated Field Names", + "anchor": "section-5.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Intermediaries MUST NOT reorder the results." + }, + { + "id": "rfc7578.5.2.should-form-processors-given-forms-well-defined", + "spec": "rfc", + "version": "7578", + "source": "rfc/rfc7578.txt", + "line": 428, + "section": "Operability Considerations > Ordered Fields and Duplicated Field Names", + "anchor": "section-5.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Configurations with no direct RFC6570 equivalent SHOULD also be handled according to RFC6570." + "text": "Form processors given forms with a well-defined ordering SHOULD send back results in order." }, { - "id": "oas-3.2.oauth-flow-object.authorizationUrl", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4681, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", - "level": "field", - "terms": [], - "text": "REQUIRED. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "id": "rfc7617.2.1.must-password-recipients-support-all-characters-defined", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 298, + "section": "The 'Basic' Authentication Scheme > The 'charset' auth-param", + "anchor": "section-2.1", + "level": "MUST", + "terms": ["MUST"], + "text": "For the password, recipients MUST support all characters defined in the \"OpaqueString\" profile defined in Section 4.2 of [RFC7613]." }, { - "id": "oas-3.2.oauth-flow-object.authorizationUrl.must-form-url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4681, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", + "id": "rfc7617.2.1.must-user-id-recipients-support-all-characters", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 294, + "section": "The 'Basic' Authentication Scheme > The 'charset' auth-param", + "anchor": "section-2.1", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "For the user-id, recipients MUST support all characters defined in the \"UsernameCasePreserved\" profile defined in Section 3.3 of [RFC7613], with the exception of the colon (\":\") character." }, { - "id": "oas-3.2.oauth-flow-object.authorizationUrl.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4681, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-authorization-url", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "id": "rfc7617.2.2.may-client-preemptively-send-corresponding-authorization-header", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 361, + "section": "The 'Basic' Authentication Scheme > Reusing Credentials", + "anchor": "section-2.2", + "level": "MAY", + "terms": ["MAY"], + "text": "A client MAY preemptively send the corresponding Authorization header field with requests for resources in that space without receipt of another challenge from the server." }, { - "id": "oas-3.2.oauth-flow-object.deviceAuthorizationUrl", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4682, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-device-authorization-url", - "level": "field", - "terms": [], - "text": "REQUIRED. The device authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "id": "rfc7617.2.2.may-similarly-client-sends-request-proxy-reuse", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 361, + "section": "The 'Basic' Authentication Scheme > Reusing Credentials", + "anchor": "section-2.2", + "level": "MAY", + "terms": ["MAY"], + "text": "Similarly, when a client sends a request to a proxy, it MAY reuse a user-id and password in the Proxy-Authorization header field without receiving another challenge from the proxy server." }, { - "id": "oas-3.2.oauth-flow-object.deviceAuthorizationUrl.must-form-url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4682, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-device-authorization-url", + "id": "rfc7617.2.2.should-client-assume-resources-identified-uris-prefix", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 353, + "section": "The 'Basic' Authentication Scheme > Reusing Credentials", + "anchor": "section-2.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A client SHOULD assume that resources identified by URIs with a prefix-match of the authentication scope are also within the protection space specified by the realm value of that authenticated request." + }, + { + "id": "rfc7617.2.must-no-other-authentication-parameters-defined-unknown", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 188, + "section": "The 'Basic' Authentication Scheme", + "anchor": "section-2", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "No other authentication parameters are defined -- unknown parameters MUST be ignored by recipients, and new parameters can only be defined by revising this specification." }, { - "id": "oas-3.2.oauth-flow-object.deviceAuthorizationUrl.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4682, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-device-authorization-url", + "id": "rfc7617.2.must-not-user-id-password-contain-any-control", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 254, + "section": "The 'Basic' Authentication Scheme", + "anchor": "section-2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The user-id and password MUST NOT contain any control characters (see \"CTL\" in Appendix B.1 of [RFC5234])." + }, + { + "id": "rfc7617.2.optional-authentication-parameter-charset-see-section-2", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 185, + "section": "The 'Basic' Authentication Scheme", + "anchor": "section-2", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "The authentication parameter 'charset' is OPTIONAL (see Section 2.1)." + }, + { + "id": "rfc7617.2.required-authentication-parameter-realm-rfc7235-section-2", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 182, + "section": "The 'Basic' Authentication Scheme", + "anchor": "section-2", "level": "MUST", "terms": ["REQUIRED"], - "text": "REQUIRED." + "text": "The authentication parameter 'realm' is REQUIRED ([RFC7235], Section 2.2)." }, { - "id": "oas-3.2.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4687, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "fixed-fields-25", + "id": "rfc7617.4.should-not-because-basic-authentication-involves-cleartext-transmission", + "spec": "rfc", + "version": "7617", + "source": "rfc/rfc7617.txt", + "line": 425, + "section": "Security Considerations", + "anchor": "section-4", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Because Basic authentication involves the cleartext transmission of passwords, it SHOULD NOT be used (without enhancements such as HTTPS [RFC2818]) to protect sensitive or valuable information." + }, + { + "id": "rfc9110.10.1.1.may-client-sends-100-continue-expectation-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6368, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "A client that sends a 100-continue expectation is not required to wait for any specific length of time; such a client MAY proceed to send the content even if it has not yet received a response." }, { - "id": "oas-3.2.oauth-flow-object.refreshUrl", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4684, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-refresh-url", - "level": "field", - "terms": [], - "text": "The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "id": "rfc9110.10.1.1.may-proxy-believes-configuration-past-interaction-next", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6438, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "MAY", + "terms": ["MAY"], + "text": "If the proxy believes (from configuration or past interaction) that the next inbound server only supports HTTP/1.0, the proxy MAY generate an immediate 100 (Continue) response to encourage the client to begin sending the content." }, { - "id": "oas-3.2.oauth-flow-object.refreshUrl.must-form-url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4684, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-refresh-url", + "id": "rfc9110.10.1.1.may-server-omit-sending-100-continue-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6392, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "MAY", + "terms": ["MAY"], + "text": "A server MAY omit sending a 100 (Continue) response if it has already received some or all of the content for the corresponding request, or if the framing indicates that there is no content." + }, + { + "id": "rfc9110.10.1.1.may-server-receives-expect-field-value-containing", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6320, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "MAY", + "terms": ["MAY"], + "text": "A server that receives an Expect field value containing a member other than 100-continue MAY respond with a 417 (Expectation Failed) status code to indicate that the unexpected expectation cannot be met." + }, + { + "id": "rfc9110.10.1.1.must-client-will-wait-100-continue-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6363, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "A client that will wait for a 100 (Continue) response before sending the request content MUST send an Expect header field containing a 100-continue expectation." }, { - "id": "oas-3.2.oauth-flow-object.scopes", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4685, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", - "level": "field", - "terms": [], - "text": "REQUIRED. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty." + "id": "rfc9110.10.1.1.must-not-client-generate-100-continue-expectation-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6359, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A client MUST NOT generate a 100-continue expectation in a request that does not include content." }, { - "id": "oas-3.2.oauth-flow-object.scopes.may-map-empty", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4685, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", - "level": "MAY", - "terms": ["MAY"], - "text": "The map MAY be empty." + "id": "rfc9110.10.1.1.must-not-origin-server-wait-content-before-sending", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6422, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The origin server MUST NOT wait for the content before sending the 100 (Continue) response." }, { - "id": "oas-3.2.oauth-flow-object.scopes.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4685, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-scopes", + "id": "rfc9110.10.1.1.must-server-receives-100-continue-expectation-http", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6388, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "A server that receives a 100-continue expectation in an HTTP/1.0 request MUST ignore that expectation." }, { - "id": "oas-3.2.oauth-flow-object.tokenUrl", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4683, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", - "level": "field", - "terms": [], - "text": "REQUIRED. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS." + "id": "rfc9110.10.1.1.must-server-sends-100-continue-response-ultimately", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6398, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "MUST", + "terms": ["MUST"], + "text": "A server that sends a 100 (Continue) response MUST ultimately send a final status code, once it receives and processes the request content, unless the connection is closed prematurely." }, { - "id": "oas-3.2.oauth-flow-object.tokenUrl.must-form-url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4683, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "id": "rfc9110.10.1.1.must-upon-receiving-http-1-1-later", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6410, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", "level": "MUST", "terms": ["MUST"], - "text": "This MUST be in the form of a URL." + "text": "Upon receiving an HTTP/1.1 (or later) request that has a method, target URI, and complete header section that contains a 100-continue expectation and an indication that request content will follow, an origin server MUST send either:" }, { - "id": "oas-3.2.oauth-flow-object.tokenUrl.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4683, - "section": "Objects and Fields > OAuth Flow Object > Fixed Fields", - "anchor": "oauth-flow-token-url", + "id": "rfc9110.10.1.1.must-upon-receiving-http-1-1-later-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6426, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "Upon receiving an HTTP/1.1 (or later) request that has a method, target URI, and complete header section that contains a 100-continue expectation and indicates a request content will follow, a proxy MUST either:" }, { - "id": "oas-3.2.oauth-flows-object.authorizationCode", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4668, - "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-authorization-code", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0." + "id": "rfc9110.10.1.1.should-client-receives-417-expectation-failed-status", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6376, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A client that receives a 417 (Expectation Failed) status code in response to a request containing a 100-continue expectation SHOULD repeat that request without a 100-continue expectation, since the 417 response merely indicates that the response chain does not support expectations (e.g., it passes through an HTTP/1.0 server)." }, { - "id": "oas-3.2.oauth-flows-object.clientCredentials", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4667, - "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-client-credentials", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0." + "id": "rfc9110.10.1.1.should-not-furthermore-since-100-continue-responses-cannot", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6368, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Furthermore, since 100 (Continue) responses cannot be sent through an HTTP/1.0 intermediary, such a client SHOULD NOT wait for an indefinite period before sending the content." }, { - "id": "oas-3.2.oauth-flows-object.deviceAuthorization", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4669, - "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-device-authorization", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Device Authorization flow." + "id": "rfc9110.10.1.1.should-server-responds-final-status-code-before", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6403, + "section": "Message Context > Request Context Fields > Expect", + "anchor": "section-10.1.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A server that responds with a final status code before reading the entire request content SHOULD indicate whether it intends to close the connection (e.g., see Section 9.6 of [HTTP/1.1]) or continue reading the request content." }, { - "id": "oas-3.2.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4671, - "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", - "anchor": "fixed-fields-24", + "id": "rfc9110.10.1.2.should-not-server-use-header-field-access-control", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6478, + "section": "Message Context > Request Context Fields > From", + "anchor": "section-10.1.2", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A server SHOULD NOT use the From header field for access control or authentication, since its value is expected to be visible to anyone receiving or observing the request and is often recorded within logfiles and error reports without any expectation of privacy." + }, + { + "id": "rfc9110.10.1.2.should-not-user-agent-send-header-field-without", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6466, + "section": "Message Context > Request Context Fields > From", + "anchor": "section-10.1.2", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A user agent SHOULD NOT send a From header field without explicit configuration by the user, since that might conflict with the user's privacy interests or their site's security policy." + }, + { + "id": "rfc9110.10.1.2.should-robotic-user-agent-send-valid-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6472, + "section": "Message Context > Request Context Fields > From", + "anchor": "section-10.1.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A robotic user agent SHOULD send a valid From header field so that the person responsible for running the robot can be contacted if problems occur on servers, such as if the robot is sending excessive, unwanted, or invalid requests." + }, + { + "id": "rfc9110.10.1.3.may-referer-header-field-value-need-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6526, + "section": "Message Context > Request Context Fields > Referer", + "anchor": "section-10.1.3", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "The Referer header field value need not convey the full URI of the referring resource; a user agent MAY truncate parts other than the referring origin." }, { - "id": "oas-3.2.oauth-flows-object.implicit", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4665, - "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-implicit", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Implicit flow" + "id": "rfc9110.10.1.3.must-not-user-agent-include-fragment-userinfo-components", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6490, + "section": "Message Context > Request Context Fields > Referer", + "anchor": "section-10.1.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A user agent MUST NOT include the fragment and userinfo components of the URI reference [URI], if any, when generating the Referer field value." + }, + { + "id": "rfc9110.10.1.3.must-not-user-agent-send-referer-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6530, + "section": "Message Context > Request Context Fields > Referer", + "anchor": "section-10.1.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A user agent MUST NOT send a Referer header field in an unsecured HTTP request if the referring resource was accessed with a secure protocol." + }, + { + "id": "rfc9110.10.1.3.must-target-uri-obtained-source-does-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6520, + "section": "Message Context > Request Context Fields > Referer", + "anchor": "section-10.1.3", + "level": "MUST", + "terms": ["MUST"], + "text": "If the target URI was obtained from a source that does not have its own URI (e.g., input from the user keyboard, or an entry within the user's bookmarks/favorites), the user agent MUST either exclude the Referer header field or send it with a value of \"about:blank\"." }, { - "id": "oas-3.2.oauth-flows-object.password", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4666, - "section": "Objects and Fields > OAuth Flows Object > Fixed Fields", - "anchor": "oauth-flows-password", - "level": "field", - "terms": [], - "text": "Configuration for the OAuth Resource Owner Password flow" + "id": "rfc9110.10.1.3.should-not-intermediary-modify-delete-referer-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6547, + "section": "Message Context > Request Context Fields > Referer", + "anchor": "section-10.1.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "An intermediary SHOULD NOT modify or delete the Referer header field when the field value shares the same scheme and host as the target URI." }, { - "id": "oas-3.2.objects-and-fields.must-json-schema-differs-section-section-considered", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 80, - "section": "Objects and Fields", - "anchor": "objects-and-fields", + "id": "rfc9110.10.1.3.should-not-user-agent-send-referer-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6530, + "section": "Message Context > Request Context Fields > Referer", + "anchor": "section-10.1.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A user agent SHOULD NOT send a Referer header field if the referring resource was accessed with a secure protocol and the request target has an origin differing from that of the referring resource, unless the referring resource explicitly allows Referer to be sent." + }, + { + "id": "rfc9110.10.1.4.must-sender-te-send-te-connection-option", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6595, + "section": "Message Context > Request Context Fields > TE", + "anchor": "section-10.1.4", "level": "MUST", "terms": ["MUST"], - "text": "If the JSON Schema differs from this section, then this section MUST be considered authoritative." + "text": "A sender of TE MUST also send a \"TE\" connection option within the Connection header field (Section 7.6.1) to inform intermediaries not to forward this field." }, { - "id": "oas-3.2.objects-and-fields.required-following-description-field-not-explicitly-described", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 85, - "section": "Objects and Fields", - "anchor": "objects-and-fields", + "id": "rfc9110.10.1.5.must-not-sender-limit-generated-product-identifiers-what", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6631, + "section": "Message Context > Request Context Fields > User-Agent", + "anchor": "section-10.1.5", "level": "MUST", - "terms": ["REQUIRED", "MUST", "SHALL", "OPTIONAL"], - "text": "In the following description, if a field is not explicitly REQUIRED or described with a MUST or SHALL, it can be considered OPTIONAL." + "terms": ["SHOULD", "MUST NOT"], + "text": "A sender SHOULD limit generated product identifiers to what is necessary to identify the product; a sender MUST NOT generate advertising or other nonessential information within the product identifier." }, { - "id": "oas-3.2.openapi-object.$self", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 98, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-self", - "level": "field", - "terms": [], - "text": "This string MUST be in the form of a URI reference as defined by [RFC3986] Section 4.1. The `$self` field provides the self-assigned URI of this document, which also serves as its base URI in accordance with [RFC3986] Section 5.1.1. Implementations MUST support identifying the targets of API description URIs using the URI defined by this field when it is present. See Establishing the Base URI for the base URI behavior when `$self` is absent or relative, and see Appendix F for examples of using `$self` to resolve references." + "id": "rfc9110.10.1.5.should-not-sender-generate-information-product-version-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6631, + "section": "Message Context > Request Context Fields > User-Agent", + "anchor": "section-10.1.5", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A sender SHOULD NOT generate information in product-version that is not a version identifier (i.e., successive versions of the same product name ought to differ only in the product-version portion of the product identifier)." }, { - "id": "oas-3.2.openapi-object.$self.must-implementations-support-identifying-targets-api-description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 98, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-self", + "id": "rfc9110.10.1.5.should-not-user-agent-generate-user-agent-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6645, + "section": "Message Context > Request Context Fields > User-Agent", + "anchor": "section-10.1.5", + "level": "SHOULD", + "terms": ["SHOULD NOT", "SHOULD"], + "text": "A user agent SHOULD NOT generate a User-Agent header field containing needlessly fine-grained detail and SHOULD limit the addition of subproducts by third parties." + }, + { + "id": "rfc9110.10.1.5.should-user-agent-send-user-agent-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6606, + "section": "Message Context > Request Context Fields > User-Agent", + "anchor": "section-10.1.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A user agent SHOULD send a User-Agent header field in each request unless specifically configured not to do so." + }, + { + "id": "rfc9110.10.2.1.must-not-proxy-modify-allow-header-field-does", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6697, + "section": "Message Context > Response Context Fields > Allow", + "anchor": "section-10.2.1", "level": "MUST", - "terms": ["MUST"], - "text": "Implementations MUST support identifying the targets of API description URIs using the URI defined by this field when it is present." + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT modify the Allow header field -- it does not need to understand all of the indicated methods in order to handle them according to the generic message handling rules." }, { - "id": "oas-3.2.openapi-object.$self.must-string-form-uri-reference-defined-rfc3986", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 98, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-self", + "id": "rfc9110.10.2.1.must-origin-server-generate-allow-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6689, + "section": "Message Context > Response Context Fields > Allow", + "anchor": "section-10.2.1", "level": "MUST", - "terms": ["MUST"], - "text": "This string MUST be in the form of a URI reference as defined by [RFC3986] Section 4.1." + "terms": ["MUST", "MAY"], + "text": "An origin server MUST generate an Allow header field in a 405 (Method Not Allowed) response and MAY do so in any other response." }, { - "id": "oas-3.2.openapi-object.components", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 104, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-components", - "level": "field", - "terms": [], - "text": "An element to hold various Objects for the OpenAPI Description." + "id": "rfc9110.10.2.2.must-location-value-provided-3xx-redirection-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6728, + "section": "Message Context > Response Context Fields > Location", + "anchor": "section-10.2.2", + "level": "MUST", + "terms": ["MUST"], + "text": "If the Location value provided in a 3xx (Redirection) response does not have a fragment component, a user agent MUST process the redirection as if the value inherits the fragment component of the URI reference used to generate the target URI (i.e., the redirection inherits the original reference's fragment, if any)." }, { - "id": "oas-3.2.openapi-object.establishing-the-base-uri.may-implementations-support-document-retrieval-although-see", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 156, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Establishing the Base URI", - "anchor": "establishing-the-base-uri", + "id": "rfc9110.10.2.4.may-origin-server-generate-server-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6831, + "section": "Message Context > Response Context Fields > Server", + "anchor": "section-10.2.4", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support document retrieval, although see the Security Considerations sections for additional guidance." + "text": "An origin server MAY generate a Server header field in its responses." }, { - "id": "oas-3.2.openapi-object.establishing-the-base-uri.must-relative-uri-references-resolved-using-appropriate", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 152, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Establishing the Base URI", - "anchor": "establishing-the-base-uri", + "id": "rfc9110.10.2.4.should-not-origin-server-generate-server-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6856, + "section": "Message Context > Response Context Fields > Server", + "anchor": "section-10.2.4", + "level": "SHOULD", + "terms": ["SHOULD NOT", "SHOULD"], + "text": "An origin server SHOULD NOT generate a Server header field containing needlessly fine-grained detail and SHOULD limit the addition of subproducts by third parties." + }, + { + "id": "rfc9110.11.2.must-authentication-parameters-name-value-pairs-name", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6910, + "section": "HTTP Authentication > Authentication Parameters", + "anchor": "section-11.2", "level": "MUST", "terms": ["MUST"], - "text": "Relative URI references are resolved using the appropriate base URI, which MUST be determined in accordance with [RFC3986] Section 5.1.1 – 5.1.4 and, for Schema objects, JSON Schema draft 2020-12 Section 8.2, as illustrated by the examples in Appendix F: Examples of Base URI Determination and Reference Resolution." + "text": "Authentication parameters are name/value pairs, where the name token is matched case-insensitively and each parameter name MUST only occur once per challenge." }, { - "id": "oas-3.2.openapi-object.establishing-the-base-uri.should-therefore-all-implementations-allow-users-provide", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 156, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Establishing the Base URI", - "anchor": "establishing-the-base-uri", + "id": "rfc9110.11.4.should-likewise-upon-receipt-request-omits-proxy", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6996, + "section": "HTTP Authentication > Credentials", + "anchor": "section-11.4", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Therefore, all implementations SHOULD allow users to provide documents with their intended retrieval URIs so that references can be resolved as if retrievals were performed." + "text": "Likewise, upon receipt of a request that omits proxy credentials or contains invalid or partial proxy credentials, a proxy that requires authentication SHOULD generate a 407 (Proxy Authentication Required) response that contains a Proxy-Authenticate header field with at least one (possibly new) challenge applicable to the proxy." }, { - "id": "oas-3.2.openapi-object.externalDocs", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 107, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation." + "id": "rfc9110.11.4.should-upon-receipt-request-protected-resource-omits", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6988, + "section": "HTTP Authentication > Credentials", + "anchor": "section-11.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Upon receipt of a request for a protected resource that omits credentials, contains invalid credentials (e.g., a bad password) or partial credentials (e.g., when the authentication scheme requires more than one round trip), an origin server SHOULD send a 401 (Unauthorized) response that contains a WWW-Authenticate header field with at least one (possibly new) challenge applicable to the requested resource." }, { - "id": "oas-3.2.openapi-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 109, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "fixed-fields", + "id": "rfc9110.11.5.may-prior-request-authorized-user-agent-reuse", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7043, + "section": "HTTP Authentication > Establishing a Protection Space (Realm)", + "anchor": "section-11.5", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "If a prior request has been authorized, the user agent MAY reuse the same credentials for all other requests within that protection space for a period of time determined by the authentication scheme, parameters, and/or user preferences (such as a configurable inactivity timeout)." }, { - "id": "oas-3.2.openapi-object.fixed-fields.must-addition-required-fields-least-one-components", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 93, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "fixed-fields", + "id": "rfc9110.11.5.must-historical-reasons-sender-only-generate-quoted", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7059, + "section": "HTTP Authentication > Establishing a Protection Space (Realm)", + "anchor": "section-11.5", "level": "MUST", "terms": ["MUST"], - "text": "In addition to the required fields, at least one of the `components`, `paths`, or `webhooks` fields MUST be present." + "text": "For historical reasons, a sender MUST only generate the quoted-string syntax." }, { - "id": "oas-3.2.openapi-object.fixed-fields.must-ensure-interoperability-references-use-target-document", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 111, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "fixed-fields", + "id": "rfc9110.11.6.1.may-server-generate-www-authenticate-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7080, + "section": "HTTP Authentication > Authenticating Users to Origin Servers > WWW-Authenticate", + "anchor": "section-11.6.1", + "level": "MAY", + "terms": ["MAY"], + "text": "A server MAY generate a WWW-Authenticate header field in other response messages to indicate that supplying credentials (or different credentials) might affect the response." + }, + { + "id": "rfc9110.11.6.1.must-not-proxy-forwarding-response-modify-any-www", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7087, + "section": "HTTP Authentication > Authenticating Users to Origin Servers > WWW-Authenticate", + "anchor": "section-11.6.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A proxy forwarding a response MUST NOT modify any WWW-Authenticate header fields in that response." + }, + { + "id": "rfc9110.11.6.1.must-server-generating-401-unauthorized-response-send", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7080, + "section": "HTTP Authentication > Authenticating Users to Origin Servers > WWW-Authenticate", + "anchor": "section-11.6.1", "level": "MUST", "terms": ["MUST"], - "text": "To ensure interoperability, references MUST use the target document's `$self` URI if the `$self` field is present." + "text": "A server generating a 401 (Unauthorized) response MUST send a WWW-Authenticate header field containing at least one challenge." }, { - "id": "oas-3.2.openapi-object.fixed-fields.not-recommended-implementations-choose-support-referencing-other-uris", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 111, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "fixed-fields", - "level": "SHOULD", - "terms": ["MAY", "NOT RECOMMENDED"], - "text": "Implementations MAY choose to support referencing by other URIs such as the retrieval URI even when `$self` is present, however this behavior is not interoperable and relying on it is NOT RECOMMENDED." + "id": "rfc9110.11.6.2.must-not-proxy-forwarding-request-modify-any-authorization", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7146, + "section": "HTTP Authentication > Authenticating Users to Origin Servers > Authorization", + "anchor": "section-11.6.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A proxy forwarding a request MUST NOT modify any Authorization header fields in that request." }, { - "id": "oas-3.2.openapi-object.info", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 99, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", - "level": "field", - "terms": [], - "text": "REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required." + "id": "rfc9110.11.7.1.must-proxy-send-least-one-proxy-authenticate", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7199, + "section": "HTTP Authentication > Authenticating Clients to Proxies > Proxy-Authenticate", + "anchor": "section-11.7.1", + "level": "MUST", + "terms": ["MUST"], + "text": "A proxy MUST send at least one Proxy-Authenticate header field in each 407 (Proxy Authentication Required) response that it generates." }, { - "id": "oas-3.2.openapi-object.info.may-metadata-used-tooling-required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 99, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", + "id": "rfc9110.11.7.2.may-proxy-relay-credentials-client-request-next", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7243, + "section": "HTTP Authentication > Authenticating Clients to Proxies > Proxy-Authorization", + "anchor": "section-11.7.2", "level": "MAY", "terms": ["MAY"], - "text": "The metadata MAY be used by tooling as required." - }, - { - "id": "oas-3.2.openapi-object.info.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 99, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-info", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "text": "A proxy MAY relay the credentials from the client request to the next proxy if that is the mechanism by which the proxies cooperatively authenticate a given request." }, { - "id": "oas-3.2.openapi-object.jsonSchemaDialect", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 100, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-json-schema-dialect", - "level": "field", - "terms": [], - "text": "The default value for the `$schema` keyword within Schema Objects contained within this OAS document. This MUST be in the form of a URI. See JSON Schema Keywords to determine the default value." + "id": "rfc9110.12.1.may-order-improve-server-s-guess-user", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7345, + "section": "Content Negotiation > Proactive Negotiation", + "anchor": "section-12.1", + "level": "MAY", + "terms": ["MAY"], + "text": "In order to improve the server's guess, a user agent MAY send request header fields that describe its preferences." }, { - "id": "oas-3.2.openapi-object.jsonSchemaDialect.must-form-uri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 100, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-json-schema-dialect", + "id": "rfc9110.12.4.2.must-not-sender-qvalue-generate-more-three-digits", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7513, + "section": "Content Negotiation > Content Negotiation Field Features > Quality Values", + "anchor": "section-12.4.2", "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "terms": ["MUST NOT"], + "text": "A sender of qvalue MUST NOT generate more than three digits after the decimal point." }, { - "id": "oas-3.2.openapi-object.openapi", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 97, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", - "level": "field", - "terms": [], - "text": "REQUIRED. This string MUST be the version number of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is _not_ related to the `info.version` string, which describes the OpenAPI document's version." + "id": "rfc9110.12.5.1.should-recipients-process-any-parameter-named-q", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7580, + "section": "Content Negotiation > Content Negotiation Fields > Accept", + "anchor": "section-12.5.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Recipients SHOULD process any parameter named \"q\" as weight, regardless of parameter ordering." }, { - "id": "oas-3.2.openapi-object.openapi-description-structure.may-documents-different-object-root-mix-oad", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 121, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", - "anchor": "openapi-description-structure", - "level": "MAY", - "terms": ["MAY"], - "text": "Documents with a different Object at the root, or that mix OAD content with other content, MAY be supported, but will have implementation-defined or, potentially, undefined behavior as described in Appendix G: Parsing and Resolution Guidance." + "id": "rfc9110.12.5.1.should-senders-using-weights-send-q-last", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7580, + "section": "Content Negotiation > Content Negotiation Fields > Accept", + "anchor": "section-12.5.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Senders using weights SHOULD send \"q\" last (after all media-range parameters)." }, { - "id": "oas-3.2.openapi-object.openapi-description-structure.may-oad-made-up-single-document-distributed", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 116, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", - "anchor": "openapi-description-structure", + "id": "rfc9110.12.5.2.may-user-agent-associate-quality-value-each", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7702, + "section": "Content Negotiation > Content Negotiation Fields > Accept-Charset", + "anchor": "section-12.5.2", "level": "MAY", "terms": ["MAY"], - "text": "An OAD MAY be made up of a single document, or be distributed across multiple documents that are connected by various fields using URI references and implicit connections." + "text": "A user agent MAY associate a quality value with each charset to indicate the user's relative preference for that charset, as defined in Section 12.4.2." }, { - "id": "oas-3.2.openapi-object.openapi-description-structure.may-openapi-object-embedded-another-format-called", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 127, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", - "anchor": "openapi-description-structure", + "id": "rfc9110.12.5.3.may-each-codings-value-given-associated-quality", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7752, + "section": "Content Negotiation > Content Negotiation Fields > Accept-Encoding", + "anchor": "section-12.5.3", "level": "MAY", "terms": ["MAY"], - "text": "An OpenAPI Object MAY be embedded in another format, called the embedding format, just as JSON Schema is embedded in the OAS in the form of Schema Objects." + "text": "Each codings value MAY be given an associated quality value (weight) representing the preference for that encoding, as defined in Section 12.4.2." }, { - "id": "oas-3.2.openapi-object.openapi-description-structure.must-order-parsing-behavior-well-defined-all", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 119, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", - "anchor": "openapi-description-structure", + "id": "rfc9110.12.5.3.must-not-order-avoid-confusion-issues-related-media", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7809, + "section": "Content Negotiation > Content Negotiation Fields > Accept-Encoding", + "anchor": "section-12.5.3", "level": "MUST", - "terms": ["MUST"], - "text": "In order for parsing behavior to be well-defined, all documents in an OAD MUST have either an OpenAPI Object or a Schema Object at the root, and MUST be parsed as complete documents, as described in the next section." + "terms": ["MUST NOT"], + "text": "In order to avoid confusion with issues related to media types, servers that fail a request with a 415 status for reasons unrelated to content codings MUST NOT include the Accept-Encoding header field." }, { - "id": "oas-3.2.openapi-object.openapi-description-structure.recommended-entry-document-oad-named-openapi-json", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 124, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure", - "anchor": "openapi-description-structure", + "id": "rfc9110.12.5.3.should-non-empty-accept-encoding-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7790, + "section": "Content Negotiation > Content Negotiation Fields > Accept-Encoding", + "anchor": "section-12.5.3", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is RECOMMENDED that the entry document of an OAD be named `openapi.json` or `openapi.yaml`." + "terms": ["SHOULD"], + "text": "If a non-empty Accept-Encoding header field is present in a request and none of the available representations for the response have a content coding that is listed as acceptable, the origin server SHOULD send a response without any content coding unless the identity coding is indicated as unacceptable." }, { - "id": "oas-3.2.openapi-object.openapi.must-string-version-number-openapi-specification-openapi", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 97, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "id": "rfc9110.12.5.4.must-not-user-agent-does-not-provide-control", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7880, + "section": "Content Negotiation > Content Negotiation Fields > Accept-Language", + "anchor": "section-12.5.4", "level": "MUST", - "terms": ["MUST"], - "text": "This string MUST be the version number of the OpenAPI Specification that the OpenAPI document uses." + "terms": ["MUST NOT"], + "text": "A user agent that does not provide such control to the user MUST NOT send an Accept-Language header field." }, { - "id": "oas-3.2.openapi-object.openapi.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 97, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", + "id": "rfc9110.12.5.5.must-not-inform-cache-recipients-they-use-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7944, + "section": "Content Negotiation > Content Negotiation Fields > Vary", + "anchor": "section-12.5.5", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "To inform cache recipients that they MUST NOT use this response to satisfy a later request unless the later request has the same values for the listed header fields as the original request (Section 4.1 of [CACHING]) or reuse of the response has been validated by the origin server." }, { - "id": "oas-3.2.openapi-object.openapi.should-openapi-field-used-tooling-interpret-openapi", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 97, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-version", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document." + "id": "rfc9110.12.5.5.must-not-proxy-generate-vary-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7919, + "section": "Content Negotiation > Content Negotiation Fields > Vary", + "anchor": "section-12.5.5", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT generate \"*\" in a Vary field value." }, { - "id": "oas-3.2.openapi-object.parsing-documents.must-each-document-oad-fully-parsed-order", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 132, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Parsing Documents", - "anchor": "parsing-documents", - "level": "MUST", - "terms": ["MUST"], - "text": "Each document in an OAD MUST be fully parsed in order to locate possible reference targets." + "id": "rfc9110.12.5.5.should-origin-server-generate-vary-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 7964, + "section": "Content Negotiation > Content Negotiation Fields > Vary", + "anchor": "section-12.5.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server SHOULD generate a Vary header field on a cacheable response when it wishes that response to be selectively reused for subsequent requests." }, { - "id": "oas-3.2.openapi-object.parsing-documents.must-not-implementations-treat-reference-unresolvable-before-completely", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 136, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Parsing Documents", - "anchor": "parsing-documents", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "Implementations MUST NOT treat a reference as unresolvable before completely parsing all documents provided to the implementation as possible parts of the OAD." + "id": "rfc9110.13.1.1.may-alternatively-request-state-changing-operation-appears", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8108, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", + "level": "MAY", + "terms": ["MAY"], + "text": "Alternatively, if the request is a state-changing operation that appears to have already been applied to the selected representation, the origin server MAY respond with a 2xx (Successful) status code (i.e., the change requested by the user agent has already succeeded, but the user agent might not be aware of it, perhaps because the prior response was lost or an equivalent change was made by some other user agent)." }, { - "id": "oas-3.2.openapi-object.paths", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 102, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-paths", - "level": "field", - "terms": [], - "text": "The available paths and operations for the API." + "id": "rfc9110.13.1.1.may-cache-intermediary-ignore-match-because-interoperability", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8146, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", + "level": "MAY", + "terms": ["MAY"], + "text": "A cache or intermediary MAY ignore If-Match because its interoperability features are only necessary for an origin server." }, { - "id": "oas-3.2.openapi-object.relative-references-in-api-description-uris.may-unless-specified-otherwise-all-fields-uris", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 148, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs", - "anchor": "relative-references-in-api-description-uris", + "id": "rfc9110.13.1.1.may-client-send-match-header-field-get", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8135, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", "level": "MAY", "terms": ["MAY"], - "text": "Unless specified otherwise, all fields that are URIs MAY be relative references as defined by [RFC3986] Section 4.2." + "text": "A client MAY send an If-Match header field in a GET request to indicate that it would prefer a 412 (Precondition Failed) response if the selected representation does not match." }, { - "id": "oas-3.2.openapi-object.resolving-implicit-connections.recommended-resolving-components-object-tag-object-names", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 176, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For resolving Components Object and Tag Object names from a referenced (non-entry) document, it is RECOMMENDED that tools resolve from the entry document, rather than the current document." + "id": "rfc9110.13.1.1.may-instead-origin-server-indicate-conditional-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8108, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", + "level": "MAY", + "terms": ["MAY"], + "text": "Instead, the origin server MAY indicate that the conditional request failed by responding with a 412 (Precondition Failed) status code." }, { - "id": "oas-3.2.openapi-object.resolving-implicit-connections.recommended-resolving-operation-object-based-operationid-consider", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 176, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For resolving an Operation Object based on an `operationId`, it is RECOMMENDED to consider all Operation Objects from all parsed documents." + "id": "rfc9110.13.1.1.must-not-origin-server-evaluates-match-condition-perform", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8108, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "An origin server that evaluates an If-Match condition MUST NOT perform the requested method if the condition evaluates to false." }, { - "id": "oas-3.2.openapi-object.resolving-implicit-connections.recommended-some-cases-unambiguous-uri-based-alternative", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 173, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Resolving Implicit Connections", - "anchor": "resolving-implicit-connections", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "In some cases, an unambiguous URI-based alternative is available, and OAD authors are RECOMMENDED to use the alternative to maximize interoperability." + "id": "rfc9110.13.1.1.must-origin-server-receives-request-selects-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8086, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", + "level": "MUST", + "terms": ["MUST"], + "text": "When an origin server receives a request that selects a representation and that request includes an If-Match header field, the origin server MUST evaluate the If-Match condition per Section 13.2 prior to performing the method." }, { - "id": "oas-3.2.openapi-object.resolving-uri-fragments.should-representation-referenced-document-json-yaml-fragment", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 163, - "section": "Objects and Fields > OpenAPI Object > OpenAPI Description Structure > Relative References in API Description URIs > Resolving URI fragments", - "anchor": "resolving-uri-fragments", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON Pointer as per RFC6901." + "id": "rfc9110.13.1.1.must-origin-server-use-strong-comparison-function", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8061, + "section": "Conditional Requests > Preconditions > If-Match", + "anchor": "section-13.1.1", + "level": "MUST", + "terms": ["MUST"], + "text": "An origin server MUST use the strong comparison function when comparing entity tags for If-Match (Section 8.8.3.2), since the client intends this precondition to prevent the method from being applied if there have been any changes to the representation data." }, { - "id": "oas-3.2.openapi-object.security", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 105, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-security", - "level": "field", - "terms": [], - "text": "A declaration of which security mechanisms can be used across the API. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. Individual operations can override this definition. The list can be incomplete, up to being empty or absent. To make security explicitly optional, an empty security requirement (`{}`) can be included in the array." + "id": "rfc9110.13.1.2.must-not-origin-server-evaluates-none-match-condition", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8228, + "section": "Conditional Requests > Preconditions > If-None-Match", + "anchor": "section-13.1.2", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "An origin server that evaluates an If-None-Match condition MUST NOT perform the requested method if the condition evaluates to false; instead, the origin server MUST respond with either a) the 304 (Not Modified) status code if the request method is GET or HEAD or b) the 412 (Precondition Failed) status code for all other request methods." }, { - "id": "oas-3.2.openapi-object.servers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 101, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-servers", - "level": "field", - "terms": [], - "text": "An array of Server Objects, which provide connectivity information to a target server. If the `servers` field is not provided, or is an empty array, the default value would be an array consisting of a single Server Object with a url value of `/`." + "id": "rfc9110.13.1.2.must-origin-server-receives-request-selects-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8206, + "section": "Conditional Requests > Preconditions > If-None-Match", + "anchor": "section-13.1.2", + "level": "MUST", + "terms": ["MUST"], + "text": "When an origin server receives a request that selects a representation and that request includes an If-None-Match header field, the origin server MUST evaluate the If-None-Match condition per Section 13.2 prior to performing the method." }, { - "id": "oas-3.2.openapi-object.tags", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 106, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", - "level": "field", - "terms": [], - "text": "A list of tags used by the OpenAPI Description with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique." + "id": "rfc9110.13.1.2.must-recipient-use-weak-comparison-function-comparing", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8169, + "section": "Conditional Requests > Preconditions > If-None-Match", + "anchor": "section-13.1.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST use the weak comparison function when comparing entity tags for If-None-Match (Section 8.8.3.2), since weak entity tags can be used for cache validation even if there have been changes to the representation data." }, { - "id": "oas-3.2.openapi-object.tags.may-tags-not-declared-organized-randomly-based", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 106, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", - "level": "MAY", - "terms": ["MAY"], - "text": "The tags that are not declared MAY be organized randomly or based on the tools' logic." + "id": "rfc9110.13.1.2.should-client-desires-update-one-more-stored", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8187, + "section": "Conditional Requests > Preconditions > If-None-Match", + "anchor": "section-13.1.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When a client desires to update one or more stored responses that have entity tags, the client SHOULD generate an If-None-Match header field containing a list of those entity tags when making a GET request; this allows recipient servers to send a 304 (Not Modified) response to indicate when one of those stored responses matches the selected representation." }, { - "id": "oas-3.2.openapi-object.tags.must-each-tag-name-list-unique", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 106, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-tags", + "id": "rfc9110.13.1.3.must-recipient-ignore-modified-since-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8275, + "section": "Conditional Requests > Preconditions > If-Modified-Since", + "anchor": "section-13.1.3", "level": "MUST", "terms": ["MUST"], - "text": "Each tag name in the list MUST be unique." + "text": "A recipient MUST ignore the If-Modified-Since header field if the received field value is not a valid HTTP-date, the field value has more than one member, or if the request method is neither GET nor HEAD." }, { - "id": "oas-3.2.openapi-object.webhooks", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 103, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-webhooks", - "level": "field", - "terms": [], - "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An example is available." + "id": "rfc9110.13.1.3.must-recipient-ignore-modified-since-header-field-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8280, + "section": "Conditional Requests > Preconditions > If-Modified-Since", + "anchor": "section-13.1.3", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST ignore the If-Modified-Since header field if the resource does not have a modification date available." }, { - "id": "oas-3.2.openapi-object.webhooks.may-incoming-webhooks-received-part-api-api", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 103, - "section": "Objects and Fields > OpenAPI Object > Fixed Fields", - "anchor": "oas-webhooks", - "level": "MAY", - "terms": ["MAY"], - "text": "The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement." + "id": "rfc9110.13.1.3.must-recipient-ignore-modified-since-request-contains", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8267, + "section": "Conditional Requests > Preconditions > If-Modified-Since", + "anchor": "section-13.1.3", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST ignore If-Modified-Since if the request contains an If-None-Match header field; the condition in If-None-Match is considered to be a more accurate replacement for the condition in If-Modified-Since, and the two are only combined for the sake of interoperating with older intermediaries that might not implement If-None-Match." }, { - "id": "oas-3.2.operation-object.callbacks", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 687, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-callbacks", - "level": "field", - "terms": [], - "text": "A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses." + "id": "rfc9110.13.1.3.must-recipient-interpret-modified-since-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8284, + "section": "Conditional Requests > Preconditions > If-Modified-Since", + "anchor": "section-13.1.3", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST interpret an If-Modified-Since field value's timestamp in terms of the origin server's clock." }, { - "id": "oas-3.2.operation-object.deprecated", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 688, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-deprecated", - "level": "field", - "terms": [], - "text": "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`." + "id": "rfc9110.13.1.3.should-not-origin-server-evaluates-modified-since-condition", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8336, + "section": "Conditional Requests > Preconditions > If-Modified-Since", + "anchor": "section-13.1.3", + "level": "SHOULD", + "terms": ["SHOULD NOT", "SHOULD"], + "text": "An origin server that evaluates an If-Modified-Since condition SHOULD NOT perform the requested method if the condition evaluates to false; instead, the origin server SHOULD generate a 304 (Not Modified) response, including only those metadata that are useful for identifying or updating a previously cached response." }, { - "id": "oas-3.2.operation-object.deprecated.should-consumers-refrain-usage-declared-operation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 688, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-deprecated", + "id": "rfc9110.13.1.3.should-origin-server-receives-request-selects-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8317, + "section": "Conditional Requests > Preconditions > If-Modified-Since", + "anchor": "section-13.1.3", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Consumers SHOULD refrain from usage of the declared operation." + "text": "When an origin server receives a request that selects a representation and that request includes an If-Modified-Since header field without an If-None-Match header field, the origin server SHOULD evaluate the If-Modified-Since condition per Section 13.2 prior to performing the method." }, { - "id": "oas-3.2.operation-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 681, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-description", - "level": "field", - "terms": [], - "text": "A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.13.1.4.may-alternatively-request-state-changing-operation-appears", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8421, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", + "level": "MAY", + "terms": ["MAY"], + "text": "Alternatively, if the request is a state-changing operation that appears to have already been applied to the selected representation, the origin server MAY respond with a 2xx (Successful) status code (i.e., the change requested by the user agent has already succeeded, but the user agent might not be aware of it, perhaps because the prior response was lost or an equivalent change was made by some other user agent)." }, { - "id": "oas-3.2.operation-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 681, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-description", + "id": "rfc9110.13.1.4.may-cache-intermediary-ignore-unmodified-since-because", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8453, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "A cache or intermediary MAY ignore If-Unmodified-Since because its interoperability features are only necessary for an origin server." }, { - "id": "oas-3.2.operation-object.externalDocs", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 682, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this operation." + "id": "rfc9110.13.1.4.may-client-send-unmodified-since-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8442, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", + "level": "MAY", + "terms": ["MAY"], + "text": "A client MAY send an If-Unmodified-Since header field in a GET request to indicate that it would prefer a 412 (Precondition Failed) response if the selected representation has been modified." }, { - "id": "oas-3.2.operation-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 692, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "fixed-fields-7", + "id": "rfc9110.13.1.4.may-instead-origin-server-indicate-conditional-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8421, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Instead, the origin server MAY indicate that the conditional request failed by responding with a 412 (Precondition Failed) status code." }, { - "id": "oas-3.2.operation-object.operationId", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 683, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-id", - "level": "field", - "terms": [], - "text": "Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + "id": "rfc9110.13.1.4.must-not-origin-server-evaluates-unmodified-since-condition", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8421, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "An origin server that evaluates an If-Unmodified-Since condition MUST NOT perform the requested method if the condition evaluates to false." }, { - "id": "oas-3.2.operation-object.operationId.must-id-unique-among-all-operations-described", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 683, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-id", + "id": "rfc9110.13.1.4.must-origin-server-receives-request-selects-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8402, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", "level": "MUST", "terms": ["MUST"], - "text": "The id MUST be unique among all operations described in the API." + "text": "When an origin server receives a request that selects a representation and that request includes an If-Unmodified-Since header field without an If-Match header field, the origin server MUST evaluate the If-Unmodified-Since condition per Section 13.2 prior to performing the method." }, { - "id": "oas-3.2.operation-object.operationId.recommended-tools-libraries-use-operationid-uniquely-identify", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 683, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-id", - "level": "SHOULD", - "terms": ["MAY", "RECOMMENDED"], - "text": "Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions." + "id": "rfc9110.13.1.4.must-recipient-ignore-unmodified-since-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8378, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST ignore the If-Unmodified-Since header field if the received field value is not a valid HTTP-date (including when the field value appears to be a list of dates)." }, { - "id": "oas-3.2.operation-object.parameters", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 684, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-parameters", - "level": "field", - "terms": [], - "text": "A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + "id": "rfc9110.13.1.4.must-recipient-ignore-unmodified-since-header-field-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8383, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST ignore the If-Unmodified-Since header field if the resource does not have a modification date available." }, { - "id": "oas-3.2.operation-object.parameters.must-not-list-include-duplicated-parameters", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 684, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-parameters", + "id": "rfc9110.13.1.4.must-recipient-ignore-unmodified-since-request-contains", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8370, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", "level": "MUST", - "terms": ["MUST NOT"], - "text": "The list MUST NOT include duplicated parameters." + "terms": ["MUST"], + "text": "A recipient MUST ignore If-Unmodified-Since if the request contains an If-Match header field; the condition in If-Match is considered to be a more accurate replacement for the condition in If-Unmodified-Since, and the two are only combined for the sake of interoperating with older intermediaries that might not implement If-Match." }, { - "id": "oas-3.2.operation-object.requestBody", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 685, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-request-body", - "level": "field", - "terms": [], - "text": "The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP specification RFC9110 has explicitly defined semantics for request bodies. In other cases where the HTTP spec discourages message content (such as GET and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." + "id": "rfc9110.13.1.4.must-recipient-interpret-unmodified-since-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8387, + "section": "Conditional Requests > Preconditions > If-Unmodified-Since", + "anchor": "section-13.1.4", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST interpret an If-Unmodified-Since field value's timestamp in terms of the origin server's clock." }, { - "id": "oas-3.2.operation-object.requestBody.should-other-cases-http-spec-discourages-message", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 685, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-request-body", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "In other cases where the HTTP spec discourages message content (such as GET and DELETE), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible." + "id": "rfc9110.13.1.5.must-not-client-generate-range-header-field-containing", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8502, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A client MUST NOT generate an If-Range header field containing an entity tag that is marked as weak." }, { - "id": "oas-3.2.operation-object.responses", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 686, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-responses", - "level": "field", - "terms": [], - "text": "The list of possible responses as they are returned from executing this operation." + "id": "rfc9110.13.1.5.must-not-client-generate-range-header-field-containing-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8502, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A client MUST NOT generate an If-Range header field containing an HTTP-date unless the client has no entity tag for the corresponding representation and the date is a strong validator in the sense defined by Section 8.8.2.2." }, { - "id": "oas-3.2.operation-object.security", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 689, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-security", - "level": "field", - "terms": [], - "text": "A declaration of which security mechanisms can be used for this operation. The list of values includes alternative Security Requirement Objects that can be used. Only one of the Security Requirement Objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level `security`. To remove a top-level security declaration, an empty array can be used." + "id": "rfc9110.13.1.5.must-not-client-generate-range-header-field-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8494, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A client MUST NOT generate an If-Range header field in a request that does not contain a Range header field." }, { - "id": "oas-3.2.operation-object.servers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 690, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-servers", - "level": "field", - "terms": [], - "text": "An alternative `servers` array to service this operation. If a `servers` array is specified at the Path Item Object or OpenAPI Object level, it will be overridden by this value." + "id": "rfc9110.13.1.5.must-origin-server-ignore-range-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8494, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST"], + "text": "An origin server MUST ignore an If-Range header field received in a request for a target resource that does not support Range requests." }, { - "id": "oas-3.2.operation-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 680, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-summary", - "level": "field", - "terms": [], - "text": "A short summary of what the operation does." + "id": "rfc9110.13.1.5.must-recipient-range-header-field-ignore-range", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8539, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient of an If-Range header field MUST ignore the Range header field if the If-Range condition evaluates to false." }, { - "id": "oas-3.2.operation-object.tags", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 679, - "section": "Objects and Fields > Operation Object > Fixed Fields", - "anchor": "operation-tags", - "level": "field", - "terms": [], - "text": "A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier." + "id": "rfc9110.13.1.5.must-server-ignore-range-header-field-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8494, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST"], + "text": "A server MUST ignore an If-Range header field received in a request that does not contain a Range header field." }, { - "id": "oas-3.2.parameter-object.allowEmptyValue", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 796, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "field", - "terms": [], - "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused. Default value is `false`. If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Interactions between this field and the parameter's Schema Object are implementation-defined. This field is valid only for `query` parameters. Deprecated: Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + "id": "rfc9110.13.1.5.must-server-receives-range-header-field-range", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8510, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", + "level": "MUST", + "terms": ["MUST"], + "text": "A server that receives an If-Range header field on a Range request MUST evaluate the condition per Section 13.2 prior to performing the method." }, { - "id": "oas-3.2.parameter-object.allowEmptyValue.not-recommended-deprecated-use-field-likely-removed-later", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 796, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", + "id": "rfc9110.13.1.5.should-otherwise-recipient-process-range-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8539, + "section": "Conditional Requests > Preconditions > If-Range", + "anchor": "section-13.1.5", "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Deprecated: Use of this field is NOT RECOMMENDED, and it is likely to be removed in a later revision." + "terms": ["SHOULD"], + "text": "Otherwise, the recipient SHOULD process the Range header field as requested." }, { - "id": "oas-3.2.parameter-object.allowEmptyValue.shall-style-used-behavior-n-cannot-serialized", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 796, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", + "id": "rfc9110.13.2.1.must-except-excluded-below-recipient-cache-origin", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8557, + "section": "Conditional Requests > Evaluation of Preconditions > When to Evaluate", + "anchor": "section-13.2.1", "level": "MUST", - "terms": ["SHALL"], - "text": "If `style` is used, and if behavior is _n/a_ (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored." + "terms": ["MUST"], + "text": "Except when excluded below, a recipient cache or origin server MUST evaluate received request preconditions after it has successfully performed its normal request checks and just before it would process the request content (if any) or perform the action associated with the request method." }, { - "id": "oas-3.2.parameter-object.allowEmptyValue.should-true-clients-pass-zero-length-string", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 796, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-allow-empty-value", - "level": "SHOULD", - "terms": ["MAY", "SHOULD"], - "text": "If `true`, clients MAY pass a zero-length string value in place of parameters that would otherwise be omitted entirely, which the server SHOULD interpret as the parameter being unused." + "id": "rfc9110.13.2.1.must-likewise-server-ignore-conditional-request-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8570, + "section": "Conditional Requests > Evaluation of Preconditions > When to Evaluate", + "anchor": "section-13.2.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Likewise, a server MUST ignore the conditional request header fields defined by this specification when received with a request method that does not involve the selection or modification of a selected representation, such as CONNECT, OPTIONS, or TRACE." }, { - "id": "oas-3.2.parameter-object.allowReserved", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 825, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-allow-reserved", - "level": "field", - "terms": [], - "text": "When this is true, parameter values are serialized using reserved expansion, as defined by RFC6570, which allows RFC3986's reserved character set, as well as percent-encoded triples, to pass through unchanged, while still percent-encoding all other disallowed characters (including `%` outside of percent-encoded triples). Applications are still responsible for percent-encoding reserved characters that are not allowed by the rules of the `in` destination or media type, or are not allowed in the path by this specification; see URL Percent-Encoding for details. The default value is `false`. This field only applies to `in` and `style` values that automatically percent-encode (that is: `in: path`, `in: query`, and `in: cookie` with `style: form`)." + "id": "rfc9110.13.2.1.must-not-server-not-origin-server-target-resource", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8570, + "section": "Conditional Requests > Evaluation of Preconditions > When to Evaluate", + "anchor": "section-13.2.1", + "level": "MUST", + "terms": ["MUST NOT", "MUST"], + "text": "A server that is not the origin server for the target resource and cannot act as a cache for requests on the target resource MUST NOT evaluate the conditional request header fields defined by this specification, and it MUST forward them if the request is forwarded, since the generating client intends that they be evaluated by a server that can provide a current representation." + }, + { + "id": "rfc9110.13.2.1.must-server-ignore-all-received-preconditions-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8557, + "section": "Conditional Requests > Evaluation of Preconditions > When to Evaluate", + "anchor": "section-13.2.1", + "level": "MUST", + "terms": ["MUST"], + "text": "A server MUST ignore all received preconditions if its response to the same request without those conditions, prior to processing the request content, would have been a status code other than a 2xx (Successful) or 412 (Precondition Failed)." + }, + { + "id": "rfc9110.13.2.2.must-recipient-cache-origin-server-evaluate-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8609, + "section": "Conditional Requests > Evaluation of Preconditions > Precedence of Preconditions", + "anchor": "section-13.2.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order:" + }, + { + "id": "rfc9110.14.1.2.must-since-no-predefined-limit-length-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8938, + "section": "Range Requests > Range Units > Byte Ranges", + "anchor": "section-14.1.2", + "level": "MUST", + "terms": ["MUST"], + "text": "Since there is no predefined limit to the length of content, recipients MUST anticipate potentially large decimal numerals and prevent parsing errors due to integer conversion overflows." + }, + { + "id": "rfc9110.14.2.may-proxy-discard-range-header-field-contains", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8974, + "section": "Range Requests > Range", + "anchor": "section-14.2", + "level": "MAY", + "terms": ["MAY"], + "text": "A proxy MAY discard a Range header field that contains a range unit it does not understand." }, { - "id": "oas-3.2.parameter-object.common-fixed-fields.may-fields-used-either-content-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 785, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields", + "id": "rfc9110.14.2.may-server-ignore-range-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8962, + "section": "Range Requests > Range", + "anchor": "section-14.2", "level": "MAY", "terms": ["MAY"], - "text": "These fields MAY be used with either `content` or `schema`." + "text": "A server MAY ignore the Range header field." }, { - "id": "oas-3.2.parameter-object.common-fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 800, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "common-fixed-fields", + "id": "rfc9110.14.2.may-server-supports-range-requests-ignore-range", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8991, + "section": "Range Requests > Range", + "anchor": "section-14.2", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "A server that supports range requests MAY ignore a Range header field when the selected representation has no content (i.e., the selected representation's data is of zero length)." }, { - "id": "oas-3.2.parameter-object.content", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 838, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "parameter-content", - "level": "field", - "terms": [], - "text": "A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry." + "id": "rfc9110.14.2.may-server-supports-range-requests-ignore-reject", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8979, + "section": "Range Requests > Range", + "anchor": "section-14.2", + "level": "MAY", + "terms": ["MAY"], + "text": "A server that supports range requests MAY ignore or reject a Range header field that contains an invalid ranges-specifier (Section 14.1.1), a ranges-specifier with more than two overlapping ranges, or a set of many small ranges that are not listed in ascending order, since these are indications of either a broken client or a deliberate denial-of-service attack (Section 17.15)." }, { - "id": "oas-3.2.parameter-object.content.must-map-only-contain-one-entry", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 838, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `content`", - "anchor": "parameter-content", + "id": "rfc9110.14.2.must-origin-server-ignore-range-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8974, + "section": "Range Requests > Range", + "anchor": "section-14.2", "level": "MUST", "terms": ["MUST"], - "text": "The map MUST only contain one entry." + "text": "An origin server MUST ignore a Range header field that contains a range unit it does not understand." }, { - "id": "oas-3.2.parameter-object.deprecated", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 795, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-deprecated", - "level": "field", - "terms": [], - "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`." + "id": "rfc9110.14.2.must-server-ignore-range-header-field-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8968, + "section": "Range Requests > Range", + "anchor": "section-14.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A server MUST ignore a Range header field received with a request method that is unrecognized or for which range handling is not defined." }, { - "id": "oas-3.2.parameter-object.deprecated.should-specifies-parameter-deprecated-transitioned-out-usage", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 795, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-deprecated", + "id": "rfc9110.14.2.should-all-preconditions-true-server-supports-range", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9016, + "section": "Range Requests > Range", + "anchor": "section-14.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage." + "text": "If all of the preconditions are true, the server supports the Range header field for the target resource, the received Range field-value contains a valid ranges-specifier with a range-unit supported for that target resource, and that ranges-specifier is satisfiable with respect to the selected representation, the server SHOULD send a 206 (Partial Content) response with content containing one or more partial representations that correspond to the satisfiable range-spec(s) requested." }, { - "id": "oas-3.2.parameter-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 793, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-description", - "level": "field", - "terms": [], - "text": "A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.14.2.should-all-preconditions-true-server-supports-range-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9034, + "section": "Range Requests > Range", + "anchor": "section-14.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If all of the preconditions are true, the server supports the Range header field for the target resource, the received Range field-value contains a valid ranges-specifier, and either the range-unit is not supported for that target resource or the ranges-specifier is unsatisfiable with respect to the selected representation, the server SHOULD send a 416 (Range Not Satisfiable) response." }, { - "id": "oas-3.2.parameter-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 793, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-description", + "id": "rfc9110.14.2.should-client-requesting-multiple-ranges-list-ranges", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8996, + "section": "Range Requests > Range", + "anchor": "section-14.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A client that is requesting multiple ranges SHOULD list those ranges in ascending order (the order in which they would typically be received in a complete representation) unless there is a specific need to request a later part earlier." + }, + { + "id": "rfc9110.14.2.should-not-client-request-multiple-ranges-inherently-less", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8979, + "section": "Range Requests > Range", + "anchor": "section-14.2", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A client SHOULD NOT request multiple ranges that are inherently less efficient to process and transfer than a single range that encompasses the same data." + }, + { + "id": "rfc9110.14.3.may-accept-ranges-field-sent-trailer-section", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9091, + "section": "Range Requests > Accept-Ranges", + "anchor": "section-14.3", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "The Accept-Ranges field MAY be sent in a trailer section, but is preferred to be sent as a header field because the information is particularly useful for restarting large information transfers that have failed in mid-content (before the trailer section is received)." }, { - "id": "oas-3.2.parameter-object.example", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 797, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-example", - "level": "field", - "terms": [], - "text": "Example of the parameter's potential value; see Working With Examples." + "id": "rfc9110.14.3.may-client-generate-range-requests-regardless-having", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9070, + "section": "Range Requests > Accept-Ranges", + "anchor": "section-14.3", + "level": "MAY", + "terms": ["MAY"], + "text": "A client MAY generate range requests regardless of having received an Accept-Ranges field." }, { - "id": "oas-3.2.parameter-object.examples", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 798, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-examples", - "level": "field", - "terms": [], - "text": "Examples of the parameter's potential value; see Working With Examples." + "id": "rfc9110.14.3.may-server-does-not-support-any-kind", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9081, + "section": "Range Requests > Accept-Ranges", + "anchor": "section-14.3", + "level": "MAY", + "terms": ["MAY"], + "text": "A server that does not support any kind of range request for the target resource MAY send" }, { - "id": "oas-3.2.parameter-object.explode", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 824, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-explode", - "level": "field", - "terms": [], - "text": "When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters, or when `style` is `\"deepObject\"`, this field has no effect. When `style` is `\"form\"` or `\"cookie\"`, the default value is `true`. For all other styles, the default value is `false`." + "id": "rfc9110.14.3.must-not-conversely-client-assume-receiving-accept-ranges", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9075, + "section": "Range Requests > Accept-Ranges", + "anchor": "section-14.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Conversely, a client MUST NOT assume that receiving an Accept-Ranges field means that future range requests will return partial responses." }, { - "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-cases-implementations-pass-values-through-unchanged", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 819, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "id": "rfc9110.14.4.must-not-206-partial-content-response-contains-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9127, + "section": "Range Requests > Content-Range", + "anchor": "section-14.4", "level": "MUST", - "terms": ["MUST"], - "text": "In these cases, implementations MUST pass values through unchanged rather than attempting to quote or escape them, as the quoting rules for headers and escaping conventions for cookies vary too widely to be performed automatically; see Appendix D for guidance on quoting and escaping." + "terms": ["MUST NOT"], + "text": "If a 206 (Partial Content) response contains a Content-Range header field with a range unit (Section 14.1) that the recipient does not understand, the recipient MUST NOT attempt to recombine it with a stored representation." }, { - "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-not-fields-used-querystring", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 808, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "id": "rfc9110.14.4.must-not-recipient-invalid-content-range-attempt-recombine", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9159, + "section": "Range Requests > Content-Range", + "anchor": "section-14.4", "level": "MUST", "terms": ["MUST NOT"], - "text": "These fields MUST NOT be used with `in: \"querystring\"`." + "text": "The recipient of an invalid Content-Range MUST NOT attempt to recombine the received content with a stored representation." }, { - "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-not-parsing-parameters-any-apparent-percent-encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 816, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "id": "rfc9110.14.4.must-server-ignore-content-range-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9134, + "section": "Range Requests > Content-Range", + "anchor": "section-14.4", "level": "MUST", - "terms": ["MUST NOT"], - "text": "When parsing these parameters, any apparent percent-encoding MUST NOT be decoded." + "terms": ["MUST"], + "text": "A server MUST ignore a Content-Range header field received in a request with a method for which Content-Range support is not defined." }, { - "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-not-serializing-values-uri-percent-encoding-applied", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 812, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "id": "rfc9110.14.4.should-byte-ranges-sender-indicate-complete-length", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9141, + "section": "Range Requests > Content-Range", + "anchor": "section-14.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "For byte ranges, a sender SHOULD indicate the complete length of the representation from which the range has been extracted, unless the complete length is unknown or difficult to determine." + }, + { + "id": "rfc9110.14.4.should-proxy-receives-message-forward-downstream", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9127, + "section": "Range Requests > Content-Range", + "anchor": "section-14.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A proxy that receives such a message SHOULD forward it downstream." + }, + { + "id": "rfc9110.14.4.should-server-generating-416-range-not-satisfiable", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9169, + "section": "Range Requests > Content-Range", + "anchor": "section-14.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A server generating a 416 (Range Not Satisfiable) response to a byte-range request SHOULD send a Content-Range header field with an unsatisfied-range value, as in the following example:" + }, + { + "id": "rfc9110.14.5.should-origin-server-respond-400-bad-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9229, + "section": "Range Requests > Partial PUT", + "anchor": "section-14.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server SHOULD respond with a 400 (Bad Request) status code if it receives Content-Range on a PUT for a target resource that does not support partial PUT requests." + }, + { + "id": "rfc9110.14.optional-range-requests-feature-http-designed-recipients", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 8706, + "section": "Range Requests", + "anchor": "section-14", + "level": "MAY", + "terms": ["OPTIONAL"], + "text": "Range requests are an OPTIONAL feature of HTTP, designed so that recipients not implementing this feature (or not supporting it for the target resource) can respond as if it is a normal GET request without impacting interoperability." + }, + { + "id": "rfc9110.15.2.2.must-server-generate-upgrade-header-field-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9490, + "section": "Status Codes > Informational 1xx > 101 Switching Protocols", + "anchor": "section-15.2.2", "level": "MUST", - "terms": ["MUST NOT"], - "text": "When serializing these values, URI percent-encoding MUST NOT be applied." + "terms": ["MUST"], + "text": "The server MUST generate an Upgrade header field in the response that indicates which protocol(s) will be in effect after this response." }, { - "id": "oas-3.2.parameter-object.fixed-fields-for-use-with-schema.must-using-rfc6570-implementation-automatically-performs-encoding", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 817, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "fixed-fields-for-use-with-schema", + "id": "rfc9110.15.2.may-user-agent-ignore-unexpected-1xx-responses", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9453, + "section": "Status Codes > Informational 1xx", + "anchor": "section-15.2", + "level": "MAY", + "terms": ["MAY"], + "text": "A user agent MAY ignore unexpected 1xx responses." + }, + { + "id": "rfc9110.15.2.must-client-able-parse-one-more-1xx", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9453, + "section": "Status Codes > Informational 1xx", + "anchor": "section-15.2", "level": "MUST", "terms": ["MUST"], - "text": "If using an RFC6570 implementation that automatically performs encoding or decoding steps, the steps MUST be undone before use." + "text": "A client MUST be able to parse one or more 1xx responses received prior to a final response, even if the client does not expect one." }, { - "id": "oas-3.2.parameter-object.fixed-fields.must-parameter-objects-include-either-content-field", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 779, - "section": "Objects and Fields > Parameter Object > Fixed Fields", - "anchor": "fixed-fields-9", + "id": "rfc9110.15.2.must-not-since-http-1-0-did-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9442, + "section": "Status Codes > Informational 1xx", + "anchor": "section-15.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "Since HTTP/1.0 did not define any 1xx status codes, a server MUST NOT send a 1xx response to an HTTP/1.0 client." + }, + { + "id": "rfc9110.15.2.must-proxy-forward-1xx-responses-unless-proxy", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9458, + "section": "Status Codes > Informational 1xx", + "anchor": "section-15.2", "level": "MUST", "terms": ["MUST"], - "text": "Parameter Objects MUST include either a `content` field or a `schema` field, but not both." + "text": "A proxy MUST forward 1xx responses unless the proxy itself requested the generation of the 1xx response." }, { - "id": "oas-3.2.parameter-object.in", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 792, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-in", - "level": "field", - "terms": [], - "text": "REQUIRED. The location of the parameter. Possible values are `\"query\"`, `\"querystring\"`, `\"header\"`, `\"path\"` or `\"cookie\"`." + "id": "rfc9110.15.3.1.should-200-responses-get-head-origin-server", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9574, + "section": "Status Codes > Successful 2xx > 200 OK", + "anchor": "section-15.3.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "In 200 responses to GET or HEAD, an origin server SHOULD send any available validator fields (Section 8.8) for the selected representation, with both a strong entity tag and a Last-Modified date being preferred." }, { - "id": "oas-3.2.parameter-object.in.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 792, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-in", + "id": "rfc9110.15.3.6.must-not-since-205-status-code-implies-no", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9706, + "section": "Status Codes > Successful 2xx > 205 Reset Content", + "anchor": "section-15.3.6", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "Since the 205 status code implies that no additional content will be provided, a server MUST NOT generate content in a 205 response." }, { - "id": "oas-3.2.parameter-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 791, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the parameter. Parameter names are _case-sensitive_. If `in` is `\"path\"`, the `name` field MUST correspond to a single template expression occurring within the path field in the Paths Object. See Path Templating for further information. If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored. If `in` is `\"querystring\"`, or for certain combinations of `style` and `explode`, the value of `name` is not used in the parameter serialization. For all other cases, the `name` corresponds to the parameter name used by the `in` field." + "id": "rfc9110.15.3.7.1.must-single-part-being-transferred-server-generating", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9766, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Single Part", + "anchor": "section-15.3.7.1", + "level": "MUST", + "terms": ["MUST"], + "text": "If a single part is being transferred, the server generating the 206 response MUST generate a Content-Range header field, describing what range of the selected representation is enclosed, and a content consisting of the range." }, { - "id": "oas-3.2.parameter-object.name.must-path-name-field-correspond-single-template", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 791, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", + "id": "rfc9110.15.3.7.2.may-however-server-generate-multipart-byteranges-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9832, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", + "level": "MAY", + "terms": ["MAY"], + "text": "However, a server MAY generate a \"multipart/byteranges\" response with only a single body part if multiple ranges were requested and only one range was found to be satisfiable or only one range remained after coalescing." + }, + { + "id": "rfc9110.15.3.7.2.may-multiple-ranges-requested-server-coalesce-any", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9821, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", + "level": "MAY", + "terms": ["MAY"], + "text": "When multiple ranges are requested, a server MAY coalesce any of the ranges that overlap, or that are separated by a gap that is smaller than the overhead of sending multiple parts, regardless of the order in which the corresponding range-spec appeared in the received Range header field." + }, + { + "id": "rfc9110.15.3.7.2.must-client-receives-multipart-response-inspect-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9842, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A client that receives a multipart response MUST inspect the Content-Range header field present in each body part in order to determine which range is contained in that body part; a client cannot rely on receiving the same ranges that it requested, nor the same order that it requested." + }, + { + "id": "rfc9110.15.3.7.2.must-multiple-parts-being-transferred-server-generating", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9784, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", "level": "MUST", "terms": ["MUST"], - "text": "If `in` is `\"path\"`, the `name` field MUST correspond to a single template expression occurring within the path field in the Paths Object." + "text": "If multiple parts are being transferred, the server generating the 206 response MUST generate \"multipart/byteranges\" content, as defined in Section 14.6, and a Content-Type header field containing the \"multipart/byteranges\" media type and its required boundary parameter." }, { - "id": "oas-3.2.parameter-object.name.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 791, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", + "id": "rfc9110.15.3.7.2.must-not-avoid-confusion-single-part-responses-server", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9784, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "To avoid confusion with single-part responses, a server MUST NOT generate a Content-Range header field in the HTTP header section of a multiple part response (this field will be sent in each part instead)." }, { - "id": "oas-3.2.parameter-object.name.shall-header-name-field-accept-content-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 791, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-name", + "id": "rfc9110.15.3.7.2.must-not-client-cannot-process-multipart-byteranges-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9832, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", "level": "MUST", - "terms": ["SHALL"], - "text": "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored." + "terms": ["MUST NOT"], + "text": "A client that cannot process a \"multipart/byteranges\" response MUST NOT generate a request that asks for multiple ranges." }, { - "id": "oas-3.2.parameter-object.parameter-locations.must-not-query-parameters-appended-url-character-subsequent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 772, - "section": "Objects and Fields > Parameter Object > Parameter Locations", - "anchor": "parameter-locations", + "id": "rfc9110.15.3.7.2.must-not-server-generate-multipart-response-request-single", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9832, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", "level": "MUST", "terms": ["MUST NOT"], - "text": "query - Parameters that are appended to the URL with the `?` character (or for subsequent query parameters, with the `&` character); MUST NOT appear in the same operation (or in the operation's path-item) as an `in: \"querystring\"` parameter." + "text": "A server MUST NOT generate a multipart response to a request for a single range, since a client that does not request multiple parts might not support multipart responses." }, { - "id": "oas-3.2.parameter-object.parameter-locations.must-querystring-parameter-treats-entire-url-query", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 773, - "section": "Objects and Fields > Parameter Object > Parameter Locations", - "anchor": "parameter-locations", + "id": "rfc9110.15.3.7.2.must-within-header-area-each-body-part", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9794, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", "level": "MUST", - "terms": ["MUST", "MUST NOT"], - "text": "querystring - A parameter that treats the entire URL query string as a value which MUST be specified using the `content` field, most often with media type `application/x-www-form-urlencoded` using Encoding Objects in the same way as with request bodies of that media type; MUST NOT appear more than once, and MUST NOT appear in the same operation (or in the operation's path-item) as any `in: \"query\"` parameters." + "terms": ["MUST"], + "text": "Within the header area of each body part in the multipart content, the server MUST generate a Content-Range header field corresponding to the range being enclosed in that body part." }, { - "id": "oas-3.2.parameter-object.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 794, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", - "level": "field", - "terms": [], - "text": "Determines whether this parameter is mandatory. If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`. Otherwise, the field MAY be included and its default value is `false`." + "id": "rfc9110.15.3.7.2.should-selected-representation-would-have-had-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9794, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the selected representation would have had a Content-Type header field in a 200 (OK) response, the server SHOULD generate that same Content-Type header field in the header area of each body part." }, { - "id": "oas-3.2.parameter-object.required.may-otherwise-field-included-default-value-false", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 794, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", + "id": "rfc9110.15.3.7.2.should-server-generates-multipart-response-send-parts", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9842, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Multiple Parts", + "anchor": "section-15.3.7.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A server that generates a multipart response SHOULD send the parts in the same order that the corresponding range-spec appeared in the received Range header field, excluding those ranges that were deemed unsatisfiable or that were coalesced into other ranges." + }, + { + "id": "rfc9110.15.3.7.3.may-client-received-multiple-partial-responses-get", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9864, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Combining Parts", + "anchor": "section-15.3.7.3", "level": "MAY", "terms": ["MAY"], - "text": "Otherwise, the field MAY be included and its default value is `false`." + "text": "A client that has received multiple partial responses to GET requests on a target resource MAY combine those responses into a larger continuous range if they share the same strong validator." }, { - "id": "oas-3.2.parameter-object.required.required-parameter-location-path-field-value-true", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 794, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Common Fixed Fields", - "anchor": "parameter-required", + "id": "rfc9110.15.3.7.3.must-all-matching-stored-responses-206-responses", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9874, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Combining Parts", + "anchor": "section-15.3.7.3", "level": "MUST", - "terms": ["REQUIRED", "MUST"], - "text": "If the parameter location is `\"path\"`, this field is REQUIRED and its value MUST be `true`." + "terms": ["MUST"], + "text": "If all of the matching stored responses are 206 responses, then the stored response with the most recent header fields is used as the source of header fields for the combined response, except that the client MUST use other header fields provided in the new response, aside from Content-Range, to replace all instances of the corresponding header fields in the stored response." }, { - "id": "oas-3.2.parameter-object.schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 826, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-schema", - "level": "field", - "terms": [], - "text": "The schema defining the type and other constraints used for the parameter." + "id": "rfc9110.15.3.7.3.must-otherwise-client-process-set-continuous-ranges", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9886, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Combining Parts", + "anchor": "section-15.3.7.3", + "level": "MUST", + "terms": ["MUST"], + "text": "Otherwise, the client MUST process the set of continuous ranges as one of the following: an incomplete 200 (OK) response if the combined response is a prefix of the representation, a single 206 (Partial Content) response containing \"multipart/byteranges\" content, or multiple 206 (Partial Content) responses, each with one continuous range that is indicated by a Content-Range header field." }, { - "id": "oas-3.2.parameter-object.serialization-and-examples.must-cases-parameter-name-inherent-part-constructing", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 891, - "section": "Objects and Fields > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", + "id": "rfc9110.15.3.7.3.must-union-consists-entire-range-representation-client", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9886, + "section": "Status Codes > Successful 2xx > 206 Partial Content > Combining Parts", + "anchor": "section-15.3.7.3", "level": "MUST", "terms": ["MUST"], - "text": "In cases where the parameter name is an inherent part of constructing the serialization, such as the `name=value` pairs produced by the combination of `style: \"form\", explode: false`, the name and any delimiter between the name and value MUST be included." + "text": "If the union consists of the entire range of the representation, then the client MUST process the combined response as if it were a complete 200 (OK) response, including a Content-Length header field that reflects the complete length." }, { - "id": "oas-3.2.parameter-object.serialization-and-examples.must-matrix-label-styles-produce-leading-delimiter", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 893, - "section": "Objects and Fields > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", + "id": "rfc9110.15.3.7.must-client-inspect-206-response-s-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9730, + "section": "Status Codes > Successful 2xx > 206 Partial Content", + "anchor": "section-15.3.7", "level": "MUST", "terms": ["MUST"], - "text": "The `matrix` and `label` styles produce a leading delimiter which is always a valid part of the serialization and MUST be included." + "text": "A client MUST inspect a 206 response's Content-Type and Content-Range field(s) to determine what parts are enclosed and whether additional requests are needed." }, { - "id": "oas-3.2.parameter-object.serialization-and-examples.must-not-headers-header-name-included-part-serialization", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 898, - "section": "Objects and Fields > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", + "id": "rfc9110.15.3.7.must-otherwise-sender-generate-all-representation-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9751, + "section": "Status Codes > Successful 2xx > 206 Partial Content", + "anchor": "section-15.3.7", "level": "MUST", - "terms": ["MUST NOT"], - "text": "For headers, the header name MUST NOT be included as part of the serialization, as it is never part of the RFC6570-derived result." + "terms": ["MUST"], + "text": "Otherwise, a sender MUST generate all of the representation header fields that would have been sent in a 200 (OK) response to the same request." }, { - "id": "oas-3.2.parameter-object.serialization-and-examples.must-not-suitability-either-delimiter-depends-query-string", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 893, - "section": "Objects and Fields > Parameter Object > Serialization and Examples", - "anchor": "serialization-and-examples", + "id": "rfc9110.15.3.7.must-server-generates-206-response-generate-following", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9735, + "section": "Status Codes > Successful 2xx > 206 Partial Content", + "anchor": "section-15.3.7", "level": "MUST", - "terms": ["MUST NOT"], - "text": "As the suitability of either delimiter depends on where in the query string the parameter occurs, as well as whether it is in a URI or in `application/x-www-form-urlencoded` content, this leading delimiter MUST NOT be included in examples of individual parameters or media type documents." + "terms": ["MUST"], + "text": "A server that generates a 206 response MUST generate the following header fields, in addition to those required in the subsections below, if the field would have been sent in a 200 (OK) response to the same request: Date, Cache-Control, ETag, Expires, Content-Location, and Vary." }, { - "id": "oas-3.2.parameter-object.style", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 823, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-style", - "level": "field", - "terms": [], - "text": "Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"` (for compatibility reasons; note that `style: \"cookie\"` SHOULD be used with `in: \"cookie\"`; see Appendix D for details)." + "id": "rfc9110.15.3.7.should-not-sender-generates-206-response-request-range", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9751, + "section": "Status Codes > Successful 2xx > 206 Partial Content", + "anchor": "section-15.3.7", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A sender that generates a 206 response to a request with an If-Range header field SHOULD NOT generate other representation header fields beyond those required because the client already has a prior response containing those header fields." }, { - "id": "oas-3.2.parameter-object.style-values.must-analogous-form-but-following-rfc6265-cookie", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 853, - "section": "Objects and Fields > Parameter Object > Style Values", - "anchor": "style-values", - "level": "MUST", - "terms": ["MUST"], - "text": "Analogous to `form`, but following [RFC6265] `Cookie` syntax rules, meaning that name-value pairs are separated by a semicolon followed by a single space (e.g. `n1=v1; n2=v2`), and no percent-encoding or other escaping is applied; data values that require any sort of escaping MUST be provided in escaped form." + "id": "rfc9110.15.4.1.may-user-agent-make-selection-list-automatically", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10054, + "section": "Status Codes > Redirection 3xx > 300 Multiple Choices", + "anchor": "section-15.4.1", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY make a selection from that list automatically if it understands the provided media type." }, { - "id": "oas-3.2.parameter-object.style.should-default-values-based-value-query-form", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 823, - "section": "Objects and Fields > Parameter Object > Fixed Fields > Fixed Fields for use with `schema`", - "anchor": "parameter-style", + "id": "rfc9110.15.4.1.may-user-agent-use-location-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10048, + "section": "Status Codes > Redirection 3xx > 300 Multiple Choices", + "anchor": "section-15.4.1", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY use the Location field value for automatic redirection." + }, + { + "id": "rfc9110.15.4.1.should-request-methods-other-head-server-generate", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10054, + "section": "Status Codes > Redirection 3xx > 300 Multiple Choices", + "anchor": "section-15.4.1", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Default values (based on value of `in`): for `\"query\"` - `\"form\"`; for `\"path\"` - `\"simple\"`; for `\"header\"` - `\"simple\"`; for `\"cookie\"` - `\"form\"` (for compatibility reasons; note that `style: \"cookie\"` SHOULD be used with `in: \"cookie\"`; see Appendix D for details)." + "text": "For request methods other than HEAD, the server SHOULD generate content in the 300 response containing a list of representation metadata and URI reference(s) from which the user or user agent can choose the one most preferred." }, { - "id": "oas-3.2.parameter-object.url-percent-encoding.must-all-api-urls-successfully-parse-percent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 857, - "section": "Objects and Fields > Parameter Object > URL Percent-Encoding", - "anchor": "url-percent-encoding", + "id": "rfc9110.15.4.1.should-server-preferred-choice-server-generate-location", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10048, + "section": "Status Codes > Redirection 3xx > 300 Multiple Choices", + "anchor": "section-15.4.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the server has a preferred choice, the server SHOULD generate a Location header field containing a preferred choice's URI reference." + }, + { + "id": "rfc9110.15.4.2.may-note-historical-reasons-user-agent-change", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10105, + "section": "Status Codes > Redirection 3xx > 301 Moved Permanently", + "anchor": "section-15.4.2", + "level": "MAY", + "terms": ["MAY"], + "text": "Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request." + }, + { + "id": "rfc9110.15.4.2.may-user-agent-use-location-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10097, + "section": "Status Codes > Redirection 3xx > 301 Moved Permanently", + "anchor": "section-15.4.2", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY use the Location field value for automatic redirection." + }, + { + "id": "rfc9110.15.4.2.should-server-generate-location-header-field-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10097, + "section": "Status Codes > Redirection 3xx > 301 Moved Permanently", + "anchor": "section-15.4.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI." + }, + { + "id": "rfc9110.15.4.3.may-note-historical-reasons-user-agent-change", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10134, + "section": "Status Codes > Redirection 3xx > 302 Found", + "anchor": "section-15.4.3", + "level": "MAY", + "terms": ["MAY"], + "text": "Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request." + }, + { + "id": "rfc9110.15.4.3.may-user-agent-use-location-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10126, + "section": "Status Codes > Redirection 3xx > 302 Found", + "anchor": "section-15.4.3", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY use the Location field value for automatic redirection." + }, + { + "id": "rfc9110.15.4.3.should-server-generate-location-header-field-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10126, + "section": "Status Codes > Redirection 3xx > 302 Found", + "anchor": "section-15.4.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate a Location header field in the response containing a URI reference for the different URI." + }, + { + "id": "rfc9110.15.4.5.must-server-generating-304-response-generate-any", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10195, + "section": "Status Codes > Redirection 3xx > 304 Not Modified", + "anchor": "section-15.4.5", "level": "MUST", "terms": ["MUST"], - "text": "All API URLs MUST successfully parse and percent-decode using [RFC3986] rules." + "text": "The server generating a 304 response MUST generate any of the following header fields that would have been sent in a 200 (OK) response to the same request:" }, { - "id": "oas-3.2.parameter-object.url-percent-encoding.must-content-application-x-www-form-urlencoded", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 859, - "section": "Objects and Fields > Parameter Object > URL Percent-Encoding", - "anchor": "url-percent-encoding", + "id": "rfc9110.15.4.5.should-conditional-request-originated-outbound-client-user", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10218, + "section": "Status Codes > Redirection 3xx > 304 Not Modified", + "anchor": "section-15.4.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the conditional request originated with an outbound client, such as a user agent with its own cache sending a conditional GET to a shared proxy, then the proxy SHOULD forward the 304 response to that client." + }, + { + "id": "rfc9110.15.4.5.should-not-since-goal-304-response-minimize-information", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10210, + "section": "Status Codes > Redirection 3xx > 304 Not Modified", + "anchor": "section-15.4.5", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Since the goal of a 304 response is to minimize information transfer when the recipient already has one or more cached representations, a sender SHOULD NOT generate representation metadata other than the above listed fields unless said metadata exists for the purpose of guiding cache updates (e.g., Last-Modified might be useful if the response does not have an ETag field)." + }, + { + "id": "rfc9110.15.4.8.may-user-agent-use-location-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10257, + "section": "Status Codes > Redirection 3xx > 307 Temporary Redirect", + "anchor": "section-15.4.8", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY use the Location field value for automatic redirection." + }, + { + "id": "rfc9110.15.4.8.must-not-307-temporary-redirect-status-code-indicates", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10249, + "section": "Status Codes > Redirection 3xx > 307 Temporary Redirect", + "anchor": "section-15.4.8", "level": "MUST", - "terms": ["MUST"], - "text": "Content in the `application/x-www-form-urlencoded` format, including query strings produced by Parameter Objects with `in: \"query\"`, MUST also successfully parse and percent-decode using [WHATWG-URL] rules, including treating non-percent-encoded `+` as an escaped space character." + "terms": ["MUST NOT"], + "text": "The 307 (Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI." + }, + { + "id": "rfc9110.15.4.8.should-server-generate-location-header-field-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10257, + "section": "Status Codes > Redirection 3xx > 307 Temporary Redirect", + "anchor": "section-15.4.8", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate a Location header field in the response containing a URI reference for the different URI." + }, + { + "id": "rfc9110.15.4.9.may-user-agent-use-location-field-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10279, + "section": "Status Codes > Redirection 3xx > 308 Permanent Redirect", + "anchor": "section-15.4.9", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY use the Location field value for automatic redirection." + }, + { + "id": "rfc9110.15.4.9.should-server-generate-location-header-field-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10279, + "section": "Status Codes > Redirection 3xx > 308 Permanent Redirect", + "anchor": "section-15.4.9", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate a Location header field in the response containing a preferred URI reference for the new permanent URI." + }, + { + "id": "rfc9110.15.4.may-location-header-field-section-10-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9957, + "section": "Status Codes > Redirection 3xx", + "anchor": "section-15.4", + "level": "MAY", + "terms": ["MAY"], + "text": "If a Location header field (Section 10.2.2) is provided, the user agent MAY automatically redirect its request to the URI referenced by the Location field value, even if the specific status code is not understood." + }, + { + "id": "rfc9110.15.4.should-automatically-following-redirected-request-user-agent", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9966, + "section": "Status Codes > Redirection 3xx", + "anchor": "section-15.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "When automatically following a redirected request, the user agent SHOULD resend the original request message with the following modifications:" + }, + { + "id": "rfc9110.15.4.should-client-detect-intervene-cyclical-redirections-i", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10023, + "section": "Status Codes > Redirection 3xx", + "anchor": "section-15.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A client SHOULD detect and intervene in cyclical redirections (i.e., \"infinite\" redirection loops)." + }, + { + "id": "rfc9110.15.5.10.should-server-generate-content-includes-enough-information", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10462, + "section": "Status Codes > Client Error 4xx > 409 Conflict", + "anchor": "section-15.5.10", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate content that includes enough information for a user to recognize the source of the conflict." + }, + { + "id": "rfc9110.15.5.12.may-client-repeat-request-adds-valid-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10510, + "section": "Status Codes > Client Error 4xx > 411 Length Required", + "anchor": "section-15.5.12", + "level": "MAY", + "terms": ["MAY"], + "text": "The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the request content." + }, + { + "id": "rfc9110.15.5.14.may-server-terminate-request-protocol-version-use", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10534, + "section": "Status Codes > Client Error 4xx > 413 Content Too Large", + "anchor": "section-15.5.14", + "level": "MAY", + "terms": ["MAY"], + "text": "The server MAY terminate the request, if the protocol version in use allows it; otherwise, the server MAY close the connection." + }, + { + "id": "rfc9110.15.5.14.should-condition-temporary-server-generate-retry-after", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10541, + "section": "Status Codes > Client Error 4xx > 413 Content Too Large", + "anchor": "section-15.5.14", + "level": "SHOULD", + "terms": ["SHOULD", "MAY"], + "text": "If the condition is temporary, the server SHOULD generate a Retry-After header field to indicate that it is temporary and after what time the client MAY try again." }, { - "id": "oas-3.2.parameter-object.url-percent-encoding.must-not-reserved-characters-percent-encoded-being-used", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 875, - "section": "Objects and Fields > Parameter Object > URL Percent-Encoding", - "anchor": "url-percent-encoding", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "Reserved characters MUST NOT be percent-encoded when being used for reserved purposes such as `&=+` for `form-urlencoded` or `,` for delimiting non-exploded array and object values in RFC6570 expansions." + "id": "rfc9110.15.5.17.should-server-generates-416-response-byte-range", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10609, + "section": "Status Codes > Client Error 4xx > 416 Range Not Satisfiable", + "anchor": "section-15.5.17", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A server that generates a 416 response to a byte-range request SHOULD generate a Content-Range header field specifying the current length of the selected representation (Section 14.4)." }, { - "id": "oas-3.2.path-item-object.$ref", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 599, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-ref", - "level": "field", - "terms": [], - "text": "Allows for a referenced definition of this path item. The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object. In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving Relative References. _Note: The behavior of `$ref` with adjacent properties is likely to change in future versions of this specification to bring it into closer alignment with the behavior of the Reference Object._" + "id": "rfc9110.15.5.2.may-user-agent-repeat-request-new-replaced", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10333, + "section": "Status Codes > Client Error 4xx > 401 Unauthorized", + "anchor": "section-15.5.2", + "level": "MAY", + "terms": ["MAY"], + "text": "The user agent MAY repeat the request with a new or replaced Authorization header field (Section 11.6.2)." }, { - "id": "oas-3.2.path-item-object.$ref.must-value-form-uri-referenced-structure-form", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 599, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-ref", + "id": "rfc9110.15.5.2.must-server-generating-401-response-send-www", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10324, + "section": "Status Codes > Client Error 4xx > 401 Unauthorized", + "anchor": "section-15.5.2", "level": "MUST", "terms": ["MUST"], - "text": "The value MUST be in the form of a URI, and the referenced structure MUST be in the form of a Path Item Object." + "text": "The server generating a 401 response MUST send a WWW-Authenticate header field (Section 11.6.1) containing at least one challenge applicable to the target resource." }, { - "id": "oas-3.2.path-item-object.additionalOperations", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 611, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-additional-operations", - "level": "field", - "terms": [], - "text": "A map of additional operations on this path. The map key is the HTTP method with the same capitalization that is to be sent in the request. This map MUST NOT contain any entry for the methods that can be defined by other fixed fields with Operation Object values (e.g. no `POST` entry, as the `post` field is used for this method)." + "id": "rfc9110.15.5.2.should-401-response-contains-same-challenge-prior", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10333, + "section": "Status Codes > Client Error 4xx > 401 Unauthorized", + "anchor": "section-15.5.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information." }, { - "id": "oas-3.2.path-item-object.additionalOperations.must-not-map-contain-any-entry-methods-defined", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 611, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-additional-operations", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "This map MUST NOT contain any entry for the methods that can be defined by other fixed fields with Operation Object values (e.g. no `POST` entry, as the `post` field is used for this method)." + "id": "rfc9110.15.5.20.may-client-receives-421-misdirected-request-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10675, + "section": "Status Codes > Client Error 4xx > 421 Misdirected Request", + "anchor": "section-15.5.20", + "level": "MAY", + "terms": ["MAY"], + "text": "A client that receives a 421 (Misdirected Request) response MAY retry the request, whether or not the request method is idempotent, over a different connection, such as a fresh connection specific to the target resource's origin, or via an alternative service [ALTSVC]." }, { - "id": "oas-3.2.path-item-object.delete", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 605, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-delete", - "level": "field", - "terms": [], - "text": "A definition of a DELETE operation on this path." + "id": "rfc9110.15.5.20.must-not-proxy-generate-421-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10681, + "section": "Status Codes > Client Error 4xx > 421 Misdirected Request", + "anchor": "section-15.5.20", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT generate a 421 response." }, { - "id": "oas-3.2.path-item-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 601, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-description", - "level": "field", - "terms": [], - "text": "An optional string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.15.5.22.must-server-send-upgrade-header-field-426", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10701, + "section": "Status Codes > Client Error 4xx > 426 Upgrade Required", + "anchor": "section-15.5.22", + "level": "MUST", + "terms": ["MUST"], + "text": "The server MUST send an Upgrade header field in a 426 response to indicate the required protocol(s) (Section 7.8)." }, { - "id": "oas-3.2.path-item-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 601, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-description", + "id": "rfc9110.15.5.4.may-client-repeat-request-new-different-credentials", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10361, + "section": "Status Codes > Client Error 4xx > 403 Forbidden", + "anchor": "section-15.5.4", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "The client MAY repeat the request with new or different credentials." }, { - "id": "oas-3.2.path-item-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 615, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "fixed-fields-6", + "id": "rfc9110.15.5.4.may-origin-server-wishes-hide-current-existence", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10370, + "section": "Status Codes > Client Error 4xx > 403 Forbidden", + "anchor": "section-15.5.4", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "An origin server that wishes to \"hide\" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found)." }, { - "id": "oas-3.2.path-item-object.get", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 602, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-get", - "level": "field", - "terms": [], - "text": "A definition of a GET operation on this path." + "id": "rfc9110.15.5.4.should-not-client-automatically-repeat-request-same-credentials", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10361, + "section": "Status Codes > Client Error 4xx > 403 Forbidden", + "anchor": "section-15.5.4", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "The client SHOULD NOT automatically repeat the request with the same credentials." }, { - "id": "oas-3.2.path-item-object.head", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 607, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-head", - "level": "field", - "terms": [], - "text": "A definition of a HEAD operation on this path." + "id": "rfc9110.15.5.6.must-origin-server-generate-allow-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10397, + "section": "Status Codes > Client Error 4xx > 405 Method Not Allowed", + "anchor": "section-15.5.6", + "level": "MUST", + "terms": ["MUST"], + "text": "The origin server MUST generate an Allow header field in a 405 response containing a list of the target resource's currently supported methods." }, { - "id": "oas-3.2.path-item-object.may-path-item-empty-due-acl-constraints", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 591, - "section": "Objects and Fields > Path Item Object", - "anchor": "path-item-object", + "id": "rfc9110.15.5.7.may-user-agent-automatically-select-most-appropriate", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10421, + "section": "Status Codes > Client Error 4xx > 406 Not Acceptable", + "anchor": "section-15.5.7", "level": "MAY", "terms": ["MAY"], - "text": "A Path Item MAY be empty, due to ACL constraints." + "text": "A user agent MAY automatically select the most appropriate choice from that list." }, { - "id": "oas-3.2.path-item-object.options", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 606, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-options", - "level": "field", - "terms": [], - "text": "A definition of a OPTIONS operation on this path." + "id": "rfc9110.15.5.7.should-server-generate-content-containing-list-available", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10421, + "section": "Status Codes > Client Error 4xx > 406 Not Acceptable", + "anchor": "section-15.5.7", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate content containing a list of available representation characteristics and corresponding resource identifiers from which the user or user agent can choose the one most appropriate." }, { - "id": "oas-3.2.path-item-object.parameters", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 613, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-parameters", - "level": "field", - "terms": [], - "text": "A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined in the OpenAPI Object's `components.parameters`." + "id": "rfc9110.15.5.8.may-client-repeat-request-new-replaced-proxy", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10433, + "section": "Status Codes > Client Error 4xx > 407 Proxy Authentication Required", + "anchor": "section-15.5.8", + "level": "MAY", + "terms": ["MAY"], + "text": "The client MAY repeat the request with a new or replaced Proxy-Authorization header field (Section 11.7.2)." }, { - "id": "oas-3.2.path-item-object.parameters.must-not-list-include-duplicated-parameters", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 613, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-parameters", + "id": "rfc9110.15.5.8.must-proxy-send-proxy-authenticate-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10433, + "section": "Status Codes > Client Error 4xx > 407 Proxy Authentication Required", + "anchor": "section-15.5.8", "level": "MUST", - "terms": ["MUST NOT"], - "text": "The list MUST NOT include duplicated parameters." + "terms": ["MUST"], + "text": "The proxy MUST send a Proxy-Authenticate header field (Section 11.7.1) containing a challenge applicable to that proxy for the request." }, { - "id": "oas-3.2.path-item-object.patch", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 608, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-patch", - "level": "field", - "terms": [], - "text": "A definition of a PATCH operation on this path." + "id": "rfc9110.15.5.9.may-client-outstanding-request-transit-repeat-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10452, + "section": "Status Codes > Client Error 4xx > 408 Request Timeout", + "anchor": "section-15.5.9", + "level": "MAY", + "terms": ["MAY"], + "text": "If the client has an outstanding request in transit, it MAY repeat that request." }, { - "id": "oas-3.2.path-item-object.post", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 604, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-post", - "level": "field", - "terms": [], - "text": "A definition of a POST operation on this path." + "id": "rfc9110.15.5.should-except-responding-head-request-server-send", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10303, + "section": "Status Codes > Client Error 4xx", + "anchor": "section-15.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition." }, { - "id": "oas-3.2.path-item-object.put", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 603, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-put", - "level": "field", - "terms": [], - "text": "A definition of a PUT operation on this path." + "id": "rfc9110.15.5.should-user-agents-display-any-included-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10303, + "section": "Status Codes > Client Error 4xx", + "anchor": "section-15.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "User agents SHOULD display any included representation to the user." }, { - "id": "oas-3.2.path-item-object.query", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 610, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-query", - "level": "field", - "terms": [], - "text": "A definition of a QUERY operation, as defined in RFC10008, on this path." + "id": "rfc9110.15.6.4.may-server-send-retry-after-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10770, + "section": "Status Codes > Server Error 5xx > 503 Service Unavailable", + "anchor": "section-15.6.4", + "level": "MAY", + "terms": ["MAY"], + "text": "The server MAY send a Retry-After header field (Section 10.2.3) to suggest an appropriate amount of time for the client to wait before retrying the request." }, { - "id": "oas-3.2.path-item-object.servers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 612, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-servers", - "level": "field", - "terms": [], - "text": "An alternative `servers` array to service all operations in this path. If a `servers` array is specified at the OpenAPI Object level, it will be overridden by this value." + "id": "rfc9110.15.6.6.should-server-generate-representation-505-response-describes", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10799, + "section": "Status Codes > Server Error 5xx > 505 HTTP Version Not Supported", + "anchor": "section-15.6.6", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The server SHOULD generate a representation for the 505 response that describes why that version is not supported and what other protocols are supported by that server." }, { - "id": "oas-3.2.path-item-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 600, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-summary", - "level": "field", - "terms": [], - "text": "An optional string summary, intended to apply to all operations in this path." + "id": "rfc9110.15.6.should-except-responding-head-request-server-send", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10725, + "section": "Status Codes > Server Error 5xx", + "anchor": "section-15.6", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition." }, { - "id": "oas-3.2.path-item-object.trace", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 609, - "section": "Objects and Fields > Path Item Object > Fixed Fields", - "anchor": "path-item-trace", - "level": "field", - "terms": [], - "text": "A definition of a TRACE operation on this path." + "id": "rfc9110.15.6.should-user-agent-display-any-included-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10725, + "section": "Status Codes > Server Error 5xx", + "anchor": "section-15.6", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A user agent SHOULD display any included representation to the user." + }, + { + "id": "rfc9110.15.must-however-client-understand-class-any-status", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9386, + "section": "Status Codes", + "anchor": "section-15", + "level": "MUST", + "terms": ["MUST"], + "text": "However, a client MUST understand the class of any status code, as indicated by the first digit, and treat an unrecognized status code as being equivalent to the x00 status code of that class." + }, + { + "id": "rfc9110.15.should-client-receives-response-invalid-status-code", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 9400, + "section": "Status Codes", + "anchor": "section-15", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A client that receives a response with an invalid status code SHOULD process the response as if it had a 5xx (Server Error) status code." + }, + { + "id": "rfc9110.16.1.1.must-http-method-registrations-include-following-fields", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10855, + "section": "Extending HTTP > Method Extensibility > Method Registry", + "anchor": "section-16.1.1", + "level": "MUST", + "terms": ["MUST"], + "text": "HTTP method registrations MUST include the following fields:" }, { - "id": "oas-3.2.paths-object.may-paths-object-empty-due-access-control", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 504, - "section": "Objects and Fields > Paths Object", - "anchor": "paths-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The Paths Object MAY be empty, due to Access Control List (ACL) constraints." + "id": "rfc9110.16.2.1.must-registration-include-following-fields", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 10928, + "section": "Extending HTTP > Status Code Extensibility > Status Code Registry", + "anchor": "section-16.2.1", + "level": "MUST", + "terms": ["MUST"], + "text": "A registration MUST include the following fields:" }, { - "id": "oas-3.2.paths-object.path-templating.must-each-template-expression-path-correspond-path", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 519, - "section": "Objects and Fields > Paths Object > Path Templating", - "anchor": "path-templating", + "id": "rfc9110.16.3.1.must-conform-field-name-syntax-defined-section", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11048, + "section": "Extending HTTP > Field Extensibility > Field Name Registry", + "anchor": "section-16.3.1", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "It MUST conform to the field-name syntax defined in Section 5.1, and it SHOULD be restricted to just letters, digits, and hyphen ('-') characters, with the first character being a letter." + }, + { + "id": "rfc9110.16.3.2.1.should-interoperable-new-field-names-constrain-themselves", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11160, + "section": "Extending HTTP > Field Extensibility > Considerations for New Fields > Considerations for New Field Names", + "anchor": "section-16.3.2.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "To be interoperable, new field names SHOULD constrain themselves to alphanumeric characters, \"-\", and \".\", and SHOULD begin with a letter." + }, + { + "id": "rfc9110.16.4.1.must-registrations-include-following-fields", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11234, + "section": "Extending HTTP > Authentication Scheme Extensibility > Authentication Scheme Registry", + "anchor": "section-16.4.1", "level": "MUST", "terms": ["MUST"], - "text": "Each template expression in the path MUST correspond to a path parameter that is included in the Path Item itself and/or in each of the Path Item's Operations." + "text": "Registrations MUST include the following fields:" }, { - "id": "oas-3.2.paths-object.path-templating.must-not-each-template-expression-appear-more-once", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 545, - "section": "Objects and Fields > Paths Object > Path Templating", - "anchor": "path-templating", + "id": "rfc9110.16.4.2.must-http-authentication-presumed-stateless-all-information", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11255, + "section": "Extending HTTP > Authentication Scheme Extensibility > Considerations for New Authentication Schemes", + "anchor": "section-16.4.2", "level": "MUST", - "terms": ["MUST NOT"], - "text": "Each template expression MUST NOT appear more than once in a single path template." + "terms": ["MUST"], + "text": "HTTP authentication is presumed to be stateless: all of the information necessary to authenticate a request MUST be provided in the request, rather than be dependent on the server remembering prior requests." }, { - "id": "oas-3.2.paths-object.path-templating.must-not-value-path-parameters-contain-any-unescaped", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 521, - "section": "Objects and Fields > Paths Object > Path Templating", - "anchor": "path-templating", + "id": "rfc9110.16.4.2.must-not-new-schemes-use-way-incompatible-definition", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11267, + "section": "Extending HTTP > Authentication Scheme Extensibility > Considerations for New Authentication Schemes", + "anchor": "section-16.4.2", "level": "MUST", "terms": ["MUST NOT"], - "text": "The value for these path parameters MUST NOT contain any unescaped \"generic syntax\" characters described by RFC3986: forward slashes (`/`), question marks (`?`), or hashes (`#`)." + "text": "New schemes MUST NOT use it in a way incompatible with that definition." }, { - "id": "oas-3.2.paths-object.pattern-path", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 511, - "section": "Objects and Fields > Paths Object > Patterned Fields", - "anchor": "paths-path", - "level": "field", - "terms": [], - "text": "A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The URL from the Server Object's `url` field, resolved and with template variables substituted, has the path appended (no relative URL resolution) to it in order to construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use." + "id": "rfc9110.16.5.1.must-registration-http-range-unit-include-following", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11349, + "section": "Extending HTTP > Range Unit Extensibility > Range Unit Registry", + "anchor": "section-16.5.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Registration of an HTTP Range Unit MUST include the following fields:" }, { - "id": "oas-3.2.paths-object.pattern-path.must-field-name-begin-forward-slash", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 511, - "section": "Objects and Fields > Paths Object > Patterned Fields", - "anchor": "paths-path", + "id": "rfc9110.16.6.1.must-content-coding-registrations-include-following-fields", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11382, + "section": "Extending HTTP > Content Coding Extensibility > Content Coding Registry", + "anchor": "section-16.6.1", "level": "MUST", "terms": ["MUST"], - "text": "The field name MUST begin with a forward slash (`/`)." + "text": "Content coding registrations MUST include the following fields:" }, { - "id": "oas-3.2.paths-object.pattern-path.must-not-templated-paths-same-hierarchy-but-different", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 511, - "section": "Objects and Fields > Paths Object > Patterned Fields", - "anchor": "paths-path", + "id": "rfc9110.16.6.1.must-not-names-content-codings-overlap-names-transfer", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11390, + "section": "Extending HTTP > Content Coding Extensibility > Content Coding Registry", + "anchor": "section-16.6.1", "level": "MUST", "terms": ["MUST NOT"], - "text": "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical." + "text": "Names of content codings MUST NOT overlap with names of transfer codings (per the \"HTTP Transfer Coding Registry\" located at ) unless the encoding transformation is identical (as is the case for the compression codings defined in Section 8.4.1)." }, { - "id": "oas-3.2.paths-object.patterned-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 513, - "section": "Objects and Fields > Paths Object > Patterned Fields", - "anchor": "patterned-fields", + "id": "rfc9110.16.6.1.must-values-added-namespace-require-ietf-review", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11398, + "section": "Extending HTTP > Content Coding Extensibility > Content Coding Registry", + "anchor": "section-16.6.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Values to be added to this namespace require IETF Review (see Section 4.8 of [RFC8126]) and MUST conform to the purpose of content coding defined in Section 8.4.1." + }, + { + "id": "rfc9110.16.7.may-iesg-reassign-responsibility-protocol-token", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11446, + "section": "Extending HTTP > Upgrade Token Registry", + "anchor": "section-16.7", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "The IESG MAY reassign responsibility for a protocol token." }, { - "id": "oas-3.2.percent-encoding-and-cookies.must-not-while-percent-encoding-seems-more-common", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5152, - "section": "Appendix D: Serializing Headers and Cookies > Percent-Encoding and Cookies", - "anchor": "percent-encoding-and-cookies", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "While percent-encoding seems more common as an escaping mechanism than the base64 encoding (`contentEncoding`: \"base64\") recommended by [RFC6265], section 5.6 of draft-ietf-httpbis-rfc6265bis-20, the proposed update to that RFC notes that cookies sent in the `Set-Cookie` response header that appear to be percent-encoded MUST NOT be decoded when stored by the client, which would mean that they are already encoded when retrieved from that storage for use in the `Cookie` request header." + "id": "rfc9110.16.7.may-registration-name-set-specifications-associated-token", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11439, + "section": "Extending HTTP > Upgrade Token Registry", + "anchor": "section-16.7", + "level": "MAY", + "terms": ["MAY"], + "text": "The registration MAY name a set of specifications associated with that token." }, { - "id": "oas-3.2.percent-encoding-and-form-data.must-users-wishing-use-percent-encoding-way", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5199, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and `form-data`", - "anchor": "percent-encoding-and-form-data", + "id": "rfc9110.16.7.may-responsible-party-change-registration-any-time", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11443, + "section": "Extending HTTP > Upgrade Token Registry", + "anchor": "section-16.7", + "level": "MAY", + "terms": ["MAY"], + "text": "The responsible party MAY change the registration at any time." + }, + { + "id": "rfc9110.16.7.must-registration-name-point-contact", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11438, + "section": "Extending HTTP > Upgrade Token Registry", + "anchor": "section-16.7", "level": "MUST", "terms": ["MUST"], - "text": "Users wishing to use percent-encoding in this way MUST provide the data in percent-encoded form, as percent-encoding is not automatically applied for this media type regardless of which Encoding Object fields are used." + "text": "The registration MUST name a point of contact." }, { - "id": "oas-3.2.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5250, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", - "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "id": "rfc9110.16.7.must-registration-name-responsible-party-registration", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11436, + "section": "Extending HTTP > Upgrade Token Registry", + "anchor": "section-16.7", "level": "MUST", "terms": ["MUST"], - "text": "The `[`, `]`, `|`, and space characters, which are used as delimiters for the `deepObject`, `pipeDelimited`, and `spaceDelimited` styles, respectively, all MUST be percent-encoded to comply with [RFC3986]." + "text": "The registration MUST name a responsible party for the registration." }, { - "id": "oas-3.2.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5261, - "section": "Appendix E: Percent-Encoding and Form Media Types > Percent-Encoding and Illegal or Reserved Delimiters", - "anchor": "percent-encoding-and-illegal-or-reserved-delimiters", + "id": "rfc9110.16.7.should-registration-name-set-expected-protocol-version", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 11441, + "section": "Extending HTTP > Upgrade Token Registry", + "anchor": "section-16.7", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "For maximum interoperability, it is RECOMMENDED to either define and document an additional escape convention while percent-encoding the delimiters for these styles, or to avoid these styles entirely." + "terms": ["SHOULD"], + "text": "The registration SHOULD name a set of expected \"protocol-version\" tokens associated with that token at the time of registration." }, { - "id": "oas-3.2.reference-object.$ref", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2963, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-ref", - "level": "field", - "terms": [], - "text": "REQUIRED. The reference identifier. This MUST be in the form of a URI." + "id": "rfc9110.2.2.may-recipient-employ-workarounds-while-remaining-conformant", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1505, + "section": "Conformance > Requirements Notation", + "anchor": "section-2.2", + "level": "MAY", + "terms": ["MAY"], + "text": "A recipient MAY employ such workarounds while remaining conformant to this protocol if the workarounds are limited to the implementations at fault." }, { - "id": "oas-3.2.reference-object.$ref.must-form-uri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2963, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-ref", + "id": "rfc9110.2.2.must-not-sender-generate-protocol-elements-do-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1486, + "section": "Conformance > Requirements Notation", + "anchor": "section-2.2", "level": "MUST", - "terms": ["MUST"], - "text": "This MUST be in the form of a URI." + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate protocol elements that do not match the grammar defined by the corresponding ABNF rules." }, { - "id": "oas-3.2.reference-object.$ref.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2963, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-ref", + "id": "rfc9110.2.2.must-not-within-given-message-sender-generate-protocol", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1486, + "section": "Conformance > Requirements Notation", + "anchor": "section-2.2", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "Within a given message, a sender MUST NOT generate protocol elements or syntax alternatives that are only allowed to be generated by participants in other roles (i.e., a role that the sender does not have for that message)." }, { - "id": "oas-3.2.reference-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2965, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-description", - "level": "field", - "terms": [], - "text": "A description which by default SHOULD override that of the referenced component. CommonMark syntax MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect." + "id": "rfc9110.2.3.must-minimum-recipient-able-parse-process-protocol", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1533, + "section": "Conformance > Length Requirements", + "anchor": "section-2.3", + "level": "MUST", + "terms": ["MUST"], + "text": "At a minimum, a recipient MUST be able to parse and process protocol element lengths that are at least as long as the values that it generates for those same protocol elements in other messages." }, { - "id": "oas-3.2.reference-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2965, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-description", + "id": "rfc9110.2.3.should-recipient-parse-received-protocol-element-defensively", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1518, + "section": "Conformance > Length Requirements", + "anchor": "section-2.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A recipient SHOULD parse a received protocol element defensively, with only marginal expectations that the element will conform to its ABNF grammar and fit within a reasonable buffer size." + }, + { + "id": "rfc9110.2.4.may-unless-noted-otherwise-recipient-attempt-recover", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1561, + "section": "Conformance > Error Handling", + "anchor": "section-2.4", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "Unless noted otherwise, a recipient MAY attempt to recover a usable protocol element from an invalid construct." }, { - "id": "oas-3.2.reference-object.description.should-description-default-override-referenced-component", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2965, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-description", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "A description which by default SHOULD override that of the referenced component." + "id": "rfc9110.2.4.must-recipient-interpret-received-protocol-element-according", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1550, + "section": "Conformance > Error Handling", + "anchor": "section-2.4", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST interpret a received protocol element according to the semantics defined for it by this specification, including extensions to this specification, unless the recipient has determined (through experience or configuration) that the sender incorrectly implements what is implied by those semantics." }, { - "id": "oas-3.2.reference-object.fixed-fields.shall-object-cannot-extended-additional-properties-any", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2967, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "fixed-fields-19", + "id": "rfc9110.3.3.must-not-result-server-assume-two-requests-same", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1731, + "section": "Terminology and Core Concepts > Connections, Clients, and Servers", + "anchor": "section-3.3", "level": "MUST", - "terms": ["SHALL"], - "text": "This object cannot be extended with additional properties, and any properties added SHALL be ignored." + "terms": ["MUST NOT"], + "text": "As a result, a server MUST NOT assume that two requests on the same connection are from the same user agent unless the connection is secured and specific to that agent." }, { - "id": "oas-3.2.reference-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2964, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-summary", - "level": "field", - "terms": [], - "text": "A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect." + "id": "rfc9110.3.8.may-any-client-server-employ-cache-though", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 1960, + "section": "Terminology and Core Concepts > Caches", + "anchor": "section-3.8", + "level": "MAY", + "terms": ["MAY"], + "text": "Any client or server MAY employ a cache, though a cache cannot be used while acting as a tunnel." }, { - "id": "oas-3.2.reference-object.summary.should-short-summary-default-override-referenced-component", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2964, - "section": "Objects and Fields > Reference Object > Fixed Fields", - "anchor": "reference-summary", + "id": "rfc9110.4.1.recommended-all-senders-recipients-support-minimum-uris", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2093, + "section": "Identifiers in HTTP > URI References", + "anchor": "section-4.1", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "A short summary which by default SHOULD override that of the referenced component." + "terms": ["RECOMMENDED"], + "text": "It is RECOMMENDED that all senders and recipients support, at a minimum, URIs with lengths of 8000 octets in protocol elements." }, { - "id": "oas-3.2.request-body-object.content", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1219, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "request-body-content", - "level": "field", - "terms": [], - "text": "REQUIRED. The content of the request body. The key is a media type or media type range and the value describes it. The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined. For requests that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + "id": "rfc9110.4.2.1.must-not-sender-generate-http-uri-empty-host", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2164, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > http URI Scheme", + "anchor": "section-4.2.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate an \"http\" URI with an empty host identifier." }, { - "id": "oas-3.2.request-body-object.content.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1219, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "request-body-content", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "id": "rfc9110.4.2.1.must-recipient-processes-uri-reference-reject-invalid", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2164, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > http URI Scheme", + "anchor": "section-4.2.1", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient that processes such a URI reference MUST reject it as invalid." }, { - "id": "oas-3.2.request-body-object.content.should-map-have-least-one-entry-does", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1219, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "request-body-content", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined." + "id": "rfc9110.4.2.2.must-client-ensure-http-requests-https-resource", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2211, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > https URI Scheme", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A client MUST ensure that its HTTP requests for an \"https\" resource are secured, prior to being communicated, and that it only accepts secured responses to those requests." }, { - "id": "oas-3.2.request-body-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1218, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "request-body-description", - "level": "field", - "terms": [], - "text": "A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.4.2.2.must-not-sender-generate-https-uri-empty-host", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2203, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > https URI Scheme", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate an \"https\" URI with an empty host identifier." }, { - "id": "oas-3.2.request-body-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1218, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "request-body-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.4.2.2.must-recipient-processes-uri-reference-reject-invalid", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2203, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > https URI Scheme", + "anchor": "section-4.2.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient that processes such a URI reference MUST reject it as invalid." }, { - "id": "oas-3.2.request-body-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1222, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "fixed-fields-10", + "id": "rfc9110.4.2.3.may-two-http-uris-equivalent-after-normalization", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2267, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > http(s) Normalization and Comparison", + "anchor": "section-4.2.3", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "Two HTTP URIs that are equivalent after normalization (using any method) can be assumed to identify the same resource, and any HTTP component MAY perform normalization." }, { - "id": "oas-3.2.request-body-object.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 1220, - "section": "Objects and Fields > Request Body Object > Fixed Fields", - "anchor": "request-body-required", - "level": "field", - "terms": [], - "text": "Determines if the request body is required in the request. Defaults to `false`." + "id": "rfc9110.4.2.3.should-not-result-distinct-resources-identified-http-uris", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2267, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > http(s) Normalization and Comparison", + "anchor": "section-4.2.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "As a result, distinct resources SHOULD NOT be identified by HTTP URIs that are equivalent after normalization (using any method defined in Section 6.2 of [URI])." }, { - "id": "oas-3.2.response-object.content", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2188, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-content", - "level": "field", - "terms": [], - "text": "A map containing descriptions of potential response payloads. The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. `\"text/plain\"` overrides `\"text/*\"`" + "id": "rfc9110.4.2.4.must-not-sender-generate-userinfo-subcomponent-delimiter-http", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2289, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > Deprecation of userinfo in http(s) URIs", + "anchor": "section-4.2.4", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate the userinfo subcomponent (and its \"@\" delimiter) when an \"http\" or \"https\" URI reference is generated within a message as a target URI or field value." }, { - "id": "oas-3.2.response-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2186, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-description", - "level": "field", - "terms": [], - "text": "A description of the response. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.4.2.4.should-before-making-use-http-https-uri", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2294, + "section": "Identifiers in HTTP > HTTP-Related URI Schemes > Deprecation of userinfo in http(s) URIs", + "anchor": "section-4.2.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Before making use of an \"http\" or \"https\" URI reference received from an untrusted source, a recipient SHOULD parse for userinfo and treat its presence as an error; it is likely being used to obscure the authority for the sake of phishing attacks." }, { - "id": "oas-3.2.response-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2186, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-description", + "id": "rfc9110.4.3.2.may-http-uri-used-within-context-calls", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2409, + "section": "Identifiers in HTTP > Authoritative Access > http Origins", + "anchor": "section-4.3.2", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "When an \"http\" URI is used within a context that calls for access to the indicated resource, a client MAY attempt access by resolving the host identifier to an IP address, establishing a TCP connection to that address on the indicated port, and sending over that connection an HTTP request message containing a request target that matches the client's target URI (Section 7.1)." }, { - "id": "oas-3.2.response-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2191, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "fixed-fields-14", + "id": "rfc9110.4.3.3.may-https-uri-used-within-context-calls", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2487, + "section": "Identifiers in HTTP > Authoritative Access > https Origins", + "anchor": "section-4.3.3", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "When an \"https\" URI is used within a context that calls for access to the indicated resource, a client MAY attempt access by resolving the host identifier to an IP address, establishing a TCP connection to that address on the indicated port, securing the connection end-to-end by successfully initiating TLS over TCP with confidentiality and integrity protection, and sending over that connection an HTTP request message containing a request target that matches the client's target URI (Section 7.1)." }, { - "id": "oas-3.2.response-object.headers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2187, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-headers", - "level": "field", - "terms": [], - "text": "Maps a header name to its definition. RFC9110 states header names are case-insensitive. If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + "id": "rfc9110.4.3.4.must-automated-clients-log-error-appropriate-audit", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2544, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", + "level": "MUST", + "terms": ["MUST", "SHOULD"], + "text": "Automated clients MUST log the error to an appropriate audit log (if available) and SHOULD terminate the connection (with a bad certificate error)." }, { - "id": "oas-3.2.response-object.headers.shall-response-header-defined-name-content-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2187, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-headers", + "id": "rfc9110.4.3.4.must-automated-clients-provide-configuration-setting-disables", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2544, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", "level": "MUST", - "terms": ["SHALL"], - "text": "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored." + "terms": ["MAY", "MUST"], + "text": "Automated clients MAY provide a configuration setting that disables this check, but MUST provide a setting which enables it." }, { - "id": "oas-3.2.response-object.links", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2189, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-links", - "level": "field", - "terms": [], - "text": "A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for Component Objects." + "id": "rfc9110.4.3.4.must-certificate-not-valid-target-uri-s", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2544, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", + "level": "MUST", + "terms": ["MUST"], + "text": "If the certificate is not valid for the target URI's origin, a user agent MUST either obtain confirmation from the user before proceeding (see Section 3.5) or terminate the connection with a bad certificate error." }, { - "id": "oas-3.2.response-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2185, - "section": "Objects and Fields > Response Object > Fixed Fields", - "anchor": "response-summary", - "level": "field", - "terms": [], - "text": "A short summary of the meaning of the response." + "id": "rfc9110.4.3.4.must-client-construct-reference-identity-service-s", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2518, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", + "level": "MUST", + "terms": ["MUST"], + "text": "The client MUST construct a reference identity from the service's host: if the host is a literal IP address (Section 4.3.5), the reference identity is an IP-ID, otherwise the host is a name and the reference identity is a DNS-ID." }, { - "id": "oas-3.2.responses-object.default", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2142, - "section": "Objects and Fields > Responses Object > Fixed Fields", - "anchor": "responses-default", - "level": "field", - "terms": [], - "text": "The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses." + "id": "rfc9110.4.3.4.must-establish-secured-connection-dereference-uri-client", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2510, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", + "level": "MUST", + "terms": ["MUST"], + "text": "To establish a secured connection to dereference a URI, a client MUST verify that the service's identity is an acceptable match for the URI's origin server." }, { - "id": "oas-3.2.responses-object.http-status-codes.should-status-codes-selected-available-status-codes", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2154, - "section": "Objects and Fields > Responses Object > HTTP Status Codes", - "anchor": "http-status-codes", + "id": "rfc9110.4.3.4.must-general-client-verify-service-identity-using", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2518, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", + "level": "MUST", + "terms": ["MUST"], + "text": "In general, a client MUST verify the service identity using the verification process defined in Section 6 of [RFC6125]." + }, + { + "id": "rfc9110.4.3.4.must-not-reference-identity-type-cn-id-used", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2526, + "section": "Identifiers in HTTP > Authoritative Access > https Certificate Verification", + "anchor": "section-4.3.4", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A reference identity of type CN-ID MUST NOT be used by clients." + }, + { + "id": "rfc9110.5.1.must-proxy-forward-unrecognized-header-fields-unless", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2618, + "section": "Fields > Field Names", + "anchor": "section-5.1", + "level": "MUST", + "terms": ["MUST"], + "text": "A proxy MUST forward unrecognized header fields unless the field name is listed in the Connection header field (Section 7.6.1) or the proxy is specifically configured to block, or otherwise transform, such fields." + }, + { + "id": "rfc9110.5.1.should-other-recipients-ignore-unrecognized-header-trailer", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2618, + "section": "Fields > Field Names", + "anchor": "section-5.1", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Status codes SHOULD be selected from the available status codes registered in the IANA Status Code Registry." + "text": "Other recipients SHOULD ignore unrecognized header and trailer fields." }, { - "id": "oas-3.2.responses-object.may-default-used-default-response-object-all", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2131, - "section": "Objects and Fields > Responses Object", - "anchor": "responses-object", + "id": "rfc9110.5.3.may-recipient-combine-multiple-field-lines-within", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2663, + "section": "Fields > Field Order", + "anchor": "section-5.3", "level": "MAY", "terms": ["MAY"], - "text": "The `default` MAY be used as a default Response Object for all HTTP codes that are not covered individually by the Responses Object." + "text": "A recipient MAY combine multiple field lines within a field section that have the same field name into one field line, without changing the semantics of the message, by appending each subsequent field line value to the initial field line value in order, separated by a comma (\",\") and optional whitespace (OWS, defined in Section 5.6.3)." }, { - "id": "oas-3.2.responses-object.must-responses-object-contain-least-one-response", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2134, - "section": "Objects and Fields > Responses Object", - "anchor": "responses-object", + "id": "rfc9110.5.3.must-not-means-aside-well-known-exception-noted", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2678, + "section": "Fields > Field Order", + "anchor": "section-5.3", "level": "MUST", - "terms": ["MUST", "SHOULD"], - "text": "The Responses Object MUST contain at least one response code, and if only one response code is provided it SHOULD be the response for a successful operation call." + "terms": ["MUST NOT"], + "text": "This means that, aside from the well-known exception noted below, a sender MUST NOT generate multiple field lines with the same name in a message (whether in the headers or trailers) or append a field line when a field line of the same name already exists in the message, unless that field's definition allows multiple field line values to be recombined as a comma-separated list (i.e., at least one alternative of the field's definition allows a comma-separated list, such as an ABNF rule of #(values) defined in Section 5.6.1)." }, { - "id": "oas-3.2.responses-object.pattern-http-status-code", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2148, - "section": "Objects and Fields > Responses Object > Patterned Fields", - "anchor": "responses-code", - "level": "field", - "terms": [], - "text": "Any HTTP status code can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be represented by a string (for example, `\"200\"` enclosed in quotes in YAML) for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `200` and `299`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code." + "id": "rfc9110.5.3.must-not-order-field-lines-same-name-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2672, + "section": "Fields > Field Order", + "anchor": "section-5.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "The order in which field lines with the same name are received is therefore significant to the interpretation of the field value; a proxy MUST NOT change the order of these field line values when forwarding a message." }, { - "id": "oas-3.2.responses-object.pattern-http-status-code.may-define-range-response-codes-field-contain", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2148, - "section": "Objects and Fields > Responses Object > Patterned Fields", - "anchor": "responses-code", + "id": "rfc9110.5.3.must-not-server-apply-request-target-resource-until", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2707, + "section": "Fields > Field Order", + "anchor": "section-5.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A server MUST NOT apply a request to the target resource until it receives the entire request header section, since later header field lines might include conditionals, authentication credentials, or deliberately misleading duplicate header fields that could impact request processing." + }, + { + "id": "rfc9110.5.4.may-client-discard-truncate-received-field-lines", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2730, + "section": "Fields > Field Limits", + "anchor": "section-5.4", "level": "MAY", "terms": ["MAY"], - "text": "To define a range of response codes, this field MAY contain the uppercase wildcard character `X`." + "text": "A client MAY discard or truncate received field lines that are larger than the client wishes to process if the field semantics are such that the dropped value(s) can be safely ignored without changing the message framing or response semantics." + }, + { + "id": "rfc9110.5.4.must-server-receives-request-header-field-line", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2723, + "section": "Fields > Field Limits", + "anchor": "section-5.4", + "level": "MUST", + "terms": ["MUST"], + "text": "A server that receives a request header field line, field value, or set of fields larger than it wishes to process MUST respond with an appropriate 4xx (Client Error) status code." + }, + { + "id": "rfc9110.5.5.may-field-values-containing-other-ctl-characters", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2773, + "section": "Fields > Field Values", + "anchor": "section-5.5", + "level": "MAY", + "terms": ["MAY"], + "text": "Field values containing other CTL characters are also invalid; however, recipients MAY retain such characters for the sake of robustness when they appear within a safe context (e.g., an application-specific quoted string that will not be processed by any downstream HTTP parser)." + }, + { + "id": "rfc9110.5.5.must-field-values-containing-cr-lf-nul", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2773, + "section": "Fields > Field Values", + "anchor": "section-5.5", + "level": "MUST", + "terms": ["MUST"], + "text": "Field values containing CR, LF, or NUL characters are invalid and dangerous, due to the varying ways that implementations might parse and interpret those characters; a recipient of CR, LF, or NUL within a field value MUST either reject the message or replace each of those characters with SP before further processing or forwarding of that message." + }, + { + "id": "rfc9110.5.5.must-specific-version-http-allows-whitespace-appear", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2754, + "section": "Fields > Field Values", + "anchor": "section-5.5", + "level": "MUST", + "terms": ["MUST"], + "text": "When a specific version of HTTP allows such whitespace to appear in a message, a field parsing implementation MUST exclude such whitespace prior to evaluating the field value." + }, + { + "id": "rfc9110.5.5.should-recipient-treat-other-allowed-octets-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2760, + "section": "Fields > Field Values", + "anchor": "section-5.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A recipient SHOULD treat other allowed octets in field content (i.e., obs-text) as opaque data." + }, + { + "id": "rfc9110.5.5.should-specifications-newly-defined-fields-limit-values", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2760, + "section": "Fields > Field Values", + "anchor": "section-5.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Specifications for newly defined fields SHOULD limit their values to visible US-ASCII octets (VCHAR), SP, and HTAB." + }, + { + "id": "rfc9110.5.6.1.1.must-not-any-production-uses-list-construct-sender", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2855, + "section": "Fields > Common Rules for Defining Field Values > Lists (#rule ABNF Extension) > Sender Requirements", + "anchor": "section-5.6.1.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "In any production that uses the list construct, a sender MUST NOT generate empty list elements." }, { - "id": "oas-3.2.responses-object.pattern-http-status-code.must-field-represented-string-example-200-enclosed", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2148, - "section": "Objects and Fields > Responses Object > Patterned Fields", - "anchor": "responses-code", + "id": "rfc9110.5.6.1.2.must-other-words-recipient-accept-lists-satisfy", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2882, + "section": "Fields > Common Rules for Defining Field Values > Lists (#rule ABNF Extension) > Recipient Requirements", + "anchor": "section-5.6.1.2", "level": "MUST", "terms": ["MUST"], - "text": "This field MUST be represented by a string (for example, `\"200\"` enclosed in quotes in YAML) for compatibility between JSON and YAML." + "text": "In other words, a recipient MUST accept lists that satisfy the following syntax:" }, { - "id": "oas-3.2.responses-object.patterned-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2150, - "section": "Objects and Fields > Responses Object > Patterned Fields", - "anchor": "patterned-fields-0", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc9110.5.6.1.2.must-recipient-parse-ignore-reasonable-number-empty", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2882, + "section": "Fields > Common Rules for Defining Field Values > Lists (#rule ABNF Extension) > Recipient Requirements", + "anchor": "section-5.6.1.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient MUST parse and ignore a reasonable number of empty list elements: enough to handle common mistakes by senders that merge values, but not so much that they could be used as a denial-of-service mechanism." }, { - "id": "oas-3.2.rich-text-formatting.may-tooling-choose-ignore-some-commonmark-extension", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 72, - "section": "Format > Rich Text Formatting", - "anchor": "rich-text-formatting", + "id": "rfc9110.5.6.3.may-any-content-known-defined-bws-removed", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2980, + "section": "Fields > Common Rules for Defining Field Values > Whitespace", + "anchor": "section-5.6.3", "level": "MAY", "terms": ["MAY"], - "text": "Tooling MAY choose to ignore some CommonMark or extension features to address security concerns." + "text": "Any content known to be defined as BWS MAY be removed before interpreting it or forwarding the message downstream." }, { - "id": "oas-3.2.rich-text-formatting.may-while-framing-commonmark-0-27-minimum", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 75, - "section": "Format > Rich Text Formatting", - "anchor": "rich-text-formatting", + "id": "rfc9110.5.6.3.may-any-content-known-defined-ows-rws", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2969, + "section": "Fields > Common Rules for Defining Field Values > Whitespace", + "anchor": "section-5.6.3", "level": "MAY", "terms": ["MAY"], - "text": "While the framing of CommonMark 0.27 as a minimum requirement means that tooling MAY choose to implement extensions on top of it, note that any such extensions are by definition implementation-defined and will not be interoperable." + "text": "Any content known to be defined as OWS or RWS MAY be replaced with a single SP before interpreting it or forwarding the message downstream." }, { - "id": "oas-3.2.rich-text-formatting.must-openapi-tooling-renders-rich-text-support", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 72, - "section": "Format > Rich Text Formatting", - "anchor": "rich-text-formatting", + "id": "rfc9110.5.6.3.must-not-sender-generate-bws-messages", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2974, + "section": "Fields > Common Rules for Defining Field Values > Whitespace", + "anchor": "section-5.6.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate BWS in messages." + }, + { + "id": "rfc9110.5.6.3.must-recipient-parse-bad-whitespace-remove-before", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2974, + "section": "Fields > Common Rules for Defining Field Values > Whitespace", + "anchor": "section-5.6.3", "level": "MUST", "terms": ["MUST"], - "text": "Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by CommonMark 0.27." + "text": "A recipient MUST parse for such bad whitespace and remove it before interpreting the protocol element." }, { - "id": "oas-3.2.rich-text-formatting.should-openapi-description-authors-consider-how-text", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 75, - "section": "Format > Rich Text Formatting", - "anchor": "rich-text-formatting", + "id": "rfc9110.5.6.3.should-protocol-elements-optional-whitespace-preferred-improve", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2957, + "section": "Fields > Common Rules for Defining Field Values > Whitespace", + "anchor": "section-5.6.3", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "OpenAPI Description authors SHOULD consider how text using such extensions will be rendered by tools that offer only the minimum support." + "terms": ["SHOULD", "SHOULD NOT"], + "text": "For protocol elements where optional whitespace is preferred to improve readability, a sender SHOULD generate the optional whitespace as a single SP; otherwise, a sender SHOULD NOT generate optional whitespace except as needed to overwrite invalid or unwanted protocol elements during in-place message filtering." }, { - "id": "oas-3.2.schema-object.annotated-enumerations.may-implementations-support-recognizing-oneof-anyof-each", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3299, - "section": "Objects and Fields > Schema Object > Data Modeling Techniques > Annotated Enumerations", - "anchor": "annotated-enumerations", - "level": "MAY", - "terms": ["MAY"], - "text": "Implementations MAY support recognizing a `oneOf` or `anyOf` where each subschema in the keyword's array consists of a `const` keyword and annotations such as `title` or `description` as an enumerated type with additional information." + "id": "rfc9110.5.6.3.should-sender-generate-rws-single-sp", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 2965, + "section": "Fields > Common Rules for Defining Field Values > Whitespace", + "anchor": "section-5.6.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A sender SHOULD generate RWS as a single SP." }, { - "id": "oas-3.2.schema-object.composition-and-inheritance-polymorphism.must-discriminating-property-defined-required-optional-but", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3277, - "section": "Objects and Fields > Schema Object > Data Modeling Techniques > Composition and Inheritance (Polymorphism)", - "anchor": "composition-and-inheritance-polymorphism", + "id": "rfc9110.5.6.4.must-recipients-process-value-quoted-string-handle", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3009, + "section": "Fields > Common Rules for Defining Field Values > Quoted Strings", + "anchor": "section-5.6.4", "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "The discriminating property MAY be defined as required or optional, but when defined as an optional property the Discriminator Object MUST include a `defaultMapping` field that specifies which schema of the `anyOf` or `oneOf`, or which schema that references the current schema in an `allOf`, is expected to validate the structure of the model when the discriminating property is not present." + "terms": ["MUST"], + "text": "Recipients that process the value of a quoted-string MUST handle a quoted-pair as if it were replaced by the octet following the backslash." }, { - "id": "oas-3.2.schema-object.data-type-format.may-tools-do-not-recognize-specific-format", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3043, - "section": "Objects and Fields > Schema Object > Data Types > Data Type Format", - "anchor": "data-type-format", - "level": "MAY", - "terms": ["MAY"], - "text": "Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified." + "id": "rfc9110.5.6.4.should-not-sender-generate-quoted-pair-comment-except", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3019, + "section": "Fields > Common Rules for Defining Field Values > Quoted Strings", + "anchor": "section-5.6.4", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A sender SHOULD NOT generate a quoted-pair in a comment except where necessary to quote parentheses [\"(\" and \")\"] and backslash octets occurring within that comment." }, { - "id": "oas-3.2.schema-object.data-type-format.optional-support-any-registered-format-strictly-support", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3041, - "section": "Objects and Fields > Schema Object > Data Types > Data Type Format", - "anchor": "data-type-format", - "level": "MAY", - "terms": ["OPTIONAL"], - "text": "Support for any registered format is strictly OPTIONAL, and support for one registered format does not imply support for any others." + "id": "rfc9110.5.6.4.should-not-sender-generate-quoted-pair-quoted-string", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3019, + "section": "Fields > Common Rules for Defining Field Values > Quoted Strings", + "anchor": "section-5.6.4", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A sender SHOULD NOT generate a quoted-pair in a quoted-string except where necessary to quote DQUOTE and backslash octets occurring within that string." }, { - "id": "oas-3.2.schema-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3008, - "section": "Objects and Fields > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.5.6.7.must-not-sender-generate-additional-whitespace-http-date", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3205, + "section": "Fields > Common Rules for Defining Field Values > Date/Time Formats", + "anchor": "section-5.6.7", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate additional whitespace in an HTTP-date beyond that specifically included as SP in the grammar." }, { - "id": "oas-3.2.schema-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3008, - "section": "Objects and Fields > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.5.6.7.must-recipient-parses-timestamp-value-http-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3107, + "section": "Fields > Common Rules for Defining Field Values > Date/Time Formats", + "anchor": "section-5.6.7", + "level": "MUST", + "terms": ["MUST"], + "text": "A recipient that parses a timestamp value in an HTTP field MUST accept all three HTTP-date formats." }, { - "id": "oas-3.2.schema-object.discriminator", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3020, - "section": "Objects and Fields > Schema Object > Fixed Fields", - "anchor": "schema-discriminator", - "level": "field", - "terms": [], - "text": "The discriminator provides a \"hint\" for which of a set of schemas a payload is expected to satisfy. See Composition and Inheritance for more details." + "id": "rfc9110.5.6.7.must-recipients-timestamp-value-rfc850-date-format", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3213, + "section": "Fields > Common Rules for Defining Field Values > Date/Time Formats", + "anchor": "section-5.6.7", + "level": "MUST", + "terms": ["MUST"], + "text": "Recipients of a timestamp value in rfc850-date format, which uses a two-digit year, MUST interpret a timestamp that appears to be more than 50 years in the future as representing the most recent year in the past that had the same last two digits." }, { - "id": "oas-3.2.schema-object.example", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3023, - "section": "Objects and Fields > Schema Object > Fixed Fields", - "anchor": "schema-example", - "level": "field", - "terms": [], - "text": "A free-form field to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. Deprecated: The `example` field has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it." + "id": "rfc9110.5.6.7.must-sender-generates-field-contains-one-more", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3107, + "section": "Fields > Common Rules for Defining Field Values > Date/Time Formats", + "anchor": "section-5.6.7", + "level": "MUST", + "terms": ["MUST"], + "text": "When a sender generates a field that contains one or more timestamps defined as HTTP-date, the sender MUST generate those timestamps in the IMF-fixdate format." }, { - "id": "oas-3.2.schema-object.extended-validation-with-annotations.may-oas-implementations-use-annotations-including-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3243, - "section": "Objects and Fields > Schema Object > Extended Validation with Annotations", - "anchor": "extended-validation-with-annotations", + "id": "rfc9110.6.2.may-client-send-lower-request-version-known", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3360, + "section": "Message Abstraction > Control Data", + "anchor": "section-6.2", "level": "MAY", "terms": ["MAY"], - "text": "OAS implementations MAY use such annotations, including extensions not recognized as part of a declared JSON Schema vocabulary, as the basis for further validation." - }, - { - "id": "oas-3.2.schema-object.externalDocs", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3022, - "section": "Objects and Fields > Schema Object > Fixed Fields", - "anchor": "schema-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this schema." + "text": "A client MAY send a lower request version if it is known that the server incorrectly implements the HTTP specification, but only after the client has attempted at least one normal request and determined from the response status code or header fields (e.g., Server) that the server improperly handles higher request versions." }, { - "id": "oas-3.2.schema-object.fixed-fields.may-object-extended-specification-extensions-though-noted", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3025, - "section": "Objects and Fields > Schema Object > Fixed Fields", - "anchor": "fixed-fields-20", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions, though as noted, additional properties MAY omit the `x-` prefix within this object." + "id": "rfc9110.6.2.must-not-client-send-version-not-conformant", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3353, + "section": "Message Abstraction > Control Data", + "anchor": "section-6.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A client MUST NOT send a version to which it is not conformant." }, { - "id": "oas-3.2.schema-object.format", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3009, - "section": "Objects and Fields > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "keyword", - "terms": [], - "text": "See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats." + "id": "rfc9110.6.2.must-not-server-send-version-not-conformant", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3367, + "section": "Message Abstraction > Control Data", + "anchor": "section-6.2", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A server MUST NOT send a version to which it is not conformant." }, { - "id": "oas-3.2.schema-object.generic-template-data-structures.should-implementations-support-defining-generic-template-data", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3288, - "section": "Objects and Fields > Schema Object > Data Modeling Techniques > Generic (Template) Data Structures", - "anchor": "generic-template-data-structures", + "id": "rfc9110.6.2.should-client-send-request-version-equal-highest", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3353, + "section": "Message Abstraction > Control Data", + "anchor": "section-6.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Implementations SHOULD support defining generic or template data structures using JSON Schema's dynamic referencing feature:" + "text": "A client SHOULD send a request version equal to the highest version to which the client is conformant and whose major version is no higher than the highest version supported by the server, if this is known." }, { - "id": "oas-3.2.schema-object.json-schema-keywords.may-json-schema-implementations-choose-treat-keywords", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3013, - "section": "Objects and Fields > Schema Object > JSON Schema Keywords", - "anchor": "json-schema-keywords", - "level": "MAY", - "terms": ["MAY"], - "text": "JSON Schema implementations MAY choose to treat keywords defined by the OpenAPI Specification's base vocabulary as unknown keywords, due to its inclusion in the OAS dialect with a `$vocabulary` value of `false`." - }, - { - "id": "oas-3.2.schema-object.may-empty-schema-allows-any-instance-validate", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2993, - "section": "Objects and Fields > Schema Object", - "anchor": "schema-object", - "level": "MAY", - "terms": ["MAY"], - "text": "The empty schema (which allows any instance to validate) MAY be represented by the boolean value `true` and a schema which allows no instance to validate MAY be represented by the boolean value `false`." + "id": "rfc9110.6.2.should-recipient-receives-message-major-version-number", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3376, + "section": "Message Abstraction > Control Data", + "anchor": "section-6.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A recipient that receives a message with a major version number that it implements and a minor version number higher than what it implements SHOULD process the message as if it were in the highest minor version within that major version to which the recipient is conformant." }, { - "id": "oas-3.2.schema-object.non-json-data.must-due-limited-requirements-searching-schemas-serializers", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3120, - "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", - "anchor": "non-json-data", - "level": "MUST", - "terms": ["MUST"], - "text": "Due to these limited requirements for searching schemas, serializers that have access to validated data MUST inspect the data if possible; implementations that either do not work with runtime data (such as code generators) or cannot access validated data for some reason MUST fall back to schema inspection." + "id": "rfc9110.6.2.should-server-send-response-version-equal-highest", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3367, + "section": "Message Abstraction > Control Data", + "anchor": "section-6.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A server SHOULD send a response version equal to the highest version to which the server is conformant that has a major version less than or equal to the one received in the request." }, { - "id": "oas-3.2.schema-object.non-json-data.must-inspecting-schemas-given-starting-point-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3094, - "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", - "anchor": "non-json-data", + "id": "rfc9110.6.5.1.must-not-recipient-merge-trailer-field-header-section", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3588, + "section": "Message Abstraction > Trailer Fields > Limitations on Use of Trailers", + "anchor": "section-6.5.1", "level": "MUST", - "terms": ["MUST"], - "text": "When inspecting schemas, given a starting point schema, implementations MUST examine that schema and all schemas that can be reached from it by following only `$ref` and `allOf` keywords." + "terms": ["MUST NOT"], + "text": "A recipient MUST NOT merge a trailer field into a header section unless the recipient understands the corresponding header field definition and that definition explicitly permits and defines how trailer field values can be safely merged." }, { - "id": "oas-3.2.schema-object.non-json-data.must-not-implementations-inspect-subschemas-possible-reference-targets", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3099, - "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", - "anchor": "non-json-data", + "id": "rfc9110.6.5.1.must-not-sender-generate-trailer-field-unless-sender", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3579, + "section": "Message Abstraction > Trailer Fields > Limitations on Use of Trailers", + "anchor": "section-6.5.1", "level": "MUST", - "terms": ["MAY", "MUST NOT"], - "text": "Implementations MAY inspect subschemas or possible reference targets of other keywords such as `oneOf` or `$dynamicRef`, but MUST NOT attempt to resolve ambiguities." + "terms": ["MUST NOT"], + "text": "A sender MUST NOT generate a trailer field unless the sender knows the corresponding header field name's definition permits the field to be sent in trailers." }, { - "id": "oas-3.2.schema-object.non-json-data.must-schema-objects-do-not-contain-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3094, - "section": "Objects and Fields > Schema Object > Parsing and Serializing > Non-JSON Data", - "anchor": "non-json-data", + "id": "rfc9110.6.5.1.should-not-because-potential-trailer-fields-discarded-transit", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3608, + "section": "Message Abstraction > Trailer Fields > Limitations on Use of Trailers", + "anchor": "section-6.5.1", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Because of the potential for trailer fields to be discarded in transit, a server SHOULD NOT generate trailer fields that it believes are necessary for the user agent to receive." + }, + { + "id": "rfc9110.6.5.2.may-end-message-recipient-treat-set-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3632, + "section": "Message Abstraction > Trailer Fields > Processing Trailer Fields", + "anchor": "section-6.5.2", + "level": "MAY", + "terms": ["MAY"], + "text": "At the end of a message, a recipient MAY treat the set of received trailer fields as a data structure of name/value pairs, similar to (but separate from) the header fields." + }, + { + "id": "rfc9110.6.5.2.must-trailer-fields-might-generated-more-once", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3624, + "section": "Message Abstraction > Trailer Fields > Processing Trailer Fields", + "anchor": "section-6.5.2", "level": "MUST", "terms": ["MUST"], - "text": "Schema Objects that do not contain `type` MUST be considered to allow all types, regardless of which other keywords are present (e.g. `maximum` applies to numbers, but _does not_ require the instance to be a number)." + "text": "Trailer fields that might be generated more than once during a message MUST be defined as a list-based field even if each member value is only processed once per field line received." }, { - "id": "oas-3.2.schema-object.non-validating-constraint-keywords.may-extended-validation-one-way-constraints-enforced", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3249, - "section": "Objects and Fields > Schema Object > Extended Validation with Annotations > Non-Validating Constraint Keywords", - "anchor": "non-validating-constraint-keywords", + "id": "rfc9110.6.6.1.may-recipient-clock-receives-response-invalid-date", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3691, + "section": "Message Abstraction > Message Metadata > Date", + "anchor": "section-6.6.1", "level": "MAY", "terms": ["MAY"], - "text": "Extended validation is one way that these constraints MAY be enforced." + "text": "A recipient with a clock that receives a response with an invalid Date header field value MAY replace that value with the time that response was received." }, { - "id": "oas-3.2.schema-object.parsing-and-serializing.may-application-form-incorporates-any-additional-information", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3064, - "section": "Objects and Fields > Schema Object > Parsing and Serializing", - "anchor": "parsing-and-serializing", + "id": "rfc9110.6.6.1.may-user-agent-send-date-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3696, + "section": "Message Abstraction > Message Metadata > Date", + "anchor": "section-6.6.1", "level": "MAY", "terms": ["MAY"], - "text": "The application form, which incorporates any additional information conveyed by JSON Schema keywords such as `format` and `contentMediaType`, and possibly additional information such as class hierarchies that are beyond the scope of this specification, although they MAY be based on specification elements such as the Discriminator Object or guidance regarding Data Modeling Techniques." + "text": "A user agent MAY send a Date header field in a request, though generally will not do so unless it is believed to convey useful information to the server." }, { - "id": "oas-3.2.schema-object.schema-evaluation-and-binary-data.must-oas-implementations-do-not-have-access", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3224, - "section": "Objects and Fields > Schema Object > Parsing and Serializing > Working with Binary Data > Schema Evaluation and Binary Data", - "anchor": "schema-evaluation-and-binary-data", + "id": "rfc9110.6.6.1.must-not-origin-server-without-clock-generate-date", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3682, + "section": "Message Abstraction > Message Metadata > Date", + "anchor": "section-6.6.1", "level": "MUST", - "terms": ["MUST"], - "text": "OAS Implementations that do not have access to a binary-instance-supporting JSON Schema implementation MUST examine schemas and apply them in accordance with Working with Binary Data." + "terms": ["MUST NOT"], + "text": "An origin server without a clock MUST NOT generate a Date header field." }, { - "id": "oas-3.2.schema-object.specifying-schema-dialects.must-default-not-set-oas-dialect-schema", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3312, - "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", + "id": "rfc9110.6.6.1.must-origin-server-clock-defined-section-5", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3673, + "section": "Message Abstraction > Message Metadata > Date", + "anchor": "section-6.6.1", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "An origin server with a clock (as defined in Section 5.6.7) MUST generate a Date header field in all 2xx (Successful), 3xx (Redirection), and 4xx (Client Error) responses, and MAY generate a Date header field in 1xx (Informational) and 5xx (Server Error) responses." + }, + { + "id": "rfc9110.6.6.1.must-recipient-clock-receives-response-message-without", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3685, + "section": "Message Abstraction > Message Metadata > Date", + "anchor": "section-6.6.1", "level": "MUST", "terms": ["MUST"], - "text": "If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects." + "text": "A recipient with a clock that receives a response message without a Date header field MUST record the time it was received and append a corresponding Date header field to the message's header section if it is cached or forwarded downstream." }, { - "id": "oas-3.2.schema-object.specifying-schema-dialects.must-schema-keyword-present-any-schema-object", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3310, - "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", + "id": "rfc9110.6.6.1.should-sender-generates-date-header-field-generate", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3666, + "section": "Message Abstraction > Message Metadata > Date", + "anchor": "section-6.6.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A sender that generates a Date header field SHOULD generate its field value as the best available approximation of the date and time of message generation." + }, + { + "id": "rfc9110.6.6.2.should-sender-intends-generate-one-more-trailer", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3725, + "section": "Message Abstraction > Message Metadata > Trailer", + "anchor": "section-6.6.2", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A sender that intends to generate one or more trailer fields in a message SHOULD generate a Trailer header field in the header section of that message to indicate which fields might be present in the trailers." + }, + { + "id": "rfc9110.6.must-however-client-retain-knowledge-request-parsing", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3278, + "section": "Message Abstraction", + "anchor": "section-6", "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "The `$schema` keyword MAY be present in any Schema Object that is a schema resource root, and if present MUST be used to determine which dialect should be used when processing the schema." + "terms": ["MUST"], + "text": "However, a client MUST retain knowledge of the request when parsing, interpreting, or caching a corresponding response." }, { - "id": "oas-3.2.schema-object.specifying-schema-dialects.must-tooling-support-oas-dialect-schema-id", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3310, - "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", + "id": "rfc9110.7.1.must-not-forms-used-other-methods", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3788, + "section": "Routing HTTP Messages > Determining the Target Resource", + "anchor": "section-7.1", "level": "MUST", - "terms": ["MUST", "MAY"], - "text": "Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`." + "terms": ["MUST NOT"], + "text": "These forms MUST NOT be used with other methods." }, { - "id": "oas-3.2.schema-object.specifying-schema-dialects.recommended-however-maximum-interoperability-openapi-description-authors", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3314, - "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, for maximum interoperability, it is RECOMMENDED that OpenAPI description authors explicitly set the dialect through `$schema` in such documents." + "id": "rfc9110.7.2.must-user-agent-generate-host-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3827, + "section": "Routing HTTP Messages > Host and :authority", + "anchor": "section-7.2", + "level": "MUST", + "terms": ["MUST"], + "text": "A user agent MUST generate a Host header field in a request unless it sends that information as an \":authority\" pseudo-header field." }, { - "id": "oas-3.2.schema-object.specifying-schema-dialects.should-standalone-json-schema-documents-do-not", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3314, - "section": "Objects and Fields > Schema Object > Specifying Schema Dialects", - "anchor": "specifying-schema-dialects", + "id": "rfc9110.7.2.should-user-agent-sends-host-send-first", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3827, + "section": "Routing HTTP Messages > Host and :authority", + "anchor": "section-7.2", "level": "SHOULD", "terms": ["SHOULD"], - "text": "For standalone JSON Schema documents that do not set `$schema`, or for Schema Objects in OpenAPI description documents that are _not_ complete documents, the dialect SHOULD be assumed to be the OAS dialect." + "text": "A user agent that sends Host SHOULD send it as the first field in the header section of a request." }, { - "id": "oas-3.2.schema-object.validating-readonly-and-writeonly.may-json-schema-validation-draft-2020-12", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3254, - "section": "Objects and Fields > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", - "anchor": "validating-readonly-and-writeonly", - "level": "MAY", - "terms": ["MAY"], - "text": "JSON Schema Validation Draft 2020-12 Section 9.4 defines the expectations of these keywords, including that a resource (described as the \"owning authority\") MAY either ignore a `readOnly` field or treat it as an error." + "id": "rfc9110.7.4.must-particular-request-https-resource-rejected-unless", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3929, + "section": "Routing HTTP Messages > Rejecting Misdirected Requests", + "anchor": "section-7.4", + "level": "MUST", + "terms": ["MUST"], + "text": "In particular, a request for an \"https\" resource MUST be rejected unless it has been received over a connection that has been secured via a certificate valid for that target URI's origin, as defined by Section 4.2.2." }, { - "id": "oas-3.2.schema-object.validating-readonly-and-writeonly.may-validation-keywords-done-checking-annotation-read", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3254, - "section": "Objects and Fields > Schema Object > Extended Validation with Annotations > Validating `readOnly` and `writeOnly`", - "anchor": "validating-readonly-and-writeonly", - "level": "MAY", - "terms": ["MAY"], - "text": "Validation of these keywords MAY be done by checking the annotation, the read or write direction, and (if relevant) the current value of the field." + "id": "rfc9110.7.4.must-unless-connection-trusted-gateway-origin-server", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3929, + "section": "Routing HTTP Messages > Rejecting Misdirected Requests", + "anchor": "section-7.4", + "level": "MUST", + "terms": ["MUST"], + "text": "Unless the connection is from a trusted gateway, an origin server MUST reject a request if any scheme-specific requirements for the target URI are not met." }, { - "id": "oas-3.2.schema-object.working-with-binary-data.shall-however-contentmediatype-contradicts-relevant-media-type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3216, - "section": "Objects and Fields > Schema Object > Parsing and Serializing > Working with Binary Data", - "anchor": "working-with-binary-data", - "level": "MUST", - "terms": ["SHALL"], - "text": "However, if `contentMediaType` contradicts a relevant Media Type Object or Encoding Object, then `contentMediaType` SHALL be ignored." + "id": "rfc9110.7.5.should-client-receives-response-while-still-sending", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3960, + "section": "Routing HTTP Messages > Response Correlation", + "anchor": "section-7.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A client that receives a response while it is still sending the associated request SHOULD continue sending that request unless it receives an explicit indication to the contrary (see, e.g., Section 9.5 of [HTTP/1.1] and Section 6.4 of [HTTP/2])." }, { - "id": "oas-3.2.schema-object.xml", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3021, - "section": "Objects and Fields > Schema Object > Fixed Fields", - "anchor": "schema-xml", - "level": "field", - "terms": [], - "text": "Adds additional metadata to describe the XML representation of this schema." + "id": "rfc9110.7.6.1.must-field-aside-connection-used-supply-control", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4019, + "section": "Routing HTTP Messages > Message Forwarding > Connection", + "anchor": "section-7.6.1", + "level": "MUST", + "terms": ["MUST"], + "text": "When a field aside from Connection is used to supply control information for or about the current connection, the sender MUST list the corresponding field name within the Connection header field." }, { - "id": "oas-3.2.security-filtering.may-path-item-object-empty", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4816, - "section": "Security Considerations > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "The Path Item Object MAY be empty." + "id": "rfc9110.7.6.1.must-intermediaries-parse-received-connection-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4026, + "section": "Routing HTTP Messages > Message Forwarding > Connection", + "anchor": "section-7.6.1", + "level": "MUST", + "terms": ["MUST"], + "text": "Intermediaries MUST parse a received Connection header field before a message is forwarded and, for each connection-option in this field, remove any header or trailer field(s) from the message with the same name as the connection-option, and then remove the Connection header field itself (or replace it with the intermediary's own control options for the forwarded message)." }, { - "id": "oas-3.2.security-filtering.may-paths-object-present-but-empty", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4815, - "section": "Security Considerations > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "The Paths Object MAY be present but empty." + "id": "rfc9110.7.6.1.must-not-sender-send-connection-option-corresponding-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4055, + "section": "Routing HTTP Messages > Message Forwarding > Connection", + "anchor": "section-7.6.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT send a connection option corresponding to a field that is intended for all recipients of the content." }, { - "id": "oas-3.2.security-filtering.may-some-objects-openapi-specification-declared-remain", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4808, - "section": "Security Considerations > Security Filtering", - "anchor": "security-filtering", - "level": "MAY", - "terms": ["MAY"], - "text": "Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation." + "id": "rfc9110.7.6.1.should-furthermore-intermediaries-remove-replace-fields-known", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4043, + "section": "Routing HTTP Messages > Message Forwarding > Connection", + "anchor": "section-7.6.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Furthermore, intermediaries SHOULD remove or replace fields that are known to require removal before forwarding, whether or not they appear as a connection-option, after applying those fields' semantics." }, { - "id": "oas-3.2.security-filtering.may-while-not-part-specification-itself-certain", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4810, - "section": "Security Considerations > Security Filtering", - "anchor": "security-filtering", + "id": "rfc9110.7.6.2.may-recipient-ignore-max-forwards-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4108, + "section": "Routing HTTP Messages > Message Forwarding > Max-Forwards", + "anchor": "section-7.6.2", "level": "MAY", "terms": ["MAY"], - "text": "While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization." + "text": "A recipient MAY ignore a Max-Forwards header field received with any other request methods." }, { - "id": "oas-3.2.security-requirement-object.must-name-used-each-property-either-correspond", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4711, - "section": "Objects and Fields > Security Requirement Object", - "anchor": "security-requirement-object", + "id": "rfc9110.7.6.2.must-each-intermediary-receives-trace-options-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4097, + "section": "Routing HTTP Messages > Message Forwarding > Max-Forwards", + "anchor": "section-7.6.2", "level": "MUST", "terms": ["MUST"], - "text": "The name used for each property MUST either correspond to a security scheme declared in the Security Schemes under the Components Object, or be the URI of a Security Scheme Object." + "text": "Each intermediary that receives a TRACE or OPTIONS request containing a Max-Forwards header field MUST check and update its value prior to forwarding the request." }, { - "id": "oas-3.2.security-requirement-object.must-property-names-identical-component-name-under", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4711, - "section": "Objects and Fields > Security Requirement Object", - "anchor": "security-requirement-object", + "id": "rfc9110.7.6.2.must-not-received-value-zero-0-intermediary-forward", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4097, + "section": "Routing HTTP Messages > Message Forwarding > Max-Forwards", + "anchor": "section-7.6.2", "level": "MUST", - "terms": ["MUST"], - "text": "Property names that are identical to a component name under the Components Object MUST be treated as a component name." + "terms": ["MUST NOT", "MUST"], + "text": "If the received value is zero (0), the intermediary MUST NOT forward the request; instead, the intermediary MUST respond as the final recipient." }, { - "id": "oas-3.2.security-requirement-object.must-security-requirement-object-refer-multiple-security", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4717, - "section": "Objects and Fields > Security Requirement Object", - "anchor": "security-requirement-object", + "id": "rfc9110.7.6.2.must-received-max-forwards-value-greater-zero", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4097, + "section": "Routing HTTP Messages > Message Forwarding > Max-Forwards", + "anchor": "section-7.6.2", "level": "MUST", - "terms": ["MAY", "MUST"], - "text": "A Security Requirement Object MAY refer to multiple security schemes in which case all schemes MUST be satisfied for a request to be authorized." - }, - { - "id": "oas-3.2.security-requirement-object.not-recommended-using-security-scheme-component-name-appears", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4715, - "section": "Objects and Fields > Security Requirement Object", - "anchor": "security-requirement-object", - "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "Using a Security Scheme component name that appears to be a URI is NOT RECOMMENDED, as the precedence of component-name-matching over URI resolution, which is necessary to maintain compatibility with prior OAS versions, is counter-intuitive." + "terms": ["MUST"], + "text": "If the received Max-Forwards value is greater than zero, the intermediary MUST generate an updated Max-Forwards field in the forwarded message with a field value that is the lesser of a) the received value decremented by one (1) or b) the recipient's maximum supported value for Max-Forwards." }, { - "id": "oas-3.2.security-requirement-object.pattern-name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4729, - "section": "Objects and Fields > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", - "level": "field", - "terms": [], - "text": "Each name or URI MUST correspond to a security scheme as described above. If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + "id": "rfc9110.7.6.3.may-however-comments-via-optional-recipient-remove", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4173, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "MAY", + "terms": ["MAY"], + "text": "However, comments in Via are optional, and a recipient MAY remove them prior to forwarding the message." }, { - "id": "oas-3.2.security-requirement-object.pattern-name.may-other-security-scheme-types-array-contain", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4729, - "section": "Objects and Fields > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "id": "rfc9110.7.6.3.may-however-real-host-considered-sensitive-information", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4164, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", "level": "MAY", "terms": ["MAY"], - "text": "For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band." + "text": "However, if the real host is considered to be sensitive information, a sender MAY replace it with a pseudonym." }, { - "id": "oas-3.2.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4729, - "section": "Objects and Fields > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "id": "rfc9110.7.6.3.may-intermediary-combine-ordered-subsequence-via-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4197, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", "level": "MAY", "terms": ["MAY"], - "text": "If the security scheme is of type `\"oauth2\"` or `\"openIdConnect\"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope." + "text": "An intermediary MAY combine an ordered subsequence of Via header field list members into a single member if the entries have identical received-protocol values." }, { - "id": "oas-3.2.security-requirement-object.pattern-name.must-each-name-uri-correspond-security-scheme", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4729, - "section": "Objects and Fields > Security Requirement Object > Patterned Fields", - "anchor": "security-requirements-name", + "id": "rfc9110.7.6.3.may-port-not-provided-recipient-interpret-meaning", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4164, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "MAY", + "terms": ["MAY"], + "text": "If a port is not provided, a recipient MAY interpret that as meaning it was received on the default port, if any, for the received-protocol." + }, + { + "id": "rfc9110.7.6.3.may-sender-generate-comments-identify-software-each", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4173, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "MAY", + "terms": ["MAY"], + "text": "A sender MAY generate comments to identify the software of each recipient, analogous to the User-Agent and Server header fields." + }, + { + "id": "rfc9110.7.6.3.must-http-http-gateway-send-appropriate-via", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4147, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", "level": "MUST", - "terms": ["MUST"], - "text": "Each name or URI MUST correspond to a security scheme as described above." + "terms": ["MUST", "MAY"], + "text": "An HTTP-to-HTTP gateway MUST send an appropriate Via header field in each inbound request message and MAY send a Via header field in forwarded response messages." }, { - "id": "oas-3.2.security-scheme-object.bearerFormat", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4605, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-bearer-format", - "level": "field", - "terms": [], - "text": "A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes." + "id": "rfc9110.7.6.3.must-not-sender-combine-members-have-different-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4209, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A sender MUST NOT combine members that have different received-protocol values." }, { - "id": "oas-3.2.security-scheme-object.deprecated", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4609, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-deprecated", - "level": "field", - "terms": [], - "text": "Declares this security scheme to be deprecated. Consumers SHOULD refrain from usage of the declared scheme. Default value is `false`." + "id": "rfc9110.7.6.3.must-proxy-send-appropriate-via-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4147, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "MUST", + "terms": ["MUST"], + "text": "A proxy MUST send an appropriate Via header field, as described below, in each message that it forwards." }, { - "id": "oas-3.2.security-scheme-object.deprecated.should-consumers-refrain-usage-declared-scheme", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4609, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-deprecated", + "id": "rfc9110.7.6.3.should-not-enabled-intermediary-replace-each-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4190, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", "level": "SHOULD", "terms": ["SHOULD"], - "text": "Consumers SHOULD refrain from usage of the declared scheme." + "text": "If not enabled, such an intermediary SHOULD replace each received-by host of any host behind the firewall by an appropriate pseudonym for that host." }, { - "id": "oas-3.2.security-scheme-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4601, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-description", - "level": "field", - "terms": [], - "text": "A description for security scheme. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.7.6.3.should-not-intermediary-used-portal-through-network-firewall", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4190, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "An intermediary used as a portal through a network firewall SHOULD NOT forward the names and ports of hosts within the firewall region unless it is explicitly enabled to do so." }, { - "id": "oas-3.2.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4601, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-description", + "id": "rfc9110.7.6.3.should-not-sender-combine-multiple-list-members-unless", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4209, + "section": "Routing HTTP Messages > Message Forwarding > Via", + "anchor": "section-7.6.3", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A sender SHOULD NOT combine multiple list members unless they are all under the same organizational control and the hosts have already been replaced by pseudonyms." + }, + { + "id": "rfc9110.7.6.must-intermediary-not-acting-tunnel-implement-connection", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3982, + "section": "Routing HTTP Messages > Message Forwarding", + "anchor": "section-7.6", + "level": "MUST", + "terms": ["MUST"], + "text": "An intermediary not acting as a tunnel MUST implement the Connection header field, as specified in Section 7.6.1, and exclude fields from being forwarded that are only intended for the incoming connection." + }, + { + "id": "rfc9110.7.6.must-not-intermediary-forward-message-itself-unless-protected", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 3988, + "section": "Routing HTTP Messages > Message Forwarding", + "anchor": "section-7.6", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "An intermediary MUST NOT forward a message to itself unless it is protected from an infinite request loop." + }, + { + "id": "rfc9110.7.7.may-proxy-receives-target-uri-host-name", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4244, + "section": "Routing HTTP Messages > Message Transformations", + "anchor": "section-7.7", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "If a proxy receives a target URI with a host name that is not a fully qualified domain name, it MAY add its own domain to the host name it received when forwarding the request." }, { - "id": "oas-3.2.security-scheme-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4611, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "fixed-fields-23", + "id": "rfc9110.7.7.may-proxy-transform-content-message-does-not", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4266, + "section": "Routing HTTP Messages > Message Transformations", + "anchor": "section-7.7", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "A proxy MAY transform the content of a message that does not contain a no-transform cache directive." }, { - "id": "oas-3.2.security-scheme-object.flows", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4606, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-flows", - "level": "field", - "terms": [], - "text": "REQUIRED. An object containing configuration information for the flow types supported." + "id": "rfc9110.7.7.must-not-proxy-change-host-name-target-uri", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4244, + "section": "Routing HTTP Messages > Message Transformations", + "anchor": "section-7.7", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT change the host name if the target URI contains a fully qualified domain name." }, { - "id": "oas-3.2.security-scheme-object.flows.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4606, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-flows", + "id": "rfc9110.7.7.must-not-proxy-modify-absolute-path-query-parts", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4250, + "section": "Routing HTTP Messages > Message Transformations", + "anchor": "section-7.7", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT modify the \"absolute-path\" and \"query\" parts of the received target URI when forwarding it to the next inbound server except as required by that forwarding protocol." }, { - "id": "oas-3.2.security-scheme-object.in", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4603, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-in", - "level": "field", - "terms": [], - "text": "REQUIRED. The location of the API key. Valid values are `\"query\"`, `\"header\"`, or `\"cookie\"`." + "id": "rfc9110.7.7.must-not-proxy-transform-content-section-6-4", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4258, + "section": "Routing HTTP Messages > Message Transformations", + "anchor": "section-7.7", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT transform the content (Section 6.4) of a response message that contains a no-transform cache directive (Section 5.2.2.6 of [CACHING])." }, { - "id": "oas-3.2.security-scheme-object.in.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4603, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-in", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "id": "rfc9110.7.7.should-not-proxy-modify-header-fields-provide-information", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4274, + "section": "Routing HTTP Messages > Message Transformations", + "anchor": "section-7.7", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A proxy SHOULD NOT modify header fields that provide information about the endpoints of the communication chain, the resource state, or the selected representation (other than the content) unless the field's definition specifically allows such modification or the modification is deemed necessary for privacy or security." }, { - "id": "oas-3.2.security-scheme-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4602, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the header, query or cookie parameter to be used." + "id": "rfc9110.7.8.may-client-send-list-protocol-names-upgrade", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4292, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MAY", + "terms": ["MAY"], + "text": "A client MAY send a list of protocol names in the Upgrade header field of a request to invite the server to switch to one or more of the named protocols, in order of descending preference, before sending the final response." }, { - "id": "oas-3.2.security-scheme-object.name.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4602, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-name", - "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "id": "rfc9110.7.8.may-server-choose-ignore-order-preference-indicated", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4312, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MAY", + "terms": ["MAY"], + "text": "A server MAY choose to ignore the order of preference indicated by the client and select the new protocol(s) based on other factors, such as the nature of the request or the current load on the server." }, { - "id": "oas-3.2.security-scheme-object.oauth2MetadataUrl", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4608, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-oauth2-metadata-url", - "level": "field", - "terms": [], - "text": "URL to the OAuth2 authorization server metadata RFC8414. TLS is required." + "id": "rfc9110.7.8.may-server-ignore-received-upgrade-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4292, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MAY", + "terms": ["MAY"], + "text": "A server MAY ignore a received Upgrade header field if it wishes to continue using the current protocol on that connection." }, { - "id": "oas-3.2.security-scheme-object.openIdConnectUrl", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4607, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-open-id-connect-url", - "level": "field", - "terms": [], - "text": "REQUIRED. Well-known URL to discover the [OpenID-Connect-Discovery] provider metadata." + "id": "rfc9110.7.8.may-server-send-upgrade-header-field-any", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4328, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MAY", + "terms": ["MAY"], + "text": "A server MAY send an Upgrade header field in any other response to advertise that it implements support for upgrading to the listed protocols, in order of descending preference, when appropriate for a future request." }, { - "id": "oas-3.2.security-scheme-object.openIdConnectUrl.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4607, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-open-id-connect-url", + "id": "rfc9110.7.8.must-not-server-switch-protocol-not-indicated-client", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4312, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "A server MUST NOT switch to a protocol that was not indicated by the client in the corresponding request's Upgrade header field." }, { - "id": "oas-3.2.security-scheme-object.scheme", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4604, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the HTTP Authentication scheme to be used in the Authorization header as defined in RFC9110. The values used SHOULD be registered in the IANA Authentication Scheme registry. The value is case-insensitive, as defined in RFC9110." + "id": "rfc9110.7.8.must-not-server-switch-protocols-unless-received-message", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4352, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A server MUST NOT switch protocols unless the received message semantics can be honored by the new protocol; an OPTIONS request can be honored by any protocol." }, { - "id": "oas-3.2.security-scheme-object.scheme.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4604, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", + "id": "rfc9110.7.8.must-sender-upgrade-send-upgrade-connection-option", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4373, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "A sender of Upgrade MUST also send an \"Upgrade\" connection option in the Connection header field (Section 7.6.1) to inform intermediaries not to forward this field." }, { - "id": "oas-3.2.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4604, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-scheme", - "level": "SHOULD", - "terms": ["SHOULD"], - "text": "The values used SHOULD be registered in the IANA Authentication Scheme registry." + "id": "rfc9110.7.8.must-server-receives-both-upgrade-expect-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4380, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MUST", + "terms": ["MUST"], + "text": "If a server receives both an Upgrade and an Expect header field with the \"100-continue\" expectation (Section 10.1.1), the server MUST send a 100 (Continue) response before sending a 101 (Switching Protocols) response." }, { - "id": "oas-3.2.security-scheme-object.type", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4600, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-type", - "level": "field", - "terms": [], - "text": "REQUIRED. The type of the security scheme. Valid values are `\"apiKey\"`, `\"http\"`, `\"mutualTLS\"`, `\"oauth2\"`, `\"openIdConnect\"`." + "id": "rfc9110.7.8.must-server-receives-upgrade-header-field-http", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4373, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MUST", + "terms": ["MUST"], + "text": "A server that receives an Upgrade header field in an HTTP/1.0 request MUST ignore that Upgrade field." }, { - "id": "oas-3.2.security-scheme-object.type.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4600, - "section": "Objects and Fields > Security Scheme Object > Fixed Fields", - "anchor": "security-scheme-type", + "id": "rfc9110.7.8.must-server-sends-101-switching-protocols-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4312, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "A server that sends a 101 (Switching Protocols) response MUST send an Upgrade header field to indicate the new protocol(s) to which the connection is being switched; if multiple protocol layers are being switched, the sender MUST list the protocols in layer-ascending order." }, { - "id": "oas-3.2.security-schemes.recommended-implementation-defined-whether-component-name-used", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4803, - "section": "Security Considerations > Security Schemes", - "anchor": "security-schemes", - "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is implementation-defined whether a component name used by a Security Requirement Object in a referenced document is resolved from the entry document (RECOMMENDED) or the referenced document." + "id": "rfc9110.7.8.must-server-sends-426-upgrade-required-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4323, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "MUST", + "terms": ["MUST"], + "text": "A server that sends a 426 (Upgrade Required) response MUST send an Upgrade header field to indicate the acceptable protocols, in order of descending preference." }, { - "id": "oas-3.2.server-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 271, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-description", - "level": "field", - "terms": [], - "text": "An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.7.8.should-although-protocol-names-registered-preferred-case", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4307, + "section": "Routing HTTP Messages > Upgrade", + "anchor": "section-7.8", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Although protocol names are registered with a preferred case, recipients SHOULD use case-insensitive comparison when matching each protocol-name to supported protocols." }, { - "id": "oas-3.2.server-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 271, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-description", + "id": "rfc9110.8.3.1.may-type-subtype-followed-semicolon-delimited-parameters", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4510, + "section": "Representation Data and Metadata > Content-Type > Media Type", + "anchor": "section-8.3.1", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "The type/subtype MAY be followed by semicolon-delimited parameters (Section 5.6.6) in the form of name/value pairs." }, { - "id": "oas-3.2.server-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 275, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "fixed-fields-3", + "id": "rfc9110.8.3.3.must-message-body-itself-protocol-element-sender", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4564, + "section": "Representation Data and Metadata > Content-Type > Multipart Types", + "anchor": "section-8.3.3", + "level": "MUST", + "terms": ["MUST"], + "text": "The message body is itself a protocol element; a sender MUST generate only CRLF to represent line breaks between body parts." + }, + { + "id": "rfc9110.8.3.may-content-type-header-field-not-present", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4458, + "section": "Representation Data and Metadata > Content-Type", + "anchor": "section-8.3", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "If a Content-Type header field is not present, the recipient MAY either assume a media type of \"application/octet-stream\" ([RFC2046], Section 4.5.1) or examine the data to determine its type." }, { - "id": "oas-3.2.server-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 272, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-name", - "level": "field", - "terms": [], - "text": "An optional unique string to refer to the host designated by the URL." + "id": "rfc9110.8.3.should-sender-generates-message-containing-content-generate", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4458, + "section": "Representation Data and Metadata > Content-Type", + "anchor": "section-8.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A sender that generates a message containing content SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender." }, { - "id": "oas-3.2.server-object.relative-references-in-api-urls.may-note-themselves-relative-referring-document", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 283, - "section": "Objects and Fields > Server Object > Relative References in API URLs", - "anchor": "relative-references-in-api-urls", - "level": "MAY", - "terms": ["MAY"], - "text": "Note that these themselves MAY be relative to the referring document." + "id": "rfc9110.8.4.1.1.should-recipient-consider-x-compress-equivalent-compress", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4675, + "section": "Representation Data and Metadata > Content-Encoding > Content Codings > Compress Coding", + "anchor": "section-8.4.1.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A recipient SHOULD consider \"x-compress\" to be equivalent to \"compress\"." }, { - "id": "oas-3.2.server-object.relative-references-in-api-urls.may-unless-specified-otherwise-all-fields-urls", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 281, - "section": "Objects and Fields > Server Object > Relative References in API URLs", - "anchor": "relative-references-in-api-urls", + "id": "rfc9110.8.4.1.3.should-recipient-consider-x-gzip-equivalent-gzip", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4701, + "section": "Representation Data and Metadata > Content-Encoding > Content Codings > Gzip Coding", + "anchor": "section-8.4.1.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A recipient SHOULD consider \"x-gzip\" to be equivalent to \"gzip\"." + }, + { + "id": "rfc9110.8.4.may-origin-server-respond-status-code-415", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4637, + "section": "Representation Data and Metadata > Content-Encoding", + "anchor": "section-8.4", "level": "MAY", "terms": ["MAY"], - "text": "Unless specified otherwise, all fields that are URLs MAY be relative references as defined by RFC3986." + "text": "An origin server MAY respond with a status code of 415 (Unsupported Media Type) if a representation in the request message has a content coding that is not acceptable." }, { - "id": "oas-3.2.server-object.url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 270, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-url", - "level": "field", - "terms": [], - "text": "REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served. Query and fragment MUST NOT be part of this URL. Variable substitutions will be made when a variable is named in `{`braces`}`." + "id": "rfc9110.8.4.must-one-more-encodings-have-applied-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4605, + "section": "Representation Data and Metadata > Content-Encoding", + "anchor": "section-8.4", + "level": "MUST", + "terms": ["MUST"], + "text": "If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied." }, { - "id": "oas-3.2.server-object.url.may-url-supports-server-variables-relative-indicate", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 270, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-url", + "id": "rfc9110.8.4.should-not-note-coding-named-identity-reserved-special", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4605, + "section": "Representation Data and Metadata > Content-Encoding", + "anchor": "section-8.4", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "Note that the coding named \"identity\" is reserved for its special role in Accept-Encoding and thus SHOULD NOT be included." + }, + { + "id": "rfc9110.8.5.may-content-language-applied-any-media-type", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4754, + "section": "Representation Data and Metadata > Content-Language", + "anchor": "section-8.5", "level": "MAY", "terms": ["MAY"], - "text": "This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the document containing the Server Object is being served." + "text": "Content-Language MAY be applied to any media type -- it is not limited to textual documents." }, { - "id": "oas-3.2.server-object.url.must-not-query-fragment-part-url", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 270, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-url", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "Query and fragment MUST NOT be part of this URL." + "id": "rfc9110.8.5.may-multiple-languages-listed-content-intended-multiple", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4738, + "section": "Representation Data and Metadata > Content-Language", + "anchor": "section-8.5", + "level": "MAY", + "terms": ["MAY"], + "text": "Multiple languages MAY be listed for content that is intended for multiple audiences." }, { - "id": "oas-3.2.server-object.url.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 270, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-url", + "id": "rfc9110.8.6.must-not-likewise-sender-forward-message-content-length", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4878, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT", "MAY"], + "text": "Likewise, a sender MUST NOT forward a message with a Content-Length header field value that does not match the ABNF above, with one exception: a recipient of a Content-Length header field value consisting of the same decimal value repeated as a comma-separated list (e.g, \"Content-Length: 42, 42\") MAY either reject the message as invalid or replace that invalid field value with a single instance of the decimal value, since this likely indicates that a duplicate was generated or combined by an upstream message processor." }, { - "id": "oas-3.2.server-object.variables", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 273, - "section": "Objects and Fields > Server Object > Fixed Fields", - "anchor": "server-variables", - "level": "field", - "terms": [], - "text": "A map between a variable name and its value. The value is used for substitution in the server's URL template." + "id": "rfc9110.8.6.must-not-result-sender-forward-message-content-length", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4874, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "As a result, a sender MUST NOT forward a message with a Content-Length header field value that is known to be incorrect." }, { - "id": "oas-3.2.server-variable-object.default", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 390, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", - "level": "field", - "terms": [], - "text": "REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. If the `enum` is defined, the value MUST exist in the enum's values. Note that this behavior is different from the Schema Object's `default` keyword, which documents the receiver's behavior rather than inserting the value into the data." + "id": "rfc9110.8.6.must-not-server-send-content-length-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4828, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", + "level": "MUST", + "terms": ["MAY", "MUST NOT"], + "text": "A server MAY send a Content-Length header field in a response to a HEAD request (Section 9.3.2); a server MUST NOT send Content-Length in such a response unless its field value equals the decimal number of octets that would have been sent in the content of a response if the same request had used the GET method." }, { - "id": "oas-3.2.server-variable-object.default.must-enum-defined-value-exist-enum-s", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 390, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "id": "rfc9110.8.6.must-not-server-send-content-length-header-field-2", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4835, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", "level": "MUST", - "terms": ["MUST"], - "text": "If the `enum` is defined, the value MUST exist in the enum's values." + "terms": ["MAY", "MUST NOT"], + "text": "A server MAY send a Content-Length header field in a 304 (Not Modified) response to a conditional GET request (Section 15.4.5); a server MUST NOT send Content-Length in such a response unless its field value equals the decimal number of octets that would have been sent in the content of a 200 (OK) response to the same request." }, { - "id": "oas-3.2.server-variable-object.default.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 390, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "id": "rfc9110.8.6.must-not-server-send-content-length-header-field-3", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4843, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST NOT"], + "text": "A server MUST NOT send a Content-Length header field in any response with a status code of 1xx (Informational) or 204 (No Content)." }, { - "id": "oas-3.2.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 390, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-default", + "id": "rfc9110.8.6.must-not-server-send-content-length-header-field-4", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4843, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", "level": "MUST", - "terms": ["SHALL"], - "text": "The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied." + "terms": ["MUST NOT"], + "text": "A server MUST NOT send a Content-Length header field in any 2xx (Successful) response to a CONNECT request (Section 9.3.6)." }, { - "id": "oas-3.2.server-variable-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 391, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-description", - "level": "field", - "terms": [], - "text": "An optional description for the server variable. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.8.6.must-since-no-predefined-limit-length-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4858, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", + "level": "MUST", + "terms": ["MUST"], + "text": "Since there is no predefined limit to the length of content, a recipient MUST anticipate potentially large decimal numerals and prevent parsing errors due to integer conversion overflows or precision loss due to integer conversion (Section 17.5)." }, { - "id": "oas-3.2.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 391, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-description", - "level": "MAY", - "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.8.6.should-aside-cases-defined-above-absence-transfer", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4850, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Aside from the cases defined above, in the absence of Transfer-Encoding, an origin server SHOULD send a Content-Length header field when the content size is known prior to sending the complete header section." }, { - "id": "oas-3.2.server-variable-object.enum", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 389, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-enum", - "level": "field", - "terms": [], - "text": "An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty." + "id": "rfc9110.8.6.should-not-user-agent-send-content-length-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4818, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A user agent SHOULD NOT send a Content-Length header field when the request message does not contain content and the method semantics do not anticipate such data." }, { - "id": "oas-3.2.server-variable-object.enum.must-not-array-empty", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 389, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "server-variable-enum", - "level": "MUST", - "terms": ["MUST NOT"], - "text": "The array MUST NOT be empty." + "id": "rfc9110.8.6.should-user-agent-send-content-length-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4818, + "section": "Representation Data and Metadata > Content-Length", + "anchor": "section-8.6", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A user agent SHOULD send Content-Length in a request when the method defines a meaning for enclosed content and it is not sending Transfer-Encoding." }, { - "id": "oas-3.2.server-variable-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 393, - "section": "Objects and Fields > Server Variable Object > Fixed Fields", - "anchor": "fixed-fields-4", + "id": "rfc9110.8.7.may-content-location-included-2xx-successful-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4919, + "section": "Representation Data and Metadata > Content-Location", + "anchor": "section-8.7", "level": "MAY", "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "text": "If Content-Location is included in a 2xx (Successful) response message and its value refers (after conversion to absolute form) to a URI that is the same as the target URI, then the recipient MAY consider the content to be a current representation of that resource at the time indicated by the message origination date." }, { - "id": "oas-3.2.server-variable-object.must-not-each-server-variable-appear-more-once", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 381, - "section": "Objects and Fields > Server Variable Object", - "anchor": "server-variable-object", + "id": "rfc9110.8.7.may-origin-server-use-context-guide-processing", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4969, + "section": "Representation Data and Metadata > Content-Location", + "anchor": "section-8.7", + "level": "MAY", + "terms": ["MAY"], + "text": "An origin server MAY use that context to guide in processing the request or to save it for other uses, such as within source links or versioning metadata." + }, + { + "id": "rfc9110.8.7.must-not-however-origin-server-use-context-information", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4969, + "section": "Representation Data and Metadata > Content-Location", + "anchor": "section-8.7", "level": "MUST", "terms": ["MUST NOT"], - "text": "Each server variable MUST NOT appear more than once in the URL template." + "text": "However, an origin server MUST NOT use such context information to alter the request semantics." }, { - "id": "oas-3.2.specification-extensions.optional-support-any-one-extension-support-one", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4780, - "section": "Specification Extensions", - "anchor": "specification-extensions", - "level": "MAY", - "terms": ["OPTIONAL"], - "text": "Support for any one extension is OPTIONAL, and support for one extension does not imply support for others." + "id": "rfc9110.8.7.must-origin-server-receives-content-location-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 4969, + "section": "Representation Data and Metadata > Content-Location", + "anchor": "section-8.7", + "level": "MUST", + "terms": ["MUST"], + "text": "An origin server that receives a Content-Location field in a request message MUST treat the information as transitory request context rather than as metadata to be saved verbatim as part of the representation." }, { - "id": "oas-3.2.specification-extensions.pattern-x", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4773, - "section": "Specification Extensions", - "anchor": "extension-properties", - "level": "field", - "terms": [], - "text": "Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the OpenAPI Initiative. The value can be any valid JSON value (`null`, a primitive, an array, or an object.)" + "id": "rfc9110.8.8.1.should-origin-server-change-weak-entity-tag", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5092, + "section": "Representation Data and Metadata > Validator Fields > Weak versus Strong", + "anchor": "section-8.8.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server SHOULD change a weak entity tag whenever it considers prior representations to be unacceptable as a substitute for the current representation." }, { - "id": "oas-3.2.specification-extensions.pattern-x.must-field-name-begin-x-example-x", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4773, - "section": "Specification Extensions", - "anchor": "extension-properties", + "id": "rfc9110.8.8.2.1.must-last-modification-time-derived-implementation-specific", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5174, + "section": "Representation Data and Metadata > Validator Fields > Last-Modified > Generation", + "anchor": "section-8.8.2.1", "level": "MUST", "terms": ["MUST"], - "text": "The field name MUST begin with `x-`, for example, `x-internal-id`." + "text": "If the last modification time is derived from implementation-specific metadata that evaluates to some time in the future, according to the origin server's clock, then the origin server MUST replace that value with the message origination date." }, { - "id": "oas-3.2.specification-extensions.recommended-therefore-implementations-designed-extensibility-support-community", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 4777, - "section": "Specification Extensions", - "anchor": "specification-extensions", + "id": "rfc9110.8.8.2.1.must-not-origin-server-clock-defined-section-5", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5174, + "section": "Representation Data and Metadata > Validator Fields > Last-Modified > Generation", + "anchor": "section-8.8.2.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "An origin server with a clock (as defined in Section 5.6.7) MUST NOT generate a Last-Modified date that is later than the server's time of message origination (Date, Section 6.6.1)." + }, + { + "id": "rfc9110.8.8.2.1.must-not-origin-server-without-clock-generate-last", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5185, + "section": "Representation Data and Metadata > Validator Fields > Last-Modified > Generation", + "anchor": "section-8.8.2.1", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "An origin server without a clock MUST NOT generate a Last-Modified date for a response unless that date value was assigned to the resource by some other system (presumably one with a clock)." + }, + { + "id": "rfc9110.8.8.2.1.should-origin-server-obtain-last-modified-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5166, + "section": "Representation Data and Metadata > Validator Fields > Last-Modified > Generation", + "anchor": "section-8.8.2.1", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "It is therefore RECOMMENDED that implementations be designed for extensibility to support community experimentation." + "terms": ["SHOULD"], + "text": "An origin server SHOULD obtain the Last-Modified value of the representation as close as possible to the time that it generates the Date field value for its response." }, { - "id": "oas-3.2.tag-object.description", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2923, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-description", - "level": "field", - "terms": [], - "text": "A description for the tag. CommonMark syntax MAY be used for rich text representation." + "id": "rfc9110.8.8.2.1.should-origin-server-send-last-modified-any", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5151, + "section": "Representation Data and Metadata > Validator Fields > Last-Modified > Generation", + "anchor": "section-8.8.2.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server SHOULD send Last-Modified for any selected representation for which a last modification date can be reasonably and consistently determined, since its use in conditional requests and evaluating cache freshness ([CACHING]) can substantially reduce unnecessary transfers and significantly improve service availability and scalability." }, { - "id": "oas-3.2.tag-object.description.may-commonmark-syntax-used-rich-text-representation", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2923, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-description", + "id": "rfc9110.8.8.3.1.should-origin-server-send-etag-any-selected", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5325, + "section": "Representation Data and Metadata > Validator Fields > ETag > Generation", + "anchor": "section-8.8.3.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server SHOULD send an ETag for any selected representation for which detection of changes can be reasonably and consistently determined, since the entity tag's use in conditional requests and evaluating cache freshness ([CACHING]) can substantially reduce unnecessary transfers and significantly improve service availability, scalability, and reliability." + }, + { + "id": "rfc9110.8.8.3.may-sender-send-etag-field-trailer-section", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5300, + "section": "Representation Data and Metadata > Validator Fields > ETag", + "anchor": "section-8.8.3", "level": "MAY", "terms": ["MAY"], - "text": "CommonMark syntax MAY be used for rich text representation." + "text": "A sender MAY send the ETag field in a trailer section (see Section 6.5)." }, { - "id": "oas-3.2.tag-object.externalDocs", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2924, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-external-docs", - "level": "field", - "terms": [], - "text": "Additional external documentation for this tag." + "id": "rfc9110.8.8.3.must-origin-server-provides-entity-tag-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5291, + "section": "Representation Data and Metadata > Validator Fields > ETag", + "anchor": "section-8.8.3", + "level": "MUST", + "terms": ["MUST"], + "text": "If an origin server provides an entity tag for a representation and the generation of that entity tag does not satisfy all of the characteristics of a strong validator (Section 8.8.1), then the origin server MUST mark the entity tag as weak by prefixing its opaque value with \"W/\" (case-sensitive)." }, { - "id": "oas-3.2.tag-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2928, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "fixed-fields-18", + "id": "rfc9110.9.1.must-all-general-purpose-servers-support-methods", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5573, + "section": "Methods > Overview", + "anchor": "section-9.1", + "level": "MUST", + "terms": ["MUST"], + "text": "All general-purpose servers MUST support the methods GET and HEAD." + }, + { + "id": "rfc9110.9.1.optional-all-other-methods", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5573, + "section": "Methods > Overview", + "anchor": "section-9.1", "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "terms": ["OPTIONAL"], + "text": "All other methods are OPTIONAL." }, { - "id": "oas-3.2.tag-object.kind", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2926, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-kind", - "level": "field", - "terms": [], - "text": "A machine-readable string to categorize what sort of tag it is. Any string value can be used; common uses are `nav` for Navigation, `badge` for visible badges, `audience` for APIs used by different groups. A registry of the most commonly used values is available." + "id": "rfc9110.9.1.should-origin-server-receives-request-method-recognized", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5577, + "section": "Methods > Overview", + "anchor": "section-9.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server that receives a request method that is recognized and implemented, but not allowed for the target resource, SHOULD respond with the 405 (Method Not Allowed) status code." }, { - "id": "oas-3.2.tag-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2921, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-name", - "level": "field", - "terms": [], - "text": "REQUIRED. The name of the tag. Use this value in the `tags` array of an Operation." + "id": "rfc9110.9.1.should-origin-server-receives-request-method-unrecognized", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5577, + "section": "Methods > Overview", + "anchor": "section-9.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "An origin server that receives a request method that is unrecognized or not implemented SHOULD respond with the 501 (Not Implemented) status code." }, { - "id": "oas-3.2.tag-object.name.required", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2921, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-name", + "id": "rfc9110.9.2.1.must-purpose-resource-perform-unsafe-action-resource", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5639, + "section": "Methods > Common Method Properties > Safe Methods", + "anchor": "section-9.2.1", "level": "MUST", - "terms": ["REQUIRED"], - "text": "REQUIRED." + "terms": ["MUST"], + "text": "If the purpose of such a resource is to perform an unsafe action, then the resource owner MUST disable or disallow that action when it is accessed using a safe request method." }, { - "id": "oas-3.2.tag-object.parent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2925, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-parent", - "level": "field", - "terms": [], - "text": "The `name` of a tag that this tag is nested under. The named tag MUST exist in the API description, and circular references between parent and child tags MUST NOT be used." + "id": "rfc9110.9.2.1.should-user-agent-distinguish-between-safe-unsafe", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5634, + "section": "Methods > Common Method Properties > Safe Methods", + "anchor": "section-9.2.1", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A user agent SHOULD distinguish between safe and unsafe methods when presenting potential actions to a user, such that the user can be made aware of an unsafe action before it is requested." }, { - "id": "oas-3.2.tag-object.parent.must-named-tag-exist-api-description-circular", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2925, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-parent", + "id": "rfc9110.9.2.2.must-not-proxy-automatically-retry-non-idempotent-requests", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5703, + "section": "Methods > Common Method Properties > Idempotent Methods", + "anchor": "section-9.2.2", "level": "MUST", - "terms": ["MUST", "MUST NOT"], - "text": "The named tag MUST exist in the API description, and circular references between parent and child tags MUST NOT be used." + "terms": ["MUST NOT"], + "text": "A proxy MUST NOT automatically retry non-idempotent requests." }, { - "id": "oas-3.2.tag-object.summary", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 2922, - "section": "Objects and Fields > Tag Object > Fixed Fields", - "anchor": "tag-summary", - "level": "field", - "terms": [], - "text": "A short summary of the tag, used for display purposes." + "id": "rfc9110.9.2.2.should-not-client-automatically-retry-failed-automatic-retry", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5703, + "section": "Methods > Common Method Properties > Idempotent Methods", + "anchor": "section-9.2.2", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A client SHOULD NOT automatically retry a failed automatic retry." }, { - "id": "oas-3.2.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 35, - "section": "Introduction > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", + "id": "rfc9110.9.2.2.should-not-client-automatically-retry-request-non-idempotent", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5681, + "section": "Methods > Common Method Properties > Idempotent Methods", + "anchor": "section-9.2.2", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied." + }, + { + "id": "rfc9110.9.3.1.may-response-get-request-cacheable-cache-use", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5784, + "section": "Methods > Method Definitions > GET", + "anchor": "section-9.3.1", "level": "MAY", "terms": ["MAY"], - "text": "Implementations MAY support undefined scenarios for historical reasons, including ambiguous text in prior versions of the specification." + "text": "The response to a GET request is cacheable; a cache MAY use it to satisfy subsequent GET and HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [CACHING])." }, { - "id": "oas-3.2.undefined-and-implementation-defined-behavior.not-recommended-support-might-produce-correct-outcomes-many", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 35, - "section": "Introduction > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", + "id": "rfc9110.9.3.1.should-not-client-generate-content-get-request-unless", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5770, + "section": "Methods > Method Definitions > GET", + "anchor": "section-9.3.1", "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "This support might produce correct outcomes in many cases, but relying on it is NOT RECOMMENDED as there is no guarantee that it will work across all tools or with future specification versions, even if those versions are otherwise strictly compatible with this one." + "terms": ["SHOULD NOT"], + "text": "A client SHOULD NOT generate content in a GET request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported." }, { - "id": "oas-3.2.undefined-and-implementation-defined-behavior.recommended-documents-ambiguous-requirements-api-description-authors", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 40, - "section": "Introduction > Undefined and Implementation-Defined Behavior", - "anchor": "undefined-and-implementation-defined-behavior", + "id": "rfc9110.9.3.1.should-not-origin-server-rely-private-agreements-receive", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5770, + "section": "Methods > Method Definitions > GET", + "anchor": "section-9.3.1", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "This documents ambiguous requirements that API description authors are RECOMMENDED to avoid in order to maximize interoperability." + "terms": ["SHOULD NOT"], + "text": "An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain." }, { - "id": "oas-3.2.versions-and-deprecation.shall-major-minor-portion-version-string-example", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 21, - "section": "Introduction > Versions and Deprecation", - "anchor": "versions-and-deprecation", + "id": "rfc9110.9.3.2.may-however-server-omit-header-fields-value", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5813, + "section": "Methods > Method Definitions > HEAD", + "anchor": "section-9.3.2", + "level": "MAY", + "terms": ["MAY"], + "text": "However, a server MAY omit header fields for which a value is determined only while generating the content." + }, + { + "id": "rfc9110.9.3.2.may-response-head-request-cacheable-cache-use", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5841, + "section": "Methods > Method Definitions > HEAD", + "anchor": "section-9.3.2", + "level": "MAY", + "terms": ["MAY"], + "text": "The response to a HEAD request is cacheable; a cache MAY use it to satisfy subsequent HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [CACHING])." + }, + { + "id": "rfc9110.9.3.2.must-not-head-method-identical-get-except-server", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5806, + "section": "Methods > Method Definitions > HEAD", + "anchor": "section-9.3.2", "level": "MUST", - "terms": ["SHALL"], - "text": "The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set." + "terms": ["MUST NOT"], + "text": "The HEAD method is identical to GET except that the server MUST NOT send content in the response." }, { - "id": "oas-3.2.versions-and-deprecation.should-not-patch-version-considered-tooling-making-no", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 21, - "section": "Introduction > Versions and Deprecation", - "anchor": "versions-and-deprecation", + "id": "rfc9110.9.3.2.should-not-client-generate-content-head-request-unless", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5827, + "section": "Methods > Method Definitions > HEAD", + "anchor": "section-9.3.2", "level": "SHOULD", "terms": ["SHOULD NOT"], - "text": "The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example." + "text": "A client SHOULD NOT generate content in a HEAD request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported." }, { - "id": "oas-3.2.versions-and-deprecation.should-tooling-supports-oas-3-1-compatible", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 21, - "section": "Introduction > Versions and Deprecation", - "anchor": "versions-and-deprecation", + "id": "rfc9110.9.3.2.should-not-origin-server-rely-private-agreements-receive", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5827, + "section": "Methods > Method Definitions > HEAD", + "anchor": "section-9.3.2", "level": "SHOULD", - "terms": ["SHOULD"], - "text": "Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.* versions." + "terms": ["SHOULD NOT"], + "text": "An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain." }, { - "id": "oas-3.2.warnings-regarding-fragmentary-parsing.not-recommended-while-possible-structure-certain-openapi-descriptions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 5499, - "section": "Appendix G: Parsing and Resolution Guidance > Warnings Regarding Fragmentary Parsing", - "anchor": "warnings-regarding-fragmentary-parsing", + "id": "rfc9110.9.3.2.should-server-send-same-header-fields-response", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5813, + "section": "Methods > Method Definitions > HEAD", + "anchor": "section-9.3.2", "level": "SHOULD", - "terms": ["NOT RECOMMENDED"], - "text": "While it is possible to structure certain OpenAPI Descriptions to ensure that they will behave correctly when references are parsed as isolated fragments, depending on this is NOT RECOMMENDED." + "terms": ["SHOULD"], + "text": "The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request method had been GET." }, { - "id": "oas-3.2.xml-object.attribute", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3847, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-attribute", - "level": "field", - "terms": [], - "text": "Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. If `nodeType` is present, this field MUST NOT be present. Deprecated: Use `nodeType: \"attribute\"` instead of `attribute: true`" + "id": "rfc9110.9.3.3.may-result-processing-post-would-equivalent-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5892, + "section": "Methods > Method Definitions > POST", + "anchor": "section-9.3.3", + "level": "MAY", + "terms": ["MAY"], + "text": "If the result of processing a POST would be equivalent to a representation of an existing resource, an origin server MAY redirect the user agent to that resource by sending a 303 (See Other) response with the existing resource's identifier in the Location field." }, { - "id": "oas-3.2.xml-object.attribute.must-not-nodetype-present-field-present", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3847, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-attribute", + "id": "rfc9110.9.3.3.should-one-more-resources-created-origin-server", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5875, + "section": "Methods > Method Definitions > POST", + "anchor": "section-9.3.3", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If one or more resources has been created on the origin server as a result of successfully processing a POST request, the origin server SHOULD send a 201 (Created) response containing a Location header field that provides an identifier for the primary resource created (Section 10.2.2) and a representation that describes the status of the request while referring to the new resource(s)." + }, + { + "id": "rfc9110.9.3.4.must-not-origin-server-send-validator-field-section", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5980, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", "level": "MUST", "terms": ["MUST NOT"], - "text": "If `nodeType` is present, this field MUST NOT be present." + "text": "An origin server MUST NOT send a validator field (Section 8.8), such as an ETag or Last-Modified field, in a successful response to PUT unless the request's representation data was saved without any transformation applied to the content (i.e., the resource's new representation data is identical to the content received in the PUT request) and the validator field value reflects the new representation." }, { - "id": "oas-3.2.xml-object.fixed-fields.may-object-extended-specification-extensions", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3855, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "fixed-fields-22", - "level": "MAY", - "terms": ["MAY"], - "text": "This object MAY be extended with Specification Extensions." + "id": "rfc9110.9.3.4.must-origin-server-will-not-make-requested", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6004, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", + "level": "MUST", + "terms": ["MUST", "MAY"], + "text": "If the origin server will not make the requested PUT state change to the target resource and instead wishes to have it applied to a different resource, such as when the resource has been moved to a different URI, then the origin server MUST send an appropriate 3xx (Redirection) response; the user agent MAY then make its own decision regarding whether or not to redirect the request." }, { - "id": "oas-3.2.xml-object.handling-null-values.recommended-however-because-no-distinct-way-represent", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3914, - "section": "Objects and Fields > XML Object > Handling `null` Values", - "anchor": "handling-null-values", + "id": "rfc9110.9.3.4.must-target-resource-does-have-current-representation", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5920, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", + "level": "MUST", + "terms": ["MUST"], + "text": "If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the request." + }, + { + "id": "rfc9110.9.3.4.must-target-resource-does-not-have-current", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5920, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", + "level": "MUST", + "terms": ["MUST"], + "text": "If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response." + }, + { + "id": "rfc9110.9.3.4.should-origin-server-verify-put-representation-consistent", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5930, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", "level": "SHOULD", - "terms": ["RECOMMENDED"], - "text": "However, because there is no distinct way to represent `null` as an attribute, it is RECOMMENDED to make attribute properties optional rather than use `null`." + "terms": ["SHOULD"], + "text": "An origin server SHOULD verify that the PUT representation is consistent with its configured constraints for the target resource." }, { - "id": "oas-3.2.xml-object.handling-null-values.should-ensure-correct-round-trip-behavior-parsing", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3918, - "section": "Objects and Fields > XML Object > Handling `null` Values", - "anchor": "handling-null-values", + "id": "rfc9110.9.3.4.should-put-representation-inconsistent-target-resource-origin", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5930, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", "level": "SHOULD", "terms": ["SHOULD"], - "text": "To ensure correct round-trip behavior, when parsing an element that omits an attribute, implementations SHOULD set the corresponding property to `null` if the schema allows for that value (e.g. `type: [\"number\", \"null\"]`), and omit the property otherwise (e.g.`type: \"number\"`)." + "text": "When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable." }, { - "id": "oas-3.2.xml-object.handling-null-values.should-however-implementations-handle-null-values-follows", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3908, - "section": "Objects and Fields > XML Object > Handling `null` Values", - "anchor": "handling-null-values", + "id": "rfc9110.9.3.4.should-result-origin-server-ignore-unrecognized-header", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 5971, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", "level": "SHOULD", "terms": ["SHOULD"], - "text": "However, implementations SHOULD handle `null` values as follows:" + "text": "As a result, an origin server SHOULD ignore unrecognized header and trailer fields received in a PUT request (i.e., not save them as part of the resource state)." }, { - "id": "oas-3.2.xml-object.name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3844, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-name", - "level": "field", - "terms": [], - "text": "Sets the name of the element/attribute corresponding to the schema, replacing the name that was inferred as described under XML Node Names. This field SHALL be ignored if the `nodeType` is `text`, `cdata`, or `none`." + "id": "rfc9110.9.3.4.should-service-selects-proper-uri-behalf-client", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6004, + "section": "Methods > Method Definitions > PUT", + "anchor": "section-9.3.4", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A service that selects a proper URI on behalf of the client, after receiving a state-changing request, SHOULD be implemented using the POST method rather than PUT." }, { - "id": "oas-3.2.xml-object.name.shall-field-ignored-nodetype-text-cdata-none", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3844, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-name", - "level": "MUST", - "terms": ["SHALL"], - "text": "This field SHALL be ignored if the `nodeType` is `text`, `cdata`, or `none`." + "id": "rfc9110.9.3.5.should-delete-method-successfully-applied-origin-server", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6073, + "section": "Methods > Method Definitions > DELETE", + "anchor": "section-9.3.5", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "If a DELETE method is successfully applied, the origin server SHOULD send" }, { - "id": "oas-3.2.xml-object.namespace", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3845, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-namespace", - "level": "field", - "terms": [], - "text": "The IRI ([RFC3987]) of the namespace definition. Value MUST be in the form of a non-relative IRI." + "id": "rfc9110.9.3.5.should-not-client-generate-content-delete-request-unless", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6084, + "section": "Methods > Method Definitions > DELETE", + "anchor": "section-9.3.5", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "A client SHOULD NOT generate content in a DELETE request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported." }, { - "id": "oas-3.2.xml-object.namespace.must-value-form-non-relative-iri", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3845, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-namespace", + "id": "rfc9110.9.3.5.should-not-origin-server-rely-private-agreements-receive", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6084, + "section": "Methods > Method Definitions > DELETE", + "anchor": "section-9.3.5", + "level": "SHOULD", + "terms": ["SHOULD NOT"], + "text": "An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain." + }, + { + "id": "rfc9110.9.3.6.may-origin-server-accept-connect-request-but", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6139, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", + "level": "MAY", + "terms": ["MAY"], + "text": "An origin server MAY accept a CONNECT request, but most origin servers do not implement CONNECT." + }, + { + "id": "rfc9110.9.3.6.must-client-ignore-any-content-length-transfer", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6180, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", "level": "MUST", "terms": ["MUST"], - "text": "Value MUST be in the form of a non-relative IRI." + "text": "A client MUST ignore any Content-Length or Transfer-Encoding header fields received in a successful response to CONNECT." }, { - "id": "oas-3.2.xml-object.nodeType", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3843, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-node-type", - "level": "field", - "terms": [], - "text": "One of `element`, `attribute`, `text`, `cdata`, or `none`, as explained under XML Node Types. The default value is `none` if `$ref`, `$dynamicRef`, or `type: \"array\"` is present in the Schema Object containing the XML Object, and `element` otherwise." + "id": "rfc9110.9.3.6.must-no-default-port-client-send-port", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6118, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", + "level": "MUST", + "terms": ["MUST"], + "text": "There is no default port; a client MUST send the port number even if the CONNECT request is based on a URI reference that contains an authority component with an elided port (Section 4.1)." }, { - "id": "oas-3.2.xml-object.prefix", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3846, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-prefix", - "level": "field", - "terms": [], - "text": "The prefix to be used for the name." + "id": "rfc9110.9.3.6.must-not-server-send-any-transfer-encoding-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6180, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", + "level": "MUST", + "terms": ["MUST NOT"], + "text": "A server MUST NOT send any Transfer-Encoding or Content-Length header fields in a 2xx (Successful) response to CONNECT." }, { - "id": "oas-3.2.xml-object.wrapped", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3848, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-wrapped", - "level": "field", - "terms": [], - "text": "MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `\"array\"` (outside the `items`). If `nodeType` is present, this field MUST NOT be present. Deprecated: Use `nodeType: \"element\"` instead of `wrapped: true`" + "id": "rfc9110.9.3.6.must-server-reject-connect-request-targets-empty", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6130, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", + "level": "MUST", + "terms": ["MUST"], + "text": "A server MUST reject a CONNECT request that targets an empty or invalid port number, typically by responding with a 400 (Bad Request) status code." }, { - "id": "oas-3.2.xml-object.wrapped.may-used-only-array-definition", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3848, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-wrapped", + "id": "rfc9110.9.3.6.must-tunnel-closed-tunnel-intermediary-detects-either", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6155, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", + "level": "MUST", + "terms": ["MUST"], + "text": "A tunnel is closed when a tunnel intermediary detects that either side has closed its connection: the intermediary MUST attempt to send any outstanding data that came from the closed side to the other side, close both connections, and then discard any remaining data left undelivered." + }, + { + "id": "rfc9110.9.3.6.should-proxies-support-connect-restrict-use-limited", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6170, + "section": "Methods > Method Definitions > CONNECT", + "anchor": "section-9.3.6", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "Proxies that support CONNECT SHOULD restrict its use to a limited set of known ports or a configurable list of safe request targets." + }, + { + "id": "rfc9110.9.3.7.may-client-send-max-forwards-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6231, + "section": "Methods > Method Definitions > OPTIONS", + "anchor": "section-9.3.7", "level": "MAY", "terms": ["MAY"], - "text": "MAY be used only for an array definition." + "text": "A client MAY send a Max-Forwards header field in an OPTIONS request to target a specific recipient in the request chain (see Section 7.6.2)." }, { - "id": "oas-3.2.xml-object.wrapped.must-not-nodetype-present-field-present", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3848, - "section": "Objects and Fields > XML Object > Fixed Fields", - "anchor": "xml-wrapped", + "id": "rfc9110.9.3.7.must-client-generates-options-request-containing-content", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6238, + "section": "Methods > Method Definitions > OPTIONS", + "anchor": "section-9.3.7", + "level": "MUST", + "terms": ["MUST"], + "text": "A client that generates an OPTIONS request containing content MUST send a valid Content-Type header field describing the representation media type." + }, + { + "id": "rfc9110.9.3.7.must-not-proxy-generate-max-forwards-header-field", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6231, + "section": "Methods > Method Definitions > OPTIONS", + "anchor": "section-9.3.7", "level": "MUST", "terms": ["MUST NOT"], - "text": "If `nodeType` is present, this field MUST NOT be present." + "text": "A proxy MUST NOT generate a Max-Forwards header field while forwarding a request unless that request was received with a Max-Forwards field." }, { - "id": "oas-3.2.xml-object.xml-node-names.must-all-other-cases-inline-schema-under", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3893, - "section": "Objects and Fields > XML Object > XML Node Names", - "anchor": "xml-node-names", + "id": "rfc9110.9.3.7.should-server-generating-successful-response-options-send", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6221, + "section": "Methods > Method Definitions > OPTIONS", + "anchor": "section-9.3.7", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "A server generating a successful response to OPTIONS SHOULD send any header that might indicate optional features implemented by the server and applicable to the target resource (e.g., Allow), including potential extensions not defined by this specification." + }, + { + "id": "rfc9110.9.3.8.must-not-client-generate-fields-trace-request-containing", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6262, + "section": "Methods > Method Definitions > TRACE", + "anchor": "section-9.3.8", "level": "MUST", - "terms": ["MUST"], - "text": "In all other cases, such as an inline schema under a Media Type Object's `schema` field, no name can be inferred and an XML Object with a `name` field MUST be present." + "terms": ["MUST NOT"], + "text": "A client MUST NOT generate fields in a TRACE request containing sensitive data that might be disclosed by the response." }, { - "id": "oas-3.2.xml-object.xml-node-names.must-element-attribute-node-types-require-name", - "spec": "openapi", - "version": "3.2.1", - "source": "openapi/3.2.1.md", - "line": 3889, - "section": "Objects and Fields > XML Object > XML Node Names", - "anchor": "xml-node-names", + "id": "rfc9110.9.3.8.must-not-client-send-content-trace-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6280, + "section": "Methods > Method Definitions > TRACE", + "anchor": "section-9.3.8", "level": "MUST", - "terms": ["MUST"], - "text": "The `element` and `attribute` node types require a name, which MUST be inferred from the schema as follows, unless overridden by the `name` field:" + "terms": ["MUST NOT"], + "text": "A client MUST NOT send content in a TRACE request." + }, + { + "id": "rfc9110.9.3.8.should-final-recipient-request-exclude-any-request", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6262, + "section": "Methods > Method Definitions > TRACE", + "anchor": "section-9.3.8", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The final recipient of the request SHOULD exclude any request fields that are likely to contain sensitive data when that recipient generates the response content." + }, + { + "id": "rfc9110.9.3.8.should-final-recipient-request-reflect-message-received", + "spec": "rfc", + "version": "9110", + "source": "rfc/rfc9110.xml", + "line": 6252, + "section": "Methods > Method Definitions > TRACE", + "anchor": "section-9.3.8", + "level": "SHOULD", + "terms": ["SHOULD"], + "text": "The final recipient of the request SHOULD reflect the message received, excluding some fields described below, back to the client as the content of a 200 (OK) response." } ] } diff --git a/conformance/results/sdk-rust.md b/conformance/results/sdk-rust.md index 9189d0c..bf4d20a 100644 --- a/conformance/results/sdk-rust.md +++ b/conformance/results/sdk-rust.md @@ -5,10 +5,10 @@ Written by `cargo run --release -j 1 --bin sdk-rust` in `conformance/sdk-rust`; | Oracle | Checked | Differ | | --- | ---: | ---: | | OpenAPI 3.2.1 "Style Examples" (conformance/specs/openapi/3.2.1.md:902), each cell not _n/a_ | 51 | 0 | -| conformance/sdk/cases.json: 51 cases, each in its versions | 234 | 0 | +| conformance/sdk/cases.json: 64 cases, each in its versions | 261 | 0 | | conformance/sdk-rust/cases.json, the Rust types' own: 5 cases | 39 | 0 | -4 calls are held to `conformance/sdk-rust/order.json`: an object with no named properties is a `BTreeMap` in Rust, so its members are written in key order. +16 calls are held to `conformance/sdk-rust/order.json`: an object with no named properties is a `BTreeMap` in Rust, so its members are written in key order. ## Differences diff --git a/conformance/results/sdk.md b/conformance/results/sdk.md index 3ebaf8f..65a9d0b 100644 --- a/conformance/results/sdk.md +++ b/conformance/results/sdk.md @@ -5,7 +5,13 @@ Written by `node conformance/sdk/run.mjs --corpus`; do not edit. Every request a | Oracle | Checked | Differ | | --- | ---: | ---: | | OpenAPI 3.2.1 "Style Examples" (conformance/specs/openapi/3.2.1.md:902), each cell not _n/a_ | 51 | 0 | -| conformance/sdk/cases.json: 51 cases, each in its versions | 438 | 0 | +| conformance/sdk/cases.json: 64 cases, each in its versions | 489 | 0 | + +| Description | Operations | Type errors | +| --- | ---: | ---: | +| github | 1281 | 0 | +| stripe | 612 | 0 | +| cloudflare | 3935 | 0 | ## Differences diff --git a/conformance/scope.json b/conformance/scope.json index e8efe2c..4a6efe9 100644 --- a/conformance/scope.json +++ b/conformance/scope.json @@ -1,6 +1,6 @@ { - "status": "decided 2026-11-24 by the maintainers, owner delegated", - "about": "Which requirements of requirements.json flowapi answers for. Edited by hand; read by `cargo run --release --bin report` and `--bin classify` in conformance/ledger/. A rule's `match` is an id or an id prefix ending at a `.`; `*` stands for a version (`oas-*` is oas-3.0, oas-3.1 and oas-3.2). The longest match wins. A rule that fits no id, or an id no rule fits, fails the report. `in-scope` ids end as covered (a `req:` marker in a test) or, once the marker exists, lossy with a reason; `out-of-scope` ids carry the reason a types generator does not answer for them. Serialization is the SDK's (map FA-012): the parts O8 (conformance/sdk) runs are in scope, each named by a case of conformance/sdk/cases.json; the rest stays out with its reason; operations themselves are in scope.", + "status": "decided 2026-11-24, the SDK stage 2026-11-26 (triage-3.md), by the maintainers, owner delegated", + "about": "Which requirements of requirements.json flowapi answers for. Edited by hand; read by `cargo run --release --bin report` and `--bin classify` in conformance/ledger/. A rule's `match` is an id or an id prefix ending at a `.`; `*` stands for a version (`oas-*` is oas-2.0, oas-3.0, oas-3.1 and oas-3.2). The longest match wins. A rule that fits no id, or an id no rule fits, fails the report. `in-scope` ids end as covered (a `req:` marker in a test) or lossy with a reason; until then MISSING.md lists them. An `in-scope` rule's `note` names the layer that answers: the types (crates/flowapi and a target), the SDK layer's table (crates/flowapi-sdk), its client runtime (crates/flowapi-sdk/src/client/core) or the serializer O8 runs (conformance/sdk). `out-of-scope` ids carry the reason none of them answers for the id: a rule for an author, a server or an intermediary, a permission not taken, or what the platform's fetch does. The decisions and their reasons: triage-2.md (2026-11-24) and triage-3.md (2026-11-26, the SDK stage, Swagger 2.0 and the RFCs).", "rules": [ { "match": "oas-*.schema-object", "class": "in-scope", "note": "The Schema Object: the types themselves." }, { "match": "oas-*.schema-object.xml", "class": "out-of-scope", "reason": "XML serialization metadata; flowapi generates JSON types." }, @@ -10,11 +10,11 @@ { "match": "oas-*.conditions-for-using-the-discriminator-object", "class": "in-scope", "note": "Tagged unions." }, { "match": "oas-*.reference-object", "class": "in-scope", "note": "$ref resolution." }, { "match": "oas-*.components-object", "class": "in-scope", "note": "Named types come from components." }, - { "match": "oas-*.components-object.securitySchemes", "class": "out-of-scope", "reason": "Authentication; no data type." }, - { "match": "oas-*.components-object.links", "class": "out-of-scope", "reason": "Links between operations at run time; no data type." }, - { "match": "oas-*.components-object.callbacks", "class": "out-of-scope", "reason": "Callbacks are requests the API makes; out of the first scope (types of the described API's own operations)." }, + { "match": "oas-*.components-object.securitySchemes", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.components-object.links", "class": "out-of-scope", "reason": "Links between operations: the SDK's client does not follow links, and no type depends on them." }, + { "match": "oas-*.components-object.callbacks", "class": "out-of-scope", "reason": "Requests the API makes to its caller (callbacks, webhooks): the SDK's client only sends the described operations, and its mock only answers them." }, { "match": "oas-*.components-object.examples", "class": "out-of-scope", "reason": "Example values; change no type." }, - { "match": "oas-*.parameter-object", "class": "in-scope", "note": "Parameter types; their serialization is the SDK stage's, out of scope below." }, + { "match": "oas-*.parameter-object", "class": "in-scope", "note": "Parameter types, and how each is serialized (the SDK, O8 in conformance/sdk)." }, { "match": "oas-*.parameter-object.example", "class": "out-of-scope", "reason": "An example value; changes no type." }, { "match": "oas-*.parameter-object.examples", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.header-object", "class": "in-scope", "note": "Header types." }, @@ -22,28 +22,28 @@ { "match": "oas-*.header-object.examples", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.request-body-object", "class": "in-scope", "note": "Request body types." }, { "match": "oas-*.response-object", "class": "in-scope", "note": "Response types." }, - { "match": "oas-*.response-object.links", "class": "out-of-scope", "reason": "Links between operations at run time; no data type." }, + { "match": "oas-*.response-object.links", "class": "out-of-scope", "reason": "Links between operations: the SDK's client does not follow links, and no type depends on them." }, { "match": "oas-*.responses-object", "class": "in-scope", "note": "Responses by status code." }, { "match": "oas-*.media-type-object", "class": "in-scope", "note": "Media types, schemas per media type, streaming items." }, { "match": "oas-*.media-type-object.example", "class": "out-of-scope", "reason": "An example value; changes no type." }, { "match": "oas-*.media-type-object.examples", "class": "out-of-scope", "reason": "Example values; change no type." }, - { "match": "oas-*.encoding-object", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, + { "match": "oas-*.encoding-object", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, { "match": "oas-*.paths-object", "class": "in-scope", "note": "Operations are found through paths; path templates give path parameters." }, { "match": "oas-*.path-item-object", "class": "in-scope", "note": "Operations and shared parameters." }, - { "match": "oas-*.path-item-object.servers", "class": "out-of-scope", "reason": "Where the API is served; a run-time base URL, no data type." }, + { "match": "oas-*.path-item-object.servers", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-*.operation-object", "class": "in-scope", "note": "operationId names types; parameters, request body and responses are types." }, - { "match": "oas-*.operation-object.tags", "class": "out-of-scope", "reason": "Grouping for documentation; no data type." }, + { "match": "oas-*.operation-object.tags", "class": "out-of-scope", "reason": "Grouping for documentation. No type depends on it; the SDK's draft config names a resource after an operation's first tag, a suggestion the config then states." }, { "match": "oas-*.operation-object.externalDocs", "class": "out-of-scope", "reason": "A link to documentation; changes no type." }, - { "match": "oas-*.operation-object.callbacks", "class": "out-of-scope", "reason": "Callbacks are requests the API makes; out of the first scope." }, + { "match": "oas-*.operation-object.callbacks", "class": "out-of-scope", "reason": "Requests the API makes to its caller (callbacks, webhooks): the SDK's client only sends the described operations, and its mock only answers them." }, { "match": "oas-*.operation-object.security", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, - { "match": "oas-*.operation-object.servers", "class": "out-of-scope", "reason": "Where the API is served; a run-time base URL, no data type." }, + { "match": "oas-*.operation-object.servers", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-*.openapi-object", "class": "in-scope", "note": "The document: its version, $self, jsonSchemaDialect, paths, components; in 3.2 also the structure and reference sections under it." }, - { "match": "oas-*.openapi-object.info", "class": "out-of-scope", "reason": "Metadata about the API; no data type." }, + { "match": "oas-*.openapi-object.info", "class": "out-of-scope", "reason": "Metadata about the API. No type depends on it; the SDK copies the title and version into its package and README as written, which asks nothing of a reader." }, { "match": "oas-*.openapi-object.servers", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, - { "match": "oas-*.openapi-object.security", "class": "out-of-scope", "reason": "Authentication; no data type." }, - { "match": "oas-*.openapi-object.tags", "class": "out-of-scope", "reason": "Grouping for documentation; no data type." }, + { "match": "oas-*.openapi-object.security", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.openapi-object.tags", "class": "out-of-scope", "reason": "Grouping for documentation. No type depends on it; the SDK's draft config names a resource after an operation's first tag, a suggestion the config then states." }, { "match": "oas-*.openapi-object.externalDocs", "class": "out-of-scope", "reason": "A link to documentation; changes no type." }, - { "match": "oas-*.openapi-object.webhooks", "class": "out-of-scope", "reason": "Webhooks are requests the API makes; out of the first scope." }, + { "match": "oas-*.openapi-object.webhooks", "class": "out-of-scope", "reason": "Requests the API makes to its caller (callbacks, webhooks): the SDK's client only sends the described operations, and its mock only answers them." }, { "match": "oas-*.specification-extensions", "class": "in-scope", "note": "x- fields are read and kept, never an error." }, { "match": "oas-*.data-type-format", "class": "in-scope", "note": "Formats map to types." }, { "match": "oas-*.working-with-binary-data", "class": "in-scope", "note": "Binary data maps to types." }, @@ -59,7 +59,7 @@ { "match": "oas-3.2.base-uri-within-content", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, { "match": "oas-3.1.relative-references-in-api-description-uris", "class": "in-scope", "note": "$ref resolution." }, { "match": "oas-3.0.relative-references-in-urls", "class": "in-scope", "note": "In 3.0 one section covers both $ref and API URLs; $ref resolution needs it." }, - { "match": "oas-3.1.relative-references-in-api-urls", "class": "out-of-scope", "reason": "Server and link URLs at run time; no data type." }, + { "match": "oas-3.1.relative-references-in-api-urls", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-*.openapi-description-structure", "class": "in-scope", "note": "How a description spans documents." }, { "match": "oas-3.1.openapi-description", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, { "match": "oas-3.0.specification", "class": "in-scope", "note": "What a description must contain and how it is structured." }, @@ -72,31 +72,31 @@ { "match": "oas-*.resolving-implicit-connections", "class": "in-scope", "note": "Component and discriminator names resolved across documents." }, { "match": "oas-3.2.guidance-regarding-implicit-connections", "class": "out-of-scope", "reason": "Implicit connections by name (Link Objects' operations, tags, security schemes, discriminator names across documents); none changes a type." }, { "match": "oas-3.2.appendix-g-parsing-and-resolution-guidance", "class": "in-scope", "note": "How documents are read and references resolved." }, - { "match": "oas-*.appendix-c-using-rfc6570-based-serialization", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-3.0.appendix-d-serializing-headers-and-cookies", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.appendix-e-percent-encoding-and-form-media-types", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.non-rfc6570-field-values-and-combinations", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, + { "match": "oas-*.appendix-c-using-rfc6570-based-serialization", "class": "out-of-scope", "reason": "Guidance for a serializer built on an RFC 6570 library: the SDK writes each style by its own code (crates/flowapi-ts/src/sdk/runtime.ts) and expands no URI Template." }, + { "match": "oas-3.0.appendix-d-serializing-headers-and-cookies", "class": "out-of-scope", "reason": "Guidance for a serializer built on an RFC 6570 library: the SDK writes each style by its own code (crates/flowapi-ts/src/sdk/runtime.ts) and expands no URI Template." }, + { "match": "oas-*.appendix-e-percent-encoding-and-form-media-types", "class": "out-of-scope", "reason": "A statement that the encoding rules differ by specification and URI part, which asks nothing itself; what the SDK encodes is held by the sections around it (O8)." }, + { "match": "oas-*.non-rfc6570-field-values-and-combinations", "class": "out-of-scope", "reason": "Guidance for a serializer built on an RFC 6570 library: the SDK writes each style by its own code (crates/flowapi-ts/src/sdk/runtime.ts) and expands no URI Template." }, { "match": "oas-*.percent-encoding-and-illegal-or-reserved-delimiters.must-space-characters-used-delimiters-deepobject-pipedelimited", "class": "in-scope", "note": "The SDK (O8): [ ] | and space encoded." }, { "match": "oas-*.non-rfc6570-field-values-and-combinations.must-parameter-name-includes-characters-outside-allowed", "class": "in-scope", "note": "The SDK (O8): names percent-encoded." }, { "match": "oas-*.non-rfc6570-field-values-and-combinations.should-configurations-no-direct-rfc6570-equivalent-handled", "class": "in-scope", "note": "The SDK (O8): Appendix C's own examples." }, { "match": "oas-*.encoding-object.encoding-the-x-www-form-urlencoded-media-type", "class": "in-scope", "note": "The SDK (O8): a form body by the Encoding Object's defaults." }, - { "match": "oas-*.percent-encoding-and-illegal-or-reserved-delimiters", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.percent-encoding-and-form-data", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.percent-encoding-and-cookies", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.interoperability-with-historical-specifications", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.interoperability-with-web-browser-environments", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.info-object", "class": "out-of-scope", "reason": "Metadata about the API; no data type." }, - { "match": "oas-*.contact-object", "class": "out-of-scope", "reason": "Metadata about the API; no data type." }, - { "match": "oas-*.license-object", "class": "out-of-scope", "reason": "Metadata about the API; no data type." }, - { "match": "oas-*.server-object", "class": "out-of-scope", "reason": "Where the API is served; a run-time base URL, no data type. Revisit at the SDK stage." }, - { "match": "oas-*.server-variable-object", "class": "out-of-scope", "reason": "Where the API is served; a run-time base URL, no data type. Revisit at the SDK stage." }, - { "match": "oas-*.security-scheme-object", "class": "out-of-scope", "reason": "Authentication; no data type. Revisit at the SDK stage." }, - { "match": "oas-*.security-requirement-object", "class": "out-of-scope", "reason": "Authentication; no data type." }, - { "match": "oas-*.oauth-flows-object", "class": "out-of-scope", "reason": "Authentication; no data type." }, - { "match": "oas-*.oauth-flow-object", "class": "out-of-scope", "reason": "Authentication; no data type." }, - { "match": "oas-3.2.security-schemes", "class": "out-of-scope", "reason": "Authentication; no data type." }, + { "match": "oas-*.percent-encoding-and-illegal-or-reserved-delimiters", "class": "out-of-scope", "reason": "Guidance for a serializer built on an RFC 6570 library: the SDK writes each style by its own code (crates/flowapi-ts/src/sdk/runtime.ts) and expands no URI Template." }, + { "match": "oas-*.percent-encoding-and-form-data", "class": "out-of-scope", "reason": "A rule for the caller: data meant percent-encoded in a multipart part is given so, and the SDK applies no percent-encoding to a part, as the section says." }, + { "match": "oas-*.percent-encoding-and-cookies", "class": "out-of-scope", "reason": "Guidance for a serializer built on an RFC 6570 library: the SDK writes each style by its own code (crates/flowapi-ts/src/sdk/runtime.ts) and expands no URI Template." }, + { "match": "oas-*.interoperability-with-historical-specifications", "class": "out-of-scope", "reason": "For an application that needs RFC 1738's rules; the SDK percent-encodes by RFC 3986 (O8)." }, + { "match": "oas-*.interoperability-with-web-browser-environments", "class": "in-scope", "note": "The SDK (O8): form bodies percent-encoded, decoded back by RFC 3986 and WHATWG." }, + { "match": "oas-*.info-object", "class": "out-of-scope", "reason": "Metadata about the API. No type depends on it; the SDK copies the title and version into its package and README as written, which asks nothing of a reader." }, + { "match": "oas-*.contact-object", "class": "out-of-scope", "reason": "Metadata about the API; no type or request depends on it." }, + { "match": "oas-*.license-object", "class": "out-of-scope", "reason": "Metadata about the API; no type or request depends on it." }, + { "match": "oas-*.server-object", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.server-variable-object", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.security-scheme-object", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.security-requirement-object", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.oauth-flows-object", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-*.oauth-flow-object", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "oas-3.2.security-schemes", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-*.security-filtering", "class": "out-of-scope", "reason": "How a server or tool hides parts of a description from a reader; flowapi reads what it is given." }, - { "match": "oas-*.appendix-f-resolving-security-requirements-in-a-referenced-document", "class": "out-of-scope", "reason": "Authentication; no data type." }, + { "match": "oas-*.appendix-f-resolving-security-requirements-in-a-referenced-document", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.0.components-object.securitySchemes", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.components-object.securitySchemes", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.openapi-object.security", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, @@ -131,7 +131,6 @@ { "match": "oas-3.2.server-object.description", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.2.server-object.name", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.server-object.url", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, - { "match": "oas-3.1.server-object.url.must-not-query-fragment-part-url", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.server-object.url.required", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.server-object.variables", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.server-variable-object.default", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, @@ -140,19 +139,12 @@ { "match": "oas-3.1.server-variable-object.description", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.server-variable-object.enum", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, { "match": "oas-3.1.server-variable-object.enum.must-not-array-empty", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, - { "match": "oas-3.0.security-requirement-object.pattern-name.must-other-security-scheme-types-array-empty", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, - { "match": "oas-3.1.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, - { "match": "oas-3.1.server-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, - { "match": "oas-3.1.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, - { "match": "oas-3.2.server-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, - { "match": "oas-3.1.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, - { "match": "oas-3.2.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, - { "match": "oas-3.1.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", "class": "out-of-scope", "reason": "What a client does when it sends a request (substitute a variable, avoid a deprecated scheme); the SDK layer prints what it needs to (the default, `deprecated`), the client is map FA-018's later step." }, - { "match": "oas-3.2.security-scheme-object.deprecated.should-consumers-refrain-usage-declared-scheme", "class": "out-of-scope", "reason": "What a client does when it sends a request (substitute a variable, avoid a deprecated scheme); the SDK layer prints what it needs to (the default, `deprecated`), the client is map FA-018's later step." }, - { "match": "oas-*.link-object", "class": "out-of-scope", "reason": "Links between operations at run time; no data type." }, - { "match": "oas-*.callback-object", "class": "out-of-scope", "reason": "Callbacks are requests the API makes; out of the first scope." }, + { "match": "oas-3.1.server-variable-object.default.shall-default-value-use-substitution-sent-alternate", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "oas-3.2.security-scheme-object.deprecated.should-consumers-refrain-usage-declared-scheme", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "oas-*.link-object", "class": "out-of-scope", "reason": "Links between operations: the SDK's client does not follow links, and no type depends on them." }, + { "match": "oas-*.callback-object", "class": "out-of-scope", "reason": "Requests the API makes to its caller (callbacks, webhooks): the SDK's client only sends the described operations, and its mock only answers them." }, { "match": "oas-*.example-object", "class": "out-of-scope", "reason": "Example values; change no type." }, - { "match": "oas-*.tag-object", "class": "out-of-scope", "reason": "Grouping for documentation; no data type." }, + { "match": "oas-*.tag-object", "class": "out-of-scope", "reason": "Grouping for documentation. No type depends on it; the SDK's draft config names a resource after an operation's first tag, a suggestion the config then states." }, { "match": "oas-*.external-documentation-object", "class": "out-of-scope", "reason": "A link to documentation; changes no type." }, { "match": "oas-*.xml-object", "class": "out-of-scope", "reason": "XML serialization; flowapi generates JSON types." }, { "match": "oas-*.rich-text-formatting", "class": "out-of-scope", "reason": "Rendering CommonMark is a documentation tool's job; descriptions pass into comments as written." }, @@ -393,15 +385,15 @@ { "match": "oas-*.structural-interoperability.may-same-json-yaml-object-parsed-multiple", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, { "match": "oas-*.undefined-and-implementation-defined-behavior.may-implementations-support-undefined-scenarios-historical-reasons", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, { "match": "oas-*.working-with-binary-data.may-maxlength-keyword-used-set-expected-upper", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take; it asks nothing of a types generator." }, - { "match": "oas-*.conditions-for-using-the-discriminator-object.recommended-however-search-all-named-schemas-components", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.defaultMapping", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.examples.may-discriminator-used-hint-improve-efficiency-selection", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.examples.may-scenarios-value-discriminator-field-does-not", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.mapping", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-both-valid-schema", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-defaultmapping-value-both", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, - { "match": "oas-*.discriminator-object.propertyName", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value at run time; flowapi's type is the union of the schemas either way (the discriminator is an annotation)." }, + { "match": "oas-*.conditions-for-using-the-discriminator-object.recommended-however-search-all-named-schemas-components", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.defaultMapping", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.examples.may-discriminator-used-hint-improve-efficiency-selection", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.examples.may-scenarios-value-discriminator-field-does-not", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.examples.should-discriminating-value-does-not-match-implicit", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.mapping", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-both-valid-schema", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.options-for-mapping-values-to-schemas.recommended-behavior-mapping-value-defaultmapping-value-both", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, + { "match": "oas-*.discriminator-object.propertyName", "class": "out-of-scope", "reason": "How a schema is selected by the discriminating value: flowapi's type is the union of the schemas either way (the discriminator is an annotation), and the SDK's client returns a body as parsed, choosing no schema." }, { "match": "jsonschema-2020-12.core.$comment.must-not-particular-value-comment-collected-annotation-result", "class": "out-of-scope", "reason": "Annotation collection and output, what a validator reports; flowapi collects no annotations and produces no validation output." }, { "match": "jsonschema-2020-12.core.annotations", "class": "out-of-scope", "reason": "Annotation collection and output, what a validator reports; flowapi collects no annotations and produces no validation output." }, { "match": "jsonschema-2020-12.core.anyOf.must-note-annotations-being-collected-all-subschemas", "class": "out-of-scope", "reason": "Annotation collection and output, what a validator reports; flowapi collects no annotations and produces no validation output." }, @@ -471,49 +463,49 @@ { "match": "jsonschema-2020-12.core.vocabulary.must-describing-valid-schema-syntax-schema-successfully", "class": "out-of-scope", "reason": "Validating schema documents against their meta-schemas; flowapi does not validate schemas." }, { "match": "oas-*.objects-and-fields.must-json-schema-differs-section-section-considered", "class": "out-of-scope", "reason": "Validating schema documents against their meta-schemas; flowapi does not validate schemas." }, { "match": "oas-*.specification.schema.must-json-schema-differs-section-section-considered", "class": "out-of-scope", "reason": "Validating schema documents against their meta-schemas; flowapi does not validate schemas." }, - { "match": "jsonschema-2020-12.core.$schema.should-uri-identifies-retrievable-resource-resource-media", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.core.schema-document.should-schema-itself-interpreted-instance-but-always", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.core.security.must-servers-ensure-malicious-parties-cannot-change", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.content.implementation-requirements.may-implementations-offer-ability-decode-parse-validate", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.content.implementation-requirements.should-process-equivalent-fully-evaluating-instance-against", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.contentEncoding.should-base64-defined-both-rfcs-definition-rfc", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.contentEncoding.should-instance-value-string-property-defines-string", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.deprecated.should-deprecated-value-boolean-true-indicates-applications", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.readonly-and-writeonly.may-instance-document-marked-readonly-entire-document", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.readonly-and-writeonly.may-instance-document-marked-writeonly-entire-document", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "jsonschema-2020-12.validation.readonly-and-writeonly.may-particular-application-choose-use-widget-hides", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "oas-*.openapi-object.establishing-the-base-uri.may-implementations-support-document-retrieval-although-see", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "oas-*.relative-references-in-urls.recommended-compatibility-future-versions-specification-ref-process", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "oas-*.schema-object.deprecated.should-specifies-schema-deprecated-transitioned-out-usage", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, - { "match": "oas-*.schema-object.validating-readonly-and-writeonly", "class": "out-of-scope", "reason": "Servers, publishing and retrieving schemas, and what an application does with data at run time (decoding, refusing, hiding); flowapi generates types and runs nothing." }, + { "match": "jsonschema-2020-12.core.$schema.should-uri-identifies-retrievable-resource-resource-media", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.core.schema-document.should-schema-itself-interpreted-instance-but-always", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.core.security.must-servers-ensure-malicious-parties-cannot-change", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.content.implementation-requirements.may-implementations-offer-ability-decode-parse-validate", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.content.implementation-requirements.should-process-equivalent-fully-evaluating-instance-against", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.contentEncoding.should-base64-defined-both-rfcs-definition-rfc", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.contentEncoding.should-instance-value-string-property-defines-string", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.deprecated.should-deprecated-value-boolean-true-indicates-applications", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.readonly-and-writeonly.may-instance-document-marked-readonly-entire-document", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.readonly-and-writeonly.may-instance-document-marked-writeonly-entire-document", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "jsonschema-2020-12.validation.readonly-and-writeonly.may-particular-application-choose-use-widget-hides", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "oas-*.openapi-object.establishing-the-base-uri.may-implementations-support-document-retrieval-although-see", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "oas-*.relative-references-in-urls.recommended-compatibility-future-versions-specification-ref-process", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "oas-*.schema-object.deprecated.should-specifies-schema-deprecated-transitioned-out-usage", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, + { "match": "oas-*.schema-object.validating-readonly-and-writeonly", "class": "out-of-scope", "reason": "Publishing and retrieving schemas, and what an application does with an instance (decoding content, refusing deprecated or read-only values, hiding fields): flowapi reads the documents it is given, and the SDK's client sends values as given and returns a body as parsed, checking neither." }, { "match": "jsonschema-2020-12.core.$comment.should-tools-editing-schemas-support-displaying-editing", "class": "out-of-scope", "reason": "A rule for tools that edit or display schemas; flowapi does neither." }, - { "match": "oas-*.appendix-d-serializing-headers-and-cookies", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.explode", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.must-not-serializing-headers-schema-uri-percent-encoding", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-headers-parameters-name-value", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.modeling-link-headers", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.representing-the-set-cookie-header", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.style", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.additional-encoding-approaches", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.encoding", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.encoding-by-name", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.encoding-by-position", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.encoding-usage-and-restrictions", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.itemEncoding", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.media-type-object.prefixEncoding", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.parameter-object.allowEmptyValue", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, + { "match": "oas-*.appendix-d-serializing-headers-and-cookies", "class": "out-of-scope", "reason": "Guidance for a serializer built on an RFC 6570 library: the SDK writes each style by its own code (crates/flowapi-ts/src/sdk/runtime.ts) and expands no URI Template." }, + { "match": "oas-*.header-object.explode", "class": "out-of-scope", "reason": "Header Objects serialized or parsed by schema: the client parses no response header by its schema (it gives the headers as strings), and a multipart part's headers are written as the caller's strings." }, + { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.must-not-serializing-headers-schema-uri-percent-encoding", "class": "out-of-scope", "reason": "Header Objects serialized or parsed by schema: the client parses no response header by its schema (it gives the headers as strings), and a multipart part's headers are written as the caller's strings." }, + { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-headers-parameters-name-value", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.header-object.modeling-link-headers", "class": "out-of-scope", "reason": "Header Objects serialized or parsed by schema: the client parses no response header by its schema (it gives the headers as strings), and a multipart part's headers are written as the caller's strings." }, + { "match": "oas-*.header-object.representing-the-set-cookie-header", "class": "out-of-scope", "reason": "Header Objects serialized or parsed by schema: the client parses no response header by its schema (it gives the headers as strings), and a multipart part's headers are written as the caller's strings." }, + { "match": "oas-*.header-object.style", "class": "out-of-scope", "reason": "Header Objects serialized or parsed by schema: the client parses no response header by its schema (it gives the headers as strings), and a multipart part's headers are written as the caller's strings." }, + { "match": "oas-*.media-type-object.additional-encoding-approaches", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "oas-*.media-type-object.encoding", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.media-type-object.encoding-by-name", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.media-type-object.encoding-by-position", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.media-type-object.encoding-usage-and-restrictions", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.media-type-object.itemEncoding", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.media-type-object.prefixEncoding", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.parameter-object.allowEmptyValue", "class": "out-of-scope", "reason": "A deprecated permission to send a parameter with an empty value; the client takes none of it: a parameter the caller leaves out is not sent." }, { "match": "oas-*.parameter-object.allowReserved", "class": "in-scope", "note": "The SDK (O8): reserved expansion." }, { "match": "oas-*.parameter-object.explode", "class": "in-scope", "note": "The SDK (O8): defaults and effect." }, - { "match": "oas-*.parameter-object.fixed-fields-for-use-with-content", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, + { "match": "oas-*.parameter-object.fixed-fields-for-use-with-content", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-cases-implementations-pass-values-through-unchanged", "class": "in-scope", "note": "The SDK (O8): headers and style cookie as given." }, { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged", "class": "in-scope", "note": "The SDK (O8): headers as given." }, - { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-not-parsing-parameters-any-apparent-percent-encoding", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, + { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-not-parsing-parameters-any-apparent-percent-encoding", "class": "out-of-scope", "reason": "Parsing parameters: the client writes parameters and parses none." }, { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-not-serializing-header-parameters-schema-uri-percent", "class": "in-scope", "note": "The SDK (O8): no percent-encoding in headers." }, { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-not-serializing-values-uri-percent-encoding-applied", "class": "in-scope", "note": "The SDK (O8): no percent-encoding in headers and style cookie." }, { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.must-using-rfc6570-implementation-automatically-performs-encoding", "class": "in-scope", "note": "The SDK (O8): no encoding applied, none to undo." }, - { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-header-parameters", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-see-appendix", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, + { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-header-parameters", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.not-recommended-serializing-schema-cookie-parameters-see-appendix", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, { "match": "oas-*.parameter-object.serialization-and-examples", "class": "in-scope", "note": "The SDK (O8): names, leading delimiters, header values." }, { "match": "oas-*.parameter-object.style", "class": "in-scope", "note": "The SDK (O8, conformance/sdk): defaults per location." }, { "match": "oas-*.parameter-object.style-examples", "class": "in-scope", "note": "The SDK (O8): the Style Examples table itself, and no ? before a form body." }, @@ -521,28 +513,258 @@ { "match": "oas-*.parameter-object.url-percent-encoding", "class": "in-scope", "note": "The SDK (O8): percent-encoding, decoded back by RFC 3986 and WHATWG." }, { "match": "oas-*.path-templating.must-not-value-path-parameters-contain-any-unescaped", "class": "in-scope", "note": "The SDK (O8): / ? # in path values encoded." }, { "match": "oas-*.paths-object.path-templating.must-not-value-path-parameters-contain-any-unescaped", "class": "in-scope", "note": "The SDK (O8): / ? # in path values encoded." }, - { "match": "oas-*.schema-object.non-json-data.must-due-limited-requirements-searching-schemas-serializers", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.schema-object.non-json-data.must-inspecting-schemas-given-starting-point-schema", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.schema-object.non-json-data.must-not-implementations-inspect-subschemas-possible-reference-targets", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.schema-object.parsing-and-serializing", "class": "out-of-scope", "reason": "Serialization no type depends on and the SDK (map FA-012, O8 in conformance/sdk) does not do or test yet: per-property Encoding Objects and multipart parts, response headers, allowEmptyValue, and guidance that binds a description's author or an RFC 6570 library rather than a generator." }, - { "match": "oas-*.header-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.operation-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.operation-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.parameter-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.path-item-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.path-item-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.reference-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.reference-object.description.should-description-default-override-referenced-component", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.reference-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.request-body-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.response-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, - { "match": "oas-*.response-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description); changes no type. flowapi prints a schema's title and description only." }, + { "match": "oas-*.schema-object.non-json-data.must-due-limited-requirements-searching-schemas-serializers", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.schema-object.non-json-data.must-inspecting-schemas-given-starting-point-schema", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.schema-object.non-json-data.must-not-implementations-inspect-subschemas-possible-reference-targets", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "oas-*.schema-object.parsing-and-serializing", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "oas-*.header-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.operation-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.operation-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.parameter-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.path-item-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.path-item-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.reference-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.reference-object.description.should-description-default-override-referenced-component", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.reference-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.request-body-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.response-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-*.response-object.summary", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.must-example-examples-provided-conjunction-schema-field", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.header-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.media-type-object.shall-example-examples-fields-mutually-exclusive-either", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.media-type-object.should-example-examples-provided-example-match-specified", "class": "out-of-scope", "reason": "Example values; change no type." }, { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.shall-example-examples-fields-mutually-exclusive-either", "class": "out-of-scope", "reason": "Example values; change no type." }, - { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", "class": "out-of-scope", "reason": "Example values; change no type." } + { "match": "oas-*.parameter-object.fixed-fields-for-use-with-schema.should-example-examples-provided-conjunction-schema-field", "class": "out-of-scope", "reason": "Example values; change no type." }, + { "match": "oas-*.oauth-flows-object.implicit", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-*.oauth-flows-object.password", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-*.oauth-flows-object.authorizationCode", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-*.oauth-flows-object.deviceAuthorization", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-*.oauth-flow-object.authorizationUrl", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-*.oauth-flow-object.deviceAuthorizationUrl", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-*.oauth-flow-object.refreshUrl", "class": "out-of-scope", "reason": "Refreshing is for the tokens of the flows the caller runs, who refreshes them; a client credentials grant gives no refresh token (RFC 6749, Section 4.4.3)." }, + { "match": "oas-*.security-scheme-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "oas-*.server-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "oas-*.server-variable-object.description.may-commonmark-syntax-used-rich-text-representation", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "oas-*.security-scheme-object.scheme.should-values-used-registered-iana-authentication-scheme", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.security-requirement-object.pattern-name.must-other-security-scheme-types-array-empty", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.security-requirement-object.must-name-used-each-property-correspond-security", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-3.2.security-requirement-object.must-name-used-each-property-either-correspond", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-3.2.security-requirement-object.must-property-names-identical-component-name-under", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-3.2.security-requirement-object.not-recommended-using-security-scheme-component-name-appears", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-3.2.server-variable-object.must-not-each-server-variable-appear-more-once", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.server-object.url.must-not-query-fragment-part-url", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-3.2.security-scheme-object.oauth2MetadataUrl", "class": "out-of-scope", "reason": "Authorization server metadata (RFC 8414): the client reads none; it requests a token at the flow's tokenUrl. RFC 8414 is not pinned (specs/SOURCE.md)." }, + { "match": "oas-2.0.security-scheme-object.authorizationUrl", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "oas-2.0.security-scheme-object.tokenUrl.should-form-url", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.security-scheme-object.x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.security-scheme-object.tokenUrl", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "oas-2.0.security-scheme-object.scopes", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "oas-2.0.scopes-object", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "oas-2.0.scopes-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.security-definitions-object", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-2.0.swagger-object", "class": "in-scope", "note": "Swagger 2.0 read into the 3.x model (crates/flowapi/src/spec/swagger.rs): types, each named by a swagger20-* case of crates/flowapi-ts/tests/cases." }, + { "match": "oas-2.0.swagger-object.swagger.must-value-2-0", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.swagger-object.info", "class": "out-of-scope", "reason": "Metadata about the API. No type depends on it; the SDK copies the title and version into its package and README as written, which asks nothing of a reader." }, + { "match": "oas-2.0.swagger-object.externalDocs", "class": "out-of-scope", "reason": "A link to documentation; changes no type." }, + { "match": "oas-2.0.swagger-object.tags", "class": "out-of-scope", "reason": "Grouping for documentation. No type depends on it; the SDK's draft config names a resource after an operation's first tag, a suggestion the config then states." }, + { "match": "oas-2.0.swagger-object.host", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-2.0.swagger-object.basePath", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-2.0.swagger-object.schemes", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-2.0.swagger-object.security", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-2.0.swagger-object.securityDefinitions", "class": "in-scope", "note": "The SDK layer (crates/flowapi-sdk, map FA-018): servers and security read for a client, each named by a kept case of crates/flowapi-sdk/tests/cases." }, + { "match": "oas-2.0.swagger-object.host.must-host-only-does-not-include-scheme", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.definitions-object", "class": "in-scope", "note": "Swagger 2.0 read into the 3.x model (crates/flowapi/src/spec/swagger.rs): types, each named by a swagger20-* case of crates/flowapi-ts/tests/cases." }, + { "match": "oas-2.0.parameters-definitions-object", "class": "in-scope", "note": "Swagger 2.0 read into the 3.x model (crates/flowapi/src/spec/swagger.rs): types, each named by a swagger20-* case of crates/flowapi-ts/tests/cases." }, + { "match": "oas-2.0.responses-definitions-object", "class": "in-scope", "note": "Swagger 2.0 read into the 3.x model (crates/flowapi/src/spec/swagger.rs): types, each named by a swagger20-* case of crates/flowapi-ts/tests/cases." }, + { "match": "oas-2.0.headers-object", "class": "in-scope", "note": "Swagger 2.0 read into the 3.x model (crates/flowapi/src/spec/swagger.rs): types, each named by a swagger20-* case of crates/flowapi-ts/tests/cases." }, + { "match": "oas-2.0.items-object", "class": "in-scope", "note": "Swagger 2.0 read into the 3.x model (crates/flowapi/src/spec/swagger.rs): types, each named by a swagger20-* case of crates/flowapi-ts/tests/cases." }, + { "match": "oas-2.0.swagger-object.consumes.must-value-described-under-mime-types", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.swagger-object.produces.must-value-described-under-mime-types", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.operation-object.consumes.must-value-described-under-mime-types", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.operation-object.produces.must-value-described-under-mime-types", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.parameter-object.name.must-path-name-field-correspond-associated-path", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.parameter-object.required.must-parameter-path-property-required-value-true", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.parameter-object.type.must-type-file-consumes-either-multipart-form", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.parameter-object.type.must-value-one-string-number-integer-boolean", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.parameter-object.default.must-unlike-json-schema-value-conform-defined", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.items-object.type.must-value-one-string-number-integer-boolean", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.items-object.default.must-unlike-json-schema-value-conform-defined", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.header-object.type.must-value-one-string-number-integer-boolean", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.header-object.collectionFormat", "class": "out-of-scope", "reason": "A 2.0 Header Object describes a response header only: the client parses no response header by its schema (it gives the headers as strings), as for 3.x's Header Object style and explode." }, + { "match": "oas-2.0.schema-object.discriminator.must-used-value-name-schema-any-schema", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.header-object.default.must-unlike-json-schema-value-conform-defined", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.path-item-object.$ref.must-referenced-structure-format-path-item-object", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.paths-object.pattern-path.must-field-name-begin-slash", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.response-object.schema.should-accompanied-relevant-produces-mime-type", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.schema-object.discriminator.must-property-name-used-defined-schema-required", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.schema-object.must-default-unlike-json-schema-value-conform", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.schema-object.readOnly.should-not-properties-marked-readonly-being-true-required", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.swagger-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.items-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.header-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.operation-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.parameter-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.path-item-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.paths-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.response-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.responses-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.schema-object.pattern-x.must-field-name-begin-x-example-x", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-2.0.header-object.description", "class": "out-of-scope", "reason": "Documentation of a path, operation, parameter, body or response (summary, description): no type or request depends on it; flowapi prints a schema's title and description, and the SDK an operation's summary, as written." }, + { "match": "oas-2.0.response-object.examples", "class": "out-of-scope", "reason": "Example values; change no type." }, + { "match": "oas-2.0.parameter-object.allowEmptyValue", "class": "out-of-scope", "reason": "A permission to send a parameter with an empty value; the client takes none of it: a parameter the caller leaves out is not sent." }, + { "match": "oas-*.encoding-object.common-fixed-fields.may-fields-used-either-without-rfc6570-style", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.encoding-object.encoding-multipart-media-types.required-contrast-openapi-2-0-schema-define", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.encoding-object.encoding-multipart-media-types.not-recommended-because-because-encoding-object-s-contenttype", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.encoding-object.content-transfer-encoding-and-contentencoding.not-recommended-because-because-encoding-object-s-contenttype", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.media-type-object.encoding.must-key-being-property-name-exist-schema", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.media-type-object.encoding.must-not-field-present-prefixencoding-itemencoding-present", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.media-type-object.itemEncoding.must-not-field-present-encoding-present", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.media-type-object.prefixEncoding.must-not-field-present-encoding-present", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.media-type-object.encoding-by-name.must-use-encoding-field-each-key-under", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.media-type-object.encoding-by-position.must-use-prefixencoding-itemencoding-fields-each-item", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.percent-encoding-and-illegal-or-reserved-delimiters.recommended-maximum-interoperability-either-define-document-additional", "class": "out-of-scope", "reason": "A rule for the author of a description or schema: what a valid document is (its meta-schema checks it). flowapi reads documents as written and does not validate them." }, + { "match": "oas-*.encoding-object.encoding-multipart-media-types.may-not-currently-possible-correlate-schema-properties", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "oas-*.media-type-object.encoding-by-name.must-deserialization-object-multiple-values-same-name", "class": "out-of-scope", "reason": "Reading a form or multipart body: the client writes them and reads none, and the mock does not parse them by the description." }, + { "match": "oas-3.2.percent-encoding-and-cookies.must-not-while-percent-encoding-seems-more-common", "class": "out-of-scope", "reason": "Storing cookies from Set-Cookie: the SDK's client stores no cookie." }, + { "match": "rfc6749", "class": "out-of-scope", "reason": "A rule for the authorization server or the resource server (the API): the SDK is a client, and its mock answers the described operations only." }, + { "match": "rfc6749.1.6", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.2", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.2.1", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.2.2", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.8", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.8.1", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.8.2", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.8.3", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.8.4", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.8.5", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.11", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.11.1", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.11.4", "class": "out-of-scope", "reason": "Client registration, extension grants and parameters, and IANA registries: nothing a client sends." }, + { "match": "rfc6749.3.1", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.1", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.2", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.2.1", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.2.2", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.2.3", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.2.4", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.3.1.2.5", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.4.1", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.4.2", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.4.3", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.6", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.9", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.5", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.6", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.7", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.11", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.12", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.13", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.14", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.16", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.4", "class": "out-of-scope", "reason": "A grant that needs the resource owner or a user agent (authorization code, implicit, password), a refresh token, or a native app: the caller runs it and gives the client the access token as the scheme's option, which the client sends as a bearer token." }, + { "match": "rfc6749.10.9", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." }, + { "match": "rfc6749.4.4.must-client-credentials-grant-type-only-used", "class": "out-of-scope", "reason": "How a deployment chooses its clients and tokens (who is confidential, token scope and lifetime): the caller's choice, not the client's." }, + { "match": "rfc6749.10.1.must-web-application-clients-ensure-confidentiality-client", "class": "out-of-scope", "reason": "How a deployment chooses its clients and tokens (who is confidential, token scope and lifetime): the caller's choice, not the client's." }, + { "match": "rfc6749.2.3.must-not-client-use-more-one-authentication-method", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.2.3.1.may-clients-possession-client-password-use-http", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.2.3.1.not-recommended-including-client-credentials-request-body-using", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.2.3.1.must-not-parameters-only-transmitted-request-body-included", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.3.2.must-client-use-http-post-method-making", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.3.2.must-endpoint-uri-include-application-x-www", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.3.2.must-not-request-response-parameters-included-more-once", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.3.2.1.must-confidential-clients-other-clients-issued-client", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.3.3.must-client-omits-scope-parameter-requesting-authorization", "class": "out-of-scope", "reason": "A rule for the authorization server or the resource server (the API): the SDK is a client, and its mock answers the described operations only." }, + { "match": "rfc6749.4.4.2.must-client-authenticate-authorization-server-described-section", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.4.4.2.must-value-set-client-credentials", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.4.4.2.optional-scope", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.4.4.2.required-grant-type", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.5.1.must-client-ignore-unrecognized-value-names-response", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.10.3.should-client-request-access-tokens-minimal-scope", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.B.must-address-shortcoming-generating-payloads-using-media", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6749.7.1.must-not-client-use-access-token-does-not", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6749.10.3.must-access-token-credentials-only-transmitted-using", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6749.10.3.must-access-token-credentials-well-any-confidential", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6749.10.8.must-not-access-tokens-refresh-tokens-resource-owner", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750", "class": "out-of-scope", "reason": "A rule for the authorization server or the resource server (the API): the SDK is a client, and its mock answers the described operations only." }, + { "match": "rfc6750.2.must-not-clients-use-more-one-method-transmit", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.2.1.should-clients-make-authenticated-requests-bearer-token", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.2.2.must-not-client-use-method-unless-all-following", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.2.3.should-not-because-security-weaknesses-associated-uri-method", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.2.must-not-therefore-bearer-tokens-stored-cookies-sent", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.2.must-second-confidentiality-protection-exchanges-between-client", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.3.must-always-use-tls-https-clients-always", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.3.must-safeguard-bearer-tokens-client-implementations-ensure", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.3.must-not-don-t-store-bearer-tokens-cookies", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.3.should-instead-bearer-tokens-passed-http-message", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.5.3.should-not-don-t-pass-bearer-tokens-page", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): how an access token is sent (an Authorization header, never a body or a query), held by tests/client/auth.mjs and wire.mjs." }, + { "match": "rfc6750.3.1.may-client-request-new-access-token-retry", "class": "in-scope", "note": "The SDK's client runtime (auth.ts, map FA-018): a client credentials token requested from the flow's tokenUrl. The client sends the token the caller gives today and requests none, so these wait for it." }, + { "match": "rfc6750.5.2.must-further-defense-against-token-disclosure-client", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." }, + { "match": "rfc6750.5.2.must-note-client-validate-tls-certificate-chain", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." }, + { "match": "rfc6750.5.2.must-furthermore-presenting-token-resource-server-client", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." }, + { "match": "rfc6750.5.3.must-validate-tls-certificate-chains-client-validate", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." }, + { "match": "rfc6750.5.2.must-protect-against-token-disclosure-confidentiality-protection", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." }, + { "match": "rfc6750.5.3.must-implementations-do-store-bearer-tokens-cookies", "class": "out-of-scope", "reason": "A rule for an implementation that keeps bearer tokens in cookies: the client keeps none there." }, + { "match": "rfc6750.2.2.must-content-encoded-entity-body-consist-entirely", "class": "out-of-scope", "reason": "How a token is sent in a form body or a query, which the client never does: it sends a bearer token in the Authorization header." }, + { "match": "rfc6750.2.2.must-entity-body-include-other-request-specific", "class": "out-of-scope", "reason": "How a token is sent in a form body or a query, which the client never does: it sends a bearer token in the Authorization header." }, + { "match": "rfc6750.2.2.must-not-particular-means-get-method-used", "class": "out-of-scope", "reason": "How a token is sent in a form body or a query, which the client never does: it sends a bearer token in the Authorization header." }, + { "match": "rfc6750.2.2.should-not-application-x-www-form-urlencoded-method", "class": "out-of-scope", "reason": "How a token is sent in a form body or a query, which the client never does: it sends a bearer token in the Authorization header." }, + { "match": "rfc6750.2.3.must-http-request-uri-query-include-other", "class": "out-of-scope", "reason": "How a token is sent in a form body or a query, which the client never does: it sends a bearer token in the Authorization header." }, + { "match": "rfc6750.2.3.should-clients-using-uri-query-parameter-method", "class": "out-of-scope", "reason": "How a token is sent in a form body or a query, which the client never does: it sends a bearer token in the Authorization header." }, + { "match": "rfc7617", "class": "out-of-scope", "reason": "A rule for the recipient of Basic credentials, the challenge's parameters or a proxy: the client sends credentials up front by the operation's security and reads no challenge." }, + { "match": "rfc7617.2.must-not-user-id-password-contain-any-control", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): HTTP Basic credentials sent, held by tests/client/auth.mjs." }, + { "match": "rfc7617.2.2.may-client-preemptively-send-corresponding-authorization-header", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): HTTP Basic credentials sent, held by tests/client/auth.mjs." }, + { "match": "rfc7617.4.should-not-because-basic-authentication-involves-cleartext-transmission", "class": "in-scope", "note": "The SDK's client runtime (auth.ts): HTTP Basic credentials sent, held by tests/client/auth.mjs." }, + { "match": "rfc7617.2.2.should-client-assume-resources-identified-uris-prefix", "class": "out-of-scope", "reason": "Protection spaces: the client sends credentials by the operation's security, not by what a challenge's realm covers." }, + { "match": "rfc7578", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "rfc7578.4.2.may-most-multipart-types-mime-header-fields", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "rfc7578.4.5.may-case-form-data-text-charset-parameter", "class": "out-of-scope", "reason": "A permission (MAY or OPTIONAL) that flowapi does not take: neither the types nor the SDK's client use it." }, + { "match": "rfc7578.4.3.should-receiving-applications-intended-wide-applicability-e", "class": "out-of-scope", "reason": "Reading a form or multipart body: the client writes them and reads none, and the mock does not parse them by the description." }, + { "match": "rfc7578.5.1.1", "class": "out-of-scope", "reason": "A rule for whoever makes a form (its field names): the names come from the description." }, + { "match": "rfc7578.5.2.must-not-intermediaries-reorder-results", "class": "out-of-scope", "reason": "A rule for intermediaries; the client sends the parts itself." }, + { "match": "rfc9110", "class": "out-of-scope", "reason": "HTTP as the platform's fetch implements it (conformance, URIs, fields, message framing, routing, content codings), or a rule for servers, intermediaries and caches: the client hands each request to fetch and reads the response through it. The rules its own code answers are in scope by id." }, + { "match": "rfc9110.9", "class": "out-of-scope", "reason": "Method semantics for the origin server, and methods a client may send that the client sends only as described: it sends each operation's method as it is." }, + { "match": "rfc9110.9.3.6", "class": "out-of-scope", "reason": "CONNECT: the platform's fetch refuses to send it (a forbidden method), so the client never does." }, + { "match": "rfc9110.9.3.8", "class": "out-of-scope", "reason": "TRACE: the platform's fetch refuses to send it (a forbidden method), so the client never does." }, + { "match": "rfc9110.10.1", "class": "out-of-scope", "reason": "Request context fields the client sends none of by itself (Expect, From, Referer, TE; User-Agent is the platform's fetch's own): a caller's header is sent as given." }, + { "match": "rfc9110.10.2", "class": "out-of-scope", "reason": "Response context fields as servers and proxies generate them (Allow, Server)." }, + { "match": "rfc9110.11", "class": "out-of-scope", "reason": "HTTP authentication's challenges and protection spaces: the client sends credentials up front by the operation's security and reads no challenge (WWW-Authenticate, Proxy-Authenticate)." }, + { "match": "rfc9110.12", "class": "out-of-scope", "reason": "Content negotiation: the client sends no Accept-* field of its own (fetch's default Accept stands); a caller's header is sent as given." }, + { "match": "rfc9110.13", "class": "out-of-scope", "reason": "Conditional requests: the client sends no precondition of its own (If-*); a caller's header is sent as given." }, + { "match": "rfc9110.14", "class": "out-of-scope", "reason": "Range requests: the client sends no Range of its own and reads each response whole." }, + { "match": "rfc9110.15", "class": "out-of-scope", "reason": "What a status code means for the server that sends it, or for a client that acts on it as the client does not: the client returns a 2xx response as described and raises any other status as an error, retrying the statuses retry.ts names and following 301, 302, 303, 307 and 308 (send.ts)." }, + { "match": "rfc9110.15.2", "class": "out-of-scope", "reason": "1xx responses: the platform's fetch reads them and gives the final response." }, + { "match": "rfc9110.15.3.7", "class": "out-of-scope", "reason": "Range requests: the client sends no Range of its own and reads each response whole." }, + { "match": "rfc9110.15.4.1", "class": "out-of-scope", "reason": "300 Multiple Choices: the client chooses nothing from the list and the server's choices are its own; a Location it follows as any redirect's (rfc9110.15.4.1.may-user-agent-use-location-field-value, in scope)." }, + { "match": "rfc9110.15.4.1.may-user-agent-use-location-field-value", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.5", "class": "out-of-scope", "reason": "304 Not Modified answers a conditional request; the client sends none of its own." }, + { "match": "rfc9110.16", "class": "out-of-scope", "reason": "Extending HTTP (new methods, codes, fields, registries): nothing a client sends." }, + { "match": "rfc9110.4.2.4.must-not-sender-generate-userinfo-subcomponent-delimiter-http", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.8.3.should-sender-generates-message-containing-content-generate", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.9.2.2.should-not-client-automatically-retry-request-non-idempotent", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.9.2.2.should-not-client-automatically-retry-failed-automatic-retry", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.9.3.1.should-not-client-generate-content-get-request-unless", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.9.3.2.should-not-client-generate-content-head-request-unless", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.9.3.5.should-not-client-generate-content-delete-request-unless", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.9.3.7.must-client-generates-options-request-containing-content", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.must-however-client-understand-class-any-status", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.should-client-receives-response-invalid-status-code", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.should-automatically-following-redirected-request-user-agent", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.should-client-detect-intervene-cyclical-redirections-i", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.may-location-header-field-section-10-2", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.2.may-note-historical-reasons-user-agent-change", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.3.may-note-historical-reasons-user-agent-change", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.2.may-user-agent-use-location-field-value", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.3.may-user-agent-use-location-field-value", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.8.may-user-agent-use-location-field-value", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.9.may-user-agent-use-location-field-value", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.4.8.must-not-307-temporary-redirect-status-code-indicates", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.5.4.should-not-client-automatically-repeat-request-same-credentials", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.15.5.9.may-client-outstanding-request-transit-repeat-request", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.8.3.3.must-message-body-itself-protocol-element-sender", "class": "in-scope", "note": "The SDK's multipart/form-data writer (crates/flowapi-ts/src/sdk/multipart.ts; the encoding put in the table by crates/flowapi-sdk/src/encoding.rs), run by O8 (conformance/sdk/cases.json)." }, + { "match": "rfc9110.15.5.should-user-agents-display-any-included-representation", "class": "out-of-scope", "reason": "Showing a response to a user: the client has no user interface; it gives the response's body to the caller in the error it raises." }, + { "match": "rfc9110.15.6.should-user-agent-display-any-included-representation", "class": "out-of-scope", "reason": "Showing a response to a user: the client has no user interface; it gives the response's body to the caller in the error it raises." }, + { "match": "rfc9110.10.2.2.must-location-value-provided-3xx-redirection-response", "class": "in-scope", "note": "The SDK's client runtime (crates/flowapi-sdk/src/client/core, map FA-018): what it sends and how, held by the tests of crates/flowapi-sdk/tests/client/*.mjs." }, + { "match": "rfc9110.4.3.4", "class": "out-of-scope", "reason": "TLS itself (certificate validation, versions, cipher suites): the platform's fetch does it; the client sets no TLS option." } ] } diff --git a/conformance/sdk-rust/Cargo.lock b/conformance/sdk-rust/Cargo.lock index 1510076..9a1f339 100644 --- a/conformance/sdk-rust/Cargo.lock +++ b/conformance/sdk-rust/Cargo.lock @@ -10,11 +10,11 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-rust" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] diff --git a/conformance/sdk-rust/order.json b/conformance/sdk-rust/order.json index e061214..e5d88e4 100644 --- a/conformance/sdk-rust/order.json +++ b/conformance/sdk-rust/order.json @@ -9,7 +9,27 @@ { "case": "in: querystring as a form", "call": 0, - "expect": { "query": "n=1&n=2&text=a%20b%26c", "pairs": [["n", "1"], ["n", "2"], ["text", "a b&c"]] } + "expect": { "query": "n=1&n=2&text=a+b%26c", "pairs": [["n", "1"], ["n", "2"], ["text", "a b&c"]] } + }, + { + "case": "a form body by WHATWG's rules: 3.2's own examples (JSON values, a JSON id, base64url with padding)", + "call": 0, + "expect": { "body": "id=f81d4fae-7dec-11d0-a765-00a0c91e6bf6&address=%7B%22city%22%3A%22Somewhere%22%2C%22state%22%3A%22CA%22%2C%22streetAddress%22%3A%22123+Example+Dr.%22%2C%22zip%22%3A%2299999%2B1234%22%7D" } + }, + { + "case": "a form body's members by their Encoding Objects' style, explode and allowReserved, as query parameters of that style; contentType then unused, headers ignored", + "call": 0, + "expect": { "body": "filter%5Bcolor%5D=red&filter%5Bsize%5D=L&n=x&path=/a/b:c@d&x=1&y=2&tags=a,b%20c" } + }, + { + "case": "a form body's members by their Encoding Objects' style, explode and allowReserved, as query parameters of that style; contentType then unused, headers ignored", + "call": 1, + "expect": { "body": "p=a%7Cb&path=%2Fa%2Fb%3Ac%40d&point=x,1,y,2&s=a%20b" } + }, + { + "case": "a form body's members by their Encoding Objects' style, explode and allowReserved, as query parameters of that style; contentType then unused, headers ignored", + "call": 2, + "expect": { "body": "a=1&id=%22x%22" } } ] } diff --git a/conformance/sdk-rust/src/describe.rs b/conformance/sdk-rust/src/describe.rs index c430e01..9d3bac8 100644 --- a/conformance/sdk-rust/src/describe.rs +++ b/conformance/sdk-rust/src/describe.rs @@ -171,8 +171,14 @@ pub(crate) fn cases( .collect() }, ); - let has_params = c["parameters"].as_array().is_some_and(|p| !p.is_empty()); - let body = c.get("requestBody"); + // Swagger 2.0's `formData` parameters are a form body, given as one. + let params = c["parameters"].as_array().map_or(&[][..], Vec::as_slice); + let has_params = params + .iter() + .any(|p| p["in"] != "formData" && p["in"] != "body"); + let lifted = json!({ "content": { FORM: {} } }); + let form_data = params.iter().any(|p| p["in"] == "formData"); + let body = c.get("requestBody").or(form_data.then_some(&lifted)); for version in &versions { let mut op = Map::new(); for k in ["parameters", "requestBody", "responses"] { @@ -183,7 +189,7 @@ pub(crate) fn cases( let id = format!("{prefix}{i}"); let path = format!("/{id}{}", c["path"].as_str().unwrap_or("")); let method = c["method"].as_str().unwrap_or("get"); - let at = docs.add(version, &id, &path, method, Value::Object(op)); + let at = docs.add(version, &id, &path, method, Value::Object(op.clone())); let name = c["name"].as_str().unwrap_or(""); for (j, call) in c["calls"].as_array().into_iter().flatten().enumerate() { let what = format!("{name} ({version})"); @@ -212,6 +218,14 @@ pub(crate) fn cases( continue; } let (data, content_type) = input(&call["input"], has_params, body); + let (at, id) = match encoded(&op, &call["input"]["body"]) { + Some(op) => { + let id = format!("{id}e{j}"); + let path = format!("/{id}{}", c["path"].as_str().unwrap_or("")); + (docs.add(version, &id, &path, method, op), id) + } + None => (at, id.clone()), + }; calls.push(Call { version: version.clone(), op: at, @@ -220,7 +234,7 @@ pub(crate) fn cases( data, what, check: Check::Request { - id: id.clone(), + id, want, content_type, }, @@ -231,6 +245,27 @@ pub(crate) fn cases( merged } +/// `application/x-www-form-urlencoded`. +const FORM: &str = "application/x-www-form-urlencoded"; + +/// The operation with its form body's Encoding Objects as a call gives them, where they differ +/// from the description's: the TypeScript SDK takes them with the body (its client passes the +/// description's), the Rust SDK prints them from the description, so the call gets an operation +/// of its own, `c<i>e<j>`. +fn encoded(op: &Map<String, Value>, body: &Value) -> Option<Value> { + let written = op.get("requestBody")?["content"].get(FORM)?; + if body["contentType"] != FORM || written.get("encoding") == body.get("encoding") { + return None; + } + let mut op = Value::Object(op.clone()); + let media = op["requestBody"]["content"][FORM].as_object_mut()?; + match body.get("encoding") { + Some(e) => media.insert("encoding".into(), e.clone()), + None => media.remove("encoding"), + }; + Some(op) +} + /// A case's input as the Rust SDK takes it: `parameters` by location, and `body` an enum /// tagged by the media type as the description writes it. fn input(input: &Value, has_params: bool, body: Option<&Value>) -> (String, Option<String>) { diff --git a/conformance/sdk/cases.json b/conformance/sdk/cases.json index 3e5a71c..3f8c0cc 100644 --- a/conformance/sdk/cases.json +++ b/conformance/sdk/cases.json @@ -275,10 +275,13 @@ "name": "in: querystring as a form", "versions": ["3.2.1"], "parameters": [{ "name": "q", "in": "querystring", "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object" } } } }], - "calls": [{ "input": { "querystring": { "q": { "text": "a b&c", "n": [1, 2] } } }, "expect": { "query": "text=a%20b%26c&n=1&n=2", "pairs": [["text", "a b&c"], ["n", "1"], ["n", "2"]] } }] + "calls": [{ "input": { "querystring": { "q": { "text": "a b&c", "n": [1, 2] } } }, "expect": { "query": "text=a+b%26c&n=1&n=2", "pairs": [["text", "a b&c"], ["n", "1"], ["n", "2"]] } }] }, { "name": "JSON bodies: the content type given, +json and parameters, falsy values", + "covers": [ + "req: rfc9110.8.3.should-sender-generates-message-containing-content-generate — every JSON body sent with its Content-Type" + ], "method": "post", "requestBody": { "required": true, "content": { "application/json": { "schema": {} }, "application/merge-patch+json": { "schema": { "type": "object" } } } }, "calls": [ @@ -308,7 +311,7 @@ "calls": [ { "input": { "body": { "contentType": "application/x-www-form-urlencoded", "value": { "a": "x y+z", "b": [1, 2], "c": { "d": 1 }, "e": null } } }, - "expect": { "body": "a=x%20y%2Bz&b=1&b=2&c=%7B%22d%22%3A1%7D&e=", "bodyPairs": [["a", "x y+z"], ["b", "1"], ["b", "2"], ["c", "{\"d\":1}"], ["e", ""]] } + "expect": { "body": "a=x+y%2Bz&b=1&b=2&c=%7B%22d%22%3A1%7D&e=", "bodyPairs": [["a", "x y+z"], ["b", "1"], ["b", "2"], ["c", "{\"d\":1}"], ["e", ""]] } } ] }, @@ -328,30 +331,72 @@ "calls": [{ "input": {}, "expect": { "method": "COPY", "path": "", "query": "" } }] }, { - "name": "Swagger 2.0 collectionFormat as 3.x styles", + "name": "Swagger 2.0 collectionFormat in each location: csv, ssv, tsv and pipes in a path, a query and a header, multi in a query", "versions": ["2.0"], - "path": "/{p}", + "covers": [ + "req: oas-2.0.parameter-object.collectionFormat — csv a,b, ssv a b, tsv a<tab>b, pipes a|b (percent-encoded in a URI, as written in a header), multi a pair per item, csv the default" + ], + "path": "/{p}/{s}/{t}/{b}", "parameters": [ { "name": "p", "in": "path", "required": true, "type": "array", "items": { "type": "string" } }, - { "name": "csv", "in": "query", "type": "array", "items": { "type": "string" } }, + { "name": "s", "in": "path", "required": true, "type": "array", "items": { "type": "string" }, "collectionFormat": "ssv" }, + { "name": "t", "in": "path", "required": true, "type": "array", "items": { "type": "string" }, "collectionFormat": "tsv" }, + { "name": "b", "in": "path", "required": true, "type": "array", "items": { "type": "string" }, "collectionFormat": "pipes" }, + { "name": "csv", "in": "query", "type": "array", "items": { "type": "string" }, "collectionFormat": "csv" }, { "name": "multi", "in": "query", "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "ssv", "in": "query", "type": "array", "items": { "type": "string" }, "collectionFormat": "ssv" }, + { "name": "tsv", "in": "query", "type": "array", "items": { "type": "string" }, "collectionFormat": "tsv" }, { "name": "pipes", "in": "query", "type": "array", "items": { "type": "string" }, "collectionFormat": "pipes" }, - { "name": "X-H", "in": "header", "type": "array", "items": { "type": "string" } } + { "name": "X-C", "in": "header", "type": "array", "items": { "type": "string" } }, + { "name": "X-S", "in": "header", "type": "array", "items": { "type": "string" }, "collectionFormat": "ssv" }, + { "name": "X-T", "in": "header", "type": "array", "items": { "type": "string" }, "collectionFormat": "tsv" }, + { "name": "X-P", "in": "header", "type": "array", "items": { "type": "string" }, "collectionFormat": "pipes" } + ], + "calls": [ + { + "input": { + "path": { "p": ["a", "b"], "s": ["a", "b"], "t": ["a", "b"], "b": ["a", "b"] }, + "query": { "csv": ["a", "b"], "multi": ["a", "b"], "ssv": ["a", "b"], "tsv": ["a", "b"], "pipes": ["a", "b"] }, + "header": { "X-C": ["a", "b"], "X-S": ["a", "b"], "X-T": ["a", "b"], "X-P": ["a", "b"] } + }, + "expect": { + "path": "/a,b/a%20b/a%09b/a%7Cb", + "query": "csv=a,b&multi=a&multi=b&ssv=a%20b&tsv=a%09b&pipes=a%7Cb", + "headers": { "X-C": "a,b", "X-S": "a b", "X-T": "a\tb", "X-P": "a|b" } + } + } + ] + }, + { + "name": "Swagger 2.0 an Items Object's collectionFormat: the arrays inside an array joined by their own, level by level", + "versions": ["2.0"], + "covers": [ + "req: oas-2.0.items-object.collectionFormat — an array of arrays: the outer by the parameter's format, each inner one by its Items Object's (csv by default), in a path, a query and a header" + ], + "path": "/{m}", + "parameters": [ + { "name": "m", "in": "path", "required": true, "type": "array", "items": { "type": "array", "collectionFormat": "ssv", "items": { "type": "string" } } }, + { "name": "grid", "in": "query", "type": "array", "collectionFormat": "multi", "items": { "type": "array", "collectionFormat": "pipes", "items": { "type": "array", "items": { "type": "integer" } } } }, + { "name": "n", "in": "query", "type": "array", "items": { "type": "array", "collectionFormat": "tsv", "items": { "type": "string" } } }, + { "name": "X-N", "in": "header", "type": "array", "collectionFormat": "pipes", "items": { "type": "array", "collectionFormat": "tsv", "items": { "type": "string" } } } ], "calls": [ { - "input": { "path": { "p": ["a", "b"] }, "query": { "csv": ["a", "b"], "multi": ["a", "b"], "ssv": ["a", "b"], "pipes": ["a", "b"] }, "header": { "X-H": ["a", "b"] } }, - "expect": { "path": "/a,b", "query": "csv=a,b&multi=a&multi=b&ssv=a%20b&pipes=a%7Cb", "headers": { "X-H": "a,b" } } + "input": { + "path": { "m": [["a", "b"], ["c"]] }, + "query": { "grid": [[[1, 2], [3]], [[4]]], "n": [["a", "b"], ["c"]] }, + "header": { "X-N": [["a", "b"], ["c"]] } + }, + "expect": { "path": "/a%20b,c", "query": "grid=1,2%7C3&grid=4&n=a%09b,c", "headers": { "X-N": "a\tb|c" } } } ] }, { - "name": "Swagger 2.0 tsv has no 3.x style: a warning, and csv", + "name": "Swagger 2.0 multi outside a query: a warning, and csv", "versions": ["2.0"], "warns": "swagger.collectionFormat", - "parameters": [{ "name": "t", "in": "query", "type": "array", "items": { "type": "string" }, "collectionFormat": "tsv" }], - "calls": [{ "input": { "query": { "t": ["a", "b"] } }, "expect": { "query": "t=a,b" } }] + "parameters": [{ "name": "X-M", "in": "header", "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }], + "calls": [{ "input": { "header": { "X-M": ["a", "b"] } }, "expect": { "headers": { "X-M": "a,b" } } }] }, { "name": "a style a location does not take: a warning, and the default", @@ -425,12 +470,24 @@ {"name": "a body neither JSON nor text is its bytes as given; JSON and text given as bytes are read as UTF-8, and refused when they are not", "targets": ["typescript"], "responses": {"200": {"description": "ok", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}, "image/png": {"schema": {"type": "string", "contentMediaType": "image/png"}}, "application/json": {"schema": {}}, "text/plain": {"schema": {"type": "string"}}}}}, "calls": [{"status": 200, "headers": {"content-type": "application/octet-stream"}, "bytes": "fffe00ff80c0ed", "expect": {"response": "200", "mediaType": "application/octet-stream", "bytes": "fffe00ff80c0ed"}}, {"status": 200, "headers": {"content-type": "image/png"}, "bytes": "89504e470d0a1a0a0000000d49484452", "expect": {"response": "200", "mediaType": "image/png", "bytes": "89504e470d0a1a0a0000000d49484452"}}, {"status": 200, "headers": {"content-type": "application/octet-stream"}, "body": "ab\u00e9", "expect": {"response": "200", "bytes": "6162c3a9"}}, {"status": 200, "headers": {"content-type": "application/json"}, "bytes": "efbbbf7b2261223a22c3a9227d", "expect": {"response": "200", "mediaType": "application/json", "body": {"a": "\u00e9"}}}, {"status": 200, "headers": {"content-type": "text/plain; charset=utf-8"}, "bytes": "68c3a96c6c6f", "expect": {"response": "200", "mediaType": "text/plain", "body": "h\u00e9llo"}}, {"status": 200, "headers": {"content-type": "text/plain"}, "bytes": "efbbbf6869", "expect": {"response": "200", "body": "\ufeffhi"}}, {"status": 200, "headers": {"content-type": "text/plain"}, "bytes": "68ff", "expect": {"response": null, "mediaType": "text/plain", "bytes": "68ff"}}, {"status": 200, "headers": {"content-type": "application/json"}, "bytes": "7b2261223a22ff227d", "expect": {"response": null, "mediaType": "application/json", "bytes": "7b2261223a22ff227d"}}]}, {"name": "a media range is read by the type sent: JSON parsed, text the text, any other the bytes", "targets": ["typescript"], "responses": {"200": {"description": "ok", "content": {"image/*": {"schema": {"type": "string", "format": "binary"}}, "*/*": {"schema": {}}}}}, "calls": [{"status": 200, "headers": {"content-type": "image/webp"}, "bytes": "52494646ff00", "expect": {"response": "200", "mediaType": "image/*", "bytes": "52494646ff00"}}, {"status": 200, "headers": {"content-type": "application/zip"}, "bytes": "504b0304ff", "expect": {"mediaType": "*/*", "bytes": "504b0304ff"}}, {"status": 200, "headers": {"content-type": "text/csv"}, "bytes": "612c62", "expect": {"mediaType": "*/*", "body": "a,b"}}, {"status": 200, "headers": {"content-type": "application/problem+json"}, "bytes": "5b315d", "expect": {"mediaType": "*/*", "body": [1]}}]}, {"name": "flowapiReadsBytes says which bodies are read as bytes: any type but JSON and text/*, and none", "targets": ["typescript"], "calls": [{"readsBytes": "application/octet-stream", "expect": true}, {"readsBytes": "image/png", "expect": true}, {"readsBytes": "application/xml", "expect": true}, {"readsBytes": "multipart/form-data; boundary=x", "expect": true}, {"readsBytes": null, "expect": true}, {"readsBytes": "application/json; charset=utf-8", "expect": false}, {"readsBytes": "application/problem+json", "expect": false}, {"readsBytes": "Text/Plain", "expect": false}, {"readsBytes": "text/event-stream", "expect": false}]}, - {"name": "multipart/form-data by the Encoding Object's defaults: a file part with its name and type, text, a number, an object as JSON, an array's items as parts of one name in order, undefined left out, null refused", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary"}, "caption": {"type": "string"}, "rank": {"type": "integer"}, "meta": {"type": "object", "properties": {"taken": {"type": "string"}}}, "tags": {"type": "array", "items": {"type": "string"}}, "files": {"type": "array", "items": {"type": "string", "format": "binary"}}, "shapes": {"type": "array", "items": {"type": "object"}}}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$file": {"text": "PNG", "name": "cat.png", "type": "image/png"}}, "caption": "a cat", "rank": 3, "meta": {"taken": "2026"}, "tags": ["a", "b"], "shapes": [{"r": 1}, [2]]}}}, "expect": {"headers": {"content-type": "multipart/form-data; boundary=XyZ"}, "body": "--XyZ\r\nContent-Disposition: form-data; name=\"file\"; filename=\"cat.png\"\r\nContent-Type: image/png\r\n\r\nPNG\r\n--XyZ\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\na cat\r\n--XyZ\r\nContent-Disposition: form-data; name=\"rank\"\r\n\r\n3\r\n--XyZ\r\nContent-Disposition: form-data; name=\"meta\"\r\nContent-Type: application/json\r\n\r\n{\"taken\":\"2026\"}\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\nb\r\n--XyZ\r\nContent-Disposition: form-data; name=\"shapes\"\r\nContent-Type: application/json\r\n\r\n{\"r\":1}\r\n--XyZ\r\nContent-Disposition: form-data; name=\"shapes\"\r\nContent-Type: application/json\r\n\r\n[2]\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"files": [{"$file": {"text": "1", "name": "c.txt"}}, {"$file": {"text": "2", "name": "a.txt"}}, {"$file": {"text": "3", "name": "b.txt"}}]}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"files\"; filename=\"c.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n1\r\n--XyZ\r\nContent-Disposition: form-data; name=\"files\"; filename=\"a.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n2\r\n--XyZ\r\nContent-Disposition: form-data; name=\"files\"; filename=\"b.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n3\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$bytes": ""}, "caption": {"$undefined": true}, "tags": ["a", {"$undefined": true}, "b"]}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"file\"; filename=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\nb\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$file": {"bytes": "fffe0080c0ed0d0a", "name": "x.bin"}}}}}, "expect": {"bytes": "2d2d58795a0d0a436f6e74656e742d446973706f736974696f6e3a20666f726d2d646174613b206e616d653d2266696c65223b2066696c656e616d653d22782e62696e220d0a436f6e74656e742d547970653a206170706c69636174696f6e2f6f637465742d73747265616d0d0a0d0afffe0080c0ed0d0a0d0a2d2d58795a2d2d0d0a"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {}}}, "expect": {"headers": {"content-type": "multipart/form-data; boundary=XyZ"}, "body": "--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"caption": null}}}, "expect": {"refused": {"location": "body", "parameter": "caption", "reason": "null"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"tags": ["a", null]}}}, "expect": {"refused": {"location": "body", "parameter": "tags", "reason": "null"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"rank": {"$number": "NaN"}}}}, "expect": {"refused": {"location": "body", "parameter": "rank", "reason": "non-finite"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"meta": {"taken": {"$number": "Infinity"}}}}}, "expect": {"refused": {"location": "body", "parameter": "meta", "reason": "non-finite"}}}]}, - {"name": "multipart/form-data with the Encoding Object given: contentType replaces the default and a file's own type replaces it, a list or a range needs one, headers are written (Content-Type among them ignored) and refused when they would inject", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"id": {"type": "string"}, "photo": {}, "note": {"type": "string"}}}, "encoding": {"id": {"contentType": "application/json"}, "photo": {"contentType": "image/png, image/jpeg", "headers": {"X-Rate-Limit-Limit": {"schema": {"type": "integer"}}}}, "note": {"contentType": "text/plain; charset=utf-8"}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"id": "a\"1", "note": "h\u00e9", "photo": {"$file": {"text": "J", "name": "p.jpg", "type": "image/jpeg"}}}, "encoding": {"id": {"contentType": "application/json"}, "note": {"contentType": "text/plain; charset=utf-8"}, "photo": {"contentType": "image/png, image/jpeg", "headers": {"X-Rate-Limit-Limit": "10", "content-type": "text/html"}}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"id\"\r\nContent-Type: application/json\r\n\r\n\"a\\\"1\"\r\n--XyZ\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nh\u00e9\r\n--XyZ\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"p.jpg\"\r\nContent-Type: image/jpeg\r\nX-Rate-Limit-Limit: 10\r\n\r\nJ\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"contentType": "image/png, image/jpeg"}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "media-range"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"contentType": "image/*"}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "media-range"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"contentType": "image/png"}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"blob\"\r\nContent-Type: image/png\r\n\r\n\u0000\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"headers": {"X-Rate-Limit-Limit": "1\r\nX-Evil: 1"}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"headers": {"X Bad": "1"}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "header-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"headers": {"Content-Disposition": "form-data; name=\"x\""}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "header-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"id": "x"}, "encoding": {"id": {"contentType": "text/plain\r\nX-Evil: 1"}}}}, "expect": {"refused": {"location": "body", "parameter": "id", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$file": {"text": "J", "type": "image/png\r\nX: 1"}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "control-character"}}}]}, - {"name": "multipart file names: the last path segment only, refused when empty, . or .., or holding a quote, a backslash left as a separator, a CR, LF or NUL; names likewise; other text kept as UTF-8", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "../../etc/passwd"}}, "g": {"$file": {"text": "y", "name": "C:\\Users\\me\\cat.png"}}, "h": {"$file": {"text": "z", "name": "%0d%0a ch\u00e9.txt"}}, "n\u00e9": "v"}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"f\"; filename=\"passwd\"\r\nContent-Type: application/octet-stream\r\n\r\nx\r\n--XyZ\r\nContent-Disposition: form-data; name=\"g\"; filename=\"cat.png\"\r\nContent-Type: application/octet-stream\r\n\r\ny\r\n--XyZ\r\nContent-Disposition: form-data; name=\"h\"; filename=\"%0d%0a ch\u00e9.txt\"\r\nContent-Type: application/octet-stream\r\n\r\nz\r\n--XyZ\r\nContent-Disposition: form-data; name=\"n\u00e9\"\r\n\r\nv\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": ".."}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "dir/.."}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "dir/"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": ""}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "a\".png"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "quote"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "a\r\nContent-Type: text/html"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "a\u0000.png"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a\r\nb": "v"}}}, "expect": {"refused": {"location": "body", "parameter": "a\r\nb", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a\"b": "v"}}}, "expect": {"refused": {"location": "body", "parameter": "a\"b", "reason": "quote"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a\\b": "v"}}}, "expect": {"refused": {"location": "body", "parameter": "a\\b", "reason": "quote"}}}]}, - {"name": "a multipart boundary: the one the content type gives, refused when RFC 2046 does not allow it or a part holds it; else 128 random bits, drawn again while a part holds them", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a": "x--XyZ"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"XyZ": "v"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$bytes": "2d2d58795a"}}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=", "value": {"a": "x"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "value": {"a": "x"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=\"ends with space \"", "value": {"a": "x"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; BOUNDARY=\"a b:c\"", "value": {"a": "x"}}}, "expect": {"headers": {"content-type": "multipart/form-data; BOUNDARY=\"a b:c\""}, "body": "--a b:c\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nx\r\n--a b:c--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data", "value": {"a": "x"}}}, "expect": {"boundary": "drawn", "headers": {"content-type": "multipart/form-data; boundary={boundary}"}, "body": "--{boundary}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nx\r\n--{boundary}--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data", "value": {"a": "flowapi-00000000000000000000000000000000"}}}, "randoms": ["00000000000000000000000000000000", "11111111111111111111111111111111"], "expect": {"headers": {"content-type": "multipart/form-data; boundary=flowapi-11111111111111111111111111111111"}, "body": "--flowapi-11111111111111111111111111111111\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nflowapi-00000000000000000000000000000000\r\n--flowapi-11111111111111111111111111111111--\r\n"}}]}, + {"name": "multipart/form-data by the Encoding Object's defaults: a file part with its name and type, text, a number, an object as JSON, an array's items as parts of one name in order, undefined left out, null refused", "covers": ["req: oas-3.0.encoding-object.contentType — no Encoding Object: a file as its own type or application/octet-stream, text as text/plain (no header), an object as application/json", "req: oas-3.1.encoding-object.contentType — no Encoding Object: a file as its own type or application/octet-stream, text as text/plain (no header), an object as application/json", "req: oas-3.2.encoding-object.contentType — no Encoding Object: a file as its own type or application/octet-stream, text as text/plain (no header), an object as application/json", "req: oas-3.2.media-type-object.encoding-by-name.must-serializing-property-values-array-type-handled — tags and files: each item a part of the property's name, in order", "req: rfc7578.4.2.must-each-part-contain-content-disposition-header — every part opens with Content-Disposition: form-data", "req: rfc7578.4.2.must-content-disposition-header-field-contain-additional — and its name, the property's", "req: rfc7578.4.2.should-form-data-represents-content-file-name — a file part carries filename, blob when the bytes have no name", "req: rfc7578.4.3.must-match-widely-deployed-implementations-multiple-files — files: each file a part of its own, all named files", "req: rfc7578.4.4.may-each-part-have-optional-content-type — a text part sends none, the default text/plain", "req: rfc7578.4.4.should-contents-file-sent-file-data-labeled — a file part labeled with its type, else application/octet-stream", "req: rfc7578.4.7.should-not-senders-generate-any-parts-content-transfer — no part carries Content-Transfer-Encoding", "req: rfc7578.5.2.must-not-form-parts-identical-field-names-coalesced — tags: a and b two parts, never one", "req: rfc9110.8.3.3.must-message-body-itself-protocol-element-sender — every line of the body ends with CRLF", "req: oas-3.2.media-type-object.encoding-by-name.must-all-other-value-types-both-top — meta: an object property one part of the whole value; shapes: an array item that is itself an array ([2]) one part of the whole item, as JSON", "req: oas-3.2.schema-object.non-json-data.must-due-limited-requirements-searching-schemas-serializers — the writer inspects the data: bytes and files a file part, an object JSON, a scalar text, whatever the schema says"], "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary"}, "caption": {"type": "string"}, "rank": {"type": "integer"}, "meta": {"type": "object", "properties": {"taken": {"type": "string"}}}, "tags": {"type": "array", "items": {"type": "string"}}, "files": {"type": "array", "items": {"type": "string", "format": "binary"}}, "shapes": {"type": "array", "items": {"type": "object"}}}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$file": {"text": "PNG", "name": "cat.png", "type": "image/png"}}, "caption": "a cat", "rank": 3, "meta": {"taken": "2026"}, "tags": ["a", "b"], "shapes": [{"r": 1}, [2]]}}}, "expect": {"headers": {"content-type": "multipart/form-data; boundary=XyZ"}, "body": "--XyZ\r\nContent-Disposition: form-data; name=\"file\"; filename=\"cat.png\"\r\nContent-Type: image/png\r\n\r\nPNG\r\n--XyZ\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\na cat\r\n--XyZ\r\nContent-Disposition: form-data; name=\"rank\"\r\n\r\n3\r\n--XyZ\r\nContent-Disposition: form-data; name=\"meta\"\r\nContent-Type: application/json\r\n\r\n{\"taken\":\"2026\"}\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\nb\r\n--XyZ\r\nContent-Disposition: form-data; name=\"shapes\"\r\nContent-Type: application/json\r\n\r\n{\"r\":1}\r\n--XyZ\r\nContent-Disposition: form-data; name=\"shapes\"\r\nContent-Type: application/json\r\n\r\n[2]\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"files": [{"$file": {"text": "1", "name": "c.txt"}}, {"$file": {"text": "2", "name": "a.txt"}}, {"$file": {"text": "3", "name": "b.txt"}}]}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"files\"; filename=\"c.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n1\r\n--XyZ\r\nContent-Disposition: form-data; name=\"files\"; filename=\"a.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n2\r\n--XyZ\r\nContent-Disposition: form-data; name=\"files\"; filename=\"b.txt\"\r\nContent-Type: application/octet-stream\r\n\r\n3\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$bytes": ""}, "caption": {"$undefined": true}, "tags": ["a", {"$undefined": true}, "b"]}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"file\"; filename=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\nb\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$file": {"bytes": "fffe0080c0ed0d0a", "name": "x.bin"}}}}}, "expect": {"bytes": "2d2d58795a0d0a436f6e74656e742d446973706f736974696f6e3a20666f726d2d646174613b206e616d653d2266696c65223b2066696c656e616d653d22782e62696e220d0a436f6e74656e742d547970653a206170706c69636174696f6e2f6f637465742d73747265616d0d0a0d0afffe0080c0ed0d0a0d0a2d2d58795a2d2d0d0a"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {}}}, "expect": {"headers": {"content-type": "multipart/form-data; boundary=XyZ"}, "body": "--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"caption": null}}}, "expect": {"refused": {"location": "body", "parameter": "caption", "reason": "null"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"tags": ["a", null]}}}, "expect": {"refused": {"location": "body", "parameter": "tags", "reason": "null"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"rank": {"$number": "NaN"}}}}, "expect": {"refused": {"location": "body", "parameter": "rank", "reason": "non-finite"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"meta": {"taken": {"$number": "Infinity"}}}}}, "expect": {"refused": {"location": "body", "parameter": "meta", "reason": "non-finite"}}}]}, + {"name": "multipart/form-data with the Encoding Object given: contentType replaces the default and a file's own type replaces it, a list or a range needs one, headers are written (Content-Type among them ignored) and refused when they would inject", "covers": ["req: oas-3.0.encoding-object.contentType — id sent as application/json; a list or a range refused unless a file's own type picks one", "req: oas-3.1.encoding-object.contentType — id sent as application/json; a list or a range refused unless a file's own type picks one", "req: oas-3.2.encoding-object.contentType — id sent as application/json; a list or a range refused unless a file's own type picks one", "req: oas-3.0.encoding-object.headers — photo: X-Rate-Limit-Limit written in its part", "req: oas-3.1.encoding-object.headers — photo: X-Rate-Limit-Limit written in its part", "req: oas-3.2.encoding-object.headers — photo: X-Rate-Limit-Limit written in its part", "req: oas-3.0.encoding-object.headers.shall-content-type-described-separately-ignored-section — photo: a content-type among the headers left out", "req: oas-3.1.encoding-object.headers.shall-content-type-described-separately-ignored-section — photo: a content-type among the headers left out", "req: oas-3.2.encoding-object.headers.shall-content-type-described-separately-ignored-section — photo: a content-type among the headers left out", "req: oas-3.0.media-type-object.encoding — each part by the Encoding Object under its property's name", "req: oas-3.1.media-type-object.encoding — each part by the Encoding Object under its property's name", "req: oas-3.2.media-type-object.encoding — each part by the Encoding Object under its property's name", "req: oas-3.2.media-type-object.encoding-by-name.must-multipart-types-decode-object-multipart-form — each encoding key is the name of the Content-Disposition: form-data part it applies to (id, note, photo)"], "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"id": {"type": "string"}, "photo": {}, "note": {"type": "string"}}}, "encoding": {"id": {"contentType": "application/json"}, "photo": {"contentType": "image/png, image/jpeg", "headers": {"X-Rate-Limit-Limit": {"schema": {"type": "integer"}}}}, "note": {"contentType": "text/plain; charset=utf-8"}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"id": "a\"1", "note": "hé", "photo": {"$file": {"text": "J", "name": "p.jpg", "type": "image/jpeg"}}}, "encoding": {"id": {"contentType": "application/json"}, "note": {"contentType": "text/plain; charset=utf-8"}, "photo": {"contentType": "image/png, image/jpeg", "headers": {"X-Rate-Limit-Limit": "10", "content-type": "text/html"}}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"id\"\r\nContent-Type: application/json\r\n\r\n\"a\\\"1\"\r\n--XyZ\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nhé\r\n--XyZ\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"p.jpg\"\r\nContent-Type: image/jpeg\r\nX-Rate-Limit-Limit: 10\r\n\r\nJ\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"contentType": "image/png, image/jpeg"}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "media-range"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"contentType": "image/*"}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "media-range"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"contentType": "image/png"}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"blob\"\r\nContent-Type: image/png\r\n\r\n\u0000\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"headers": {"X-Rate-Limit-Limit": "1\r\nX-Evil: 1"}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"headers": {"X Bad": "1"}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "header-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "00"}}, "encoding": {"photo": {"headers": {"Content-Disposition": "form-data; name=\"x\""}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "header-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"id": "x"}, "encoding": {"id": {"contentType": "text/plain\r\nX-Evil: 1"}}}}, "expect": {"refused": {"location": "body", "parameter": "id", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$file": {"text": "J", "type": "image/png\r\nX: 1"}}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "control-character"}}}]}, + {"name": "multipart file names: the last path segment only, refused when empty, . or .., or holding a quote, a backslash left as a separator, a CR, LF or NUL; names likewise; other text kept as UTF-8", "covers": ["req: rfc7578.4.2.must-not-note-encoding-method-described-rfc5987-would — ché.txt written as UTF-8 in filename, no filename*", "req: rfc7578.5.1.2.may-any-text-whether-field-name-field — the name né and the file name ché.txt sent as UTF-8"], "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "../../etc/passwd"}}, "g": {"$file": {"text": "y", "name": "C:\\Users\\me\\cat.png"}}, "h": {"$file": {"text": "z", "name": "%0d%0a ch\u00e9.txt"}}, "n\u00e9": "v"}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"f\"; filename=\"passwd\"\r\nContent-Type: application/octet-stream\r\n\r\nx\r\n--XyZ\r\nContent-Disposition: form-data; name=\"g\"; filename=\"cat.png\"\r\nContent-Type: application/octet-stream\r\n\r\ny\r\n--XyZ\r\nContent-Disposition: form-data; name=\"h\"; filename=\"%0d%0a ch\u00e9.txt\"\r\nContent-Type: application/octet-stream\r\n\r\nz\r\n--XyZ\r\nContent-Disposition: form-data; name=\"n\u00e9\"\r\n\r\nv\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": ".."}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "dir/.."}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "dir/"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": ""}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "file-name"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "a\".png"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "quote"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "a\r\nContent-Type: text/html"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$file": {"text": "x", "name": "a\u0000.png"}}}}}, "expect": {"refused": {"location": "body", "parameter": "f", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a\r\nb": "v"}}}, "expect": {"refused": {"location": "body", "parameter": "a\r\nb", "reason": "control-character"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a\"b": "v"}}}, "expect": {"refused": {"location": "body", "parameter": "a\"b", "reason": "quote"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a\\b": "v"}}}, "expect": {"refused": {"location": "body", "parameter": "a\\b", "reason": "quote"}}}]}, + {"name": "a multipart boundary: the one the content type gives, refused when RFC 2046 does not allow it or a part holds it; else 128 random bits, drawn again while a part holds them", "covers": ["req: rfc7578.4.1.must-not-noted-section-5-1-rfc2046-boundary — a value, a name or a file holding the boundary refused; a drawn one drawn again"], "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a": "x--XyZ"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"XyZ": "v"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"f": {"$bytes": "2d2d58795a"}}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=", "value": {"a": "x"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "value": {"a": "x"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=\"ends with space \"", "value": {"a": "x"}}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "boundary"}}}, {"input": {"body": {"contentType": "multipart/form-data; BOUNDARY=\"a b:c\"", "value": {"a": "x"}}}, "expect": {"headers": {"content-type": "multipart/form-data; BOUNDARY=\"a b:c\""}, "body": "--a b:c\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nx\r\n--a b:c--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data", "value": {"a": "x"}}}, "expect": {"boundary": "drawn", "headers": {"content-type": "multipart/form-data; boundary={boundary}"}, "body": "--{boundary}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nx\r\n--{boundary}--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data", "value": {"a": "flowapi-00000000000000000000000000000000"}}}, "randoms": ["00000000000000000000000000000000", "11111111111111111111111111111111"], "expect": {"headers": {"content-type": "multipart/form-data; boundary=flowapi-11111111111111111111111111111111"}, "body": "--flowapi-11111111111111111111111111111111\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nflowapi-00000000000000000000000000000000\r\n--flowapi-11111111111111111111111111111111--\r\n"}}]}, {"name": "a Blob or a File is read by flowapiBlob (its name, else a File's own, else blob; its type), and refused when given unread", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a": {"$blob": {"text": "A", "as": "photo.png", "blobType": "image/png"}}, "b": {"$blob": {"text": "B"}}, "c": {"$blob": {"text": "C", "as": "mine.png", "name": "yours.png", "type": "image/webp", "blobType": "image/png"}}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"a\"; filename=\"photo.png\"\r\nContent-Type: image/png\r\n\r\nA\r\n--XyZ\r\nContent-Disposition: form-data; name=\"b\"; filename=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\nB\r\n--XyZ\r\nContent-Disposition: form-data; name=\"c\"; filename=\"yours.png\"\r\nContent-Type: image/webp\r\n\r\nC\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a": {"$unread": {"text": "A"}}}}}, "expect": {"refused": {"location": "body", "parameter": "a", "reason": "unread-blob"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"a": [{"$unread": {"text": "A"}}]}}}, "expect": {"refused": {"location": "body", "parameter": "a", "reason": "unread-blob"}}}]}, - {"name": "multipart/form-data as an array of objects (3.2): the parts in order, each item's members", "targets": ["typescript"], "versions": ["3.2.1"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "array", "items": {"type": "object", "additionalProperties": {"type": "string"}}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": [{"a": "1"}, {"b": "2"}, {"a": "3"}]}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n--XyZ\r\nContent-Disposition: form-data; name=\"b\"\r\n\r\n2\r\n--XyZ\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n3\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": ["a"]}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "unnamed-part"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": [null]}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "null"}}}]}, - {"name": "a request body neither JSON, text nor a form may be given as bytes, sent as they are; a multipart body given as a string or bytes is the caller's", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}, "image/*": {"schema": {}}, "multipart/form-data": {"schema": {}}, "multipart/mixed": {"schema": {}}}}, "calls": [{"input": {"body": {"contentType": "application/octet-stream", "value": {"$bytes": "fffe00ff80"}}}, "expect": {"headers": {"content-type": "application/octet-stream"}, "bytes": "fffe00ff80"}}, {"input": {"body": {"contentType": "image/png", "value": {"$bytes": "89504e47"}}}, "expect": {"headers": {"content-type": "image/png"}, "bytes": "89504e47"}}, {"input": {"body": {"contentType": "application/octet-stream", "value": "ab"}}, "expect": {"body": "ab"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=q", "value": "--q--\r\n"}}, "expect": {"headers": {"content-type": "multipart/form-data; boundary=q"}, "body": "--q--\r\n"}}, {"input": {"body": {"contentType": "multipart/mixed; boundary=q", "value": {"$bytes": "2d2d712d2d0d0a"}}}, "expect": {"bytes": "2d2d712d2d0d0a"}}]} + {"name": "multipart/form-data as an array of objects (3.2): the parts in order, each item's members", "covers": ["req: oas-3.2.media-type-object.encoding-by-position.shall-applications-wish-preserve-part-order-multipart — the parts in the array's order, a, b, a", "req: rfc7578.5.2.should-form-processors-given-forms-well-defined — the parts sent back in the order given"], "targets": ["typescript"], "versions": ["3.2.1"], "method": "post", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "array", "items": {"type": "object", "additionalProperties": {"type": "string"}}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": [{"a": "1"}, {"b": "2"}, {"a": "3"}]}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n--XyZ\r\nContent-Disposition: form-data; name=\"b\"\r\n\r\n2\r\n--XyZ\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n3\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": ["a"]}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "unnamed-part"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": [null]}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "null"}}}]}, + {"name": "a request body neither JSON, text nor a form may be given as bytes, sent as they are; a multipart body given as a string or bytes is the caller's", "targets": ["typescript"], "method": "post", "requestBody": {"required": true, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}, "image/*": {"schema": {}}, "multipart/form-data": {"schema": {}}, "multipart/mixed": {"schema": {}}}}, "calls": [{"input": {"body": {"contentType": "application/octet-stream", "value": {"$bytes": "fffe00ff80"}}}, "expect": {"headers": {"content-type": "application/octet-stream"}, "bytes": "fffe00ff80"}}, {"input": {"body": {"contentType": "image/png", "value": {"$bytes": "89504e47"}}}, "expect": {"headers": {"content-type": "image/png"}, "bytes": "89504e47"}}, {"input": {"body": {"contentType": "application/octet-stream", "value": "ab"}}, "expect": {"body": "ab"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=q", "value": "--q--\r\n"}}, "expect": {"headers": {"content-type": "multipart/form-data; boundary=q"}, "body": "--q--\r\n"}}, {"input": {"body": {"contentType": "multipart/mixed; boundary=q", "value": {"$bytes": "2d2d712d2d0d0a"}}}, "expect": {"bytes": "2d2d712d2d0d0a"}}]}, + {"name": "a form body by WHATWG's rules: 3.2's own examples (JSON values, a JSON id, base64url with padding)", "method": "post", "covers": ["req: oas-3.0.interoperability-with-web-browser-environments.should-implementations-needing-maximum-compatibility-web-browsers — a form's content percent-encoded by WHATWG's form-urlencoded rules: a space as +, + : , { } \" as %2B %3A %2C %7B %7D %22, ~ ! ' ( ) encoded, * - . _ kept (3.2's own example bytes)", "req: oas-3.1.interoperability-with-web-browser-environments.should-implementations-needing-maximum-compatibility-web-browsers — a form's content percent-encoded by WHATWG's form-urlencoded rules: a space as +, + : , { } \" as %2B %3A %2C %7B %7D %22, ~ ! ' ( ) encoded, * - . _ kept (3.2's own example bytes)", "req: oas-3.2.media-type-object.encoding-by-name.must-application-x-www-form-urlencoded-encoding — id: the encoding key names the pair, its value serialized by its Encoding Object"], "requestBody": {"content": {"application/x-www-form-urlencoded": {"schema": {"type": "object", "properties": {"id": {"type": "string", "format": "uuid"}, "address": {"type": "object", "properties": {}}, "name": {"type": "string"}, "icon": {"type": "string", "contentEncoding": "base64url"}}}, "encoding": {"icon": {"contentType": "image/png, image/jpeg"}}}}}, "calls": [{"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"id": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "address": {"streetAddress": "123 Example Dr.", "city": "Somewhere", "state": "CA", "zip": "99999+1234"}}}}, "expect": {"body": "id=f81d4fae-7dec-11d0-a765-00a0c91e6bf6&address=%7B%22streetAddress%22%3A%22123+Example+Dr.%22%2C%22city%22%3A%22Somewhere%22%2C%22state%22%3A%22CA%22%2C%22zip%22%3A%2299999%2B1234%22%7D"}}, {"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"id": "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"}, "encoding": {"id": {"contentType": "application/json"}}}}, "expect": {"body": "id=%22f81d4fae-7dec-11d0-a765-00a0c91e6bf6%22"}}, {"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"name": "example", "icon": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAABGdBTUEAALGPC_xhBQAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAAqADAAQAAAABAAAAAgAAAADO0J6QAAAAEElEQVQIHWP8zwACTGCSAQANHQEDqtPptQAAAABJRU5ErkJggg=="}, "encoding": {"icon": {"contentType": "image/png, image/jpeg"}}}}, "expect": {"body": "name=example&icon=iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAABGdBTUEAALGPC_xhBQAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAAqADAAQAAAABAAAAAgAAAADO0J6QAAAAEElEQVQIHWP8zwACTGCSAQANHQEDqtPptQAAAABJRU5ErkJggg%3D%3D"}}, {"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"k ~*'!()": "a b~*'!()é&=+/?"}}}, "expect": {"body": "k+%7E*%27%21%28%29=a+b%7E*%27%21%28%29%C3%A9%26%3D%2B%2F%3F", "bodyPairs": [["k ~*'!()", "a b~*'!()é&=+/?"]]}}]}, + {"name": "a query string is percent-encoded by RFC 3986, not by WHATWG's generic query rules: \" < > ` { } | ^ and the space encoded", "covers": ["req: oas-3.0.interoperability-with-web-browser-environments.should-not-however-they-rely-whatwg-s-less — q: every character WHATWG's query set leaves raw but RFC 3986 forbids is percent-encoded, so the URL passes RFC 3986 validation", "req: oas-3.1.interoperability-with-web-browser-environments.should-not-however-they-rely-whatwg-s-less — q: every character WHATWG's query set leaves raw but RFC 3986 forbids is percent-encoded, so the URL passes RFC 3986 validation"], "parameters": [{"name": "q", "in": "query", "schema": {"type": "string"}}], "calls": [{"input": {"query": {"q": "a\"<>`{}|^ b"}}, "expect": {"query": "q=a%22%3C%3E%60%7B%7D%7C%5E%20b", "pairs": [["q", "a\"<>`{}|^ b"]]}}]}, + {"name": "a form body's members by their Encoding Objects' style, explode and allowReserved, as query parameters of that style; contentType then unused, headers ignored", "method": "post", "covers": ["req: oas-3.0.encoding-object.style — tags: form unexploded a,b; spaceDelimited %20; pipeDelimited %7C; filter: deepObject filter[color]; as a query parameter of the style is", "req: oas-3.1.encoding-object.style — tags: form unexploded a,b; spaceDelimited %20; pipeDelimited %7C; filter: deepObject filter[color]; as a query parameter of the style is", "req: oas-3.2.encoding-object.style — tags: form unexploded a,b; spaceDelimited %20; pipeDelimited %7C; filter: deepObject filter[color]; as a query parameter of the style is", "req: oas-3.0.encoding-object.explode — point: explode true makes a pair per member (x=1&y=2), false one pair point=x,1,y,2; style form by default", "req: oas-3.1.encoding-object.explode — point: explode true makes a pair per member (x=1&y=2), false one pair point=x,1,y,2; style form by default", "req: oas-3.2.encoding-object.explode — point: explode true makes a pair per member (x=1&y=2), false one pair point=x,1,y,2; style form by default", "req: oas-3.0.encoding-object.allowReserved — path: allowReserved keeps / : @ as they are; without it they are percent-encoded", "req: oas-3.1.encoding-object.allowReserved — path: allowReserved keeps / : @ as they are; without it they are percent-encoded", "req: oas-3.2.encoding-object.allowReserved — path: allowReserved keeps / : @ as they are; without it they are percent-encoded", "req: oas-3.0.encoding-object.style.must-note-initial-used-query-strings-not — no body starts with ?", "req: oas-3.1.encoding-object.style.must-note-initial-used-query-strings-not — no body starts with ?", "req: oas-3.2.encoding-object.style.must-note-initial-used-query-strings-not — no body starts with ?", "req: oas-3.1.encoding-object.style.shall-value-explicitly-defined-value-contenttype-implicit — n: contentType application/json beside a style, explode or allowReserved is not used: n=x, not %22x%22", "req: oas-3.2.encoding-object.style.shall-value-explicitly-defined-value-contenttype-implicit — n: contentType application/json beside a style, explode or allowReserved is not used: n=x, not %22x%22", "req: oas-3.1.encoding-object.explode.shall-value-explicitly-defined-value-contenttype-implicit — n: contentType application/json beside a style, explode or allowReserved is not used: n=x, not %22x%22", "req: oas-3.2.encoding-object.explode.shall-value-explicitly-defined-value-contenttype-implicit — n: contentType application/json beside a style, explode or allowReserved is not used: n=x, not %22x%22", "req: oas-3.1.encoding-object.allowReserved.shall-value-explicitly-defined-value-contenttype-implicit — n: contentType application/json beside a style, explode or allowReserved is not used: n=x, not %22x%22", "req: oas-3.2.encoding-object.allowReserved.shall-value-explicitly-defined-value-contenttype-implicit — n: contentType application/json beside a style, explode or allowReserved is not used: n=x, not %22x%22", "req: oas-3.0.encoding-object.fixed-fields-for-rfc6570-style-serialization.recommended-match-intent-fields-compatible-version-3 — n: any of style, explode, allowReserved written: contentType ignored, the others their defaults (explode alone is style form)", "req: oas-3.0.encoding-object.fixed-fields-for-rfc6570-style-serialization.recommended-however-all-three-style-explode-allowreserved — id: none of the three written: contentType alone decides (application/json: a JSON string)", "req: oas-3.0.encoding-object.headers.shall-field-ignored-request-body-media-type — a: headers given for a form member write nothing; the request's only header is its Content-Type", "req: oas-3.1.encoding-object.headers.shall-field-ignored-request-body-media-type — a: headers given for a form member write nothing; the request's only header is its Content-Type", "req: oas-3.2.encoding-object.headers.shall-field-ignored-media-type-not-multipart — a: headers given for a form member write nothing; the request's only header is its Content-Type"], "requestBody": {"content": {"application/x-www-form-urlencoded": {"schema": {"type": "object"}, "encoding": {"tags": {"style": "form", "explode": false}, "filter": {"style": "deepObject"}, "point": {"explode": true}, "path": {"allowReserved": true}, "n": {"contentType": "application/json", "style": "form"}}}}}, "calls": [{"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"tags": ["a", "b c"], "filter": {"color": "red", "size": "L"}, "point": {"x": 1, "y": 2}, "path": "/a/b:c@d", "n": "x"}, "encoding": {"tags": {"style": "form", "explode": false}, "filter": {"style": "deepObject"}, "point": {"explode": true}, "path": {"allowReserved": true}, "n": {"contentType": "application/json", "style": "form"}}}}, "expect": {"body": "tags=a,b%20c&filter%5Bcolor%5D=red&filter%5Bsize%5D=L&x=1&y=2&path=/a/b:c@d&n=x", "headers": {"content-type": "application/x-www-form-urlencoded"}}}, {"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"s": ["a", "b"], "p": ["a", "b"], "point": {"x": 1, "y": 2}, "path": "/a/b:c@d"}, "encoding": {"s": {"style": "spaceDelimited"}, "p": {"style": "pipeDelimited"}, "point": {"explode": false}}}}, "expect": {"body": "s=a%20b&p=a%7Cb&point=x,1,y,2&path=%2Fa%2Fb%3Ac%40d"}}, {"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"id": "x", "a": "1"}, "encoding": {"id": {"contentType": "application/json"}, "a": {"headers": {"X-A": "1"}}}}}, "expect": {"body": "id=%22x%22&a=1", "headers": {"content-type": "application/x-www-form-urlencoded"}}}]}, + {"name": "multipart/form-data members by style (3.1, 3.2): a pair a part, no percent-encoding, contentType unused", "versions": ["3.1.2", "3.2.1"], "targets": ["typescript"], "method": "post", "covers": ["req: oas-3.1.encoding-object.fixed-fields-for-rfc6570-style-serialization.must-not-using-rfc6570-style-serialization-multipart-form — raw: a b&c/d sent as it is with allowReserved and without; no part percent-encoded", "req: oas-3.2.encoding-object.fixed-fields-for-rfc6570-style-serialization.must-not-using-rfc6570-style-serialization-multipart-form — raw: a b&c/d sent as it is with allowReserved and without; no part percent-encoded", "req: oas-3.1.encoding-object.style — multipart/form-data: tags unexploded one part a,b c; point deepObject a part point[x]; o exploded a part per member; each its own part", "req: oas-3.2.encoding-object.style — multipart/form-data: tags unexploded one part a,b c; point deepObject a part point[x]; o exploded a part per member; each its own part", "req: oas-3.1.encoding-object.explode — multipart/form-data: tags unexploded one part a,b c; point deepObject a part point[x]; o exploded a part per member; each its own part", "req: oas-3.2.encoding-object.explode — multipart/form-data: tags unexploded one part a,b c; point deepObject a part point[x]; o exploded a part per member; each its own part"], "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}, "encoding": {"tags": {"style": "form", "explode": false}, "point": {"style": "deepObject"}, "raw": {"allowReserved": true}, "j": {"contentType": "application/json", "explode": true}, "o": {"explode": true}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"tags": ["a", "b c"], "point": {"x": 1}, "raw": "a b&c/d", "j": "x", "o": {"r": "1", "g": "2"}}, "encoding": {"tags": {"style": "form", "explode": false}, "point": {"style": "deepObject"}, "raw": {"allowReserved": true}, "j": {"contentType": "application/json", "explode": true}, "o": {"explode": true}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na,b c\r\n--XyZ\r\nContent-Disposition: form-data; name=\"point[x]\"\r\n\r\n1\r\n--XyZ\r\nContent-Disposition: form-data; name=\"raw\"\r\n\r\na b&c/d\r\n--XyZ\r\nContent-Disposition: form-data; name=\"j\"\r\n\r\nx\r\n--XyZ\r\nContent-Disposition: form-data; name=\"r\"\r\n\r\n1\r\n--XyZ\r\nContent-Disposition: form-data; name=\"g\"\r\n\r\n2\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"n": {"$number": "NaN"}}, "encoding": {"n": {"style": "form"}}}}, "expect": {"refused": {"location": "body", "parameter": "n", "reason": "non-finite"}}}]}, + {"name": "a part's header values are written as given, never quoted or escaped; other header fields are sent, as OpenAPI's Encoding Object describes them", "targets": ["typescript"], "method": "post", "covers": ["req: oas-3.1.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged — note: X-Note's value with quotes, a comma and a semicolon written byte for byte", "req: oas-3.2.header-object.fixed-fields-for-use-with-schema.must-implementations-pass-header-values-through-unchanged — note: X-Note's value with quotes, a comma and a semicolon written byte for byte", "lossy: rfc7578.4.8.must-not-other-header-fields-included-ignored — flowapi follows OpenAPI: the Encoding Object's headers describe exactly such fields for multipart parts, and the writer sends them (X-Note); the owner's decision 2026-11-26"], "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object"}, "encoding": {"note": {"headers": {"X-Note": {"schema": {"type": "string"}}}}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"note": "n"}, "encoding": {"note": {"headers": {"X-Note": "a \"quoted\", value; x=1"}}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"note\"\r\nX-Note: a \"quoted\", value; x=1\r\n\r\nn\r\n--XyZ--\r\n"}}]}, + {"name": "multipart/mixed by position (3.2): an item a part in order, no Content-Disposition; prefixEncoding, then itemEncoding, then the defaults", "versions": ["3.2.1"], "targets": ["typescript"], "method": "post", "covers": ["req: oas-3.2.media-type-object.prefixEncoding — items 0 and 1 by prefixEncoding: application/json, then text/csv with its header", "req: oas-3.2.media-type-object.prefixEncoding.shall-prefixencoding-field-only-apply-media-type — items 0 and 1 by prefixEncoding: application/json, then text/csv with its header", "req: oas-3.2.media-type-object.itemEncoding — items 2 and 3 by itemEncoding: text/markdown each", "req: oas-3.2.media-type-object.itemEncoding.shall-itemencoding-field-only-apply-media-type — items 2 and 3 by itemEncoding: text/markdown each", "req: oas-3.2.media-type-object.encoding-by-position.shall-prefixitems-not-error-instance-array-shorter — one item and two prefixEncoding entries: the item written, the extra entry ignored"], "requestBody": {"required": true, "content": {"multipart/mixed": {"schema": {"type": "array", "prefixItems": [{"type": "object"}, {"type": "string"}], "items": {"type": "string"}}, "prefixEncoding": [{"contentType": "application/json"}, {"contentType": "text/csv"}], "itemEncoding": {"contentType": "text/markdown"}}}}, "calls": [{"input": {"body": {"contentType": "multipart/mixed; boundary=XyZ", "value": [{"a": 1}, "x,y", "z", "w"], "prefixEncoding": [{"contentType": "application/json"}, {"contentType": "text/csv", "headers": {"X-Rows": "1"}}], "itemEncoding": {"contentType": "text/markdown"}}}, "expect": {"headers": {"content-type": "multipart/mixed; boundary=XyZ"}, "body": "--XyZ\r\nContent-Type: application/json\r\n\r\n{\"a\":1}\r\n--XyZ\r\nContent-Type: text/csv\r\nX-Rows: 1\r\n\r\nx,y\r\n--XyZ\r\nContent-Type: text/markdown\r\n\r\nz\r\n--XyZ\r\nContent-Type: text/markdown\r\n\r\nw\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/mixed; boundary=XyZ", "value": ["only"], "prefixEncoding": [{"contentType": "text/csv"}, {"contentType": "application/json"}]}}, "expect": {"body": "--XyZ\r\nContent-Type: text/csv\r\n\r\nonly\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/mixed; boundary=XyZ", "value": [{"a": 1}, "t"]}}, "expect": {"body": "--XyZ\r\nContent-Type: application/json\r\n\r\n{\"a\":1}\r\n--XyZ\r\n\r\nt\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/mixed; boundary=XyZ", "value": [null]}}, "expect": {"refused": {"location": "body", "parameter": null, "reason": "null"}}}]}, + {"name": "a part that is itself multipart (3.2's nested encoding, its own example): its own body and boundary, its parts by the nested Encoding Objects", "versions": ["3.2.1"], "targets": ["typescript"], "method": "post", "covers": ["req: oas-3.2.encoding-object.nested-encoding.must-implementations-support-one-level-nesting-support — the second item, of type multipart/mixed, written as its own multipart body with a drawn boundary, its parts by the nested prefixEncoding; meta likewise as multipart/form-data", "req: oas-3.2.encoding-object.prefixEncoding — the nested parts by position: application/xml, the default text/plain (no header), image/png", "req: oas-3.2.encoding-object.encoding — meta: its nested parts by name, a as application/json, b by the defaults"], "requestBody": {"required": true, "content": {"multipart/mixed": {"schema": {"type": "array", "prefixItems": [{"type": "array"}, {"type": "array", "prefixItems": [{"type": "object"}, {"type": "string"}, {}]}]}, "prefixEncoding": [{}, {"contentType": "multipart/mixed", "prefixEncoding": [{"contentType": "application/xml"}, {}, {"contentType": "image/png"}]}]}, "multipart/form-data": {"schema": {"type": "object", "properties": {"meta": {"type": "object"}}}, "encoding": {"meta": {"contentType": "multipart/form-data", "encoding": {"a": {"contentType": "application/json"}}}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/mixed; boundary=XyZ", "value": [[1, 2], ["<a/>", "t", {"$bytes": "50"}]], "prefixEncoding": [{}, {"contentType": "multipart/mixed", "prefixEncoding": [{"contentType": "application/xml"}, {}, {"contentType": "image/png"}]}]}}, "randoms": ["22222222222222222222222222222222"], "expect": {"body": "--XyZ\r\nContent-Type: application/json\r\n\r\n[1,2]\r\n--XyZ\r\nContent-Type: multipart/mixed; boundary=flowapi-22222222222222222222222222222222\r\n\r\n--flowapi-22222222222222222222222222222222\r\nContent-Type: application/xml\r\n\r\n<a/>\r\n--flowapi-22222222222222222222222222222222\r\n\r\nt\r\n--flowapi-22222222222222222222222222222222\r\nContent-Type: image/png\r\n\r\nP\r\n--flowapi-22222222222222222222222222222222--\r\n\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"meta": {"a": "x", "b": "y"}}, "encoding": {"meta": {"contentType": "multipart/form-data", "encoding": {"a": {"contentType": "application/json"}}}}}}, "randoms": ["33333333333333333333333333333333"], "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"meta\"\r\nContent-Type: multipart/form-data; boundary=flowapi-33333333333333333333333333333333\r\n\r\n--flowapi-33333333333333333333333333333333\r\nContent-Disposition: form-data; name=\"a\"\r\nContent-Type: application/json\r\n\r\n\"x\"\r\n--flowapi-33333333333333333333333333333333\r\nContent-Disposition: form-data; name=\"b\"\r\n\r\ny\r\n--flowapi-33333333333333333333333333333333--\r\n\r\n--XyZ--\r\n"}}]}, + {"name": "a part with several types: the caller picks one, nothing is sniffed; an Encoding Object's type wins over the schema's contentMediaType", "targets": ["typescript"], "method": "post", "covers": ["req: oas-3.2.encoding-object.handling-multiple-contenttype-values.must-encoding-serialization-implementations-provide-mechanism-applications — photo: image/png, image/jpeg names no one type; the caller says which, by a file's own type or by the body's encoding", "req: oas-3.2.encoding-object.handling-multiple-contenttype-values.must-not-implementations-choose-offer-media-type-sniffing — photo: PNG's signature given as bytes is refused (media-range), never sniffed as image/png", "req: oas-3.1.encoding-object.encoding-multipart-media-types.shall-note-stated-working-binary-data-encoding — shot: contentMediaType image/png beside contentType image/jpeg: sent as image/jpeg", "req: oas-3.2.encoding-object.content-transfer-encoding-and-contentencoding.shall-note-stated-working-binary-data-encoding — shot: contentMediaType image/png beside contentType image/jpeg: sent as image/jpeg"], "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"photo": {}, "shot": {"type": "string", "contentMediaType": "image/png"}}}, "encoding": {"photo": {"contentType": "image/png, image/jpeg"}, "shot": {"contentType": "image/jpeg"}}}}}, "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "89504e470d0a1a0a"}}, "encoding": {"photo": {"contentType": "image/png, image/jpeg"}}}}, "expect": {"refused": {"location": "body", "parameter": "photo", "reason": "media-range"}}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": {"$bytes": "4a"}}, "encoding": {"photo": {"contentType": "image/jpeg"}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"blob\"\r\nContent-Type: image/jpeg\r\n\r\nJ\r\n--XyZ--\r\n"}}, {"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"shot": {"$bytes": "4a"}}, "encoding": {"shot": {"contentType": "image/jpeg"}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"shot\"; filename=\"blob\"\r\nContent-Type: image/jpeg\r\n\r\nJ\r\n--XyZ--\r\n"}}]}, + {"name": "Swagger 2.0 formData arrays by collectionFormat, as the table's encoding gives them: csv a,b, multi repeated, ssv, pipes, tsv a tab", "versions": ["2.0"], "method": "post", "parameters": [{"name": "tags", "in": "formData", "type": "array", "items": {"type": "string"}}, {"name": "m", "in": "formData", "type": "array", "items": {"type": "string"}, "collectionFormat": "multi"}, {"name": "s", "in": "formData", "type": "array", "items": {"type": "string"}, "collectionFormat": "ssv"}, {"name": "p", "in": "formData", "type": "array", "items": {"type": "string"}, "collectionFormat": "pipes"}, {"name": "t", "in": "formData", "type": "array", "items": {"type": "string"}, "collectionFormat": "tsv"}], "calls": [{"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"tags": ["a", "b"], "m": ["a", "b"], "s": ["a", "b"], "p": ["a", "b"], "t": ["a", "b"]}, "encoding": {"tags": {"style": "form", "explode": false}, "m": {"style": "form", "explode": true}, "s": {"style": "spaceDelimited", "explode": false}, "p": {"style": "pipeDelimited", "explode": false}, "t": {"style": "tabDelimited", "explode": false}}}}, "expect": {"body": "tags=a,b&m=a&m=b&s=a%20b&p=a%7Cb&t=a%09b", "bodyPairs": [["tags", "a,b"], ["m", "a"], ["m", "b"], ["s", "a b"], ["p", "a|b"], ["t", "a\tb"]]}}]}, + {"name": "Swagger 2.0 formData with a file: multipart/form-data, an array by its collectionFormat in one part", "versions": ["2.0"], "targets": ["typescript"], "method": "post", "parameters": [{"name": "file", "in": "formData", "type": "file", "required": true}, {"name": "tags", "in": "formData", "type": "array", "items": {"type": "string"}}], "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"file": {"$file": {"text": "x", "name": "a.txt"}}, "tags": ["a", "b"]}, "encoding": {"tags": {"style": "form", "explode": false}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a.txt\"\r\nContent-Type: application/octet-stream\r\n\r\nx\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na,b\r\n--XyZ--\r\n"}}]}, + {"name": "Swagger 2.0 formData arrays of arrays in a form: each level by its own collectionFormat, as the table's encoding gives them (nested)", "versions": ["2.0"], "covers": ["req: oas-2.0.items-object.collectionFormat — formData: grid multi of pipes of csv, rows csv of tsv, each join percent-encoded"], "method": "post", "parameters": [{"name": "grid", "in": "formData", "type": "array", "collectionFormat": "multi", "items": {"type": "array", "collectionFormat": "pipes", "items": {"type": "array", "items": {"type": "integer"}}}}, {"name": "rows", "in": "formData", "type": "array", "items": {"type": "array", "collectionFormat": "tsv", "items": {"type": "string"}}}], "calls": [{"input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"grid": [[[1, 2], [3]], [[4]]], "rows": [["a b", "c"], ["d"]]}, "encoding": {"grid": {"style": "form", "explode": true, "nested": ["pipeDelimited", "form"]}, "rows": {"style": "form", "explode": false, "nested": ["tabDelimited"]}}}}, "expect": {"body": "grid=1,2%7C3&grid=4&rows=a%20b%09c,d", "bodyPairs": [["grid", "1,2|3"], ["grid", "4"], ["rows", "a b\tc,d"]]}}]}, + {"name": "Swagger 2.0 formData arrays of arrays in a multipart part: each level by its own collectionFormat, its joins as written", "versions": ["2.0"], "targets": ["typescript"], "covers": ["req: oas-2.0.items-object.collectionFormat — formData with a file: grid's and rows's inner arrays joined in their parts, not percent-encoded"], "method": "post", "parameters": [{"name": "grid", "in": "formData", "type": "array", "collectionFormat": "multi", "items": {"type": "array", "collectionFormat": "pipes", "items": {"type": "array", "items": {"type": "integer"}}}}, {"name": "rows", "in": "formData", "type": "array", "items": {"type": "array", "collectionFormat": "tsv", "items": {"type": "string"}}}, {"name": "file", "in": "formData", "type": "file"}], "calls": [{"input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"grid": [[[1, 2], [3]], [[4]]], "rows": [["a b", "c"], ["d"]]}, "encoding": {"grid": {"style": "form", "explode": true, "nested": ["pipeDelimited", "form"]}, "rows": {"style": "form", "explode": false, "nested": ["tabDelimited"]}}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"grid\"\r\n\r\n1,2|3\r\n--XyZ\r\nContent-Disposition: form-data; name=\"grid\"\r\n\r\n4\r\n--XyZ\r\nContent-Disposition: form-data; name=\"rows\"\r\n\r\na b\tc,d\r\n--XyZ--\r\n"}}]} ] } diff --git a/conformance/specs/SOURCE.md b/conformance/specs/SOURCE.md index 16e2b63..e156bd1 100644 --- a/conformance/specs/SOURCE.md +++ b/conformance/specs/SOURCE.md @@ -6,18 +6,34 @@ Never edit one by hand; take a new release as below. | File | Specification | Repository | Ref | Commit | SHA-256 | | --- | --- | --- | --- | --- | --- | +| `openapi/2.0.md` | OpenAPI 2.0 (Swagger 2.0) | https://github.com/OAI/OpenAPI-Specification | `main`, `versions/2.0.md` | `4f86429f134f7e48b6351563549b4502fc69de52` (2026-10-18) | `57bf00dfabdb79634e2886e022f3c6195296682b237ed4a56c7fc631c85b3c91` | | `openapi/3.0.4.md` | OpenAPI 3.0.4 | https://github.com/OAI/OpenAPI-Specification | `main`, `versions/3.0.4.md` | `4f86429f134f7e48b6351563549b4502fc69de52` (2026-10-18) | `77af0760571a228e61ca2126d6f4de9efcf053d5dcfb7f0ad2f84d7ecf622ff6` | | `openapi/3.1.2.md` | OpenAPI 3.1.2 | same | `main`, `versions/3.1.2.md` | same | `7e30126d65acad53523f420e522d34edb3717af225aae727e73a522abc227da7` | | `openapi/3.2.1.md` | OpenAPI 3.2.1 | same | `main`, `versions/3.2.1.md` | same | `01fadb4ce8253fa70b962e1a04cb73c549f2fe98c6311dff2b323cac6e322fad` | | `openapi/LICENSE` | The OAI repository's licence | same | `main`, `LICENSE` | same | `4948367c65e1ce06690e2cadc6e86fce1a6a6db55ef874ce4b78c0f472ce5f13` | | `json-schema-2020-12/jsonschema-core.xml` | JSON Schema 2020-12 Core (`draft-bhutton-json-schema-01`) | https://github.com/json-schema-org/json-schema-spec | tag `draft-bhutton-json-schema-01` | `add836e705c9a07434c467b6b90946ba45258a73` (2022-06-10) | `94fe780e41c5230db71549786f57db9e24544828e23a4a94714545d9b41f1431` | | `json-schema-2020-12/jsonschema-validation.xml` | JSON Schema 2020-12 Validation (`draft-bhutton-json-schema-validation-01`) | same | same tag (also `draft-bhutton-json-schema-validation-01`) | same | `dcba094c316c17922cb95cc36affc53b9d9521139bfd5a3afdd1cc810ab39773` | +| `rfc/rfc6749.txt` | RFC 6749, The OAuth 2.0 Authorization Framework (October 2012) | https://www.rfc-editor.org/rfc/rfc6749.txt | the RFC Editor's text | (an RFC does not change) | `f204fc8661d6c92d2ec6e0b54808f961a9ad26e792f57f312d9528335519bd71` | +| `rfc/rfc6750.txt` | RFC 6750, OAuth 2.0 Bearer Token Usage (October 2012) | https://www.rfc-editor.org/rfc/rfc6750.txt | same | same | `9dc385cf4ecdd85024e5a95e447ede9230e11700bf35251906b25b37557d604b` | +| `rfc/rfc7578.txt` | RFC 7578, Returning Values from Forms: multipart/form-data (July 2015) | https://www.rfc-editor.org/rfc/rfc7578.txt | same | same | `813277f91c6c65c9047da9e9a8f1f0c19c1fb4bb1aaeea944bcf3bbdcc2eef49` | +| `rfc/rfc7617.txt` | RFC 7617, The 'Basic' HTTP Authentication Scheme (September 2015) | https://www.rfc-editor.org/rfc/rfc7617.txt | same | same | `bc941321da9912fbb1bc92ad1820848ddfd3283dbfbc30f26ea2800bdaf541db` | +| `rfc/rfc9110.xml` | RFC 9110, HTTP Semantics (June 2022, STD 97) | https://www.rfc-editor.org/rfc/rfc9110.xml | the RFC Editor's RFCXML v3 source, as published (prepped) | same | `09ec9ad4d1664623adcb298577e3fb9cd5c285f1bbe6b24d8c715b29f218e721` | The OpenAPI files under `versions/` are the published releases; `main` only gains new ones. 3.0.4, 3.1.2 and 3.2.1 are the latest patch releases of their minor versions on that commit (3.2.1 is dated 2026-09-10 in its revision history). 3.2.1 replaced 3.2.0 here on 2026-11-24, decided by the maintainers (owner delegated); the ids it changed are listed in -`../triage-2.md`. OpenAPI 2.0 is not pinned: it is out of scope until flowapi reads Swagger. +`../triage-2.md`. OpenAPI 2.0 (`versions/2.0.md`, Swagger 2.0) is pinned from the same commit since 2026-11-26: +flowapi reads Swagger 2.0 into the 3.x model, and the SDK lifts its `host`, `basePath`, `schemes` +and `securityDefinitions`. + +The RFCs are the ones the SDK's client and its multipart writer follow (`../triage-3.md`). An RFC +is never revised once published, so the RFC Editor's file is the pin and its SHA-256 the check. +RFC 9110 is published as RFCXML v3, and its XML is the copy here: the ledger reads its numbered +sections. RFCs 6749, 6750, 7578 and 7617 came before RFCXML v3 and the RFC Editor publishes no XML +for them, so their plain text is the copy (`../ledger/src/rfc_text.rs` reads it). RFC 8414 (OAuth +authorization server metadata) is not pinned: the client reads no metadata; OpenAPI 3.2's +`oauth2MetadataUrl` is out of scope for that reason. The JSON Schema files are the sources of the 2020-12 publication as Internet-Drafts (xml2rfc v2), not the rendered HTML: the ledger reads their sections, titles and anchors. @@ -35,12 +51,19 @@ The JSON Schema files are the sources of the 2020-12 publication as Internet-Dra the editors and authors in its front matter, and its `ipr` statement (from which xml2rfc writes the IETF Trust copyright notice); this table names where each came from. Decided 2026-11-24 by the maintainers (owner delegated). +- **The RFCs**: IETF Stream documents under the IETF Trust's Legal Provisions relating to IETF + Documents (BCP 78), which allow them to be copied and redistributed whole and unmodified. Each + copy keeps its own notice: RFCs 6749 and 6750 "Copyright (c) 2012 IETF Trust and the persons + identified as the document authors", RFCs 7578 and 7617 the same for 2015, and RFC 9110 its + `ipr="pre5378Trust200902"`, from which xml2rfc writes its notice (it holds material from before + November 10, 2008). The copies are unmodified and this table names where each came from. ## Updating a text 1. Take the new file from the same repository at a tag or a commit, never from a rendered page: `git clone --depth 1 https://github.com/OAI/OpenAPI-Specification` and copy - `versions/<version>.md`; for JSON Schema, check out the release's tag and copy the XML. + `versions/<version>.md`; for JSON Schema, check out the release's tag and copy the XML; for an + RFC, `https://www.rfc-editor.org/rfc/rfc<N>.xml` where it exists, else `rfc<N>.txt`. 2. Replace the file here (a new version is a new file, and a new entry in `SOURCES` in `../ledger/src/sources.rs`), and write its commit and `sha256sum` into the table above. 3. In `../ledger/`: `cargo run --release --bin extract`. It prints how many ids were added and diff --git a/conformance/specs/openapi/2.0.md b/conformance/specs/openapi/2.0.md new file mode 100644 index 0000000..bc4a36d --- /dev/null +++ b/conformance/specs/openapi/2.0.md @@ -0,0 +1,2298 @@ +# OpenAPI Specification +## (fka Swagger RESTful API Documentation Specification) + +#### Version 2.0 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](http://www.ietf.org/rfc/rfc2119.txt). + +The Swagger specification is licensed under [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). + +## Introductions + +Swagger™ is a project used to describe and document RESTful APIs. + +The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages. Additional utilities can also take advantage of the resulting files, such as testing tools. + +## Revision History + +Version | Date | Notes +--- | --- | --- +2.0 | 2014-09-08 | Release of Swagger 2.0 +1.2 | 2014-03-14 | Initial release of the formal document. +1.1 | 2012-08-22 | Release of Swagger 1.1 +1.0 | 2011-08-10 | First release of the Swagger Specification + +## Definitions + +##### Path Templating +Path templating refers to the usage of curly braces ({}) to mark a section of a URL path as replaceable using path parameters. + +##### Mime Types +Mime type definitions are spread across several resources. The mime type definitions should be in compliance with [RFC 6838](http://tools.ietf.org/html/rfc6838). + +Some examples of possible mime type definitions: +``` + text/plain; charset=utf-8 + application/json + application/vnd.github+json + application/vnd.github.v3+json + application/vnd.github.v3.raw+json + application/vnd.github.v3.text+json + application/vnd.github.v3.html+json + application/vnd.github.v3.full+json + application/vnd.github.v3.diff + application/vnd.github.v3.patch +``` +##### HTTP Status Codes +The HTTP Status Codes are used to indicate the status of the executed operation. The available status codes are described by [RFC 7231](http://tools.ietf.org/html/rfc7231#section-6) and in the [IANA Status Code Registry](http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). + +## Specification + +### Format + +The files describing the RESTful API in accordance with the Swagger specification are represented as JSON objects and conform to the JSON standards. YAML, being a superset of JSON, can be used as well to +represent a Swagger specification file. + +For example, if a field is said to have an array value, the JSON array representation will be used: + +```js +{ + "field" : [...] +} +``` + +While the API is described using JSON it does not impose a JSON input/output to the API itself. + +All field names in the specification are **case sensitive**. + +The schema exposes two types of fields. Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. Patterned fields can have multiple occurrences as long as each has a unique name. + +### File Structure + +The Swagger representation of the API is made of a single file. However, parts of the definitions can be split into separate files, at the discretion of the user. This is applicable for `$ref` fields in the specification as follows from the [JSON Schema](http://json-schema.org) definitions. + +By convention, the Swagger specification file is named `swagger.json`. + +### Data Types + +Primitive data types in the Swagger Specification are based on the types supported by the [JSON-Schema Draft 4](https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5). Models are described using the [Schema Object](#schema-object) which is a subset of JSON Schema Draft 4. + +An additional primitive data type `"file"` is used by the [Parameter Object](#parameter-object) and the [Response Object](#response-object) to set the parameter type or the response as being a file. + +<a name="dataTypeFormat"></a>Primitives have an optional modifier property `format`. Swagger uses several known formats to more finely define the data type being used. However, the `format` property is an open `string`-valued property, and can have any value to support documentation needs. Formats such as `"email"`, `"uuid"`, etc., can be used even though they are not defined by this specification. Types that are not accompanied by a `format` property follow their definition from the JSON Schema (except for `file` type which is defined above). The formats defined by the Swagger Specification are: + + +Common Name | [`type`](#dataTypeType) | [`format`](#dataTypeFormat) | Comments +----------- | ------ | -------- | -------- +integer | `integer` | `int32` | signed 32 bits +long | `integer` | `int64` | signed 64 bits +float | `number` | `float` | | +double | `number` | `double` | | +string | `string` | | | +byte | `string` | `byte` | base64 encoded characters +binary | `string` | `binary` | any sequence of octets +boolean | `boolean` | | | +date | `string` | `date` | As defined by `full-date` - [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6) +dateTime | `string` | `date-time` | As defined by `date-time` - [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6) +password | `string` | `password` | Used to hint UIs the input needs to be obscured. + +### Schema + +#### Swagger Object + +This is the root document object for the API specification. It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) together into one document. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="swaggerSwagger"></a>swagger | `string` | **Required.** Specifies the Swagger Specification version being used. It can be used by the Swagger UI and other clients to interpret the API listing. The value MUST be `"2.0"`. +<a name="swaggerInfo"></a>info | [Info Object](#info-object) | **Required.** Provides metadata about the API. The metadata can be used by the clients if needed. +<a name="swaggerHost"></a>host | `string` | The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the `host` is not included, the host serving the documentation is to be used (including the port). The `host` does not support [path templating](#path-templating). +<a name="swaggerBasePath"></a>basePath | `string` | The base path on which the API is served, which is relative to the [`host`](#swaggerHost). If it is not included, the API is served directly under the `host`. The value MUST start with a leading slash (`/`). The `basePath` does not support [path templating](#path-templating). +<a name="swaggerSchemes"></a>schemes | [`string`] | The transfer protocol of the API. Values MUST be from the list: `"http"`, `"https"`, `"ws"`, `"wss"`. If the `schemes` is not included, the default scheme to be used is the one used to access the Swagger definition itself. +<a name="swaggerConsumes"></a>consumes | [`string`] | A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under [Mime Types](#mime-types). +<a name="swaggerProduces"></a>produces | [`string`] | A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under [Mime Types](#mime-types). +<a name="swaggerPaths"></a>paths | [Paths Object](#paths-object) | **Required.** The available paths and operations for the API. +<a name="swaggerDefinitions"></a>definitions | [Definitions Object](#definitions-object) | An object to hold data types produced and consumed by operations. +<a name="swaggerParameters"></a>parameters | [Parameters Definitions Object](#parameters-definitions-object) | An object to hold parameters that can be used across operations. This property *does not* define global parameters for all operations. +<a name="swaggerResponses"></a>responses | [Responses Definitions Object](#responses-definitions-object) | An object to hold responses that can be used across operations. This property *does not* define global responses for all operations. +<a name="swaggerSecurityDefinitions"></a>securityDefinitions | [Security Definitions Object](#security-definitions-object) | Security scheme definitions that can be used across the specification. +<a name="swaggerSecurity"></a>security | [[Security Requirement Object](#security-requirement-object)] | A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition. +<a name="swaggerTags"></a>tags | [[Tag Object](#tag-object)] | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operation-object) must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. +<a name="swaggerExternalDocs"></a>externalDocs | [External Documentation Object](#external-documentation-object) | Additional external documentation. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="swaggerExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +#### Info Object + +The object provides metadata about the API. The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="infoTitle"></a>title | `string` | **Required.** The title of the application. +<a name="infoDescription"></a>description | `string` | A short description of the application. [GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation. +<a name="infoTermsOfService"></a>termsOfService | `string` | The Terms of Service for the API. +<a name="infoContact"></a>contact | [Contact Object](#contact-object) | The contact information for the exposed API. +<a name="infoLicense"></a>license | [License Object](#license-object) | The license information for the exposed API. +<a name="infoVersion"></a>version | `string` | **Required** Provides the version of the application API (not to be confused with the specification version). + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="infoExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Info Object Example: + +```js +{ + "title": "Swagger Sample App", + "description": "This is a sample server Petstore server.", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "name": "API Support", + "url": "http://www.swagger.io/support", + "email": "support@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.1" +} +``` + +```yaml +title: Swagger Sample App +description: This is a sample server Petstore server. +termsOfService: http://swagger.io/terms/ +contact: + name: API Support + url: http://www.swagger.io/support + email: support@swagger.io +license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html +version: 1.0.1 +``` + +#### Contact Object + +Contact information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="contactName"></a>name | `string` | The identifying name of the contact person/organization. +<a name="contactUrl"></a>url | `string` | The URL pointing to the contact information. MUST be in the format of a URL. +<a name="contactEmail"></a>email | `string` | The email address of the contact person/organization. MUST be in the format of an email address. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="contactExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Contact Object Example: + +```js +{ + "name": "API Support", + "url": "http://www.swagger.io/support", + "email": "support@swagger.io" +} +``` + +```yaml +name: API Support +url: http://www.swagger.io/support +email: support@swagger.io +``` + +#### License Object + +License information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="licenseName"></a>name | `string` | **Required.** The license name used for the API. +<a name="licenseUrl"></a>url | `string` | A URL to the license used for the API. MUST be in the format of a URL. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="licenseExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### License Object Example: + +```js +{ + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" +} +``` + +```yaml +name: Apache 2.0 +url: http://www.apache.org/licenses/LICENSE-2.0.html +``` + +#### Paths Object + +Holds the relative paths to the individual endpoints. The path is appended to the [`basePath`](#swaggerBasePath) in order to construct the full URL. +The Paths may be empty, due to [ACL constraints](#security-filtering). + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="pathsPath"></a>/{path} | [Path Item Object](#path-item-object) | A relative path to an individual endpoint. The field name MUST begin with a slash. The path is appended to the [`basePath`](#swaggerBasePath) in order to construct the full URL. [Path templating](#path-templating) is allowed. +<a name="pathsExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Paths Object Example + +```js +{ + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "A list of pets.", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/pet" + } + } + } + } + } + } +} +``` + +```yaml +/pets: + get: + description: Returns all pets from the system that the user has access to + produces: + - application/json + responses: + '200': + description: A list of pets. + schema: + type: array + items: + $ref: '#/definitions/pet' +``` + +#### Path Item Object + +Describes the operations available on a single path. +A Path Item may be empty, due to [ACL constraints](#security-filtering). The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="pathItemRef"></a>$ref | `string` | Allows for an external definition of this path item. The referenced structure MUST be in the format of a [Path Item Object](#path-item-object). If there are conflicts between the referenced definition and this Path Item's definition, the behavior is *undefined*. +<a name="pathItemGet"></a>get | [Operation Object](#operation-object) | A definition of a GET operation on this path. +<a name="pathItemPut"></a>put | [Operation Object](#operation-object) | A definition of a PUT operation on this path. +<a name="pathItemPost"></a>post | [Operation Object](#operation-object) | A definition of a POST operation on this path. +<a name="pathItemDelete"></a>delete | [Operation Object](#operation-object) | A definition of a DELETE operation on this path. +<a name="pathItemOptions"></a>options | [Operation Object](#operation-object) | A definition of a OPTIONS operation on this path. +<a name="pathItemHead"></a>head | [Operation Object](#operation-object) | A definition of a HEAD operation on this path. +<a name="pathItemPatch"></a>patch | [Operation Object](#operation-object) | A definition of a PATCH operation on this path. +<a name="pathItemParameters"></a>parameters | [[Parameter Object](#parameter-object) \| [Reference Object](#reference-object)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#reference-object) to link to parameters that are defined at the [Swagger Object's parameters](#swaggerParameters). There can be one "body" parameter at most. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="pathItemExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Path Item Object Example + +```js +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "produces": [ + "application/json", + "text/html" + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "default": { + "description": "error payload", + "schema": { + "$ref": "#/definitions/ErrorModel" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + produces: + - application/json + - text/html + responses: + '200': + description: pet response + schema: + type: array + items: + $ref: '#/definitions/Pet' + default: + description: error payload + schema: + $ref: '#/definitions/ErrorModel' +parameters: +- name: id + in: path + description: ID of pet to use + required: true + type: array + items: + type: string + collectionFormat: csv +``` + +#### Operation Object + +Describes a single API operation on a path. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="operationTags"></a>tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. +<a name="operationSummary"></a>summary | `string` | A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters. +<a name="operationDescription"></a>description | `string` | A verbose explanation of the operation behavior. [GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation. +<a name="operationExternalDocs"></a>externalDocs | [External Documentation Object](#external-documentation-object) | Additional external documentation for this operation. +<a name="operationId"></a>operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions. +<a name="operationConsumes"></a>consumes | [`string`] | A list of MIME types the operation can consume. This overrides the [`consumes`](#swaggerConsumes) definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under [Mime Types](#mime-types). +<a name="operationProduces"></a>produces | [`string`] | A list of MIME types the operation can produce. This overrides the [`produces`](#swaggerProduces) definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under [Mime Types](#mime-types). +<a name="operationParameters"></a>parameters | [[Parameter Object](#parameter-object) \| [Reference Object](#reference-object)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#reference-object) to link to parameters that are defined at the [Swagger Object's parameters](#swaggerParameters). There can be one "body" parameter at most. +<a name="operationResponses"></a>responses | [Responses Object](#responses-object) | **Required.** The list of possible responses as they are returned from executing this operation. +<a name="operationSchemes"></a>schemes | [`string`] | The transfer protocol for the operation. Values MUST be from the list: `"http"`, `"https"`, `"ws"`, `"wss"`. The value overrides the Swagger Object [`schemes`](#swaggerSchemes) definition. +<a name="operationDeprecated"></a>deprecated | `boolean` | Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is `false`. +<a name="operationSecurity"></a>security | [[Security Requirement Object](#security-requirement-object)] | A declaration of which security schemes are applied for this operation. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). This definition overrides any declared top-level [`security`](#swaggerSecurity). To remove a top-level security declaration, an empty array can be used. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="operationExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Operation Object Example + +```js +{ + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "string" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "Pet updated." + }, + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +tags: +- pet +summary: Updates a pet in the store with form data +description: "" +operationId: updatePetWithForm +consumes: +- application/x-www-form-urlencoded +produces: +- application/json +- application/xml +parameters: +- name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: string +- name: name + in: formData + description: Updated name of the pet + required: false + type: string +- name: status + in: formData + description: Updated status of the pet + required: false + type: string +responses: + '200': + description: Pet updated. + '405': + description: Invalid input +security: +- petstore_auth: + - write:pets + - read:pets +``` + + +#### External Documentation Object + +Allows referencing an external resource for extended documentation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +<a name="externalDocDescription"></a>description | `string` | A short description of the target documentation. [GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation. +<a name="externalDocUrl"></a>url | `string` | **Required.** The URL for the target documentation. Value MUST be in the format of a URL. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="externalDocExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### External Documentation Object Example + +```js +{ + "description": "Find more info here", + "url": "https://swagger.io" +} +``` + +```yaml +description: Find more info here +url: https://swagger.io +``` + +#### Parameter Object + +Describes a single operation parameter. + +A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + +There are five possible parameter types. +* Path - Used together with [Path Templating](#path-templating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +* Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +* Header - Custom headers that are expected as part of the request. +* Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be *one* body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation. +* Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded`, `multipart/form-data` or both are used as the content type of the request (in Swagger's definition, the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4): + * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred. + * `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="parameterName"></a>name | `string` | **Required.** The name of the parameter. Parameter names are *case sensitive*. <ul><li>If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to the associated path segment from the [path](#pathsPath) field in the [Paths Object](#paths-object). See [Path Templating](#path-templating) for further information.<li>For all other cases, the `name` corresponds to the parameter name used based on the [`in`](#parameterIn) property.</ul> +<a name="parameterIn"></a>in | `string` | **Required.** The location of the parameter. Possible values are "query", "header", "path", "formData" or "body". +<a name="parameterDescription"></a>description | `string` | A brief description of the parameter. This could contain examples of use. [GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation. +<a name="parameterRequired"></a>required | `boolean` | Determines whether this parameter is mandatory. If the parameter is [`in`](#parameterIn) "path", this property is **required** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. + +If [`in`](#parameterIn) is `"body"`: + +Field Name | Type | Description +---|:---:|--- +<a name="parameterSchema"></a>schema | [Schema Object](#schema-object) | **Required.** The schema defining the type used for the body parameter. + +If [`in`](#parameterIn) is any value other than `"body"`: + +Field Name | Type | Description +---|:---:|--- +<a name="parameterType"></a>type | `string` | **Required.** The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, `"array"` or `"file"`. If `type` is `"file"`, the [`consumes`](#operationConsumes) MUST be either `"multipart/form-data"`, `" application/x-www-form-urlencoded"` or both and the parameter MUST be [`in`](#parameterIn) `"formData"`. +<a name="parameterFormat"></a>format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](#dataTypeFormat) for further details. +<a name="parameterAllowEmptyValue"/>allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for either `query` or `formData` parameters and allows you to send a parameter with a name only or an empty value. Default value is `false`. +<a name="parameterItems"></a>items | [Items Object](#items-object) | **Required if [`type`](#parameterType) is "array".** Describes the type of items in the array. +<a name="parameterCollectionFormat"></a>collectionFormat | `string` | Determines the format of the array if type array is used. Possible values are: <ul><li>`csv` - comma separated values `foo,bar`. <li>`ssv` - space separated values `foo bar`. <li>`tsv` - tab separated values `foo\tbar`. <li>`pipes` - pipe separated values <code>foo|bar</code>. <li>`multi` - corresponds to multiple parameter instances instead of multiple values for a single instance `foo=bar&foo=baz`. This is valid only for parameters [`in`](#parameterIn) "query" or "formData". </ul> Default value is `csv`. +<a name="parameterDefault"></a>default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#parameterType) for this parameter. +<a name="parameterMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. +<a name="parameterExclusiveMaximum"></a>exclusiveMaximum | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. +<a name="parameterMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. +<a name="parameterExclusiveMinimum"></a>exclusiveMinimum | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. +<a name="parameterMaxLength"></a>maxLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. +<a name="parameterMinLength"></a>minLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. +<a name="parameterPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. +<a name="parameterMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. +<a name="parameterMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. +<a name="parameterUniqueItems"></a>uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. +<a name="parameterEnum"></a>enum | [*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. +<a name="parameterMultipleOf"></a>multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. + + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +<a name="parameterExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + + +##### Parameter Object Examples + +###### Body Parameters + +A body parameter with a referenced schema definition (normally for a model definition): +```js +{ + "name": "user", + "in": "body", + "description": "user to add to the system", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } +} +``` + +```yaml +name: user +in: body +description: user to add to the system +required: true +schema: + $ref: '#/definitions/User' +``` + +A body parameter that is an array of string values: +```js +{ + "name": "user", + "in": "body", + "description": "user to add to the system", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +name: user +in: body +description: user to add to the system +required: true +schema: + type: array + items: + type: string +``` + +###### Other Parameters + +A header parameter with an array of 64 bit integer numbers: + +```js +{ + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": true, + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "collectionFormat": "csv" +} +``` + +```yaml +name: token +in: header +description: token to be passed as a header +required: true +type: array +items: + type: integer + format: int64 +collectionFormat: csv +``` + +A path parameter of a string value: +```js +{ + "name": "username", + "in": "path", + "description": "username to fetch", + "required": true, + "type": "string" +} +``` + +```yaml +name: username +in: path +description: username to fetch +required: true +type: string +``` + +An optional query parameter of a string value, allowing multiple values by repeating the query parameter: +```js +{ + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" +} +``` + +```yaml +name: id +in: query +description: ID of the object to fetch +required: false +type: array +items: + type: string +collectionFormat: multi +``` + +A form data with file type for a file upload: +```js +{ + "name": "avatar", + "in": "formData", + "description": "The avatar of the user", + "required": true, + "type": "file" +} +``` + +```yaml +name: avatar +in: formData +description: The avatar of the user +required: true +type: file +``` + +#### Items Object + +A limited subset of JSON-Schema's items object. It is used by parameter definitions that are not located [`in`](#parameterIn) `"body"`. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="itemsType"></a>type | `string` | **Required.** The internal type of the array. The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, or `"array"`. Files and models are not allowed. +<a name="itemsFormat"></a>format | `string` | The extending format for the previously mentioned [`type`](#parameterType). See [Data Type Formats](#dataTypeFormat) for further details. +<a name="itemsItems"></a>items | [Items Object](#items-object) | **Required if [`type`](#itemsType) is "array".** Describes the type of items in the array. +<a name="itemsCollectionFormat"></a>collectionFormat | `string` | Determines the format of the array if type array is used. Possible values are: <ul><li>`csv` - comma separated values `foo,bar`. <li>`ssv` - space separated values `foo bar`. <li>`tsv` - tab separated values `foo\tbar`. <li>`pipes` - pipe separated values <code>foo|bar</code>. </ul> Default value is `csv`. +<a name="itemsDefault"></a>default | * | Declares the value of the item that the server will use if none is provided. (Note: "default" has no meaning for required items.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#itemsType) for the data type. +<a name="itemsMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. +<a name="itemsMaximum"></a>exclusiveMaximum | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. +<a name="itemsMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. +<a name="itemsExclusiveMinimum"></a>exclusiveMinimum | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. +<a name="itemsMaxLength"></a>maxLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. +<a name="itemsMinLength"></a>minLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. +<a name="itemsPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. +<a name="itemsMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. +<a name="itemsMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. +<a name="itemsUniqueItems"></a>uniqueItems | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. +<a name="itemsEnum"></a>enum | [*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. +<a name="itemsMultipleOf"></a>multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="itemsExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Items Object Examples + +Items must be of type string and have the minimum length of 2 characters: + +```js +{ + "type": "string", + "minLength": 2 +} +``` + +```yaml +type: string +minLength: 2 +``` + +An array of arrays, the internal array being of type integer, numbers must be between 0 and 63 (inclusive): + +```js +{ + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 63 + } +} +``` + +```yaml +type: array +items: + type: integer + minimum: 0 + maximum: 63 +``` + +#### Responses Object + +A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. It is not expected from the documentation to necessarily cover all possible HTTP response codes, since they may not be known in advance. However, it is expected from the documentation to cover a successful operation response and any known errors. + +The `default` can be used as the default response object for all HTTP codes that are not covered individually by the specification. + +The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="responsesDefault"></a>default | [Response Object](#response-object) \| [Reference Object](#reference-object) | The documentation of responses other than the ones declared for specific HTTP response codes. It can be used to cover undeclared responses. [Reference Object](#reference-object) can be used to link to a response that is defined at the [Swagger Object's responses](#swaggerResponses) section. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +<a name="responsesCode"></a>{[HTTP Status Code](#http-status-codes)} | [Response Object](#response-object) \| [Reference Object](#reference-object) | Any [HTTP status code](#http-status-codes) can be used as the property name (one property per HTTP status code). Describes the expected response for that HTTP status code. [Reference Object](#reference-object) can be used to link to a response that is defined at the [Swagger Object's responses](#swaggerResponses) section. +<a name="responsesExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + + +##### Responses Object Example + +A 200 response for successful operation and a default response for others (implying an error): + +```js +{ + "200": { + "description": "a pet to be returned", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/ErrorModel" + } + } +} +``` + +```yaml +'200': + description: a pet to be returned + schema: + $ref: '#/definitions/Pet' +default: + description: Unexpected error + schema: + $ref: '#/definitions/ErrorModel' +``` + +#### Response Object +Describes a single response from an API Operation. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="responseDescription"></a>description | `string` | **Required.** A short description of the response. [GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation. +<a name="responseSchema"></a>schema | [Schema Object](#schema-object) | A definition of the response structure. It can be a primitive, an array or an object. If this field does not exist, it means no content is returned as part of the response. As an extension to the [Schema Object](#schema-object), its root `type` value may also be `"file"`. This SHOULD be accompanied by a relevant `produces` mime-type. +<a name="responseHeaders"></a>headers | [Headers Object](#headers-object) | A list of headers that are sent with the response. +<a name="responseExamples"></a>examples | [Example Object](#example-object) | An example of the response message. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="responseExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Response Object Examples + +Response of an array of a complex type: + +```js +{ + "description": "A complex object array response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/VeryComplexType" + } + } +} +``` + +```yaml +description: A complex object array response +schema: + type: array + items: + $ref: '#/definitions/VeryComplexType' +``` + +Response with a string type: + +```js +{ + "description": "A simple string response", + "schema": { + "type": "string" + } +} +``` + +```yaml +description: A simple string response +schema: + type: string +``` + +Response with headers: + +```js +{ + "description": "A simple string response", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "type": "integer" + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "type": "integer" + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "type": "integer" + } + } +} +``` + +```yaml +description: A simple string response +schema: + type: string +headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + type: integer + X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + type: integer +``` + +Response with no return value: + +```js +{ + "description": "object created" +} +``` + +```yaml +description: object created +``` + +#### Headers Object +Lists the headers that can be sent as part of a response. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +<a name="headersName"></a>{name} | [Header Object](#header-object) | The name of the property corresponds to the name of the header. The value describes the type of the header. + +##### Headers Object Example + +Rate-limit headers: + +```js +{ + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "type": "integer" + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "type": "integer" + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "type": "integer" + } +} +``` + +```yaml +X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + type: integer +X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + type: integer +X-Rate-Limit-Reset: + description: The number of seconds left in the current period + type: integer +``` + +#### Example Object + +Allows sharing examples for operation responses. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +<a name="exampleMimeType"></a>{[mime type](#mime-types)} | Any | The name of the property MUST be one of the Operation `produces` values (either implicit or inherited). The value SHOULD be an example of what such a response would look like. + +##### Example Object Example + +Example response for application/json mimetype of a Pet data type: + +```js +{ + "application/json": { + "name": "Puma", + "type": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + } +} +``` + +```yaml +application/json: + name: Puma + type: Dog + color: Black + gender: Female + breed: Mixed +``` + +#### Header Object + +Field Name | Type | Description +---|:---:|--- +<a name="headerDescription"></a>description | `string` | A short description of the header. +<a name="headerType"></a>type | `string` | **Required.** The type of the object. The value MUST be one of `"string"`, `"number"`, `"integer"`, `"boolean"`, or `"array"`. +<a name="headerFormat"></a>format | `string` | The extending format for the previously mentioned [`type`](#stType). See [Data Type Formats](#dataTypeFormat) for further details. +<a name="headerItems"></a>items | [Items Object](#items-object) | **Required if [`type`](#stType) is "array".** Describes the type of items in the array. +<a name="headerCollectionFormat"></a>collectionFormat | `string` | Determines the format of the array if type array is used. Possible values are: <ul><li>`csv` - comma separated values `foo,bar`. <li>`ssv` - space separated values `foo bar`. <li>`tsv` - tab separated values `foo\tbar`. <li>`pipes` - pipe separated values <code>foo|bar</code>. </ul> Default value is `csv`. +<a name="headerDefault"></a>default | * | Declares the value of the header that the server will use if none is provided. (Note: "default" has no meaning for required headers.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined [`type`](#headerDefault) for the header. +<a name="headerMaximum"></a>maximum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. +<a name="headerMaximum"></a>exclusiveMaximum | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. +<a name="headerMinimum"></a>minimum | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. +<a name="headerExclusiveMinimum"></a>exclusiveMinimum | `boolean` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. +<a name="headerMaxLength"></a>maxLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. +<a name="headerMinLength"></a>minLength | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. +<a name="headerPattern"></a>pattern | `string` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. +<a name="headerMaxItems"></a>maxItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. +<a name="headerMinItems"></a>minItems | `integer` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. +<a name="headerUniqueItems"></a>uniqueItems | `boolean` | https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. +<a name="headerEnum"></a>enum | [*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. +<a name="headerMultipleOf"></a>multipleOf | `number` | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="headerExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Header Object Example + +A simple header with of an integer type: + +```js +{ + "description": "The number of allowed requests in the current period", + "type": "integer" +} +``` + +```yaml +description: The number of allowed requests in the current period +type: integer +``` + +#### Tag Object + +Allows adding meta data to a single tag that is used by the [Operation Object](#operation-object). It is not mandatory to have a Tag Object per tag used there. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="tagName"></a>name | `string` | **Required.** The name of the tag. +<a name="tagDescription"></a>description | `string` | A short description for the tag. [GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation. +<a name="tagExternalDocs"></a>externalDocs | [External Documentation Object](#external-documentation-object) | Additional external documentation for this tag. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +<a name="tagExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Tag Object Example + +```js +{ + "name": "pet", + "description": "Pets operations" +} +``` + +```yaml +name: pet +description: Pets operations +``` + +#### Reference Object + +A simple object to allow referencing other definitions in the specification. It can be used to reference parameters and responses that are defined at the top level for reuse. + +The Reference Object is a [JSON Reference](http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-02) that uses a [JSON Pointer](http://tools.ietf.org/html/rfc6901) as its value. For this specification, only [canonical dereferencing](https://tools.ietf.org/html/draft-zyp-json-schema-04#section-7.2.3) is supported. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="referenceRef"></a>$ref | `string` | **Required.** The reference string. + +##### Reference Object Example + +```js +{ + "$ref": "#/definitions/Pet" +} +``` + +```yaml +$ref: '#/definitions/Pet' +``` + +##### Relative Schema File Example +```js +{ + "$ref": "Pet.json" +} +``` + +```yaml +$ref: 'Pet.yaml' +``` + +##### Relative Files With Embedded Schema Example +```js +{ + "$ref": "definitions.json#/Pet" +} +``` + +```yaml +$ref: 'definitions.yaml#/Pet' +``` + +#### Schema Object + +The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) and uses a predefined subset of it. On top of this subset, there are extensions provided by this specification to allow for more complete documentation. + +Further information about the properties can be found in [JSON Schema Core](https://tools.ietf.org/html/draft-zyp-json-schema-04) and [JSON Schema Validation](https://tools.ietf.org/html/draft-fge-json-schema-validation-00). Unless stated otherwise, the property definitions follow the JSON Schema specification as referenced here. + +The following properties are taken directly from the JSON Schema definition and follow the same specifications: +- $ref - As a [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) +- format (See [Data Type Formats](#dataTypeFormat) for further details) +- title +- description ([GFM syntax](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) can be used for rich text representation) +- default (Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object) +- multipleOf +- maximum +- exclusiveMaximum +- minimum +- exclusiveMinimum +- maxLength +- minLength +- pattern +- maxItems +- minItems +- uniqueItems +- maxProperties +- minProperties +- required +- enum +- type + +The following properties are taken from the JSON Schema definition but their definitions were adjusted to the Swagger Specification. Their definition is the same as the one from JSON Schema, only where the original definition references the JSON Schema definition, the [Schema Object](#schema-object) definition is used instead. +- items +- allOf +- properties +- additionalProperties + +Other than the JSON Schema subset fields, the following fields may be used for further schema documentation. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="schemaDiscriminator"></a>discriminator | `string` | Adds support for polymorphism. The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the `required` property list. When used, the value MUST be the name of this schema or any schema that inherits it. +<a name="schemaReadOnly"></a>readOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request. Properties marked as `readOnly` being `true` SHOULD NOT be in the `required` list of the defined schema. Default value is `false`. +<a name="schemaXml"></a>xml | [XML Object](#xml-object) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds Additional metadata to describe the XML representation format of this property. +<a name="schemaExternalDocs"></a>externalDocs | [External Documentation Object](#external-documentation-object) | Additional external documentation for this schema. +<a name="schemaExample"></a>example | Any | A free-form property to include an example of an instance for this schema. + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="schemaExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +###### Composition and Inheritance (Polymorphism) + +Swagger allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. `allOf` takes in an array of object definitions that are validated *independently* but together compose a single object. + +While composition offers model extensibility, it does not imply a hierarchy between the models. To support polymorphism, Swagger adds the support of the `discriminator` field. When used, the `discriminator` will be the name of the property used to decide which schema definition is used to validate the structure of the model. As such, the `discriminator` field MUST be a required field. The value of the chosen property has to be the friendly name given to the model under the `definitions` property. As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. + +###### XML Modeling + +The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. The [XML Object](#xml-object) contains additional information about the available options. + +##### Schema Object Examples + +###### Primitive Sample + +Unlike previous versions of Swagger, Schema definitions can be used to describe primitive and arrays as well. + +```js +{ + "type": "string", + "format": "email" +} +``` + +```yaml +type: string +format: email +``` + +###### Simple Model + +```js +{ + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "address": { + "$ref": "#/definitions/Address" + }, + "age": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } +} +``` + +```yaml +type: object +required: +- name +properties: + name: + type: string + address: + $ref: '#/definitions/Address' + age: + type: integer + format: int32 + minimum: 0 +``` + +###### Model with Map/Dictionary Properties + +For a simple string to string mapping: + +```js +{ + "type": "object", + "additionalProperties": { + "type": "string" + } +} +``` + +```yaml +type: object +additionalProperties: + type: string +``` + +For a string to model mapping: + +```js +{ + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/ComplexModel" + } +} +``` + +```yaml +type: object +additionalProperties: + $ref: '#/definitions/ComplexModel' +``` + +###### Model with Example + +```js +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "example": { + "name": "Puma", + "id": 1 + } +} +``` + +```yaml +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +required: +- name +example: + name: Puma + id: 1 +``` + +###### Models with Composition + +```js +{ + "definitions": { + "ErrorModel": { + "type": "object", + "required": [ + "message", + "code" + ], + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": 100, + "maximum": 600 + } + } + }, + "ExtendedErrorModel": { + "allOf": [ + { + "$ref": "#/definitions/ErrorModel" + }, + { + "type": "object", + "required": [ + "rootCause" + ], + "properties": { + "rootCause": { + "type": "string" + } + } + } + ] + } + } +} +``` + +```yaml +definitions: + ErrorModel: + type: object + required: + - message + - code + properties: + message: + type: string + code: + type: integer + minimum: 100 + maximum: 600 + ExtendedErrorModel: + allOf: + - $ref: '#/definitions/ErrorModel' + - type: object + required: + - rootCause + properties: + rootCause: + type: string +``` + +###### Models with Polymorphism Support + +```js +{ + "definitions": { + "Pet": { + "type": "object", + "discriminator": "petType", + "properties": { + "name": { + "type": "string" + }, + "petType": { + "type": "string" + } + }, + "required": [ + "name", + "petType" + ] + }, + "Cat": { + "description": "A representation of a cat", + "allOf": [ + { + "$ref": "#/definitions/Pet" + }, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive" + ] + } + }, + "required": [ + "huntingSkill" + ] + } + ] + }, + "Dog": { + "description": "A representation of a dog", + "allOf": [ + { + "$ref": "#/definitions/Pet" + }, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0 + } + }, + "required": [ + "packSize" + ] + } + ] + } + } +} +``` + +```yaml +definitions: + Pet: + type: object + discriminator: petType + properties: + name: + type: string + petType: + type: string + required: + - name + - petType + Cat: + description: A representation of a cat + allOf: + - $ref: '#/definitions/Pet' + - type: object + properties: + huntingSkill: + type: string + description: The measured skill for hunting + default: lazy + enum: + - clueless + - lazy + - adventurous + - aggressive + required: + - huntingSkill + Dog: + description: A representation of a dog + allOf: + - $ref: '#/definitions/Pet' + - type: object + properties: + packSize: + type: integer + format: int32 + description: the size of the pack the dog is from + default: 0 + minimum: 0 + required: + - packSize +``` + +#### XML Object + +A metadata object that allows for more fine-tuned XML model definitions. + +When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property should be used to add that information. See examples for expected behavior. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +<a name="xmlName"></a>name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within the Items Object (`items`), it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. +<a name="xmlNamespace"></a>namespace | `string` | The URL of the namespace definition. Value SHOULD be in the form of a URL. +<a name="xmlPrefix"></a>prefix | `string` | The prefix to be used for the [name](#xmlName). +<a name="xmlAttribute"></a>attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. +<a name="xmlWrapped"></a>wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, `<books><book/><book/></books>`) or unwrapped (`<book/><book/>`). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="xmlExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### XML Object Examples + +The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schema-object) with a sample of the XML representation of it. + +###### No XML Element + +Basic string property: + +```js +{ + "animals": { + "type": "string" + } +} +``` + +```yaml +animals: + type: string +``` + +```xml +<animals>...</animals> +``` + +Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string +``` + +```xml +<animals>...</animals> +<animals>...</animals> +<animals>...</animals> +``` + +###### XML Name Replacement + +```js +{ + "animals": { + "type": "string", + "xml": { + "name": "animal" + } + } +} +``` + +```yaml +animals: + type: string + xml: + name: animal +``` + +```xml +<animal>...</animal> +``` + + +###### XML Attribute, Prefix and Namespace + +In this example, a full model definition is shown. + +```js +{ + "Person": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "xml": { + "attribute": true + } + }, + "name": { + "type": "string", + "xml": { + "namespace": "http://swagger.io/schema/sample", + "prefix": "sample" + } + } + } + } +} +``` + +```yaml +Person: + type: object + properties: + id: + type: integer + format: int32 + xml: + attribute: true + name: + type: string + xml: + namespace: http://swagger.io/schema/sample + prefix: sample +``` + +```xml +<Person id="123"> + <sample:name xmlns:sample="http://swagger.io/schema/sample">example</sample:name> +</Person> +``` + +###### XML Arrays + +Changing the element names: + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal +``` + +```xml +<animal>value</animal> +<animal>value</animal> +``` + +The external `name` property has no effect on the XML: + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens +``` + +```xml +<animal>value</animal> +<animal>value</animal> +``` + +Even when the array is wrapped, if no name is explicitly defined, the same name will be used both internally and externally: + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + wrapped: true +``` + +```xml +<animals> + <animals>value</animals> + <animals>value</animals> +</animals> +``` + +To overcome the above example, the following definition can be used: + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + wrapped: true +``` + +```xml +<animals> + <animal>value</animal> + <animal>value</animal> +</animals> +``` + +Affecting both internal and external names: + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens + wrapped: true +``` + +```xml +<aliens> + <animal>value</animal> + <animal>value</animal> +</aliens> +``` + +If we change the external element but not the internal ones: + +```js +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: aliens + wrapped: true +``` + +```xml +<aliens> + <aliens>value</aliens> + <aliens>value</aliens> +</aliens> +``` + +#### Definitions Object + +An object to hold data types that can be consumed and produced by operations. These data types can be primitives, arrays or models. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="definitionsName"></a>{name} | [Schema Object](#schema-object) | A single definition, mapping a "name" to the schema it defines. + +##### Definitions Object Example + +```js +{ + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } +} +``` + +```yaml +Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string +Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string +``` + +#### Parameters Definitions Object + +An object to hold parameters to be reused across operations. Parameter definitions can be referenced to the ones defined here. + +This does *not* define global operation parameters. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="pdName"></a>{name} | [Parameter Object](#parameter-object) | A single parameter definition, mapping a "name" to the parameter it defines. + +##### Parameters Definition Object Example + +```js +{ + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": true, + "type": "integer", + "format": "int32" + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": true, + "type": "integer", + "format": "int32" + } +} +``` + +```yaml +skipParam: + name: skip + in: query + description: number of items to skip + required: true + type: integer + format: int32 +limitParam: + name: limit + in: query + description: max records to return + required: true + type: integer + format: int32 +``` + + +#### Responses Definitions Object + +An object to hold responses to be reused across operations. Response definitions can be referenced to the ones defined here. + +This does *not* define global operation responses. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="rdName"></a>{name} | [Response Object](#response-object) | A single response definition, mapping a "name" to the response it defines. + +##### Responses Definitions Object Example + +```js +{ + "NotFound": { + "description": "Entity not found." + }, + "IllegalInput": { + "description": "Illegal input for operation." + }, + "GeneralError": { + "description": "General Error", + "schema": { + "$ref": "#/definitions/GeneralError" + } + } +} +``` + +```yaml +NotFound: + description: Entity not found. +IllegalInput: + description: Illegal input for operation. +GeneralError: + description: General Error + schema: + $ref: '#/definitions/GeneralError' +``` + +#### Security Definitions Object + +A declaration of the security schemes available to be used in the specification. This does not enforce the security schemes on the operations and only serves to provide the relevant details for each scheme. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +<a name="sdName"></a>{name} | [Security Scheme Object](#security-scheme-object) | A single security scheme definition, mapping a "name" to the scheme it defines. + +##### Security Definitions Object Example + +```js +{ + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } +} +``` + +```yaml +api_key: + type: apiKey + name: api_key + in: header +petstore_auth: + type: oauth2 + authorizationUrl: http://swagger.io/api/oauth/dialog + flow: implicit + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Security Scheme Object + +Allows the definition of a security scheme that can be used by the operations. Supported schemes are basic authentication, an API key (either as a header or as a query parameter) and OAuth2's common flows (implicit, password, application and access code). + +##### Fixed Fields +Field Name | Type | Validity | Description +---|:---:|---|--- +<a name="securitySchemeType"></a>type | `string` | Any | **Required.** The type of the security scheme. Valid values are `"basic"`, `"apiKey"` or `"oauth2"`. +<a name="securitySchemeDescription"></a>description | `string` | Any | A short description for security scheme. +<a name="securitySchemeName"></a>name | `string` | `apiKey` | **Required.** The name of the header or query parameter to be used. +<a name="securitySchemeIn"></a>in | `string` | `apiKey` | **Required** The location of the API key. Valid values are `"query"` or `"header"`. +<a name="securitySchemeFlow"></a>flow | `string` | `oauth2` | **Required.** The flow used by the OAuth2 security scheme. Valid values are `"implicit"`, `"password"`, `"application"` or `"accessCode"`. +<a name="securitySchemeAuthorizationUrl"></a>authorizationUrl | `string` | `oauth2` (`"implicit"`, `"accessCode"`) | **Required.** The authorization URL to be used for this flow. This SHOULD be in the form of a URL. +<a name="securitySchemeTokenUrl"></a>tokenUrl | `string` | `oauth2` (`"password"`, `"application"`, `"accessCode"`) | **Required.** The token URL to be used for this flow. This SHOULD be in the form of a URL. +<a name="securitySchemeScopes"></a>scopes | [Scopes Object](#scopes-object) | `oauth2` | **Required.** The available scopes for the OAuth2 security scheme. + +##### Patterned Fields + +Field Name | Type | Description +---|:---:|--- +<a name="securitySchemeExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Security Scheme Object Example + +###### Basic Authentication Sample + +```js +{ + "type": "basic" +} +``` + +```yaml +type: basic +``` + +###### API Key Sample + +```js +{ + "type": "apiKey", + "name": "api_key", + "in": "header" +} +``` + +```yaml +type: apiKey +name: api_key +in: header +``` + +###### Implicit OAuth2 Sample + +```js +{ + "type": "oauth2", + "authorizationUrl": "http://swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } +} +``` + +```yaml +type: oauth2 +authorizationUrl: http://swagger.io/api/oauth/dialog +flow: implicit +scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Scopes Object + +Lists the available scopes for an OAuth2 security scheme. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="scopesName"></a>{name} | `string` | Maps between a name of a scope to a short description of it (as the value of the property). + +##### Patterned Objects + +Field Pattern | Type | Description +---|:---:|--- +<a name="scopesExtensions"></a>^x- | Any | Allows extensions to the Swagger Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. See [Vendor Extensions](#specification-extensions) for further details. + +##### Scopes Object Example + +```js +{ + "write:pets": "modify pets in your account", + "read:pets": "read your pets" +} +``` + +```yaml +write:pets: modify pets in your account +read:pets: read your pets +``` + +#### Security Requirement Object + +Lists the required security schemes to execute this operation. The object can have multiple security schemes declared in it which are all required (that is, there is a logical AND between the schemes). + +The name used for each property MUST correspond to a security scheme declared in the [Security Definitions](#security-definitions-object). + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +<a name="securityRequirementsName"></a>{name} | [`string`] | Each name must correspond to a security scheme which is declared in the [Security Definitions](#securityDefinitions). If the security scheme is of type `"oauth2"`, then the value is a list of scope names required for the execution. For other security scheme types, the array MUST be empty. + +##### Security Requirement Object Examples + +###### Non-OAuth2 Security Requirement + +```js +{ + "api_key": [] +} +``` + +```yaml +api_key: [] +``` + +###### OAuth2 Security Requirement + +```js +{ + "petstore_auth": [ + "write:pets", + "read:pets" + ] +} +``` + +```yaml +petstore_auth: +- write:pets +- read:pets +``` + +### Specification Extensions + +While the Swagger Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. + +The extensions properties are always prefixed by `"x-"` and can have any valid JSON format value. + +The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). + +### Security Filtering + +Some objects in the Swagger specification may be declared and remain empty, or completely be removed, even though they are inherently the core of the API documentation. + +The reasoning behind it is to allow an additional layer of access control over the documentation itself. While not part of the specification itself, certain libraries may choose to allow access to parts of the documentation based on some form of authentication/authorization. + +Two examples for this: + +1. The [Paths Object](#paths-object) may be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the [Info Object](#info-object) which may contain additional information regarding authentication. +2. The [Path Item Object](#path-item-object) may be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different than hiding the path itself from the [Paths Object](#paths-object) so the user will not be aware of its existence. This allows the documentation provider a finer control over what the viewer can see. diff --git a/conformance/specs/rfc/rfc6749.txt b/conformance/specs/rfc/rfc6749.txt new file mode 100644 index 0000000..5a0046c --- /dev/null +++ b/conformance/specs/rfc/rfc6749.txt @@ -0,0 +1,4259 @@ + + + + + + +Internet Engineering Task Force (IETF) D. Hardt, Ed. +Request for Comments: 6749 Microsoft +Obsoletes: 5849 October 2012 +Category: Standards Track +ISSN: 2070-1721 + + + The OAuth 2.0 Authorization Framework + +Abstract + + The OAuth 2.0 authorization framework enables a third-party + application to obtain limited access to an HTTP service, either on + behalf of a resource owner by orchestrating an approval interaction + between the resource owner and the HTTP service, or by allowing the + third-party application to obtain access on its own behalf. This + specification replaces and obsoletes the OAuth 1.0 protocol described + in RFC 5849. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by the + Internet Engineering Steering Group (IESG). Further information on + Internet Standards is available in Section 2 of RFC 5741. + + Information about the current status of this document, any errata, + and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc6749. + +Copyright Notice + + Copyright (c) 2012 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + + + + +Hardt Standards Track [Page 1] + +RFC 6749 OAuth 2.0 October 2012 + + +Table of Contents + + 1. Introduction ....................................................4 + 1.1. Roles ......................................................6 + 1.2. Protocol Flow ..............................................7 + 1.3. Authorization Grant ........................................8 + 1.3.1. Authorization Code ..................................8 + 1.3.2. Implicit ............................................8 + 1.3.3. Resource Owner Password Credentials .................9 + 1.3.4. Client Credentials ..................................9 + 1.4. Access Token ..............................................10 + 1.5. Refresh Token .............................................10 + 1.6. TLS Version ...............................................12 + 1.7. HTTP Redirections .........................................12 + 1.8. Interoperability ..........................................12 + 1.9. Notational Conventions ....................................13 + 2. Client Registration ............................................13 + 2.1. Client Types ..............................................14 + 2.2. Client Identifier .........................................15 + 2.3. Client Authentication .....................................16 + 2.3.1. Client Password ....................................16 + 2.3.2. Other Authentication Methods .......................17 + 2.4. Unregistered Clients ......................................17 + 3. Protocol Endpoints .............................................18 + 3.1. Authorization Endpoint ....................................18 + 3.1.1. Response Type ......................................19 + 3.1.2. Redirection Endpoint ...............................19 + 3.2. Token Endpoint ............................................21 + 3.2.1. Client Authentication ..............................22 + 3.3. Access Token Scope ........................................23 + 4. Obtaining Authorization ........................................23 + 4.1. Authorization Code Grant ..................................24 + 4.1.1. Authorization Request ..............................25 + 4.1.2. Authorization Response .............................26 + 4.1.3. Access Token Request ...............................29 + 4.1.4. Access Token Response ..............................30 + 4.2. Implicit Grant ............................................31 + 4.2.1. Authorization Request ..............................33 + 4.2.2. Access Token Response ..............................35 + 4.3. Resource Owner Password Credentials Grant .................37 + 4.3.1. Authorization Request and Response .................39 + 4.3.2. Access Token Request ...............................39 + 4.3.3. Access Token Response ..............................40 + 4.4. Client Credentials Grant ..................................40 + 4.4.1. Authorization Request and Response .................41 + 4.4.2. Access Token Request ...............................41 + 4.4.3. Access Token Response ..............................42 + 4.5. Extension Grants ..........................................42 + + + +Hardt Standards Track [Page 2] + +RFC 6749 OAuth 2.0 October 2012 + + + 5. Issuing an Access Token ........................................43 + 5.1. Successful Response .......................................43 + 5.2. Error Response ............................................45 + 6. Refreshing an Access Token .....................................47 + 7. Accessing Protected Resources ..................................48 + 7.1. Access Token Types ........................................49 + 7.2. Error Response ............................................49 + 8. Extensibility ..................................................50 + 8.1. Defining Access Token Types ...............................50 + 8.2. Defining New Endpoint Parameters ..........................50 + 8.3. Defining New Authorization Grant Types ....................51 + 8.4. Defining New Authorization Endpoint Response Types ........51 + 8.5. Defining Additional Error Codes ...........................51 + 9. Native Applications ............................................52 + 10. Security Considerations .......................................53 + 10.1. Client Authentication ....................................53 + 10.2. Client Impersonation .....................................54 + 10.3. Access Tokens ............................................55 + 10.4. Refresh Tokens ...........................................55 + 10.5. Authorization Codes ......................................56 + 10.6. Authorization Code Redirection URI Manipulation ..........56 + 10.7. Resource Owner Password Credentials ......................57 + 10.8. Request Confidentiality ..................................58 + 10.9. Ensuring Endpoint Authenticity ...........................58 + 10.10. Credentials-Guessing Attacks ............................58 + 10.11. Phishing Attacks ........................................58 + 10.12. Cross-Site Request Forgery ..............................59 + 10.13. Clickjacking ............................................60 + 10.14. Code Injection and Input Validation .....................60 + 10.15. Open Redirectors ........................................60 + 10.16. Misuse of Access Token to Impersonate Resource + Owner in Implicit Flow ..................................61 + 11. IANA Considerations ...........................................62 + 11.1. OAuth Access Token Types Registry ........................62 + 11.1.1. Registration Template .............................62 + 11.2. OAuth Parameters Registry ................................63 + 11.2.1. Registration Template .............................63 + 11.2.2. Initial Registry Contents .........................64 + 11.3. OAuth Authorization Endpoint Response Types Registry .....66 + 11.3.1. Registration Template .............................66 + 11.3.2. Initial Registry Contents .........................67 + 11.4. OAuth Extensions Error Registry ..........................67 + 11.4.1. Registration Template .............................68 + 12. References ....................................................68 + 12.1. Normative References .....................................68 + 12.2. Informative References ...................................70 + + + + + +Hardt Standards Track [Page 3] + +RFC 6749 OAuth 2.0 October 2012 + + + Appendix A. Augmented Backus-Naur Form (ABNF) Syntax ..............71 + A.1. "client_id" Syntax ........................................71 + A.2. "client_secret" Syntax ....................................71 + A.3. "response_type" Syntax ....................................71 + A.4. "scope" Syntax ............................................72 + A.5. "state" Syntax ............................................72 + A.6. "redirect_uri" Syntax .....................................72 + A.7. "error" Syntax ............................................72 + A.8. "error_description" Syntax ................................72 + A.9. "error_uri" Syntax ........................................72 + A.10. "grant_type" Syntax .......................................73 + A.11. "code" Syntax .............................................73 + A.12. "access_token" Syntax .....................................73 + A.13. "token_type" Syntax .......................................73 + A.14. "expires_in" Syntax .......................................73 + A.15. "username" Syntax .........................................73 + A.16. "password" Syntax .........................................73 + A.17. "refresh_token" Syntax ....................................74 + A.18. Endpoint Parameter Syntax .................................74 + Appendix B. Use of application/x-www-form-urlencoded Media Type ...74 + Appendix C. Acknowledgements ......................................75 + +1. Introduction + + In the traditional client-server authentication model, the client + requests an access-restricted resource (protected resource) on the + server by authenticating with the server using the resource owner's + credentials. In order to provide third-party applications access to + restricted resources, the resource owner shares its credentials with + the third party. This creates several problems and limitations: + + o Third-party applications are required to store the resource + owner's credentials for future use, typically a password in + clear-text. + + o Servers are required to support password authentication, despite + the security weaknesses inherent in passwords. + + o Third-party applications gain overly broad access to the resource + owner's protected resources, leaving resource owners without any + ability to restrict duration or access to a limited subset of + resources. + + o Resource owners cannot revoke access to an individual third party + without revoking access to all third parties, and must do so by + changing the third party's password. + + + + + +Hardt Standards Track [Page 4] + +RFC 6749 OAuth 2.0 October 2012 + + + o Compromise of any third-party application results in compromise of + the end-user's password and all of the data protected by that + password. + + OAuth addresses these issues by introducing an authorization layer + and separating the role of the client from that of the resource + owner. In OAuth, the client requests access to resources controlled + by the resource owner and hosted by the resource server, and is + issued a different set of credentials than those of the resource + owner. + + Instead of using the resource owner's credentials to access protected + resources, the client obtains an access token -- a string denoting a + specific scope, lifetime, and other access attributes. Access tokens + are issued to third-party clients by an authorization server with the + approval of the resource owner. The client uses the access token to + access the protected resources hosted by the resource server. + + For example, an end-user (resource owner) can grant a printing + service (client) access to her protected photos stored at a photo- + sharing service (resource server), without sharing her username and + password with the printing service. Instead, she authenticates + directly with a server trusted by the photo-sharing service + (authorization server), which issues the printing service delegation- + specific credentials (access token). + + This specification is designed for use with HTTP ([RFC2616]). The + use of OAuth over any protocol other than HTTP is out of scope. + + The OAuth 1.0 protocol ([RFC5849]), published as an informational + document, was the result of a small ad hoc community effort. This + Standards Track specification builds on the OAuth 1.0 deployment + experience, as well as additional use cases and extensibility + requirements gathered from the wider IETF community. The OAuth 2.0 + protocol is not backward compatible with OAuth 1.0. The two versions + may co-exist on the network, and implementations may choose to + support both. However, it is the intention of this specification + that new implementations support OAuth 2.0 as specified in this + document and that OAuth 1.0 is used only to support existing + deployments. The OAuth 2.0 protocol shares very few implementation + details with the OAuth 1.0 protocol. Implementers familiar with + OAuth 1.0 should approach this document without any assumptions as to + its structure and details. + + + + + + + + +Hardt Standards Track [Page 5] + +RFC 6749 OAuth 2.0 October 2012 + + +1.1. Roles + + OAuth defines four roles: + + resource owner + An entity capable of granting access to a protected resource. + When the resource owner is a person, it is referred to as an + end-user. + + resource server + The server hosting the protected resources, capable of accepting + and responding to protected resource requests using access tokens. + + client + An application making protected resource requests on behalf of the + resource owner and with its authorization. The term "client" does + not imply any particular implementation characteristics (e.g., + whether the application executes on a server, a desktop, or other + devices). + + authorization server + The server issuing access tokens to the client after successfully + authenticating the resource owner and obtaining authorization. + + The interaction between the authorization server and resource server + is beyond the scope of this specification. The authorization server + may be the same server as the resource server or a separate entity. + A single authorization server may issue access tokens accepted by + multiple resource servers. + + + + + + + + + + + + + + + + + + + + + + +Hardt Standards Track [Page 6] + +RFC 6749 OAuth 2.0 October 2012 + + +1.2. Protocol Flow + + +--------+ +---------------+ + | |--(A)- Authorization Request ->| Resource | + | | | Owner | + | |<-(B)-- Authorization Grant ---| | + | | +---------------+ + | | + | | +---------------+ + | |--(C)-- Authorization Grant -->| Authorization | + | Client | | Server | + | |<-(D)----- Access Token -------| | + | | +---------------+ + | | + | | +---------------+ + | |--(E)----- Access Token ------>| Resource | + | | | Server | + | |<-(F)--- Protected Resource ---| | + +--------+ +---------------+ + + Figure 1: Abstract Protocol Flow + + The abstract OAuth 2.0 flow illustrated in Figure 1 describes the + interaction between the four roles and includes the following steps: + + (A) The client requests authorization from the resource owner. The + authorization request can be made directly to the resource owner + (as shown), or preferably indirectly via the authorization + server as an intermediary. + + (B) The client receives an authorization grant, which is a + credential representing the resource owner's authorization, + expressed using one of four grant types defined in this + specification or using an extension grant type. The + authorization grant type depends on the method used by the + client to request authorization and the types supported by the + authorization server. + + (C) The client requests an access token by authenticating with the + authorization server and presenting the authorization grant. + + (D) The authorization server authenticates the client and validates + the authorization grant, and if valid, issues an access token. + + + + + + + + +Hardt Standards Track [Page 7] + +RFC 6749 OAuth 2.0 October 2012 + + + (E) The client requests the protected resource from the resource + server and authenticates by presenting the access token. + + (F) The resource server validates the access token, and if valid, + serves the request. + + The preferred method for the client to obtain an authorization grant + from the resource owner (depicted in steps (A) and (B)) is to use the + authorization server as an intermediary, which is illustrated in + Figure 3 in Section 4.1. + +1.3. Authorization Grant + + An authorization grant is a credential representing the resource + owner's authorization (to access its protected resources) used by the + client to obtain an access token. This specification defines four + grant types -- authorization code, implicit, resource owner password + credentials, and client credentials -- as well as an extensibility + mechanism for defining additional types. + +1.3.1. Authorization Code + + The authorization code is obtained by using an authorization server + as an intermediary between the client and resource owner. Instead of + requesting authorization directly from the resource owner, the client + directs the resource owner to an authorization server (via its + user-agent as defined in [RFC2616]), which in turn directs the + resource owner back to the client with the authorization code. + + Before directing the resource owner back to the client with the + authorization code, the authorization server authenticates the + resource owner and obtains authorization. Because the resource owner + only authenticates with the authorization server, the resource + owner's credentials are never shared with the client. + + The authorization code provides a few important security benefits, + such as the ability to authenticate the client, as well as the + transmission of the access token directly to the client without + passing it through the resource owner's user-agent and potentially + exposing it to others, including the resource owner. + +1.3.2. Implicit + + The implicit grant is a simplified authorization code flow optimized + for clients implemented in a browser using a scripting language such + as JavaScript. In the implicit flow, instead of issuing the client + an authorization code, the client is issued an access token directly + + + + +Hardt Standards Track [Page 8] + +RFC 6749 OAuth 2.0 October 2012 + + + (as the result of the resource owner authorization). The grant type + is implicit, as no intermediate credentials (such as an authorization + code) are issued (and later used to obtain an access token). + + When issuing an access token during the implicit grant flow, the + authorization server does not authenticate the client. In some + cases, the client identity can be verified via the redirection URI + used to deliver the access token to the client. The access token may + be exposed to the resource owner or other applications with access to + the resource owner's user-agent. + + Implicit grants improve the responsiveness and efficiency of some + clients (such as a client implemented as an in-browser application), + since it reduces the number of round trips required to obtain an + access token. However, this convenience should be weighed against + the security implications of using implicit grants, such as those + described in Sections 10.3 and 10.16, especially when the + authorization code grant type is available. + +1.3.3. Resource Owner Password Credentials + + The resource owner password credentials (i.e., username and password) + can be used directly as an authorization grant to obtain an access + token. The credentials should only be used when there is a high + degree of trust between the resource owner and the client (e.g., the + client is part of the device operating system or a highly privileged + application), and when other authorization grant types are not + available (such as an authorization code). + + Even though this grant type requires direct client access to the + resource owner credentials, the resource owner credentials are used + for a single request and are exchanged for an access token. This + grant type can eliminate the need for the client to store the + resource owner credentials for future use, by exchanging the + credentials with a long-lived access token or refresh token. + +1.3.4. Client Credentials + + The client credentials (or other forms of client authentication) can + be used as an authorization grant when the authorization scope is + limited to the protected resources under the control of the client, + or to protected resources previously arranged with the authorization + server. Client credentials are used as an authorization grant + typically when the client is acting on its own behalf (the client is + also the resource owner) or is requesting access to protected + resources based on an authorization previously arranged with the + authorization server. + + + + +Hardt Standards Track [Page 9] + +RFC 6749 OAuth 2.0 October 2012 + + +1.4. Access Token + + Access tokens are credentials used to access protected resources. An + access token is a string representing an authorization issued to the + client. The string is usually opaque to the client. Tokens + represent specific scopes and durations of access, granted by the + resource owner, and enforced by the resource server and authorization + server. + + The token may denote an identifier used to retrieve the authorization + information or may self-contain the authorization information in a + verifiable manner (i.e., a token string consisting of some data and a + signature). Additional authentication credentials, which are beyond + the scope of this specification, may be required in order for the + client to use a token. + + The access token provides an abstraction layer, replacing different + authorization constructs (e.g., username and password) with a single + token understood by the resource server. This abstraction enables + issuing access tokens more restrictive than the authorization grant + used to obtain them, as well as removing the resource server's need + to understand a wide range of authentication methods. + + Access tokens can have different formats, structures, and methods of + utilization (e.g., cryptographic properties) based on the resource + server security requirements. Access token attributes and the + methods used to access protected resources are beyond the scope of + this specification and are defined by companion specifications such + as [RFC6750]. + +1.5. Refresh Token + + Refresh tokens are credentials used to obtain access tokens. Refresh + tokens are issued to the client by the authorization server and are + used to obtain a new access token when the current access token + becomes invalid or expires, or to obtain additional access tokens + with identical or narrower scope (access tokens may have a shorter + lifetime and fewer permissions than authorized by the resource + owner). Issuing a refresh token is optional at the discretion of the + authorization server. If the authorization server issues a refresh + token, it is included when issuing an access token (i.e., step (D) in + Figure 1). + + A refresh token is a string representing the authorization granted to + the client by the resource owner. The string is usually opaque to + the client. The token denotes an identifier used to retrieve the + + + + + +Hardt Standards Track [Page 10] + +RFC 6749 OAuth 2.0 October 2012 + + + authorization information. Unlike access tokens, refresh tokens are + intended for use only with authorization servers and are never sent + to resource servers. + + +--------+ +---------------+ + | |--(A)------- Authorization Grant --------->| | + | | | | + | |<-(B)----------- Access Token -------------| | + | | & Refresh Token | | + | | | | + | | +----------+ | | + | |--(C)---- Access Token ---->| | | | + | | | | | | + | |<-(D)- Protected Resource --| Resource | | Authorization | + | Client | | Server | | Server | + | |--(E)---- Access Token ---->| | | | + | | | | | | + | |<-(F)- Invalid Token Error -| | | | + | | +----------+ | | + | | | | + | |--(G)----------- Refresh Token ----------->| | + | | | | + | |<-(H)----------- Access Token -------------| | + +--------+ & Optional Refresh Token +---------------+ + + Figure 2: Refreshing an Expired Access Token + + The flow illustrated in Figure 2 includes the following steps: + + (A) The client requests an access token by authenticating with the + authorization server and presenting an authorization grant. + + (B) The authorization server authenticates the client and validates + the authorization grant, and if valid, issues an access token + and a refresh token. + + (C) The client makes a protected resource request to the resource + server by presenting the access token. + + (D) The resource server validates the access token, and if valid, + serves the request. + + (E) Steps (C) and (D) repeat until the access token expires. If the + client knows the access token expired, it skips to step (G); + otherwise, it makes another protected resource request. + + (F) Since the access token is invalid, the resource server returns + an invalid token error. + + + +Hardt Standards Track [Page 11] + +RFC 6749 OAuth 2.0 October 2012 + + + (G) The client requests a new access token by authenticating with + the authorization server and presenting the refresh token. The + client authentication requirements are based on the client type + and on the authorization server policies. + + (H) The authorization server authenticates the client and validates + the refresh token, and if valid, issues a new access token (and, + optionally, a new refresh token). + + Steps (C), (D), (E), and (F) are outside the scope of this + specification, as described in Section 7. + +1.6. TLS Version + + Whenever Transport Layer Security (TLS) is used by this + specification, the appropriate version (or versions) of TLS will vary + over time, based on the widespread deployment and known security + vulnerabilities. At the time of this writing, TLS version 1.2 + [RFC5246] is the most recent version, but has a very limited + deployment base and might not be readily available for + implementation. TLS version 1.0 [RFC2246] is the most widely + deployed version and will provide the broadest interoperability. + + Implementations MAY also support additional transport-layer security + mechanisms that meet their security requirements. + +1.7. HTTP Redirections + + This specification makes extensive use of HTTP redirections, in which + the client or the authorization server directs the resource owner's + user-agent to another destination. While the examples in this + specification show the use of the HTTP 302 status code, any other + method available via the user-agent to accomplish this redirection is + allowed and is considered to be an implementation detail. + +1.8. Interoperability + + OAuth 2.0 provides a rich authorization framework with well-defined + security properties. However, as a rich and highly extensible + framework with many optional components, on its own, this + specification is likely to produce a wide range of non-interoperable + implementations. + + In addition, this specification leaves a few required components + partially or fully undefined (e.g., client registration, + authorization server capabilities, endpoint discovery). Without + + + + + +Hardt Standards Track [Page 12] + +RFC 6749 OAuth 2.0 October 2012 + + + these components, clients must be manually and specifically + configured against a specific authorization server and resource + server in order to interoperate. + + This framework was designed with the clear expectation that future + work will define prescriptive profiles and extensions necessary to + achieve full web-scale interoperability. + +1.9. Notational Conventions + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + specification are to be interpreted as described in [RFC2119]. + + This specification uses the Augmented Backus-Naur Form (ABNF) + notation of [RFC5234]. Additionally, the rule URI-reference is + included from "Uniform Resource Identifier (URI): Generic Syntax" + [RFC3986]. + + Certain security-related terms are to be understood in the sense + defined in [RFC4949]. These terms include, but are not limited to, + "attack", "authentication", "authorization", "certificate", + "confidentiality", "credential", "encryption", "identity", "sign", + "signature", "trust", "validate", and "verify". + + Unless otherwise noted, all the protocol parameter names and values + are case sensitive. + +2. Client Registration + + Before initiating the protocol, the client registers with the + authorization server. The means through which the client registers + with the authorization server are beyond the scope of this + specification but typically involve end-user interaction with an HTML + registration form. + + Client registration does not require a direct interaction between the + client and the authorization server. When supported by the + authorization server, registration can rely on other means for + establishing trust and obtaining the required client properties + (e.g., redirection URI, client type). For example, registration can + be accomplished using a self-issued or third-party-issued assertion, + or by the authorization server performing client discovery using a + trusted channel. + + + + + + + +Hardt Standards Track [Page 13] + +RFC 6749 OAuth 2.0 October 2012 + + + When registering a client, the client developer SHALL: + + o specify the client type as described in Section 2.1, + + o provide its client redirection URIs as described in Section 3.1.2, + and + + o include any other information required by the authorization server + (e.g., application name, website, description, logo image, the + acceptance of legal terms). + +2.1. Client Types + + OAuth defines two client types, based on their ability to + authenticate securely with the authorization server (i.e., ability to + maintain the confidentiality of their client credentials): + + confidential + Clients capable of maintaining the confidentiality of their + credentials (e.g., client implemented on a secure server with + restricted access to the client credentials), or capable of secure + client authentication using other means. + + public + Clients incapable of maintaining the confidentiality of their + credentials (e.g., clients executing on the device used by the + resource owner, such as an installed native application or a web + browser-based application), and incapable of secure client + authentication via any other means. + + The client type designation is based on the authorization server's + definition of secure authentication and its acceptable exposure + levels of client credentials. The authorization server SHOULD NOT + make assumptions about the client type. + + A client may be implemented as a distributed set of components, each + with a different client type and security context (e.g., a + distributed client with both a confidential server-based component + and a public browser-based component). If the authorization server + does not provide support for such clients or does not provide + guidance with regard to their registration, the client SHOULD + register each component as a separate client. + + + + + + + + + +Hardt Standards Track [Page 14] + +RFC 6749 OAuth 2.0 October 2012 + + + This specification has been designed around the following client + profiles: + + web application + A web application is a confidential client running on a web + server. Resource owners access the client via an HTML user + interface rendered in a user-agent on the device used by the + resource owner. The client credentials as well as any access + token issued to the client are stored on the web server and are + not exposed to or accessible by the resource owner. + + user-agent-based application + A user-agent-based application is a public client in which the + client code is downloaded from a web server and executes within a + user-agent (e.g., web browser) on the device used by the resource + owner. Protocol data and credentials are easily accessible (and + often visible) to the resource owner. Since such applications + reside within the user-agent, they can make seamless use of the + user-agent capabilities when requesting authorization. + + native application + A native application is a public client installed and executed on + the device used by the resource owner. Protocol data and + credentials are accessible to the resource owner. It is assumed + that any client authentication credentials included in the + application can be extracted. On the other hand, dynamically + issued credentials such as access tokens or refresh tokens can + receive an acceptable level of protection. At a minimum, these + credentials are protected from hostile servers with which the + application may interact. On some platforms, these credentials + might be protected from other applications residing on the same + device. + +2.2. Client Identifier + + The authorization server issues the registered client a client + identifier -- a unique string representing the registration + information provided by the client. The client identifier is not a + secret; it is exposed to the resource owner and MUST NOT be used + alone for client authentication. The client identifier is unique to + the authorization server. + + The client identifier string size is left undefined by this + specification. The client should avoid making assumptions about the + identifier size. The authorization server SHOULD document the size + of any identifier it issues. + + + + + +Hardt Standards Track [Page 15] + +RFC 6749 OAuth 2.0 October 2012 + + +2.3. Client Authentication + + If the client type is confidential, the client and authorization + server establish a client authentication method suitable for the + security requirements of the authorization server. The authorization + server MAY accept any form of client authentication meeting its + security requirements. + + Confidential clients are typically issued (or establish) a set of + client credentials used for authenticating with the authorization + server (e.g., password, public/private key pair). + + The authorization server MAY establish a client authentication method + with public clients. However, the authorization server MUST NOT rely + on public client authentication for the purpose of identifying the + client. + + The client MUST NOT use more than one authentication method in each + request. + +2.3.1. Client Password + + Clients in possession of a client password MAY use the HTTP Basic + authentication scheme as defined in [RFC2617] to authenticate with + the authorization server. The client identifier is encoded using the + "application/x-www-form-urlencoded" encoding algorithm per + Appendix B, and the encoded value is used as the username; the client + password is encoded using the same algorithm and used as the + password. The authorization server MUST support the HTTP Basic + authentication scheme for authenticating clients that were issued a + client password. + + For example (with extra line breaks for display purposes only): + + Authorization: Basic czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3 + + Alternatively, the authorization server MAY support including the + client credentials in the request-body using the following + parameters: + + client_id + REQUIRED. The client identifier issued to the client during + the registration process described by Section 2.2. + + client_secret + REQUIRED. The client secret. The client MAY omit the + parameter if the client secret is an empty string. + + + + +Hardt Standards Track [Page 16] + +RFC 6749 OAuth 2.0 October 2012 + + + Including the client credentials in the request-body using the two + parameters is NOT RECOMMENDED and SHOULD be limited to clients unable + to directly utilize the HTTP Basic authentication scheme (or other + password-based HTTP authentication schemes). The parameters can only + be transmitted in the request-body and MUST NOT be included in the + request URI. + + For example, a request to refresh an access token (Section 6) using + the body parameters (with extra line breaks for display purposes + only): + + POST /token HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + + grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA + &client_id=s6BhdRkqt3&client_secret=7Fjfp0ZBr1KtDRbnfVdmIw + + The authorization server MUST require the use of TLS as described in + Section 1.6 when sending requests using password authentication. + + Since this client authentication method involves a password, the + authorization server MUST protect any endpoint utilizing it against + brute force attacks. + +2.3.2. Other Authentication Methods + + The authorization server MAY support any suitable HTTP authentication + scheme matching its security requirements. When using other + authentication methods, the authorization server MUST define a + mapping between the client identifier (registration record) and + authentication scheme. + +2.4. Unregistered Clients + + This specification does not exclude the use of unregistered clients. + However, the use of such clients is beyond the scope of this + specification and requires additional security analysis and review of + its interoperability impact. + + + + + + + + + + + + +Hardt Standards Track [Page 17] + +RFC 6749 OAuth 2.0 October 2012 + + +3. Protocol Endpoints + + The authorization process utilizes two authorization server endpoints + (HTTP resources): + + o Authorization endpoint - used by the client to obtain + authorization from the resource owner via user-agent redirection. + + o Token endpoint - used by the client to exchange an authorization + grant for an access token, typically with client authentication. + + As well as one client endpoint: + + o Redirection endpoint - used by the authorization server to return + responses containing authorization credentials to the client via + the resource owner user-agent. + + Not every authorization grant type utilizes both endpoints. + Extension grant types MAY define additional endpoints as needed. + +3.1. Authorization Endpoint + + The authorization endpoint is used to interact with the resource + owner and obtain an authorization grant. The authorization server + MUST first verify the identity of the resource owner. The way in + which the authorization server authenticates the resource owner + (e.g., username and password login, session cookies) is beyond the + scope of this specification. + + The means through which the client obtains the location of the + authorization endpoint are beyond the scope of this specification, + but the location is typically provided in the service documentation. + + The endpoint URI MAY include an "application/x-www-form-urlencoded" + formatted (per Appendix B) query component ([RFC3986] Section 3.4), + which MUST be retained when adding additional query parameters. The + endpoint URI MUST NOT include a fragment component. + + Since requests to the authorization endpoint result in user + authentication and the transmission of clear-text credentials (in the + HTTP response), the authorization server MUST require the use of TLS + as described in Section 1.6 when sending requests to the + authorization endpoint. + + The authorization server MUST support the use of the HTTP "GET" + method [RFC2616] for the authorization endpoint and MAY support the + use of the "POST" method as well. + + + + +Hardt Standards Track [Page 18] + +RFC 6749 OAuth 2.0 October 2012 + + + Parameters sent without a value MUST be treated as if they were + omitted from the request. The authorization server MUST ignore + unrecognized request parameters. Request and response parameters + MUST NOT be included more than once. + +3.1.1. Response Type + + The authorization endpoint is used by the authorization code grant + type and implicit grant type flows. The client informs the + authorization server of the desired grant type using the following + parameter: + + response_type + REQUIRED. The value MUST be one of "code" for requesting an + authorization code as described by Section 4.1.1, "token" for + requesting an access token (implicit grant) as described by + Section 4.2.1, or a registered extension value as described by + Section 8.4. + + Extension response types MAY contain a space-delimited (%x20) list of + values, where the order of values does not matter (e.g., response + type "a b" is the same as "b a"). The meaning of such composite + response types is defined by their respective specifications. + + If an authorization request is missing the "response_type" parameter, + or if the response type is not understood, the authorization server + MUST return an error response as described in Section 4.1.2.1. + +3.1.2. Redirection Endpoint + + After completing its interaction with the resource owner, the + authorization server directs the resource owner's user-agent back to + the client. The authorization server redirects the user-agent to the + client's redirection endpoint previously established with the + authorization server during the client registration process or when + making the authorization request. + + The redirection endpoint URI MUST be an absolute URI as defined by + [RFC3986] Section 4.3. The endpoint URI MAY include an + "application/x-www-form-urlencoded" formatted (per Appendix B) query + component ([RFC3986] Section 3.4), which MUST be retained when adding + additional query parameters. The endpoint URI MUST NOT include a + fragment component. + + + + + + + + +Hardt Standards Track [Page 19] + +RFC 6749 OAuth 2.0 October 2012 + + +3.1.2.1. Endpoint Request Confidentiality + + The redirection endpoint SHOULD require the use of TLS as described + in Section 1.6 when the requested response type is "code" or "token", + or when the redirection request will result in the transmission of + sensitive credentials over an open network. This specification does + not mandate the use of TLS because at the time of this writing, + requiring clients to deploy TLS is a significant hurdle for many + client developers. If TLS is not available, the authorization server + SHOULD warn the resource owner about the insecure endpoint prior to + redirection (e.g., display a message during the authorization + request). + + Lack of transport-layer security can have a severe impact on the + security of the client and the protected resources it is authorized + to access. The use of transport-layer security is particularly + critical when the authorization process is used as a form of + delegated end-user authentication by the client (e.g., third-party + sign-in service). + +3.1.2.2. Registration Requirements + + The authorization server MUST require the following clients to + register their redirection endpoint: + + o Public clients. + + o Confidential clients utilizing the implicit grant type. + + The authorization server SHOULD require all clients to register their + redirection endpoint prior to utilizing the authorization endpoint. + + The authorization server SHOULD require the client to provide the + complete redirection URI (the client MAY use the "state" request + parameter to achieve per-request customization). If requiring the + registration of the complete redirection URI is not possible, the + authorization server SHOULD require the registration of the URI + scheme, authority, and path (allowing the client to dynamically vary + only the query component of the redirection URI when requesting + authorization). + + The authorization server MAY allow the client to register multiple + redirection endpoints. + + Lack of a redirection URI registration requirement can enable an + attacker to use the authorization endpoint as an open redirector as + described in Section 10.15. + + + + +Hardt Standards Track [Page 20] + +RFC 6749 OAuth 2.0 October 2012 + + +3.1.2.3. Dynamic Configuration + + If multiple redirection URIs have been registered, if only part of + the redirection URI has been registered, or if no redirection URI has + been registered, the client MUST include a redirection URI with the + authorization request using the "redirect_uri" request parameter. + + When a redirection URI is included in an authorization request, the + authorization server MUST compare and match the value received + against at least one of the registered redirection URIs (or URI + components) as defined in [RFC3986] Section 6, if any redirection + URIs were registered. If the client registration included the full + redirection URI, the authorization server MUST compare the two URIs + using simple string comparison as defined in [RFC3986] Section 6.2.1. + +3.1.2.4. Invalid Endpoint + + If an authorization request fails validation due to a missing, + invalid, or mismatching redirection URI, the authorization server + SHOULD inform the resource owner of the error and MUST NOT + automatically redirect the user-agent to the invalid redirection URI. + +3.1.2.5. Endpoint Content + + The redirection request to the client's endpoint typically results in + an HTML document response, processed by the user-agent. If the HTML + response is served directly as the result of the redirection request, + any script included in the HTML document will execute with full + access to the redirection URI and the credentials it contains. + + The client SHOULD NOT include any third-party scripts (e.g., third- + party analytics, social plug-ins, ad networks) in the redirection + endpoint response. Instead, it SHOULD extract the credentials from + the URI and redirect the user-agent again to another endpoint without + exposing the credentials (in the URI or elsewhere). If third-party + scripts are included, the client MUST ensure that its own scripts + (used to extract and remove the credentials from the URI) will + execute first. + +3.2. Token Endpoint + + The token endpoint is used by the client to obtain an access token by + presenting its authorization grant or refresh token. The token + endpoint is used with every authorization grant except for the + implicit grant type (since an access token is issued directly). + + + + + + +Hardt Standards Track [Page 21] + +RFC 6749 OAuth 2.0 October 2012 + + + The means through which the client obtains the location of the token + endpoint are beyond the scope of this specification, but the location + is typically provided in the service documentation. + + The endpoint URI MAY include an "application/x-www-form-urlencoded" + formatted (per Appendix B) query component ([RFC3986] Section 3.4), + which MUST be retained when adding additional query parameters. The + endpoint URI MUST NOT include a fragment component. + + Since requests to the token endpoint result in the transmission of + clear-text credentials (in the HTTP request and response), the + authorization server MUST require the use of TLS as described in + Section 1.6 when sending requests to the token endpoint. + + The client MUST use the HTTP "POST" method when making access token + requests. + + Parameters sent without a value MUST be treated as if they were + omitted from the request. The authorization server MUST ignore + unrecognized request parameters. Request and response parameters + MUST NOT be included more than once. + +3.2.1. Client Authentication + + Confidential clients or other clients issued client credentials MUST + authenticate with the authorization server as described in + Section 2.3 when making requests to the token endpoint. Client + authentication is used for: + + o Enforcing the binding of refresh tokens and authorization codes to + the client they were issued to. Client authentication is critical + when an authorization code is transmitted to the redirection + endpoint over an insecure channel or when the redirection URI has + not been registered in full. + + o Recovering from a compromised client by disabling the client or + changing its credentials, thus preventing an attacker from abusing + stolen refresh tokens. Changing a single set of client + credentials is significantly faster than revoking an entire set of + refresh tokens. + + o Implementing authentication management best practices, which + require periodic credential rotation. Rotation of an entire set + of refresh tokens can be challenging, while rotation of a single + set of client credentials is significantly easier. + + + + + + +Hardt Standards Track [Page 22] + +RFC 6749 OAuth 2.0 October 2012 + + + A client MAY use the "client_id" request parameter to identify itself + when sending requests to the token endpoint. In the + "authorization_code" "grant_type" request to the token endpoint, an + unauthenticated client MUST send its "client_id" to prevent itself + from inadvertently accepting a code intended for a client with a + different "client_id". This protects the client from substitution of + the authentication code. (It provides no additional security for the + protected resource.) + +3.3. Access Token Scope + + The authorization and token endpoints allow the client to specify the + scope of the access request using the "scope" request parameter. In + turn, the authorization server uses the "scope" response parameter to + inform the client of the scope of the access token issued. + + The value of the scope parameter is expressed as a list of space- + delimited, case-sensitive strings. The strings are defined by the + authorization server. If the value contains multiple space-delimited + strings, their order does not matter, and each string adds an + additional access range to the requested scope. + + scope = scope-token *( SP scope-token ) + scope-token = 1*( %x21 / %x23-5B / %x5D-7E ) + + The authorization server MAY fully or partially ignore the scope + requested by the client, based on the authorization server policy or + the resource owner's instructions. If the issued access token scope + is different from the one requested by the client, the authorization + server MUST include the "scope" response parameter to inform the + client of the actual scope granted. + + If the client omits the scope parameter when requesting + authorization, the authorization server MUST either process the + request using a pre-defined default value or fail the request + indicating an invalid scope. The authorization server SHOULD + document its scope requirements and default value (if defined). + +4. Obtaining Authorization + + To request an access token, the client obtains authorization from the + resource owner. The authorization is expressed in the form of an + authorization grant, which the client uses to request the access + token. OAuth defines four grant types: authorization code, implicit, + resource owner password credentials, and client credentials. It also + provides an extension mechanism for defining additional grant types. + + + + + +Hardt Standards Track [Page 23] + +RFC 6749 OAuth 2.0 October 2012 + + +4.1. Authorization Code Grant + + The authorization code grant type is used to obtain both access + tokens and refresh tokens and is optimized for confidential clients. + Since this is a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server. + + +----------+ + | Resource | + | Owner | + | | + +----------+ + ^ + | + (B) + +----|-----+ Client Identifier +---------------+ + | -+----(A)-- & Redirection URI ---->| | + | User- | | Authorization | + | Agent -+----(B)-- User authenticates --->| Server | + | | | | + | -+----(C)-- Authorization Code ---<| | + +-|----|---+ +---------------+ + | | ^ v + (A) (C) | | + | | | | + ^ v | | + +---------+ | | + | |>---(D)-- Authorization Code ---------' | + | Client | & Redirection URI | + | | | + | |<---(E)----- Access Token -------------------' + +---------+ (w/ Optional Refresh Token) + + Note: The lines illustrating steps (A), (B), and (C) are broken into + two parts as they pass through the user-agent. + + Figure 3: Authorization Code Flow + + + + + + + + + + + + +Hardt Standards Track [Page 24] + +RFC 6749 OAuth 2.0 October 2012 + + + The flow illustrated in Figure 3 includes the following steps: + + (A) The client initiates the flow by directing the resource owner's + user-agent to the authorization endpoint. The client includes + its client identifier, requested scope, local state, and a + redirection URI to which the authorization server will send the + user-agent back once access is granted (or denied). + + (B) The authorization server authenticates the resource owner (via + the user-agent) and establishes whether the resource owner + grants or denies the client's access request. + + (C) Assuming the resource owner grants access, the authorization + server redirects the user-agent back to the client using the + redirection URI provided earlier (in the request or during + client registration). The redirection URI includes an + authorization code and any local state provided by the client + earlier. + + (D) The client requests an access token from the authorization + server's token endpoint by including the authorization code + received in the previous step. When making the request, the + client authenticates with the authorization server. The client + includes the redirection URI used to obtain the authorization + code for verification. + + (E) The authorization server authenticates the client, validates the + authorization code, and ensures that the redirection URI + received matches the URI used to redirect the client in + step (C). If valid, the authorization server responds back with + an access token and, optionally, a refresh token. + +4.1.1. Authorization Request + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format, per Appendix B: + + response_type + REQUIRED. Value MUST be set to "code". + + client_id + REQUIRED. The client identifier as described in Section 2.2. + + redirect_uri + OPTIONAL. As described in Section 3.1.2. + + + + + +Hardt Standards Track [Page 25] + +RFC 6749 OAuth 2.0 October 2012 + + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + state + RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in Section 10.12. + + The client directs the resource owner to the constructed URI using an + HTTP redirection response, or by other means available to it via the + user-agent. + + For example, the client directs the user-agent to make the following + HTTP request using TLS (with extra line breaks for display purposes + only): + + GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 + Host: server.example.com + + The authorization server validates the request to ensure that all + required parameters are present and valid. If the request is valid, + the authorization server authenticates the resource owner and obtains + an authorization decision (by asking the resource owner or by + establishing approval via other means). + + When a decision is established, the authorization server directs the + user-agent to the provided client redirection URI using an HTTP + redirection response, or by other means available to it via the + user-agent. + +4.1.2. Authorization Response + + If the resource owner grants the access request, the authorization + server issues an authorization code and delivers it to the client by + adding the following parameters to the query component of the + redirection URI using the "application/x-www-form-urlencoded" format, + per Appendix B: + + code + REQUIRED. The authorization code generated by the + authorization server. The authorization code MUST expire + shortly after it is issued to mitigate the risk of leaks. A + maximum authorization code lifetime of 10 minutes is + RECOMMENDED. The client MUST NOT use the authorization code + + + +Hardt Standards Track [Page 26] + +RFC 6749 OAuth 2.0 October 2012 + + + more than once. If an authorization code is used more than + once, the authorization server MUST deny the request and SHOULD + revoke (when possible) all tokens previously issued based on + that authorization code. The authorization code is bound to + the client identifier and redirection URI. + + state + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response: + + HTTP/1.1 302 Found + Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA + &state=xyz + + The client MUST ignore unrecognized response parameters. The + authorization code string size is left undefined by this + specification. The client should avoid making assumptions about code + value sizes. The authorization server SHOULD document the size of + any value it issues. + +4.1.2.1. Error Response + + If the request fails due to a missing, invalid, or mismatching + redirection URI, or if the client identifier is missing or invalid, + the authorization server SHOULD inform the resource owner of the + error and MUST NOT automatically redirect the user-agent to the + invalid redirection URI. + + If the resource owner denies the access request or if the request + fails for reasons other than a missing or invalid redirection URI, + the authorization server informs the client by adding the following + parameters to the query component of the redirection URI using the + "application/x-www-form-urlencoded" format, per Appendix B: + + error + REQUIRED. A single ASCII [USASCII] error code from the + following: + + invalid_request + The request is missing a required parameter, includes an + invalid parameter value, includes a parameter more than + once, or is otherwise malformed. + + + + + +Hardt Standards Track [Page 27] + +RFC 6749 OAuth 2.0 October 2012 + + + unauthorized_client + The client is not authorized to request an authorization + code using this method. + + access_denied + The resource owner or authorization server denied the + request. + + unsupported_response_type + The authorization server does not support obtaining an + authorization code using this method. + + invalid_scope + The requested scope is invalid, unknown, or malformed. + + server_error + The authorization server encountered an unexpected + condition that prevented it from fulfilling the request. + (This error code is needed because a 500 Internal Server + Error HTTP status code cannot be returned to the client + via an HTTP redirect.) + + temporarily_unavailable + The authorization server is currently unable to handle + the request due to a temporary overloading or maintenance + of the server. (This error code is needed because a 503 + Service Unavailable HTTP status code cannot be returned + to the client via an HTTP redirect.) + + Values for the "error" parameter MUST NOT include characters + outside the set %x20-21 / %x23-5B / %x5D-7E. + + error_description + OPTIONAL. Human-readable ASCII [USASCII] text providing + additional information, used to assist the client developer in + understanding the error that occurred. + Values for the "error_description" parameter MUST NOT include + characters outside the set %x20-21 / %x23-5B / %x5D-7E. + + error_uri + OPTIONAL. A URI identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error. + Values for the "error_uri" parameter MUST conform to the + URI-reference syntax and thus MUST NOT include characters + outside the set %x21 / %x23-5B / %x5D-7E. + + + + + +Hardt Standards Track [Page 28] + +RFC 6749 OAuth 2.0 October 2012 + + + state + REQUIRED if a "state" parameter was present in the client + authorization request. The exact value received from the + client. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response: + + HTTP/1.1 302 Found + Location: https://client.example.com/cb?error=access_denied&state=xyz + +4.1.3. Access Token Request + + The client makes a request to the token endpoint by sending the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "authorization_code". + + code + REQUIRED. The authorization code received from the + authorization server. + + redirect_uri + REQUIRED, if the "redirect_uri" parameter was included in the + authorization request as described in Section 4.1.1, and their + values MUST be identical. + + client_id + REQUIRED, if the client is not authenticating with the + authorization server as described in Section 3.2.1. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in Section 3.2.1. + + + + + + + + + + + + + +Hardt Standards Track [Page 29] + +RFC 6749 OAuth 2.0 October 2012 + + + For example, the client makes the following HTTP request using TLS + (with extra line breaks for display purposes only): + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb + + The authorization server MUST: + + o require client authentication for confidential clients or for any + client that was issued client credentials (or with other + authentication requirements), + + o authenticate the client if client authentication is included, + + o ensure that the authorization code was issued to the authenticated + confidential client, or if the client is public, ensure that the + code was issued to "client_id" in the request, + + o verify that the authorization code is valid, and + + o ensure that the "redirect_uri" parameter is present if the + "redirect_uri" parameter was included in the initial authorization + request as described in Section 4.1.1, and if included ensure that + their values are identical. + +4.1.4. Access Token Response + + If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in Section 5.1. If the request client + authentication failed or is invalid, the authorization server returns + an error response as described in Section 5.2. + + + + + + + + + + + + + + +Hardt Standards Track [Page 30] + +RFC 6749 OAuth 2.0 October 2012 + + + An example successful response: + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", + "example_parameter":"example_value" + } + +4.2. Implicit Grant + + The implicit grant type is used to obtain access tokens (it does not + support the issuance of refresh tokens) and is optimized for public + clients known to operate a particular redirection URI. These clients + are typically implemented in a browser using a scripting language + such as JavaScript. + + Since this is a redirection-based flow, the client must be capable of + interacting with the resource owner's user-agent (typically a web + browser) and capable of receiving incoming requests (via redirection) + from the authorization server. + + Unlike the authorization code grant type, in which the client makes + separate requests for authorization and for an access token, the + client receives the access token as the result of the authorization + request. + + The implicit grant type does not include client authentication, and + relies on the presence of the resource owner and the registration of + the redirection URI. Because the access token is encoded into the + redirection URI, it may be exposed to the resource owner and other + applications residing on the same device. + + + + + + + + + + + + + +Hardt Standards Track [Page 31] + +RFC 6749 OAuth 2.0 October 2012 + + + +----------+ + | Resource | + | Owner | + | | + +----------+ + ^ + | + (B) + +----|-----+ Client Identifier +---------------+ + | -+----(A)-- & Redirection URI --->| | + | User- | | Authorization | + | Agent -|----(B)-- User authenticates -->| Server | + | | | | + | |<---(C)--- Redirection URI ----<| | + | | with Access Token +---------------+ + | | in Fragment + | | +---------------+ + | |----(D)--- Redirection URI ---->| Web-Hosted | + | | without Fragment | Client | + | | | Resource | + | (F) |<---(E)------- Script ---------<| | + | | +---------------+ + +-|--------+ + | | + (A) (G) Access Token + | | + ^ v + +---------+ + | | + | Client | + | | + +---------+ + + Note: The lines illustrating steps (A) and (B) are broken into two + parts as they pass through the user-agent. + + Figure 4: Implicit Grant Flow + + + + + + + + + + + + + + +Hardt Standards Track [Page 32] + +RFC 6749 OAuth 2.0 October 2012 + + + The flow illustrated in Figure 4 includes the following steps: + + (A) The client initiates the flow by directing the resource owner's + user-agent to the authorization endpoint. The client includes + its client identifier, requested scope, local state, and a + redirection URI to which the authorization server will send the + user-agent back once access is granted (or denied). + + (B) The authorization server authenticates the resource owner (via + the user-agent) and establishes whether the resource owner + grants or denies the client's access request. + + (C) Assuming the resource owner grants access, the authorization + server redirects the user-agent back to the client using the + redirection URI provided earlier. The redirection URI includes + the access token in the URI fragment. + + (D) The user-agent follows the redirection instructions by making a + request to the web-hosted client resource (which does not + include the fragment per [RFC2616]). The user-agent retains the + fragment information locally. + + (E) The web-hosted client resource returns a web page (typically an + HTML document with an embedded script) capable of accessing the + full redirection URI including the fragment retained by the + user-agent, and extracting the access token (and other + parameters) contained in the fragment. + + (F) The user-agent executes the script provided by the web-hosted + client resource locally, which extracts the access token. + + (G) The user-agent passes the access token to the client. + + See Sections 1.3.2 and 9 for background on using the implicit grant. + See Sections 10.3 and 10.16 for important security considerations + when using the implicit grant. + +4.2.1. Authorization Request + + The client constructs the request URI by adding the following + parameters to the query component of the authorization endpoint URI + using the "application/x-www-form-urlencoded" format, per Appendix B: + + response_type + REQUIRED. Value MUST be set to "token". + + client_id + REQUIRED. The client identifier as described in Section 2.2. + + + +Hardt Standards Track [Page 33] + +RFC 6749 OAuth 2.0 October 2012 + + + redirect_uri + OPTIONAL. As described in Section 3.1.2. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + state + RECOMMENDED. An opaque value used by the client to maintain + state between the request and callback. The authorization + server includes this value when redirecting the user-agent back + to the client. The parameter SHOULD be used for preventing + cross-site request forgery as described in Section 10.12. + + The client directs the resource owner to the constructed URI using an + HTTP redirection response, or by other means available to it via the + user-agent. + + For example, the client directs the user-agent to make the following + HTTP request using TLS (with extra line breaks for display purposes + only): + + GET /authorize?response_type=token&client_id=s6BhdRkqt3&state=xyz + &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 + Host: server.example.com + + The authorization server validates the request to ensure that all + required parameters are present and valid. The authorization server + MUST verify that the redirection URI to which it will redirect the + access token matches a redirection URI registered by the client as + described in Section 3.1.2. + + If the request is valid, the authorization server authenticates the + resource owner and obtains an authorization decision (by asking the + resource owner or by establishing approval via other means). + + When a decision is established, the authorization server directs the + user-agent to the provided client redirection URI using an HTTP + redirection response, or by other means available to it via the + user-agent. + + + + + + + + + + + +Hardt Standards Track [Page 34] + +RFC 6749 OAuth 2.0 October 2012 + + +4.2.2. Access Token Response + + If the resource owner grants the access request, the authorization + server issues an access token and delivers it to the client by adding + the following parameters to the fragment component of the redirection + URI using the "application/x-www-form-urlencoded" format, per + Appendix B: + + access_token + REQUIRED. The access token issued by the authorization server. + + token_type + REQUIRED. The type of the token issued as described in + Section 7.1. Value is case insensitive. + + expires_in + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + scope + OPTIONAL, if identical to the scope requested by the client; + otherwise, REQUIRED. The scope of the access token as + described by Section 3.3. + + state + REQUIRED if the "state" parameter was present in the client + authorization request. The exact value received from the + client. + + The authorization server MUST NOT issue a refresh token. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response (with extra line breaks for + display purposes only): + + HTTP/1.1 302 Found + Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA + &state=xyz&token_type=example&expires_in=3600 + + Developers should note that some user-agents do not support the + inclusion of a fragment component in the HTTP "Location" response + header field. Such clients will require using other methods for + redirecting the client than a 3xx redirection response -- for + example, returning an HTML page that includes a 'continue' button + with an action linked to the redirection URI. + + + +Hardt Standards Track [Page 35] + +RFC 6749 OAuth 2.0 October 2012 + + + The client MUST ignore unrecognized response parameters. The access + token string size is left undefined by this specification. The + client should avoid making assumptions about value sizes. The + authorization server SHOULD document the size of any value it issues. + +4.2.2.1. Error Response + + If the request fails due to a missing, invalid, or mismatching + redirection URI, or if the client identifier is missing or invalid, + the authorization server SHOULD inform the resource owner of the + error and MUST NOT automatically redirect the user-agent to the + invalid redirection URI. + + If the resource owner denies the access request or if the request + fails for reasons other than a missing or invalid redirection URI, + the authorization server informs the client by adding the following + parameters to the fragment component of the redirection URI using the + "application/x-www-form-urlencoded" format, per Appendix B: + + error + REQUIRED. A single ASCII [USASCII] error code from the + following: + + invalid_request + The request is missing a required parameter, includes an + invalid parameter value, includes a parameter more than + once, or is otherwise malformed. + + unauthorized_client + The client is not authorized to request an access token + using this method. + + access_denied + The resource owner or authorization server denied the + request. + + unsupported_response_type + The authorization server does not support obtaining an + access token using this method. + + invalid_scope + The requested scope is invalid, unknown, or malformed. + + + + + + + + + +Hardt Standards Track [Page 36] + +RFC 6749 OAuth 2.0 October 2012 + + + server_error + The authorization server encountered an unexpected + condition that prevented it from fulfilling the request. + (This error code is needed because a 500 Internal Server + Error HTTP status code cannot be returned to the client + via an HTTP redirect.) + + temporarily_unavailable + The authorization server is currently unable to handle + the request due to a temporary overloading or maintenance + of the server. (This error code is needed because a 503 + Service Unavailable HTTP status code cannot be returned + to the client via an HTTP redirect.) + + Values for the "error" parameter MUST NOT include characters + outside the set %x20-21 / %x23-5B / %x5D-7E. + + error_description + OPTIONAL. Human-readable ASCII [USASCII] text providing + additional information, used to assist the client developer in + understanding the error that occurred. + Values for the "error_description" parameter MUST NOT include + characters outside the set %x20-21 / %x23-5B / %x5D-7E. + + error_uri + OPTIONAL. A URI identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error. + Values for the "error_uri" parameter MUST conform to the + URI-reference syntax and thus MUST NOT include characters + outside the set %x21 / %x23-5B / %x5D-7E. + + state + REQUIRED if a "state" parameter was present in the client + authorization request. The exact value received from the + client. + + For example, the authorization server redirects the user-agent by + sending the following HTTP response: + + HTTP/1.1 302 Found + Location: https://client.example.com/cb#error=access_denied&state=xyz + +4.3. Resource Owner Password Credentials Grant + + The resource owner password credentials grant type is suitable in + cases where the resource owner has a trust relationship with the + client, such as the device operating system or a highly privileged + + + +Hardt Standards Track [Page 37] + +RFC 6749 OAuth 2.0 October 2012 + + + application. The authorization server should take special care when + enabling this grant type and only allow it when other flows are not + viable. + + This grant type is suitable for clients capable of obtaining the + resource owner's credentials (username and password, typically using + an interactive form). It is also used to migrate existing clients + using direct authentication schemes such as HTTP Basic or Digest + authentication to OAuth by converting the stored credentials to an + access token. + + +----------+ + | Resource | + | Owner | + | | + +----------+ + v + | Resource Owner + (A) Password Credentials + | + v + +---------+ +---------------+ + | |>--(B)---- Resource Owner ------->| | + | | Password Credentials | Authorization | + | Client | | Server | + | |<--(C)---- Access Token ---------<| | + | | (w/ Optional Refresh Token) | | + +---------+ +---------------+ + + Figure 5: Resource Owner Password Credentials Flow + + The flow illustrated in Figure 5 includes the following steps: + + (A) The resource owner provides the client with its username and + password. + + (B) The client requests an access token from the authorization + server's token endpoint by including the credentials received + from the resource owner. When making the request, the client + authenticates with the authorization server. + + (C) The authorization server authenticates the client and validates + the resource owner credentials, and if valid, issues an access + token. + + + + + + + +Hardt Standards Track [Page 38] + +RFC 6749 OAuth 2.0 October 2012 + + +4.3.1. Authorization Request and Response + + The method through which the client obtains the resource owner + credentials is beyond the scope of this specification. The client + MUST discard the credentials once an access token has been obtained. + +4.3.2. Access Token Request + + The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "password". + + username + REQUIRED. The resource owner username. + + password + REQUIRED. The resource owner password. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + If the client type is confidential or the client was issued client + credentials (or assigned other authentication requirements), the + client MUST authenticate with the authorization server as described + in Section 3.2.1. + + For example, the client makes the following HTTP request using + transport-layer security (with extra line breaks for display purposes + only): + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=password&username=johndoe&password=A3ddj3w + + + + + + + + + + +Hardt Standards Track [Page 39] + +RFC 6749 OAuth 2.0 October 2012 + + + The authorization server MUST: + + o require client authentication for confidential clients or for any + client that was issued client credentials (or with other + authentication requirements), + + o authenticate the client if client authentication is included, and + + o validate the resource owner password credentials using its + existing password validation algorithm. + + Since this access token request utilizes the resource owner's + password, the authorization server MUST protect the endpoint against + brute force attacks (e.g., using rate-limitation or generating + alerts). + +4.3.3. Access Token Response + + If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in Section 5.1. If the request failed client + authentication or is invalid, the authorization server returns an + error response as described in Section 5.2. + + An example successful response: + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", + "example_parameter":"example_value" + } + +4.4. Client Credentials Grant + + The client can request an access token using only its client + credentials (or other supported means of authentication) when the + client is requesting access to the protected resources under its + control, or those of another resource owner that have been previously + arranged with the authorization server (the method of which is beyond + the scope of this specification). + + + + +Hardt Standards Track [Page 40] + +RFC 6749 OAuth 2.0 October 2012 + + + The client credentials grant type MUST only be used by confidential + clients. + + +---------+ +---------------+ + | | | | + | |>--(A)- Client Authentication --->| Authorization | + | Client | | Server | + | |<--(B)---- Access Token ---------<| | + | | | | + +---------+ +---------------+ + + Figure 6: Client Credentials Flow + + The flow illustrated in Figure 6 includes the following steps: + + (A) The client authenticates with the authorization server and + requests an access token from the token endpoint. + + (B) The authorization server authenticates the client, and if valid, + issues an access token. + +4.4.1. Authorization Request and Response + + Since the client authentication is used as the authorization grant, + no additional authorization request is needed. + +4.4.2. Access Token Request + + The client makes a request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "client_credentials". + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. + + The client MUST authenticate with the authorization server as + described in Section 3.2.1. + + + + + + + + + +Hardt Standards Track [Page 41] + +RFC 6749 OAuth 2.0 October 2012 + + + For example, the client makes the following HTTP request using + transport-layer security (with extra line breaks for display purposes + only): + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=client_credentials + + The authorization server MUST authenticate the client. + +4.4.3. Access Token Response + + If the access token request is valid and authorized, the + authorization server issues an access token as described in + Section 5.1. A refresh token SHOULD NOT be included. If the request + failed client authentication or is invalid, the authorization server + returns an error response as described in Section 5.2. + + An example successful response: + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "example_parameter":"example_value" + } + +4.5. Extension Grants + + The client uses an extension grant type by specifying the grant type + using an absolute URI (defined by the authorization server) as the + value of the "grant_type" parameter of the token endpoint, and by + adding any additional parameters necessary. + + + + + + + + + + +Hardt Standards Track [Page 42] + +RFC 6749 OAuth 2.0 October 2012 + + + For example, to request an access token using a Security Assertion + Markup Language (SAML) 2.0 assertion grant type as defined by + [OAuth-SAML2], the client could make the following HTTP request using + TLS (with extra line breaks for display purposes only): + + POST /token HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + + grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Asaml2- + bearer&assertion=PEFzc2VydGlvbiBJc3N1ZUluc3RhbnQ9IjIwMTEtMDU + [...omitted for brevity...]aG5TdGF0ZW1lbnQ-PC9Bc3NlcnRpb24- + + If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in Section 5.1. If the request failed client + authentication or is invalid, the authorization server returns an + error response as described in Section 5.2. + +5. Issuing an Access Token + + If the access token request is valid and authorized, the + authorization server issues an access token and optional refresh + token as described in Section 5.1. If the request failed client + authentication or is invalid, the authorization server returns an + error response as described in Section 5.2. + +5.1. Successful Response + + The authorization server issues an access token and optional refresh + token, and constructs the response by adding the following parameters + to the entity-body of the HTTP response with a 200 (OK) status code: + + access_token + REQUIRED. The access token issued by the authorization server. + + token_type + REQUIRED. The type of the token issued as described in + Section 7.1. Value is case insensitive. + + expires_in + RECOMMENDED. The lifetime in seconds of the access token. For + example, the value "3600" denotes that the access token will + expire in one hour from the time the response was generated. + If omitted, the authorization server SHOULD provide the + expiration time via other means or document the default value. + + + + + +Hardt Standards Track [Page 43] + +RFC 6749 OAuth 2.0 October 2012 + + + refresh_token + OPTIONAL. The refresh token, which can be used to obtain new + access tokens using the same authorization grant as described + in Section 6. + + scope + OPTIONAL, if identical to the scope requested by the client; + otherwise, REQUIRED. The scope of the access token as + described by Section 3.3. + + The parameters are included in the entity-body of the HTTP response + using the "application/json" media type as defined by [RFC4627]. The + parameters are serialized into a JavaScript Object Notation (JSON) + structure by adding each parameter at the highest structure level. + Parameter names and string values are included as JSON strings. + Numerical values are included as JSON numbers. The order of + parameters does not matter and can vary. + + The authorization server MUST include the HTTP "Cache-Control" + response header field [RFC2616] with a value of "no-store" in any + response containing tokens, credentials, or other sensitive + information, as well as the "Pragma" response header field [RFC2616] + with a value of "no-cache". + + For example: + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"2YotnFZFEjr1zCsicMWpAA", + "token_type":"example", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", + "example_parameter":"example_value" + } + + The client MUST ignore unrecognized value names in the response. The + sizes of tokens and other values received from the authorization + server are left undefined. The client should avoid making + assumptions about value sizes. The authorization server SHOULD + document the size of any value it issues. + + + + + + + +Hardt Standards Track [Page 44] + +RFC 6749 OAuth 2.0 October 2012 + + +5.2. Error Response + + The authorization server responds with an HTTP 400 (Bad Request) + status code (unless specified otherwise) and includes the following + parameters with the response: + + error + REQUIRED. A single ASCII [USASCII] error code from the + following: + + invalid_request + The request is missing a required parameter, includes an + unsupported parameter value (other than grant type), + repeats a parameter, includes multiple credentials, + utilizes more than one mechanism for authenticating the + client, or is otherwise malformed. + + invalid_client + Client authentication failed (e.g., unknown client, no + client authentication included, or unsupported + authentication method). The authorization server MAY + return an HTTP 401 (Unauthorized) status code to indicate + which HTTP authentication schemes are supported. If the + client attempted to authenticate via the "Authorization" + request header field, the authorization server MUST + respond with an HTTP 401 (Unauthorized) status code and + include the "WWW-Authenticate" response header field + matching the authentication scheme used by the client. + + invalid_grant + The provided authorization grant (e.g., authorization + code, resource owner credentials) or refresh token is + invalid, expired, revoked, does not match the redirection + URI used in the authorization request, or was issued to + another client. + + unauthorized_client + The authenticated client is not authorized to use this + authorization grant type. + + unsupported_grant_type + The authorization grant type is not supported by the + authorization server. + + + + + + + + +Hardt Standards Track [Page 45] + +RFC 6749 OAuth 2.0 October 2012 + + + invalid_scope + The requested scope is invalid, unknown, malformed, or + exceeds the scope granted by the resource owner. + + Values for the "error" parameter MUST NOT include characters + outside the set %x20-21 / %x23-5B / %x5D-7E. + + error_description + OPTIONAL. Human-readable ASCII [USASCII] text providing + additional information, used to assist the client developer in + understanding the error that occurred. + Values for the "error_description" parameter MUST NOT include + characters outside the set %x20-21 / %x23-5B / %x5D-7E. + + error_uri + OPTIONAL. A URI identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error. + Values for the "error_uri" parameter MUST conform to the + URI-reference syntax and thus MUST NOT include characters + outside the set %x21 / %x23-5B / %x5D-7E. + + The parameters are included in the entity-body of the HTTP response + using the "application/json" media type as defined by [RFC4627]. The + parameters are serialized into a JSON structure by adding each + parameter at the highest structure level. Parameter names and string + values are included as JSON strings. Numerical values are included + as JSON numbers. The order of parameters does not matter and can + vary. + + For example: + + HTTP/1.1 400 Bad Request + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "error":"invalid_request" + } + + + + + + + + + + + +Hardt Standards Track [Page 46] + +RFC 6749 OAuth 2.0 October 2012 + + +6. Refreshing an Access Token + + If the authorization server issued a refresh token to the client, the + client makes a refresh request to the token endpoint by adding the + following parameters using the "application/x-www-form-urlencoded" + format per Appendix B with a character encoding of UTF-8 in the HTTP + request entity-body: + + grant_type + REQUIRED. Value MUST be set to "refresh_token". + + refresh_token + REQUIRED. The refresh token issued to the client. + + scope + OPTIONAL. The scope of the access request as described by + Section 3.3. The requested scope MUST NOT include any scope + not originally granted by the resource owner, and if omitted is + treated as equal to the scope originally granted by the + resource owner. + + Because refresh tokens are typically long-lasting credentials used to + request additional access tokens, the refresh token is bound to the + client to which it was issued. If the client type is confidential or + the client was issued client credentials (or assigned other + authentication requirements), the client MUST authenticate with the + authorization server as described in Section 3.2.1. + + For example, the client makes the following HTTP request using + transport-layer security (with extra line breaks for display purposes + only): + + POST /token HTTP/1.1 + Host: server.example.com + Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + Content-Type: application/x-www-form-urlencoded + + grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA + + + + + + + + + + + + + +Hardt Standards Track [Page 47] + +RFC 6749 OAuth 2.0 October 2012 + + + The authorization server MUST: + + o require client authentication for confidential clients or for any + client that was issued client credentials (or with other + authentication requirements), + + o authenticate the client if client authentication is included and + ensure that the refresh token was issued to the authenticated + client, and + + o validate the refresh token. + + If valid and authorized, the authorization server issues an access + token as described in Section 5.1. If the request failed + verification or is invalid, the authorization server returns an error + response as described in Section 5.2. + + The authorization server MAY issue a new refresh token, in which case + the client MUST discard the old refresh token and replace it with the + new refresh token. The authorization server MAY revoke the old + refresh token after issuing a new refresh token to the client. If a + new refresh token is issued, the refresh token scope MUST be + identical to that of the refresh token included by the client in the + request. + +7. Accessing Protected Resources + + The client accesses protected resources by presenting the access + token to the resource server. The resource server MUST validate the + access token and ensure that it has not expired and that its scope + covers the requested resource. The methods used by the resource + server to validate the access token (as well as any error responses) + are beyond the scope of this specification but generally involve an + interaction or coordination between the resource server and the + authorization server. + + The method in which the client utilizes the access token to + authenticate with the resource server depends on the type of access + token issued by the authorization server. Typically, it involves + using the HTTP "Authorization" request header field [RFC2617] with an + authentication scheme defined by the specification of the access + token type used, such as [RFC6750]. + + + + + + + + + +Hardt Standards Track [Page 48] + +RFC 6749 OAuth 2.0 October 2012 + + +7.1. Access Token Types + + The access token type provides the client with the information + required to successfully utilize the access token to make a protected + resource request (along with type-specific attributes). The client + MUST NOT use an access token if it does not understand the token + type. + + For example, the "bearer" token type defined in [RFC6750] is utilized + by simply including the access token string in the request: + + GET /resource/1 HTTP/1.1 + Host: example.com + Authorization: Bearer mF_9.B5f-4.1JqM + + while the "mac" token type defined in [OAuth-HTTP-MAC] is utilized by + issuing a Message Authentication Code (MAC) key together with the + access token that is used to sign certain components of the HTTP + requests: + + GET /resource/1 HTTP/1.1 + Host: example.com + Authorization: MAC id="h480djs93hd8", + nonce="274312:dj83hs9s", + mac="kDZvddkndxvhGRXZhvuDjEWhGeE=" + + The above examples are provided for illustration purposes only. + Developers are advised to consult the [RFC6750] and [OAuth-HTTP-MAC] + specifications before use. + + Each access token type definition specifies the additional attributes + (if any) sent to the client together with the "access_token" response + parameter. It also defines the HTTP authentication method used to + include the access token when making a protected resource request. + +7.2. Error Response + + If a resource access request fails, the resource server SHOULD inform + the client of the error. While the specifics of such error responses + are beyond the scope of this specification, this document establishes + a common registry in Section 11.4 for error values to be shared among + OAuth token authentication schemes. + + New authentication schemes designed primarily for OAuth token + authentication SHOULD define a mechanism for providing an error + status code to the client, in which the error values allowed are + registered in the error registry established by this specification. + + + + +Hardt Standards Track [Page 49] + +RFC 6749 OAuth 2.0 October 2012 + + + Such schemes MAY limit the set of valid error codes to a subset of + the registered values. If the error code is returned using a named + parameter, the parameter name SHOULD be "error". + + Other schemes capable of being used for OAuth token authentication, + but not primarily designed for that purpose, MAY bind their error + values to the registry in the same manner. + + New authentication schemes MAY choose to also specify the use of the + "error_description" and "error_uri" parameters to return error + information in a manner parallel to their usage in this + specification. + +8. Extensibility + +8.1. Defining Access Token Types + + Access token types can be defined in one of two ways: registered in + the Access Token Types registry (following the procedures in + Section 11.1), or by using a unique absolute URI as its name. + + Types utilizing a URI name SHOULD be limited to vendor-specific + implementations that are not commonly applicable, and are specific to + the implementation details of the resource server where they are + used. + + All other types MUST be registered. Type names MUST conform to the + type-name ABNF. If the type definition includes a new HTTP + authentication scheme, the type name SHOULD be identical to the HTTP + authentication scheme name (as defined by [RFC2617]). The token type + "example" is reserved for use in examples. + + type-name = 1*name-char + name-char = "-" / "." / "_" / DIGIT / ALPHA + +8.2. Defining New Endpoint Parameters + + New request or response parameters for use with the authorization + endpoint or the token endpoint are defined and registered in the + OAuth Parameters registry following the procedure in Section 11.2. + + Parameter names MUST conform to the param-name ABNF, and parameter + values syntax MUST be well-defined (e.g., using ABNF, or a reference + to the syntax of an existing parameter). + + param-name = 1*name-char + name-char = "-" / "." / "_" / DIGIT / ALPHA + + + + +Hardt Standards Track [Page 50] + +RFC 6749 OAuth 2.0 October 2012 + + + Unregistered vendor-specific parameter extensions that are not + commonly applicable and that are specific to the implementation + details of the authorization server where they are used SHOULD + utilize a vendor-specific prefix that is not likely to conflict with + other registered values (e.g., begin with 'companyname_'). + +8.3. Defining New Authorization Grant Types + + New authorization grant types can be defined by assigning them a + unique absolute URI for use with the "grant_type" parameter. If the + extension grant type requires additional token endpoint parameters, + they MUST be registered in the OAuth Parameters registry as described + by Section 11.2. + +8.4. Defining New Authorization Endpoint Response Types + + New response types for use with the authorization endpoint are + defined and registered in the Authorization Endpoint Response Types + registry following the procedure in Section 11.3. Response type + names MUST conform to the response-type ABNF. + + response-type = response-name *( SP response-name ) + response-name = 1*response-char + response-char = "_" / DIGIT / ALPHA + + If a response type contains one or more space characters (%x20), it + is compared as a space-delimited list of values in which the order of + values does not matter. Only one order of values can be registered, + which covers all other arrangements of the same set of values. + + For example, the response type "token code" is left undefined by this + specification. However, an extension can define and register the + "token code" response type. Once registered, the same combination + cannot be registered as "code token", but both values can be used to + denote the same response type. + +8.5. Defining Additional Error Codes + + In cases where protocol extensions (i.e., access token types, + extension parameters, or extension grant types) require additional + error codes to be used with the authorization code grant error + response (Section 4.1.2.1), the implicit grant error response + (Section 4.2.2.1), the token error response (Section 5.2), or the + resource access error response (Section 7.2), such error codes MAY be + defined. + + + + + + +Hardt Standards Track [Page 51] + +RFC 6749 OAuth 2.0 October 2012 + + + Extension error codes MUST be registered (following the procedures in + Section 11.4) if the extension they are used in conjunction with is a + registered access token type, a registered endpoint parameter, or an + extension grant type. Error codes used with unregistered extensions + MAY be registered. + + Error codes MUST conform to the error ABNF and SHOULD be prefixed by + an identifying name when possible. For example, an error identifying + an invalid value set to the extension parameter "example" SHOULD be + named "example_invalid". + + error = 1*error-char + error-char = %x20-21 / %x23-5B / %x5D-7E + +9. Native Applications + + Native applications are clients installed and executed on the device + used by the resource owner (i.e., desktop application, native mobile + application). Native applications require special consideration + related to security, platform capabilities, and overall end-user + experience. + + The authorization endpoint requires interaction between the client + and the resource owner's user-agent. Native applications can invoke + an external user-agent or embed a user-agent within the application. + For example: + + o External user-agent - the native application can capture the + response from the authorization server using a redirection URI + with a scheme registered with the operating system to invoke the + client as the handler, manual copy-and-paste of the credentials, + running a local web server, installing a user-agent extension, or + by providing a redirection URI identifying a server-hosted + resource under the client's control, which in turn makes the + response available to the native application. + + o Embedded user-agent - the native application obtains the response + by directly communicating with the embedded user-agent by + monitoring state changes emitted during the resource load, or + accessing the user-agent's cookies storage. + + When choosing between an external or embedded user-agent, developers + should consider the following: + + o An external user-agent may improve completion rate, as the + resource owner may already have an active session with the + authorization server, removing the need to re-authenticate. It + provides a familiar end-user experience and functionality. The + + + +Hardt Standards Track [Page 52] + +RFC 6749 OAuth 2.0 October 2012 + + + resource owner may also rely on user-agent features or extensions + to assist with authentication (e.g., password manager, 2-factor + device reader). + + o An embedded user-agent may offer improved usability, as it removes + the need to switch context and open new windows. + + o An embedded user-agent poses a security challenge because resource + owners are authenticating in an unidentified window without access + to the visual protections found in most external user-agents. An + embedded user-agent educates end-users to trust unidentified + requests for authentication (making phishing attacks easier to + execute). + + When choosing between the implicit grant type and the authorization + code grant type, the following should be considered: + + o Native applications that use the authorization code grant type + SHOULD do so without using client credentials, due to the native + application's inability to keep client credentials confidential. + + o When using the implicit grant type flow, a refresh token is not + returned, which requires repeating the authorization process once + the access token expires. + +10. Security Considerations + + As a flexible and extensible framework, OAuth's security + considerations depend on many factors. The following sections + provide implementers with security guidelines focused on the three + client profiles described in Section 2.1: web application, + user-agent-based application, and native application. + + A comprehensive OAuth security model and analysis, as well as + background for the protocol design, is provided by + [OAuth-THREATMODEL]. + +10.1. Client Authentication + + The authorization server establishes client credentials with web + application clients for the purpose of client authentication. The + authorization server is encouraged to consider stronger client + authentication means than a client password. Web application clients + MUST ensure confidentiality of client passwords and other client + credentials. + + + + + + +Hardt Standards Track [Page 53] + +RFC 6749 OAuth 2.0 October 2012 + + + The authorization server MUST NOT issue client passwords or other + client credentials to native application or user-agent-based + application clients for the purpose of client authentication. The + authorization server MAY issue a client password or other credentials + for a specific installation of a native application client on a + specific device. + + When client authentication is not possible, the authorization server + SHOULD employ other means to validate the client's identity -- for + example, by requiring the registration of the client redirection URI + or enlisting the resource owner to confirm identity. A valid + redirection URI is not sufficient to verify the client's identity + when asking for resource owner authorization but can be used to + prevent delivering credentials to a counterfeit client after + obtaining resource owner authorization. + + The authorization server must consider the security implications of + interacting with unauthenticated clients and take measures to limit + the potential exposure of other credentials (e.g., refresh tokens) + issued to such clients. + +10.2. Client Impersonation + + A malicious client can impersonate another client and obtain access + to protected resources if the impersonated client fails to, or is + unable to, keep its client credentials confidential. + + The authorization server MUST authenticate the client whenever + possible. If the authorization server cannot authenticate the client + due to the client's nature, the authorization server MUST require the + registration of any redirection URI used for receiving authorization + responses and SHOULD utilize other means to protect resource owners + from such potentially malicious clients. For example, the + authorization server can engage the resource owner to assist in + identifying the client and its origin. + + The authorization server SHOULD enforce explicit resource owner + authentication and provide the resource owner with information about + the client and the requested authorization scope and lifetime. It is + up to the resource owner to review the information in the context of + the current client and to authorize or deny the request. + + The authorization server SHOULD NOT process repeated authorization + requests automatically (without active resource owner interaction) + without authenticating the client or relying on other measures to + ensure that the repeated request comes from the original client and + not an impersonator. + + + + +Hardt Standards Track [Page 54] + +RFC 6749 OAuth 2.0 October 2012 + + +10.3. Access Tokens + + Access token credentials (as well as any confidential access token + attributes) MUST be kept confidential in transit and storage, and + only shared among the authorization server, the resource servers the + access token is valid for, and the client to whom the access token is + issued. Access token credentials MUST only be transmitted using TLS + as described in Section 1.6 with server authentication as defined by + [RFC2818]. + + When using the implicit grant type, the access token is transmitted + in the URI fragment, which can expose it to unauthorized parties. + + The authorization server MUST ensure that access tokens cannot be + generated, modified, or guessed to produce valid access tokens by + unauthorized parties. + + The client SHOULD request access tokens with the minimal scope + necessary. The authorization server SHOULD take the client identity + into account when choosing how to honor the requested scope and MAY + issue an access token with less rights than requested. + + This specification does not provide any methods for the resource + server to ensure that an access token presented to it by a given + client was issued to that client by the authorization server. + +10.4. Refresh Tokens + + Authorization servers MAY issue refresh tokens to web application + clients and native application clients. + + Refresh tokens MUST be kept confidential in transit and storage, and + shared only among the authorization server and the client to whom the + refresh tokens were issued. The authorization server MUST maintain + the binding between a refresh token and the client to whom it was + issued. Refresh tokens MUST only be transmitted using TLS as + described in Section 1.6 with server authentication as defined by + [RFC2818]. + + The authorization server MUST verify the binding between the refresh + token and client identity whenever the client identity can be + authenticated. When client authentication is not possible, the + authorization server SHOULD deploy other means to detect refresh + token abuse. + + For example, the authorization server could employ refresh token + rotation in which a new refresh token is issued with every access + token refresh response. The previous refresh token is invalidated + + + +Hardt Standards Track [Page 55] + +RFC 6749 OAuth 2.0 October 2012 + + + but retained by the authorization server. If a refresh token is + compromised and subsequently used by both the attacker and the + legitimate client, one of them will present an invalidated refresh + token, which will inform the authorization server of the breach. + + The authorization server MUST ensure that refresh tokens cannot be + generated, modified, or guessed to produce valid refresh tokens by + unauthorized parties. + +10.5. Authorization Codes + + The transmission of authorization codes SHOULD be made over a secure + channel, and the client SHOULD require the use of TLS with its + redirection URI if the URI identifies a network resource. Since + authorization codes are transmitted via user-agent redirections, they + could potentially be disclosed through user-agent history and HTTP + referrer headers. + + Authorization codes operate as plaintext bearer credentials, used to + verify that the resource owner who granted authorization at the + authorization server is the same resource owner returning to the + client to complete the process. Therefore, if the client relies on + the authorization code for its own resource owner authentication, the + client redirection endpoint MUST require the use of TLS. + + Authorization codes MUST be short lived and single-use. If the + authorization server observes multiple attempts to exchange an + authorization code for an access token, the authorization server + SHOULD attempt to revoke all access tokens already granted based on + the compromised authorization code. + + If the client can be authenticated, the authorization servers MUST + authenticate the client and ensure that the authorization code was + issued to the same client. + +10.6. Authorization Code Redirection URI Manipulation + + When requesting authorization using the authorization code grant + type, the client can specify a redirection URI via the "redirect_uri" + parameter. If an attacker can manipulate the value of the + redirection URI, it can cause the authorization server to redirect + the resource owner user-agent to a URI under the control of the + attacker with the authorization code. + + An attacker can create an account at a legitimate client and initiate + the authorization flow. When the attacker's user-agent is sent to + the authorization server to grant access, the attacker grabs the + authorization URI provided by the legitimate client and replaces the + + + +Hardt Standards Track [Page 56] + +RFC 6749 OAuth 2.0 October 2012 + + + client's redirection URI with a URI under the control of the + attacker. The attacker then tricks the victim into following the + manipulated link to authorize access to the legitimate client. + + Once at the authorization server, the victim is prompted with a + normal, valid request on behalf of a legitimate and trusted client, + and authorizes the request. The victim is then redirected to an + endpoint under the control of the attacker with the authorization + code. The attacker completes the authorization flow by sending the + authorization code to the client using the original redirection URI + provided by the client. The client exchanges the authorization code + with an access token and links it to the attacker's client account, + which can now gain access to the protected resources authorized by + the victim (via the client). + + In order to prevent such an attack, the authorization server MUST + ensure that the redirection URI used to obtain the authorization code + is identical to the redirection URI provided when exchanging the + authorization code for an access token. The authorization server + MUST require public clients and SHOULD require confidential clients + to register their redirection URIs. If a redirection URI is provided + in the request, the authorization server MUST validate it against the + registered value. + +10.7. Resource Owner Password Credentials + + The resource owner password credentials grant type is often used for + legacy or migration reasons. It reduces the overall risk of storing + usernames and passwords by the client but does not eliminate the need + to expose highly privileged credentials to the client. + + This grant type carries a higher risk than other grant types because + it maintains the password anti-pattern this protocol seeks to avoid. + The client could abuse the password, or the password could + unintentionally be disclosed to an attacker (e.g., via log files or + other records kept by the client). + + Additionally, because the resource owner does not have control over + the authorization process (the resource owner's involvement ends when + it hands over its credentials to the client), the client can obtain + access tokens with a broader scope than desired by the resource + owner. The authorization server should consider the scope and + lifetime of access tokens issued via this grant type. + + The authorization server and client SHOULD minimize use of this grant + type and utilize other grant types whenever possible. + + + + + +Hardt Standards Track [Page 57] + +RFC 6749 OAuth 2.0 October 2012 + + +10.8. Request Confidentiality + + Access tokens, refresh tokens, resource owner passwords, and client + credentials MUST NOT be transmitted in the clear. Authorization + codes SHOULD NOT be transmitted in the clear. + + The "state" and "scope" parameters SHOULD NOT include sensitive + client or resource owner information in plain text, as they can be + transmitted over insecure channels or stored insecurely. + +10.9. Ensuring Endpoint Authenticity + + In order to prevent man-in-the-middle attacks, the authorization + server MUST require the use of TLS with server authentication as + defined by [RFC2818] for any request sent to the authorization and + token endpoints. The client MUST validate the authorization server's + TLS certificate as defined by [RFC6125] and in accordance with its + requirements for server identity authentication. + +10.10. Credentials-Guessing Attacks + + The authorization server MUST prevent attackers from guessing access + tokens, authorization codes, refresh tokens, resource owner + passwords, and client credentials. + + The probability of an attacker guessing generated tokens (and other + credentials not intended for handling by end-users) MUST be less than + or equal to 2^(-128) and SHOULD be less than or equal to 2^(-160). + + The authorization server MUST utilize other means to protect + credentials intended for end-user usage. + +10.11. Phishing Attacks + + Wide deployment of this and similar protocols may cause end-users to + become inured to the practice of being redirected to websites where + they are asked to enter their passwords. If end-users are not + careful to verify the authenticity of these websites before entering + their credentials, it will be possible for attackers to exploit this + practice to steal resource owners' passwords. + + Service providers should attempt to educate end-users about the risks + phishing attacks pose and should provide mechanisms that make it easy + for end-users to confirm the authenticity of their sites. Client + developers should consider the security implications of how they + interact with the user-agent (e.g., external, embedded), and the + ability of the end-user to verify the authenticity of the + authorization server. + + + +Hardt Standards Track [Page 58] + +RFC 6749 OAuth 2.0 October 2012 + + + To reduce the risk of phishing attacks, the authorization servers + MUST require the use of TLS on every endpoint used for end-user + interaction. + +10.12. Cross-Site Request Forgery + + Cross-site request forgery (CSRF) is an exploit in which an attacker + causes the user-agent of a victim end-user to follow a malicious URI + (e.g., provided to the user-agent as a misleading link, image, or + redirection) to a trusting server (usually established via the + presence of a valid session cookie). + + A CSRF attack against the client's redirection URI allows an attacker + to inject its own authorization code or access token, which can + result in the client using an access token associated with the + attacker's protected resources rather than the victim's (e.g., save + the victim's bank account information to a protected resource + controlled by the attacker). + + The client MUST implement CSRF protection for its redirection URI. + This is typically accomplished by requiring any request sent to the + redirection URI endpoint to include a value that binds the request to + the user-agent's authenticated state (e.g., a hash of the session + cookie used to authenticate the user-agent). The client SHOULD + utilize the "state" request parameter to deliver this value to the + authorization server when making an authorization request. + + Once authorization has been obtained from the end-user, the + authorization server redirects the end-user's user-agent back to the + client with the required binding value contained in the "state" + parameter. The binding value enables the client to verify the + validity of the request by matching the binding value to the + user-agent's authenticated state. The binding value used for CSRF + protection MUST contain a non-guessable value (as described in + Section 10.10), and the user-agent's authenticated state (e.g., + session cookie, HTML5 local storage) MUST be kept in a location + accessible only to the client and the user-agent (i.e., protected by + same-origin policy). + + A CSRF attack against the authorization server's authorization + endpoint can result in an attacker obtaining end-user authorization + for a malicious client without involving or alerting the end-user. + + The authorization server MUST implement CSRF protection for its + authorization endpoint and ensure that a malicious client cannot + obtain authorization without the awareness and explicit consent of + the resource owner. + + + + +Hardt Standards Track [Page 59] + +RFC 6749 OAuth 2.0 October 2012 + + +10.13. Clickjacking + + In a clickjacking attack, an attacker registers a legitimate client + and then constructs a malicious site in which it loads the + authorization server's authorization endpoint web page in a + transparent iframe overlaid on top of a set of dummy buttons, which + are carefully constructed to be placed directly under important + buttons on the authorization page. When an end-user clicks a + misleading visible button, the end-user is actually clicking an + invisible button on the authorization page (such as an "Authorize" + button). This allows an attacker to trick a resource owner into + granting its client access without the end-user's knowledge. + + To prevent this form of attack, native applications SHOULD use + external browsers instead of embedding browsers within the + application when requesting end-user authorization. For most newer + browsers, avoidance of iframes can be enforced by the authorization + server using the (non-standard) "x-frame-options" header. This + header can have two values, "deny" and "sameorigin", which will block + any framing, or framing by sites with a different origin, + respectively. For older browsers, JavaScript frame-busting + techniques can be used but may not be effective in all browsers. + +10.14. Code Injection and Input Validation + + A code injection attack occurs when an input or otherwise external + variable is used by an application unsanitized and causes + modification to the application logic. This may allow an attacker to + gain access to the application device or its data, cause denial of + service, or introduce a wide range of malicious side-effects. + + The authorization server and client MUST sanitize (and validate when + possible) any value received -- in particular, the value of the + "state" and "redirect_uri" parameters. + +10.15. Open Redirectors + + The authorization server, authorization endpoint, and client + redirection endpoint can be improperly configured and operate as open + redirectors. An open redirector is an endpoint using a parameter to + automatically redirect a user-agent to the location specified by the + parameter value without any validation. + + Open redirectors can be used in phishing attacks, or by an attacker + to get end-users to visit malicious sites by using the URI authority + component of a familiar and trusted destination. In addition, if the + authorization server allows the client to register only part of the + redirection URI, an attacker can use an open redirector operated by + + + +Hardt Standards Track [Page 60] + +RFC 6749 OAuth 2.0 October 2012 + + + the client to construct a redirection URI that will pass the + authorization server validation but will send the authorization code + or access token to an endpoint under the control of the attacker. + +10.16. Misuse of Access Token to Impersonate Resource Owner in Implicit + Flow + + For public clients using implicit flows, this specification does not + provide any method for the client to determine what client an access + token was issued to. + + A resource owner may willingly delegate access to a resource by + granting an access token to an attacker's malicious client. This may + be due to phishing or some other pretext. An attacker may also steal + a token via some other mechanism. An attacker may then attempt to + impersonate the resource owner by providing the access token to a + legitimate public client. + + In the implicit flow (response_type=token), the attacker can easily + switch the token in the response from the authorization server, + replacing the real access token with the one previously issued to the + attacker. + + Servers communicating with native applications that rely on being + passed an access token in the back channel to identify the user of + the client may be similarly compromised by an attacker creating a + compromised application that can inject arbitrary stolen access + tokens. + + Any public client that makes the assumption that only the resource + owner can present it with a valid access token for the resource is + vulnerable to this type of attack. + + This type of attack may expose information about the resource owner + at the legitimate client to the attacker (malicious client). This + will also allow the attacker to perform operations at the legitimate + client with the same permissions as the resource owner who originally + granted the access token or authorization code. + + Authenticating resource owners to clients is out of scope for this + specification. Any specification that uses the authorization process + as a form of delegated end-user authentication to the client (e.g., + third-party sign-in service) MUST NOT use the implicit flow without + additional security mechanisms that would enable the client to + determine if the access token was issued for its use (e.g., audience- + restricting the access token). + + + + + +Hardt Standards Track [Page 61] + +RFC 6749 OAuth 2.0 October 2012 + + +11. IANA Considerations + +11.1. OAuth Access Token Types Registry + + This specification establishes the OAuth Access Token Types registry. + + Access token types are registered with a Specification Required + ([RFC5226]) after a two-week review period on the + oauth-ext-review@ietf.org mailing list, on the advice of one or more + Designated Experts. However, to allow for the allocation of values + prior to publication, the Designated Expert(s) may approve + registration once they are satisfied that such a specification will + be published. + + Registration requests must be sent to the oauth-ext-review@ietf.org + mailing list for review and comment, with an appropriate subject + (e.g., "Request for access token type: example"). + + Within the review period, the Designated Expert(s) will either + approve or deny the registration request, communicating this decision + to the review list and IANA. Denials should include an explanation + and, if applicable, suggestions as to how to make the request + successful. + + IANA must only accept registry updates from the Designated Expert(s) + and should direct all requests for registration to the review mailing + list. + +11.1.1. Registration Template + + Type name: + The name requested (e.g., "example"). + + Additional Token Endpoint Response Parameters: + Additional response parameters returned together with the + "access_token" parameter. New parameters MUST be separately + registered in the OAuth Parameters registry as described by + Section 11.2. + + HTTP Authentication Scheme(s): + The HTTP authentication scheme name(s), if any, used to + authenticate protected resource requests using access tokens of + this type. + + Change controller: + For Standards Track RFCs, state "IETF". For others, give the name + of the responsible party. Other details (e.g., postal address, + email address, home page URI) may also be included. + + + +Hardt Standards Track [Page 62] + +RFC 6749 OAuth 2.0 October 2012 + + + Specification document(s): + Reference to the document(s) that specify the parameter, + preferably including a URI that can be used to retrieve a copy of + the document(s). An indication of the relevant sections may also + be included but is not required. + +11.2. OAuth Parameters Registry + + This specification establishes the OAuth Parameters registry. + + Additional parameters for inclusion in the authorization endpoint + request, the authorization endpoint response, the token endpoint + request, or the token endpoint response are registered with a + Specification Required ([RFC5226]) after a two-week review period on + the oauth-ext-review@ietf.org mailing list, on the advice of one or + more Designated Experts. However, to allow for the allocation of + values prior to publication, the Designated Expert(s) may approve + registration once they are satisfied that such a specification will + be published. + + Registration requests must be sent to the oauth-ext-review@ietf.org + mailing list for review and comment, with an appropriate subject + (e.g., "Request for parameter: example"). + + Within the review period, the Designated Expert(s) will either + approve or deny the registration request, communicating this decision + to the review list and IANA. Denials should include an explanation + and, if applicable, suggestions as to how to make the request + successful. + + IANA must only accept registry updates from the Designated Expert(s) + and should direct all requests for registration to the review mailing + list. + +11.2.1. Registration Template + + Parameter name: + The name requested (e.g., "example"). + + Parameter usage location: + The location(s) where parameter can be used. The possible + locations are authorization request, authorization response, token + request, or token response. + + Change controller: + For Standards Track RFCs, state "IETF". For others, give the name + of the responsible party. Other details (e.g., postal address, + email address, home page URI) may also be included. + + + +Hardt Standards Track [Page 63] + +RFC 6749 OAuth 2.0 October 2012 + + + Specification document(s): + Reference to the document(s) that specify the parameter, + preferably including a URI that can be used to retrieve a copy of + the document(s). An indication of the relevant sections may also + be included but is not required. + +11.2.2. Initial Registry Contents + + The OAuth Parameters registry's initial contents are: + + o Parameter name: client_id + o Parameter usage location: authorization request, token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: client_secret + o Parameter usage location: token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: response_type + o Parameter usage location: authorization request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: redirect_uri + o Parameter usage location: authorization request, token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: scope + o Parameter usage location: authorization request, authorization + response, token request, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: state + o Parameter usage location: authorization request, authorization + response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: code + o Parameter usage location: authorization response, token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + + + + +Hardt Standards Track [Page 64] + +RFC 6749 OAuth 2.0 October 2012 + + + o Parameter name: error_description + o Parameter usage location: authorization response, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: error_uri + o Parameter usage location: authorization response, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: grant_type + o Parameter usage location: token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: access_token + o Parameter usage location: authorization response, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: token_type + o Parameter usage location: authorization response, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: expires_in + o Parameter usage location: authorization response, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: username + o Parameter usage location: token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: password + o Parameter usage location: token request + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Parameter name: refresh_token + o Parameter usage location: token request, token response + o Change controller: IETF + o Specification document(s): RFC 6749 + + + + + + + +Hardt Standards Track [Page 65] + +RFC 6749 OAuth 2.0 October 2012 + + +11.3. OAuth Authorization Endpoint Response Types Registry + + This specification establishes the OAuth Authorization Endpoint + Response Types registry. + + Additional response types for use with the authorization endpoint are + registered with a Specification Required ([RFC5226]) after a two-week + review period on the oauth-ext-review@ietf.org mailing list, on the + advice of one or more Designated Experts. However, to allow for the + allocation of values prior to publication, the Designated Expert(s) + may approve registration once they are satisfied that such a + specification will be published. + + Registration requests must be sent to the oauth-ext-review@ietf.org + mailing list for review and comment, with an appropriate subject + (e.g., "Request for response type: example"). + + Within the review period, the Designated Expert(s) will either + approve or deny the registration request, communicating this decision + to the review list and IANA. Denials should include an explanation + and, if applicable, suggestions as to how to make the request + successful. + + IANA must only accept registry updates from the Designated Expert(s) + and should direct all requests for registration to the review mailing + list. + +11.3.1. Registration Template + + Response type name: + The name requested (e.g., "example"). + + Change controller: + For Standards Track RFCs, state "IETF". For others, give the name + of the responsible party. Other details (e.g., postal address, + email address, home page URI) may also be included. + + Specification document(s): + Reference to the document(s) that specify the type, preferably + including a URI that can be used to retrieve a copy of the + document(s). An indication of the relevant sections may also be + included but is not required. + + + + + + + + + +Hardt Standards Track [Page 66] + +RFC 6749 OAuth 2.0 October 2012 + + +11.3.2. Initial Registry Contents + + The OAuth Authorization Endpoint Response Types registry's initial + contents are: + + o Response type name: code + o Change controller: IETF + o Specification document(s): RFC 6749 + + o Response type name: token + o Change controller: IETF + o Specification document(s): RFC 6749 + +11.4. OAuth Extensions Error Registry + + This specification establishes the OAuth Extensions Error registry. + + Additional error codes used together with other protocol extensions + (i.e., extension grant types, access token types, or extension + parameters) are registered with a Specification Required ([RFC5226]) + after a two-week review period on the oauth-ext-review@ietf.org + mailing list, on the advice of one or more Designated Experts. + However, to allow for the allocation of values prior to publication, + the Designated Expert(s) may approve registration once they are + satisfied that such a specification will be published. + + Registration requests must be sent to the oauth-ext-review@ietf.org + mailing list for review and comment, with an appropriate subject + (e.g., "Request for error code: example"). + + Within the review period, the Designated Expert(s) will either + approve or deny the registration request, communicating this decision + to the review list and IANA. Denials should include an explanation + and, if applicable, suggestions as to how to make the request + successful. + + IANA must only accept registry updates from the Designated Expert(s) + and should direct all requests for registration to the review mailing + list. + + + + + + + + + + + + +Hardt Standards Track [Page 67] + +RFC 6749 OAuth 2.0 October 2012 + + +11.4.1. Registration Template + + Error name: + The name requested (e.g., "example"). Values for the error name + MUST NOT include characters outside the set %x20-21 / %x23-5B / + %x5D-7E. + + Error usage location: + The location(s) where the error can be used. The possible + locations are authorization code grant error response + (Section 4.1.2.1), implicit grant error response + (Section 4.2.2.1), token error response (Section 5.2), or resource + access error response (Section 7.2). + + Related protocol extension: + The name of the extension grant type, access token type, or + extension parameter that the error code is used in conjunction + with. + + Change controller: + For Standards Track RFCs, state "IETF". For others, give the name + of the responsible party. Other details (e.g., postal address, + email address, home page URI) may also be included. + + Specification document(s): + Reference to the document(s) that specify the error code, + preferably including a URI that can be used to retrieve a copy of + the document(s). An indication of the relevant sections may also + be included but is not required. + +12. References + +12.1. Normative References + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC2246] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", + RFC 2246, January 1999. + + [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., + Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext + Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999. + + [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., + Leach, P., Luotonen, A., and L. Stewart, "HTTP + Authentication: Basic and Digest Access Authentication", + RFC 2617, June 1999. + + + +Hardt Standards Track [Page 68] + +RFC 6749 OAuth 2.0 October 2012 + + + [RFC2818] Rescorla, E., "HTTP Over TLS", RFC 2818, May 2000. + + [RFC3629] Yergeau, F., "UTF-8, a transformation format of + ISO 10646", STD 63, RFC 3629, November 2003. + + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, + RFC 3986, January 2005. + + [RFC4627] Crockford, D., "The application/json Media Type for + JavaScript Object Notation (JSON)", RFC 4627, July 2006. + + [RFC4949] Shirey, R., "Internet Security Glossary, Version 2", + RFC 4949, August 2007. + + [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an + IANA Considerations Section in RFCs", BCP 26, RFC 5226, + May 2008. + + [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", STD 68, RFC 5234, January 2008. + + [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer Security + (TLS) Protocol Version 1.2", RFC 5246, August 2008. + + [RFC6125] Saint-Andre, P. and J. Hodges, "Representation and + Verification of Domain-Based Application Service Identity + within Internet Public Key Infrastructure Using X.509 + (PKIX) Certificates in the Context of Transport Layer + Security (TLS)", RFC 6125, March 2011. + + [USASCII] American National Standards Institute, "Coded Character + Set -- 7-bit American Standard Code for Information + Interchange", ANSI X3.4, 1986. + + [W3C.REC-html401-19991224] + Raggett, D., Le Hors, A., and I. Jacobs, "HTML 4.01 + Specification", World Wide Web Consortium + Recommendation REC-html401-19991224, December 1999, + <http://www.w3.org/TR/1999/REC-html401-19991224>. + + [W3C.REC-xml-20081126] + Bray, T., Paoli, J., Sperberg-McQueen, C., Maler, E., + and F. Yergeau, "Extensible Markup Language (XML) 1.0 + (Fifth Edition)", World Wide Web Consortium + Recommendation REC-xml-20081126, November 2008, + <http://www.w3.org/TR/2008/REC-xml-20081126>. + + + + +Hardt Standards Track [Page 69] + +RFC 6749 OAuth 2.0 October 2012 + + +12.2. Informative References + + [OAuth-HTTP-MAC] + Hammer-Lahav, E., Ed., "HTTP Authentication: MAC Access + Authentication", Work in Progress, February 2012. + + [OAuth-SAML2] + Campbell, B. and C. Mortimore, "SAML 2.0 Bearer Assertion + Profiles for OAuth 2.0", Work in Progress, September 2012. + + [OAuth-THREATMODEL] + Lodderstedt, T., Ed., McGloin, M., and P. Hunt, "OAuth 2.0 + Threat Model and Security Considerations", Work + in Progress, October 2012. + + [OAuth-WRAP] + Hardt, D., Ed., Tom, A., Eaton, B., and Y. Goland, "OAuth + Web Resource Authorization Profiles", Work in Progress, + January 2010. + + [RFC5849] Hammer-Lahav, E., "The OAuth 1.0 Protocol", RFC 5849, + April 2010. + + [RFC6750] Jones, M. and D. Hardt, "The OAuth 2.0 Authorization + Framework: Bearer Token Usage", RFC 6750, October 2012. + + + + + + + + + + + + + + + + + + + + + + + + + + +Hardt Standards Track [Page 70] + +RFC 6749 OAuth 2.0 October 2012 + + +Appendix A. Augmented Backus-Naur Form (ABNF) Syntax + + This section provides Augmented Backus-Naur Form (ABNF) syntax + descriptions for the elements defined in this specification using the + notation of [RFC5234]. The ABNF below is defined in terms of Unicode + code points [W3C.REC-xml-20081126]; these characters are typically + encoded in UTF-8. Elements are presented in the order first defined. + + Some of the definitions that follow use the "URI-reference" + definition from [RFC3986]. + + Some of the definitions that follow use these common definitions: + + VSCHAR = %x20-7E + NQCHAR = %x21 / %x23-5B / %x5D-7E + NQSCHAR = %x20-21 / %x23-5B / %x5D-7E + UNICODECHARNOCRLF = %x09 /%x20-7E / %x80-D7FF / + %xE000-FFFD / %x10000-10FFFF + + (The UNICODECHARNOCRLF definition is based upon the Char definition + in Section 2.2 of [W3C.REC-xml-20081126], but omitting the Carriage + Return and Linefeed characters.) + +A.1. "client_id" Syntax + + The "client_id" element is defined in Section 2.3.1: + + client-id = *VSCHAR + +A.2. "client_secret" Syntax + + The "client_secret" element is defined in Section 2.3.1: + + client-secret = *VSCHAR + +A.3. "response_type" Syntax + + The "response_type" element is defined in Sections 3.1.1 and 8.4: + + response-type = response-name *( SP response-name ) + response-name = 1*response-char + response-char = "_" / DIGIT / ALPHA + + + + + + + + + +Hardt Standards Track [Page 71] + +RFC 6749 OAuth 2.0 October 2012 + + +A.4. "scope" Syntax + + The "scope" element is defined in Section 3.3: + + scope = scope-token *( SP scope-token ) + scope-token = 1*NQCHAR + +A.5. "state" Syntax + + The "state" element is defined in Sections 4.1.1, 4.1.2, 4.1.2.1, + 4.2.1, 4.2.2, and 4.2.2.1: + + state = 1*VSCHAR + +A.6. "redirect_uri" Syntax + + The "redirect_uri" element is defined in Sections 4.1.1, 4.1.3, + and 4.2.1: + + redirect-uri = URI-reference + +A.7. "error" Syntax + + The "error" element is defined in Sections 4.1.2.1, 4.2.2.1, 5.2, + 7.2, and 8.5: + + error = 1*NQSCHAR + +A.8. "error_description" Syntax + + The "error_description" element is defined in Sections 4.1.2.1, + 4.2.2.1, 5.2, and 7.2: + + error-description = 1*NQSCHAR + +A.9. "error_uri" Syntax + + The "error_uri" element is defined in Sections 4.1.2.1, 4.2.2.1, 5.2, + and 7.2: + + error-uri = URI-reference + + + + + + + + + + +Hardt Standards Track [Page 72] + +RFC 6749 OAuth 2.0 October 2012 + + +A.10. "grant_type" Syntax + + The "grant_type" element is defined in Sections 4.1.3, 4.3.2, 4.4.2, + 4.5, and 6: + + grant-type = grant-name / URI-reference + grant-name = 1*name-char + name-char = "-" / "." / "_" / DIGIT / ALPHA + +A.11. "code" Syntax + + The "code" element is defined in Section 4.1.3: + + code = 1*VSCHAR + +A.12. "access_token" Syntax + + The "access_token" element is defined in Sections 4.2.2 and 5.1: + + access-token = 1*VSCHAR + +A.13. "token_type" Syntax + + The "token_type" element is defined in Sections 4.2.2, 5.1, and 8.1: + + token-type = type-name / URI-reference + type-name = 1*name-char + name-char = "-" / "." / "_" / DIGIT / ALPHA + +A.14. "expires_in" Syntax + + The "expires_in" element is defined in Sections 4.2.2 and 5.1: + + expires-in = 1*DIGIT + +A.15. "username" Syntax + + The "username" element is defined in Section 4.3.2: + + username = *UNICODECHARNOCRLF + +A.16. "password" Syntax + + The "password" element is defined in Section 4.3.2: + + password = *UNICODECHARNOCRLF + + + + + +Hardt Standards Track [Page 73] + +RFC 6749 OAuth 2.0 October 2012 + + +A.17. "refresh_token" Syntax + + The "refresh_token" element is defined in Sections 5.1 and 6: + + refresh-token = 1*VSCHAR + +A.18. Endpoint Parameter Syntax + + The syntax for new endpoint parameters is defined in Section 8.2: + + param-name = 1*name-char + name-char = "-" / "." / "_" / DIGIT / ALPHA + +Appendix B. Use of application/x-www-form-urlencoded Media Type + + At the time of publication of this specification, the + "application/x-www-form-urlencoded" media type was defined in + Section 17.13.4 of [W3C.REC-html401-19991224] but not registered in + the IANA MIME Media Types registry + (<http://www.iana.org/assignments/media-types>). Furthermore, that + definition is incomplete, as it does not consider non-US-ASCII + characters. + + To address this shortcoming when generating payloads using this media + type, names and values MUST be encoded using the UTF-8 character + encoding scheme [RFC3629] first; the resulting octet sequence then + needs to be further encoded using the escaping rules defined in + [W3C.REC-html401-19991224]. + + When parsing data from a payload using this media type, the names and + values resulting from reversing the name/value encoding consequently + need to be treated as octet sequences, to be decoded using the UTF-8 + character encoding scheme. + + For example, the value consisting of the six Unicode code points + (1) U+0020 (SPACE), (2) U+0025 (PERCENT SIGN), + (3) U+0026 (AMPERSAND), (4) U+002B (PLUS SIGN), + (5) U+00A3 (POUND SIGN), and (6) U+20AC (EURO SIGN) would be encoded + into the octet sequence below (using hexadecimal notation): + + 20 25 26 2B C2 A3 E2 82 AC + + and then represented in the payload as: + + +%25%26%2B%C2%A3%E2%82%AC + + + + + + +Hardt Standards Track [Page 74] + +RFC 6749 OAuth 2.0 October 2012 + + +Appendix C. Acknowledgements + + The initial OAuth 2.0 protocol specification was edited by David + Recordon, based on two previous publications: the OAuth 1.0 community + specification [RFC5849], and OAuth WRAP (OAuth Web Resource + Authorization Profiles) [OAuth-WRAP]. Eran Hammer then edited many + of the intermediate drafts that evolved into this RFC. The Security + Considerations section was drafted by Torsten Lodderstedt, Mark + McGloin, Phil Hunt, Anthony Nadalin, and John Bradley. The section + on use of the "application/x-www-form-urlencoded" media type was + drafted by Julian Reschke. The ABNF section was drafted by Michael + B. Jones. + + The OAuth 1.0 community specification was edited by Eran Hammer and + authored by Mark Atwood, Dirk Balfanz, Darren Bounds, Richard M. + Conlan, Blaine Cook, Leah Culver, Breno de Medeiros, Brian Eaton, + Kellan Elliott-McCrea, Larry Halff, Eran Hammer, Ben Laurie, Chris + Messina, John Panzer, Sam Quigley, David Recordon, Eran Sandler, + Jonathan Sergent, Todd Sieling, Brian Slesinsky, and Andy Smith. + + The OAuth WRAP specification was edited by Dick Hardt and authored by + Brian Eaton, Yaron Y. Goland, Dick Hardt, and Allen Tom. + + This specification is the work of the OAuth Working Group, which + includes dozens of active and dedicated participants. In particular, + the following individuals contributed ideas, feedback, and wording + that shaped and formed the final specification: + + Michael Adams, Amanda Anganes, Andrew Arnott, Dirk Balfanz, Aiden + Bell, John Bradley, Marcos Caceres, Brian Campbell, Scott Cantor, + Blaine Cook, Roger Crew, Leah Culver, Bill de hOra, Andre DeMarre, + Brian Eaton, Wesley Eddy, Wolter Eldering, Brian Ellin, Igor + Faynberg, George Fletcher, Tim Freeman, Luca Frosini, Evan Gilbert, + Yaron Y. Goland, Brent Goldman, Kristoffer Gronowski, Eran Hammer, + Dick Hardt, Justin Hart, Craig Heath, Phil Hunt, Michael B. Jones, + Terry Jones, John Kemp, Mark Kent, Raffi Krikorian, Chasen Le Hara, + Rasmus Lerdorf, Torsten Lodderstedt, Hui-Lan Lu, Casey Lucas, Paul + Madsen, Alastair Mair, Eve Maler, James Manger, Mark McGloin, + Laurence Miao, William Mills, Chuck Mortimore, Anthony Nadalin, + Julian Reschke, Justin Richer, Peter Saint-Andre, Nat Sakimura, Rob + Sayre, Marius Scurtescu, Naitik Shah, Luke Shepard, Vlad Skvortsov, + Justin Smith, Haibin Song, Niv Steingarten, Christian Stuebner, + Jeremy Suriel, Paul Tarjan, Christopher Thomas, Henry S. Thompson, + Allen Tom, Franklin Tse, Nick Walker, Shane Weeden, and Skylar + Woodward. + + + + + + +Hardt Standards Track [Page 75] + +RFC 6749 OAuth 2.0 October 2012 + + + This document was produced under the chairmanship of Blaine Cook, + Peter Saint-Andre, Hannes Tschofenig, Barry Leiba, and Derek Atkins. + The area directors included Lisa Dusseault, Peter Saint-Andre, and + Stephen Farrell. + +Author's Address + + Dick Hardt (editor) + Microsoft + + EMail: dick.hardt@gmail.com + URI: http://dickhardt.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Hardt Standards Track [Page 76] + diff --git a/conformance/specs/rfc/rfc6750.txt b/conformance/specs/rfc/rfc6750.txt new file mode 100644 index 0000000..b433c72 --- /dev/null +++ b/conformance/specs/rfc/rfc6750.txt @@ -0,0 +1,1011 @@ + + + + + + +Internet Engineering Task Force (IETF) M. Jones +Request for Comments: 6750 Microsoft +Category: Standards Track D. Hardt +ISSN: 2070-1721 Independent + October 2012 + + + The OAuth 2.0 Authorization Framework: Bearer Token Usage + +Abstract + + This specification describes how to use bearer tokens in HTTP + requests to access OAuth 2.0 protected resources. Any party in + possession of a bearer token (a "bearer") can use it to get access to + the associated resources (without demonstrating possession of a + cryptographic key). To prevent misuse, bearer tokens need to be + protected from disclosure in storage and in transport. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by the + Internet Engineering Steering Group (IESG). Further information on + Internet Standards is available in Section 2 of RFC 5741. + + Information about the current status of this document, any errata, + and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc6750. + +Copyright Notice + + Copyright (c) 2012 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + + + + + +Jones & Hardt Standards Track [Page 1] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +Table of Contents + + 1. Introduction ....................................................2 + 1.1. Notational Conventions .....................................3 + 1.2. Terminology ................................................3 + 1.3. Overview ...................................................3 + 2. Authenticated Requests ..........................................4 + 2.1. Authorization Request Header Field .........................5 + 2.2. Form-Encoded Body Parameter ................................5 + 2.3. URI Query Parameter ........................................6 + 3. The WWW-Authenticate Response Header Field ......................7 + 3.1. Error Codes ................................................9 + 4. Example Access Token Response ..................................10 + 5. Security Considerations ........................................10 + 5.1. Security Threats ..........................................10 + 5.2. Threat Mitigation .........................................11 + 5.3. Summary of Recommendations ................................13 + 6. IANA Considerations ............................................14 + 6.1. OAuth Access Token Type Registration ......................14 + 6.1.1. The "Bearer" OAuth Access Token Type ...............14 + 6.2. OAuth Extensions Error Registration .......................14 + 6.2.1. The "invalid_request" Error Value ..................14 + 6.2.2. The "invalid_token" Error Value ....................15 + 6.2.3. The "insufficient_scope" Error Value ...............15 + 7. References .....................................................15 + 7.1. Normative References ......................................15 + 7.2. Informative References ....................................17 + Appendix A. Acknowledgements ......................................18 + +1. Introduction + + OAuth enables clients to access protected resources by obtaining an + access token, which is defined in "The OAuth 2.0 Authorization + Framework" [RFC6749] as "a string representing an access + authorization issued to the client", rather than using the resource + owner's credentials directly. + + Tokens are issued to clients by an authorization server with the + approval of the resource owner. The client uses the access token to + access the protected resources hosted by the resource server. This + specification describes how to make protected resource requests when + the OAuth access token is a bearer token. + + This specification defines the use of bearer tokens over HTTP/1.1 + [RFC2616] using Transport Layer Security (TLS) [RFC5246] to access + protected resources. TLS is mandatory to implement and use with this + specification; other specifications may extend this specification for + use with other protocols. While designed for use with access tokens + + + +Jones & Hardt Standards Track [Page 2] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + resulting from OAuth 2.0 authorization [RFC6749] flows to access + OAuth protected resources, this specification actually defines a + general HTTP authorization method that can be used with bearer tokens + from any source to access any resources protected by those bearer + tokens. The Bearer authentication scheme is intended primarily for + server authentication using the WWW-Authenticate and Authorization + HTTP headers but does not preclude its use for proxy authentication. + +1.1. Notational Conventions + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in "Key words for use in + RFCs to Indicate Requirement Levels" [RFC2119]. + + This document uses the Augmented Backus-Naur Form (ABNF) notation of + [RFC5234]. Additionally, the following rules are included from + HTTP/1.1 [RFC2617]: auth-param and auth-scheme; and from "Uniform + Resource Identifier (URI): Generic Syntax" [RFC3986]: URI-reference. + + Unless otherwise noted, all the protocol parameter names and values + are case sensitive. + +1.2. Terminology + + Bearer Token + A security token with the property that any party in possession of + the token (a "bearer") can use the token in any way that any other + party in possession of it can. Using a bearer token does not + require a bearer to prove possession of cryptographic key material + (proof-of-possession). + + All other terms are as defined in "The OAuth 2.0 Authorization + Framework" [RFC6749]. + +1.3. Overview + + OAuth provides a method for clients to access a protected resource on + behalf of a resource owner. In the general case, before a client can + access a protected resource, it must first obtain an authorization + grant from the resource owner and then exchange the authorization + grant for an access token. The access token represents the grant's + scope, duration, and other attributes granted by the authorization + grant. The client accesses the protected resource by presenting the + access token to the resource server. In some cases, a client can + directly present its own credentials to an authorization server to + obtain an access token without having to first obtain an + authorization grant from a resource owner. + + + +Jones & Hardt Standards Track [Page 3] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + The access token provides an abstraction, replacing different + authorization constructs (e.g., username and password, assertion) for + a single token understood by the resource server. This abstraction + enables issuing access tokens valid for a short time period, as well + as removing the resource server's need to understand a wide range of + authentication schemes. + + +--------+ +---------------+ + | |--(A)- Authorization Request ->| Resource | + | | | Owner | + | |<-(B)-- Authorization Grant ---| | + | | +---------------+ + | | + | | +---------------+ + | |--(C)-- Authorization Grant -->| Authorization | + | Client | | Server | + | |<-(D)----- Access Token -------| | + | | +---------------+ + | | + | | +---------------+ + | |--(E)----- Access Token ------>| Resource | + | | | Server | + | |<-(F)--- Protected Resource ---| | + +--------+ +---------------+ + + Figure 1: Abstract Protocol Flow + + The abstract OAuth 2.0 flow illustrated in Figure 1 describes the + interaction between the client, resource owner, authorization server, + and resource server (described in [RFC6749]). The following two + steps are specified within this document: + + (E) The client requests the protected resource from the resource + server and authenticates by presenting the access token. + + (F) The resource server validates the access token, and if valid, + serves the request. + + This document also imposes semantic requirements upon the access + token returned in step (D). + +2. Authenticated Requests + + This section defines three methods of sending bearer access tokens in + resource requests to resource servers. Clients MUST NOT use more + than one method to transmit the token in each request. + + + + + +Jones & Hardt Standards Track [Page 4] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +2.1. Authorization Request Header Field + + When sending the access token in the "Authorization" request header + field defined by HTTP/1.1 [RFC2617], the client uses the "Bearer" + authentication scheme to transmit the access token. + + For example: + + GET /resource HTTP/1.1 + Host: server.example.com + Authorization: Bearer mF_9.B5f-4.1JqM + + The syntax of the "Authorization" header field for this scheme + follows the usage of the Basic scheme defined in Section 2 of + [RFC2617]. Note that, as with Basic, it does not conform to the + generic syntax defined in Section 1.2 of [RFC2617] but is compatible + with the general authentication framework being developed for + HTTP 1.1 [HTTP-AUTH], although it does not follow the preferred + practice outlined therein in order to reflect existing deployments. + The syntax for Bearer credentials is as follows: + + b64token = 1*( ALPHA / DIGIT / + "-" / "." / "_" / "~" / "+" / "/" ) *"=" + credentials = "Bearer" 1*SP b64token + + Clients SHOULD make authenticated requests with a bearer token using + the "Authorization" request header field with the "Bearer" HTTP + authorization scheme. Resource servers MUST support this method. + +2.2. Form-Encoded Body Parameter + + When sending the access token in the HTTP request entity-body, the + client adds the access token to the request-body using the + "access_token" parameter. The client MUST NOT use this method unless + all of the following conditions are met: + + o The HTTP request entity-header includes the "Content-Type" header + field set to "application/x-www-form-urlencoded". + + o The entity-body follows the encoding requirements of the + "application/x-www-form-urlencoded" content-type as defined by + HTML 4.01 [W3C.REC-html401-19991224]. + + o The HTTP request entity-body is single-part. + + + + + + + +Jones & Hardt Standards Track [Page 5] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + o The content to be encoded in the entity-body MUST consist entirely + of ASCII [USASCII] characters. + + o The HTTP request method is one for which the request-body has + defined semantics. In particular, this means that the "GET" + method MUST NOT be used. + + The entity-body MAY include other request-specific parameters, in + which case the "access_token" parameter MUST be properly separated + from the request-specific parameters using "&" character(s) (ASCII + code 38). + + For example, the client makes the following HTTP request using + transport-layer security: + + POST /resource HTTP/1.1 + Host: server.example.com + Content-Type: application/x-www-form-urlencoded + + access_token=mF_9.B5f-4.1JqM + + The "application/x-www-form-urlencoded" method SHOULD NOT be used + except in application contexts where participating browsers do not + have access to the "Authorization" request header field. Resource + servers MAY support this method. + +2.3. URI Query Parameter + + When sending the access token in the HTTP request URI, the client + adds the access token to the request URI query component as defined + by "Uniform Resource Identifier (URI): Generic Syntax" [RFC3986], + using the "access_token" parameter. + + For example, the client makes the following HTTP request using + transport-layer security: + + GET /resource?access_token=mF_9.B5f-4.1JqM HTTP/1.1 + Host: server.example.com + + The HTTP request URI query can include other request-specific + parameters, in which case the "access_token" parameter MUST be + properly separated from the request-specific parameters using "&" + character(s) (ASCII code 38). + + + + + + + + +Jones & Hardt Standards Track [Page 6] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + For example: + + https://server.example.com/resource?access_token=mF_9.B5f-4.1JqM&p=q + + Clients using the URI Query Parameter method SHOULD also send a + Cache-Control header containing the "no-store" option. Server + success (2XX status) responses to these requests SHOULD contain a + Cache-Control header with the "private" option. + + Because of the security weaknesses associated with the URI method + (see Section 5), including the high likelihood that the URL + containing the access token will be logged, it SHOULD NOT be used + unless it is impossible to transport the access token in the + "Authorization" request header field or the HTTP request entity-body. + Resource servers MAY support this method. + + This method is included to document current use; its use is not + recommended, due to its security deficiencies (see Section 5) and + also because it uses a reserved query parameter name, which is + counter to URI namespace best practices, per "Architecture of the + World Wide Web, Volume One" [W3C.REC-webarch-20041215]. + +3. The WWW-Authenticate Response Header Field + + If the protected resource request does not include authentication + credentials or does not contain an access token that enables access + to the protected resource, the resource server MUST include the HTTP + "WWW-Authenticate" response header field; it MAY include it in + response to other conditions as well. The "WWW-Authenticate" header + field uses the framework defined by HTTP/1.1 [RFC2617]. + + All challenges defined by this specification MUST use the auth-scheme + value "Bearer". This scheme MUST be followed by one or more + auth-param values. The auth-param attributes used or defined by this + specification are as follows. Other auth-param attributes MAY be + used as well. + + A "realm" attribute MAY be included to indicate the scope of + protection in the manner described in HTTP/1.1 [RFC2617]. The + "realm" attribute MUST NOT appear more than once. + + The "scope" attribute is defined in Section 3.3 of [RFC6749]. The + "scope" attribute is a space-delimited list of case-sensitive scope + values indicating the required scope of the access token for + accessing the requested resource. "scope" values are implementation + defined; there is no centralized registry for them; allowed values + are defined by the authorization server. The order of "scope" values + is not significant. In some cases, the "scope" value will be used + + + +Jones & Hardt Standards Track [Page 7] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + when requesting a new access token with sufficient scope of access to + utilize the protected resource. Use of the "scope" attribute is + OPTIONAL. The "scope" attribute MUST NOT appear more than once. The + "scope" value is intended for programmatic use and is not meant to be + displayed to end-users. + + Two example scope values follow; these are taken from the OpenID + Connect [OpenID.Messages] and the Open Authentication Technology + Committee (OATC) Online Multimedia Authorization Protocol [OMAP] + OAuth 2.0 use cases, respectively: + + scope="openid profile email" + scope="urn:example:channel=HBO&urn:example:rating=G,PG-13" + + If the protected resource request included an access token and failed + authentication, the resource server SHOULD include the "error" + attribute to provide the client with the reason why the access + request was declined. The parameter value is described in + Section 3.1. In addition, the resource server MAY include the + "error_description" attribute to provide developers a human-readable + explanation that is not meant to be displayed to end-users. It also + MAY include the "error_uri" attribute with an absolute URI + identifying a human-readable web page explaining the error. The + "error", "error_description", and "error_uri" attributes MUST NOT + appear more than once. + + Values for the "scope" attribute (specified in Appendix A.4 of + [RFC6749]) MUST NOT include characters outside the set %x21 / %x23-5B + / %x5D-7E for representing scope values and %x20 for delimiters + between scope values. Values for the "error" and "error_description" + attributes (specified in Appendixes A.7 and A.8 of [RFC6749]) MUST + NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E. + Values for the "error_uri" attribute (specified in Appendix A.9 of + [RFC6749]) MUST conform to the URI-reference syntax and thus MUST NOT + include characters outside the set %x21 / %x23-5B / %x5D-7E. + + For example, in response to a protected resource request without + authentication: + + HTTP/1.1 401 Unauthorized + WWW-Authenticate: Bearer realm="example" + + + + + + + + + + +Jones & Hardt Standards Track [Page 8] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + And in response to a protected resource request with an + authentication attempt using an expired access token: + + HTTP/1.1 401 Unauthorized + WWW-Authenticate: Bearer realm="example", + error="invalid_token", + error_description="The access token expired" + +3.1. Error Codes + + When a request fails, the resource server responds using the + appropriate HTTP status code (typically, 400, 401, 403, or 405) and + includes one of the following error codes in the response: + + invalid_request + The request is missing a required parameter, includes an + unsupported parameter or parameter value, repeats the same + parameter, uses more than one method for including an access + token, or is otherwise malformed. The resource server SHOULD + respond with the HTTP 400 (Bad Request) status code. + + invalid_token + The access token provided is expired, revoked, malformed, or + invalid for other reasons. The resource SHOULD respond with + the HTTP 401 (Unauthorized) status code. The client MAY + request a new access token and retry the protected resource + request. + + insufficient_scope + The request requires higher privileges than provided by the + access token. The resource server SHOULD respond with the HTTP + 403 (Forbidden) status code and MAY include the "scope" + attribute with the scope necessary to access the protected + resource. + + If the request lacks any authentication information (e.g., the client + was unaware that authentication is necessary or attempted using an + unsupported authentication method), the resource server SHOULD NOT + include an error code or other error information. + + For example: + + HTTP/1.1 401 Unauthorized + WWW-Authenticate: Bearer realm="example" + + + + + + + +Jones & Hardt Standards Track [Page 9] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +4. Example Access Token Response + + Typically, a bearer token is returned to the client as part of an + OAuth 2.0 [RFC6749] access token response. An example of such a + response is: + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + Cache-Control: no-store + Pragma: no-cache + + { + "access_token":"mF_9.B5f-4.1JqM", + "token_type":"Bearer", + "expires_in":3600, + "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA" + } + +5. Security Considerations + + This section describes the relevant security threats regarding token + handling when using bearer tokens and describes how to mitigate these + threats. + +5.1. Security Threats + + The following list presents several common threats against protocols + utilizing some form of tokens. This list of threats is based on NIST + Special Publication 800-63 [NIST800-63]. Since this document builds + on the OAuth 2.0 Authorization specification [RFC6749], we exclude a + discussion of threats that are described there or in related + documents. + + Token manufacture/modification: An attacker may generate a bogus + token or modify the token contents (such as the authentication or + attribute statements) of an existing token, causing the resource + server to grant inappropriate access to the client. For example, + an attacker may modify the token to extend the validity period; a + malicious client may modify the assertion to gain access to + information that they should not be able to view. + + Token disclosure: Tokens may contain authentication and attribute + statements that include sensitive information. + + + + + + + + +Jones & Hardt Standards Track [Page 10] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + Token redirect: An attacker uses a token generated for consumption + by one resource server to gain access to a different resource + server that mistakenly believes the token to be for it. + + Token replay: An attacker attempts to use a token that has already + been used with that resource server in the past. + +5.2. Threat Mitigation + + A large range of threats can be mitigated by protecting the contents + of the token by using a digital signature or a Message Authentication + Code (MAC). Alternatively, a bearer token can contain a reference to + authorization information, rather than encoding the information + directly. Such references MUST be infeasible for an attacker to + guess; using a reference may require an extra interaction between a + server and the token issuer to resolve the reference to the + authorization information. The mechanics of such an interaction are + not defined by this specification. + + This document does not specify the encoding or the contents of the + token; hence, detailed recommendations about the means of + guaranteeing token integrity protection are outside the scope of this + document. The token integrity protection MUST be sufficient to + prevent the token from being modified. + + To deal with token redirect, it is important for the authorization + server to include the identity of the intended recipients (the + audience), typically a single resource server (or a list of resource + servers), in the token. Restricting the use of the token to a + specific scope is also RECOMMENDED. + + The authorization server MUST implement TLS. Which version(s) ought + to be implemented will vary over time and will depend on the + widespread deployment and known security vulnerabilities at the time + of implementation. At the time of this writing, TLS version 1.2 + [RFC5246] is the most recent version, but it has very limited actual + deployment and might not be readily available in implementation + toolkits. TLS version 1.0 [RFC2246] is the most widely deployed + version and will give the broadest interoperability. + + To protect against token disclosure, confidentiality protection MUST + be applied using TLS [RFC5246] with a ciphersuite that provides + confidentiality and integrity protection. This requires that the + communication interaction between the client and the authorization + server, as well as the interaction between the client and the + resource server, utilize confidentiality and integrity protection. + Since TLS is mandatory to implement and to use with this + specification, it is the preferred approach for preventing token + + + +Jones & Hardt Standards Track [Page 11] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + disclosure via the communication channel. For those cases where the + client is prevented from observing the contents of the token, token + encryption MUST be applied in addition to the usage of TLS + protection. As a further defense against token disclosure, the + client MUST validate the TLS certificate chain when making requests + to protected resources, including checking the Certificate Revocation + List (CRL) [RFC5280]. + + Cookies are typically transmitted in the clear. Thus, any + information contained in them is at risk of disclosure. Therefore, + bearer tokens MUST NOT be stored in cookies that can be sent in the + clear. See "HTTP State Management Mechanism" [RFC6265] for security + considerations about cookies. + + In some deployments, including those utilizing load balancers, the + TLS connection to the resource server terminates prior to the actual + server that provides the resource. This could leave the token + unprotected between the front-end server where the TLS connection + terminates and the back-end server that provides the resource. In + such deployments, sufficient measures MUST be employed to ensure + confidentiality of the token between the front-end and back-end + servers; encryption of the token is one such possible measure. + + To deal with token capture and replay, the following recommendations + are made: First, the lifetime of the token MUST be limited; one means + of achieving this is by putting a validity time field inside the + protected part of the token. Note that using short-lived (one hour + or less) tokens reduces the impact of them being leaked. Second, + confidentiality protection of the exchanges between the client and + the authorization server and between the client and the resource + server MUST be applied. As a consequence, no eavesdropper along the + communication path is able to observe the token exchange. + Consequently, such an on-path adversary cannot replay the token. + Furthermore, when presenting the token to a resource server, the + client MUST verify the identity of that resource server, as per + Section 3.1 of "HTTP Over TLS" [RFC2818]. Note that the client MUST + validate the TLS certificate chain when making these requests to + protected resources. Presenting the token to an unauthenticated and + unauthorized resource server or failing to validate the certificate + chain will allow adversaries to steal the token and gain unauthorized + access to protected resources. + + + + + + + + + + +Jones & Hardt Standards Track [Page 12] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +5.3. Summary of Recommendations + + Safeguard bearer tokens: Client implementations MUST ensure that + bearer tokens are not leaked to unintended parties, as they will + be able to use them to gain access to protected resources. This + is the primary security consideration when using bearer tokens and + underlies all the more specific recommendations that follow. + + Validate TLS certificate chains: The client MUST validate the TLS + certificate chain when making requests to protected resources. + Failing to do so may enable DNS hijacking attacks to steal the + token and gain unintended access. + + Always use TLS (https): Clients MUST always use TLS [RFC5246] + (https) or equivalent transport security when making requests with + bearer tokens. Failing to do so exposes the token to numerous + attacks that could give attackers unintended access. + + Don't store bearer tokens in cookies: Implementations MUST NOT store + bearer tokens within cookies that can be sent in the clear (which + is the default transmission mode for cookies). Implementations + that do store bearer tokens in cookies MUST take precautions + against cross-site request forgery. + + Issue short-lived bearer tokens: Token servers SHOULD issue + short-lived (one hour or less) bearer tokens, particularly when + issuing tokens to clients that run within a web browser or other + environments where information leakage may occur. Using + short-lived bearer tokens can reduce the impact of them being + leaked. + + Issue scoped bearer tokens: Token servers SHOULD issue bearer tokens + that contain an audience restriction, scoping their use to the + intended relying party or set of relying parties. + + Don't pass bearer tokens in page URLs: Bearer tokens SHOULD NOT be + passed in page URLs (for example, as query string parameters). + Instead, bearer tokens SHOULD be passed in HTTP message headers or + message bodies for which confidentiality measures are taken. + Browsers, web servers, and other software may not adequately + secure URLs in the browser history, web server logs, and other + data structures. If bearer tokens are passed in page URLs, + attackers might be able to steal them from the history data, logs, + or other unsecured locations. + + + + + + + +Jones & Hardt Standards Track [Page 13] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +6. IANA Considerations + +6.1. OAuth Access Token Type Registration + + This specification registers the following access token type in the + OAuth Access Token Types registry defined in [RFC6749]. + +6.1.1. The "Bearer" OAuth Access Token Type + + Type name: + Bearer + + Additional Token Endpoint Response Parameters: + (none) + + HTTP Authentication Scheme(s): + Bearer + + Change controller: + IETF + + Specification document(s): + RFC 6750 + +6.2. OAuth Extensions Error Registration + + This specification registers the following error values in the OAuth + Extensions Error registry defined in [RFC6749]. + +6.2.1. The "invalid_request" Error Value + + Error name: + invalid_request + + Error usage location: + Resource access error response + + Related protocol extension: + Bearer access token type + + Change controller: + IETF + + Specification document(s): + RFC 6750 + + + + + + +Jones & Hardt Standards Track [Page 14] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +6.2.2. The "invalid_token" Error Value + + Error name: + invalid_token + + Error usage location: + Resource access error response + + Related protocol extension: + Bearer access token type + + Change controller: + IETF + + Specification document(s): + RFC 6750 + +6.2.3. The "insufficient_scope" Error Value + + Error name: + insufficient_scope + + Error usage location: + Resource access error response + + Related protocol extension: + Bearer access token type + + Change controller: + IETF + + Specification document(s): + RFC 6750 + +7. References + +7.1. Normative References + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC2246] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", + RFC 2246, January 1999. + + [RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., + Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext + Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999. + + + + +Jones & Hardt Standards Track [Page 15] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + + [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, + S., Leach, P., Luotonen, A., and L. Stewart, "HTTP + Authentication: Basic and Digest Access Authentication", + RFC 2617, June 1999. + + [RFC2818] Rescorla, E., "HTTP Over TLS", RFC 2818, May 2000. + + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, + RFC 3986, January 2005. + + [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", STD 68, RFC 5234, January 2008. + + [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer + Security (TLS) Protocol Version 1.2", RFC 5246, + August 2008. + + [RFC5280] Cooper, D., Santesson, S., Farrell, S., Boeyen, S., + Housley, R., and W. Polk, "Internet X.509 Public Key + Infrastructure Certificate and Certificate Revocation + List (CRL) Profile", RFC 5280, May 2008. + + [RFC6265] Barth, A., "HTTP State Management Mechanism", RFC 6265, + April 2011. + + [RFC6749] Hardt, D., Ed., "The OAuth 2.0 Authorization Framework", + RFC 6749, October 2012. + + [USASCII] American National Standards Institute, "Coded Character + Set -- 7-bit American Standard Code for Information + Interchange", ANSI X3.4, 1986. + + [W3C.REC-html401-19991224] + Raggett, D., Le Hors, A., and I. Jacobs, "HTML 4.01 + Specification", World Wide Web Consortium + Recommendation REC-html401-19991224, December 1999, + <http://www.w3.org/TR/1999/REC-html401-19991224>. + + [W3C.REC-webarch-20041215] + Jacobs, I. and N. Walsh, "Architecture of the World Wide + Web, Volume One", World Wide Web Consortium + Recommendation REC-webarch-20041215, December 2004, + <http://www.w3.org/TR/2004/REC-webarch-20041215>. + + + + + + + +Jones & Hardt Standards Track [Page 16] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +7.2. Informative References + + [HTTP-AUTH] Fielding, R., Ed., and J. Reschke, Ed., "Hypertext + Transfer Protocol (HTTP/1.1): Authentication", Work + in Progress, October 2012. + + [NIST800-63] Burr, W., Dodson, D., Newton, E., Perlner, R., Polk, T., + Gupta, S., and E. Nabbus, "NIST Special Publication + 800-63-1, INFORMATION SECURITY", December 2011, + <http://csrc.nist.gov/publications/>. + + [OMAP] Huff, J., Schlacht, D., Nadalin, A., Simmons, J., + Rosenberg, P., Madsen, P., Ace, T., Rickelton-Abdi, C., + and B. Boyer, "Online Multimedia Authorization Protocol: + An Industry Standard for Authorized Access to Internet + Multimedia Resources", April 2012, + <http://www.oatc.us/Standards/Download.aspx>. + + [OpenID.Messages] + Sakimura, N., Bradley, J., Jones, M., de Medeiros, B., + Mortimore, C., and E. Jay, "OpenID Connect Messages + 1.0", June 2012, <http://openid.net/specs/ + openid-connect-messages-1_0.html>. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Jones & Hardt Standards Track [Page 17] + +RFC 6750 OAuth 2.0 Bearer Token Usage October 2012 + + +Appendix A. Acknowledgements + + The following people contributed to preliminary versions of this + document: Blaine Cook (BT), Brian Eaton (Google), Yaron Y. Goland + (Microsoft), Brent Goldman (Facebook), Raffi Krikorian (Twitter), + Luke Shepard (Facebook), and Allen Tom (Yahoo!). The content and + concepts within are a product of the OAuth community, the Web + Resource Authorization Profiles (WRAP) community, and the OAuth + Working Group. David Recordon created a preliminary version of this + specification based upon an early draft of the specification that + evolved into OAuth 2.0 [RFC6749]. Michael B. Jones in turn created + the first version (00) of this specification using portions of + David's preliminary document and edited all subsequent versions. + + The OAuth Working Group has dozens of very active contributors who + proposed ideas and wording for this document, including Michael + Adams, Amanda Anganes, Andrew Arnott, Derek Atkins, Dirk Balfanz, + John Bradley, Brian Campbell, Francisco Corella, Leah Culver, Bill de + hOra, Breno de Medeiros, Brian Ellin, Stephen Farrell, Igor Faynberg, + George Fletcher, Tim Freeman, Evan Gilbert, Yaron Y. Goland, Eran + Hammer, Thomas Hardjono, Dick Hardt, Justin Hart, Phil Hunt, John + Kemp, Chasen Le Hara, Barry Leiba, Amos Jeffries, Michael B. Jones, + Torsten Lodderstedt, Paul Madsen, Eve Maler, James Manger, Laurence + Miao, William J. Mills, Chuck Mortimore, Anthony Nadalin, Axel + Nennker, Mark Nottingham, David Recordon, Julian Reschke, Rob + Richards, Justin Richer, Peter Saint-Andre, Nat Sakimura, Rob Sayre, + Marius Scurtescu, Naitik Shah, Justin Smith, Christian Stuebner, + Jeremy Suriel, Doug Tangren, Paul Tarjan, Hannes Tschofenig, Franklin + Tse, Sean Turner, Paul Walker, Shane Weeden, Skylar Woodward, and + Zachary Zeltsan. + +Authors' Addresses + + Michael B. Jones + Microsoft + + EMail: mbj@microsoft.com + URI: http://self-issued.info/ + + + Dick Hardt + Independent + + EMail: dick.hardt@gmail.com + URI: http://dickhardt.org/ + + + + + + +Jones & Hardt Standards Track [Page 18] + diff --git a/conformance/specs/rfc/rfc7578.txt b/conformance/specs/rfc/rfc7578.txt new file mode 100644 index 0000000..1e68cec --- /dev/null +++ b/conformance/specs/rfc/rfc7578.txt @@ -0,0 +1,843 @@ + + + + + + +Internet Engineering Task Force (IETF) L. Masinter +Request for Comments: 7578 Adobe +Obsoletes: 2388 July 2015 +Category: Standards Track +ISSN: 2070-1721 + + + Returning Values from Forms: multipart/form-data + +Abstract + + This specification defines the multipart/form-data media type, which + can be used by a wide variety of applications and transported by a + wide variety of protocols as a way of returning a set of values as + the result of a user filling out a form. This document obsoletes + RFC 2388. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by the + Internet Engineering Steering Group (IESG). Further information on + Internet Standards is available in Section 2 of RFC 5741. + + Information about the current status of this document, any errata, + and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc7578. + +Copyright Notice + + Copyright (c) 2015 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + + + + + + +Masinter Standards Track [Page 1] + +RFC 7578 multipart/form-data July 2015 + + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 + 2. Percent-Encoding Option . . . . . . . . . . . . . . . . . . . 3 + 3. Advice for Forms and Form Processing . . . . . . . . . . . . 3 + 4. Definition of multipart/form-data . . . . . . . . . . . . . . 4 + 4.1. "Boundary" Parameter of multipart/form-data . . . . . . . 4 + 4.2. Content-Disposition Header Field for Each Part . . . . . 4 + 4.3. Multiple Files for One Form Field . . . . . . . . . . . . 5 + 4.4. Content-Type Header Field for Each Part . . . . . . . . . 5 + 4.5. The Charset Parameter for "text/plain" Form Data . . . . 5 + 4.6. The _charset_ Field for Default Charset . . . . . . . . . 6 + 4.7. Content-Transfer-Encoding Deprecated . . . . . . . . . . 6 + 4.8. Other "Content-" Header Fields . . . . . . . . . . . . . 7 + 5. Operability Considerations . . . . . . . . . . . . . . . . . 7 + 5.1. Non-ASCII Field Names and Values . . . . . . . . . . . . 7 + 5.1.1. Avoid Non-ASCII Field Names . . . . . . . . . . . . . 7 + 5.1.2. Interpreting Forms and Creating multipart/form-data + Data . . . . . . . . . . . . . . . . . . . . . . . . 7 + 5.1.3. Parsing and Interpreting Form Data . . . . . . . . . 8 + 5.2. Ordered Fields and Duplicated Field Names . . . . . . . . 8 + 5.3. Interoperability with Web Applications . . . . . . . . . 8 + 5.4. Correlating Form Data with the Original Form . . . . . . 9 + 6. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 9 + 7. Security Considerations . . . . . . . . . . . . . . . . . . . 9 + 8. Media Type Registration for multipart/form-data . . . . . . . 10 + 9. References . . . . . . . . . . . . . . . . . . . . . . . . . 11 + 9.1. Normative References . . . . . . . . . . . . . . . . . . 11 + 9.2. Informative References . . . . . . . . . . . . . . . . . 12 + Appendix A. Changes from RFC 2388 . . . . . . . . . . . . . . . 14 + Appendix B. Alternatives . . . . . . . . . . . . . . . . . . . . 14 + Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . 15 + Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 15 + +1. Introduction + + In many applications, it is possible for a user to be presented with + a form. The user will fill out the form, including information that + is typed, generated by user input, or included from files that the + user has selected. When the form is filled out, the data from the + form is sent from the user to the receiving application. + + The definition of multipart/form-data is derived from one of those + applications, originally set out in [RFC1867] and subsequently + incorporated into HTML 3.2 [W3C.REC-html32-19970114], where forms are + expressed in HTML, and the form data is sent via HTTP or electronic + mail. This representation is widely implemented in numerous web + browsers and web servers. + + + +Masinter Standards Track [Page 2] + +RFC 7578 multipart/form-data July 2015 + + + However, multipart/form-data is also used for forms that are + presented using representations other than HTML (spreadsheets, PDF, + etc.) and for transport using means other than electronic mail or + HTTP; it is used in distributed applications that do not involve + forms at all or do not have users filling out the form. For this + reason, this document defines a general syntax and semantics + independent of the application for which it is used, with specific + rules for web applications noted in context. + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in BCP 14, RFC 2119 + [RFC2119]. + +2. Percent-Encoding Option + + Within this specification, "percent-encoding" (as defined in + [RFC3986]) is offered as a possible way of encoding characters in + file names that are otherwise disallowed, including non-ASCII + characters, spaces, control characters, and so forth. The encoding + is created replacing each non-ASCII or disallowed character with a + sequence, where each byte of the UTF-8 encoding of the character is + represented by a percent-sign (%) followed by the (case-insensitive) + hexadecimal of that byte. + +3. Advice for Forms and Form Processing + + The representation and interpretation of forms and the nature of form + processing is not specified by this document. However, for forms and + form processing that result in the generation of multipart/form-data, + some suggestions are included. + + In a form, there is generally a sequence of fields, where each field + is expected to be supplied with a value, e.g., by a user who fills + out the form. Each field has a name. After a form has been filled + out and the form's data is "submitted", the form processing results + in a set of values for each field -- the "form data". + + In forms that work with multipart/form-data, field names could be + arbitrary Unicode strings; however, restricting field names to ASCII + will help avoid some interoperability issues (see Section 5.1). + + Within a given form, ensuring field names are unique is also helpful. + Some fields may have default values or presupplied values in the form + itself. Fields with presupplied values might be hidden or invisible; + this allows using generic processing for form data from a variety of + actual forms. + + + + +Masinter Standards Track [Page 3] + +RFC 7578 multipart/form-data July 2015 + + +4. Definition of multipart/form-data + + The media type multipart/form-data follows the model of multipart + MIME data streams as specified in Section 5.1 of [RFC2046]; changes + are noted in this document. + + A multipart/form-data body contains a series of parts separated by a + boundary. + +4.1. "Boundary" Parameter of multipart/form-data + + As with other multipart types, the parts are delimited with a + boundary delimiter, constructed using CRLF, "--", and the value of + the "boundary" parameter. The boundary is supplied as a "boundary" + parameter to the multipart/form-data type. As noted in Section 5.1 + of [RFC2046], the boundary delimiter MUST NOT appear inside any of + the encapsulated parts, and it is often necessary to enclose the + "boundary" parameter values in quotes in the Content-Type header + field. + +4.2. Content-Disposition Header Field for Each Part + + Each part MUST contain a Content-Disposition header field [RFC2183] + where the disposition type is "form-data". The Content-Disposition + header field MUST also contain an additional parameter of "name"; the + value of the "name" parameter is the original field name from the + form (possibly encoded; see Section 5.1). For example, a part might + contain a header field such as the following, with the body of the + part containing the form data of the "user" field: + + Content-Disposition: form-data; name="user" + + For form data that represents the content of a file, a name for the + file SHOULD be supplied as well, by using a "filename" parameter of + the Content-Disposition header field. The file name isn't mandatory + for cases where the file name isn't available or is meaningless or + private; this might result, for example, when selection or drag-and- + drop is used or when the form data content is streamed directly from + a device. + + If a "filename" parameter is supplied, the requirements of + Section 2.3 of [RFC2183] for the "receiving MUA" (i.e., the receiving + Mail User Agent) apply to receivers of multipart/form-data as well: + do not use the file name blindly, check and possibly change to match + local file system conventions if applicable, and do not use directory + path information that may be present. + + + + + +Masinter Standards Track [Page 4] + +RFC 7578 multipart/form-data July 2015 + + + In most multipart types, the MIME header fields in each part are + restricted to US-ASCII; for compatibility with those systems, file + names normally visible to users MAY be encoded using the percent- + encoding method in Section 2, following how a "file:" URI + [URI-SCHEME] might be encoded. + + NOTE: The encoding method described in [RFC5987], which would add a + "filename*" parameter to the Content-Disposition header field, MUST + NOT be used. + + Some commonly deployed systems use multipart/form-data with file + names directly encoded including octets outside the US-ASCII range. + The encoding used for the file names is typically UTF-8, although + HTML forms will use the charset associated with the form. + +4.3. Multiple Files for One Form Field + + The form data for a form field might include multiple files. + + [RFC2388] suggested that multiple files for a single form field be + transmitted using a nested "multipart/mixed" part. This usage is + deprecated. + + To match widely deployed implementations, multiple files MUST be sent + by supplying each file in a separate part but all with the same + "name" parameter. + + Receiving applications intended for wide applicability (e.g., + multipart/form-data parsing libraries) SHOULD also support the older + method of supplying multiple files. + +4.4. Content-Type Header Field for Each Part + + Each part MAY have an (optional) "Content-Type" header field, which + defaults to "text/plain". If the contents of a file are to be sent, + the file data SHOULD be labeled with an appropriate media type, if + known, or "application/octet-stream". + +4.5. The Charset Parameter for "text/plain" Form Data + + In the case where the form data is text, the charset parameter for + the "text/plain" Content-Type MAY be used to indicate the character + encoding used in that part. For example, a form with a text field in + which a user typed "Joe owes <eu>100", where <eu> is the Euro symbol, + might have form data returned as: + + + + + + +Masinter Standards Track [Page 5] + +RFC 7578 multipart/form-data July 2015 + + + --AaB03x + content-disposition: form-data; name="field1" + content-type: text/plain;charset=UTF-8 + content-transfer-encoding: quoted-printable + + Joe owes =E2=82=AC100. + --AaB03x + + In practice, many widely deployed implementations do not supply a + charset parameter in each part, but rather, they rely on the notion + of a "default charset" for a multipart/form-data instance. + Subsequent sections will explain how the default charset is + established. + +4.6. The _charset_ Field for Default Charset + + Some form-processing applications (including HTML) have the + convention that the value of a form entry with entry name "_charset_" + and type "hidden" is automatically set when the form is opened; the + value is used as the default charset of text field values (see form- + charset in Section 5.1.2). In such cases, the value of the default + charset for each "text/plain" part without a charset parameter is the + supplied value. For example: + + --AaB03x + content-disposition: form-data; name="_charset_" + + iso-8859-1 + --AaB03x-- + content-disposition: form-data; name="field1" + + ...text encoded in iso-8859-1 ... + AaB03x-- + +4.7. Content-Transfer-Encoding Deprecated + + Previously, it was recommended that senders use a Content-Transfer- + Encoding encoding (such as "quoted-printable") for each non-ASCII + part of a multipart/form-data body because that would allow use in + transports that only support a "7bit" encoding. This use is + deprecated for use in contexts that support binary data such as HTTP. + Senders SHOULD NOT generate any parts with a Content-Transfer- + Encoding header field. + + Currently, no deployed implementations that send such bodies have + been discovered. + + + + + +Masinter Standards Track [Page 6] + +RFC 7578 multipart/form-data July 2015 + + +4.8. Other "Content-" Header Fields + + The multipart/form-data media type does not support any MIME header + fields in parts other than Content-Type, Content-Disposition, and (in + limited circumstances) Content-Transfer-Encoding. Other header + fields MUST NOT be included and MUST be ignored. + +5. Operability Considerations + +5.1. Non-ASCII Field Names and Values + + Normally, MIME header fields in multipart bodies are required to + consist only of 7-bit data in the US-ASCII character set. While + [RFC2388] suggested that non-ASCII field names be encoded according + to the method in [RFC2047], this practice doesn't seem to have been + followed widely. + + This specification makes three sets of recommendations for three + different states of workflow. + +5.1.1. Avoid Non-ASCII Field Names + + For broadest interoperability with existing deployed software, those + creating forms SHOULD avoid non-ASCII field names. This should not + be a burden because, in general, the field names are not visible to + users. The field names in the underlying need not match what the + user sees on the screen. + + If non-ASCII field names are unavoidable, form or application + creators SHOULD use UTF-8 uniformly. This will minimize + interoperability problems. + +5.1.2. Interpreting Forms and Creating multipart/form-data Data + + Some applications of this specification will supply a character + encoding to be used for interpretation of the multipart/form-data + body. In particular, HTML 5 [W3C.REC-html5-20141028] uses + + o the content of a "_charset_" field, if there is one; + + o the value of an accept-charset attribute of the <form> element, if + there is one; + + o the character encoding of the document containing the form, if it + is US-ASCII compatible; + + o otherwise, UTF-8. + + + + +Masinter Standards Track [Page 7] + +RFC 7578 multipart/form-data July 2015 + + + Call this value the form-charset. Any text, whether field name, + field value, or ("text/plain") form data that uses characters outside + the ASCII range MAY be represented directly encoded in the form- + charset. + +5.1.3. Parsing and Interpreting Form Data + + While this specification provides guidance for the creation of + multipart/form-data, parsers and interpreters should be aware of the + variety of implementations. File systems differ as to whether and + how they normalize Unicode names, for example. The matching of form + elements to form-data parts may rely on a fuzzier match. In + particular, some multipart/form-data generators might have followed + the previous advice of [RFC2388] and used the "encoded-word" method + of encoding non-ASCII values, as described in [RFC2047]: + + encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" + + Others have been known to follow [RFC2231], to send unencoded UTF-8, + or even to send strings encoded in the form-charset. + + For this reason, interpreting multipart/form-data (even from + conforming generators) may require knowing the charset used in form + encoding in cases where the _charset_ field value or a charset + parameter of a "text/plain" Content-Type header field is not + supplied. + +5.2. Ordered Fields and Duplicated Field Names + + Form processors given forms with a well-defined ordering SHOULD send + back results in order. (Note that there are some forms that do not + define a natural order.) Intermediaries MUST NOT reorder the + results. Form parts with identical field names MUST NOT be + coalesced. + +5.3. Interoperability with Web Applications + + Many web applications use the "application/x-www-form-urlencoded" + method for returning data from forms. This format is quite compact, + for example: + + name=Xavier+Xantico&verdict=Yes&colour=Blue&happy=sad&Utf%F6r=Send + + However, there is no opportunity to label the enclosed data with a + content type, apply a charset, or use other encoding mechanisms. + + + + + + +Masinter Standards Track [Page 8] + +RFC 7578 multipart/form-data July 2015 + + + Many form-interpreting programs (primarily web browsers) now + implement and generate multipart/form-data, but a receiving + application might also need to support the + "application/x-www-form-urlencoded" format. + +5.4. Correlating Form Data with the Original Form + + This specification provides no specific mechanism by which multipart/ + form-data can be associated with the form that caused it to be + transmitted. This separation is intentional; many different forms + might be used for transmitting the same data. In practice, + applications may supply a specific form processing resource (in HTML, + the ACTION attribute in a FORM tag) for each different form. + Alternatively, data about the form might be encoded in a "hidden + field" (a field that is part of the form but that has a fixed value + to be transmitted back to the form-data processor). + +6. IANA Considerations + + The media type registration of multipart/form-data has been updated + to point to this document, using the template in Section 8. In + addition, the registrations of the "name" parameter and the "form- + data" value in the "Content Disposition Values and Parameters" + registry have been updated to both point to this document. + +7. Security Considerations + + All form-processing software should treat user supplied form-data + with sensitivity, as it often contains confidential or personally + identifying information. There is widespread use of form "auto-fill" + features in web browsers; these might be used to trick users to + unknowingly send confidential information when completing otherwise + innocuous tasks. multipart/form-data does not supply any features + for checking integrity, ensuring confidentiality, avoiding user + confusion, or other security features; those concerns must be + addressed by the form-filling and form-data-interpreting + applications. + + Applications that receive forms and process them must be careful not + to supply data back to the requesting form-processing site that was + not intended to be sent. + + It is important when interpreting the filename of the Content- + Disposition header field to not inadvertently overwrite files in the + recipient's file space. + + + + + + +Masinter Standards Track [Page 9] + +RFC 7578 multipart/form-data July 2015 + + + User applications that request form information from users must be + careful not to cause a user to send information to the requestor or a + third party unwillingly or unwittingly. For example, a form might + request that spam information be sent to an unintended third party or + private information be sent to someone that the user might not + actually intend. While this is primarily an issue for the + representation and interpretation of forms themselves (rather than + the data representation of the form data), the transportation of + private information must be done in a way that does not expose it to + unwanted prying. + + With the introduction of form-data that can reasonably send back the + content of files from a user's file space, the possibility arises + that a user might be sent an automated script that fills out a form + and then sends one of the user's local files to another address. + Thus, additional caution is required when executing automated + scripting where form-data might include a user's files. + + Files sent via multipart/form-data may contain arbitrary executable + content, and precautions against malicious content are necessary. + + The considerations of Sections 2.3 and 5 of [RFC2183], with respect + to the "filename" parameter of the Content-Disposition header field, + also apply to its usage here. + +8. Media Type Registration for multipart/form-data + + This section is the media type registration using the template from + [RFC6838]. + + Type name: multipart + + Subtype name: form-data + + Required parameters: boundary + + Optional parameters: none + + Encoding considerations: Common use is BINARY. + In limited use (or transports that restrict the encoding to 7bit + or 8bit), each part is encoded separately using Content-Transfer- + Encoding; see Section 4.7. + + Security considerations: See Section 7 of this document. + + Interoperability considerations: This document makes several + recommendations for interoperability with deployed + implementations, including Section 4.7. + + + +Masinter Standards Track [Page 10] + +RFC 7578 multipart/form-data July 2015 + + + Published specification: This document. + + Applications that use this media type: Numerous web browsers, + servers, and web applications. + + Fragment identifier considerations: None; fragment identifiers are + not defined for this type. + + Additional information: + + Additional information: + + Deprecated alias names for this type: N/A + Magic number(s): N/A + File extension(s): N/A + Macintosh file type code(s): N/A + + Person & email address to contact for further information: Author of + this document. + + Intended usage: COMMON + + Restrictions on usage: none + + Author: Author of this document. + + Change controller: IETF + + Provisional registration: N/A + +9. References + +9.1. Normative References + + [RFC2046] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, + DOI 10.17487/RFC2046, November 1996, + <http://www.rfc-editor.org/info/rfc2046>. + + [RFC2047] Moore, K., "MIME (Multipurpose Internet Mail Extensions) + Part Three: Message Header Extensions for Non-ASCII Text", + RFC 2047, DOI 10.17487/RFC2047, November 1996, + <http://www.rfc-editor.org/info/rfc2047>. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, + DOI 10.17487/RFC2119, March 1997, + <http://www.rfc-editor.org/info/rfc2119>. + + + +Masinter Standards Track [Page 11] + +RFC 7578 multipart/form-data July 2015 + + + [RFC2183] Troost, R., Dorner, S., and K. Moore, Ed., "Communicating + Presentation Information in Internet Messages: The + Content-Disposition Header Field", RFC 2183, + DOI 10.17487/RFC2183, August 1997, + <http://www.rfc-editor.org/info/rfc2183>. + + [RFC2231] Freed, N. and K. Moore, "MIME Parameter Value and Encoded + Word Extensions: Character Sets, Languages, and + Continuations", RFC 2231, DOI 10.17487/RFC2231, November + 1997, <http://www.rfc-editor.org/info/rfc2231>. + + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, + RFC 3986, DOI 10.17487/RFC3986, January 2005, + <http://www.rfc-editor.org/info/rfc3986>. + +9.2. Informative References + + [RFC1867] Nebel, E. and L. Masinter, "Form-based File Upload in + HTML", RFC 1867, DOI 10.17487/RFC1867, November 1995, + <http://www.rfc-editor.org/info/rfc1867>. + + [RFC2388] Masinter, L., "Returning Values from Forms: multipart/ + form-data", RFC 2388, DOI 10.17487/RFC2388, August 1998, + <http://www.rfc-editor.org/info/rfc2388>. + + [RFC5987] Reschke, J., "Character Set and Language Encoding for + Hypertext Transfer Protocol (HTTP) Header Field + Parameters", RFC 5987, DOI 10.17487/RFC5987, August 2010, + <http://www.rfc-editor.org/info/rfc5987>. + + [RFC6838] Freed, N., Klensin, J., and T. Hansen, "Media Type + Specifications and Registration Procedures", BCP 13, + RFC 6838, DOI 10.17487/RFC6838, January 2013, + <http://www.rfc-editor.org/info/rfc6838>. + + [URI-SCHEME] + Kerwin, M., "The file URI Scheme", Work in Progress, + draft-ietf-appsawg-file-scheme-02, May 2015. + + [W3C.REC-html32-19970114] + Raggett, D., "HTML 3.2 Reference Specification", W3C + Recommendation REC-html32-19970114, January 1997, + <http://www.w3.org/TR/REC-html32-19970114>. + + + + + + + +Masinter Standards Track [Page 12] + +RFC 7578 multipart/form-data July 2015 + + + [W3C.REC-html5-20141028] + Hickson, I., Berjon, R., Faulkner, S., Leithead, T., + Navara, E., O'Connor, E., and S. Pfeiffer, "HTML5", W3C + Recommendation REC-html5-20141028, October 2014, + <http://www.w3.org/TR/2014/REC-html5-20141028>. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Masinter Standards Track [Page 13] + +RFC 7578 multipart/form-data July 2015 + + +Appendix A. Changes from RFC 2388 + + The handling of non-ASCII field names has changed -- the method + described in RFC 2047 is no longer recommended; instead, it is + suggested that senders send UTF-8 field names directly and that file + names be sent directly in the form-charset. + + The handling of multiple files submitted as the result of a single + form field (e.g., HTML's <input type=file multiple> element) results + in each file having its own top-level part with the same name + parameter; the method of using a nested "multipart/mixed" from + [RFC2388] is no longer recommended for creators and is not required + for receivers as there are no known implementations of senders. + + The _charset_ convention and use of an explicit "form-data" charset + is documented; also, "boundary" is now a required parameter in + Content-Type. + + The relationship of the ordering of fields within a form and the + ordering of returned values within multipart/form-data was not + defined before, nor was the handling of the case where a form has + multiple fields with the same name. + + Various editorial changes were made; they include removing the + obsolete discussion of alternatives from the appendix, updating the + references, and moving the outline of form processing into the + introduction. + +Appendix B. Alternatives + + There are numerous alternative ways in which form data can be + encoded; many are listed in Section 5.2 of [RFC2388]. The multipart/ + form-data encoding is verbose, especially if there are many fields + with short values. In most use cases, this overhead isn't + significant. + + More problematic are the differences introduced when implementors + opted to not follow [RFC2388] when encoding non-ASCII field names + (perhaps because "may" should have been "MUST"). As a result, + parsers need to be more complex for matching against the possible + outputs of various encoding methods. + + + + + + + + + + +Masinter Standards Track [Page 14] + +RFC 7578 multipart/form-data July 2015 + + +Acknowledgements + + Many thanks to the those who reviewed this document -- Alexey + Melnikov, Salvatore Loreto, Chris Lonvick, Kathleen Moriarty, Barry + Leiba, Julian Reschke, Tom Petch, Ned Freed, Cedric Brancourt, as + well as others, including Ian Hickson, who requested it be produced + in the first place. + +Author's Address + + Larry Masinter + Adobe + + Email: masinter@adobe.com + URI: http://larry.masinter.net + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Masinter Standards Track [Page 15] + diff --git a/conformance/specs/rfc/rfc7617.txt b/conformance/specs/rfc/rfc7617.txt new file mode 100644 index 0000000..3c035a6 --- /dev/null +++ b/conformance/specs/rfc/rfc7617.txt @@ -0,0 +1,843 @@ + + + + + + +Internet Engineering Task Force (IETF) J. Reschke +Request for Comments: 7617 greenbytes +Obsoletes: 2617 September 2015 +Category: Standards Track +ISSN: 2070-1721 + + + The 'Basic' HTTP Authentication Scheme + +Abstract + + This document defines the "Basic" Hypertext Transfer Protocol (HTTP) + authentication scheme, which transmits credentials as user-id/ + password pairs, encoded using Base64. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by the + Internet Engineering Steering Group (IESG). Further information on + Internet Standards is available in Section 2 of RFC 5741. + + Information about the current status of this document, any errata, + and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc7617. + + + + + + + + + + + + + + + + + + + + + + + +Reschke Standards Track [Page 1] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +Copyright Notice + + Copyright (c) 2015 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + + This document may contain material from IETF Documents or IETF + Contributions published or made publicly available before November + 10, 2008. The person(s) controlling the copyright in some of this + material may not have granted the IETF Trust the right to allow + modifications of such material outside the IETF Standards Process. + Without obtaining an adequate license from the person(s) controlling + the copyright in such materials, this document may not be modified + outside the IETF Standards Process, and derivative works of it may + not be created outside the IETF Standards Process, except to format + it for publication as an RFC or to translate it into languages other + than English. + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 3 + 1.1. Terminology and Notation . . . . . . . . . . . . . . . . 3 + 2. The 'Basic' Authentication Scheme . . . . . . . . . . . . . . 3 + 2.1. The 'charset' auth-param . . . . . . . . . . . . . . . . 5 + 2.2. Reusing Credentials . . . . . . . . . . . . . . . . . . . 7 + 3. Internationalization Considerations . . . . . . . . . . . . . 8 + 4. Security Considerations . . . . . . . . . . . . . . . . . . . 8 + 5. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 9 + 6. References . . . . . . . . . . . . . . . . . . . . . . . . . 10 + 6.1. Normative References . . . . . . . . . . . . . . . . . . 10 + 6.2. Informative References . . . . . . . . . . . . . . . . . 11 + Appendix A. Changes from RFC 2617 . . . . . . . . . . . . . . . 13 + Appendix B. Deployment Considerations for the 'charset' + Parameter . . . . . . . . . . . . . . . . . . . . . 13 + B.1. User Agents . . . . . . . . . . . . . . . . . . . . . . . 13 + B.2. Servers . . . . . . . . . . . . . . . . . . . . . . . . . 13 + B.3. Why not simply switch the default encoding to UTF-8? . . 14 + Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . 14 + Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 15 + + + +Reschke Standards Track [Page 2] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +1. Introduction + + This document defines the "Basic" Hypertext Transfer Protocol (HTTP) + authentication scheme, which transmits credentials as user-id/ + password pairs, encoded using Base64 (HTTP authentication schemes are + defined in [RFC7235]). + + This scheme is not considered to be a secure method of user + authentication unless used in conjunction with some external secure + system such as TLS (Transport Layer Security, [RFC5246]), as the + user-id and password are passed over the network as cleartext. + + The "Basic" scheme previously was defined in Section 2 of [RFC2617]. + This document updates the definition, and also addresses + internationalization issues by introducing the 'charset' + authentication parameter (Section 2.1). + + Other documents updating RFC 2617 are "Hypertext Transfer Protocol + (HTTP/1.1): Authentication" ([RFC7235], defining the authentication + framework), "HTTP Digest Access Authentication" ([RFC7616], updating + the definition of the "Digest" authentication scheme), and "HTTP + Authentication-Info and Proxy-Authentication-Info Response Header + Fields" ([RFC7615]). Taken together, these four documents obsolete + RFC 2617. + +1.1. Terminology and Notation + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [RFC2119]. + + The terms "protection space" and "realm" are defined in Section 2.2 + of [RFC7235]. + + The terms "(character) repertoire" and "character encoding scheme" + are defined in Section 2 of [RFC6365]. + +2. The 'Basic' Authentication Scheme + + The Basic authentication scheme is based on the model that the client + needs to authenticate itself with a user-id and a password for each + protection space ("realm"). The realm value is a free-form string + that can only be compared for equality with other realms on that + server. The server will service the request only if it can validate + the user-id and password for the protection space applying to the + requested resource. + + + + + +Reschke Standards Track [Page 3] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + The Basic authentication scheme utilizes the Authentication Framework + as follows. + + In challenges: + + o The scheme name is "Basic". + + o The authentication parameter 'realm' is REQUIRED ([RFC7235], + Section 2.2). + + o The authentication parameter 'charset' is OPTIONAL (see + Section 2.1). + + o No other authentication parameters are defined -- unknown + parameters MUST be ignored by recipients, and new parameters can + only be defined by revising this specification. + + See also Section 4.1 of [RFC7235], which discusses the complexity of + parsing challenges properly. + + Note that both scheme and parameter names are matched case- + insensitively. + + For credentials, the "token68" syntax defined in Section 2.1 of + [RFC7235] is used. The value is computed based on user-id and + password as defined below. + + Upon receipt of a request for a URI within the protection space that + lacks credentials, the server can reply with a challenge using the + 401 (Unauthorized) status code ([RFC7235], Section 3.1) and the + WWW-Authenticate header field ([RFC7235], Section 4.1). + + For instance: + + HTTP/1.1 401 Unauthorized + Date: Mon, 04 Feb 2014 16:50:53 GMT + WWW-Authenticate: Basic realm="WallyWorld" + + where "WallyWorld" is the string assigned by the server to identify + the protection space. + + A proxy can respond with a similar challenge using the 407 (Proxy + Authentication Required) status code ([RFC7235], Section 3.2) and the + Proxy-Authenticate header field ([RFC7235], Section 4.3). + + + + + + + +Reschke Standards Track [Page 4] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + To receive authorization, the client + + 1. obtains the user-id and password from the user, + + 2. constructs the user-pass by concatenating the user-id, a single + colon (":") character, and the password, + + 3. encodes the user-pass into an octet sequence (see below for a + discussion of character encoding schemes), + + 4. and obtains the basic-credentials by encoding this octet sequence + using Base64 ([RFC4648], Section 4) into a sequence of US-ASCII + characters ([RFC0020]). + + The original definition of this authentication scheme failed to + specify the character encoding scheme used to convert the user-pass + into an octet sequence. In practice, most implementations chose + either a locale-specific encoding such as ISO-8859-1 ([ISO-8859-1]), + or UTF-8 ([RFC3629]). For backwards compatibility reasons, this + specification continues to leave the default encoding undefined, as + long as it is compatible with US-ASCII (mapping any US-ASCII + character to a single octet matching the US-ASCII character code). + + The user-id and password MUST NOT contain any control characters (see + "CTL" in Appendix B.1 of [RFC5234]). + + Furthermore, a user-id containing a colon character is invalid, as + the first colon in a user-pass string separates user-id and password + from one another; text after the first colon is part of the password. + User-ids containing colons cannot be encoded in user-pass strings. + + Note that many user agents produce user-pass strings without checking + that user-ids supplied by users do not contain colons; recipients + will then treat part of the username input as part of the password. + + If the user agent wishes to send the user-id "Aladdin" and password + "open sesame", it would use the following header field: + + Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== + +2.1. The 'charset' auth-param + + In challenges, servers can use the 'charset' authentication parameter + to indicate the character encoding scheme they expect the user agent + to use when generating "user-pass" (a sequence of octets). This + information is purely advisory. + + + + + +Reschke Standards Track [Page 5] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + The only allowed value is "UTF-8"; it is to be matched case- + insensitively (see [RFC2978], Section 2.3). It indicates that the + server expects character data to be converted to Unicode + Normalization Form C ("NFC"; see Section 3 of [RFC5198]) and to be + encoded into octets using the UTF-8 character encoding scheme + ([RFC3629]). + + For the user-id, recipients MUST support all characters defined in + the "UsernameCasePreserved" profile defined in Section 3.3 of + [RFC7613], with the exception of the colon (":") character. + + For the password, recipients MUST support all characters defined in + the "OpaqueString" profile defined in Section 4.2 of [RFC7613]. + + Other values are reserved for future use. + + Note: The 'charset' is only defined on challenges, as Basic + authentication uses a single token for credentials ('token68' + syntax); thus, the credentials syntax isn't extensible. + + Note: The name 'charset' has been chosen for consistency with + Section 2.1.1 of [RFC2831]. A better name would have been + 'accept-charset', as it is not about the message it appears in, + but the server's expectation. + + In the example below, the server prompts for authentication in the + "foo" realm, using Basic authentication, with a preference for the + UTF-8 character encoding scheme: + + WWW-Authenticate: Basic realm="foo", charset="UTF-8" + + Note that the parameter value can be either a token or a quoted + string; in this case, the server chose to use the quoted-string + notation. + + The user's name is "test", and the password is the string "123" + followed by the Unicode character U+00A3 (POUND SIGN). Using the + character encoding scheme UTF-8, the user-pass becomes: + + 't' 'e' 's' 't' ':' '1' '2' '3' pound + 74 65 73 74 3A 31 32 33 C2 A3 + + Encoding this octet sequence in Base64 ([RFC4648], Section 4) yields: + + dGVzdDoxMjPCow== + + + + + + +Reschke Standards Track [Page 6] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + Thus, the Authorization header field would be: + + Authorization: Basic dGVzdDoxMjPCow== + + Or, for proxy authentication: + + Proxy-Authorization: Basic dGVzdDoxMjPCow== + +2.2. Reusing Credentials + + Given the absolute URI ([RFC3986], Section 4.3) of an authenticated + request, the authentication scope of that request is obtained by + removing all characters after the last slash ("/") character of the + path component ("hier_part"; see [RFC3986], Section 3). A client + SHOULD assume that resources identified by URIs with a prefix-match + of the authentication scope are also within the protection space + specified by the realm value of that authenticated request. + + A client MAY preemptively send the corresponding Authorization header + field with requests for resources in that space without receipt of + another challenge from the server. Similarly, when a client sends a + request to a proxy, it MAY reuse a user-id and password in the Proxy- + Authorization header field without receiving another challenge from + the proxy server. + + For example, given an authenticated request to: + + http://example.com/docs/index.html + + requests to the URIs below could use the known credentials: + + http://example.com/docs/ + http://example.com/docs/test.doc + http://example.com/docs/?page=1 + + while the URIs + + http://example.com/other/ + https://example.com/docs/ + + would be considered to be outside the authentication scope. + + Note that a URI can be part of multiple authentication scopes (such + as "http://example.com/" and "http://example.com/docs/"). This + specification does not define which of these should be treated with + higher priority. + + + + + +Reschke Standards Track [Page 7] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +3. Internationalization Considerations + + User-ids or passwords containing characters outside the US-ASCII + character repertoire will cause interoperability issues, unless both + communication partners agree on what character encoding scheme is to + be used. Servers can use the new 'charset' parameter (Section 2.1) + to indicate a preference of "UTF-8", increasing the probability that + clients will switch to that encoding. + + The 'realm' parameter carries data that can be considered textual; + however, [RFC7235] does not define a way to reliably transport non- + US-ASCII characters. This is a known issue that would need to be + addressed in a revision to that specification. + +4. Security Considerations + + The Basic authentication scheme is not a secure method of user + authentication, nor does it in any way protect the entity, which is + transmitted in cleartext across the physical network used as the + carrier. HTTP does not prevent the addition of enhancements (such as + schemes to use one-time passwords) to Basic authentication. + + The most serious flaw of Basic authentication is that it results in + the cleartext transmission of the user's password over the physical + network. Many other authentication schemes address this problem. + + Because Basic authentication involves the cleartext transmission of + passwords, it SHOULD NOT be used (without enhancements such as HTTPS + [RFC2818]) to protect sensitive or valuable information. + + A common use of Basic authentication is for identification purposes + -- requiring the user to provide a user-id and password as a means of + identification, for example, for purposes of gathering accurate usage + statistics on a server. When used in this way it is tempting to + think that there is no danger in its use if illicit access to the + protected documents is not a major concern. This is only correct if + the server issues both user-id and password to the users and, in + particular, does not allow the user to choose his or her own + password. The danger arises because naive users frequently reuse a + single password to avoid the task of maintaining multiple passwords. + + If a server permits users to select their own passwords, then the + threat is not only unauthorized access to documents on the server but + also unauthorized access to any other resources on other systems that + the user protects with the same password. Furthermore, in the + server's password database, many of the passwords may also be users' + passwords for other sites. The owner or administrator of such a + system could therefore expose all users of the system to the risk of + + + +Reschke Standards Track [Page 8] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + unauthorized access to all those other sites if this information is + not maintained in a secure fashion. This raises both security and + privacy concerns ([RFC6973]). If the same user-id and password + combination is in use to access other accounts, such as an email or + health portal account, personal information could be exposed. + + Basic authentication is also vulnerable to spoofing by counterfeit + servers. If a user can be led to believe that she is connecting to a + host containing information protected by Basic authentication when, + in fact, she is connecting to a hostile server or gateway, then the + attacker can request a password, store it for later use, and feign an + error. Server implementers ought to guard against this sort of + counterfeiting; in particular, software components that can take over + control over the message framing on an existing connection need to be + used carefully or not at all (for instance: NPH ("Non-Parsed Header") + scripts as described in Section 5 of [RFC3875]). + + Servers and proxies implementing Basic authentication need to store + user passwords in some form in order to authenticate a request. + These passwords ought to be stored in such a way that a leak of the + password data doesn't make them trivially recoverable. This is + especially important when users are allowed to set their own + passwords, since users are known to choose weak passwords and to + reuse them across authentication realms. While a full discussion of + good password hashing techniques is beyond the scope of this + document, server operators ought to make an effort to minimize risks + to their users in the event of a password data leak. For example, + servers ought to avoid storing user passwords in plaintext or as + unsalted digests. For more discussion about modern password hashing + techniques, see the "Password Hashing Competition" + (<https://password-hashing.net>). + + The use of the UTF-8 character encoding scheme and of normalization + introduces additional security considerations; see Section 10 of + [RFC3629] and Section 6 of [RFC5198] for more information. + +5. IANA Considerations + + IANA maintains the "Hypertext Transfer Protocol (HTTP) Authentication + Scheme Registry" ([RFC7235]) at <http://www.iana.org/assignments/ + http-authschemes>. + + The entry for the "Basic" authentication scheme has been updated to + reference this specification. + + + + + + + +Reschke Standards Track [Page 9] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +6. References + +6.1. Normative References + + [RFC20] Cerf, V., "ASCII format for network interchange", STD 80, + RFC 20, DOI 10.17487/RFC0020, October 1969, + <http://www.rfc-editor.org/info/rfc20>. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, + DOI 10.17487/RFC2119, March 1997, + <http://www.rfc-editor.org/info/rfc2119>. + + [RFC2978] Freed, N. and J. Postel, "IANA Charset Registration + Procedures", BCP 19, RFC 2978, DOI 10.17487/RFC2978, + October 2000, <http://www.rfc-editor.org/info/rfc2978>. + + [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", STD 63, RFC 3629, DOI 10.17487/RFC3629, November + 2003, <http://www.rfc-editor.org/info/rfc3629>. + + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, + RFC 3986, DOI 10.17487/RFC3986, January 2005, + <http://www.rfc-editor.org/info/rfc3986>. + + [RFC4648] Josefsson, S., "The Base16, Base32, and Base64 Data + Encodings", RFC 4648, DOI 10.17487/RFC4648, October 2006, + <http://www.rfc-editor.org/info/rfc4648>. + + [RFC5198] Klensin, J. and M. Padlipsky, "Unicode Format for Network + Interchange", RFC 5198, DOI 10.17487/RFC5198, March 2008, + <http://www.rfc-editor.org/info/rfc5198>. + + [RFC5234] Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", STD 68, RFC 5234, + DOI 10.17487/RFC5234, January 2008, + <http://www.rfc-editor.org/info/rfc5234>. + + [RFC6365] Hoffman, P. and J. Klensin, "Terminology Used in + Internationalization in the IETF", BCP 166, RFC 6365, + DOI 10.17487/RFC6365, September 2011, + <http://www.rfc-editor.org/info/rfc6365>. + + [RFC7235] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer + Protocol (HTTP/1.1): Authentication", RFC 7235, + DOI 10.17487/RFC7235, June 2014, + <http://www.rfc-editor.org/info/rfc7235>. + + + +Reschke Standards Track [Page 10] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + [RFC7613] Saint-Andre, P. and A. Melnikov, "Preparation, + Enforcement, and Comparison of Internationalized Strings + Representing Usernames and Passwords", RFC 7613, + DOI 10.17487/RFC7613, August 2015, + <http://www.rfc-editor.org/info/rfc7613>. + +6.2. Informative References + + [ISO-8859-1] + International Organization for Standardization, + "Information technology -- 8-bit single-byte coded graphic + character sets -- Part 1: Latin alphabet No. 1", ISO/IEC + 8859-1:1998, 1998. + + [RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., + Leach, P., Luotonen, A., and L. Stewart, "HTTP + Authentication: Basic and Digest Access Authentication", + RFC 2617, DOI 10.17487/RFC2617, June 1999, + <http://www.rfc-editor.org/info/rfc2617>. + + [RFC2818] Rescorla, E., "HTTP Over TLS", RFC 2818, + DOI 10.17487/RFC2818, May 2000, + <http://www.rfc-editor.org/info/rfc2818>. + + [RFC2831] Leach, P. and C. Newman, "Using Digest Authentication as a + SASL Mechanism", RFC 2831, DOI 10.17487/RFC2831, May 2000, + <http://www.rfc-editor.org/info/rfc2831>. + + [RFC3875] Robinson, D. and K. Coar, "The Common Gateway Interface + (CGI) Version 1.1", RFC 3875, DOI 10.17487/RFC3875, + October 2004, <http://www.rfc-editor.org/info/rfc3875>. + + [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer Security + (TLS) Protocol Version 1.2", RFC 5246, + DOI 10.17487/RFC5246, August 2008, + <http://www.rfc-editor.org/info/rfc5246>. + + [RFC6973] Cooper, A., Tschofenig, H., Aboba, B., Peterson, J., + Morris, J., Hansen, M., and R. Smith, "Privacy + Considerations for Internet Protocols", RFC 6973, + DOI 10.17487/RFC6973, July 2013, + <http://www.rfc-editor.org/info/rfc6973>. + + [RFC7231] Fielding, R., Ed. and J. Reschke, Ed., "Hypertext Transfer + Protocol (HTTP/1.1): Semantics and Content", RFC 7231, + DOI 10.17487/RFC7231, June 2014, + <http://www.rfc-editor.org/info/rfc7231>. + + + + +Reschke Standards Track [Page 11] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + + [RFC7615] Reschke, J., "HTTP Authentication-Info and Proxy- + Authentication-Info Response Header Fields", RFC 7615, + DOI 10.17487/RFC7615, September 2015, + <http://www.rfc-editor.org/info/rfc7615>. + + [RFC7616] Shekh-Yusef, R., Ed., Ahrens, D., and S. Bremer, "HTTP + Digest Access Authentication", RFC 7616, + DOI 10.17487/RFC7616, September 2015, + <http://www.rfc-editor.org/info/rfc7616>. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Reschke Standards Track [Page 12] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +Appendix A. Changes from RFC 2617 + + The scheme definition has been rewritten to be consistent with newer + specifications such as [RFC7235]. + + The new authentication parameter 'charset' has been added. It is + purely advisory, so existing implementations do not need to change, + unless they want to take advantage of the additional information that + previously wasn't available. + +Appendix B. Deployment Considerations for the 'charset' Parameter + +B.1. User Agents + + User agents not implementing 'charset' will continue to work as + before, ignoring the new parameter. + + User agents that already default to the UTF-8 encoding implement + 'charset' by definition. + + Other user agents can keep their default behavior and switch to UTF-8 + when seeing the new parameter. + +B.2. Servers + + Servers that do not support non-US-ASCII characters in credentials do + not require any changes to support 'charset'. + + Servers that need to support non-US-ASCII characters, but cannot use + the UTF-8 character encoding scheme will not be affected; they will + continue to function as well or as badly as before. + + Finally, servers that need to support non-US-ASCII characters and can + use the UTF-8 character encoding scheme can opt in by specifying the + 'charset' parameter in the authentication challenge. Clients that do + understand the 'charset' parameter will then start to use UTF-8, + while other clients will continue to send credentials in their + default encoding, broken credentials, or no credentials at all. + Until all clients are upgraded to support UTF-8, servers are likely + to see both UTF-8 and "legacy" encodings in requests. When + processing as UTF-8 fails (due to a failure to decode as UTF-8 or a + mismatch of user-id/password), a server might try a fallback to the + previously supported legacy encoding in order to accommodate these + legacy clients. Note that implicit retries need to be done + carefully; for instance, some subsystems might detect repeated login + failures and treat them as a potential credentials-guessing attack. + + + + + +Reschke Standards Track [Page 13] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +B.3. Why not simply switch the default encoding to UTF-8? + + There are sites in use today that default to a local character + encoding scheme, such as ISO-8859-1 ([ISO-8859-1]), and expect user + agents to use that encoding. Authentication on these sites will stop + working if the user agent switches to a different encoding, such as + UTF-8. + + Note that sites might even inspect the User-Agent header field + ([RFC7231], Section 5.5.3) to decide which character encoding scheme + to expect from the client. Therefore, they might support UTF-8 for + some user agents, but default to something else for others. User + agents in the latter group will have to continue to do what they do + today until the majority of these servers have been upgraded to + always use UTF-8. + +Acknowledgements + + This specification takes over the definition of the "Basic" HTTP + Authentication Scheme, previously defined in RFC 2617. We thank John + Franks, Phillip M. Hallam-Baker, Jeffery L. Hostetler, Scott + D. Lawrence, Paul J. Leach, Ari Luotonen, and Lawrence C. Stewart for + their work on that specification, from which significant amounts of + text were borrowed. See Section 6 of [RFC2617] for further + acknowledgements. + + The internationalization problem with respect to the character + encoding scheme used for user-pass was reported as a Mozilla bug back + in the year 2000 (see + <https://bugzilla.mozilla.org/show_bug.cgi?id=41489> and also the + more recent <https://bugzilla.mozilla.org/show_bug.cgi?id=656213>). + It was Andrew Clover's idea to address it using a new auth-param. + + We also thank the members of the HTTPAUTH Working Group and other + reviewers, namely, Stephen Farrell, Roy Fielding, Daniel Kahn + Gillmor, Tony Hansen, Bjoern Hoehrmann, Kari Hurtta, Amos Jeffries, + Benjamin Kaduk, Michael Koeller, Eric Lawrence, Barry Leiba, James + Manger, Alexey Melnikov, Kathleen Moriarty, Juergen Schoenwaelder, + Yaron Sheffer, Meral Shirazipour, Michael Sweet, and Martin Thomson + for feedback on this revision. + + + + + + + + + + + +Reschke Standards Track [Page 14] + +RFC 7617 'Basic' HTTP Authentication Scheme September 2015 + + +Author's Address + + Julian F. Reschke + greenbytes GmbH + Hafenweg 16 + Muenster, NW 48155 + Germany + + Email: julian.reschke@greenbytes.de + URI: http://greenbytes.de/tech/webdav/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Reschke Standards Track [Page 15] + diff --git a/conformance/specs/rfc/rfc9110.xml b/conformance/specs/rfc/rfc9110.xml new file mode 100644 index 0000000..52e5f6b --- /dev/null +++ b/conformance/specs/rfc/rfc9110.xml @@ -0,0 +1,18156 @@ +<?xml version='1.0' encoding='utf-8'?> +<rfc xmlns:xi="http://www.w3.org/2001/XInclude" version="3" category="std" consensus="true" docName="draft-ietf-httpbis-semantics-19" indexInclude="true" ipr="pre5378Trust200902" number="9110" obsoletes="2818, 7230, 7231, 7232, 7233, 7235, 7538, 7615, 7694" prepTime="2022-06-06T11:05:59" scripts="Common,Latin" sortRefs="true" submissionType="IETF" symRefs="true" tocDepth="4" tocInclude="true" updates="3864" xml:lang="en"> + <link href="https://datatracker.ietf.org/doc/draft-ietf-httpbis-semantics-19" rel="prev"/> + <link href="https://dx.doi.org/10.17487/rfc9110" rel="alternate"/> + <link href="urn:issn:2070-1721" rel="alternate"/> + <front> + <title>HTTP Semantics + + + + Adobe +
+ + 345 Park Ave + San Jose, CA 95110 + United States of America + + fielding@gbiv.com + https://roy.gbiv.com/ +
+
+ + Fastly +
+ + Prahran + Australia + + mnot@mnot.net + https://www.mnot.net/ +
+
+ + greenbytes GmbH +
+ + Hafenweg 16 + 48155 Münster + Germany + + julian.reschke@greenbytes.de + https://greenbytes.de/tech/webdav/ +
+
+ + Applications and Real-Time + HTTP Working Group + Hypertext Transfer Protocol + HTTP + HTTP semantics + HTTP content + HTTP method + HTTP status code + + + The Hypertext Transfer Protocol (HTTP) is a stateless application-level + protocol for distributed, collaborative, hypertext information systems. + This document describes the overall architecture of HTTP, establishes common + terminology, and defines aspects of the protocol that are shared by all + versions. In this definition are core protocol elements, extensibility + mechanisms, and the "http" and "https" Uniform Resource Identifier (URI) + schemes. + + + This document updates RFC 3864 and + obsoletes RFCs 2818, 7231, 7232, 7233, + 7235, 7538, 7615, 7694, and portions of 7230. + + + +
+ Status of This Memo + + This is an Internet Standards Track document. + + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by + the Internet Engineering Steering Group (IESG). Further + information on Internet Standards is available in Section 2 of + RFC 7841. + + + Information about the current status of this document, any + errata, and how to provide feedback on it may be obtained at + . + +
+
+ Copyright Notice + + Copyright (c) 2022 IETF Trust and the persons identified as the + document authors. All rights reserved. + + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + () in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with + respect to this document. Code Components extracted from this + document must include Revised BSD License text as described in + Section 4.e of the Trust Legal Provisions and are provided without + warranty as described in the Revised BSD License. + + + This document may contain material from IETF Documents or IETF + Contributions published or made publicly available before November + 10, 2008. The person(s) controlling the copyright in some of this + material may not have granted the IETF Trust the right to allow + modifications of such material outside the IETF Standards Process. + Without obtaining an adequate license from the person(s) + controlling the copyright in such materials, this document may not + be modified outside the IETF Standards Process, and derivative + works of it may not be created outside the IETF Standards Process, + except to format it for publication as an RFC or to translate it + into languages other than English. + +
+
+ +
+ Table of Contents +
    +
  • + .  Introduction +
      +
    • + .  Purpose +
    • +
    • + .  History and Evolution +
    • +
    • + .  Core Semantics +
    • +
    • + .  Specifications Obsoleted by This Document +
    • +
    +
  • +
  • + .  Conformance +
      +
    • + .  Syntax Notation +
    • +
    • + .  Requirements Notation +
    • +
    • + .  Length Requirements +
    • +
    • + .  Error Handling +
    • +
    • + .  Protocol Version +
    • +
    +
  • +
  • + .  Terminology and Core Concepts +
      +
    • + .  Resources +
    • +
    • + .  Representations +
    • +
    • + .  Connections, Clients, and Servers +
    • +
    • + .  Messages +
    • +
    • + .  User Agents +
    • +
    • + .  Origin Server +
    • +
    • + .  Intermediaries +
    • +
    • + .  Caches +
    • +
    • + .  Example Message Exchange +
    • +
    +
  • +
  • + .  Identifiers in HTTP +
      +
    • + .  URI References +
    • +
    • + .  HTTP-Related URI Schemes +
        +
      • + .  http URI Scheme +
      • +
      • + .  https URI Scheme +
      • +
      • + .  http(s) Normalization and Comparison +
      • +
      • + .  Deprecation of userinfo in http(s) URIs +
      • +
      • + .  http(s) References with Fragment Identifiers +
      • +
      +
    • +
    • + .  Authoritative Access +
        +
      • + .  URI Origin +
      • +
      • + .  http Origins +
      • +
      • + .  https Origins +
      • +
      • + .  https Certificate Verification +
      • +
      • + .  IP-ID Reference Identity +
      • +
      +
    • +
    +
  • +
  • + .  Fields +
      +
    • + .  Field Names +
    • +
    • + .  Field Lines and Combined Field Value +
    • +
    • + .  Field Order +
    • +
    • + .  Field Limits +
    • +
    • + .  Field Values +
    • +
    • + .  Common Rules for Defining Field Values +
        +
      • + .  Lists (#rule ABNF Extension) +
          +
        • + .  Sender Requirements +
        • +
        • + .  Recipient Requirements +
        • +
        +
      • +
      • + .  Tokens +
      • +
      • + .  Whitespace +
      • +
      • + .  Quoted Strings +
      • +
      • + .  Comments +
      • +
      • + .  Parameters +
      • +
      • + .  Date/Time Formats +
      • +
      +
    • +
    +
  • +
  • + .  Message Abstraction +
      +
    • + .  Framing and Completeness +
    • +
    • + .  Control Data +
    • +
    • + .  Header Fields +
    • +
    • + .  Content +
        +
      • + .  Content Semantics +
      • +
      • + .  Identifying Content +
      • +
      +
    • +
    • + .  Trailer Fields +
        +
      • + .  Limitations on Use of Trailers +
      • +
      • + .  Processing Trailer Fields +
      • +
      +
    • +
    • + .  Message Metadata +
        +
      • + .  Date +
      • +
      • + .  Trailer +
      • +
      +
    • +
    +
  • +
  • + .  Routing HTTP Messages +
      +
    • + .  Determining the Target Resource +
    • +
    • + .  Host and :authority +
    • +
    • + .  Routing Inbound Requests +
        +
      • + .  To a Cache +
      • +
      • + .  To a Proxy +
      • +
      • + .  To the Origin +
      • +
      +
    • +
    • + .  Rejecting Misdirected Requests +
    • +
    • + .  Response Correlation +
    • +
    • + .  Message Forwarding +
        +
      • + .  Connection +
      • +
      • + .  Max-Forwards +
      • +
      • + .  Via +
      • +
      +
    • +
    • + .  Message Transformations +
    • +
    • + .  Upgrade +
    • +
    +
  • +
  • + .  Representation Data and Metadata +
      +
    • + .  Representation Data +
    • +
    • + .  Representation Metadata +
    • +
    • + .  Content-Type +
        +
      • + .  Media Type +
      • +
      • + .  Charset +
      • +
      • + .  Multipart Types +
      • +
      +
    • +
    • + .  Content-Encoding +
        +
      • + .  Content Codings +
          +
        • + .  Compress Coding +
        • +
        • + .  Deflate Coding +
        • +
        • + .  Gzip Coding +
        • +
        +
      • +
      +
    • +
    • + .  Content-Language +
        +
      • + .  Language Tags +
      • +
      +
    • +
    • + .  Content-Length +
    • +
    • + .  Content-Location +
    • +
    • + .  Validator Fields +
        +
      • + .  Weak versus Strong +
      • +
      • + .  Last-Modified +
          +
        • + .  Generation +
        • +
        • + .  Comparison +
        • +
        +
      • +
      • + .  ETag +
          +
        • + .  Generation +
        • +
        • + .  Comparison +
        • +
        • + .  Example: Entity Tags Varying on Content-Negotiated Resources +
        • +
        +
      • +
      +
    • +
    +
  • +
  • + .  Methods +
      +
    • + .  Overview +
    • +
    • + .  Common Method Properties +
        +
      • + .  Safe Methods +
      • +
      • + .  Idempotent Methods +
      • +
      • + .  Methods and Caching +
      • +
      +
    • +
    • + .  Method Definitions +
        +
      • + .  GET +
      • +
      • + .  HEAD +
      • +
      • + .  POST +
      • +
      • + .  PUT +
      • +
      • + .  DELETE +
      • +
      • + .  CONNECT +
      • +
      • + .  OPTIONS +
      • +
      • + .  TRACE +
      • +
      +
    • +
    +
  • +
  • + . Message Context +
      +
    • + .  Request Context Fields +
        +
      • + .  Expect +
      • +
      • + .  From +
      • +
      • + .  Referer +
      • +
      • + .  TE +
      • +
      • + .  User-Agent +
      • +
      +
    • +
    • + .  Response Context Fields +
        +
      • + .  Allow +
      • +
      • + .  Location +
      • +
      • + .  Retry-After +
      • +
      • + .  Server +
      • +
      +
    • +
    +
  • +
  • + . HTTP Authentication +
      +
    • + .  Authentication Scheme +
    • +
    • + .  Authentication Parameters +
    • +
    • + .  Challenge and Response +
    • +
    • + .  Credentials +
    • +
    • + .  Establishing a Protection Space (Realm) +
    • +
    • + .  Authenticating Users to Origin Servers +
        +
      • + .  WWW-Authenticate +
      • +
      • + .  Authorization +
      • +
      • + .  Authentication-Info +
      • +
      +
    • +
    • + .  Authenticating Clients to Proxies +
        +
      • + .  Proxy-Authenticate +
      • +
      • + .  Proxy-Authorization +
      • +
      • + .  Proxy-Authentication-Info +
      • +
      +
    • +
    +
  • +
  • + . Content Negotiation +
      +
    • + .  Proactive Negotiation +
    • +
    • + .  Reactive Negotiation +
    • +
    • + .  Request Content Negotiation +
    • +
    • + .  Content Negotiation Field Features +
        +
      • + .  Absence +
      • +
      • + .  Quality Values +
      • +
      • + .  Wildcard Values +
      • +
      +
    • +
    • + .  Content Negotiation Fields +
        +
      • + .  Accept +
      • +
      • + .  Accept-Charset +
      • +
      • + .  Accept-Encoding +
      • +
      • + .  Accept-Language +
      • +
      • + .  Vary +
      • +
      +
    • +
    +
  • +
  • + . Conditional Requests +
      +
    • + .  Preconditions +
        +
      • + .  If-Match +
      • +
      • + .  If-None-Match +
      • +
      • + .  If-Modified-Since +
      • +
      • + .  If-Unmodified-Since +
      • +
      • + .  If-Range +
      • +
      +
    • +
    • + .  Evaluation of Preconditions +
        +
      • + .  When to Evaluate +
      • +
      • + .  Precedence of Preconditions +
      • +
      +
    • +
    +
  • +
  • + . Range Requests +
      +
    • + .  Range Units +
        +
      • + .  Range Specifiers +
      • +
      • + .  Byte Ranges +
      • +
      +
    • +
    • + .  Range +
    • +
    • + .  Accept-Ranges +
    • +
    • + .  Content-Range +
    • +
    • + .  Partial PUT +
    • +
    • + .  Media Type multipart/byteranges +
    • +
    +
  • +
  • + . Status Codes +
      +
    • + .  Overview of Status Codes +
    • +
    • + .  Informational 1xx +
        +
      • + .  100 Continue +
      • +
      • + .  101 Switching Protocols +
      • +
      +
    • +
    • + .  Successful 2xx +
        +
      • + .  200 OK +
      • +
      • + .  201 Created +
      • +
      • + .  202 Accepted +
      • +
      • + .  203 Non-Authoritative Information +
      • +
      • + .  204 No Content +
      • +
      • + .  205 Reset Content +
      • +
      • + .  206 Partial Content +
          +
        • + .  Single Part +
        • +
        • + .  Multiple Parts +
        • +
        • + .  Combining Parts +
        • +
        +
      • +
      +
    • +
    • + .  Redirection 3xx +
        +
      • + .  300 Multiple Choices +
      • +
      • + .  301 Moved Permanently +
      • +
      • + .  302 Found +
      • +
      • + .  303 See Other +
      • +
      • + .  304 Not Modified +
      • +
      • + .  305 Use Proxy +
      • +
      • + .  306 (Unused) +
      • +
      • + .  307 Temporary Redirect +
      • +
      • + .  308 Permanent Redirect +
      • +
      +
    • +
    • + .  Client Error 4xx +
        +
      • + .  400 Bad Request +
      • +
      • + .  401 Unauthorized +
      • +
      • + .  402 Payment Required +
      • +
      • + .  403 Forbidden +
      • +
      • + .  404 Not Found +
      • +
      • + .  405 Method Not Allowed +
      • +
      • + .  406 Not Acceptable +
      • +
      • + .  407 Proxy Authentication Required +
      • +
      • + .  408 Request Timeout +
      • +
      • + . 409 Conflict +
      • +
      • + . 410 Gone +
      • +
      • + . 411 Length Required +
      • +
      • + . 412 Precondition Failed +
      • +
      • + . 413 Content Too Large +
      • +
      • + . 414 URI Too Long +
      • +
      • + . 415 Unsupported Media Type +
      • +
      • + . 416 Range Not Satisfiable +
      • +
      • + . 417 Expectation Failed +
      • +
      • + . 418 (Unused) +
      • +
      • + . 421 Misdirected Request +
      • +
      • + . 422 Unprocessable Content +
      • +
      • + . 426 Upgrade Required +
      • +
      +
    • +
    • + .  Server Error 5xx +
        +
      • + .  500 Internal Server Error +
      • +
      • + .  501 Not Implemented +
      • +
      • + .  502 Bad Gateway +
      • +
      • + .  503 Service Unavailable +
      • +
      • + .  504 Gateway Timeout +
      • +
      • + .  505 HTTP Version Not Supported +
      • +
      +
    • +
    +
  • +
  • + . Extending HTTP +
      +
    • + .  Method Extensibility +
        +
      • + .  Method Registry +
      • +
      • + .  Considerations for New Methods +
      • +
      +
    • +
    • + .  Status Code Extensibility +
        +
      • + .  Status Code Registry +
      • +
      • + .  Considerations for New Status Codes +
      • +
      +
    • +
    • + .  Field Extensibility +
        +
      • + .  Field Name Registry +
      • +
      • + .  Considerations for New Fields +
          +
        • + .  Considerations for New Field Names +
        • +
        • + .  Considerations for New Field Values +
        • +
        +
      • +
      +
    • +
    • + .  Authentication Scheme Extensibility +
        +
      • + .  Authentication Scheme Registry +
      • +
      • + .  Considerations for New Authentication Schemes +
      • +
      +
    • +
    • + .  Range Unit Extensibility +
        +
      • + .  Range Unit Registry +
      • +
      • + .  Considerations for New Range Units +
      • +
      +
    • +
    • + .  Content Coding Extensibility +
        +
      • + .  Content Coding Registry +
      • +
      • + .  Considerations for New Content Codings +
      • +
      +
    • +
    • + .  Upgrade Token Registry +
    • +
    +
  • +
  • + . Security Considerations +
      +
    • + .  Establishing Authority +
    • +
    • + .  Risks of Intermediaries +
    • +
    • + .  Attacks Based on File and Path Names +
    • +
    • + .  Attacks Based on Command, Code, or Query Injection +
    • +
    • + .  Attacks via Protocol Element Length +
    • +
    • + .  Attacks Using Shared-Dictionary Compression +
    • +
    • + .  Disclosure of Personal Information +
    • +
    • + .  Privacy of Server Log Information +
    • +
    • + .  Disclosure of Sensitive Information in URIs +
    • +
    • + . Application Handling of Field Names +
    • +
    • + . Disclosure of Fragment after Redirects +
    • +
    • + . Disclosure of Product Information +
    • +
    • + . Browser Fingerprinting +
    • +
    • + . Validator Retention +
    • +
    • + . Denial-of-Service Attacks Using Range +
    • +
    • + . Authentication Considerations +
        +
      • + .  Confidentiality of Credentials +
      • +
      • + .  Credentials and Idle Clients +
      • +
      • + .  Protection Spaces +
      • +
      • + .  Additional Response Fields +
      • +
      +
    • +
    +
  • +
  • + . IANA Considerations +
      +
    • + .  URI Scheme Registration +
    • +
    • + .  Method Registration +
    • +
    • + .  Status Code Registration +
    • +
    • + .  Field Name Registration +
    • +
    • + .  Authentication Scheme Registration +
    • +
    • + .  Content Coding Registration +
    • +
    • + .  Range Unit Registration +
    • +
    • + .  Media Type Registration +
    • +
    • + .  Port Registration +
    • +
    • + . Upgrade Token Registration +
    • +
    +
  • +
  • + . References +
      +
    • + .  Normative References +
    • +
    • + .  Informative References +
    • +
    +
  • +
  • + .  Collected ABNF +
  • +
  • + .  Changes from Previous RFCs +
      +
    • + .  Changes from RFC 2818 +
    • +
    • + .  Changes from RFC 7230 +
    • +
    • + .  Changes from RFC 7231 +
    • +
    • + .  Changes from RFC 7232 +
    • +
    • + .  Changes from RFC 7233 +
    • +
    • + .  Changes from RFC 7235 +
    • +
    • + .  Changes from RFC 7538 +
    • +
    • + .  Changes from RFC 7615 +
    • +
    • + .  Changes from RFC 7694 +
    • +
    +
  • +
  • + Acknowledgements +
  • +
  • + Index +
  • +
  • + Authors' Addresses +
  • +
+
+
+ + +
+ Introduction +
+ Purpose + + The Hypertext Transfer Protocol (HTTP) is a family of stateless, + application-level, request/response protocols that share a generic interface, + extensible semantics, and self-descriptive messages to enable flexible + interaction with network-based hypertext information systems. + + + HTTP hides the details of how a service is implemented by presenting a + uniform interface to clients that is independent of the types of resources + provided. Likewise, servers do not need to be aware of each client's + purpose: a request can be considered in isolation rather than being + associated with a specific type of client or a predetermined sequence of + application steps. This allows general-purpose implementations to be used + effectively in many different contexts, reduces interaction complexity, and + enables independent evolution over time. + + + HTTP is also designed for use as an intermediation protocol, wherein + proxies and gateways can translate non-HTTP information systems into a + more generic interface. + + + One consequence of this flexibility is that the protocol cannot be + defined in terms of what occurs behind the interface. Instead, we + are limited to defining the syntax of communication, the intent + of received communication, and the expected behavior of recipients. + If the communication is considered in isolation, then successful + actions ought to be reflected in corresponding changes to the + observable interface provided by servers. However, since multiple + clients might act in parallel and perhaps at cross-purposes, we + cannot require that such changes be observable beyond the scope + of a single response. + +
+
+ History and Evolution + + HTTP has been the primary information transfer protocol for the World + Wide Web since its introduction in 1990. It began as a trivial + mechanism for low-latency requests, with a single method (GET) to + request transfer of a presumed hypertext document identified by a given pathname. + As the Web grew, HTTP was extended to enclose requests and responses within + messages, transfer arbitrary data formats using MIME-like media types, and + route requests through intermediaries. These protocols were eventually + defined as HTTP/0.9 and HTTP/1.0 (see ). + + + HTTP/1.1 was designed to refine the protocol's features while retaining + compatibility with the existing text-based messaging syntax, improving + its interoperability, scalability, and robustness across the Internet. + This included length-based data delimiters for both fixed and dynamic + (chunked) content, a consistent framework for content negotiation, + opaque validators for conditional requests, cache controls for better + cache consistency, range requests for partial updates, and default + persistent connections. HTTP/1.1 was introduced in 1995 and published on + the Standards Track in 1997 , revised in + 1999 , and revised again in 2014 + ( through ). + + + HTTP/2 () introduced a multiplexed session layer + on top of the existing TLS and TCP protocols for exchanging concurrent + HTTP messages with efficient field compression and server push. + HTTP/3 () provides greater independence for concurrent + messages by using QUIC as a secure multiplexed transport over UDP instead of + TCP. + + + All three major versions of HTTP rely on the semantics defined by + this document. They have not obsoleted each other because each one has + specific benefits and limitations depending on the context of use. + Implementations are expected to choose the most appropriate transport and + messaging syntax for their particular context. + + + This revision of HTTP separates the definition of semantics (this document) + and caching () from the current HTTP/1.1 messaging + syntax () to allow each major protocol version + to progress independently while referring to the same core semantics. + +
+
+ Core Semantics + + HTTP provides a uniform interface for interacting with a resource + () -- regardless of its type, nature, or + implementation -- by sending messages that manipulate or transfer + representations (). + + + Each message is either a request or a response. A client constructs request + messages that communicate its intentions and routes those messages toward + an identified origin server. A server listens for requests, parses each + message received, interprets the message semantics in relation to the + identified target resource, and responds to that request with one or more + response messages. The client examines received responses to see if its + intentions were carried out, determining what to do next based on the + status codes and content received. + + + HTTP semantics include the intentions defined by each request method + (), extensions to those semantics that might be + described in request header fields, + status codes that describe the response (), and + other control data and resource metadata that might be given in response + fields. + + + + Semantics also include representation metadata that describe how + content is intended to be interpreted by a recipient, request header + fields that might influence content selection, and the various selection + algorithms that are collectively referred to as + "content negotiation" (). + +
+
+ Specifications Obsoleted by This Document + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TitleReferenceSee
HTTP Over TLS + + + +
HTTP/1.1 Message Syntax and Routing [*] + + + +
HTTP/1.1 Semantics and Content + + + +
HTTP/1.1 Conditional Requests + + + +
HTTP/1.1 Range Requests + + + +
HTTP/1.1 Authentication + + + +
HTTP Status Code 308 (Permanent Redirect) + + + +
HTTP Authentication-Info and Proxy-Authentication-Info + Response Header Fields + + + +
HTTP Client-Initiated Content-Encoding + + + +
+ + [*] This document only obsoletes the portions of + RFC 7230 that are independent of + the HTTP/1.1 messaging syntax and connection management; the remaining + bits of RFC 7230 are + obsoleted by "HTTP/1.1" . + +
+
+
+ Conformance +
+ Syntax Notation + + + + + + + + + + + + + + This specification uses the Augmented Backus-Naur Form (ABNF) notation of + , extended with the notation for case-sensitivity + in strings defined in . + + + It also uses a list extension, defined in , + that allows for compact definition of comma-separated lists using a "#" + operator (similar to how the "*" operator indicates repetition). shows the collected grammar with all list + operators expanded to standard ABNF notation. + + + As a convention, ABNF rule names prefixed with "obs-" denote + obsolete grammar rules that appear for historical reasons. + + + + + + + + + + + + + + + The following core rules are included by + reference, as defined in : + ALPHA (letters), CR (carriage return), CRLF (CR LF), CTL (controls), + DIGIT (decimal 0-9), DQUOTE (double quote), + HEXDIG (hexadecimal 0-9/A-F/a-f), HTAB (horizontal tab), LF (line feed), + OCTET (any 8-bit sequence of data), SP (space), and + VCHAR (any visible US-ASCII character). + + + defines some generic syntactic + components for field values. + + + This specification uses the terms + "character", + "character encoding scheme", + "charset", and + "protocol element" + as they are defined in . + +
+
+ Requirements Notation + + The key words "MUST", "MUST NOT", + "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", + "RECOMMENDED", "NOT RECOMMENDED", + "MAY", and "OPTIONAL" in this document are to be + interpreted as described in BCP 14 when, and only when, they appear in all capitals, as + shown here. + + + This specification targets conformance criteria according to the role of + a participant in HTTP communication. Hence, requirements are placed + on senders, recipients, clients, servers, user agents, intermediaries, + origin servers, proxies, gateways, or caches, depending on what behavior + is being constrained by the requirement. Additional requirements + are placed on implementations, resource owners, and protocol element + registrations when they apply beyond the scope of a single communication. + + + The verb "generate" is used instead of "send" where a requirement applies + only to implementations that create the protocol element, rather than an + implementation that forwards a received element downstream. + + + An implementation is considered conformant if it complies with all of the + requirements associated with the roles it partakes in HTTP. + + + A sender MUST NOT generate protocol elements that do not match the grammar + defined by the corresponding ABNF rules. + Within a given message, a sender MUST NOT generate protocol elements or + syntax alternatives that are only allowed to be generated by participants in + other roles (i.e., a role that the sender does not have for that message). + + + Conformance to HTTP includes both conformance to the particular messaging + syntax of the protocol version in use and conformance to the semantics of + protocol elements sent. For example, a client that claims conformance to + HTTP/1.1 but fails to recognize the features required of HTTP/1.1 + recipients will fail to interoperate with servers that adjust their + responses in accordance with those claims. + Features that reflect user choices, such as content negotiation and + user-selected extensions, can impact application behavior beyond the + protocol stream; sending protocol elements that inaccurately reflect a + user's choices will confuse the user and inhibit choice. + + + When an implementation fails semantic conformance, recipients of that + implementation's messages will eventually develop workarounds to adjust + their behavior accordingly. A recipient MAY employ such workarounds while + remaining conformant to this protocol if the workarounds are limited to the + implementations at fault. For example, servers often scan portions of the + User-Agent field value, and user agents often scan the Server field value, + to adjust their own behavior with respect to known bugs or poorly chosen + defaults. + +
+
+ Length Requirements + + A recipient SHOULD parse a received protocol element defensively, with + only marginal expectations that the element will conform to its ABNF + grammar and fit within a reasonable buffer size. + + + HTTP does not have specific length limitations for many of its protocol + elements because the lengths that might be appropriate will vary widely, + depending on the deployment context and purpose of the implementation. + Hence, interoperability between senders and recipients depends on shared + expectations regarding what is a reasonable length for each protocol + element. Furthermore, what is commonly understood to be a reasonable length + for some protocol elements has changed over the course of the past three + decades of HTTP use and is expected to continue changing in the future. + + + At a minimum, a recipient MUST be able to parse and process protocol + element lengths that are at least as long as the values that it generates + for those same protocol elements in other messages. For example, an origin + server that publishes very long URI references to its own resources needs + to be able to parse and process those same references when received as a + target URI. + + + Many received protocol elements are only parsed to the extent necessary to + identify and forward that element downstream. For example, an intermediary + might parse a received field into its field name and field value components, + but then forward the field without further parsing inside the field value. + +
+
+ Error Handling + + A recipient MUST interpret a received protocol element according to the + semantics defined for it by this specification, including extensions to + this specification, unless the recipient has determined (through experience + or configuration) that the sender incorrectly implements what is implied by + those semantics. + For example, an origin server might disregard the contents of a received + Accept-Encoding header field if inspection of the + User-Agent header field indicates a specific implementation + version that is known to fail on receipt of certain content codings. + + + Unless noted otherwise, a recipient MAY attempt to recover a usable + protocol element from an invalid construct. HTTP does not define + specific error handling mechanisms except when they have a direct impact + on security, since different applications of the protocol require + different error handling strategies. For example, a Web browser might + wish to transparently recover from a response where the + Location header field doesn't parse according to the ABNF, + whereas a systems control client might consider any form of error recovery + to be dangerous. + + + Some requests can be automatically retried by a client in the event of + an underlying connection failure, as described in + . + +
+
+ Protocol Version + + HTTP's version number consists of two decimal digits separated by a "." + (period or decimal point). The first digit (major version) indicates the + messaging syntax, whereas the second digit (minor version) + indicates the highest minor version within that major version to which the + sender is conformant (able to understand for future communication). + + + While HTTP's core semantics don't change between protocol versions, their + expression "on the wire" can change, and so the + HTTP version number changes when incompatible changes are made to the wire + format. Additionally, HTTP allows incremental, backwards-compatible + changes to be made to the protocol without changing its version through + the use of defined extension points (). + + + The protocol version as a whole indicates the sender's conformance with + the set of requirements laid out in that version's corresponding + specification(s). + For example, the version "HTTP/1.1" is defined by the combined + specifications of this document, "HTTP Caching" , + and "HTTP/1.1" . + + + HTTP's major version number is incremented when an incompatible message + syntax is introduced. The minor number is incremented when changes made to + the protocol have the effect of adding to the message semantics or + implying additional capabilities of the sender. + + + The minor version advertises the sender's communication capabilities even + when the sender is only using a backwards-compatible subset of the + protocol, thereby letting the recipient know that more advanced features + can be used in response (by servers) or in future requests (by clients). + + + When a major version of HTTP does not define any minor versions, the minor + version "0" is implied. The "0" is used when referring to that protocol + within elements that require a minor version identifier. + +
+
+
+ Terminology and Core Concepts + + HTTP was created for the World Wide Web (WWW) architecture + and has evolved over time to support the scalability needs of a worldwide + hypertext system. Much of that architecture is reflected in the terminology + used to define HTTP. + +
+ Resources + + + The target of an HTTP request is called a "resource". + HTTP does not limit the nature of a resource; it merely + defines an interface that might be used to interact with resources. + Most resources are identified by a Uniform Resource Identifier (URI), as + described in . + + + One design goal of HTTP is to separate resource identification from + request semantics, which is made possible by vesting the request + semantics in the request method () and a few + request-modifying header fields. + A resource cannot treat a request in a manner inconsistent with the + semantics of the method of the request. For example, though the URI of a + resource might imply semantics that are not safe, a client can expect the + resource to avoid actions that are unsafe when processing a request with a + safe method (see ). + + + HTTP relies upon the Uniform Resource Identifier (URI) + standard to indicate the target resource + () and relationships between resources. + +
+
+ Representations + + + A "representation" is information + that is intended to reflect a past, current, or desired state of a given + resource, in a format that can be readily communicated via the protocol. + A representation consists of a set of representation metadata and a + potentially unbounded stream of representation data + (). + + + HTTP allows "information hiding" behind its uniform interface by defining + communication with respect to a transferable representation of the resource + state, rather than transferring the resource itself. This allows the + resource identified by a URI to be anything, including temporal functions + like "the current weather in Laguna Beach", while potentially providing + information that represents that resource at the time a message is + generated . + + + The uniform interface is similar to a window through which one can observe + and act upon a thing only through the communication of messages to an + independent actor on the other side. A shared abstraction is needed to + represent ("take the place of") the current or desired state of that thing + in our communications. When a representation is hypertext, it can provide + both a representation of the resource state and processing instructions + that help guide the recipient's future interactions. + + + + A target resource might be provided with, or be capable of + generating, multiple representations that are each intended to reflect the + resource's current state. An algorithm, usually based on + content negotiation (), + would be used to select one of those representations as being most + applicable to a given request. + This "selected representation" provides the data and metadata + for evaluating conditional requests () + and constructing the content for 200 (OK), + 206 (Partial Content), and + 304 (Not Modified) responses to GET (). + +
+
+ Connections, Clients, and Servers + + + + + HTTP is a client/server protocol that operates over a reliable + transport- or session-layer "connection". + + + An HTTP "client" is a program that establishes a connection + to a server for the purpose of sending one or more HTTP requests. + An HTTP "server" is a program that accepts connections + in order to service HTTP requests by sending HTTP responses. + + + The terms client and server refer only to the roles that + these programs perform for a particular connection. The same program + might act as a client on some connections and a server on others. + + + HTTP is defined as a stateless protocol, meaning that each request message's semantics + can be understood in isolation, and that the relationship between connections + and messages on them has no impact on the interpretation of those messages. + For example, a CONNECT request () or a request with + the Upgrade header field () can occur at any time, + not just in the first message on a connection. Many implementations depend on + HTTP's stateless design in order to reuse proxied connections or dynamically + load balance requests across multiple servers. + + + As a result, a server MUST NOT + assume that two requests on the same connection are from the same user + agent unless the connection is secured and specific to that agent. + Some non-standard HTTP extensions (e.g., ) have + been known to violate this requirement, resulting in security and + interoperability problems. + +
+
+ Messages + + + + + + + + HTTP is a stateless request/response protocol for exchanging + "messages" across a connection. + The terms "sender" and "recipient" refer to + any implementation that sends or receives a given message, respectively. + + + A client sends requests to a server in the form of a "request" + message with a method () and request target + (). The request might also contain + header fields () for request modifiers, + client information, and representation metadata, + content () intended for processing + in accordance with the method, and + trailer fields () to communicate information + collected while sending the content. + + + A server responds to a client's request by sending one or more + "response" messages, each including a status + code (). The response might also contain + header fields for server information, resource metadata, and representation + metadata, content to be interpreted in accordance with the status + code, and trailer fields to communicate information + collected while sending the content. + +
+
+ User Agents + + + + + The term "user agent" refers to any of the various + client programs that initiate a request. + + + The most familiar form of user agent is the general-purpose Web browser, but + that's only a small percentage of implementations. Other common user agents + include spiders (web-traversing robots), command-line tools, billboard + screens, household appliances, scales, light bulbs, firmware update scripts, + mobile apps, and communication devices in a multitude of shapes and sizes. + + + Being a user agent does not imply that there is a human user directly + interacting with the software agent at the time of a request. In many + cases, a user agent is installed or configured to run in the background + and save its results for later inspection (or save only a subset of those + results that might be interesting or erroneous). Spiders, for example, are + typically given a start URI and configured to follow certain behavior while + crawling the Web as a hypertext graph. + + + Many user agents cannot, or choose not to, + make interactive suggestions to their user or provide adequate warning for + security or privacy concerns. In the few cases where this + specification requires reporting of errors to the user, it is acceptable + for such reporting to only be observable in an error console or log file. + Likewise, requirements that an automated action be confirmed by the user + before proceeding might be met via advance configuration choices, + run-time options, or simple avoidance of the unsafe action; confirmation + does not imply any specific user interface or interruption of normal + processing if the user has already made that choice. + +
+
+ Origin Server + + + The term "origin server" refers to a program that can + originate authoritative responses for a given target resource. + + + The most familiar form of origin server are large public websites. + However, like user agents being equated with browsers, it is easy to be + misled into thinking that all origin servers are alike. + Common origin servers also include home automation units, configurable + networking components, office machines, autonomous robots, news feeds, + traffic cameras, real-time ad selectors, and video-on-demand platforms. + + + Most HTTP communication consists of a retrieval request (GET) for + a representation of some resource identified by a URI. In the + simplest case, this might be accomplished via a single bidirectional + connection (===) between the user agent (UA) and the origin server (O). + +
+ + request > + UA ======================================= O + < response + +
+
+
+ Intermediaries + + + HTTP enables the use of intermediaries to satisfy requests through + a chain of connections. There are three common forms of HTTP + "intermediary": proxy, gateway, and tunnel. In some cases, + a single intermediary might act as an origin server, proxy, gateway, + or tunnel, switching behavior based on the nature of each request. + +
+ + > > > > + UA =========== A =========== B =========== C =========== O + < < < < + +
+ + The figure above shows three intermediaries (A, B, and C) between the + user agent and origin server. A request or response message that + travels the whole chain will pass through four separate connections. + Some HTTP communication options + might apply only to the connection with the nearest, non-tunnel + neighbor, only to the endpoints of the chain, or to all connections + along the chain. Although the diagram is linear, each participant might + be engaged in multiple, simultaneous communications. For example, B + might be receiving requests from many clients other than A, and/or + forwarding requests to servers other than C, at the same time that it + is handling A's request. Likewise, later requests might be sent through a + different path of connections, often based on dynamic configuration for + load balancing. + + + + + + + The terms "upstream" and "downstream" are + used to describe directional requirements in relation to the message flow: + all messages flow from upstream to downstream. + The terms "inbound" and "outbound" are used to describe directional + requirements in relation to the request route: + inbound means "toward the origin server", whereas + outbound means "toward the user agent". + + + + A "proxy" is a message-forwarding agent that is chosen by the + client, usually via local configuration rules, to receive requests + for some type(s) of absolute URI and attempt to satisfy those + requests via translation through the HTTP interface. Some translations + are minimal, such as for proxy requests for "http" URIs, whereas + other requests might require translation to and from entirely different + application-level protocols. Proxies are often used to group an + organization's HTTP requests through a common intermediary for the + sake of security services, annotation services, or shared caching. Some + proxies are designed to apply transformations to selected messages or + content while they are being forwarded, as described in + . + + + + + + A "gateway" (a.k.a. "reverse proxy") is an + intermediary that acts as an origin server for the outbound connection but + translates received requests and forwards them inbound to another server or + servers. Gateways are often used to encapsulate legacy or untrusted + information services, to improve server performance through + "accelerator" caching, and to enable partitioning or load + balancing of HTTP services across multiple machines. + + + All HTTP requirements applicable to an origin server + also apply to the outbound communication of a gateway. + A gateway communicates with inbound servers using any protocol that + it desires, including private extensions to HTTP that are outside + the scope of this specification. However, an HTTP-to-HTTP gateway + that wishes to interoperate with third-party HTTP servers needs to conform + to user agent requirements on the gateway's inbound connection. + + + + A "tunnel" acts as a blind relay between two connections + without changing the messages. Once active, a tunnel is not + considered a party to the HTTP communication, though the tunnel might + have been initiated by an HTTP request. A tunnel ceases to exist when + both ends of the relayed connection are closed. Tunnels are used to + extend a virtual connection through an intermediary, such as when + Transport Layer Security (TLS, ) is used to + establish confidential communication through a shared firewall proxy. + + + The above categories for intermediary only consider those acting as + participants in the HTTP communication. There are also intermediaries + that can act on lower layers of the network protocol stack, filtering or + redirecting HTTP traffic without the knowledge or permission of message + senders. Network intermediaries are indistinguishable (at a protocol level) + from an on-path attacker, often introducing security flaws or + interoperability problems due to mistakenly violating HTTP semantics. + + + + + For example, an "interception proxy" (also commonly + known as a "transparent proxy" ) + differs from an HTTP proxy because it is not chosen by the client. + Instead, an interception proxy filters or redirects outgoing TCP port 80 + packets (and occasionally other common port traffic). + Interception proxies are commonly found on public network access points, + as a means of enforcing account subscription prior to allowing use of + non-local Internet services, and within corporate firewalls to enforce + network usage policies. + +
+
+ Caches + + + A "cache" is a local store of previous response messages and the + subsystem that controls its message storage, retrieval, and deletion. + A cache stores cacheable responses in order to reduce the response + time and network bandwidth consumption on future, equivalent + requests. Any client or server MAY employ a cache, though a cache + cannot be used while acting as a tunnel. + + + The effect of a cache is that the request/response chain is shortened + if one of the participants along the chain has a cached response + applicable to that request. The following illustrates the resulting + chain if B has a cached copy of an earlier response from O (via C) + for a request that has not been cached by UA or A. + +
+ + > > + UA =========== A =========== B - - - - - - C - - - - - - O + < < + +
+ + + A response is "cacheable" if a cache is allowed to store a copy of + the response message for use in answering subsequent requests. + Even when a response is cacheable, there might be additional + constraints placed by the client or by the origin server on when + that cached response can be used for a particular request. HTTP + requirements for cache behavior and cacheable responses are + defined in . + + + There is a wide variety of architectures and configurations + of caches deployed across the World Wide Web and + inside large organizations. These include national hierarchies + of proxy caches to save bandwidth and reduce latency, content delivery + networks that use gateway caching to optimize regional and global distribution of popular sites, + collaborative systems that + broadcast or multicast cache entries, archives of pre-fetched cache + entries for use in off-line or high-latency environments, and so on. + +
+
+ Example Message Exchange + + The following example illustrates a typical HTTP/1.1 message exchange for a + GET request () on the URI "http://www.example.com/hello.txt": + + +Client request: + + GET /hello.txt HTTP/1.1 +User-Agent: curl/7.64.1 +Host: www.example.com +Accept-Language: en, mi + + + +Server response: + + HTTP/1.1 200 OK +Date: Mon, 27 Jul 2009 12:28:53 GMT +Server: Apache +Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT +ETag: "34aa387-d-1568eb00" +Accept-Ranges: bytes +Content-Length: 51 +Vary: Accept-Encoding +Content-Type: text/plain + +Hello World! My content includes a trailing CRLF. + +
+
+
+ Identifiers in HTTP + + + + Uniform Resource Identifiers (URIs) are used + throughout HTTP as the means for identifying resources (). + +
+ URI References + + + URI references are used to target requests, indicate redirects, and define + relationships. + + + The definitions of "URI-reference", + "absolute-URI", "relative-part", "authority", "port", "host", + "path-abempty", "segment", and "query" are adopted from the + URI generic syntax. + An "absolute-path" rule is defined for protocol elements that can contain a + non-empty path component. (This rule differs slightly from the path-abempty + rule of RFC 3986, which allows for an empty path, + and path-absolute rule, which does not allow paths that begin with "//".) + A "partial-URI" rule is defined for protocol elements + that can contain a relative URI but not a fragment component. + + + + + + + + + + + URI-reference = <URI-reference, see [URI], Section 4.1> + absolute-URI = <absolute-URI, see [URI], Section 4.3> + relative-part = <relative-part, see [URI], Section 4.2> + authority = <authority, see [URI], Section 3.2> + uri-host = <host, see [URI], Section 3.2.2> + port = <port, see [URI], Section 3.2.3> + path-abempty = <path-abempty, see [URI], Section 3.3> + segment = <segment, see [URI], Section 3.3> + query = <query, see [URI], Section 3.4> + + absolute-path = 1*( "/" segment ) + partial-URI = relative-part [ "?" query ] + + + Each protocol element in HTTP that allows a URI reference will indicate + in its ABNF production whether the element allows any form of reference + (URI-reference), only a URI in absolute form (absolute-URI), only the + path and optional query components (partial-URI), + or some combination of the above. + Unless otherwise indicated, URI references are parsed + relative to the target URI (). + + + It is RECOMMENDED that all senders and recipients support, at a minimum, + URIs with lengths of 8000 octets in protocol elements. Note that this + implies some structures and on-wire representations (for example, the + request line in HTTP/1.1) will necessarily be larger in some cases. + +
+
+ HTTP-Related URI Schemes + + IANA maintains the registry of URI Schemes at + . + Although requests might target any URI scheme, the following schemes are + inherent to HTTP servers: + + + + + + + + + + + + + + + + + + + + + +
URI SchemeDescriptionSection
httpHypertext Transfer Protocol + +
httpsHypertext Transfer Protocol Secure + +
+ + Note that the presence of an "http" or "https" URI does not imply that + there is always an HTTP server at the identified origin listening for + connections. Anyone can mint a URI, whether or not a server exists and + whether or not that server currently maps that identifier to a resource. + The delegated nature of registered names and IP addresses creates a + federated namespace whether or not an HTTP server is present. + +
+ http URI Scheme + + + + The "http" URI scheme is hereby defined for minting identifiers within the + hierarchical namespace governed by a potential HTTP origin server + listening for TCP () connections on a given port. + + + http-URI = "http" "://" authority path-abempty [ "?" query ] + + + The origin server for an "http" URI is identified by the + authority component, which includes a host identifier + () + and optional port number (). + If the port subcomponent is empty or not given, TCP port 80 (the + reserved port for WWW services) is the default. + The origin determines who has the right to respond authoritatively to + requests that target the identified resource, as defined in + . + + + A sender MUST NOT generate an "http" URI with an empty host identifier. + A recipient that processes such a URI reference MUST reject it as invalid. + + + The hierarchical path component and optional query component identify the + target resource within that origin server's namespace. + +
+
+ https URI Scheme + + + + + The "https" URI scheme is hereby defined for minting identifiers within the + hierarchical namespace governed by a potential origin server listening for + TCP connections on a given port and capable of establishing a TLS + () connection that has been secured for HTTP + communication. In this context, "secured" specifically + means that the server has been authenticated as acting on behalf of the + identified authority and all HTTP communication with that server has + confidentiality and integrity protection that is acceptable to both client + and server. + + + https-URI = "https" "://" authority path-abempty [ "?" query ] + + + The origin server for an "https" URI is identified by the + authority component, which includes a host identifier + () + and optional port number (). + If the port subcomponent is empty or not given, TCP port 443 + (the reserved port for HTTP over TLS) is the default. + The origin determines who has the right to respond authoritatively to + requests that target the identified resource, as defined in + . + + + A sender MUST NOT generate an "https" URI with an empty host identifier. + A recipient that processes such a URI reference MUST reject it as invalid. + + + The hierarchical path component and optional query component identify the + target resource within that origin server's namespace. + + + A client MUST ensure that its HTTP requests for an "https" resource are + secured, prior to being communicated, and that it only accepts secured + responses to those requests. Note that the definition of what cryptographic + mechanisms are acceptable to client and server are usually negotiated and + can change over time. + + + Resources made available via the "https" scheme have no shared identity + with the "http" scheme. They are distinct origins with separate namespaces. + However, extensions to HTTP that are defined as applying to all origins with + the same host, such as the Cookie protocol , + allow information set by one service to impact communication with other + services within a matching group of host domains. Such extensions ought to + be designed with great care to prevent information obtained from a secured + connection being inadvertently exchanged within an unsecured context. + +
+
+ http(s) Normalization and Comparison + + URIs with an "http" or "https" scheme are normalized and compared according to the + methods defined in , using + the defaults described above for each scheme. + + + HTTP does not require the use of a specific method for determining + equivalence. For example, a cache key might be compared as a simple + string, after syntax-based normalization, or after scheme-based + normalization. + + + Scheme-based normalization () of "http" and "https" URIs involves the following + additional rules: + +
    +
  • If the port is equal to the default port for a scheme, the normal form + is to omit the port subcomponent.
  • +
  • When not being used as the target of an OPTIONS request, an empty path + component is equivalent to an absolute path of "/", so the normal form is + to provide a path of "/" instead.
  • +
  • The scheme and host are case-insensitive and normally provided in + lowercase; all other components are compared in a case-sensitive + manner.
  • +
  • Characters other than those in the "reserved" set are equivalent to + their percent-encoded octets: the normal form is to not encode them (see + Sections and of ).
  • +
+ + For example, the following three URIs are equivalent: + + + http://example.com:80/~smith/home.html + http://EXAMPLE.com/%7Esmith/home.html + http://EXAMPLE.com:/%7esmith/home.html + + + Two HTTP URIs that are equivalent after normalization (using any method) + can be assumed to identify the same resource, and any HTTP component MAY + perform normalization. As a result, distinct resources SHOULD NOT be + identified by HTTP URIs that are equivalent after normalization (using any + method defined in ). + +
+
+ Deprecation of userinfo in http(s) URIs + + The URI generic syntax for authority also includes a userinfo subcomponent + () for including user + authentication information in the URI. In that subcomponent, the + use of the format "user:password" is deprecated. + + + Some implementations make use of the userinfo component for internal + configuration of authentication information, such as within command + invocation options, configuration files, or bookmark lists, even + though such usage might expose a user identifier or password. + + + A sender MUST NOT generate the userinfo subcomponent (and its "@" + delimiter) when an "http" or "https" URI reference is generated within a + message as a target URI or field value. + + + Before making use of an "http" or "https" URI reference received from an untrusted + source, a recipient SHOULD parse for userinfo and treat its presence as + an error; it is likely being used to obscure the authority for the sake of + phishing attacks. + +
+
+ http(s) References with Fragment Identifiers + + + Fragment identifiers allow for indirect identification + of a secondary resource, independent of the URI scheme, as defined in + . + Some protocol elements that refer to a URI allow inclusion of a fragment, + while others do not. They are distinguished by use of the ABNF rule for + elements where fragment is allowed; otherwise, a specific rule that excludes + fragments is used. + + +
+
+
+ Authoritative Access + + Authoritative access refers to dereferencing a given identifier, + for the sake of access to the identified resource, in a way that the client + believes is authoritative (controlled by the resource owner). The process + for determining whether access is granted is defined by the URI scheme and often uses + data within the URI components, such as the authority component when + the generic syntax is used. However, authoritative access is not limited to + the identified mechanism. + + + defines the concept of an origin as an aid to + such uses, and the subsequent subsections explain how to establish that a + peer has the authority to represent an origin. + + + See for security considerations + related to establishing authority. + +
+ URI Origin + + + + The "origin" for a given URI is the triple of scheme, host, + and port after normalizing the scheme and host to lowercase and + normalizing the port to remove any leading zeros. If port is elided from + the URI, the default port for that scheme is used. For example, the URI + + + https://Example.Com/happy.js + + + would have the origin + + + { "https", "example.com", "443" } + + + which can also be described as the normalized URI prefix with port always + present: + + + https://example.com:443 + + + Each origin defines its own namespace and controls how identifiers + within that namespace are mapped to resources. In turn, how the origin + responds to valid requests, consistently over time, determines the + semantics that users will associate with a URI, and the usefulness of + those semantics is what ultimately transforms these mechanisms into a + resource for users to reference and access in the future. + + + Two origins are distinct if they differ in scheme, host, or port. Even + when it can be verified that the same entity controls two distinct origins, + the two namespaces under those origins are distinct unless explicitly + aliased by a server authoritative for that origin. + + + Origin is also used within HTML and related Web protocols, beyond the + scope of this document, as described in . + +
+
+ http Origins + + Although HTTP is independent of the transport protocol, the "http" scheme + () is specific to associating authority with + whomever controls the origin + server listening for TCP connections on the indicated port of whatever + host is identified within the authority component. This is a very weak + sense of authority because it depends on both client-specific name + resolution mechanisms and communication that might not be secured from + an on-path attacker. Nevertheless, it is a sufficient minimum for + binding "http" identifiers to an origin server for consistent resolution + within a trusted environment. + + + If the host identifier is provided as an IP address, the origin server is + the listener (if any) on the indicated TCP port at that IP address. + If host is a registered name, the registered name is an indirect identifier + for use with a name resolution service, such as DNS, to find an address for + an appropriate origin server. + + + When an "http" URI is used within a context that calls for access to the + indicated resource, a client MAY attempt access by resolving the host + identifier to an IP address, establishing a TCP connection to that + address on the indicated port, and sending over that connection an HTTP + request message containing a request target that matches the client's + target URI (). + + + If the server responds to such a request with a non-interim HTTP response + message, as described in , then that response + is considered an authoritative answer to the client's request. + + + Note, however, that the above is not the only means for obtaining an + authoritative response, nor does it imply that an authoritative response + is always necessary (see ). + For example, the Alt-Svc header field allows an + origin server to identify other services that are also authoritative for + that origin. Access to "http" identified resources might also be provided + by protocols outside the scope of this document. + +
+
+ https Origins + + The "https" scheme () associates authority based + on the ability of a server to use the private key corresponding to a + certificate that the client considers to be trustworthy for the identified + origin server. The client usually relies upon a chain of trust, conveyed + from some prearranged or configured trust anchor, to deem a certificate + trustworthy (). + + + In HTTP/1.1 and earlier, a client will only attribute authority to a server + when they are communicating over a successfully established and secured + connection specifically to that URI origin's host. The connection + establishment and certificate verification are used as proof of authority. + + + In HTTP/2 and HTTP/3, a client will attribute authority to a server when + they are communicating over a successfully established and secured + connection if the URI origin's host matches any of the hosts present in the + server's certificate and the client believes that it could open a connection + to that host for that URI. In practice, a client will make a DNS query to + check that the origin's host contains the same server IP address as the + established connection. This restriction can be removed by the origin server + sending an equivalent ORIGIN frame . + + + The request target's host and port value are passed within each HTTP + request, identifying the origin and distinguishing it from other namespaces + that might be controlled by the same server (). + It is the origin's responsibility to ensure that any services provided with + control over its certificate's private key are equally responsible for + managing the corresponding "https" namespaces or at least prepared to + reject requests that appear to have been misdirected + (). + + + An origin server might be unwilling to process requests for certain target + URIs even when they have the authority to do so. For example, when a host + operates distinct services on different ports (e.g., 443 and 8000), checking + the target URI at the origin server is necessary (even after the connection + has been secured) because a network attacker might cause connections for one + port to be received at some other port. Failing to check the target URI + might allow such an attacker to replace a response to one target URI + (e.g., "https://example.com/foo") with a seemingly authoritative response + from the other port (e.g., "https://example.com:8000/foo"). + + + Note that the "https" scheme does not rely on TCP and the connected port + number for associating authority, since both are outside the secured + communication and thus cannot be trusted as definitive. Hence, the HTTP + communication might take place over any channel that has been secured, + as defined in , including protocols that don't + use TCP. + + + When an "https" URI is used within a context that calls for access to + the indicated resource, a client MAY attempt access by resolving the + host identifier to an IP address, establishing a TCP connection to that + address on the indicated port, securing the connection end-to-end by + successfully initiating TLS over TCP with confidentiality and integrity + protection, and sending over that connection an HTTP request message + containing a request target that matches the client's target URI + (). + + + If the server responds to such a request with a non-interim HTTP response + message, as described in , then that response + is considered an authoritative answer to the client's request. + + + Note, however, that the above is not the only means for obtaining an + authoritative response, nor does it imply that an authoritative response + is always necessary (see ). + +
+
+ https Certificate Verification + + To establish a secured connection to dereference a URI, + a client MUST verify that the service's identity is an acceptable + match for the URI's origin server. Certificate verification is used to + prevent server impersonation by an on-path attacker or by an attacker + that controls name resolution. This process requires that a client be + configured with a set of trust anchors. + + + In general, a client MUST verify the service identity using the + verification process defined in + . The client MUST construct + a reference identity from the service's host: if the host is a literal IP address + (), the reference identity is an IP-ID, otherwise + the host is a name and the reference identity is a DNS-ID. + + + A reference identity of type CN-ID MUST NOT be used by clients. As noted + in , a reference + identity of type CN-ID might be used by older clients. + + + A client might be specially configured to accept an alternative form of + server identity verification. For example, a client might be connecting + to a server whose address and hostname are dynamic, with an expectation that + the service will present a specific certificate (or a certificate matching + some externally defined reference identity) rather than one matching the + target URI's origin. + + + In special cases, it might be appropriate for + a client to simply ignore the server's identity, but it must be + understood that this leaves a connection open to active attack. + + + If the certificate is not valid for the target URI's origin, + a user agent MUST either obtain confirmation from the user + before proceeding (see ) or + terminate the connection with a bad certificate error. Automated + clients MUST log the error to an appropriate audit log (if available) + and SHOULD terminate the connection (with a bad certificate error). + Automated clients MAY provide a configuration setting that disables + this check, but MUST provide a setting which enables it. + +
+
+ IP-ID Reference Identity + + A server that is identified using an IP address literal in the "host" field + of an "https" URI has a reference identity of type IP-ID. An IP version 4 + address uses the "IPv4address" ABNF rule, and an IP version 6 address uses + the "IP-literal" production with the "IPv6address" option; see + . A reference identity of + IP-ID contains the decoded bytes of the IP address. + + + An IP version 4 address is 4 octets, and an IP version 6 address is 16 octets. + Use of IP-ID is not defined for any other IP version. The iPAddress + choice in the certificate subjectAltName extension does not explicitly + include the IP version and so relies on the length of the address to + distinguish versions; see + . + + + A reference identity of type IP-ID matches if the address is identical to + an iPAddress value of the subjectAltName extension of the certificate. + +
+
+
+
+ Fields + + + HTTP uses "fields" to provide data in the form of extensible + name/value pairs with a registered key namespace. Fields are sent and + received within the header and trailer sections of messages + (). + +
+ Field Names + + A field name labels the corresponding field value as having the + semantics defined by that name. For example, the Date + header field is defined in as containing the + origination timestamp for the message in which it appears. + + + field-name = token + + + Field names are case-insensitive and ought to be registered within the + "Hypertext Transfer Protocol (HTTP) Field Name Registry"; see . + + + The interpretation of a field does not change between minor + versions of the same major HTTP version, though the default behavior of a + recipient in the absence of such a field can change. Unless specified + otherwise, fields are defined for all versions of HTTP. + In particular, the Host and Connection + fields ought to be recognized by all HTTP implementations + whether or not they advertise conformance with HTTP/1.1. + + + New fields can be introduced without changing the protocol version if + their defined semantics allow them to be safely ignored by recipients + that do not recognize them; see . + + + A proxy MUST forward unrecognized header fields unless the + field name is listed in the Connection header field + () or the proxy is specifically + configured to block, or otherwise transform, such fields. + Other recipients SHOULD ignore unrecognized header and trailer fields. + Adhering to these requirements allows HTTP's functionality to be extended + without updating or removing deployed intermediaries. + +
+
+ Field Lines and Combined Field Value + + + + + Field sections are composed of any number of "field lines", + each with a "field name" (see ) + identifying the field, and a "field line value" that conveys + data for that instance of the field. + + + + When a field name is only present once in a section, the combined + "field value" for that field consists of the corresponding + field line value. + When a field name is repeated within a section, its combined field value + consists of the list of corresponding field line values within that section, + concatenated in order, with each field line value separated by a comma. + + + For example, this section: + + Example-Field: Foo, Bar +Example-Field: Baz + + + contains two field lines, both with the field name "Example-Field". The + first field line has a field line value of "Foo, Bar", while the second + field line value is "Baz". The field value for "Example-Field" is the list + "Foo, Bar, Baz". + +
+
+ Field Order + + A recipient MAY combine multiple field lines within a field section that + have the same field name + into one field line, without changing the semantics of the message, by + appending each subsequent field line value to the initial field line value + in order, separated by a comma (",") and optional whitespace + (OWS, defined in ). + For consistency, use comma SP. + + + The order in which field lines with the + same name are received is therefore significant to the interpretation of + the field value; a proxy MUST NOT change the order of these field line + values when forwarding a message. + + + This means that, aside from the well-known exception noted below, a sender + MUST NOT generate multiple field lines with the same name in a message + (whether in the headers or trailers) or append a field line when a field + line of the same name already exists in the message, unless that field's + definition allows multiple field line values to be recombined as a + comma-separated list (i.e., at least one alternative of the field's + definition allows a comma-separated list, such as an ABNF rule of + #(values) defined in ). + + + + The order in which field lines with differing field names are received in a + section is not significant. However, it is good practice to send header + fields that contain additional control data first, such as + Host on requests and Date on responses, so + that implementations can decide when not to handle a message as early as + possible. + + + A server MUST NOT apply a request to the target resource until it + receives the entire request header section, since later header field lines + might include conditionals, authentication credentials, or deliberately + misleading duplicate header fields that could impact request processing. + +
+
+ Field Limits + + HTTP does not place a predefined limit on the length of each field line, field value, + or on the length of a header or trailer section as a whole, as described in + . Various ad hoc limitations on individual + lengths are found in practice, often depending on the specific + field's semantics. + + + A server that receives a request header field line, field value, or set of + fields larger than it wishes to process MUST respond with an appropriate + 4xx (Client Error) status code. Ignoring such header fields + would increase the server's vulnerability to request smuggling attacks + (). + + + A client MAY discard or truncate received field lines that are larger + than the client wishes to process if the field semantics are such that the + dropped value(s) can be safely ignored without changing the + message framing or response semantics. + +
+
+ Field Values + + HTTP field values consist of a sequence of characters in a format defined + by the field's grammar. Each field's grammar is usually defined using + ABNF (). + + + + + + field-value = *field-content + field-content = field-vchar + [ 1*( SP / HTAB / field-vchar ) field-vchar ] + field-vchar = VCHAR / obs-text + obs-text = %x80-FF + + + A field value does not include leading or trailing whitespace. When a + specific version of HTTP allows such whitespace to appear in a message, + a field parsing implementation MUST exclude such whitespace prior to + evaluating the field value. + + + Field values are usually constrained to the range of US-ASCII characters + . + Fields needing a greater range of characters can use an encoding, + such as the one defined in . + Historically, HTTP allowed field content with text in the ISO-8859-1 + charset , supporting other charsets only + through use of encoding. + Specifications for newly defined fields SHOULD limit their values to + visible US-ASCII octets (VCHAR), SP, and HTAB. + A recipient SHOULD treat other allowed octets in field content + (i.e., obs-text) as opaque data. + + + Field values containing CR, LF, or NUL characters are invalid and dangerous, + due to the varying ways that implementations might parse and interpret + those characters; a recipient of CR, LF, or NUL within a field value MUST + either reject the message or replace each of those characters with SP + before further processing or forwarding of that message. Field values + containing other CTL characters are also invalid; however, + recipients MAY retain such characters for the sake of robustness when + they appear within a safe context (e.g., an application-specific quoted + string that will not be processed by any downstream HTTP parser). + + + + Fields that only anticipate a single member as the field value are + referred to as "singleton fields". + + + + Fields that allow multiple members as the field value are referred to as + "list-based fields". The list operator extension of + is used as a common notation for defining + field values that can contain multiple members. + + + Because commas (",") are used as the delimiter between members, they need + to be treated with care if they are allowed as data within a member. This + is true for both list-based and singleton fields, since a singleton field + might be erroneously sent with multiple members and detecting such errors + improves interoperability. Fields that expect to contain a + comma within a member, such as within an HTTP-date or + URI-reference + element, ought to be defined with delimiters around that element to + distinguish any comma within that data from potential list separators. + + + For example, a textual date and a URI (either of which might contain a comma) + could be safely carried in list-based field values like these: + + Example-URIs: "http://example.com/a.html,foo", + "http://without-a-comma.example.com/" +Example-Dates: "Sat, 04 May 1996", "Wed, 14 Sep 2005" + + + Note that double-quote delimiters are almost always used with the + quoted-string production (); using a different syntax inside double-quotes + will likely cause unnecessary confusion. + + + Many fields (such as Content-Type, defined in + ) use a common syntax for parameters + that allows both unquoted (token) and quoted (quoted-string) syntax for + a parameter value (). Use of common syntax + allows recipients to reuse existing parser components. When allowing both + forms, the meaning of a parameter value ought to be the same whether it + was received as a token or a quoted string. + + +
+
+ Common Rules for Defining Field Values +
+ Lists (#rule ABNF Extension) + + A #rule extension to the ABNF rules of is used to + improve readability in the definitions of some list-based field values. + + + A construct "#" is defined, similar to "*", for defining comma-delimited + lists of elements. The full form is "<n>#<m>element" indicating + at least <n> and at most <m> elements, each separated by a single + comma (",") and optional whitespace (OWS, + defined in ). + +
+ Sender Requirements + + In any production that uses the list construct, a sender MUST NOT + generate empty list elements. In other words, a sender has to generate + lists that satisfy the following syntax: + + + 1#element => element *( OWS "," OWS element ) + + + and: + + + #element => [ 1#element ] + + + and for n >= 1 and m > 1: + + + <n>#<m>element => element <n-1>*<m-1>( OWS "," OWS element ) + + + shows the collected ABNF for senders + after the list constructs have been expanded. + +
+
+ Recipient Requirements + + Empty elements do not contribute to the count of elements present. + A recipient MUST parse and ignore + a reasonable number of empty list elements: enough to handle common mistakes + by senders that merge values, but not so much that they could be used as a + denial-of-service mechanism. In other words, a recipient MUST accept lists + that satisfy the following syntax: + + + #element => [ element ] *( OWS "," OWS [ element ] ) + + + Note that because of the potential presence of empty list elements, the + RFC 5234 ABNF cannot enforce the cardinality of list elements, and + consequently all cases are mapped as if there was no cardinality specified. + + + For example, given these ABNF productions: + + + example-list = 1#example-list-elmt + example-list-elmt = token ; see Section 5.6.2 + + + Then the following are valid values for example-list (not including the + double quotes, which are present for delimitation only): + + + "foo,bar" + "foo ,bar," + "foo , ,bar,charlie" + + + In contrast, the following values would be invalid, since at least one + non-empty element is required by the example-list production: + + + "" + "," + ", ," + +
+
+
+ Tokens + + + + Tokens are short textual identifiers that do not include whitespace or + delimiters. + + + + token = 1*tchar + + tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + / DIGIT / ALPHA + ; any VCHAR, except delimiters + + + + Many HTTP field values are defined using common syntax + components, separated by whitespace or specific delimiting characters. + Delimiters are chosen from the set of US-ASCII visual characters not + allowed in a token (DQUOTE and "(),/:;<=>?@[\]{}"). + +
+
+ Whitespace + + This specification uses three rules to denote the use of linear + whitespace: OWS (optional whitespace), RWS (required whitespace), and + BWS ("bad" whitespace). + + + The OWS rule is used where zero or more linear whitespace octets might + appear. For protocol elements where optional whitespace is preferred to + improve readability, a sender SHOULD generate the optional whitespace + as a single SP; otherwise, a sender SHOULD NOT generate optional + whitespace except as needed to overwrite invalid or unwanted protocol + elements during in-place message filtering. + + + The RWS rule is used when at least one linear whitespace octet is required + to separate field tokens. A sender SHOULD generate RWS as a single SP. + + + OWS and RWS have the same semantics as a single SP. Any content known to + be defined as OWS or RWS MAY be replaced with a single SP before + interpreting it or forwarding the message downstream. + + + The BWS rule is used where the grammar allows optional whitespace only for + historical reasons. A sender MUST NOT generate BWS in messages. + A recipient MUST parse for such bad whitespace and remove it before + interpreting the protocol element. + + + BWS has no semantics. Any content known to be + defined as BWS MAY be removed before interpreting it or forwarding the + message downstream. + + + + + OWS = *( SP / HTAB ) + ; optional whitespace + RWS = 1*( SP / HTAB ) + ; required whitespace + BWS = OWS + ; "bad" whitespace + +
+
+ Quoted Strings + + + + A string of text is parsed as a single value if it is quoted using + double-quote marks. + + + + quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + + + + The backslash octet ("\") can be used as a single-octet + quoting mechanism within quoted-string and comment constructs. + Recipients that process the value of a quoted-string MUST handle a + quoted-pair as if it were replaced by the octet following the backslash. + + + quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + + + A sender SHOULD NOT generate a quoted-pair in a quoted-string except + where necessary to quote DQUOTE and backslash octets occurring within that + string. + A sender SHOULD NOT generate a quoted-pair in a comment except + where necessary to quote parentheses ["(" and ")"] and backslash octets + occurring within that comment. + +
+
+ Comments + + + + Comments can be included in some HTTP fields by surrounding + the comment text with parentheses. Comments are only allowed in + fields containing "comment" as part of their field value definition. + + + + comment = "(" *( ctext / quoted-pair / comment ) ")" + ctext = HTAB / SP / %x21-27 / %x2A-5B / %x5D-7E / obs-text + +
+
+ Parameters + + + + + Parameters are instances of name/value pairs; they are often used in field + values as a common syntax for appending auxiliary information to an item. + Each parameter is usually delimited by an immediately preceding semicolon. + + + + + + parameters = *( OWS ";" OWS [ parameter ] ) + parameter = parameter-name "=" parameter-value + parameter-name = token + parameter-value = ( token / quoted-string ) + + + Parameter names are case-insensitive. Parameter values might or might + not be case-sensitive, depending on the semantics of the parameter + name. Examples of parameters and some equivalent forms can be seen in + media types () and the Accept header field + (). + + + A parameter value that matches the token production can be + transmitted either as a token or within a quoted-string. The quoted and + unquoted values are equivalent. + + +
+
+ Date/Time Formats + + + Prior to 1995, there were three different formats commonly used by servers + to communicate timestamps. For compatibility with old implementations, all + three are defined here. The preferred format is a fixed-length and + single-zone subset of the date and time specification used by the + Internet Message Format . + + + HTTP-date = IMF-fixdate / obs-date + + + An example of the preferred format is + + + Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate + + + Examples of the two obsolete formats are + + + Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format + Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format + + + A recipient that parses a timestamp value in an HTTP field MUST + accept all three HTTP-date formats. When a sender generates a field + that contains one or more timestamps defined as HTTP-date, + the sender MUST generate those timestamps in the IMF-fixdate format. + + + An HTTP-date value represents time as an instance of Coordinated + Universal Time (UTC). The first two formats indicate UTC by the + three-letter abbreviation for Greenwich Mean Time, "GMT", a predecessor + of the UTC name; values in the asctime format are assumed to be in UTC. + + + A "clock" is an implementation capable of providing a + reasonable approximation of the current instant in UTC. + A clock implementation ought to use NTP (), + or some similar protocol, to synchronize with UTC. + + + + + + + + + + + + + Preferred format: + + + + + + + + + + + + + + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %s"Mon" / %s"Tue" / %s"Wed" + / %s"Thu" / %s"Fri" / %s"Sat" / %s"Sun" + + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %s"Jan" / %s"Feb" / %s"Mar" / %s"Apr" + / %s"May" / %s"Jun" / %s"Jul" / %s"Aug" + / %s"Sep" / %s"Oct" / %s"Nov" / %s"Dec" + year = 4DIGIT + + GMT = %s"GMT" + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + + + + + + + + + + Obsolete formats: + + + obs-date = rfc850-date / asctime-date + + + rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT + date2 = day "-" month "-" 2DIGIT + ; e.g., 02-Jun-82 + + day-name-l = %s"Monday" / %s"Tuesday" / %s"Wednesday" + / %s"Thursday" / %s"Friday" / %s"Saturday" + / %s"Sunday" + + + asctime-date = day-name SP date3 SP time-of-day SP year + date3 = month SP ( 2DIGIT / ( SP 1DIGIT )) + ; e.g., Jun 2 + + + HTTP-date is case sensitive. Note that relaxes this for cache recipients. + + + A sender MUST NOT generate additional whitespace in an HTTP-date beyond + that specifically included as SP in the grammar. + The semantics of day-name, day, + month, year, and time-of-day + are the same as those defined for the Internet Message Format constructs + with the corresponding name (). + + + Recipients of a timestamp value in rfc850-date format, which uses a + two-digit year, MUST interpret a timestamp that appears to be more + than 50 years in the future as representing the most recent year in the + past that had the same last two digits. + + + Recipients of timestamp values are encouraged to be robust in parsing + timestamps unless otherwise restricted by the field definition. + For example, messages are occasionally forwarded over HTTP from a non-HTTP + source that might generate any of the date and time specifications defined + by the Internet Message Format. + + +
+
+
+
+ Message Abstraction + + + + + Each major version of HTTP defines its own syntax for communicating + messages. This section defines an abstract data type for HTTP messages + based on a generalization of those message characteristics, common structure, + and capacity for conveying semantics. This abstraction is used to define + requirements on senders and recipients that are independent of the HTTP + version, such that a message in one version can be relayed through other + versions without changing its meaning. + + + A "message" consists of the following: + +
    +
  • control data to describe and route the message,
  • +
  • a headers lookup table of name/value pairs for extending that control + data and conveying additional information about the sender, message, + content, or context,
  • +
  • a potentially unbounded stream of content, and
  • +
  • a trailers lookup table of name/value pairs for communicating information + obtained while sending the content.
  • +
+ + Framing and control data is sent first, followed by a header section + containing fields for the headers table. When a message includes content, + the content is sent after the header section, potentially followed by a + trailer section that might contain fields for the trailers table. + + + Messages are expected to be processed as a stream, wherein the purpose of + that stream and its continued processing is revealed while being read. + Hence, control data describes what the recipient needs to know immediately, + header fields describe what needs to be known before receiving content, + the content (when present) presumably contains what the recipient wants or + needs to fulfill the message semantics, and trailer fields provide + optional metadata that was unknown prior to sending the content. + + + Messages are intended to be "self-descriptive": + everything a recipient needs to know about the message can be determined by + looking at the message itself, after decoding or reconstituting parts that + have been compressed or elided in transit, without requiring an + understanding of the sender's current application state (established via + prior messages). However, a client MUST retain knowledge of the request when + parsing, interpreting, or caching a corresponding response. For example, + responses to the HEAD method look just like the beginning of a + response to GET but cannot be parsed in the same manner. + + + Note that this message abstraction is a generalization across many versions + of HTTP, including features that might not be found in some versions. For + example, trailers were introduced within the HTTP/1.1 chunked transfer + coding as a trailer section after the content. An equivalent feature is + present in HTTP/2 and HTTP/3 within the header block that terminates each + stream. + +
+ Framing and Completeness + + + + Message framing indicates how each message begins and ends, such that each + message can be distinguished from other messages or noise on the same + connection. Each major version of HTTP defines its own framing mechanism. + + + HTTP/0.9 and early deployments of HTTP/1.0 used closure of the underlying + connection to end a response. For backwards compatibility, this implicit + framing is also allowed in HTTP/1.1. However, implicit framing can fail to + distinguish an incomplete response if the connection closes early. For + that reason, almost all modern implementations use explicit framing in + the form of length-delimited sequences of message data. + + + A message is considered "complete" when all of the octets + indicated by its framing are available. Note that, + when no explicit framing is used, a response message that is ended + by the underlying connection's close is considered complete even though it + might be indistinguishable from an incomplete response, unless a + transport-level error indicates that it is not complete. + +
+
+ Control Data + + + Messages start with control data that describe its primary purpose. Request + message control data includes a request method (), + request target (), and protocol version + (). Response message control data includes + a status code (), optional reason phrase, and + protocol version. + + + In HTTP/1.1 () and earlier, control data is sent + as the first line of a message. In HTTP/2 () and + HTTP/3 (), control data is sent as pseudo-header + fields with a reserved name prefix (e.g., ":authority"). + + + Every HTTP message has a protocol version. Depending on the version in use, + it might be identified within the message explicitly or inferred by the + connection over which the message is received. Recipients use that version + information to determine limitations or potential for later communication + with that sender. + + + When a message is forwarded by an intermediary, the protocol version is + updated to reflect the version used by that intermediary. + The Via header field () is used to + communicate upstream protocol information within a forwarded message. + + + A client SHOULD send a request version equal to the highest + version to which the client is conformant and + whose major version is no higher than the highest version supported + by the server, if this is known. A client MUST NOT send a + version to which it is not conformant. + + + A client MAY send a lower request version if it is known that + the server incorrectly implements the HTTP specification, but only + after the client has attempted at least one normal request and determined + from the response status code or header fields (e.g., Server) that + the server improperly handles higher request versions. + + + A server SHOULD send a response version equal to the highest version to + which the server is conformant that has a major version less than or equal + to the one received in the request. + A server MUST NOT send a version to which it is not conformant. + A server can send a 505 (HTTP Version Not Supported) + response if it wishes, for any reason, to refuse service of the client's + major protocol version. + + + A recipient that receives a message with a major version number that it + implements and a minor version number higher than what it implements + SHOULD process the message as if it + were in the highest minor version within that major version to which the + recipient is conformant. A recipient can assume that a message with a + higher minor version, when sent to a recipient that has not yet indicated + support for that higher version, is sufficiently backwards-compatible to be + safely processed by any implementation of the same major version. + +
+
+ Header Fields + + + + Fields () that are sent or received before the content + are referred to as "header fields" (or just "headers", colloquially). + + + The "header section" of a message consists of a sequence of + header field lines. Each header field might modify or extend message + semantics, describe the sender, define the content, or provide additional + context. + + +
+
+ Content + + + HTTP messages often transfer a complete or partial representation as the + message "content": a stream of octets sent after the header + section, as delineated by the message framing. + + + This abstract definition of content reflects the data after it has been + extracted from the message framing. For example, an HTTP/1.1 message body + () might consist of a stream of data encoded + with the chunked transfer coding -- a sequence of data chunks, one + zero-length chunk, and a trailer section -- whereas + the content of that same message + includes only the data stream after the transfer coding has been decoded; + it does not include the chunk lengths, chunked framing syntax, nor the + trailer fields (). + + +
+ Content Semantics + + The purpose of content in a request is defined by the method semantics + (). + + + For example, a representation in the content of a PUT request + () represents the desired state of the + target resource after the request is successfully applied, + whereas a representation in the content of a POST request + () represents information to be processed by the + target resource. + + + In a response, the content's purpose is defined by the request method, + response status code (), and response + fields describing that content. + For example, the content of a 200 (OK) response to GET + () represents the current state of the + target resource, as observed at the time of the message + origination date (), whereas the content of + the same status code in a response to POST might represent either the + processing result or the new state of the target resource after applying + the processing. + + + The content of a 206 (Partial Content) response to GET + contains either a single part of the selected representation or a + multipart message body containing multiple parts of that representation, + as described in . + + + Response messages with an error status code usually contain content that + represents the error condition, such that the content describes the + error state and what steps are suggested for resolving it. + + + Responses to the HEAD request method () never include + content; the associated response header fields indicate only + what their values would have been if the request method had been GET + (). + + + 2xx (Successful) responses to a CONNECT request method + () switch the connection to tunnel mode instead of + having content. + + + All 1xx (Informational), 204 (No Content), and + 304 (Not Modified) responses do not include content. + + + All other responses do include content, although that content + might be of zero length. + +
+
+ Identifying Content + + When a complete or partial representation is transferred as message + content, it is often desirable for the sender to supply, or the recipient + to determine, an identifier for a resource corresponding to that specific + representation. For example, a client making a GET request on a resource + for "the current weather report" might want an identifier specific to the + content returned (e.g., "weather report for Laguna Beach at 20210720T1711"). + This can be useful for sharing or bookmarking content from resources that + are expected to have changing representations over time. + + + For a request message: + +
    +
  • If the request has a Content-Location header field, + then the sender asserts that the content is a representation of the + resource identified by the Content-Location field value. However, + such an assertion cannot be trusted unless it can be verified by + other means (not defined by this specification). The information + might still be useful for revision history links.
  • +
  • Otherwise, the content is unidentified by HTTP, but a more specific + identifier might be supplied within the content itself.
  • +
+ + For a response message, the following rules are applied in order until a + match is found: + +
    +
  1. If the request method is HEAD or the response status code is + 204 (No Content) or 304 (Not Modified), + there is no content in the response.
  2. +
  3. If the request method is GET and the response status code is + 200 (OK), + the content is a representation of the target resource ().
  4. +
  5. If the request method is GET and the response status code is + 203 (Non-Authoritative Information), the content is + a potentially modified or enhanced representation of the + target resource as provided by an intermediary.
  6. +
  7. If the request method is GET and the response status code is + 206 (Partial Content), + the content is one or more parts of a representation of the + target resource.
  8. +
  9. If the response has a Content-Location header field + and its field value is a reference to the same URI as the target URI, + the content is a representation of the target resource.
  10. +
  11. If the response has a Content-Location header field + and its field value is a reference to a URI different from the + target URI, then the sender asserts that the content is a + representation of the resource identified by the Content-Location + field value. However, such an assertion cannot be trusted unless + it can be verified by other means (not defined by this specification).
  12. +
  13. Otherwise, the content is unidentified by HTTP, but a more specific + identifier might be supplied within the content itself.
  14. +
+
+
+
+ Trailer Fields + + + + + Fields () that are located within a + "trailer section" are referred to as "trailer fields" + (or just "trailers", colloquially). + Trailer fields can be useful for supplying message integrity checks, digital + signatures, delivery metrics, or post-processing status information. + + + Trailer fields ought to be processed and stored separately from the fields + in the header section to avoid contradicting message semantics known at + the time the header section was complete. The presence or absence of + certain header fields might impact choices made for the routing or + processing of the message as a whole before the trailers are received; + those choices cannot be unmade by the later discovery of trailer fields. + +
+ Limitations on Use of Trailers + + A trailer section is only possible when supported by the version + of HTTP in use and enabled by an explicit framing mechanism. + For example, the chunked transfer coding in HTTP/1.1 allows a trailer section to be + sent after the content (). + + + Many fields cannot be processed outside the header section because + their evaluation is necessary prior to receiving the content, such as + those that describe message framing, routing, authentication, + request modifiers, response controls, or content format. + A sender MUST NOT generate a trailer field unless the sender knows the + corresponding header field name's definition permits the field to be sent + in trailers. + + + Trailer fields can be difficult to process by intermediaries that forward + messages from one protocol version to another. If the entire message can be + buffered in transit, some intermediaries could merge trailer fields into + the header section (as appropriate) before it is forwarded. However, in + most cases, the trailers are simply discarded. + A recipient MUST NOT merge a trailer field into a header section unless + the recipient understands the corresponding header field definition and + that definition explicitly permits and defines how trailer field values + can be safely merged. + + + The presence of the keyword "trailers" in the TE header field () of a request indicates that the client is willing to + accept trailer fields, on behalf of itself and any downstream clients. For + requests from an intermediary, this implies that all + downstream clients are willing to accept trailer fields in the forwarded + response. Note that the presence of "trailers" does not mean that the + client(s) will process any particular trailer field in the response; only + that the trailer section(s) will not be dropped by any of the clients. + + + Because of the potential for trailer fields to be discarded in transit, a + server SHOULD NOT generate trailer fields that it believes are necessary + for the user agent to receive. + +
+
+ Processing Trailer Fields + + The "Trailer" header field () can be sent + to indicate fields likely to be sent in the trailer section, which allows + recipients to prepare for their receipt before processing the content. + For example, this could be useful if a field name indicates that a dynamic + checksum should be calculated as the content is received and then + immediately checked upon receipt of the trailer field value. + + + Like header fields, trailer fields with the same name are processed in the + order received; multiple trailer field lines with the same name have the + equivalent semantics as appending the multiple values as a list of members. + Trailer fields that might be generated more than once during a message + MUST be defined as a list-based field even if each member value is only + processed once per field line received. + + + At the end of a message, a recipient MAY treat the set of received + trailer fields as a data structure of name/value pairs, similar to (but + separate from) the header fields. Additional processing expectations, if + any, can be defined within the field specification for a field intended + for use in trailers. + +
+
+
+ Message Metadata + + Fields that describe the message itself, such as when and how the + message has been generated, can appear in both requests and responses. + +
+ Date + + + + + The "Date" header field represents the date and time at which + the message was originated, having the same semantics as the Origination + Date Field (orig-date) defined in . + The field value is an HTTP-date, as defined in . + + + Date = HTTP-date + + + An example is + + Date: Tue, 15 Nov 1994 08:12:31 GMT + + + A sender that generates a Date header field SHOULD generate its + field value as the best available approximation of the date and time of + message generation. In theory, the date ought to represent the moment just + before generating the message content. In practice, a sender can generate + the date value at any time during message origination. + + + An origin server with a clock (as defined in + ) MUST generate a Date header field in + all 2xx (Successful), 3xx (Redirection), + and 4xx (Client Error) responses, + and MAY generate a Date header field in + 1xx (Informational) and + 5xx (Server Error) responses. + + + An origin server without a clock MUST NOT generate a Date header field. + + + A recipient with a clock that receives a response message without a Date + header field MUST record the time it was received and append a + corresponding Date header field to the message's header section if it is + cached or forwarded downstream. + + + A recipient with a clock that receives a response with an invalid Date + header field value MAY replace that value with the time that + response was received. + + + A user agent MAY send a Date header field in a request, though generally + will not do so unless it is believed to convey useful information to the + server. For example, custom applications of HTTP might convey a Date if + the server is expected to adjust its interpretation of the user's request + based on differences between the user agent and server clocks. + +
+
+ Trailer + + + + + The "Trailer" header field provides a list of field names that the sender + anticipates sending as trailer fields within that message. This allows a + recipient to prepare for receipt of the indicated metadata before it starts + processing the content. + + + + Trailer = #field-name + + + For example, a sender might indicate that a signature will + be computed as the content is being streamed and provide the final + signature as a trailer field. This allows a recipient to perform the same + check on the fly as it receives the content. + + + A sender that intends to generate one or more trailer fields in a message + SHOULD generate a Trailer header field in the header + section of that message to indicate which fields might be present in the + trailers. + + + If an intermediary discards the trailer section in transit, the + Trailer field could provide a hint of what metadata + was lost, though there is no guarantee that a sender of Trailer + will always follow through by sending the named fields. + +
+
+
+
+ Routing HTTP Messages + + HTTP request message routing is determined by each client based on the + target resource, the client's proxy configuration, and + establishment or reuse of an inbound connection. The corresponding + response routing follows the same connection chain back to the client. + +
+ Determining the Target Resource + + + + + Although HTTP is used in a wide variety of applications, most clients rely + on the same resource identification mechanism and configuration techniques + as general-purpose Web browsers. Even when communication options are + hard-coded in a client's configuration, we can think of their combined + effect as a URI reference (). + + + A URI reference is resolved to its absolute form in order to obtain the + "target URI". The target URI excludes the reference's + fragment component, if any, since fragment identifiers are reserved for + client-side processing (). + + + To perform an action on a "target resource", the client sends + a request message containing enough components of its parsed target URI to + enable recipients to identify that same resource. For historical reasons, + the parsed target URI components, collectively referred to as the + "request target", are sent within the message control data + and the Host header field (). + + + There are two unusual cases for which the request target components are in + a method-specific form: + +
    +
  • + For CONNECT (), the request target is the host + name and port number of the tunnel destination, separated by a colon. +
  • +
  • + For OPTIONS (), the request target can be a + single asterisk ("*"). +
  • +
+ + See the respective method definitions for details. These forms MUST NOT + be used with other methods. + + + Upon receipt of a client's request, a server reconstructs the target URI + from the received components in accordance with their local configuration + and incoming connection context. This reconstruction is specific to each + major protocol version. For example, + defines how a server + determines the target URI of an HTTP/1.1 request. + + +
+
+ Host and :authority + + + + + The "Host" header field in a request provides the host and port + information from the target URI, enabling the origin + server to distinguish among resources while servicing requests + for multiple host names. + + + In HTTP/2 and HTTP/3 , the + Host header field is, in some cases, supplanted by the ":authority" + pseudo-header field of a request's control data. + + + Host = uri-host [ ":" port ] ; Section 4 + + + The target URI's authority information is critical for handling a + request. A user agent MUST generate a Host header field in a request + unless it sends that information as an ":authority" pseudo-header field. + A user agent that sends Host SHOULD send it as the first field in the + header section of a request. + + + For example, a GET request to the origin server for + <http://www.example.org/pub/WWW/> would begin with: + + GET /pub/WWW/ HTTP/1.1 +Host: www.example.org + + + Since the host and port information acts as an application-level routing + mechanism, it is a frequent target for malware seeking to poison + a shared cache or redirect a request to an unintended server. + An interception proxy is particularly vulnerable if it relies on + the host and port information for redirecting requests to internal + servers, or for use as a cache key in a shared cache, without + first verifying that the intercepted connection is targeting a + valid IP address for that host. + +
+
+ Routing Inbound Requests + + Once the target URI and its origin are determined, a client decides whether + a network request is necessary to accomplish the desired semantics and, + if so, where that request is to be directed. + +
+ To a Cache + + If the client has a cache and the request can be + satisfied by it, then the request is + usually directed there first. + +
+
+ To a Proxy + + If the request is not satisfied by a cache, then a typical client will + check its configuration to determine whether a proxy is to be used to + satisfy the request. Proxy configuration is implementation-dependent, + but is often based on URI prefix matching, selective authority matching, + or both, and the proxy itself is usually identified by an "http" or + "https" URI. + + + If an "http" or "https" proxy is applicable, the client connects + inbound by establishing (or reusing) a connection to that proxy and + then sending it an HTTP request message containing a request target + that matches the client's target URI. + +
+
+ To the Origin + + If no proxy is applicable, a typical client will invoke a handler + routine (specific to the target URI's scheme) to obtain access to the + identified resource. How that is accomplished is dependent on the + target URI scheme and defined by its associated specification. + + + defines how to obtain access to an + "http" resource by establishing (or reusing) an inbound connection to + the identified origin server and then sending it an HTTP request message + containing a request target that matches the client's target URI. + + + defines how to obtain access to an + "https" resource by establishing (or reusing) an inbound secured + connection to an origin server that is authoritative for the identified + origin and then sending it an HTTP request message containing a request + target that matches the client's target URI. + +
+
+
+ Rejecting Misdirected Requests + + Once a request is received by a server and parsed sufficiently to determine + its target URI, the server decides whether to process the request itself, + forward the request to another server, redirect the client to a different + resource, respond with an error, or drop the connection. This decision can + be influenced by anything about the request or connection context, but is + specifically directed at whether the server has been configured to process + requests for that target URI and whether the connection context is + appropriate for that request. + + + For example, a request might have been misdirected, + deliberately or accidentally, such that the information within a received + Host header field differs from the connection's host or port. + If the connection is from a trusted gateway, such inconsistency might + be expected; otherwise, it might indicate an attempt to bypass security + filters, trick the server into delivering non-public content, or poison a + cache. See for security + considerations regarding message routing. + + + Unless the connection is from a trusted gateway, + an origin server MUST reject a request if any scheme-specific requirements + for the target URI are not met. In particular, + a request for an "https" resource MUST be rejected unless it has been + received over a connection that has been secured via a certificate + valid for that target URI's origin, as defined by . + + + The 421 (Misdirected Request) status code in a response + indicates that the origin server has rejected the request because it + appears to have been misdirected (). + +
+
+ Response Correlation + + A connection might be used for multiple request/response exchanges. The + mechanism used to correlate between request and response messages is + version dependent; some versions of HTTP use implicit ordering of + messages, while others use an explicit identifier. + + + All responses, regardless of the status code (including interim + responses) can be sent at any time after a request is received, even if the + request is not yet complete. A response can complete before its + corresponding request is complete (). Likewise, clients are not expected + to wait any specific amount of time for a response. Clients + (including intermediaries) might abandon a request if the response is not + received within a reasonable period of time. + + + A client that receives a response while it is still sending the associated + request SHOULD continue sending that request unless it receives + an explicit indication to the contrary (see, e.g., and ). + +
+
+ Message Forwarding + + As described in , intermediaries can serve + a variety of roles in the processing of HTTP requests and responses. + Some intermediaries are used to improve performance or availability. + Others are used for access control or to filter content. + Since an HTTP stream has characteristics similar to a pipe-and-filter + architecture, there are no inherent limits to the extent an intermediary + can enhance (or interfere) with either direction of the stream. + + + Intermediaries are expected to forward messages even when protocol elements + are not recognized (e.g., new methods, status codes, or field names) since that + preserves extensibility for downstream recipients. + + + An intermediary not acting as a tunnel MUST implement the + Connection header field, as specified in + , and exclude fields from being forwarded + that are only intended for the incoming connection. + + + An intermediary MUST NOT forward a message to itself unless it is + protected from an infinite request loop. In general, an intermediary ought + to recognize its own server names, including any aliases, local variations, + or literal IP addresses, and respond to such requests directly. + + + An HTTP message can be parsed as a stream for incremental processing or + forwarding downstream. + However, senders and recipients cannot rely on incremental + delivery of partial messages, since some implementations will buffer or + delay message forwarding for the sake of network efficiency, security + checks, or content transformations. + +
+ Connection + + + + + + + The "Connection" header field allows the sender to list desired + control options for the current connection. + + Connection = #connection-option + connection-option = token + + + Connection options are case-insensitive. + + + When a field aside from Connection is used to supply control + information for or about the current connection, the sender MUST list + the corresponding field name within the Connection header field. + Note that some versions of HTTP prohibit the use of fields for such + information, and therefore do not allow the Connection field. + + + Intermediaries MUST parse a received Connection + header field before a message is forwarded and, for each + connection-option in this field, remove any header or trailer field(s) from + the message with the same name as the connection-option, and then + remove the Connection header field itself (or replace it with the + intermediary's own control options for the forwarded message). + + + Hence, the Connection header field provides a declarative way of + distinguishing fields that are only intended for the + immediate recipient ("hop-by-hop") from those fields that are + intended for all recipients on the chain ("end-to-end"), enabling the + message to be self-descriptive and allowing future connection-specific + extensions to be deployed without fear that they will be blindly + forwarded by older intermediaries. + + + Furthermore, intermediaries SHOULD remove or replace fields + that are known to require removal before forwarding, whether or not they appear as a + connection-option, after applying those fields' semantics. This includes but is not limited to: + +
    +
  • Proxy-Connection ()
  • +
  • Keep-Alive ()
  • +
  • TE ()
  • +
  • Transfer-Encoding ()
  • +
  • Upgrade ()
  • +
+ + A sender MUST NOT send a connection option corresponding to a + field that is intended for all recipients of the content. + For example, Cache-Control is never appropriate as a + connection option (). + + + Connection options do not always correspond to a field + present in the message, since a connection-specific field + might not be needed if there are no parameters associated with a + connection option. In contrast, a connection-specific field + received without a corresponding connection option usually indicates + that the field has been improperly forwarded by an intermediary and + ought to be ignored by the recipient. + + + When defining a new connection option that does not correspond to a field, + specification authors ought to reserve the corresponding field name + anyway in order to avoid later collisions. Such reserved field names are + registered in the "Hypertext Transfer Protocol (HTTP) Field Name Registry" + (). + +
+
+ Max-Forwards + + + + + The "Max-Forwards" header field provides a mechanism with the + TRACE () and OPTIONS () + request methods to limit the number of times that the request is forwarded by + proxies. This can be useful when the client is attempting to + trace a request that appears to be failing or looping mid-chain. + + + Max-Forwards = 1*DIGIT + + + The Max-Forwards value is a decimal integer indicating the remaining + number of times this request message can be forwarded. + + + Each intermediary that receives a TRACE or OPTIONS request containing a + Max-Forwards header field MUST check and update its value prior to + forwarding the request. If the received value is zero (0), the intermediary + MUST NOT forward the request; instead, the intermediary MUST respond as + the final recipient. If the received Max-Forwards value is greater than + zero, the intermediary MUST generate an updated Max-Forwards field in the + forwarded message with a field value that is the lesser of a) the received + value decremented by one (1) or b) the recipient's maximum supported value + for Max-Forwards. + + + A recipient MAY ignore a Max-Forwards header field received with any + other request methods. + +
+
+ Via + + + + + The "Via" header field indicates the presence of intermediate protocols and + recipients between the user agent and the server (on requests) or between + the origin server and the client (on responses), similar to the + "Received" header field in email + (). + Via can be used for tracking message forwards, + avoiding request loops, and identifying the protocol capabilities of + senders along the request/response chain. + + + + + + + + Via = #( received-protocol RWS received-by [ RWS comment ] ) + + received-protocol = [ protocol-name "/" ] protocol-version + ; see Section 7.8 + received-by = pseudonym [ ":" port ] + pseudonym = token + + + Each member of the Via field value represents a proxy or gateway that has + forwarded the message. Each intermediary appends its own information + about how the message was received, such that the end result is ordered + according to the sequence of forwarding recipients. + + + A proxy MUST send an appropriate Via header field, as described below, in + each message that it forwards. + An HTTP-to-HTTP gateway MUST send an appropriate Via header field in + each inbound request message and MAY send a Via header field in + forwarded response messages. + + + For each intermediary, the received-protocol indicates the protocol and + protocol version used by the upstream sender of the message. Hence, the + Via field value records the advertised protocol capabilities of the + request/response chain such that they remain visible to downstream + recipients; this can be useful for determining what backwards-incompatible + features might be safe to use in response, or within a later request, as + described in . For brevity, the protocol-name + is omitted when the received protocol is HTTP. + + + The received-by portion is normally the host and optional + port number of a recipient server or client that subsequently forwarded the + message. + However, if the real host is considered to be sensitive information, a + sender MAY replace it with a pseudonym. If a port is not provided, + a recipient MAY interpret that as meaning it was received on the default + port, if any, for the received-protocol. + + + A sender MAY generate comments to identify the + software of each recipient, analogous to the User-Agent and + Server header fields. However, comments in Via + are optional, and a recipient MAY remove them prior to forwarding the + message. + + + For example, a request message could be sent from an HTTP/1.0 user + agent to an internal proxy code-named "fred", which uses HTTP/1.1 to + forward the request to a public proxy at p.example.net, which completes + the request by forwarding it to the origin server at www.example.com. + The request received by www.example.com would then have the following + Via header field: + + Via: 1.0 fred, 1.1 p.example.net + + + An intermediary used as a portal through a network firewall + SHOULD NOT forward the names and ports of hosts within the firewall + region unless it is explicitly enabled to do so. If not enabled, such an + intermediary SHOULD replace each received-by host of any host behind the + firewall by an appropriate pseudonym for that host. + + + An intermediary MAY combine an ordered subsequence of Via header + field list members into a single member if the entries have identical + received-protocol values. For example, + + Via: 1.0 ricky, 1.1 ethel, 1.1 fred, 1.0 lucy + + + could be collapsed to + + Via: 1.0 ricky, 1.1 mertz, 1.0 lucy + + + A sender SHOULD NOT combine multiple list members unless they are all + under the same organizational control and the hosts have already been + replaced by pseudonyms. A sender MUST NOT combine members that + have different received-protocol values. + +
+
+
+ Message Transformations + + + + Some intermediaries include features for transforming messages and their + content. A proxy might, for example, convert between image formats in + order to save cache space or to reduce the amount of traffic on a slow + link. However, operational problems might occur when these transformations + are applied to content intended for critical applications, such as medical + imaging or scientific data analysis, particularly when integrity checks or + digital signatures are used to ensure that the content received is + identical to the original. + + + An HTTP-to-HTTP proxy is called a "transforming proxy" + if it is designed or configured to modify messages in a semantically + meaningful way (i.e., modifications, beyond those required by normal + HTTP processing, that change the message in a way that would be + significant to the original sender or potentially significant to + downstream recipients). For example, a transforming proxy might be + acting as a shared annotation server (modifying responses to include + references to a local annotation database), a malware filter, a + format transcoder, or a privacy filter. Such transformations are presumed + to be desired by whichever client (or client organization) chose the + proxy. + + + If a proxy receives a target URI with a host name that is not a + fully qualified domain name, it MAY add its own domain to the host name + it received when forwarding the request. A proxy MUST NOT change the + host name if the target URI contains a fully qualified domain name. + + + A proxy MUST NOT modify the "absolute-path" and "query" parts of the + received target URI when forwarding it to the next inbound server except + as required by that forwarding protocol. For example, a proxy forwarding + a request to an origin server via HTTP/1.1 will replace an empty path with + "/" () or "*" (), + depending on the request method. + + + A proxy MUST NOT transform the content () of a + response message that contains a no-transform cache directive + (). Note that this + does not apply to message transformations that do not change the content, + such as the addition or removal of transfer codings + (). + + + A proxy MAY transform the content of a message + that does not contain a no-transform cache directive. + A proxy that transforms the content of a 200 (OK) response + can inform downstream recipients that a transformation has been + applied by changing the response status code to + 203 (Non-Authoritative Information) (). + + + A proxy SHOULD NOT modify header fields that provide information about + the endpoints of the communication chain, the resource state, or the + selected representation (other than the content) unless the field's + definition specifically allows such modification or the modification is + deemed necessary for privacy or security. + +
+
+ Upgrade + + + + + The "Upgrade" header field is intended to provide a simple mechanism + for transitioning from HTTP/1.1 to some other protocol on the same + connection. + + + A client MAY send a list of protocol names in the Upgrade header field + of a request to invite the server to switch to one or more of the named + protocols, in order of descending preference, before sending + the final response. A server MAY ignore a received Upgrade header field + if it wishes to continue using the current protocol on that connection. + Upgrade cannot be used to insist on a protocol change. + + + Upgrade = #protocol + + protocol = protocol-name ["/" protocol-version] + protocol-name = token + protocol-version = token + + + Although protocol names are registered with a preferred case, + recipients SHOULD use case-insensitive comparison when matching each + protocol-name to supported protocols. + + + A server that sends a 101 (Switching Protocols) response + MUST send an Upgrade header field to indicate the new protocol(s) to + which the connection is being switched; if multiple protocol layers are + being switched, the sender MUST list the protocols in layer-ascending + order. A server MUST NOT switch to a protocol that was not indicated by + the client in the corresponding request's Upgrade header field. + A server MAY choose to ignore the order of preference indicated by the + client and select the new protocol(s) based on other factors, such as the + nature of the request or the current load on the server. + + + A server that sends a 426 (Upgrade Required) response + MUST send an Upgrade header field to indicate the acceptable protocols, + in order of descending preference. + + + A server MAY send an Upgrade header field in any other response to + advertise that it implements support for upgrading to the listed protocols, + in order of descending preference, when appropriate for a future request. + + + The following is a hypothetical example sent by a client: + + GET /hello HTTP/1.1 +Host: www.example.com +Connection: upgrade +Upgrade: websocket, IRC/6.9, RTA/x11 + + + + The capabilities and nature of the + application-level communication after the protocol change is entirely + dependent upon the new protocol(s) chosen. However, immediately after + sending the 101 (Switching Protocols) response, the server is expected to continue responding to + the original request as if it had received its equivalent within the new + protocol (i.e., the server still has an outstanding request to satisfy + after the protocol has been changed, and is expected to do so without + requiring the request to be repeated). + + + For example, if the Upgrade header field is received in a GET request + and the server decides to switch protocols, it first responds + with a 101 (Switching Protocols) message in HTTP/1.1 and + then immediately follows that with the new protocol's equivalent of a + response to a GET on the target resource. This allows a connection to be + upgraded to protocols with the same semantics as HTTP without the + latency cost of an additional round trip. A server MUST NOT switch + protocols unless the received message semantics can be honored by the new + protocol; an OPTIONS request can be honored by any protocol. + + + The following is an example response to the above hypothetical request: + + HTTP/1.1 101 Switching Protocols +Connection: upgrade +Upgrade: websocket + +[... data stream switches to websocket with an appropriate response +(as defined by new protocol) to the "GET /hello" request ...] + + + A sender of Upgrade MUST also send an "Upgrade" connection option in the + Connection header field () + to inform intermediaries not to forward this field. + A server that receives an Upgrade header field in an HTTP/1.0 request + MUST ignore that Upgrade field. + + + A client cannot begin using an upgraded protocol on the connection until + it has completely sent the request message (i.e., the client can't change + the protocol it is sending in the middle of a message). + If a server receives both an Upgrade and an Expect header field + with the "100-continue" expectation (), the + server MUST send a 100 (Continue) response before sending + a 101 (Switching Protocols) response. + + + The Upgrade header field only applies to switching protocols on top of the + existing connection; it cannot be used to switch the underlying connection + (transport) protocol, nor to switch the existing communication to a + different connection. For those purposes, it is more appropriate to use a + 3xx (Redirection) response (). + + + This specification only defines the protocol name "HTTP" for use by + the family of Hypertext Transfer Protocols, as defined by the HTTP + version rules of and future updates to this + specification. Additional protocol names ought to be registered using the + registration procedure defined in . + +
+
+
+ Representation Data and Metadata +
+ Representation Data + + The representation data associated with an HTTP message is + either provided as the content of the message or + referred to by the message semantics and the target + URI. The representation data is in a format and encoding defined by + the representation metadata header fields. + + + The data type of the representation data is determined via the header fields + Content-Type and Content-Encoding. + These define a two-layer, ordered encoding model: + + + representation-data := Content-Encoding( Content-Type( data ) ) + +
+
+ Representation Metadata + + Representation header fields provide metadata about the representation. + When a message includes content, the representation header fields + describe how to interpret that data. In a response to a HEAD request, the + representation header fields describe the representation data that would + have been enclosed in the content if the same request had been a GET. + +
+
+ Content-Type + + + + + The "Content-Type" header field indicates the media type of the + associated representation: either the representation enclosed in + the message content or the selected representation, as determined by the + message semantics. The indicated media type defines both the data format + and how that data is intended to be processed by a recipient, within the + scope of the received message semantics, after any content codings + indicated by Content-Encoding are decoded. + + + Content-Type = media-type + + + Media types are defined in . An example of the + field is + + Content-Type: text/html; charset=ISO-8859-4 + + + A sender that generates a message containing content SHOULD + generate a Content-Type header field in that message unless the intended + media type of the enclosed representation is unknown to the sender. + If a Content-Type header field is not present, the recipient MAY either + assume a media type of + "application/octet-stream" () + or examine the data to determine its type. + + + In practice, resource owners do not always properly configure their origin + server to provide the correct Content-Type for a given representation. + Some user agents examine the content and, in certain cases, + override the received type (for example, see ). + This "MIME sniffing" risks drawing incorrect conclusions about the data, + which might expose the user to additional security risks + (e.g., "privilege escalation"). + Furthermore, distinct media types often share a common data format, + differing only in how the data is intended to be processed, which is + impossible to distinguish by inspecting the data alone. + When sniffing is implemented, implementers are encouraged to provide a + means for the user to disable it. + + + Although Content-Type is defined as a singleton field, it is + sometimes incorrectly generated multiple times, resulting in a combined + field value that appears to be a list. + Recipients often attempt to handle this error by using the last + syntactically valid member of the list, leading to potential + interoperability and security issues if different implementations + have different error handling behaviors. + +
+ Media Type + + HTTP uses media types in the + Content-Type () + and Accept () header fields in + order to provide open and extensible data typing and type negotiation. + Media types define both a data format and various processing models: + how to process that data in accordance with the message context. + + + + + media-type = type "/" subtype parameters + type = token + subtype = token + + + The type and subtype tokens are case-insensitive. + + + The type/subtype MAY be followed by semicolon-delimited parameters + () in the form of name/value pairs. + The presence or absence of a parameter might be significant to the + processing of a media type, depending on its definition within the media + type registry. + Parameter values might or might not be case-sensitive, depending on the + semantics of the parameter name. + + + For example, the following media types are equivalent in describing HTML + text data encoded in the UTF-8 character encoding scheme, but the first is + preferred for consistency (the "charset" parameter value is defined as + being case-insensitive in ): + + + text/html;charset=utf-8 + Text/HTML;Charset="utf-8" + text/html; charset="utf-8" + text/html;charset=UTF-8 + + + Media types ought to be registered with IANA according to the + procedures defined in . + +
+
+ Charset + + HTTP uses "charset" names to indicate or negotiate the + character encoding scheme () + of a textual representation. In the fields defined by this document, + charset names appear either in parameters (Content-Type), + or, for Accept-Encoding, in the form of a plain token. + In both cases, charset names are matched case-insensitively. + + + Charset names ought to be registered in the IANA "Character Sets" registry + () + according to the procedures defined in . + + +
+
+ Multipart Types + + MIME provides for a number of "multipart" types -- encapsulations of + one or more representations within a single message body. All multipart + types share a common syntax, as defined in , + and include a boundary parameter as part of the media type + value. The message body is itself a protocol element; a sender MUST + generate only CRLF to represent line breaks between body parts. + + + HTTP message framing does not use the multipart boundary as an indicator + of message body length, though it might be used by implementations that + generate or process the content. For example, the "multipart/form-data" + type is often used for carrying form data in a request, as described in + , and the "multipart/byteranges" type is defined + by this specification for use in some 206 (Partial Content) + responses (see ). + +
+
+
+ Content-Encoding + + + + + The "Content-Encoding" header field indicates what content codings + have been applied to the representation, beyond those inherent in the media + type, and thus what decoding mechanisms have to be applied in order to + obtain data in the media type referenced by the Content-Type + header field. + Content-Encoding is primarily used to allow a representation's data to be + compressed without losing the identity of its underlying media type. + + + Content-Encoding = #content-coding + + + An example of its use is + + Content-Encoding: gzip + + + If one or more encodings have been applied to a representation, the sender + that applied the encodings MUST generate a Content-Encoding header field + that lists the content codings in the order in which they were applied. + Note that the coding named "identity" is reserved for its special role + in Accept-Encoding and thus SHOULD NOT be included. + + + Additional information about the encoding parameters can be provided + by other header fields not defined by this specification. + + + Unlike Transfer-Encoding (), the codings listed + in Content-Encoding are a characteristic of the representation; the + representation is defined in terms of the coded form, and all other + metadata about the representation is about the coded form unless otherwise + noted in the metadata definition. Typically, the representation is only + decoded just prior to rendering or analogous usage. + + + If the media type includes an inherent encoding, such as a data format + that is always compressed, then that encoding would not be restated in + Content-Encoding even if it happens to be the same algorithm as one + of the content codings. Such a content coding would only be listed if, + for some bizarre reason, it is applied a second time to form the + representation. Likewise, an origin server might choose to publish the + same data as multiple representations that differ only in whether + the coding is defined as part of Content-Type or + Content-Encoding, since some user agents will behave differently in their + handling of each response (e.g., open a "Save as ..." dialog instead of + automatic decompression and rendering of content). + + + An origin server MAY respond with a status code of + 415 (Unsupported Media Type) if a representation in the + request message has a content coding that is not acceptable. + +
+ Content Codings + + + + + + + + Content coding values indicate an encoding transformation that has + been or can be applied to a representation. Content codings are primarily + used to allow a representation to be compressed or otherwise usefully + transformed without losing the identity of its underlying media type + and without loss of information. Frequently, the representation is stored + in coded form, transmitted directly, and only decoded by the final recipient. + + + content-coding = token + + + All content codings are case-insensitive and ought to be registered + within the "HTTP Content Coding Registry", as described in + + + + Content-coding values are used in the + Accept-Encoding () + and Content-Encoding () + header fields. + +
+ Compress Coding + + + The "compress" coding is an adaptive Lempel-Ziv-Welch (LZW) coding + that is commonly produced by the UNIX file + compression program "compress". + A recipient SHOULD consider "x-compress" to be equivalent to "compress". + +
+
+ Deflate Coding + + + The "deflate" coding is a "zlib" data format + containing a "deflate" compressed data stream + that uses a combination of the Lempel-Ziv (LZ77) compression algorithm and + Huffman coding. + + +
+
+ Gzip Coding + + + The "gzip" coding is an LZ77 coding with a 32-bit Cyclic Redundancy Check + (CRC) that is commonly + produced by the gzip file compression program . + A recipient SHOULD consider "x-gzip" to be equivalent to "gzip". + +
+
+
+
+ Content-Language + + + + + The "Content-Language" header field describes the natural + language(s) of the intended audience for the representation. Note that this might + not be equivalent to all the languages used within the representation. + + + Content-Language = #language-tag + + + Language tags are defined in . The primary purpose of + Content-Language is to allow a user to identify and differentiate + representations according to the users' own preferred language. Thus, if the + content is intended only for a Danish-literate audience, the + appropriate field is + + Content-Language: da + + + If no Content-Language is specified, the default is that the content + is intended for all language audiences. This might mean that the + sender does not consider it to be specific to any natural language, + or that the sender does not know for which language it is intended. + + + Multiple languages MAY be listed for content that is intended for + multiple audiences. For example, a rendition of the "Treaty of + Waitangi", presented simultaneously in the original Maori and English + versions, would call for + + Content-Language: mi, en + + + However, just because multiple languages are present within a representation + does not mean that it is intended for multiple linguistic audiences. + An example would be a beginner's language primer, such as "A First + Lesson in Latin", which is clearly intended to be used by an + English-literate audience. In this case, the Content-Language would + properly only include "en". + + + Content-Language MAY be applied to any media type -- it is not + limited to textual documents. + +
+ Language Tags + + A language tag, as defined in , identifies a + natural language spoken, written, or otherwise conveyed by human beings for + communication of information to other human beings. Computer languages are + explicitly excluded. + + + HTTP uses language tags within the Accept-Language and + Content-Language header fields. + Accept-Language uses the broader language-range production + defined in , whereas + Content-Language uses the language-tag production defined + below. + + + language-tag = <Language-Tag, see [RFC5646], Section 2.1> + + + A language tag is a sequence of one or more case-insensitive subtags, each + separated by a hyphen character ("-", %x2D). In most cases, a language tag + consists of a primary language subtag that identifies a broad family of + related languages (e.g., "en" = English), which is optionally followed by a + series of subtags that refine or narrow that language's range (e.g., + "en-CA" = the variety of English as communicated in Canada). + Whitespace is not allowed within a language tag. + Example tags include: + + + fr, en-US, es-419, az-Arab, x-pig-latin, man-Nkoo-GN + + + See for further information. + +
+
+
+ Content-Length + + + + + The "Content-Length" header field indicates the associated representation's + data length as a decimal non-negative integer number of octets. + When transferring a representation as content, Content-Length refers + specifically to the amount of data enclosed so that it can be used to + delimit framing (e.g., ). + In other cases, Content-Length indicates the selected representation's + current length, which can be used by recipients to estimate transfer time + or to compare with previously stored representations. + + + Content-Length = 1*DIGIT + + + An example is + + Content-Length: 3495 + + + A user agent SHOULD send Content-Length in a request when the method + defines a meaning for enclosed content and it is not sending + Transfer-Encoding. + For example, a user agent normally sends Content-Length in a POST request + even when the value is 0 (indicating empty content). + A user agent SHOULD NOT send a + Content-Length header field when the request message does not contain + content and the method semantics do not anticipate such data. + + + A server MAY send a Content-Length header field in a response to a HEAD + request (); a server MUST NOT send Content-Length in such a + response unless its field value equals the decimal number of octets that + would have been sent in the content of a response if the same + request had used the GET method. + + + A server MAY send a Content-Length header field in a + 304 (Not Modified) response to a conditional GET request + (); a server MUST NOT send Content-Length in such a + response unless its field value equals the decimal number of octets that + would have been sent in the content of a 200 (OK) + response to the same request. + + + A server MUST NOT send a Content-Length header field in any response + with a status code of + 1xx (Informational) or 204 (No Content). + A server MUST NOT send a Content-Length header field in any + 2xx (Successful) response to a CONNECT request (). + + + Aside from the cases defined above, in the absence of Transfer-Encoding, + an origin server SHOULD send a Content-Length header field when the + content size is known prior to sending the complete header section. + This will allow downstream recipients to measure transfer progress, + know when a received message is complete, and potentially reuse the + connection for additional requests. + + + Any Content-Length field value greater than or equal to zero is valid. + Since there is no predefined limit to the length of content, a + recipient MUST anticipate potentially large decimal numerals and + prevent parsing errors due to integer conversion overflows + or precision loss due to integer conversion + (). + + + Because Content-Length is used for message delimitation in HTTP/1.1, + its field value can impact how the message is parsed by downstream + recipients even when the immediate connection is not using HTTP/1.1. + If the message is forwarded by a downstream intermediary, a Content-Length + field value that is inconsistent with the received message framing might + cause a security failure due to request smuggling or response splitting. + + + As a result, a sender MUST NOT forward a message with a + Content-Length header field value that is known to be incorrect. + + + Likewise, a sender MUST NOT forward a message with a Content-Length + header field value that does not match the ABNF above, with one exception: + a recipient of a Content-Length header field value consisting of the same + decimal value repeated as a comma-separated list (e.g, + "Content-Length: 42, 42") MAY either reject the message as invalid or + replace that invalid field value with a single instance of the decimal + value, since this likely indicates that a duplicate was generated or + combined by an upstream message processor. + +
+
+ Content-Location + + + + + The "Content-Location" header field references a URI that can be used + as an identifier for a specific resource corresponding to the + representation in this message's content. + In other words, if one were to perform a GET request on this URI at the time + of this message's generation, then a 200 (OK) response would + contain the same representation that is enclosed as content in this message. + + + Content-Location = absolute-URI / partial-URI + + + The field value is either an absolute-URI or a + partial-URI. In the latter case (), + the referenced URI is relative to the target URI + (). + + + The Content-Location value is not a replacement for the target URI + (). It is representation metadata. + It has the same syntax and semantics as the header field of the same name + defined for MIME body parts in . + However, its appearance in an HTTP message has some special implications + for HTTP recipients. + + + If Content-Location is included in a 2xx (Successful) + response message and its value refers (after conversion to absolute form) + to a URI that is the same as the target URI, then + the recipient MAY consider the content to be a current representation of + that resource at the time indicated by the message origination date. + For a GET () or HEAD () request, + this is the same as the default semantics when no Content-Location is + provided by the server. + For a state-changing request like PUT () or + POST (), it implies that the server's response + contains the new representation of that resource, thereby distinguishing it + from representations that might only report about the action + (e.g., "It worked!"). + This allows authoring applications to update their local copies without + the need for a subsequent GET request. + + + If Content-Location is included in a 2xx (Successful) + response message and its field value refers to a URI that differs from the + target URI, then the origin server claims that the URI + is an identifier for a different resource corresponding to the enclosed + representation. Such a claim can only be trusted if both identifiers share + the same resource owner, which cannot be programmatically determined via + HTTP. + +
    +
  • For a response to a GET or HEAD request, this is an indication that the + target URI refers to a resource that is subject to content + negotiation and the Content-Location field value is a more specific + identifier for the selected representation.
  • +
  • For a 201 (Created) response to a state-changing method, + a Content-Location field value that is identical to the + Location field value indicates that this content is a + current representation of the newly created resource.
  • +
  • Otherwise, such a Content-Location indicates that this content is a + representation reporting on the requested action's status and that the + same report is available (for future access with GET) at the given URI. + For example, a purchase transaction made via a POST request might + include a receipt document as the content of the 200 (OK) + response; the Content-Location field value provides an identifier for + retrieving a copy of that same receipt in the future.
  • +
+ + A user agent that sends Content-Location in a request message is stating + that its value refers to where the user agent originally obtained the + content of the enclosed representation (prior to any modifications made by + that user agent). In other words, the user agent is providing a back link + to the source of the original representation. + + + An origin server that receives a Content-Location field in a request + message MUST treat the information as transitory request context rather + than as metadata to be saved verbatim as part of the representation. + An origin server MAY use that context to guide in processing the + request or to save it for other uses, such as within source links or + versioning metadata. However, an origin server MUST NOT use such context + information to alter the request semantics. + + + For example, if a client makes a PUT request on a negotiated resource and + the origin server accepts that PUT (without redirection), then the new + state of that resource is expected to be consistent with the one + representation supplied in that PUT; the Content-Location cannot be used as + a form of reverse content selection identifier to update only one of the + negotiated representations. If the user agent had wanted the latter + semantics, it would have applied the PUT directly to the Content-Location + URI. + +
+
+ Validator Fields + + + + + Resource metadata is referred to as a "validator" if it + can be used within a precondition () to + make a conditional request (). + Validator fields convey a current validator for the + selected representation + (). + + + In responses to safe requests, validator fields describe the selected + representation chosen by the origin server while handling the response. + Note that, depending on the method and status code semantics, the + selected representation for a given response is not + necessarily the same as the representation enclosed as response content. + + + In a successful response to a state-changing request, validator fields + describe the new representation that has replaced the prior + selected representation as a result of processing the + request. + + + For example, an ETag field in a 201 (Created) response + communicates the entity tag of the newly created resource's + representation, so that the entity tag can be used as a validator in + later conditional requests to prevent the "lost update" problem. + + + This specification defines two forms of metadata that are commonly used + to observe resource state and test for preconditions: modification dates + () and opaque entity tags + (). + Additional metadata that reflects resource state + has been defined by various extensions of HTTP, such as Web Distributed + Authoring and Versioning , that are beyond the + scope of this specification. + +
+ Weak versus Strong + + + + Validators come in two flavors: strong or weak. Weak validators are easy + to generate but are far less useful for comparisons. Strong validators + are ideal for comparisons but can be very difficult (and occasionally + impossible) to generate efficiently. Rather than impose that all forms + of resource adhere to the same strength of validator, HTTP exposes the + type of validator in use and imposes restrictions on when weak validators + can be used as preconditions. + + + A "strong validator" is representation metadata that changes value whenever + a change occurs to the representation data that would be observable in the + content of a 200 (OK) response to GET. + + + A strong validator might change for reasons other than a change to the + representation data, such as when a + semantically significant part of the representation metadata is changed + (e.g., Content-Type), but it is in the best interests of the + origin server to only change the value when it is necessary to invalidate + the stored responses held by remote caches and authoring tools. + + + Cache entries might persist for arbitrarily long periods, regardless + of expiration times. Thus, a cache might attempt to validate an + entry using a validator that it obtained in the distant past. + A strong validator is unique across all versions of all + representations associated with a particular resource over time. + However, there is no implication of uniqueness across representations + of different resources (i.e., the same strong validator might be + in use for representations of multiple resources at the same time + and does not imply that those representations are equivalent). + + + There are a variety of strong validators used in practice. The best are + based on strict revision control, wherein each change to a representation + always results in a unique node name and revision identifier being assigned + before the representation is made accessible to GET. + A collision-resistant hash + function applied to the representation data is also sufficient if the data + is available prior to the response header fields being sent and the digest + does not need to be recalculated every time a validation request is + received. However, if a resource has distinct representations that differ + only in their metadata, such as might occur with content negotiation over + media types that happen to share the same data format, then the origin + server needs to incorporate additional information in the validator to + distinguish those representations. + + + In contrast, a "weak validator" is representation metadata + that might not change for every change to the representation data. This + weakness might be due to limitations in how the value is calculated + (e.g., clock resolution), an inability to ensure uniqueness for all + possible representations of the resource, or a desire of the resource + owner to group representations by some self-determined set of + equivalency rather than unique sequences of data. + + + An origin server SHOULD change a weak entity tag whenever it + considers prior representations to be unacceptable as a substitute for + the current representation. In other words, a weak entity tag ought to + change whenever the origin server wants caches to invalidate old + responses. + + + For example, the representation of a weather report that changes in + content every second, based on dynamic measurements, might be grouped + into sets of equivalent representations (from the origin server's + perspective) with the same weak validator in order to allow cached + representations to be valid for a reasonable period of time (perhaps + adjusted dynamically based on server load or weather quality). + Likewise, a representation's modification time, if defined with only + one-second resolution, might be a weak validator if it is possible + for the representation to be modified twice during a single second and + retrieved between those modifications. + + + Likewise, a validator is weak if it is shared by two or more + representations of a given resource at the same time, unless those + representations have identical representation data. For example, if the + origin server sends the same validator for a representation with a gzip + content coding applied as it does for a representation with no content + coding, then that validator is weak. However, two simultaneous + representations might share the same strong validator if they differ only + in the representation metadata, such as when two different media types are + available for the same representation data. + + + Strong validators are usable for all conditional requests, including cache + validation, partial content ranges, and "lost update" avoidance. + Weak validators are only usable when the client does not require exact + equality with previously obtained representation data, such as when + validating a cache entry or limiting a web traversal to recent changes. + +
+
+ Last-Modified + + + + + The "Last-Modified" header field in a response provides a timestamp + indicating the date and time at which the origin server believes the + selected representation was last modified, as determined at the conclusion + of handling the request. + + + Last-Modified = HTTP-date + + + An example of its use is + + Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT + +
+ Generation + + An origin server SHOULD send Last-Modified for any selected + representation for which a last modification date can be reasonably + and consistently determined, since its use in conditional requests + and evaluating cache freshness () can + substantially reduce unnecessary transfers and significantly + improve service availability and scalability. + + + A representation is typically the sum of many parts behind the + resource interface. The last-modified time would usually be + the most recent time that any of those parts were changed. + How that value is determined for any given resource is an + implementation detail beyond the scope of this specification. + + + An origin server SHOULD obtain the Last-Modified value of the + representation as close as possible to the time that it generates the + Date field value for its response. This allows a recipient to + make an accurate assessment of the representation's modification time, + especially if the representation changes near the time that the + response is generated. + + + An origin server with a clock (as defined in ) + MUST NOT generate a Last-Modified date that is later than the + server's time of message origination + (Date, ). + If the last modification time is derived from implementation-specific + metadata that evaluates to some time in the future, according to the + origin server's clock, then the origin server MUST replace that + value with the message origination date. This prevents a future + modification date from having an adverse impact on cache validation. + + + An origin server without a clock MUST NOT generate a Last-Modified + date for a response unless that date value was assigned to the resource + by some other system (presumably one with a clock). + +
+
+ Comparison + + A Last-Modified time, when used as a validator in a request, is + implicitly weak unless it is possible to deduce that it is strong, + using the following rules: + +
    +
  • The validator is being compared by an origin server to the + actual current validator for the representation and,
  • +
  • That origin server reliably knows that the associated representation did + not change twice during the second covered by the presented + validator;
  • +
+ + or + +
    +
  • The validator is about to be used by a client in an + If-Modified-Since, + If-Unmodified-Since, or If-Range header + field, because the client has a cache entry for the associated + representation, and
  • +
  • That cache entry includes a Date value which is + at least one second after the Last-Modified value and + the client has reason to believe that they were generated by the + same clock or that there is enough difference between the Last-Modified + and Date values to make clock synchronization issues unlikely;
  • +
+ + or + +
    +
  • The validator is being compared by an intermediate cache to the + validator stored in its cache entry for the representation, and
  • +
  • That cache entry includes a Date value which is + at least one second after the Last-Modified value and + the cache has reason to believe that they were generated by the + same clock or that there is enough difference between the Last-Modified + and Date values to make clock synchronization issues unlikely.
  • +
+ + This method relies on the fact that if two different responses were + sent by the origin server during the same second, but both had the + same Last-Modified time, then at least one of those responses would + have a Date value equal to its Last-Modified time. + +
+
+
+ ETag + + + + + + The "ETag" field in a response provides the current entity tag for + the selected representation, as determined at the conclusion of handling + the request. + An entity tag is an opaque validator for differentiating between + multiple representations of the same resource, regardless of whether + those multiple representations are due to resource state changes over + time, content negotiation resulting in multiple representations being + valid at the same time, or both. An entity tag consists of an opaque + quoted string, possibly prefixed by a weakness indicator. + + + + + + + ETag = entity-tag + + entity-tag = [ weak ] opaque-tag + weak = %s"W/" + opaque-tag = DQUOTE *etagc DQUOTE + etagc = %x21 / %x23-7E / obs-text + ; VCHAR except double quotes, plus obs-text + + + + An entity tag can be more reliable for validation than a modification + date in situations where it is inconvenient to store modification + dates, where the one-second resolution of HTTP-date values is not + sufficient, or where modification dates are not consistently maintained. + + + Examples: + + ETag: "xyzzy" +ETag: W/"xyzzy" +ETag: "" + + + An entity tag can be either a weak or strong validator, with + strong being the default. If an origin server provides an entity tag + for a representation and the generation of that entity tag does not satisfy + all of the characteristics of a strong validator + (), then the origin server + MUST mark the entity tag as weak by prefixing its opaque value + with "W/" (case-sensitive). + + + A sender MAY send the ETag field in a trailer section (see + ). However, since trailers are often + ignored, it is preferable to send ETag as a header field unless the + entity tag is generated while sending the content. + +
+ Generation + + The principle behind entity tags is that only the service author + knows the implementation of a resource well enough to select the + most accurate and efficient validation mechanism for that resource, + and that any such mechanism can be mapped to a simple sequence of + octets for easy comparison. Since the value is opaque, there is no + need for the client to be aware of how each entity tag is constructed. + + + For example, a resource that has implementation-specific versioning + applied to all changes might use an internal revision number, perhaps + combined with a variance identifier for content negotiation, to + accurately differentiate between representations. + Other implementations might use a collision-resistant hash of + representation content, a combination of various file attributes, or + a modification timestamp that has sub-second resolution. + + + An origin server SHOULD send an ETag for any selected representation + for which detection of changes can be reasonably and consistently + determined, since the entity tag's use in conditional requests and + evaluating cache freshness () can + substantially reduce unnecessary transfers and significantly + improve service availability, scalability, and reliability. + +
+
+ Comparison + + There are two entity tag comparison functions, depending on whether or not + the comparison context allows the use of weak validators: + +
+
+ "Strong comparison": +
+
+ two entity tags are equivalent if both are not weak and their opaque-tags + match character-by-character. +
+
+ "Weak comparison": +
+
+ two entity tags are equivalent if their opaque-tags match + character-by-character, regardless of either or both being tagged as "weak". +
+
+ + The example below shows the results for a set of entity tag pairs and both + the weak and strong comparison function results: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ETag 1ETag 2Strong ComparisonWeak Comparison
W/"1"W/"1"no matchmatch
W/"1"W/"2"no matchno match
W/"1""1"no matchmatch
"1""1"matchmatch
+
+
+ Example: Entity Tags Varying on Content-Negotiated Resources + + Consider a resource that is subject to content negotiation + (), and where the representations sent in response to + a GET request vary based on the Accept-Encoding request + header field (): + + + >> Request: + + GET /index HTTP/1.1 +Host: www.example.com +Accept-Encoding: gzip + + + + In this case, the response might or might not use the gzip content coding. + If it does not, the response might look like: + + + >> Response: + + HTTP/1.1 200 OK +Date: Fri, 26 Mar 2010 00:05:00 GMT +ETag: "123-a" +Content-Length: 70 +Vary: Accept-Encoding +Content-Type: text/plain + +Hello World! +Hello World! +Hello World! +Hello World! +Hello World! + + + An alternative representation that does use gzip content coding would be: + + + >> Response: + + HTTP/1.1 200 OK +Date: Fri, 26 Mar 2010 00:05:00 GMT +ETag: "123-b" +Content-Length: 43 +Vary: Accept-Encoding +Content-Type: text/plain +Content-Encoding: gzip + +...binary data... + +
+
+
+
+
+ Methods +
+ Overview + + The request method token is the primary source of request semantics; + it indicates the purpose for which the client has made this request + and what is expected by the client as a successful result. + + + The request method's semantics might be further specialized by the + semantics of some header fields when present in a request + if those additional semantics do not conflict with the method. + For example, a client can send conditional request header fields + () to make the requested + action conditional on the current state of the target resource. + + + HTTP is designed to be usable as an interface to distributed + object systems. The request method invokes an action to be applied to + a target resource in much the same way that a remote + method invocation can be sent to an identified object. + + + method = token + + + The method token is case-sensitive because it might be used as a gateway + to object-based systems with case-sensitive method names. By convention, + standardized methods are defined in all-uppercase US-ASCII letters. + + + Unlike distributed objects, the standardized request methods in HTTP are + not resource-specific, since uniform interfaces provide for better + visibility and reuse in network-based systems . + Once defined, a standardized method ought to have the same semantics when + applied to any resource, though each resource determines for itself + whether those semantics are implemented or allowed. + + + This specification defines a number of standardized methods that are + commonly used in HTTP, as outlined by the following table. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Method NameDescriptionSection
GETTransfer a current representation of the target resource. + +
HEADSame as GET, but do not transfer the response content. + +
POSTPerform resource-specific processing on the request content. + +
PUTReplace all current representations of the target resource with + the request content. + +
DELETERemove all current representations of the target resource. + +
CONNECTEstablish a tunnel to the server identified by the target resource. + +
OPTIONSDescribe the communication options for the target resource. + +
TRACEPerform a message loop-back test along the path to the target resource. + +
+ + All general-purpose servers MUST support the methods GET and HEAD. + All other methods are OPTIONAL. + + + The set of methods allowed by a target resource can be listed in an + Allow header field (). + However, the set of allowed methods can change dynamically. + An origin server that receives a request method that is unrecognized or + not implemented SHOULD respond with the + 501 (Not Implemented) status code. + An origin server that receives a request method that is recognized and + implemented, but not allowed for the target resource, SHOULD respond + with the 405 (Method Not Allowed) status code. + + + Additional methods, outside the scope of this specification, have been + specified for use in HTTP. All such methods ought to be registered + within the "Hypertext Transfer Protocol (HTTP) Method Registry", + as described in . + +
+
+ Common Method Properties +
+ Safe Methods + + + Request methods are considered "safe" if + their defined semantics are essentially read-only; i.e., the client does + not request, and does not expect, any state change on the origin server + as a result of applying a safe method to a target resource. Likewise, + reasonable use of a safe method is not expected to cause any harm, + loss of property, or unusual burden on the origin server. + + + This definition of safe methods does not prevent an implementation from + including behavior that is potentially harmful, that is not entirely read-only, + or that causes side effects while invoking a safe method. What is + important, however, is that the client did not request that additional + behavior and cannot be held accountable for it. For example, + most servers append request information to access log files at the + completion of every response, regardless of the method, and that is + considered safe even though the log storage might become full and cause + the server to fail. Likewise, a safe request initiated by selecting an + advertisement on the Web will often have the side effect of charging an + advertising account. + + + Of the request methods defined by this specification, the + GET, HEAD, OPTIONS, and + TRACE methods are defined to be safe. + + + The purpose of distinguishing between safe and unsafe methods is to + allow automated retrieval processes (spiders) and cache performance + optimization (pre-fetching) to work without fear of causing harm. + In addition, it allows a user agent to apply appropriate constraints + on the automated use of unsafe methods when processing potentially + untrusted content. + + + A user agent SHOULD distinguish between safe and unsafe methods when + presenting potential actions to a user, such that the user can be made + aware of an unsafe action before it is requested. + + + When a resource is constructed such that parameters within the target URI + have the effect of selecting an action, it is the resource + owner's responsibility to ensure that the action is consistent with the + request method semantics. + For example, it is common for Web-based content editing software + to use actions within query parameters, such as "page?do=delete". + If the purpose of such a resource is to perform an unsafe action, then + the resource owner MUST disable or disallow that action when it is + accessed using a safe request method. Failure to do so will result in + unfortunate side effects when automated processes perform a GET on + every URI reference for the sake of link maintenance, pre-fetching, + building a search index, etc. + +
+
+ Idempotent Methods + + + A request method is considered "idempotent" + if the intended effect on the server of multiple identical requests with + that method is the same as the effect for a single such request. + Of the request methods defined by this + specification, PUT, DELETE, and safe request + methods are idempotent. + + + Like the definition of safe, the idempotent property only applies to + what has been requested by the user; a server is free to log each request + separately, retain a revision control history, or implement other + non-idempotent side effects for each idempotent request. + + + Idempotent methods are distinguished because the request can be repeated + automatically if a communication failure occurs before the client is + able to read the server's response. For example, if a client sends a PUT + request and the underlying connection is closed before any response is + received, then the client can establish a new connection and retry the + idempotent request. It knows that repeating the request will have + the same intended effect, even if the original request succeeded, though + the response might differ. + + + A client SHOULD NOT automatically retry a request with a non-idempotent + method unless it has some means to know that the request semantics are + actually idempotent, regardless of the method, or some means to detect that + the original request was never applied. + + + For example, a user agent can repeat a POST request automatically if it + knows (through design or configuration) that the request is safe for that + resource. Likewise, a user agent designed specifically to operate on + a version control repository might be able to recover from partial failure + conditions by checking the target resource revision(s) after a failed + connection, reverting or fixing any changes that were partially applied, + and then automatically retrying the requests that failed. + + + Some clients take a riskier approach and attempt to guess when an + automatic retry is possible. For example, a client might automatically + retry a POST request if the underlying transport connection closed before + any part of a response is received, particularly if an idle persistent + connection was used. + + + A proxy MUST NOT automatically retry non-idempotent requests. + A client SHOULD NOT automatically retry a failed automatic retry. + +
+
+ Methods and Caching + + For a cache to store and use a response, the associated method needs to + explicitly allow caching and to detail under what conditions a response can + be used to satisfy subsequent requests; a method definition that does not + do so cannot be cached. For additional requirements see . + + + This specification defines caching semantics for GET, HEAD, and POST, + although the overwhelming majority of cache implementations only support + GET and HEAD. + +
+
+
+ Method Definitions +
+ GET + + + + The GET method requests transfer of a current + selected representation for the + target resource. + A successful response reflects the quality of "sameness" identified by + the target URI (). Hence, + retrieving identifiable information via HTTP is usually performed by + making a GET request on an identifier associated with the potential for + providing that information in a 200 (OK) response. + + + GET is the primary mechanism of information retrieval and the focus of + almost all performance optimizations. Applications that produce a URI for + each important resource can benefit from those optimizations while enabling + their reuse by other applications, creating a network effect that promotes + further expansion of the Web. + + + It is tempting to think of resource identifiers as remote file system + pathnames and of representations as being a copy of the contents of such + files. In fact, that is how many resources are implemented (see + for related security considerations). + However, there are no such limitations in practice. + + + The HTTP interface for + a resource is just as likely to be implemented as a tree of content + objects, a programmatic view on various database records, or a gateway to + other information systems. Even when the URI mapping mechanism is tied to a + file system, an origin server might be configured to execute the files with + the request as input and send the output as the representation rather than + transfer the files directly. Regardless, only the origin server needs to + know how each resource identifier corresponds to an implementation + and how that implementation manages to select and send a current + representation of the target resource. + + + A client can alter the semantics of GET to be a "range request", requesting + transfer of only some part(s) of the selected representation, by sending a + Range header field in the request (). + + + Although request message framing is independent of the method used, + content received in a GET request has no generally defined semantics, + cannot alter the meaning or target of the request, and might lead some + implementations to reject the request and close the connection because of + its potential as a request smuggling attack + (). + A client SHOULD NOT generate content in a GET request unless it is + made directly to an origin server that has previously indicated, + in or out of band, that such a request has a purpose and will be adequately + supported. An origin server SHOULD NOT rely on private agreements to + receive content, since participants in HTTP communication are often + unaware of intermediaries along the request chain. + + + The response to a GET request is cacheable; a cache MAY use it to satisfy + subsequent GET and HEAD requests unless otherwise indicated by the + Cache-Control header field (). + + + When information retrieval is performed with a mechanism that constructs a + target URI from user-provided information, such as the query fields of a + form using GET, potentially sensitive data might be provided that would not + be appropriate for disclosure within a URI + (see ). In some cases, the + data can be filtered or transformed such that it would not reveal such + information. In others, particularly when there is no benefit from caching + a response, using the POST method () instead of GET + can transmit such information in the request content rather than within + the target URI. + +
+
+ HEAD + + + + The HEAD method is identical to GET except that the server MUST NOT + send content in the response. HEAD is used to obtain metadata about the + selected representation without transferring its + representation data, often for the sake of testing hypertext links or + finding recent modifications. + + + The server SHOULD send the same header fields in response to a HEAD + request as it would have sent if the request method had been GET. + However, a server MAY omit header fields for which a value is determined + only while generating the content. For example, some servers buffer a + dynamic response to GET until a minimum amount of data is generated so + that they can more efficiently delimit small responses or make late + decisions with regard to content selection. Such a response to GET might + contain Content-Length and Vary fields, for + example, that are not generated within a HEAD response. These minor + inconsistencies are considered preferable to generating and discarding the + content for a HEAD request, since HEAD is usually requested for the + sake of efficiency. + + + Although request message framing is independent of the method used, + content received in a HEAD request has no generally defined semantics, + cannot alter the meaning or target of the request, and might lead some + implementations to reject the request and close the connection because of + its potential as a request smuggling attack + (). + A client SHOULD NOT generate content in a HEAD request unless it is + made directly to an origin server that has previously indicated, + in or out of band, that such a request has a purpose and will be adequately + supported. An origin server SHOULD NOT rely on private agreements to + receive content, since participants in HTTP communication are often + unaware of intermediaries along the request chain. + + + The response to a HEAD request is cacheable; a cache MAY use it to + satisfy subsequent HEAD requests unless otherwise indicated by the + Cache-Control header field (). + A HEAD response might also affect previously cached responses to GET; + see . + +
+
+ POST + + + + The POST method requests that the target resource process + the representation enclosed in the request according to the resource's own + specific semantics. For example, POST is used for the following functions + (among others): + +
    +
  • Providing a block of data, such as the fields entered into an HTML + form, to a data-handling process;
  • +
  • Posting a message to a bulletin board, newsgroup, mailing list, blog, + or similar group of articles;
  • +
  • Creating a new resource that has yet to be identified by the origin + server; and
  • +
  • Appending data to a resource's existing representation(s).
  • +
+ + An origin server indicates response semantics by choosing an appropriate + status code depending on the result of processing the POST request; + almost all of the status codes defined by this specification could be + received in a response to POST (the exceptions being 206 (Partial Content), + 304 (Not Modified), and 416 (Range Not Satisfiable)). + + + If one or more resources has been created on the origin server as a result + of successfully processing a POST request, the origin server SHOULD send + a 201 (Created) response containing a Location + header field that provides an identifier for the primary resource created + () and a representation that describes the + status of the request while referring to the new resource(s). + + + Responses to POST requests are only cacheable when they include explicit + freshness information (see ) and a + Content-Location header field that has the same value as + the POST's target URI (). A cached POST response can be reused + to satisfy a later GET or HEAD request. In contrast, a POST request cannot + be satisfied by a cached POST response because POST is potentially unsafe; + see . + + + If the result of processing a POST would be equivalent to a representation + of an existing resource, an origin server MAY redirect the user agent to + that resource by sending a 303 (See Other) response with the + existing resource's identifier in the Location field. + This has the benefits of providing the user agent a resource identifier + and transferring the representation via a method more amenable to shared + caching, though at the cost of an extra request if the user agent does not + already have the representation cached. + +
+
+ PUT + + + + The PUT method requests that the state of the target resource + be created or replaced with the state defined by the representation + enclosed in the request message content. A successful PUT of a given + representation would suggest that a subsequent GET on that same target + resource will result in an equivalent representation being sent in + a 200 (OK) response. However, there is no guarantee that + such a state change will be observable, since the target resource might be + acted upon by other user agents in parallel, or might be subject to dynamic + processing by the origin server, before any subsequent GET is received. + A successful response only implies that the user agent's intent was + achieved at the time of its processing by the origin server. + + + If the target resource does not have a current representation and + the PUT successfully creates one, then the origin server MUST inform + the user agent by sending a 201 (Created) response. If the + target resource does have a current representation and that representation is + successfully modified in accordance with the state of the enclosed + representation, then the origin server MUST send either a + 200 (OK) or a 204 (No Content) response to + indicate successful completion of the request. + + + An origin server SHOULD verify that the PUT representation is consistent + with its configured constraints for the target resource. For example, if + an origin server determines a resource's representation metadata based on + the URI, then the origin server needs to ensure that the content received + in a successful PUT request is consistent with that metadata. When a PUT + representation is inconsistent with the target resource, the origin + server SHOULD either make them consistent, by transforming the + representation or changing the resource configuration, or respond + with an appropriate error message containing sufficient information + to explain why the representation is unsuitable. The + 409 (Conflict) or 415 (Unsupported Media Type) + status codes are suggested, with the latter being specific to constraints on + Content-Type values. + + + For example, if the target resource is configured to always have a + Content-Type of "text/html" and the representation being PUT + has a Content-Type of "image/jpeg", the origin server ought to do one of: + +
    +
  1. reconfigure the target resource to reflect the new media type;
  2. +
  3. transform the PUT representation to a format consistent with that + of the resource before saving it as the new resource state; or,
  4. +
  5. reject the request with a 415 (Unsupported Media Type) + response indicating that the target resource is limited to "text/html", + perhaps including a link to a different resource that would be a + suitable target for the new representation.
  6. +
+ + HTTP does not define exactly how a PUT method affects the state + of an origin server beyond what can be expressed by the intent of + the user agent request and the semantics of the origin server response. + It does not define what a resource might be, in any sense of that + word, beyond the interface provided via HTTP. It does not define + how resource state is "stored", nor how such storage might change + as a result of a change in resource state, nor how the origin server + translates resource state into representations. Generally speaking, + all implementation details behind the resource interface are + intentionally hidden by the server. + + + This extends to how header and trailer fields are stored; while common + header fields like Content-Type will typically be stored + and returned upon subsequent GET requests, header and trailer field + handling is specific to the resource that received the request. As a result, + an origin server SHOULD ignore unrecognized header and trailer fields + received in a PUT request (i.e., not save them as part of the resource + state). + + + An origin server MUST NOT send a validator field + (), such as an ETag or + Last-Modified field, in a successful response to PUT unless + the request's representation data was saved without any transformation + applied to the content (i.e., the resource's new representation data is + identical to the content received in the PUT request) and the + validator field value reflects the new representation. + This requirement allows a user agent to know when the representation it + sent (and retains in memory) is the result of the PUT, and thus it doesn't + need to be retrieved again from the origin server. The new validator(s) + received in the response can be used for future conditional requests in + order to prevent accidental overwrites (). + + + The fundamental difference between the POST and PUT methods is + highlighted by the different intent for the enclosed representation. + The target resource in a POST request is intended to handle the + enclosed representation according to the resource's own semantics, + whereas the enclosed representation in a PUT request is defined as + replacing the state of the target resource. Hence, the intent of PUT is + idempotent and visible to intermediaries, even though the exact effect is + only known by the origin server. + + + Proper interpretation of a PUT request presumes that the user agent knows + which target resource is desired. A service that selects a proper URI on + behalf of the client, after receiving a state-changing request, SHOULD be + implemented using the POST method rather than PUT. If the origin server + will not make the requested PUT state change to the target resource and + instead wishes to have it applied to a different resource, such as when the + resource has been moved to a different URI, then the origin server MUST + send an appropriate 3xx (Redirection) response; the + user agent MAY then make its own decision regarding whether or not to + redirect the request. + + + A PUT request applied to the target resource can have side effects + on other resources. For example, an article might have a URI for + identifying "the current version" (a resource) that is separate + from the URIs identifying each particular version (different + resources that at one point shared the same state as the current version + resource). A successful PUT request on "the current version" URI might + therefore create a new version resource in addition to changing the + state of the target resource, and might also cause links to be added + between the related resources. + + + Some origin servers support use of the Content-Range header + field () as a request modifier to + perform a partial PUT, as described in . + + + Responses to the PUT method are not cacheable. If a successful PUT request + passes through a cache that has one or more stored responses for the + target URI, those stored responses will be invalidated + (see ). + +
+
+ DELETE + + + + The DELETE method requests that the origin server remove the association + between the target resource and its current functionality. + In effect, this method is similar to the "rm" command in UNIX: it expresses a + deletion operation on the URI mapping of the origin server rather than an + expectation that the previously associated information be deleted. + + + If the target resource has one or more current representations, they might + or might not be destroyed by the origin server, and the associated storage + might or might not be reclaimed, depending entirely on the nature of the + resource and its implementation by the origin server (which are beyond the + scope of this specification). Likewise, other implementation aspects of a + resource might need to be deactivated or archived as a result of a DELETE, + such as database or gateway connections. In general, it is assumed that the + origin server will only allow DELETE on resources for which it has a + prescribed mechanism for accomplishing the deletion. + + + Relatively few resources allow the DELETE method -- its primary use + is for remote authoring environments, where the user has some direction + regarding its effect. For example, a resource that was previously created + using a PUT request, or identified via the Location header field after a + 201 (Created) response to a POST request, might allow a + corresponding DELETE request to undo those actions. Similarly, custom + user agent implementations that implement an authoring function, such as + revision control clients using HTTP for remote operations, might use + DELETE based on an assumption that the server's URI space has been crafted + to correspond to a version repository. + + + If a DELETE method is successfully applied, the origin server SHOULD send + +
    +
  • a 202 (Accepted) status code if the action will likely succeed but + has not yet been enacted,
  • +
  • a 204 (No Content) status code if the action has been + enacted and no further information is to be supplied, or
  • +
  • a 200 (OK) status code if the action has been enacted and + the response message includes a representation describing the status.
  • +
+ + Although request message framing is independent of the method used, + content received in a DELETE request has no generally defined semantics, + cannot alter the meaning or target of the request, and might lead some + implementations to reject the request and close the connection because of + its potential as a request smuggling attack + (). + A client SHOULD NOT generate content in a DELETE request unless it is + made directly to an origin server that has previously indicated, + in or out of band, that such a request has a purpose and will be adequately + supported. An origin server SHOULD NOT rely on private agreements to + receive content, since participants in HTTP communication are often + unaware of intermediaries along the request chain. + + + Responses to the DELETE method are not cacheable. If a successful DELETE + request passes through a cache that has one or more stored responses for + the target URI, those stored responses will be invalidated (see + ). + +
+
+ CONNECT + + + + The CONNECT method requests that the recipient establish a tunnel to the + destination origin server identified by the request target and, if + successful, thereafter restrict its behavior to blind forwarding of + data, in both directions, until the tunnel is closed. + Tunnels are commonly used to create an end-to-end virtual connection, + through one or more proxies, which can then be secured using TLS + (Transport Layer Security, ). + + + CONNECT uses a special form of request target, unique to this method, + consisting of only the host and port number of the tunnel destination, + separated by a colon. There is no default port; a client MUST send the + port number even if the CONNECT request is based on a URI reference that + contains an authority component with an elided port + (). For example, + + CONNECT server.example.com:80 HTTP/1.1 +Host: server.example.com + + + + A server MUST reject a CONNECT request that targets an empty or invalid + port number, typically by responding with a 400 (Bad Request) status code. + + + Because CONNECT changes the request/response nature of an HTTP connection, + specific HTTP versions might have different ways of mapping its semantics + into the protocol's wire format. + + + CONNECT is intended for use in requests to a proxy. + The recipient can establish a tunnel either by directly connecting to + the server identified by the request target or, if configured to use + another proxy, by forwarding the CONNECT request to the next inbound proxy. + An origin server MAY accept a CONNECT request, but most origin servers + do not implement CONNECT. + + + Any 2xx (Successful) response indicates + that the sender (and all inbound proxies) will switch to tunnel mode + immediately after the response header section; data received after that + header section is from the server identified by the request target. + Any response other than a successful response indicates that the tunnel + has not yet been formed. + + + A tunnel is closed when a tunnel intermediary detects that either side + has closed its connection: the intermediary MUST attempt to send any + outstanding data that came from the closed side to the other side, close + both connections, and then discard any remaining data left undelivered. + + + Proxy authentication might be used to establish the + authority to create a tunnel. For example, + + CONNECT server.example.com:443 HTTP/1.1 +Host: server.example.com:443 +Proxy-Authorization: basic aGVsbG86d29ybGQ= + + + + There are significant risks in establishing a tunnel to arbitrary servers, + particularly when the destination is a well-known or reserved TCP port that + is not intended for Web traffic. For example, a CONNECT to + "example.com:25" would suggest that the proxy connect to the reserved + port for SMTP traffic; if allowed, that could trick the proxy into + relaying spam email. Proxies that support CONNECT SHOULD restrict its + use to a limited set of known ports or a configurable list of safe + request targets. + + + A server MUST NOT send any Transfer-Encoding or + Content-Length header fields in a + 2xx (Successful) response to CONNECT. + A client MUST ignore any Content-Length or Transfer-Encoding header + fields received in a successful response to CONNECT. + + + A CONNECT request message does not have content. The interpretation of + data sent after the header section of the CONNECT request message is + specific to the version of HTTP in use. + + + Responses to the CONNECT method are not cacheable. + +
+
+ OPTIONS + + + + The OPTIONS method requests information about the communication options + available for the target resource, at either the origin server or an + intervening intermediary. This method allows a client to determine the + options and/or requirements associated with a resource, or the capabilities + of a server, without implying a resource action. + + + An OPTIONS request with an asterisk ("*") as the request target + () applies to the server in general rather than to a + specific resource. Since a server's communication options typically depend + on the resource, the "*" request is only useful as a "ping" or "no-op" + type of method; it does nothing beyond allowing the client to test + the capabilities of the server. For example, this can be used to test + a proxy for HTTP/1.1 conformance (or lack thereof). + + + If the request target is not an asterisk, the OPTIONS request applies + to the options that are available when communicating with the target + resource. + + + A server generating a successful response to OPTIONS SHOULD send any + header that might indicate optional features implemented by the + server and applicable to the target resource (e.g., Allow), + including potential extensions not defined by this specification. + The response content, if any, might also describe the communication options + in a machine or human-readable representation. A standard format for such a + representation is not defined by this specification, but might be defined by + future extensions to HTTP. + + + A client MAY send a Max-Forwards header field in an + OPTIONS request to target a specific recipient in the request chain (see + ). A proxy MUST NOT generate a + Max-Forwards header field while forwarding a request unless that request + was received with a Max-Forwards field. + + + A client that generates an OPTIONS request containing content + MUST send a valid Content-Type header field describing + the representation media type. Note that this specification does not define + any use for such content. + + + Responses to the OPTIONS method are not cacheable. + +
+
+ TRACE + + + + The TRACE method requests a remote, application-level loop-back of the + request message. The final recipient of the request SHOULD reflect the + message received, excluding some fields described below, back to the client + as the content of a 200 (OK) response. The "message/http" + format () is one way to do so. + The final recipient is either the origin server or the first server to + receive a Max-Forwards value of zero (0) in the request + (). + + + A client MUST NOT generate fields in a TRACE request containing + sensitive data that might be disclosed by the response. For example, it + would be foolish for a user agent to send stored user credentials + () or cookies in a TRACE + request. The final recipient of the request SHOULD exclude any request + fields that are likely to contain sensitive data when that recipient + generates the response content. + + + TRACE allows the client to see what is being received at the other + end of the request chain and use that data for testing or diagnostic + information. The value of the Via header field () + is of particular interest, since it acts as a trace of the request chain. + Use of the Max-Forwards header field allows the client to + limit the length of the request chain, which is useful for testing a chain + of proxies forwarding messages in an infinite loop. + + + A client MUST NOT send content in a TRACE request. + + + Responses to the TRACE method are not cacheable. + +
+
+
+
+ Message Context +
+ Request Context Fields + + The request header fields below provide additional information about the + request context, including information about the user, user agent, and + resource behind the request. + +
+ Expect + + + + + + The "Expect" header field in a request indicates a certain set of + behaviors (expectations) that need to be supported by the server in + order to properly handle this request. + + + Expect = #expectation + expectation = token [ "=" ( token / quoted-string ) parameters ] + + + The Expect field value is case-insensitive. + + + The only expectation defined by this specification is "100-continue" + (with no defined parameters). + + + A server that receives an Expect field value containing a member other than + 100-continue + MAY respond with a + 417 (Expectation Failed) status code to indicate that the + unexpected expectation cannot be met. + + + A "100-continue" expectation informs recipients that the + client is about to send (presumably large) content in this request + and wishes to receive a 100 (Continue) interim response if + the method, target URI, and header fields are not sufficient to cause an immediate + success, redirect, or error response. This allows the client to wait for an + indication that it is worthwhile to send the content before actually + doing so, which can improve efficiency when the data is huge or + when the client anticipates that an error is likely (e.g., when sending a + state-changing method, for the first time, without previously verified + authentication credentials). + + + For example, a request that begins with + + PUT /somewhere/fun HTTP/1.1 +Host: origin.example.com +Content-Type: video/h264 +Content-Length: 1234567890987 +Expect: 100-continue + + + + allows the origin server to immediately respond with an error message, such + as 401 (Unauthorized) or 405 (Method Not Allowed), + before the client starts filling the pipes with an unnecessary data + transfer. + + + Requirements for clients: + +
    +
  • + A client MUST NOT generate a 100-continue expectation in a request that + does not include content. +
  • +
  • + A client that will wait for a 100 (Continue) response + before sending the request content MUST send an + Expect header field containing a 100-continue expectation. +
  • +
  • + A client that sends a 100-continue expectation is not required to wait + for any specific length of time; such a client MAY proceed to send the + content even if it has not yet received a response. Furthermore, + since 100 (Continue) responses cannot be sent through an + HTTP/1.0 intermediary, such a client SHOULD NOT wait for an indefinite + period before sending the content. +
  • +
  • + A client that receives a 417 (Expectation Failed) status + code in response to a request containing a 100-continue expectation + SHOULD repeat that request without a 100-continue expectation, since + the 417 response merely indicates that the response chain does not + support expectations (e.g., it passes through an HTTP/1.0 server). +
  • +
+ + Requirements for servers: + +
    +
  • + A server that receives a 100-continue expectation in an HTTP/1.0 request + MUST ignore that expectation. +
  • +
  • + A server MAY omit sending a 100 (Continue) response if + it has already received some or all of the content for the + corresponding request, or if the framing indicates that there is no + content. +
  • +
  • + A server that sends a 100 (Continue) response MUST + ultimately send a final status code, once it receives and processes the + request content, unless the connection is closed prematurely. +
  • +
  • + A server that responds with a final status code before reading the + entire request content SHOULD indicate whether it intends to + close the connection (e.g., see ) or + continue reading the request content. +
  • +
+ + Upon receiving an HTTP/1.1 (or later) request that has a method, target URI, + and complete header section that contains a 100-continue expectation and + an indication that request content will follow, an origin server MUST + send either: + +
    +
  • an immediate response with a final status code, if that status can be + determined by examining just the method, target URI, and header fields, or
  • +
  • an immediate 100 (Continue) response to encourage the client + to send the request content.
  • +
+ + The origin server MUST NOT wait for the content + before sending the 100 (Continue) response. + + + Upon receiving an HTTP/1.1 (or later) request that has a method, target URI, + and complete header section that contains a 100-continue expectation and + indicates a request content will follow, a proxy MUST either: + +
    +
  • send an immediate + response with a final status code, if that status can be determined by + examining just the method, target URI, and header fields, or
  • +
  • forward the request toward the origin server by sending a corresponding + request-line and header section to the next inbound server.
  • +
+ + If the proxy believes (from configuration or past interaction) that the + next inbound server only supports HTTP/1.0, the proxy MAY generate an + immediate 100 (Continue) response to encourage the client to + begin sending the content. + +
+
+ From + + + + + The "From" header field contains an Internet email address for a human + user who controls the requesting user agent. The address ought to be + machine-usable, as defined by "mailbox" + in : + + + From = mailbox + + mailbox = <mailbox, see [RFC5322], Section 3.4> + + + An example is: + + From: spider-admin@example.org + + + The From header field is rarely sent by non-robotic user agents. + A user agent SHOULD NOT send a From header field without explicit + configuration by the user, since that might conflict with the user's + privacy interests or their site's security policy. + + + A robotic user agent SHOULD send a valid From header field so that the + person responsible for running the robot can be contacted if problems + occur on servers, such as if the robot is sending excessive, unwanted, + or invalid requests. + + + A server SHOULD NOT use the From header field for access control or + authentication, since its value is expected to be visible to anyone + receiving or observing the request and is often recorded within logfiles + and error reports without any expectation of privacy. + +
+
+ Referer + + + + + The "Referer" [sic] header field allows the user agent to specify a URI + reference for the resource from which the target URI was + obtained (i.e., the "referrer", though the field name is misspelled). + A user agent MUST NOT include the fragment and userinfo components + of the URI reference , if any, when generating the + Referer field value. + + + Referer = absolute-URI / partial-URI + + + The field value is either an absolute-URI or a + partial-URI. In the latter case (), + the referenced URI is relative to the target URI + (). + + + The Referer header field allows servers to generate back-links to other + resources for simple analytics, logging, optimized caching, etc. It also + allows obsolete or mistyped links to be found for maintenance. Some servers + use the Referer header field as a means of denying links from other sites + (so-called "deep linking") or restricting cross-site request forgery (CSRF), + but not all requests contain it. + + + Example: + + Referer: http://www.example.org/hypertext/Overview.html + + + If the target URI was obtained from a source that does not have its own + URI (e.g., input from the user keyboard, or an entry within the user's + bookmarks/favorites), the user agent MUST either exclude the Referer header field + or send it with a value of "about:blank". + + + The Referer header field value need not convey the full URI of the referring + resource; a user agent MAY truncate parts other than the referring origin. + + + The Referer header field has the potential to reveal information about the request + context or browsing history of the user, which is a privacy concern if the + referring resource's identifier reveals personal information (such as an + account name) or a resource that is supposed to be confidential (such as + behind a firewall or internal to a secured service). Most general-purpose + user agents do not send the Referer header field when the referring + resource is a local "file" or "data" URI. A user agent SHOULD NOT send a + Referer header field if the referring resource was accessed with + a secure protocol and the request target has an origin differing from that + of the referring resource, unless the referring resource explicitly allows + Referer to be sent. A user agent MUST NOT send a + Referer header field in an unsecured HTTP request if the + referring resource was accessed with a secure protocol. + See for additional + security considerations. + + + Some intermediaries have been known to indiscriminately remove Referer + header fields from outgoing requests. This has the unfortunate side effect + of interfering with protection against CSRF attacks, which can be far + more harmful to their users. Intermediaries and user agent extensions that + wish to limit information disclosure in Referer ought to restrict their + changes to specific edits, such as replacing internal domain names with + pseudonyms or truncating the query and/or path components. + An intermediary SHOULD NOT modify or delete the Referer header field when + the field value shares the same scheme and host as the target URI. + +
+
+ TE + + + + + The "TE" header field describes capabilities of the client with regard to + transfer codings and trailer sections. + + + As described in , + a TE field with a "trailers" member sent in a request indicates that the + client will not discard trailer fields. + + + TE is also used within HTTP/1.1 to advise servers about which transfer + codings the client is able to accept in a response. + As of publication, only HTTP/1.1 uses transfer codings + (see ). + + + The TE field value is a list of members, with each member (aside from + "trailers") consisting of a transfer coding name token with an optional + weight indicating the client's relative preference for that + transfer coding () and + optional parameters for that transfer coding. + + + + + + TE = #t-codings + t-codings = "trailers" / ( transfer-coding [ weight ] ) + transfer-coding = token *( OWS ";" OWS transfer-parameter ) + transfer-parameter = token BWS "=" BWS ( token / quoted-string ) + + + A sender of TE MUST also send a "TE" connection option within the + Connection header field () + to inform intermediaries not to forward this field. + +
+
+ User-Agent + + + + + The "User-Agent" header field contains information about the user agent + originating the request, which is often used by servers to help identify + the scope of reported interoperability problems, to work around or tailor + responses to avoid particular user agent limitations, and for analytics + regarding browser or operating system use. A user agent SHOULD send + a User-Agent header field in each request unless specifically configured not + to do so. + + + User-Agent = product *( RWS ( product / comment ) ) + + + The User-Agent field value consists of one or more product identifiers, + each followed by zero or more comments (), which together + identify the user agent software and its significant subproducts. + By convention, the product identifiers are listed in decreasing order of + their significance for identifying the user agent software. Each product + identifier consists of a name and optional version. + + + + product = token ["/" product-version] + product-version = token + + + A sender SHOULD limit generated product identifiers to what is necessary + to identify the product; a sender MUST NOT generate advertising or other + nonessential information within the product identifier. + A sender SHOULD NOT generate information in product-version + that is not a version identifier (i.e., successive versions of the same + product name ought to differ only in the product-version portion of the + product identifier). + + + Example: + + User-Agent: CERN-LineMode/2.15 libwww/2.17b3 + + + A user agent SHOULD NOT generate a User-Agent header field containing needlessly + fine-grained detail and SHOULD limit the addition of subproducts by third + parties. Overly long and detailed User-Agent field values increase request + latency and the risk of a user being identified against their wishes + ("fingerprinting"). + + + Likewise, implementations are encouraged not to use the product tokens of + other implementations in order to declare compatibility with them, as this + circumvents the purpose of the field. If a user agent masquerades as a + different user agent, recipients can assume that the user intentionally + desires to see responses tailored for that identified user agent, even + if they might not work as well for the actual user agent being used. + +
+
+
+ Response Context Fields + + The response header fields below provide additional information about the + response, beyond what is implied by the status code, including information + about the server, about the target resource, or about related + resources. + +
+ Allow + + + + + The "Allow" header field lists the set of methods advertised as + supported by the target resource. The purpose of this field + is strictly to inform the recipient of valid request methods associated + with the resource. + + + Allow = #method + + + Example of use: + + Allow: GET, HEAD, PUT + + + The actual set of allowed methods is defined by the origin server at the + time of each request. An origin server MUST generate an Allow header field in a + 405 (Method Not Allowed) response and MAY do so in any + other response. An empty Allow field value indicates that the resource + allows no methods, which might occur in a 405 response if the resource has + been temporarily disabled by configuration. + + + A proxy MUST NOT modify the Allow header field -- it does not need + to understand all of the indicated methods in order to handle them + according to the generic message handling rules. + +
+
+ Location + + + + + The "Location" header field is used in some responses to refer to a + specific resource in relation to the response. The type of relationship is + defined by the combination of request method and status code semantics. + + + Location = URI-reference + + + The field value consists of a single URI-reference. When it has the form + of a relative reference (), + the final value is computed by resolving it against the target + URI (). + + + For 201 (Created) responses, the Location value refers to + the primary resource created by the request. + For 3xx (Redirection) responses, the Location value refers + to the preferred target resource for automatically redirecting the request. + + + If the Location value provided in a 3xx (Redirection) + response does not have a fragment component, a user agent MUST process the + redirection as if the value inherits the fragment component of the URI + reference used to generate the target URI (i.e., the redirection + inherits the original reference's fragment, if any). + + + For example, a GET request generated for the URI reference + "http://www.example.org/~tim" might result in a + 303 (See Other) response containing the header field: + + Location: /People.html#tim + + + which suggests that the user agent redirect to + "http://www.example.org/People.html#tim" + + + Likewise, a GET request generated for the URI reference + "http://www.example.org/index.html#larry" might result in a + 301 (Moved Permanently) response containing the header + field: + + Location: http://www.example.net/index.html + + + which suggests that the user agent redirect to + "http://www.example.net/index.html#larry", preserving the original fragment + identifier. + + + There are circumstances in which a fragment identifier in a Location + value would not be appropriate. For example, the Location header field in a + 201 (Created) response is supposed to provide a URI that is + specific to the created resource. + + + +
+
+ Retry-After + + + + + Servers send the "Retry-After" header field to indicate how long the user + agent ought to wait before making a follow-up request. When sent with a + 503 (Service Unavailable) response, Retry-After indicates + how long the service is expected to be unavailable to the client. + When sent with any 3xx (Redirection) response, Retry-After + indicates the minimum time that the user agent is asked to wait before + issuing the redirected request. + + + The Retry-After field value can be either an HTTP-date or a number + of seconds to delay after receiving the response. + + + Retry-After = HTTP-date / delay-seconds + + + + A delay-seconds value is a non-negative decimal integer, representing time + in seconds. + + + delay-seconds = 1*DIGIT + + + Two examples of its use are + + Retry-After: Fri, 31 Dec 1999 23:59:59 GMT +Retry-After: 120 + + + In the latter example, the delay is 2 minutes. + +
+
+ Server + + + + + The "Server" header field contains information about the + software used by the origin server to handle the request, which is often + used by clients to help identify the scope of reported interoperability + problems, to work around or tailor requests to avoid particular server + limitations, and for analytics regarding server or operating system use. + An origin server MAY generate a Server header field in its responses. + + + Server = product *( RWS ( product / comment ) ) + + + The Server header field value consists of one or more product identifiers, each + followed by zero or more comments (), which together + identify the origin server software and its significant subproducts. + By convention, the product identifiers are listed in decreasing order of + their significance for identifying the origin server software. Each product + identifier consists of a name and optional version, as defined in + . + + + Example: + + Server: CERN/3.0 libwww/2.17 + + + An origin server SHOULD NOT generate a Server header field containing needlessly + fine-grained detail and SHOULD limit the addition of subproducts by third + parties. Overly long and detailed Server field values increase response + latency and potentially reveal internal implementation details that might + make it (slightly) easier for attackers to find and exploit known security + holes. + +
+
+
+
+ HTTP Authentication +
+ Authentication Scheme + + HTTP provides a general framework for access control and authentication, + via an extensible set of challenge-response authentication schemes, which + can be used by a server to challenge a client request and by a client to + provide authentication information. It uses a case-insensitive + token to identify the authentication scheme: + + + auth-scheme = token + + + Aside from the general framework, this document does not specify any + authentication schemes. New and existing authentication schemes are + specified independently and ought to be registered within the + "Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry". + For example, the "basic" and "digest" authentication schemes are defined by + and + , respectively. + +
+
+ Authentication Parameters + + The authentication scheme is followed by additional information necessary + for achieving authentication via that scheme as either a + comma-separated list of parameters or a single sequence of characters + capable of holding base64-encoded information. + + + token68 = 1*( ALPHA / DIGIT / + "-" / "." / "_" / "~" / "+" / "/" ) *"=" + + + The token68 syntax allows the 66 unreserved URI characters + (), plus a few others, so that it can hold a + base64, base64url (URL and filename safe alphabet), base32, or base16 (hex) + encoding, with or without padding, but excluding whitespace + (). + + + Authentication parameters are name/value pairs, where the name token is + matched case-insensitively + and each parameter name MUST only occur once per challenge. + + + auth-param = token BWS "=" BWS ( token / quoted-string ) + + + Parameter values can be expressed either as "token" or as "quoted-string" + (). + Authentication scheme definitions need to accept both notations, both for + senders and recipients, to allow recipients to use generic parsing + components regardless of the authentication scheme. + + + For backwards compatibility, authentication scheme definitions can restrict + the format for senders to one of the two variants. This can be important + when it is known that deployed implementations will fail when encountering + one of the two formats. + +
+
+ Challenge and Response + + A 401 (Unauthorized) response message is used by an origin + server to challenge the authorization of a user agent, including a + WWW-Authenticate header field containing at least one + challenge applicable to the requested resource. + + + A 407 (Proxy Authentication Required) response message is + used by a proxy to challenge the authorization of a client, including a + Proxy-Authenticate header field containing at least one + challenge applicable to the proxy for the requested resource. + + + challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ] + + + + A user agent that wishes to authenticate itself with an origin server + -- usually, but not necessarily, after receiving a + 401 (Unauthorized) -- can do so by including an + Authorization header field with the request. + + + A client that wishes to authenticate itself with a proxy -- usually, + but not necessarily, after receiving a + 407 (Proxy Authentication Required) -- can do so by + including a Proxy-Authorization header field with the + request. + +
+
+ Credentials + + Both the Authorization field value and the + Proxy-Authorization field value contain the client's + credentials for the realm of the resource being requested, based upon a + challenge received in a response (possibly at some point in the past). + When creating their values, the user agent ought to do so by selecting the + challenge with what it considers to be the most secure auth-scheme that it + understands, obtaining credentials from the user as appropriate. + Transmission of credentials within header field values implies significant + security considerations regarding the confidentiality of the underlying + connection, as described in + . + + + credentials = auth-scheme [ 1*SP ( token68 / #auth-param ) ] + + + Upon receipt of a request for a protected resource that omits credentials, + contains invalid credentials (e.g., a bad password) or partial credentials + (e.g., when the authentication scheme requires more than one round trip), + an origin server SHOULD send a 401 (Unauthorized) response + that contains a WWW-Authenticate header field with at least + one (possibly new) challenge applicable to the requested resource. + + + Likewise, upon receipt of a request that omits proxy credentials or + contains invalid or partial proxy credentials, a proxy that requires + authentication SHOULD generate a + 407 (Proxy Authentication Required) response that contains + a Proxy-Authenticate header field with at least one + (possibly new) challenge applicable to the proxy. + + + A server that receives valid credentials that are not adequate to gain + access ought to respond with the 403 (Forbidden) status + code (). + + + HTTP does not restrict applications to this simple challenge-response + framework for access authentication. Additional mechanisms can be used, + such as authentication at the transport level or via message encapsulation, + and with additional header fields specifying authentication information. + However, such additional mechanisms are not defined by this specification. + + + Note that various custom mechanisms for user authentication use the + Set-Cookie and Cookie header fields, defined in , + for passing tokens related to authentication. + +
+
+ Establishing a Protection Space (Realm) + + + + + The "realm" authentication parameter is reserved for use by + authentication schemes that wish to indicate a scope of protection. + + + A "protection space" is defined by the origin (see + ) of the + server being accessed, in combination with the realm value if present. + These realms allow the protected resources on a server to be + partitioned into a set of protection spaces, each with its own + authentication scheme and/or authorization database. The realm value + is a string, generally assigned by the origin server, that can have + additional semantics specific to the authentication scheme. Note that a + response can have multiple challenges with the same auth-scheme but + with different realms. + + + The protection space determines the domain over which credentials can + be automatically applied. If a prior request has been authorized, the + user agent MAY reuse the same credentials for all other requests within + that protection space for a period of time determined by the authentication + scheme, parameters, and/or user preferences (such as a configurable + inactivity timeout). + + + The extent of a protection space, and therefore the requests to which + credentials might be automatically applied, is not necessarily known to + clients without additional information. An authentication scheme might + define parameters that describe the extent of a protection space. Unless + specifically allowed by the authentication scheme, a single protection + space cannot extend outside the scope of its server. + + + For historical reasons, a sender MUST only generate the quoted-string syntax. + Recipients might have to support both token and quoted-string syntax for + maximum interoperability with existing clients that have been accepting both + notations for a long time. + +
+
+ Authenticating Users to Origin Servers +
+ WWW-Authenticate + + + + + The "WWW-Authenticate" response header field indicates the authentication + scheme(s) and parameters applicable to the target resource. + + + WWW-Authenticate = #challenge + + + A server generating a 401 (Unauthorized) response + MUST send a WWW-Authenticate header field containing at least one + challenge. A server MAY generate a WWW-Authenticate header field + in other response messages to indicate that supplying credentials + (or different credentials) might affect the response. + + + A proxy forwarding a response MUST NOT modify any + WWW-Authenticate header fields in that response. + + + User agents are advised to take special care in parsing the field value, as + it might contain more than one challenge, and each challenge can contain a + comma-separated list of authentication parameters. Furthermore, the header + field itself can occur multiple times. + + + For instance: + + WWW-Authenticate: Basic realm="simple", Newauth realm="apps", + type=1, title="Login to \"apps\"" + + + This header field contains two challenges, one for the "Basic" scheme with + a realm value of "simple" and another for the "Newauth" scheme with a + realm value of "apps". It also contains two additional parameters, "type" and "title". + + + Some user agents do not recognize this form, however. As a result, sending + a WWW-Authenticate field value with more than one member on the same field + line might not be interoperable. + + +
+
+ Authorization + + + + + The "Authorization" header field allows a user agent to authenticate itself + with an origin server -- usually, but not necessarily, after receiving + a 401 (Unauthorized) response. Its value consists of + credentials containing the authentication information of the user agent for + the realm of the resource being requested. + + + Authorization = credentials + + + If a request is authenticated and a realm specified, the same credentials + are presumed to be valid for all other requests within this realm (assuming + that the authentication scheme itself does not require otherwise, such as + credentials that vary according to a challenge value or using synchronized + clocks). + + + A proxy forwarding a request MUST NOT modify any + Authorization header fields in that request. + See for details of and requirements + pertaining to handling of the Authorization header field by HTTP caches. + +
+
+ Authentication-Info + + + + + HTTP authentication schemes can use the "Authentication-Info" response + field to communicate information after the client's authentication credentials have been accepted. + This information can include a finalization message from the server (e.g., it can contain the + server authentication). + + + The field value is a list of parameters (name/value pairs), using the "auth-param" + syntax defined in . + This specification only describes the generic format; authentication schemes + using Authentication-Info will define the individual parameters. The "Digest" + Authentication Scheme, for instance, defines multiple parameters in + . + + + Authentication-Info = #auth-param + + + The Authentication-Info field can be used in any HTTP response, + independently of request method and status code. Its semantics are defined + by the authentication scheme indicated by the Authorization header field + () of the corresponding request. + + + A proxy forwarding a response is not allowed to modify the field value in any + way. + + + Authentication-Info can be sent as a trailer field + () + when the authentication scheme explicitly allows this. + +
+
+
+ Authenticating Clients to Proxies +
+ Proxy-Authenticate + + + + + The "Proxy-Authenticate" header field consists of at least one + challenge that indicates the authentication scheme(s) and parameters + applicable to the proxy for this request. + A proxy MUST send at least one Proxy-Authenticate header field in + each 407 (Proxy Authentication Required) response that it + generates. + + + Proxy-Authenticate = #challenge + + + Unlike WWW-Authenticate, the Proxy-Authenticate header field + applies only to the next outbound client on the response chain. + This is because only the client that chose a given proxy is likely to have + the credentials necessary for authentication. However, when multiple + proxies are used within the same administrative domain, such as office and + regional caching proxies within a large corporate network, it is common + for credentials to be generated by the user agent and passed through the + hierarchy until consumed. Hence, in such a configuration, it will appear + as if Proxy-Authenticate is being forwarded because each proxy will send + the same challenge set. + + + Note that the parsing considerations for WWW-Authenticate + apply to this header field as well; see + for details. + +
+
+ Proxy-Authorization + + + + + The "Proxy-Authorization" header field allows the client to + identify itself (or its user) to a proxy that requires + authentication. Its value consists of credentials containing the + authentication information of the client for the proxy and/or realm of the + resource being requested. + + + Proxy-Authorization = credentials + + + Unlike Authorization, the Proxy-Authorization header field + applies only to the next inbound proxy that demanded authentication using + the Proxy-Authenticate header field. When multiple proxies are used + in a chain, the Proxy-Authorization header field is consumed by the first + inbound proxy that was expecting to receive credentials. A proxy MAY + relay the credentials from the client request to the next proxy if that is + the mechanism by which the proxies cooperatively authenticate a given + request. + +
+
+ Proxy-Authentication-Info + + + + + The "Proxy-Authentication-Info" response header field is equivalent to + Authentication-Info, except that it applies to proxy authentication () + and its semantics are defined by the + authentication scheme indicated by the Proxy-Authorization header field + () + of the corresponding request: + + + Proxy-Authentication-Info = #auth-param + + + However, unlike Authentication-Info, the Proxy-Authentication-Info header + field applies only to the next outbound client on the response chain. This is + because only the client that chose a given proxy is likely to have the + credentials necessary for authentication. However, when multiple proxies are + used within the same administrative domain, such as office and regional + caching proxies within a large corporate network, it is common for + credentials to be generated by the user agent and passed through the + hierarchy until consumed. Hence, in such a configuration, it will appear as + if Proxy-Authentication-Info is being forwarded because each proxy will send + the same field value. + + + Proxy-Authentication-Info can be sent as a trailer field + () + when the authentication scheme explicitly allows this. + +
+
+
+
+ Content Negotiation + + When responses convey content, whether indicating a success or + an error, the origin server often has different ways of representing that + information; for example, in different formats, languages, or encodings. + Likewise, different users or user agents might have differing capabilities, + characteristics, or preferences that could influence which representation, + among those available, would be best to deliver. For this reason, HTTP + provides mechanisms for content negotiation. + + + This specification defines three patterns of content negotiation that can + be made visible within the protocol: + "proactive" negotiation, where the server selects the representation based + upon the user agent's stated preferences; "reactive" negotiation, + where the server provides a list of representations for the user agent to + choose from; and "request content" negotiation, where the user agent + selects the representation for a future request based upon the server's + stated preferences in past responses. + + + Other patterns of content negotiation include + "conditional content", where the representation consists of multiple + parts that are selectively rendered based on user agent parameters, + "active content", where the representation contains a script that + makes additional (more specific) requests based on the user agent + characteristics, and "Transparent Content Negotiation" + (), where content selection is performed by + an intermediary. These patterns are not mutually exclusive, and each has + trade-offs in applicability and practicality. + + + Note that, in all cases, HTTP is not aware of the resource semantics. + The consistency with which an origin server responds to requests, over time + and over the varying dimensions of content negotiation, and thus the + "sameness" of a resource's observed representations over time, is + determined entirely by whatever entity or algorithm selects or generates + those responses. + +
+ Proactive Negotiation + + When content negotiation preferences are sent by the user agent in a + request to encourage an algorithm located at the server to + select the preferred representation, it is called + "proactive negotiation" + (a.k.a., "server-driven negotiation"). Selection is based on + the available representations for a response (the dimensions over which it + might vary, such as language, content coding, etc.) compared to various + information supplied in the request, including both the explicit + negotiation header fields below and implicit + characteristics, such as the client's network address or parts of the + User-Agent field. + + + Proactive negotiation is advantageous when the algorithm for + selecting from among the available representations is difficult to + describe to a user agent, or when the server desires to send its + "best guess" to the user agent along with the first response (when that + "best guess" is good enough for the user, this avoids the round-trip + delay of a subsequent request). In order to improve the server's + guess, a user agent MAY send request header fields that describe + its preferences. + + + Proactive negotiation has serious disadvantages: + +
    +
  • + It is impossible for the server to accurately determine what + might be "best" for any given user, since that would require + complete knowledge of both the capabilities of the user agent + and the intended use for the response (e.g., does the user want + to view it on screen or print it on paper?); +
  • +
  • + Having the user agent describe its capabilities in every + request can be both very inefficient (given that only a small + percentage of responses have multiple representations) and a + potential risk to the user's privacy; +
  • +
  • + It complicates the implementation of an origin server and the + algorithms for generating responses to a request; and, +
  • +
  • + It limits the reusability of responses for shared caching. +
  • +
+ + A user agent cannot rely on proactive negotiation preferences being + consistently honored, since the origin server might not implement proactive + negotiation for the requested resource or might decide that sending a + response that doesn't conform to the user agent's preferences is better + than sending a 406 (Not Acceptable) response. + + + A Vary header field () is + often sent in a response subject to proactive negotiation to indicate what + parts of the request information were used in the selection algorithm. + + + The request header fields Accept, + Accept-Charset, Accept-Encoding, and + Accept-Language are defined below for a user agent to engage + in proactive negotiation of the response content. + The preferences sent in these + fields apply to any content in the response, including representations of + the target resource, representations of error or processing status, and + potentially even the miscellaneous text strings that might appear within + the protocol. + +
+
+ Reactive Negotiation + + With "reactive negotiation" (a.k.a., "agent-driven negotiation"), selection of + content (regardless of the status code) is performed by + the user agent after receiving an initial response. The mechanism for + reactive negotiation might be as simple as a list of references to + alternative representations. + + + If the user agent is not satisfied by the initial response content, + it can perform a GET request on one or more of the alternative resources + to obtain a different representation. Selection of such alternatives might + be performed automatically (by the user agent) or manually (e.g., by the + user selecting from a hypertext menu). + + + A server might choose not to send an initial representation, other than + the list of alternatives, and thereby indicate that reactive + negotiation by the user agent is preferred. For example, the alternatives + listed in responses with the 300 (Multiple Choices) and + 406 (Not Acceptable) status codes include information about + available representations so that the user or user agent can react by + making a selection. + + + Reactive negotiation is advantageous when the response would vary + over commonly used dimensions (such as type, language, or encoding), + when the origin server is unable to determine a user agent's + capabilities from examining the request, and generally when public + caches are used to distribute server load and reduce network usage. + + + Reactive negotiation suffers from the disadvantages of transmitting + a list of alternatives to the user agent, which degrades user-perceived + latency if transmitted in the header section, and needing a second request + to obtain an alternate representation. Furthermore, this specification + does not define a mechanism for supporting automatic selection, though it + does not prevent such a mechanism from being developed. + +
+
+ Request Content Negotiation + + When content negotiation preferences are sent in a server's response, the + listed preferences are called "request content negotiation" + because they intend to influence selection of an appropriate content for + subsequent requests to that resource. For example, + the Accept () and + Accept-Encoding () + header fields can be sent in a response to indicate preferred media types + and content codings for subsequent requests to that resource. + + + Similarly, defines + the "Accept-Patch" response header field, which allows discovery of + which content types are accepted in PATCH requests. + +
+
+ Content Negotiation Field Features +
+ Absence + + For each of the content negotiation fields, a request that does not contain + the field implies that the sender has no preference on that dimension of + negotiation. + + + If a content negotiation header field is present in a request and none of + the available + representations for the response can be considered acceptable according to + it, the origin server can either honor the header field by sending a + 406 (Not Acceptable) response or disregard the header field + by treating the response as if it is not subject to content negotiation + for that request header field. This does not imply, however, that the + client will be able to use the representation. + + +
+
+ Quality Values + + The content negotiation fields defined by this specification + use a common parameter, named "q" (case-insensitive), to assign a relative + "weight" to the preference for that associated kind of content. + This weight is referred to as a "quality value" (or "qvalue") because + the same parameter name is often used within server configurations to + assign a weight to the relative quality of the various representations + that can be selected for a resource. + + + The weight is normalized to a real number in the range 0 through 1, + where 0.001 is the least preferred and 1 is the most preferred; + a value of 0 means "not acceptable". If no "q" parameter is present, + the default weight is 1. + + + + weight = OWS ";" OWS "q=" qvalue + qvalue = ( "0" [ "." 0*3DIGIT ] ) + / ( "1" [ "." 0*3("0") ] ) + + + A sender of qvalue MUST NOT generate more than three digits after the + decimal point. User configuration of these values ought to be limited in + the same fashion. + +
+
+ Wildcard Values + + Most of these header fields, where indicated, define a wildcard value ("*") + to select unspecified values. If no wildcard is present, values that are + not explicitly mentioned in the field are considered unacceptable. + Within Vary, the wildcard value means that the variance + is unlimited. + + +
+
+
+ Content Negotiation Fields +
+ Accept + + + + + The "Accept" header field can be used by user agents to specify their + preferences regarding response media types. For example, Accept header + fields can be used to indicate that the request is specifically limited to + a small set of desired types, as in the case of a request for an in-line + image. + + + When sent by a server in a response, Accept provides information + about which content types are preferred in the content of a subsequent + request to the same resource. + + + + Accept = #( media-range [ weight ] ) + + media-range = ( "*/*" + / ( type "/" "*" ) + / ( type "/" subtype ) + ) parameters + + + The asterisk "*" character is used to group media types into ranges, + with "*/*" indicating all media types and "type/*" indicating all + subtypes of that type. The media-range can include media type + parameters that are applicable to that range. + + + Each media-range might be followed by optional applicable media type + parameters (e.g., charset), followed by an optional "q" + parameter for indicating a relative weight (). + + + Previous specifications allowed additional extension parameters to appear + after the weight parameter. The accept extension grammar (accept-params, accept-ext) has + been removed because it had a complicated definition, was not being used in + practice, and is more easily deployed through new header fields. Senders + using weights SHOULD send "q" last (after all media-range parameters). + Recipients SHOULD process any parameter named "q" as weight, regardless of + parameter ordering. + + + + The example + + Accept: audio/*; q=0.2, audio/basic + + + is interpreted as "I prefer audio/basic, but send me any audio + type if it is the best available after an 80% markdown in quality". + + + A more elaborate example is + + Accept: text/plain; q=0.5, text/html, + text/x-dvi; q=0.8, text/x-c + + + Verbally, this would be interpreted as "text/html and text/x-c are + the equally preferred media types, but if they do not exist, then send the + text/x-dvi representation, and if that does not exist, send the text/plain + representation". + + + Media ranges can be overridden by more specific media ranges or + specific media types. If more than one media range applies to a given + type, the most specific reference has precedence. For example, + + Accept: text/*, text/plain, text/plain;format=flowed, */* + + + have the following precedence: + +
    +
  1. text/plain;format=flowed
  2. +
  3. text/plain
  4. +
  5. text/*
  6. +
  7. */*
  8. +
+ + The media type quality factor associated with a given type is + determined by finding the media range with the highest precedence + that matches the type. For example, + + Accept: text/*;q=0.3, text/plain;q=0.7, text/plain;format=flowed, + text/plain;format=fixed;q=0.4, */*;q=0.5 + + + would cause the following values to be associated: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Media TypeQuality Value
text/plain;format=flowed1
text/plain0.7
text/html0.3
image/jpeg0.5
text/plain;format=fixed0.4
text/html;level=30.7
+ +
+
+ Accept-Charset + + + + + The "Accept-Charset" header field can be sent by a user agent to indicate + its preferences for charsets in textual response content. For example, + this field allows user agents capable of understanding more comprehensive + or special-purpose charsets to signal that capability to an origin server + that is capable of representing information in those charsets. + + + Accept-Charset = #( ( token / "*" ) [ weight ] ) + + + Charset names are defined in . + A user agent MAY associate a quality value with each charset to indicate + the user's relative preference for that charset, as defined in . + An example is + + Accept-Charset: iso-8859-5, unicode-1-1;q=0.8 + + + The special value "*", if present in the Accept-Charset header field, + matches every charset that is not mentioned elsewhere in the + field. + + +
+
+ Accept-Encoding + + + + + The "Accept-Encoding" header field can be used to indicate preferences + regarding the use of content codings (). + + + When sent by a user agent in a request, Accept-Encoding indicates the + content codings acceptable in a response. + + + When sent by a server in a response, Accept-Encoding provides information + about which content codings are preferred in the content of a subsequent + request to the same resource. + + + An "identity" token is used as a synonym for + "no encoding" in order to communicate when no encoding is preferred. + + + + Accept-Encoding = #( codings [ weight ] ) + codings = content-coding / "identity" / "*" + + + Each codings value MAY be given an associated quality value (weight) + representing the preference for that encoding, as defined in . + The asterisk "*" symbol in an Accept-Encoding field matches any available + content coding not explicitly listed in the field. + + + Examples: + + Accept-Encoding: compress, gzip +Accept-Encoding: +Accept-Encoding: * +Accept-Encoding: compress;q=0.5, gzip;q=1.0 +Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0 + + + A server tests whether a content coding for a given representation is + acceptable using these rules: + +
    +
  1. If no Accept-Encoding header field is in the request, any content coding is + considered acceptable by the user agent.
  2. +
  3. If the representation has no content coding, then it is acceptable + by default unless specifically excluded by the Accept-Encoding header field + stating either "identity;q=0" or "*;q=0" without a more specific + entry for "identity".
  4. +
  5. If the representation's content coding is one of the content codings + listed in the Accept-Encoding field value, then it is acceptable unless + it is accompanied by a qvalue of 0. (As defined in , a + qvalue of 0 means "not acceptable".)
  6. +
+ + A representation could be encoded with multiple content codings. However, most + content codings are alternative ways to accomplish the same purpose + (e.g., data compression). When selecting between multiple content codings that + have the same purpose, the acceptable content coding with the highest + non-zero qvalue is preferred. + + + An Accept-Encoding header field with a field value that is empty + implies that the user agent does not want any content coding in response. + If a non-empty Accept-Encoding header field is present in a request and none of the + available representations for the response have a content coding that + is listed as acceptable, the origin server SHOULD send a response + without any content coding unless the identity coding is indicated as unacceptable. + + + When the Accept-Encoding header field is present in a response, it indicates + what content codings the resource was willing to accept in the associated + request. The field value is evaluated the same way as in a request. + + + Note that this information is specific to the associated request; the set of + supported encodings might be different for other resources on the same + server and could change over time or depend on other aspects of the request + (such as the request method). + + + Servers that fail a request due to an unsupported content coding ought to + respond with a 415 (Unsupported Media Type) status and + include an Accept-Encoding header field in that response, allowing + clients to distinguish between issues related to content codings and media + types. In order to avoid confusion with issues related to media types, + servers that fail a request with a 415 status for reasons unrelated to + content codings MUST NOT include the Accept-Encoding header + field. + + + The most common use of Accept-Encoding is in responses with a + 415 (Unsupported Media Type) status code, in response to + optimistic use of a content coding by clients. However, the header field + can also be used to indicate to clients that content codings are supported in order + to optimize future interactions. For example, a resource might include it + in a 2xx (Successful) response when the request content was + big enough to justify use of a compression coding but the client failed do + so. + +
+
+ Accept-Language + + + + + The "Accept-Language" header field can be used by user agents to + indicate the set of natural languages that are preferred in the response. + Language tags are defined in . + + + + Accept-Language = #( language-range [ weight ] ) + language-range = + <language-range, see [RFC4647], Section 2.1> + + + Each language-range can be given an associated quality value + representing an estimate of the user's preference for the languages + specified by that range, as defined in . For example, + + Accept-Language: da, en-gb;q=0.8, en;q=0.7 + + + would mean: "I prefer Danish, but will accept British English and + other types of English". + + + Note that some recipients treat the order in which language tags are listed + as an indication of descending priority, particularly for tags that are + assigned equal quality values (no value is the same as q=1). However, this + behavior cannot be relied upon. For consistency and to maximize + interoperability, many user agents assign each language tag a unique + quality value while also listing them in order of decreasing quality. + Additional discussion of language priority lists can be found in + . + + + For matching, defines + several matching schemes. Implementations can offer the most appropriate + matching scheme for their requirements. The "Basic Filtering" scheme + () is identical to the + matching scheme that was previously defined for HTTP in + . + + + It might be contrary to the privacy expectations of the user to send + an Accept-Language header field with the complete linguistic preferences of + the user in every request (). + + + Since intelligibility is highly dependent on the individual user, user + agents need to allow user control over the linguistic preference (either + through configuration of the user agent itself or by defaulting to a user + controllable system setting). + A user agent that does not provide such control to the user MUST NOT + send an Accept-Language header field. + + +
+
+ Vary + + + + + The "Vary" header field in a response describes what parts of a request + message, aside from the method and target URI, might have influenced the + origin server's process for selecting the content of this response. + + + Vary = #( "*" / field-name ) + + + A Vary field value is either the wildcard member "*" or a list of + request field names, known as the selecting header fields, that might + have had a role in selecting the representation for this response. + Potential selecting header fields are not limited to fields defined by + this specification. + + + A list containing the member "*" signals that other aspects of the + request might have played a role in selecting the response representation, + possibly including aspects outside the message syntax (e.g., the + client's network address). + A recipient will not be able to determine whether this response is + appropriate for a later request without forwarding the request to the + origin server. A proxy MUST NOT generate "*" in a Vary field value. + + + For example, a response that contains + + Vary: accept-encoding, accept-language + + + indicates that the origin server might have used the request's + Accept-Encoding and Accept-Language + header fields (or lack thereof) as determining factors while choosing + the content for this response. + + + A Vary field containing a list of field names has two purposes: + +
    +
  1. + + To inform cache recipients that they MUST NOT use this response + to satisfy a later request unless the later request has the + same values for the listed header fields as the original request + () or reuse of the + response has been validated by the origin server. + In other words, Vary expands the cache key + required to match a new request to the stored cache entry. + +
  2. +
  3. + + To inform user agent recipients that this response was subject to + content negotiation () and a + different representation might be sent in a subsequent request if + other values are provided in the listed header fields + (proactive negotiation). + +
  4. +
+ + An origin server SHOULD generate a Vary header field on a cacheable + response when it wishes that response to be selectively reused for + subsequent requests. Generally, that is the case when the response + content has been tailored to better fit the preferences expressed by + those selecting header fields, such as when an origin server has + selected the response's language based on the request's + Accept-Language header field. + + + Vary might be elided when an origin server considers variance in + content selection to be less significant than Vary's performance impact + on caching, particularly when reuse is already limited by cache + response directives (). + + + There is no need to send the Authorization field name in Vary because + reuse of that response for a different user is prohibited by the field + definition (). + Likewise, if the response content has been selected or influenced by + network region, but the origin server wants the cached response to be + reused even if recipients move from one region to another, then there + is no need for the origin server to indicate such variance in Vary. + +
+
+
+
+ Conditional Requests + + + A conditional request is an HTTP request with one or more request header + fields that indicate a precondition to be tested before + applying the request method to the target resource. + defines when to evaluate preconditions and + their order of precedence when more than one precondition is present. + + + Conditional GET requests are the most efficient mechanism for HTTP + cache updates . Conditionals can also be + applied to state-changing methods, such as PUT and DELETE, to prevent + the "lost update" problem: one client accidentally overwriting + the work of another client that has been acting in parallel. + +
+ Preconditions + + + Preconditions are usually defined with respect to a state of the target + resource as a whole (its current value set) or the state as observed in a + previously obtained representation (one value in that set). If a resource + has multiple current representations, each with its own observable state, + a precondition will assume that the mapping of each request to a + selected representation () + is consistent over time. + Regardless, if the mapping is inconsistent or the server is unable to + select an appropriate representation, then no harm will result when the + precondition evaluates to false. + + + Each precondition defined below consists of a comparison between a + set of validators obtained from prior representations of the target + resource to the current state of validators for the selected + representation (). Hence, these + preconditions evaluate whether the state of the target resource has + changed since a given state known by the client. The effect of such an + evaluation depends on the method semantics and choice of conditional, as + defined in . + + + Other preconditions, defined by other specifications as extension fields, + might place conditions on all recipients, on the state of the target + resource in general, or on a group of resources. For instance, the "If" + header field in WebDAV can make a request conditional on various aspects + of multiple resources, such as locks, if the recipient understands and + implements that field (). + + + Extensibility of preconditions is only possible when the precondition can + be safely ignored if unknown (like If-Modified-Since), when + deployment can be assumed for a given use case, or when implementation + is signaled by some other property of the target resource. This encourages + a focus on mutually agreed deployment of common standards. + +
+ If-Match + + + + + The "If-Match" header field makes the request method conditional on the + recipient origin server either having at least one current + representation of the target resource, when the field value is "*", or + having a current representation of the target resource that has an + entity tag matching a member of the list of entity tags provided in the + field value. + + + An origin server MUST use the strong comparison function when comparing + entity tags for If-Match (), since + the client intends this precondition to prevent the method from being + applied if there have been any changes to the representation data. + + + If-Match = "*" / #entity-tag + + + Examples: + + If-Match: "xyzzy" +If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" +If-Match: * + + + If-Match is most often used with state-changing methods (e.g., POST, PUT, + DELETE) to prevent accidental overwrites when multiple user agents might be + acting in parallel on the same resource (i.e., to prevent the "lost update" + problem). In general, it can be used with any method that involves the + selection or modification of a representation to abort the request if the + selected representation's current entity tag is not a + member within the If-Match field value. + + + When an origin server receives a request that selects a representation + and that request includes an If-Match header field, + the origin server MUST evaluate the If-Match condition per + prior to performing the method. + + + To evaluate a received If-Match header field: + +
    +
  1. + If the field value is "*", the condition is true if the origin server + has a current representation for the target resource. +
  2. +
  3. + If the field value is a list of entity tags, the condition is true if + any of the listed tags match the entity tag of the selected representation. +
  4. +
  5. + Otherwise, the condition is false. +
  6. +
+ + An origin server that evaluates an If-Match condition MUST NOT perform + the requested method if the condition evaluates to false. Instead, + the origin server MAY + indicate that the conditional request failed by responding with a + 412 (Precondition Failed) status code. Alternatively, + if the request is a state-changing operation that appears to have already + been applied to the selected representation, the origin server MAY respond + with a 2xx (Successful) status code + (i.e., the change requested by the user agent has already succeeded, but + the user agent might not be aware of it, perhaps because the prior response + was lost or an equivalent change was made by some other user agent). + + + Allowing an origin server to send a success response when a change request + appears to have already been applied is more efficient for many authoring + use cases, but comes with some risk if multiple user agents are making + change requests that are very similar but not cooperative. + For example, multiple user agents writing to a common resource as a + semaphore (e.g., a nonatomic increment) are likely to collide and + potentially lose important state transitions. For those kinds of resources, + an origin server is better off being stringent in sending 412 for every + failed precondition on an unsafe method. + In other cases, excluding the ETag field from a success response might + encourage the user agent to perform a GET as its next request to eliminate + confusion about the resource's current state. + + + A client MAY send an If-Match header field in a + GET request to indicate that it would prefer a + 412 (Precondition Failed) response if the selected + representation does not match. However, this is only useful in range + requests () for completing a previously + received partial representation when there is no desire for a new + representation. If-Range () + is better suited for range requests when the client prefers to receive a + new representation. + + + A cache or intermediary MAY ignore If-Match because its + interoperability features are only necessary for an origin server. + + + Note that an If-Match header field with a list value containing "*" and + other values (including other instances of "*") is syntactically + invalid (therefore not allowed to be generated) and furthermore is + unlikely to be interoperable. + +
+
+ If-None-Match + + + + + The "If-None-Match" header field makes the request method conditional on + a recipient cache or origin server either not having any current + representation of the target resource, when the field value is "*", or + having a selected representation with an entity tag that does not match any + of those listed in the field value. + + + A recipient MUST use the weak comparison function when comparing + entity tags for If-None-Match (), + since weak entity tags can be used for cache validation even if there have + been changes to the representation data. + + + If-None-Match = "*" / #entity-tag + + + Examples: + + If-None-Match: "xyzzy" +If-None-Match: W/"xyzzy" +If-None-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" +If-None-Match: W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz" +If-None-Match: * + + + If-None-Match is primarily used in conditional GET requests to enable + efficient updates of cached information with a minimum amount of + transaction overhead. When a client desires to update one or more stored + responses that have entity tags, the client SHOULD generate an + If-None-Match header field containing a list of those entity tags when + making a GET request; this allows recipient servers to send a + 304 (Not Modified) response to indicate when one of those + stored responses matches the selected representation. + + + If-None-Match can also be used with a value of "*" to prevent an unsafe + request method (e.g., PUT) from inadvertently modifying an existing + representation of the target resource when the client believes that + the resource does not have a current representation (). + This is a variation on the "lost update" problem that might arise if more + than one client attempts to create an initial representation for the target + resource. + + + When an origin server receives a request that selects a representation + and that request includes an If-None-Match header field, + the origin server MUST evaluate the If-None-Match condition per + prior to performing the method. + + + To evaluate a received If-None-Match header field: + +
    +
  1. + If the field value is "*", the condition is false if the origin server + has a current representation for the target resource. +
  2. +
  3. + If the field value is a list of entity tags, the condition is false if + one of the listed tags matches the entity tag of the selected representation. +
  4. +
  5. + Otherwise, the condition is true. +
  6. +
+ + An origin server that evaluates an If-None-Match condition MUST NOT + perform the requested method if the condition evaluates to false; instead, + the origin server MUST respond with either + a) the 304 (Not Modified) status code if the request method + is GET or HEAD or b) the 412 (Precondition Failed) status + code for all other request methods. + + + Requirements on cache handling of a received If-None-Match header field + are defined in . + + + Note that an If-None-Match header field with a list value containing "*" and + other values (including other instances of "*") is syntactically + invalid (therefore not allowed to be generated) and furthermore is + unlikely to be interoperable. + +
+
+ If-Modified-Since + + + + + The "If-Modified-Since" header field makes a GET or HEAD request method + conditional on the selected representation's modification + date being more + recent than the date provided in the field value. Transfer of the selected + representation's data is avoided if that data has not changed. + + + If-Modified-Since = HTTP-date + + + An example of the field is: + + If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT + + + A recipient MUST ignore If-Modified-Since if the request contains an + If-None-Match header field; the condition in + If-None-Match is considered to be a more accurate + replacement for the condition in If-Modified-Since, and the two are only + combined for the sake of interoperating with older intermediaries that + might not implement If-None-Match. + + + A recipient MUST ignore the If-Modified-Since header field if the + received field value is not a valid HTTP-date, the field value has more than + one member, or if the request method is neither GET nor HEAD. + + + A recipient MUST ignore the If-Modified-Since header field if the + resource does not have a modification date available. + + + A recipient MUST interpret an If-Modified-Since field value's timestamp + in terms of the origin server's clock. + + + If-Modified-Since is typically used for two distinct purposes: + 1) to allow efficient updates of a cached representation that does not + have an entity tag and 2) to limit the scope of a web traversal to resources + that have recently changed. + + + When used for cache updates, a cache will typically use the value of the + cached message's Last-Modified header field to generate the field + value of If-Modified-Since. This behavior is most interoperable for cases + where clocks are poorly synchronized or when the server has chosen to only + honor exact timestamp matches (due to a problem with Last-Modified dates + that appear to go "back in time" when the origin server's clock is + corrected or a representation is restored from an archived backup). + However, caches occasionally generate the field value based on other data, + such as the Date header field of the cached message or the + clock time at which the message was received, particularly when the + cached message does not contain a Last-Modified header field. + + + When used for limiting the scope of retrieval to a recent time window, a + user agent will generate an If-Modified-Since field value based on either + its own clock or a Date header field received from the + server in a prior response. Origin servers that choose an exact + timestamp match based on the selected representation's + Last-Modified + header field will not be able to help the user agent limit its data + transfers to only those changed during the specified window. + + + When an origin server receives a request that selects a representation + and that request includes an If-Modified-Since header field without an + If-None-Match header field, the origin server SHOULD + evaluate the If-Modified-Since condition per + prior to performing the method. + + + To evaluate a received If-Modified-Since header field: + +
    +
  1. + If the selected representation's last modification date is earlier or + equal to the date provided in the field value, the condition is false. +
  2. +
  3. + Otherwise, the condition is true. +
  4. +
+ + An origin server that evaluates an If-Modified-Since condition + SHOULD NOT perform the requested method if the condition evaluates to + false; instead, + the origin server SHOULD generate a 304 (Not Modified) + response, including only those metadata that are useful for identifying or + updating a previously cached response. + + + Requirements on cache handling of a received If-Modified-Since header field + are defined in . + +
+
+ If-Unmodified-Since + + + + + The "If-Unmodified-Since" header field makes the request method conditional + on the selected representation's last modification date being + earlier than or equal to the date provided in the field value. + This field accomplishes the + same purpose as If-Match for cases where the user agent does + not have an entity tag for the representation. + + + If-Unmodified-Since = HTTP-date + + + An example of the field is: + + If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT + + + A recipient MUST ignore If-Unmodified-Since if the request contains an + If-Match header field; the condition in + If-Match is considered to be a more accurate replacement for + the condition in If-Unmodified-Since, and the two are only combined for the + sake of interoperating with older intermediaries that might not implement + If-Match. + + + A recipient MUST ignore the If-Unmodified-Since header field if the + received field value is not a valid HTTP-date (including when the field + value appears to be a list of dates). + + + A recipient MUST ignore the If-Unmodified-Since header field if the + resource does not have a modification date available. + + + A recipient MUST interpret an If-Unmodified-Since field value's timestamp + in terms of the origin server's clock. + + + If-Unmodified-Since is most often used with state-changing methods + (e.g., POST, PUT, DELETE) to prevent accidental overwrites when multiple + user agents might be acting in parallel on a resource that does + not supply entity tags with its representations (i.e., to prevent the + "lost update" problem). + In general, it can be used with any method that involves the selection + or modification of a representation to abort the request if the + selected representation's last modification date has + changed since the date provided in the If-Unmodified-Since field value. + + + When an origin server receives a request that selects a representation + and that request includes an If-Unmodified-Since header field without + an If-Match header field, + the origin server MUST evaluate the If-Unmodified-Since condition per + prior to performing the method. + + + To evaluate a received If-Unmodified-Since header field: + +
    +
  1. + If the selected representation's last modification date is earlier than or + equal to the date provided in the field value, the condition is true. +
  2. +
  3. + Otherwise, the condition is false. +
  4. +
+ + An origin server that evaluates an If-Unmodified-Since condition MUST NOT + perform the requested method if the condition evaluates to false. + Instead, the origin server MAY indicate that the conditional request + failed by responding with a 412 (Precondition Failed) + status code. Alternatively, if the request is a state-changing operation + that appears to have already been applied to the selected representation, + the origin server MAY respond with a 2xx (Successful) + status code + (i.e., the change requested by the user agent has already succeeded, but + the user agent might not be aware of it, perhaps because the prior response + was lost or an equivalent change was made by some other user agent). + + + Allowing an origin server to send a success response when a change request + appears to have already been applied is more efficient for many authoring + use cases, but comes with some risk if multiple user agents are making + change requests that are very similar but not cooperative. + In those cases, an origin server is better off being stringent in sending + 412 for every failed precondition on an unsafe method. + + + A client MAY send an If-Unmodified-Since header field in a + GET request to indicate that it would prefer a + 412 (Precondition Failed) response if the selected + representation has been modified. However, this is only useful in range + requests () for completing a previously + received partial representation when there is no desire for a new + representation. If-Range () + is better suited for range requests when the client prefers to receive a + new representation. + + + A cache or intermediary MAY ignore If-Unmodified-Since because its + interoperability features are only necessary for an origin server. + +
+
+ If-Range + + + + + The "If-Range" header field provides a special conditional request + mechanism that is similar to the If-Match and + If-Unmodified-Since header fields but that instructs the + recipient to ignore the Range header field if the validator + doesn't match, resulting in transfer of the new selected representation + instead of a 412 (Precondition Failed) response. + + + If a client has a partial copy of a representation and wishes + to have an up-to-date copy of the entire representation, it could use the + Range header field with a conditional GET (using + either or both of If-Unmodified-Since and + If-Match.) However, if the precondition fails because the + representation has been modified, the client would then have to make a + second request to obtain the entire current representation. + + + The "If-Range" header field allows a client to "short-circuit" the second + request. Informally, its meaning is as follows: if the representation is unchanged, + send me the part(s) that I am requesting in Range; otherwise, send me the + entire representation. + + + If-Range = entity-tag / HTTP-date + + + A valid entity-tag can be distinguished from a valid + HTTP-date by examining the first three characters for a + DQUOTE. + + + A client MUST NOT generate an If-Range header field in a request that + does not contain a Range header field. + A server MUST ignore an If-Range header field received in a request that + does not contain a Range header field. + An origin server MUST ignore an If-Range header field received in a + request for a target resource that does not support Range requests. + + + A client MUST NOT generate an If-Range header field containing an + entity tag that is marked as weak. + A client MUST NOT generate an If-Range header field containing an + HTTP-date unless the client has no entity tag for + the corresponding representation and the date is a strong validator + in the sense defined by . + + + A server that receives an If-Range header field on a Range request MUST + evaluate the condition per prior to + performing the method. + + + To evaluate a received If-Range header field containing an + HTTP-date: + +
    +
  1. If the HTTP-date validator provided is not a + strong validator in the sense defined by + , the condition is false.
  2. +
  3. If the HTTP-date validator provided exactly matches + the Last-Modified field value for the selected + representation, the condition is true.
  4. +
  5. Otherwise, the condition is false.
  6. +
+ + To evaluate a received If-Range header field containing an + entity-tag: + +
    +
  1. If the entity-tag validator provided exactly matches + the ETag field value for the selected representation + using the strong comparison function + (), the condition is true.
  2. +
  3. Otherwise, the condition is false.
  4. +
+ + A recipient of an If-Range header field MUST ignore the + Range header field if the If-Range condition + evaluates to false. Otherwise, the recipient SHOULD process the + Range header field as requested. + + + Note that the If-Range comparison is by exact match, including when the + validator is an HTTP-date, and so it + differs from the "earlier than or equal to" comparison used when evaluating + an If-Unmodified-Since conditional. + +
+
+
+ Evaluation of Preconditions +
+ When to Evaluate + + Except when excluded below, a recipient cache or origin server MUST + evaluate received request preconditions after it has successfully performed + its normal request checks and just before it would process the request content + (if any) or perform the action associated with the request method. + A server MUST ignore all received preconditions if its response to the + same request without those conditions, prior to processing the request content, + would have been a status code other than a 2xx (Successful) + or 412 (Precondition Failed). + In other words, redirects and failures that can be detected before + significant processing occurs take precedence over the evaluation + of preconditions. + + + A server that is not the origin server for the target resource and cannot + act as a cache for requests on the target resource MUST NOT evaluate the + conditional request header fields defined by this specification, and it + MUST forward them if the request is forwarded, since the generating + client intends that they be evaluated by a server that can provide a + current representation. + Likewise, a server MUST ignore the conditional request header fields + defined by this specification when received with a request method that does + not involve the selection or modification of a + selected representation, such as CONNECT, OPTIONS, or TRACE. + + + Note that protocol extensions can modify the conditions under which + preconditions are evaluated or the consequences of their evaluation. + For example, the immutable cache directive + (defined by ) instructs caches to forgo + forwarding conditional requests when they hold a fresh response. + + + Although conditional request header fields are defined as being usable with + the HEAD method (to keep HEAD's semantics consistent with those of GET), + there is no point in sending a conditional HEAD because a successful + response is around the same size as a 304 (Not Modified) + response and more useful than a 412 (Precondition Failed) + response. + +
+
+ Precedence of Preconditions + + When more than one conditional request header field is present in a request, + the order in which the fields are evaluated becomes important. In practice, + the fields defined in this document are consistently implemented in a + single, logical order, since "lost update" preconditions have more strict + requirements than cache validation, a validated cache is more efficient + than a partial response, and entity tags are presumed to be more accurate + than date validators. + + + A recipient cache or origin server MUST evaluate the request + preconditions defined by this specification in the following order: + +
    +
  1. + When recipient is the origin server and + If-Match is present, + evaluate the If-Match precondition: +
      +
    • if true, continue to step +
    • +
    • if false, respond 412 (Precondition Failed) unless + it can be determined that the state-changing request has already + succeeded (see )
    • +
    +
  2. +
  3. + When recipient is the origin server, + If-Match is not present, and + If-Unmodified-Since is present, + evaluate the If-Unmodified-Since precondition: +
      +
    • if true, continue to step +
    • +
    • if false, respond 412 (Precondition Failed) unless + it can be determined that the state-changing request has already + succeeded (see )
    • +
    +
  4. +
  5. + When If-None-Match is present, + evaluate the If-None-Match precondition: +
      +
    • if true, continue to step +
    • +
    • if false for GET/HEAD, respond 304 (Not Modified) +
    • +
    • if false for other methods, respond 412 (Precondition Failed) +
    • +
    +
  6. +
  7. + When the method is GET or HEAD, + If-None-Match is not present, and + If-Modified-Since is present, + evaluate the If-Modified-Since precondition: +
      +
    • if true, continue to step +
    • +
    • if false, respond 304 (Not Modified) +
    • +
    +
  8. +
  9. + When the method is GET and both + Range and If-Range are present, + evaluate the If-Range precondition: +
      +
    • if true and the Range is + applicable to the selected representation, + respond 206 (Partial Content) +
    • +
    • otherwise, ignore the Range header field + and respond 200 (OK) +
    • +
    +
  10. +
  11. + Otherwise, +
      +
    • perform the requested method and + respond according to its success or failure.
    • +
    +
  12. +
+ + Any extension to HTTP that defines additional conditional request + header fields ought to define the order + for evaluating such fields in relation to those defined in this document + and other conditionals that might be found in practice. + +
+
+
+
+ Range Requests + + Clients often encounter interrupted data + transfers as a result of canceled requests or dropped connections. When a + client has stored a partial representation, it is desirable to request the + remainder of that representation in a subsequent request rather than + transfer the entire representation. Likewise, devices with limited local + storage might benefit from being able to request only a subset of a larger + representation, such as a single page of a very large document, or the + dimensions of an embedded image. + + + Range requests are an OPTIONAL feature + of HTTP, designed so that recipients not implementing this feature (or not + supporting it for the target resource) can respond as if it is a normal + GET request without impacting interoperability. Partial responses are + indicated by a distinct status code to not be mistaken for full responses + by caches that might not implement the feature. + +
+ Range Units + + Representation data can be partitioned into subranges when there are + addressable structural units inherent to that data's content coding or + media type. For example, octet (a.k.a. byte) boundaries are a structural + unit common to all representation data, allowing partitions of the data to + be identified as a range of bytes at some offset from the start or end of + that data. + + + This general notion of a "range unit" is used + in the Accept-Ranges () + response header field to advertise support for range requests, the + Range () request header field + to delineate the parts of a representation that are requested, and the + Content-Range () + header field to describe which part of a representation is being + transferred. + + + range-unit = token + + + All range unit names are case-insensitive and ought to be registered + within the "HTTP Range Unit Registry", as defined in + . + + + Range units are intended to be extensible, as described in + . + +
+ Range Specifiers + + + + Ranges are expressed in terms of a range unit paired with a set of range + specifiers. The range unit name determines what kinds of range-spec + are applicable to its own specifiers. Hence, the following grammar is + generic: each range unit is expected to specify requirements on when + int-range, suffix-range, and + other-range are allowed. + + + + + + A range request can specify a single range or a set + of ranges within a single representation. + + + + + ranges-specifier = range-unit "=" range-set + range-set = 1#range-spec + range-spec = int-range + / suffix-range + / other-range + + + + + + An int-range is a range expressed as two non-negative + integers or as one non-negative integer through to the end of the + representation data. + The range unit specifies what the integers mean (e.g., they might indicate + unit offsets from the beginning, inclusive numbered parts, etc.). + + + + + int-range = first-pos "-" [ last-pos ] + first-pos = 1*DIGIT + last-pos = 1*DIGIT + + + An int-range is invalid if the + last-pos value is present and less than the + first-pos. + + + + + A suffix-range is a range expressed as a suffix of the + representation data with the provided non-negative integer maximum length + (in range units). In other words, the last N units of the representation + data. + + + + suffix-range = "-" suffix-length + suffix-length = 1*DIGIT + + + + To provide for extensibility, the other-range rule is a + mostly unconstrained grammar that allows application-specific or future + range units to define additional range specifiers. + + + other-range = 1*( %x21-2B / %x2D-7E ) + ; 1*(VCHAR excluding comma) + + + A ranges-specifier is invalid if it contains any + range-spec that is invalid or undefined for the indicated + range-unit. + + + A valid ranges-specifier is "satisfiable" + if it contains at least one range-spec that is + satisfiable, as defined by the indicated range-unit. + Otherwise, the ranges-specifier is + "unsatisfiable". + +
+
+ Byte Ranges + + The "bytes" range unit is used to express subranges of a representation + data's octet sequence. + Each byte range is expressed as an integer range at some offset, relative + to either the beginning (int-range) or end + (suffix-range) of the representation data. + Byte ranges do not use the other-range specifier. + + + The first-pos value in a bytes int-range + gives the offset of the first byte in a range. + The last-pos value gives the offset of the last + byte in the range; that is, the byte positions specified are inclusive. + Byte offsets start at zero. + + + If the representation data has a content coding applied, each byte range is + calculated with respect to the encoded sequence of bytes, not the sequence + of underlying bytes that would be obtained after decoding. + + + Examples of bytes range specifiers: + +
    +
  • + The first 500 bytes (byte offsets 0-499, inclusive): + + bytes=0-499 + +
  • +
  • + The second 500 bytes (byte offsets 500-999, inclusive): + + bytes=500-999 + +
  • +
+ + A client can limit the number of bytes requested without knowing the size + of the selected representation. + If the last-pos value is absent, or if the value is + greater than or equal to the current length of the representation data, the + byte range is interpreted as the remainder of the representation (i.e., the + server replaces the value of last-pos with a value that + is one less than the current length of the selected representation). + + + A client can refer to the last N bytes (N > 0) of the selected + representation using a suffix-range. + If the selected representation is shorter than the specified + suffix-length, the entire representation is used. + + + Additional examples, assuming a representation of length 10000: + +
    +
  • + The final 500 bytes (byte offsets 9500-9999, inclusive): + + bytes=-500 + + Or: + + bytes=9500- + +
  • +
  • + The first and last bytes only (bytes 0 and 9999): + + bytes=0-0,-1 + +
  • +
  • + The first, middle, and last 1000 bytes: + + bytes= 0-999, 4500-5499, -1000 + +
  • +
  • + Other valid (but not canonical) specifications of the second 500 + bytes (byte offsets 500-999, inclusive): + + bytes=500-600,601-999 + bytes=500-700,601-999 + +
  • +
+ + For a GET request, a valid bytes range-spec + is satisfiable if it is either: + +
    +
  • an int-range with a first-pos that + is less than the current length of the selected representation + or
  • +
  • a suffix-range with a non-zero + suffix-length.
  • +
+ + When a selected representation has zero length, the only + satisfiable form of range-spec in a + GET request is a suffix-range with a + non-zero suffix-length. + + + In the byte-range syntax, first-pos, + last-pos, and suffix-length are + expressed as decimal number of octets. Since there is no predefined limit + to the length of content, recipients MUST anticipate potentially + large decimal numerals and prevent parsing errors due to integer conversion + overflows. + +
+
+
+ Range + + + + + The "Range" header field on a GET request modifies the method semantics to + request transfer of only one or more subranges of the + selected representation data (), + rather than the entire selected representation. + + + Range = ranges-specifier + + + A server MAY ignore the Range header field. However, origin servers and + intermediate caches ought to support byte ranges when possible, since they + support efficient recovery from partially failed transfers and partial + retrieval of large representations. + + + A server MUST ignore a Range header field received with a request method + that is unrecognized or for which range handling is not defined. For this + specification, GET is the only method for which range handling + is defined. + + + An origin server MUST ignore a Range header field that contains a range + unit it does not understand. A proxy MAY discard a Range header + field that contains a range unit it does not understand. + + + A server that supports range requests MAY ignore or reject a + Range header field that contains an invalid + ranges-specifier (), + a ranges-specifier with more than two overlapping ranges, + or a set of many small ranges that are not listed in ascending order, + since these are indications of either a broken client or a deliberate + denial-of-service attack (). + A client SHOULD NOT request multiple ranges that are inherently less + efficient to process and transfer than a single range that encompasses the + same data. + + + A server that supports range requests MAY ignore a Range + header field when the selected representation has no content + (i.e., the selected representation's data is of zero length). + + + A client that is requesting multiple ranges SHOULD list those ranges in + ascending order (the order in which they would typically be received in a + complete representation) unless there is a specific need to request a later + part earlier. For example, a user agent processing a large representation + with an internal catalog of parts might need to request later parts first, + particularly if the representation consists of pages stored in reverse + order and the user agent wishes to transfer one page at a time. + + + The Range header field is evaluated after evaluating the precondition header + fields defined in , and only if the result in absence + of the Range header field would be a 200 (OK) response. In + other words, Range is ignored when a conditional GET would result in a + 304 (Not Modified) response. + + + The If-Range header field () can be used as + a precondition to applying the Range header field. + + + If all of the preconditions are true, the server supports the Range header + field for the target resource, the received Range field-value contains a + valid ranges-specifier with a range-unit + supported for that target resource, and that + ranges-specifier is satisfiable with respect + to the selected representation, + the server SHOULD send a 206 (Partial Content) response + with content containing one or more partial representations + that correspond to the satisfiable range-spec(s) requested. + + + The above does not imply that a server will send all requested ranges. + In some cases, it may only be possible (or efficient) to send a portion of + the requested ranges first, while expecting the client to re-request the + remaining portions later if they are still desired + (see ). + + + If all of the preconditions are true, the server supports the Range header + field for the target resource, the received Range field-value contains a + valid ranges-specifier, and either the + range-unit is not supported for that target resource or + the ranges-specifier is unsatisfiable with respect to + the selected representation, the server SHOULD send a + 416 (Range Not Satisfiable) response. + +
+
+ Accept-Ranges + + + + + The "Accept-Ranges" field in a response indicates whether an upstream + server supports range requests for the target resource. + + + + Accept-Ranges = acceptable-ranges + acceptable-ranges = 1#range-unit + + + For example, a server that supports + byte-range requests can send the field + + Accept-Ranges: bytes + + + to indicate that it supports byte range requests for that target resource, + thereby encouraging its use by the client for future partial requests on + the same request path. + Range units are defined in . + + + A client MAY generate range requests regardless of having received an + Accept-Ranges field. The information only provides advice for the sake of + improving performance and reducing unnecessary network transfers. + + + Conversely, a client MUST NOT assume that receiving an Accept-Ranges field + means that future range requests will return partial responses. The content might + change, the server might only support range requests at certain times or under + certain conditions, or a different intermediary might process the next request. + + + A server that does not support any kind of range request for the target + resource MAY send + + Accept-Ranges: none + + + to advise the client not to attempt a range request on the same request path. + The range unit "none" is reserved for this purpose. + + + The Accept-Ranges field MAY be sent in a trailer section, but is preferred + to be sent as a header field because the information is particularly useful + for restarting large information transfers that have failed in mid-content + (before the trailer section is received). + +
+
+ Content-Range + + + + + The "Content-Range" header field is sent in a single part + 206 (Partial Content) response to indicate the partial range + of the selected representation enclosed as the message content, sent in + each part of a multipart 206 response to indicate the range enclosed within + each body part (), and sent in 416 (Range Not Satisfiable) + responses to provide information about the selected representation. + + + + + + + + + Content-Range = range-unit SP + ( range-resp / unsatisfied-range ) + + range-resp = incl-range "/" ( complete-length / "*" ) + incl-range = first-pos "-" last-pos + unsatisfied-range = "*/" complete-length + + complete-length = 1*DIGIT + + + If a 206 (Partial Content) response contains a + Content-Range header field with a range unit + () that the recipient does not understand, the + recipient MUST NOT attempt to recombine it with a stored representation. + A proxy that receives such a message SHOULD forward it downstream. + + + Content-Range might also be sent as a request modifier to request a + partial PUT, as described in , based on private + agreements between client and origin server. + A server MUST ignore a Content-Range header field received in a request + with a method for which Content-Range support is not defined. + + + For byte ranges, a sender SHOULD indicate the complete length of the + representation from which the range has been extracted, unless the complete + length is unknown or difficult to determine. An asterisk character ("*") in + place of the complete-length indicates that the representation length was + unknown when the header field was generated. + + + The following example illustrates when the complete length of the selected + representation is known by the sender to be 1234 bytes: + + Content-Range: bytes 42-1233/1234 + + + and this second example illustrates when the complete length is unknown: + + Content-Range: bytes 42-1233/* + + + A Content-Range field value is invalid if it contains a + range-resp that has a last-pos + value less than its first-pos value, or a + complete-length value less than or equal to its + last-pos value. The recipient of an invalid + Content-Range + MUST NOT attempt to recombine the received + content with a stored representation. + + + A server generating a 416 (Range Not Satisfiable) response + to a byte-range request SHOULD send a Content-Range header field with an + unsatisfied-range value, as in the following example: + + Content-Range: bytes */1234 + + + The complete-length in a 416 response indicates the current length of the + selected representation. + + + The Content-Range header field has no meaning for status codes that do + not explicitly describe its semantic. For this specification, only the + 206 (Partial Content) and + 416 (Range Not Satisfiable) status codes describe a meaning + for Content-Range. + + + The following are examples of Content-Range values in which the + selected representation contains a total of 1234 bytes: + +
    +
  • + The first 500 bytes: + Content-Range: bytes 0-499/1234 + +
  • +
  • + The second 500 bytes: + Content-Range: bytes 500-999/1234 + +
  • +
  • + All except for the first 500 bytes: + Content-Range: bytes 500-1233/1234 + +
  • +
  • + The last 500 bytes: + Content-Range: bytes 734-1233/1234 + +
  • +
+
+
+ Partial PUT + + + + + Some origin servers support PUT of a partial representation + when the user agent sends a Content-Range header field + () in the request, though + such support is inconsistent and depends on private agreements with + user agents. In general, it requests that the state of the + target resource be partly replaced with the enclosed content + at an offset and length indicated by the Content-Range value, where the + offset is relative to the current selected representation. + + + An origin server SHOULD respond with a 400 (Bad Request) + status code if it receives Content-Range on a PUT for a + target resource that does not support partial PUT requests. + + + Partial PUT is not backwards compatible with the original definition of PUT. + It may result in the content being written as a complete replacement for the + current representation. + + + Partial resource updates are also possible by targeting a separately + identified resource with state that overlaps or extends a portion of the + larger resource, or by using a different method that has been specifically + defined for partial updates (for example, the PATCH method defined in + ). + +
+
+ Media Type multipart/byteranges + + + + When a 206 (Partial Content) response message includes the + content of multiple ranges, they are transmitted as body parts in a + multipart message body () + with the media type of "multipart/byteranges". + + + The "multipart/byteranges" media type includes one or more body parts, each + with its own Content-Type and Content-Range + fields. The required boundary parameter specifies the boundary string used + to separate each body part. + + + Implementation Notes: + +
    +
  1. Additional CRLFs might precede the first boundary string in the body.
  2. +
  3. Although permits the boundary string to be + quoted, some existing implementations handle a quoted boundary + string incorrectly.
  4. +
  5. A number of clients and servers were coded to an early draft + of the byteranges specification that used a media type of + "multipart/x-byteranges", + which is almost (but not quite) compatible with this type.
  6. +
+ + Despite the name, the "multipart/byteranges" media type is not limited to + byte ranges. The following example uses an "exampleunit" range unit: + + HTTP/1.1 206 Partial Content +Date: Tue, 14 Nov 1995 06:25:24 GMT +Last-Modified: Tue, 14 July 04:58:08 GMT +Content-Length: 2331785 +Content-Type: multipart/byteranges; boundary=THIS_STRING_SEPARATES + +--THIS_STRING_SEPARATES +Content-Type: video/example +Content-Range: exampleunit 1.2-4.3/25 + +...the first range... +--THIS_STRING_SEPARATES +Content-Type: video/example +Content-Range: exampleunit 11.2-14.3/25 + +...the second range +--THIS_STRING_SEPARATES-- + + + The following information serves as the registration form for the + "multipart/byteranges" media type. + +
+
Type name:
+
multipart
+
Subtype name:
+
byteranges
+
Required parameters:
+
boundary
+
Optional parameters:
+
N/A
+
Encoding considerations:
+
only "7bit", "8bit", or "binary" are permitted
+
Security considerations:
+
see +
+
Interoperability considerations:
+
N/A
+
Published specification:
+
RFC 9110 (see )
+
Applications that use this media type:
+
HTTP components supporting multiple ranges in a single request
+
Fragment identifier considerations:
+
N/A
+
Additional information:
+
+
+
Deprecated alias names for this type:
+
N/A
+
Magic number(s):
+
N/A
+
File extension(s):
+
N/A
+
Macintosh file type code(s):
+
N/A
+
+
+
Person and email address to contact for further information:
+
See Authors' Addresses section.
+
Intended usage:
+
COMMON
+
Restrictions on usage:
+
N/A
+
Author:
+
See Authors' Addresses section.
+
Change controller:
+
IESG
+
+
+
+
+ Status Codes + + + The status code of a response is a three-digit integer code that describes + the result of the request and the semantics of the response, including + whether the request was successful and what content is enclosed (if any). + All valid status codes are within the range of 100 to 599, inclusive. + + + The first digit of the status code defines the class of response. The + last two digits do not have any categorization role. There are five + values for the first digit: + +
    +
  • + 1xx (Informational): The request was received, continuing + process +
  • +
  • + 2xx (Successful): The request was successfully received, + understood, and accepted +
  • +
  • + 3xx (Redirection): Further action needs to be taken in order to + complete the request +
  • +
  • + 4xx (Client Error): The request contains bad syntax or cannot + be fulfilled +
  • +
  • + 5xx (Server Error): The server failed to fulfill an apparently + valid request +
  • +
+ + HTTP status codes are extensible. A client is not required to understand + the meaning of all registered status codes, though such understanding is + obviously desirable. However, a client MUST understand the class of any + status code, as indicated by the first digit, and treat an unrecognized + status code as being equivalent to the x00 status code of that class. + + + For example, if a client receives an unrecognized status code of 471, + it can see from the first digit that there was something wrong with its + request and treat the response as if it had received a + 400 (Bad Request) status code. The response + message will usually contain a representation that explains the status. + + + Values outside the range 100..599 are invalid. Implementations often use + three-digit integer values outside of that range (i.e., 600..999) for + internal communication of non-HTTP status (e.g., library errors). A client + that receives a response with an invalid status code SHOULD process the + response as if it had a 5xx (Server Error) status code. + + + + + + A single request can have multiple associated responses: zero or more + "interim" (non-final) responses with status codes in the + "informational" (1xx) range, followed by exactly one + "final" response with a status code in one of the other ranges. + +
+ Overview of Status Codes + + The status codes listed below are defined in this specification. + The reason phrases listed here are only recommendations -- they can be + replaced by local equivalents or left out altogether without affecting the + protocol. + + + Responses with status codes that are defined as heuristically cacheable + (e.g., 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, and 501 in this + specification) can be reused by a cache with heuristic expiration unless + otherwise indicated by the method definition or explicit cache controls + ; all other status codes are not heuristically cacheable. + + + Additional status codes, outside the scope of this specification, have been + specified for use in HTTP. All such status codes ought to be registered + within the "Hypertext Transfer Protocol (HTTP) Status Code Registry", + as described in . + +
+
+ Informational 1xx + + + + The 1xx (Informational) class of status code indicates an + interim response for communicating connection status or request progress + prior to completing the requested action and sending a final response. + Since HTTP/1.0 did not define any 1xx status codes, a server MUST NOT send + a 1xx response to an HTTP/1.0 client. + + + A 1xx response is terminated by the end of the header section; + it cannot contain content or trailers. + + + A client MUST be able to parse one or more 1xx responses received + prior to a final response, even if the client does not expect one. + A user agent MAY ignore unexpected 1xx responses. + + + A proxy MUST forward 1xx responses unless the proxy itself + requested the generation of the 1xx response. For example, if a + proxy adds an "Expect: 100-continue" header field when it forwards a request, + then it need not forward the corresponding 100 (Continue) + response(s). + +
+ 100 Continue + + + The 100 (Continue) status code indicates that the initial + part of a request has been received and has not yet been rejected by the + server. The server intends to send a final response after the request has + been fully received and acted upon. + + + When the request contains an Expect header field that + includes a 100-continue expectation, the 100 response + indicates that the server wishes to receive the request content, + as described in . The client + ought to continue sending the request and discard the 100 response. + + + If the request did not contain an Expect header field + containing the 100-continue expectation, + the client can simply discard this interim response. + +
+
+ 101 Switching Protocols + + + The 101 (Switching Protocols) status code indicates that the + server understands and is willing to comply with the client's request, + via the Upgrade header field (), for + a change in the application protocol being used on this connection. + The server MUST generate an Upgrade header field in the response that + indicates which protocol(s) will be in effect after this response. + + + It is assumed that the server will only agree to switch protocols when + it is advantageous to do so. For example, switching to a newer version of + HTTP might be advantageous over older versions, and switching to a + real-time, synchronous protocol might be advantageous when delivering + resources that use such features. + +
+
+
+ Successful 2xx + + + + The 2xx (Successful) class of status code indicates that + the client's request was successfully received, understood, and accepted. + +
+ 200 OK + + + The 200 (OK) status code indicates that the request has + succeeded. The content sent in a 200 response depends on the request + method. For the methods defined by this specification, the intended meaning + of the content can be summarized as: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Request MethodResponse content is a representation of:
GETthe target resource +
HEADthe target resource, like GET, but without + transferring the representation data
POSTthe status of, or results obtained from, the action
PUT, DELETEthe status of the action
OPTIONScommunication options for the target resource
TRACEthe request message as received by the server returning the + trace
+ + Aside from responses to CONNECT, a 200 response is expected to contain + message content unless the message framing explicitly indicates that the + content has zero length. If some aspect of the request indicates a + preference for no content upon success, the origin server ought to send a + 204 (No Content) response instead. + For CONNECT, there is no content because the successful result is a + tunnel, which begins immediately after the 200 response header section. + + + A 200 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + + + In 200 responses to GET or HEAD, an origin server SHOULD send any + available validator fields () for the + selected representation, with both a strong entity tag and + a Last-Modified date being preferred. + + + In 200 responses to state-changing methods, any validator fields + () sent in the response convey the + current validators for the new representation formed as a result of + successfully applying the request semantics. Note that the PUT method + () has additional requirements that might preclude + sending such validators. + +
+
+ 201 Created + + + The 201 (Created) status code indicates that the request has + been fulfilled and has resulted in one or more new resources being created. + The primary resource created by the request is identified by either a + Location header field in the response or, if no + Location header field is received, by the target URI. + + + The 201 response content typically describes and links to the resource(s) + created. Any validator fields () + sent in the response convey the current validators for a new + representation created by the request. Note that the PUT method + () has additional requirements that might preclude + sending such validators. + +
+
+ 202 Accepted + + + The 202 (Accepted) status code indicates that the request + has been accepted for processing, but the processing has not been + completed. The request might or might not eventually be acted upon, as it + might be disallowed when processing actually takes place. There is no + facility in HTTP for re-sending a status code from an asynchronous + operation. + + + The 202 response is intentionally noncommittal. Its purpose is to + allow a server to accept a request for some other process (perhaps a + batch-oriented process that is only run once per day) without + requiring that the user agent's connection to the server persist + until the process is completed. The representation sent with this + response ought to describe the request's current status and point to + (or embed) a status monitor that can provide the user with an estimate of + when the request will be fulfilled. + +
+
+ 203 Non-Authoritative Information + + + The 203 (Non-Authoritative Information) status code + indicates that the request was successful but the enclosed content has been + modified from that of the origin server's 200 (OK) response + by a transforming proxy (). This status code allows the + proxy to notify recipients when a transformation has been applied, since + that knowledge might impact later decisions regarding the content. For + example, future cache validation requests for the content might only be + applicable along the same request path (through the same proxies). + + + A 203 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 204 No Content + + + The 204 (No Content) status code indicates that the server + has successfully fulfilled the request and that there is no additional + content to send in the response content. Metadata in the response + header fields refer to the target resource and its + selected representation after the requested action was applied. + + + For example, if a 204 status code is received in response to a PUT + request and the response contains an ETag field, then + the PUT was successful and the ETag field value contains the entity tag for + the new representation of that target resource. + + + The 204 response allows a server to indicate that the action has been + successfully applied to the target resource, while implying that the + user agent does not need to traverse away from its current "document view" + (if any). The server assumes that the user agent will provide some + indication of the success to its user, in accord with its own interface, + and apply any new or updated metadata in the response to its active + representation. + + + For example, a 204 status code is commonly used with document editing + interfaces corresponding to a "save" action, such that the document + being saved remains available to the user for editing. It is also + frequently used with interfaces that expect automated data transfers + to be prevalent, such as within distributed version control systems. + + + A 204 response is terminated by the end of the header section; + it cannot contain content or trailers. + + + A 204 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 205 Reset Content + + + The 205 (Reset Content) status code indicates that the + server has fulfilled the request and desires that the user agent reset the + "document view", which caused the request to be sent, to its original state + as received from the origin server. + + + This response is intended to support a common data entry use case where + the user receives content that supports data entry (a form, notepad, + canvas, etc.), enters or manipulates data in that space, causes the entered + data to be submitted in a request, and then the data entry mechanism is + reset for the next entry so that the user can easily initiate another + input action. + + + Since the 205 status code implies that no additional content will be + provided, a server MUST NOT generate content in a 205 response. + +
+
+ 206 Partial Content + + + The 206 (Partial Content) status code indicates that the + server is successfully fulfilling a range request for the target resource + by transferring one or more parts of the + selected representation. + + + A server that supports range requests () will + usually attempt to satisfy all of the requested ranges, since sending + less data will likely result in another client request for the remainder. + However, a server might want to send only a subset of the data requested + for reasons of its own, such as temporary unavailability, cache efficiency, + load balancing, etc. Since a 206 response is self-descriptive, the client + can still understand a response that only partially satisfies its range + request. + + + A client MUST inspect a 206 response's Content-Type and + Content-Range field(s) to determine what parts are enclosed + and whether additional requests are needed. + + + A server that generates a 206 response MUST generate the following + header fields, in addition to those required in the subsections below, + if the field would + have been sent in a 200 (OK) response to the same request: + Date, Cache-Control, ETag, + Expires, Content-Location, and + Vary. + + + A Content-Length header field present in a 206 response + indicates the number of octets in the content of this message, which is + usually not the complete length of the selected representation. + Each Content-Range header field includes information about the + selected representation's complete length. + + + A sender that generates a 206 response to a request with an If-Range + header field SHOULD NOT generate other representation header + fields beyond those required because the client + already has a prior response containing those header fields. + Otherwise, a sender MUST generate all of the representation header + fields that would have been sent in a 200 (OK) response + to the same request. + + + A 206 response is heuristically cacheable; i.e., unless otherwise indicated by + explicit cache controls (see ). + +
+ Single Part + + If a single part is being transferred, the server generating the 206 + response MUST generate a Content-Range header field, + describing what range of the selected representation is enclosed, and a + content consisting of the range. For example: + + HTTP/1.1 206 Partial Content +Date: Wed, 15 Nov 1995 06:25:24 GMT +Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT +Content-Range: bytes 21010-47021/47022 +Content-Length: 26012 +Content-Type: image/gif + +... 26012 bytes of partial image data ... + +
+
+ Multiple Parts + + If multiple parts are being transferred, the server generating the 206 + response MUST generate "multipart/byteranges" content, as defined + in , and a + Content-Type header field containing the + "multipart/byteranges" media type and its required boundary parameter. + To avoid confusion with single-part responses, a server MUST NOT generate + a Content-Range header field in the HTTP header section of a + multiple part response (this field will be sent in each part instead). + + + Within the header area of each body part in the multipart content, the + server MUST generate a Content-Range header field + corresponding to the range being enclosed in that body part. + If the selected representation would have had a Content-Type + header field in a 200 (OK) response, the server SHOULD + generate that same Content-Type header field in the header area of + each body part. For example: + + HTTP/1.1 206 Partial Content +Date: Wed, 15 Nov 1995 06:25:24 GMT +Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT +Content-Length: 1741 +Content-Type: multipart/byteranges; boundary=THIS_STRING_SEPARATES + +--THIS_STRING_SEPARATES +Content-Type: application/pdf +Content-Range: bytes 500-999/8000 + +...the first range... +--THIS_STRING_SEPARATES +Content-Type: application/pdf +Content-Range: bytes 7000-7999/8000 + +...the second range +--THIS_STRING_SEPARATES-- + + + When multiple ranges are requested, a server MAY coalesce any of the + ranges that overlap, or that are separated by a gap that is smaller than the + overhead of sending multiple parts, regardless of the order in which the + corresponding range-spec appeared in the received Range + header field. Since the typical overhead between each part of a + "multipart/byteranges" is around 80 bytes, depending on the selected + representation's media type and the chosen boundary parameter length, it + can be less efficient to transfer many small disjoint parts than it is to + transfer the entire selected representation. + + + A server MUST NOT generate a multipart response to a request for a single + range, since a client that does not request multiple parts might not + support multipart responses. However, a server MAY generate a + "multipart/byteranges" response with only a single body part if multiple + ranges were requested and only one range was found to be satisfiable or + only one range remained after coalescing. + A client that cannot process a "multipart/byteranges" response MUST NOT + generate a request that asks for multiple ranges. + + + A server that generates a multipart response SHOULD send + the parts in the same order that the corresponding range-spec appeared + in the received Range header field, excluding those ranges + that were deemed unsatisfiable or that were coalesced into other ranges. + A client that receives a multipart response MUST inspect the + Content-Range header field present in each body part in + order to determine which range is contained in that body part; a client + cannot rely on receiving the same ranges that it requested, nor the same + order that it requested. + +
+
+ Combining Parts + + A response might transfer only a subrange of a representation if the + connection closed prematurely or if the request used one or more Range + specifications. After several such transfers, a client might have + received several ranges of the same representation. These ranges can only + be safely combined if they all have in common the same strong validator + (). + + + A client that has received multiple partial responses to GET requests on a + target resource MAY combine those responses into a larger continuous + range if they share the same strong validator. + + + If the most recent response is an incomplete 200 (OK) + response, then the header fields of that response are used for any + combined response and replace those of the matching stored responses. + + + If the most recent response is a 206 (Partial Content) + response and at least one of the matching stored responses is a + 200 (OK), then the combined response header fields consist + of the most recent 200 response's header fields. If all of the matching + stored responses are 206 responses, then the stored response with the most + recent header fields is used as the source of header fields for the + combined response, except that the client MUST use other header fields + provided in the new response, aside from Content-Range, to + replace all instances of the corresponding header fields in the stored + response. + + + The combined response content consists of the union of partial content + ranges within the new response and all of the matching stored responses. + If the union consists of the entire range of the representation, then the + client MUST process the combined response as if it were a complete + 200 (OK) response, including a Content-Length + header field that reflects the complete length. + Otherwise, the client MUST process the set of continuous ranges as one of + the following: + an incomplete 200 (OK) response if the combined response is + a prefix of the representation, + a single 206 (Partial Content) response containing + "multipart/byteranges" content, or + multiple 206 (Partial Content) responses, each with one + continuous range that is indicated by a Content-Range header + field. + +
+
+
+
+ Redirection 3xx + + + + The 3xx (Redirection) class of status code indicates that + further action needs to be taken by the user agent in order to fulfill the + request. There are several types of redirects: + +
    +
  1. + Redirects that indicate this resource might be available at a + different URI, as provided by the Location header field, + as in the status codes 301 (Moved Permanently), + 302 (Found), 307 (Temporary Redirect), and + 308 (Permanent Redirect). +
  2. +
  3. + Redirection that offers a choice among matching resources capable + of representing this resource, as in the + 300 (Multiple Choices) status code. +
  4. +
  5. + Redirection to a different resource, identified by the + Location header field, that can represent an indirect + response to the request, as in the 303 (See Other) + status code. +
  6. +
  7. + Redirection to a previously stored result, as in the + 304 (Not Modified) status code. +
  8. +
+ + + If a Location header field + () is provided, the user agent MAY + automatically redirect its request to the URI referenced by the Location + field value, even if the specific status code is not understood. + Automatic redirection needs to be done with care for methods not known to be + safe, as defined in , since + the user might not wish to redirect an unsafe request. + + + When automatically following a redirected request, the user agent SHOULD + resend the original request message with the following modifications: + +
    +
  1. + + Replace the target URI with the URI referenced by the redirection response's + Location header field value after resolving it relative to the original + request's target URI. + +
  2. +
  3. + + Remove header fields that were automatically generated by the implementation, + replacing them with updated values as appropriate to the new request. This + includes: + +
      +
    1. Connection-specific header fields (see ),
    2. +
    3. Header fields specific to the client's proxy configuration, + including (but not limited to) Proxy-Authorization,
    4. +
    5. Origin-specific header fields (if any), including (but not + limited to) Host,
    6. +
    7. Validating header fields that were added by the implementation's + cache (e.g., If-None-Match, + If-Modified-Since), and
    8. +
    9. Resource-specific header fields, including (but not limited to) + Referer, Origin, + Authorization, and Cookie.
    10. +
    +
  4. +
  5. + + Consider removing header fields that were not automatically generated by the + implementation (i.e., those present in the request because they were added + by the calling context) where there are security implications; this + includes but is not limited to Authorization and Cookie. + +
  6. +
  7. + + Change the request method according to the redirecting status code's + semantics, if applicable. + +
  8. +
  9. + + If the request method has been changed to GET or HEAD, remove + content-specific header fields, including (but not limited to) + Content-Encoding, + Content-Language, Content-Location, + Content-Type, Content-Length, + Digest, Last-Modified. + +
  10. +
+ + A client SHOULD detect and intervene in cyclical redirections (i.e., + "infinite" redirection loops). + + +
+ 300 Multiple Choices + + + The 300 (Multiple Choices) status code indicates that the + target resource has more than one representation, each with + its own more specific identifier, and information about the alternatives is + being provided so that the user (or user agent) can select a preferred + representation by redirecting its request to one or more of those + identifiers. In other words, the server desires that the user agent engage + in reactive negotiation to select the most appropriate representation(s) + for its needs (). + + + If the server has a preferred choice, the server SHOULD generate a + Location header field containing a preferred choice's URI + reference. The user agent MAY use the Location field value for automatic + redirection. + + + For request methods other than HEAD, the server SHOULD generate content + in the 300 response containing a list of representation metadata and URI + reference(s) from which the user or user agent can choose the one most + preferred. The user agent MAY make a selection from that list + automatically if it understands the provided media type. A specific format + for automatic selection is not defined by this specification because HTTP + tries to remain orthogonal to the definition of its content. + In practice, the representation is provided in some easily parsed format + believed to be acceptable to the user agent, as determined by shared design + or content negotiation, or in some commonly accepted hypertext format. + + + A 300 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + + +
+
+ 301 Moved Permanently + + + The 301 (Moved Permanently) status code indicates that the + target resource has been assigned a new permanent URI and + any future references to this resource ought to use one of the enclosed + URIs. The server is suggesting that a user agent with link-editing capability + can permanently replace references to the target URI with one of the + new references sent by the server. However, this suggestion is usually + ignored unless the user agent is actively editing references + (e.g., engaged in authoring content), the connection is secured, and + the origin server is a trusted authority for the content being edited. + + + The server SHOULD generate a Location header field in the + response containing a preferred URI reference for the new permanent URI. + The user agent MAY use the Location field value for automatic redirection. + The server's response content usually contains a short hypertext note with + a hyperlink to the new URI(s). + + + + A 301 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 302 Found + + + The 302 (Found) status code indicates that the target + resource resides temporarily under a different URI. Since the redirection + might be altered on occasion, the client ought to continue to use the + target URI for future requests. + + + The server SHOULD generate a Location header field in the + response containing a URI reference for the different URI. + The user agent MAY use the Location field value for automatic redirection. + The server's response content usually contains a short hypertext note with + a hyperlink to the different URI(s). + + +
+
+ 303 See Other + + + The 303 (See Other) status code indicates that the server is + redirecting the user agent to a different resource, as indicated by a URI + in the Location header field, which is intended to provide + an indirect response to the original request. A user agent can perform a + retrieval request targeting that URI (a GET or HEAD request if using HTTP), + which might also be redirected, and present the eventual result as an + answer to the original request. Note that the new URI in the Location + header field is not considered equivalent to the target URI. + + + This status code is applicable to any HTTP method. It is + primarily used to allow the output of a POST action to redirect + the user agent to a different resource, since doing so provides the + information corresponding to the POST response as a resource that + can be separately identified, bookmarked, and cached. + + + A 303 response to a GET request indicates that the origin server does not + have a representation of the target resource that can be + transferred by the server over HTTP. However, the + Location field value refers to a resource that is + descriptive of the target resource, such that making a retrieval request + on that other resource might result in a representation that is useful to + recipients without implying that it represents the original target resource. + Note that answers to the questions of what can be represented, what + representations are adequate, and what might be a useful description are + outside the scope of HTTP. + + + Except for responses to a HEAD request, the representation of a 303 + response ought to contain a short hypertext note with a hyperlink to the + same URI reference provided in the Location header field. + +
+
+ 304 Not Modified + + + The 304 (Not Modified) status code indicates that a + conditional GET or HEAD request has been + received and would have resulted in a 200 (OK) response + if it were not for the fact that the condition evaluated to false. + In other words, there is no need for the server to transfer a + representation of the target resource because the request indicates that + the client, which made the request conditional, already has a valid + representation; the server is therefore redirecting the client to make + use of that stored representation as if it were the content of a + 200 (OK) response. + + + The server generating a 304 response MUST generate any of the following + header fields that would have been sent in a 200 (OK) + response to the same request: + +
    +
  • + Content-Location, Date, ETag, + and Vary +
  • +
  • + Cache-Control and Expires (see + ) +
  • +
+ + Since the goal of a 304 response is to minimize information transfer + when the recipient already has one or more cached representations, + a sender SHOULD NOT generate representation metadata other + than the above listed fields unless said metadata exists for the + purpose of guiding cache updates (e.g., Last-Modified might + be useful if the response does not have an ETag field). + + + Requirements on a cache that receives a 304 response are defined in + . If the conditional request originated with an + outbound client, such as a user agent with its own cache sending a + conditional GET to a shared proxy, then the proxy SHOULD forward the + 304 response to that client. + + + A 304 response is terminated by the end of the header section; + it cannot contain content or trailers. + +
+
+ 305 Use Proxy + + + The 305 (Use Proxy) status code was defined in a previous + version of this specification and is now deprecated (). + +
+
+ 306 (Unused) + + + The 306 status code was defined in a previous version of this + specification, is no longer used, and the code is reserved. + +
+
+ 307 Temporary Redirect + + + The 307 (Temporary Redirect) status code indicates that the + target resource resides temporarily under a different URI + and the user agent MUST NOT change the request method if it performs an + automatic redirection to that URI. + Since the redirection can change over time, the client ought to continue + using the original target URI for future requests. + + + The server SHOULD generate a Location header field in the + response containing a URI reference for the different URI. + The user agent MAY use the Location field value for automatic redirection. + The server's response content usually contains a short hypertext note with + a hyperlink to the different URI(s). + +
+
+ 308 Permanent Redirect + + + The 308 (Permanent Redirect) status code indicates that the + target resource has been assigned a new permanent URI and + any future references to this resource ought to use one of the enclosed + URIs. The server is suggesting that a user agent with link-editing capability + can permanently replace references to the target URI with one of the + new references sent by the server. However, this suggestion is usually + ignored unless the user agent is actively editing references + (e.g., engaged in authoring content), the connection is secured, and + the origin server is a trusted authority for the content being edited. + + + The server SHOULD generate a Location header field in the + response containing a preferred URI reference for the new permanent URI. + The user agent MAY use the Location field value for automatic redirection. + The server's response content usually contains a short hypertext note with + a hyperlink to the new URI(s). + + + A 308 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + + +
+
+
+ Client Error 4xx + + + + The 4xx (Client Error) class of status code indicates that + the client seems to have erred. Except when responding to a HEAD request, + the server SHOULD send a representation containing an explanation of + the error situation, and whether it is a temporary or permanent condition. + These status codes are applicable to any request method. User agents + SHOULD display any included representation to the user. + +
+ 400 Bad Request + + + The 400 (Bad Request) status code indicates that the server + cannot or will not process the request due to something that is perceived + to be a client error (e.g., malformed request syntax, invalid request + message framing, or deceptive request routing). + +
+
+ 401 Unauthorized + + + The 401 (Unauthorized) status code indicates that the + request has not been applied because it lacks valid authentication + credentials for the target resource. + The server generating a 401 response MUST send a + WWW-Authenticate header field + () + containing at least one challenge applicable to the target resource. + + + If the request included authentication credentials, then the 401 response + indicates that authorization has been refused for those credentials. + The user agent MAY repeat the request with a new or replaced + Authorization header field (). + If the 401 response contains the same challenge as the prior response, and + the user agent has already attempted authentication at least once, then the + user agent SHOULD present the enclosed representation to the user, since + it usually contains relevant diagnostic information. + +
+
+ 402 Payment Required + + + The 402 (Payment Required) status code is reserved for + future use. + +
+
+ 403 Forbidden + + + The 403 (Forbidden) status code indicates that the + server understood the request but refuses to fulfill it. + A server that wishes to make public why the request has been forbidden + can describe that reason in the response content (if any). + + + If authentication credentials were provided in the request, the + server considers them insufficient to grant access. + The client SHOULD NOT automatically repeat the request with the same + credentials. + The client MAY repeat the request with new or different credentials. + However, a request might be forbidden for reasons unrelated to the + credentials. + + + An origin server that wishes to "hide" the current existence of a forbidden + target resource + MAY instead respond with a status + code of 404 (Not Found). + +
+
+ 404 Not Found + + + The 404 (Not Found) status code indicates that the origin + server did not find a current representation for the + target resource or is not willing to disclose that one + exists. A 404 status code does not indicate whether this lack of representation + is temporary or permanent; the 410 (Gone) status code is + preferred over 404 if the origin server knows, presumably through some + configurable means, that the condition is likely to be permanent. + + + A 404 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 405 Method Not Allowed + + + The 405 (Method Not Allowed) status code indicates that the + method received in the request-line is known by the origin server but + not supported by the target resource. + The origin server MUST generate an Allow header field in + a 405 response containing a list of the target resource's currently + supported methods. + + + A 405 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 406 Not Acceptable + + + The 406 (Not Acceptable) status code indicates that the + target resource does not have a current representation that + would be acceptable to the user agent, according to the + proactive negotiation header fields received in the request + (), and the server is unwilling to supply a + default representation. + + + The server SHOULD generate content containing a list of available + representation characteristics and corresponding resource identifiers from + which the user or user agent can choose the one most appropriate. + A user agent MAY automatically select the most appropriate choice from + that list. However, this specification does not define any standard for + such automatic selection, as described in . + +
+
+ 407 Proxy Authentication Required + + + The 407 (Proxy Authentication Required) status code is + similar to 401 (Unauthorized), but it indicates that the client + needs to authenticate itself in order to use a proxy for this request. + The proxy MUST send a Proxy-Authenticate header field + () containing a challenge + applicable to that proxy for the request. The client MAY repeat + the request with a new or replaced Proxy-Authorization + header field (). + +
+
+ 408 Request Timeout + + + The 408 (Request Timeout) status code indicates + that the server did not receive a complete request message within the time + that it was prepared to wait. + + + If the client has an outstanding request in transit, it MAY repeat that + request. If the current connection is not usable (e.g., as it would be in + HTTP/1.1 because request delimitation is lost), a new connection will be + used. + +
+
+ 409 Conflict + + + The 409 (Conflict) status code indicates that the request + could not be completed due to a conflict with the current state of the target + resource. This code is used in situations where the user might be able to + resolve the conflict and resubmit the request. The server SHOULD generate + content that includes enough information for a user to recognize the + source of the conflict. + + + Conflicts are most likely to occur in response to a PUT request. For + example, if versioning were being used and the representation being PUT + included changes to a resource that conflict with those made by an + earlier (third-party) request, the origin server might use a 409 response + to indicate that it can't complete the request. In this case, the response + representation would likely contain information useful for merging the + differences based on the revision history. + +
+
+ 410 Gone + + + The 410 (Gone) status code indicates that access to the + target resource is no longer available at the origin + server and that this condition is likely to be permanent. If the origin + server does not know, or has no facility to determine, whether or not the + condition is permanent, the status code 404 (Not Found) + ought to be used instead. + + + The 410 response is primarily intended to assist the task of web + maintenance by notifying the recipient that the resource is + intentionally unavailable and that the server owners desire that + remote links to that resource be removed. Such an event is common for + limited-time, promotional services and for resources belonging to + individuals no longer associated with the origin server's site. It is not + necessary to mark all permanently unavailable resources as "gone" or + to keep the mark for any length of time -- that is left to the + discretion of the server owner. + + + A 410 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 411 Length Required + + + The 411 (Length Required) status code indicates that the + server refuses to accept the request without a defined + Content-Length (). + The client MAY repeat the request if it adds a valid Content-Length + header field containing the length of the request content. + +
+
+ 412 Precondition Failed + + + The 412 (Precondition Failed) status code indicates that one + or more conditions given in the request header fields evaluated to false + when tested on the server (). This + response status code allows the client to place preconditions on the + current resource state (its current representations and metadata) and, + thus, prevent the request method from being applied if the target resource + is in an unexpected state. + +
+
+ 413 Content Too Large + + + The 413 (Content Too Large) status code indicates + that the server is refusing to process a request because the request + content is larger than the server is willing or able to process. + The server MAY terminate the request, if the protocol version in use + allows it; otherwise, the server MAY close the connection. + + + If the condition is temporary, the server SHOULD generate a + Retry-After header field to indicate that it is temporary + and after what time the client MAY try again. + +
+
+ 414 URI Too Long + + + The 414 (URI Too Long) status code indicates that the server + is refusing to service the request because the + target URI is longer than the server is willing to + interpret. This rare condition is only likely to occur when a client has + improperly converted a POST request to a GET request with long query + information, when the client has descended into an infinite loop of + redirection (e.g., a redirected URI prefix that points to a suffix of + itself) or when the server is under attack by a client attempting to + exploit potential security holes. + + + A 414 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 415 Unsupported Media Type + + + The 415 (Unsupported Media Type) status code indicates that + the origin server is refusing to service the request because the content is + in a format not supported by this method on the target resource. + + + The format problem might be due to the request's indicated + Content-Type or Content-Encoding, or as a + result of inspecting the data directly. + + + If the problem was caused by an unsupported content coding, the + Accept-Encoding response header field + () ought to be + used to indicate which (if any) content codings would have been accepted + in the request. + + + On the other hand, if the cause was an unsupported media type, the + Accept response header field () + can be used to indicate which media types would have been accepted + in the request. + +
+
+ 416 Range Not Satisfiable + + + The 416 (Range Not Satisfiable) status code indicates that + the set of ranges in the request's Range header field + () has been rejected either because none of + the requested ranges are satisfiable or because the client has requested + an excessive number of small or overlapping ranges (a potential denial of + service attack). + + + Each range unit defines what is required for its own range sets to be + satisfiable. For example, defines what makes + a bytes range set satisfiable. + + + A server that generates a 416 response to a byte-range request SHOULD + generate a Content-Range header field + specifying the current length of the selected representation + (). + + + For example: + + HTTP/1.1 416 Range Not Satisfiable +Date: Fri, 20 Jan 2012 15:41:54 GMT +Content-Range: bytes */47022 + + +
+
+ 417 Expectation Failed + + + The 417 (Expectation Failed) status code indicates that the + expectation given in the request's Expect header field + () could not be met by at least one of the + inbound servers. + +
+
+ 418 (Unused) + + + was an April 1 RFC that lampooned the various ways + HTTP was abused; one such abuse was the definition of an + application-specific 418 status code, which has been deployed as a joke + often enough for the code to be unusable for any future use. + + + Therefore, the 418 status code is reserved in the IANA HTTP Status Code + Registry. This indicates that the status code cannot be assigned to other + applications currently. If future circumstances require its use (e.g., + exhaustion of 4NN status codes), it can be re-assigned to another use. + +
+
+ 421 Misdirected Request + + + The 421 (Misdirected Request) status code indicates that the request was + directed at a server that is unable or unwilling to produce an + authoritative response for the target URI. An origin server (or gateway + acting on behalf of the origin server) sends 421 to reject a target URI + that does not match an origin for which the server has been + configured () or does not match the connection + context over which the request was received + (). + + + A client that receives a 421 (Misdirected Request) response MAY retry the + request, whether or not the request method is idempotent, over a different + connection, such as a fresh connection specific to the target resource's + origin, or via an alternative service . + + + A proxy MUST NOT generate a 421 response. + +
+
+ 422 Unprocessable Content + + + The 422 (Unprocessable Content) status code indicates that the server + understands the content type of the request content (hence a + 415 (Unsupported Media Type) status code is inappropriate), + and the syntax of the request content is correct, but it was unable to process + the contained instructions. For example, this status code can be sent if + an XML request content contains well-formed (i.e., syntactically correct), but + semantically erroneous XML instructions. + +
+
+ 426 Upgrade Required + + + The 426 (Upgrade Required) status code indicates that the + server refuses to perform the request using the current protocol but might + be willing to do so after the client upgrades to a different protocol. + The server MUST send an Upgrade header field in a 426 + response to indicate the required protocol(s) (). + + + Example: + + HTTP/1.1 426 Upgrade Required +Upgrade: HTTP/3.0 +Connection: Upgrade +Content-Length: 53 +Content-Type: text/plain + +This service requires use of the HTTP/3.0 protocol. + +
+
+
+ Server Error 5xx + + + + The 5xx (Server Error) class of status code indicates that + the server is aware that it has erred or is incapable of performing the + requested method. + Except when responding to a HEAD request, the server SHOULD send a + representation containing an explanation of the error situation, and + whether it is a temporary or permanent condition. + A user agent SHOULD display any included representation to the user. + These status codes are applicable to any request method. + +
+ 500 Internal Server Error + + + The 500 (Internal Server Error) status code indicates that + the server encountered an unexpected condition that prevented it from + fulfilling the request. + +
+
+ 501 Not Implemented + + + The 501 (Not Implemented) status code indicates that the + server does not support the functionality required to fulfill the request. + This is the appropriate response when the server does not recognize the + request method and is not capable of supporting it for any resource. + + + A 501 response is heuristically cacheable; i.e., unless otherwise indicated by + the method definition or explicit cache controls (see ). + +
+
+ 502 Bad Gateway + + + The 502 (Bad Gateway) status code indicates that the server, + while acting as a gateway or proxy, received an invalid response from an + inbound server it accessed while attempting to fulfill the request. + +
+
+ 503 Service Unavailable + + + The 503 (Service Unavailable) status code indicates that the + server is currently unable to handle the request due to a temporary overload + or scheduled maintenance, which will likely be alleviated after some delay. + The server MAY send a Retry-After header field + () to suggest an appropriate + amount of time for the client to wait before retrying the request. + + +
+
+ 504 Gateway Timeout + + + The 504 (Gateway Timeout) status code indicates that the + server, while acting as a gateway or proxy, did not receive a timely + response from an upstream server it needed to access in order to + complete the request. + +
+
+ 505 HTTP Version Not Supported + + + The 505 (HTTP Version Not Supported) status code indicates + that the server does not support, or refuses to support, the major version + of HTTP that was used in the request message. The server is indicating that + it is unable or unwilling to complete the request using the same major + version as the client, as described in , other than with this + error message. The server SHOULD generate a representation for the 505 + response that describes why that version is not supported and what other + protocols are supported by that server. + +
+
+
+
+ Extending HTTP + + HTTP defines a number of generic extension points that can be used to + introduce capabilities to the protocol without introducing a new version, + including methods, status codes, field names, and further extensibility + points within defined fields, such as authentication schemes and + cache directives (see Cache-Control extensions in ). Because the semantics of HTTP are + not versioned, these extension points are persistent; the version of the + protocol in use does not affect their semantics. + + + Version-independent extensions are discouraged from depending on or + interacting with the specific version of the protocol in use. When this is + unavoidable, careful consideration needs to be given to how the extension + can interoperate across versions. + + + Additionally, specific versions of HTTP might have their own extensibility + points, such as transfer codings in HTTP/1.1 () and HTTP/2 SETTINGS or frame types + (). These extension points are specific to the + version of the protocol they occur within. + + + Version-specific extensions cannot override or modify the semantics of + a version-independent mechanism or extension point (like a method or + header field) without explicitly being allowed by that protocol element. For + example, the CONNECT method () allows this. + + + These guidelines assure that the protocol operates correctly and + predictably, even when parts of the path implement different versions of + HTTP. + +
+ Method Extensibility +
+ Method Registry + + The "Hypertext Transfer Protocol (HTTP) Method Registry", maintained by + IANA at , + registers method names. + + + HTTP method registrations MUST include the following fields: + +
    +
  • Method Name (see )
  • +
  • Safe ("yes" or "no", see )
  • +
  • Idempotent ("yes" or "no", see )
  • +
  • Pointer to specification text
  • +
+ + Values to be added to this namespace require IETF Review + (see ). + +
+
+ Considerations for New Methods + + Standardized methods are generic; that is, they are potentially + applicable to any resource, not just one particular media type, kind of + resource, or application. As such, it is preferred that new methods + be registered in a document that isn't specific to a single application or + data format, since orthogonal technologies deserve orthogonal specification. + + + Since message parsing () needs to be + independent of method + semantics (aside from responses to HEAD), definitions of new methods + cannot change the parsing algorithm or prohibit the presence of content + on either the request or the response message. + Definitions of new methods can specify that only a zero-length content + is allowed by requiring a Content-Length header field with a value of "0". + + + Likewise, new methods cannot use the special host:port and asterisk forms of + request target that are allowed for CONNECT and + OPTIONS, respectively (). + A full URI in absolute form is needed for the target URI, which means either + the request target needs to be sent in absolute form or the target URI will + be reconstructed from the request context in the same way it is for other + methods. + + + A new method definition needs to indicate whether it is safe (), idempotent (), + cacheable (), what + semantics are to be associated with the request content (if any), and what + refinements the method makes to header field or status code semantics. + If the new method is cacheable, its definition ought to describe how, and + under what conditions, a cache can store a response and use it to satisfy a + subsequent request. + The new method ought to describe whether it can be made conditional + () and, if so, how a server responds + when the condition is false. + Likewise, if the new method might have some use for partial response + semantics (), it ought to document this, too. + + +
+
+
+ Status Code Extensibility +
+ Status Code Registry + + The "Hypertext Transfer Protocol (HTTP) Status Code Registry", maintained + by IANA at , + registers status code numbers. + + + A registration MUST include the following fields: + +
    +
  • Status Code (3 digits)
  • +
  • Short Description
  • +
  • Pointer to specification text
  • +
+ + Values to be added to the HTTP status code namespace require IETF Review + (see ). + +
+
+ Considerations for New Status Codes + + When it is necessary to express semantics for a response that are not + defined by current status codes, a new status code can be registered. + Status codes are generic; they are potentially applicable to any resource, + not just one particular media type, kind of resource, or application of + HTTP. As such, it is preferred that new status codes be registered in a + document that isn't specific to a single application. + + + New status codes are required to fall under one of the categories + defined in . To allow existing parsers to + process the response message, new status codes cannot disallow content, + although they can mandate a zero-length content. + + + Proposals for new status codes that are not yet widely deployed ought to + avoid allocating a specific number for the code until there is clear + consensus that it will be registered; instead, early drafts can use a + notation such as "4NN", or "3N0" .. "3N9", to indicate the class + of the proposed status code(s) without consuming a number prematurely. + + + The definition of a new status code ought to explain the request + conditions that would cause a response containing that status code (e.g., + combinations of request header fields and/or method(s)) along with any + dependencies on response header fields (e.g., what fields are required, + what fields can modify the semantics, and what field semantics are + further refined when used with the new status code). + + + By default, a status code applies only to the request corresponding to the + response it occurs within. If a status code applies to a larger scope of + applicability -- for example, all requests to the resource in question or + all requests to a server -- this must be explicitly specified. When doing + so, it should be noted that not all clients can be expected to + consistently apply a larger scope because they might not understand the + new status code. + + + The definition of a new final status code ought to specify whether or not it + is heuristically cacheable. Note that any response with a final status code + can be cached if the response has explicit freshness information. A status + code defined as heuristically cacheable is allowed to be cached without + explicit freshness information. + Likewise, the definition of a status code can place + constraints upon cache behavior if the must-understand cache + directive is used. See for more information. + + + Finally, the definition of a new status code ought to indicate whether the + content has any implied association with an identified resource (). + +
+
+
+ Field Extensibility + + HTTP's most widely used extensibility point is the definition of new header and + trailer fields. + + + New fields can be defined such that, when they are understood by a + recipient, they override or enhance the interpretation of previously + defined fields, define preconditions on request evaluation, or + refine the meaning of responses. + + + However, defining a field doesn't guarantee its deployment or recognition + by recipients. Most fields are designed with the expectation that a recipient + can safely ignore (but forward downstream) any field not recognized. + In other cases, the sender's ability to understand a given field might be + indicated by its prior communication, perhaps in the protocol version + or fields that it sent in prior messages, or its use of a specific media type. + Likewise, direct inspection of support might be possible through an + OPTIONS request or by interacting with a defined well-known URI + if such inspection is defined along with + the field being introduced. + +
+ Field Name Registry + + The "Hypertext Transfer Protocol (HTTP) Field Name Registry" defines the + namespace for HTTP field names. + + + Any party can request registration of an HTTP field. See for considerations to take + into account when creating a new HTTP field. + + + The "Hypertext Transfer Protocol (HTTP) Field Name Registry" is located at + . + Registration requests can be made by following the instructions located + there or by sending an email to the "ietf-http-wg@w3.org" mailing list. + + + Field names are registered on the advice of a designated expert + (appointed by the IESG or their delegate). Fields with the status + 'permanent' are Specification Required + (). + + + Registration requests consist of the following information: + +
+
Field name:
+
+ The requested field name. It MUST conform to the + field-name syntax defined in , and it SHOULD be + restricted to just letters, digits, and hyphen ('-') + characters, with the first character being a letter. +
+
Status:
+
+ "permanent", "provisional", "deprecated", or "obsoleted". +
+
Specification document(s):
+
+ Reference to the document that specifies + the field, preferably including a URI that can be used to retrieve + a copy of the document. Optional but encouraged for provisional registrations. + An indication of the relevant section(s) can also be included, but is not required. +
+
+ + And optionally: + +
+
Comments:
+
+ Additional information, such as about reserved entries. +
+
+ + The expert(s) can define additional fields to be collected in the + registry, in consultation with the community. + + + Standards-defined names have a status of "permanent". Other names can also + be registered as permanent if the expert(s) finds that they are in use, in + consultation with the community. Other names should be registered as + "provisional". + + + Provisional entries can be removed by the expert(s) if -- in consultation + with the community -- the expert(s) find that they are not in use. The + expert(s) can change a provisional entry's status to permanent at any time. + + + Note that names can be registered by third parties (including the + expert(s)) if the expert(s) determines that an unregistered name is widely + deployed and not likely to be registered in a timely manner otherwise. + +
+
+ Considerations for New Fields + + HTTP header and trailer fields are a widely used extension point for the protocol. + While they can be used in an ad hoc fashion, fields that are intended for + wider use need to be carefully documented to ensure interoperability. + + + In particular, authors of specifications defining new fields are advised to consider + and, where appropriate, document the following aspects: + +
    +
  • Under what conditions the field can be used; e.g., only in + responses or requests, in all messages, only on responses to a + particular request method, etc.
  • +
  • Whether the field semantics are further refined by their context, + such as their use with certain request methods or status codes.
  • +
  • The scope of applicability for the information conveyed. + By default, fields apply only to the message they are + associated with, but some response fields are designed to apply to all + representations of a resource, the resource itself, or an even broader + scope. Specifications that expand the scope of a response field will + need to carefully consider issues such as content negotiation, the time + period of applicability, and (in some cases) multi-tenant server + deployments.
  • +
  • Under what conditions intermediaries are allowed to insert, + delete, or modify the field's value.
  • +
  • If the field is allowable in trailers; by + default, it will not be (see ).
  • +
  • Whether it is appropriate or even required to list the field name in the + Connection header field (i.e., if the field is to + be hop-by-hop; see ).
  • +
  • Whether the field introduces any additional security considerations, such + as disclosure of privacy-related data.
  • +
+ + Request header fields have additional considerations that need to be documented + if the default behavior is not appropriate: + +
    +
  • If it is appropriate to list the field name in a + Vary response header field (e.g., when the request header + field is used by an origin server's content selection algorithm; see + ).
  • +
  • If the field is intended to be stored when received in a PUT + request (see ).
  • +
  • If the field ought to be removed when automatically redirecting a + request due to security concerns (see ).
  • +
+
+ Considerations for New Field Names + + Authors of specifications defining new fields are advised to choose a short + but descriptive field name. Short names avoid needless data transmission; + descriptive names avoid confusion and "squatting" on names that might have + broader uses. + + + To that end, limited-use fields (such as a header confined to a single + application or use case) are encouraged to use a name that includes that use + (or an abbreviation) as a prefix; for example, if the Foo Application needs + a Description field, it might use "Foo-Desc"; "Description" is too generic, + and "Foo-Description" is needlessly long. + + + While the field-name syntax is defined to allow any token character, in + practice some implementations place limits on the characters they accept + in field-names. To be interoperable, new field names SHOULD constrain + themselves to alphanumeric characters, "-", and ".", and SHOULD + begin with a letter. For example, the underscore + ("_") character can be problematic when passed through non-HTTP + gateway interfaces (see ). + + + Field names ought not be prefixed with "X-"; see + for further information. + + + Other prefixes are sometimes used in HTTP field names; for example, + "Accept-" is used in many content negotiation headers, and "Content-" is used + as explained in . These prefixes are + only an aid to recognizing the purpose of a field and do not + trigger automatic processing. + +
+
+ Considerations for New Field Values + + A major task in the definition of a new HTTP field is the specification of + the field value syntax: what senders should generate, and how recipients + should infer semantics from what is received. + + + Authors are encouraged (but not required) to use either the ABNF rules in + this specification or those in to define the syntax + of new field values. + + + Authors are advised to carefully consider how the combination of multiple + field lines will impact them (see ). Because + senders might erroneously send multiple values, and both intermediaries + and HTTP libraries can perform combination automatically, this applies to + all field values -- even when only a single value is anticipated. + + + Therefore, authors are advised to delimit or encode values that contain + commas (e.g., with the quoted-string rule of + , the String data type of + , or a field-specific encoding). + This ensures that commas within field data are not confused + with the commas that delimit a list value. + + + For example, the Content-Type field value only allows commas + inside quoted strings, which can be reliably parsed even when multiple + values are present. The Location field value provides a + counter-example that should not be emulated: because URIs can include + commas, it is not possible to reliably distinguish between a single value + that includes a comma from two values. + + + Authors of fields with a singleton value (see ) are additionally advised to document how to treat + messages where the multiple members are present (a sensible default would + be to ignore the field, but this might not always be the right choice). + +
+
+
+
+ Authentication Scheme Extensibility +
+ Authentication Scheme Registry + + The "Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry" + defines the namespace for the authentication schemes in challenges and + credentials. It is maintained + at . + + + Registrations MUST include the following fields: + +
    +
  • Authentication Scheme Name
  • +
  • Pointer to specification text
  • +
  • Notes (optional)
  • +
+ + Values to be added to this namespace require IETF Review + (see ). + +
+
+ Considerations for New Authentication Schemes + + There are certain aspects of the HTTP Authentication framework that put + constraints on how new authentication schemes can work: + +
    +
  • + + HTTP authentication is presumed to be stateless: all of the information + necessary to authenticate a request MUST be provided in the request, + rather than be dependent on the server remembering prior requests. + Authentication based on, or bound to, the underlying connection is + outside the scope of this specification and inherently flawed unless + steps are taken to ensure that the connection cannot be used by any + party other than the authenticated user + (see ). + +
  • +
  • + + The authentication parameter "realm" is reserved for defining protection + spaces as described in . New schemes + MUST NOT use it in a way incompatible with that definition. + +
  • +
  • + + The "token68" notation was introduced for compatibility with existing + authentication schemes and can only be used once per challenge or credential. + Thus, new schemes ought to use the auth-param syntax instead, because + otherwise future extensions will be impossible. + +
  • +
  • + + The parsing of challenges and credentials is defined by this specification + and cannot be modified by new authentication schemes. When the auth-param + syntax is used, all parameters ought to support both token and + quoted-string syntax, and syntactical constraints ought to be defined on + the field value after parsing (i.e., quoted-string processing). This is + necessary so that recipients can use a generic parser that applies to + all authentication schemes. + + + Note: The fact that the value syntax for the "realm" parameter + is restricted to quoted-string was a bad design choice not to be repeated + for new parameters. + +
  • +
  • + + Definitions of new schemes ought to define the treatment of unknown + extension parameters. In general, a "must-ignore" rule is preferable + to a "must-understand" rule, because otherwise it will be hard to introduce + new parameters in the presence of legacy recipients. Furthermore, + it's good to describe the policy for defining new parameters (such + as "update the specification" or "use this registry"). + +
  • +
  • + + Authentication schemes need to document whether they are usable in + origin-server authentication (i.e., using WWW-Authenticate), + and/or proxy authentication (i.e., using Proxy-Authenticate). + +
  • +
  • + + The credentials carried in an Authorization header field are specific to + the user agent and, therefore, have the same effect on HTTP caches as the + "private" cache response directive (), + within the scope of the request in which they appear. + + + Therefore, new authentication schemes that choose not to carry + credentials in the Authorization header field (e.g., using a newly defined + header field) will need to explicitly disallow caching, by mandating the use of + cache response directives (e.g., "private"). + +
  • +
  • + + Schemes using Authentication-Info, Proxy-Authentication-Info, + or any other authentication related response header field need to + consider and document the related security considerations (see + ). + +
  • +
+
+
+
+ Range Unit Extensibility +
+ Range Unit Registry + + The "HTTP Range Unit Registry" defines the namespace for the range + unit names and refers to their corresponding specifications. + It is maintained at + . + + + Registration of an HTTP Range Unit MUST include the following fields: + +
    +
  • Name
  • +
  • Description
  • +
  • Pointer to specification text
  • +
+ + Values to be added to this namespace require IETF Review + (see ). + +
+
+ Considerations for New Range Units + + Other range units, such as format-specific boundaries like pages, + sections, records, rows, or time, are potentially usable in HTTP for + application-specific purposes, but are not commonly used in practice. + Implementors of alternative range units ought to consider how they would + work with content codings and general-purpose intermediaries. + +
+
+
+ Content Coding Extensibility +
+ Content Coding Registry + + The "HTTP Content Coding Registry", maintained by + IANA at , + registers content-coding names. + + + Content coding registrations MUST include the following fields: + +
    +
  • Name
  • +
  • Description
  • +
  • Pointer to specification text
  • +
+ + Names of content codings MUST NOT overlap with names of transfer codings + (per the "HTTP Transfer Coding Registry" located at + ) unless + the encoding transformation is + identical (as is the case for the compression codings defined in + ). + + + Values to be added to this namespace require IETF Review + (see ) and MUST + conform to the purpose of content coding defined in + . + +
+
+ Considerations for New Content Codings + + New content codings ought to be self-descriptive whenever possible, with + optional parameters discoverable within the coding format itself, rather + than rely on external metadata that might be lost during transit. + +
+
+
+ Upgrade Token Registry + + The "Hypertext Transfer Protocol (HTTP) Upgrade Token Registry" defines + the namespace for protocol-name tokens used to identify protocols in the + Upgrade header field. The registry is maintained at + . + + + Each registered protocol name is associated with contact information + and an optional set of specifications that details how the connection + will be processed after it has been upgraded. + + + Registrations happen on a "First Come First Served" basis (see + ) and are subject to the + following rules: + +
    +
  1. A protocol-name token, once registered, stays registered forever.
  2. +
  3. A protocol-name token is case-insensitive and registered with the + preferred case to be generated by senders.
  4. +
  5. The registration MUST name a responsible party for the + registration.
  6. +
  7. The registration MUST name a point of contact.
  8. +
  9. The registration MAY name a set of specifications associated with + that token. Such specifications need not be publicly available.
  10. +
  11. The registration SHOULD name a set of expected "protocol-version" + tokens associated with that token at the time of registration.
  12. +
  13. The responsible party MAY change the registration at any time. + The IANA will keep a record of all such changes, and make them + available upon request.
  14. +
  15. The IESG MAY reassign responsibility for a protocol token. + This will normally only be used in the case when a + responsible party cannot be contacted.
  16. +
+
+
+
+ Security Considerations + + This section is meant to inform developers, information providers, and + users of known security concerns relevant to HTTP semantics and its + use for transferring information over the Internet. Considerations related + to caching are discussed in , + and considerations related to HTTP/1.1 message syntax and parsing are + discussed in . + + + The list of considerations below is not exhaustive. Most security concerns + related to HTTP semantics are about securing server-side applications (code + behind the HTTP interface), securing user agent processing of content + received via HTTP, or secure use of the Internet in general, rather than + security of the protocol. The security considerations for URIs, which + are fundamental to HTTP operation, are discussed in + . Various organizations maintain + topical information and links to current research on Web application + security (e.g., ). + +
+ Establishing Authority + + + + HTTP relies on the notion of an "authoritative response": a + response that has been determined by (or at the direction of) the origin + server identified within the target URI to be the most appropriate response + for that request given the state of the target resource at the time of + response message origination. + + + When a registered name is used in the authority component, the "http" URI + scheme () relies on the user's local name + resolution service to determine where it can find authoritative responses. + This means that any attack on a user's network host table, cached names, + or name resolution libraries becomes an avenue for attack on establishing + authority for "http" URIs. Likewise, the user's choice of server for + Domain Name Service (DNS), and the hierarchy of servers from which it + obtains resolution results, could impact the authenticity of address + mappings; DNS Security Extensions (DNSSEC, ) are + one way to improve authenticity, as are the various mechanisms for making + DNS requests over more secure transfer protocols. + + + Furthermore, after an IP address is obtained, establishing authority for + an "http" URI is vulnerable to attacks on Internet Protocol routing. + + + The "https" scheme () is intended to prevent + (or at least reveal) many of these potential attacks on establishing + authority, provided that the negotiated connection is secured and + the client properly verifies that the communicating server's identity + matches the target URI's authority component + (). Correctly implementing such verification + can be difficult (see ). + + + Authority for a given origin server can be delegated through protocol + extensions; for example, . Likewise, the set of + servers for which a connection is considered authoritative can be changed + with a protocol extension like . + + + Providing a response from a non-authoritative source, such as a shared + proxy cache, is often useful to improve performance and availability, but + only to the extent that the source can be trusted or the distrusted + response can be safely used. + + + Unfortunately, communicating authority to users can be difficult. + For example, "phishing" is an attack on the user's perception + of authority, where that perception can be misled by presenting similar + branding in hypertext, possibly aided by userinfo obfuscating the authority + component (see ). + User agents can reduce the impact of phishing attacks by enabling users to + easily inspect a target URI prior to making an action, by prominently + distinguishing (or rejecting) userinfo when present, and by not sending + stored credentials and cookies when the referring document is from an + unknown or untrusted source. + +
+
+ Risks of Intermediaries + + HTTP intermediaries are inherently situated for on-path attacks. + Compromise of + the systems on which the intermediaries run can result in serious security + and privacy problems. Intermediaries might have access to security-related + information, personal information about individual users and + organizations, and proprietary information belonging to users and + content providers. A compromised intermediary, or an intermediary + implemented or configured without regard to security and privacy + considerations, might be used in the commission of a wide range of + potential attacks. + + + Intermediaries that contain a shared cache are especially vulnerable + to cache poisoning attacks, as described in . + + + Implementers need to consider the privacy and security + implications of their design and coding decisions, and of the + configuration options they provide to operators (especially the + default configuration). + + + Intermediaries are no more trustworthy than the people and policies + under which they operate; HTTP cannot solve this problem. + +
+
+ Attacks Based on File and Path Names + + Origin servers frequently make use of their local file system to manage the + mapping from target URI to resource representations. + Most file systems are not designed to protect against malicious file + or path names. Therefore, an origin server needs to avoid accessing + names that have a special significance to the system when mapping the + target resource to files, folders, or directories. + + + For example, UNIX, Microsoft Windows, and other operating systems use ".." + as a path component to indicate a directory level above the current one, + and they use specially named paths or file names to send data to system devices. + Similar naming conventions might exist within other types of storage + systems. Likewise, local storage systems have an annoying tendency to + prefer user-friendliness over security when handling invalid or unexpected + characters, recomposition of decomposed characters, and case-normalization + of case-insensitive names. + + + Attacks based on such special names tend to focus on either denial-of-service + (e.g., telling the server to read from a COM port) or disclosure + of configuration and source files that are not meant to be served. + +
+
+ Attacks Based on Command, Code, or Query Injection + + Origin servers often use parameters within the URI as a + means of identifying system services, selecting database entries, or + choosing a data source. However, data received in a request cannot be + trusted. An attacker could construct any of the request data elements + (method, target URI, header fields, or content) to contain data that might + be misinterpreted as a command, code, or query when passed through a + command invocation, language interpreter, or database interface. + + + For example, SQL injection is a common attack wherein additional query + language is inserted within some part of the target URI or header + fields (e.g., Host, Referer, etc.). + If the received data is used directly within a SELECT statement, the + query language might be interpreted as a database command instead of a + simple string value. This type of implementation vulnerability is extremely + common, in spite of being easy to prevent. + + + In general, resource implementations ought to avoid use of request data + in contexts that are processed or interpreted as instructions. Parameters + ought to be compared to fixed strings and acted upon as a result of that + comparison, rather than passed through an interface that is not prepared + for untrusted data. Received data that isn't based on fixed parameters + ought to be carefully filtered or encoded to avoid being misinterpreted. + + + Similar considerations apply to request data when it is stored and later + processed, such as within log files, monitoring tools, or when included + within a data format that allows embedded scripts. + +
+
+ Attacks via Protocol Element Length + + Because HTTP uses mostly textual, character-delimited fields, parsers are + often vulnerable to attacks based on sending very long (or very slow) + streams of data, particularly where an implementation is expecting a + protocol element with no predefined length + (). + + + To promote interoperability, specific recommendations are made for minimum + size limits on fields (). These are + minimum recommendations, chosen to be supportable even by implementations + with limited resources; it is expected that most implementations will + choose substantially higher limits. + + + A server can reject a message that + has a target URI that is too long () or request content + that is too large (). Additional status codes related to + capacity limits have been defined by extensions to HTTP + . + + + Recipients ought to carefully limit the extent to which they process other + protocol elements, including (but not limited to) request methods, response + status phrases, field names, numeric values, and chunk lengths. + Failure to limit such processing can result in arbitrary code execution due to + buffer or arithmetic + overflows, and increased vulnerability to denial-of-service attacks. + +
+
+ Attacks Using Shared-Dictionary Compression + + Some attacks on encrypted protocols use the differences in size created by + dynamic compression to reveal confidential information; for example, . These attacks rely on creating a redundancy between + attacker-controlled content and the confidential information, such that a + dynamic compression algorithm using the same dictionary for both content + will compress more efficiently when the attacker-controlled content matches + parts of the confidential content. + + + HTTP messages can be compressed in a number of ways, including using TLS + compression, content codings, transfer codings, and other extension or + version-specific mechanisms. + + + The most effective mitigation for this risk is to disable compression on + sensitive data, or to strictly separate sensitive data from attacker-controlled + data so that they cannot share the same compression dictionary. With + careful design, a compression scheme can be designed in a way that is not + considered exploitable in limited use cases, such as HPACK (). + +
+
+ Disclosure of Personal Information + + Clients are often privy to large amounts of personal information, + including both information provided by the user to interact with resources + (e.g., the user's name, location, mail address, passwords, encryption + keys, etc.) and information about the user's browsing activity over + time (e.g., history, bookmarks, etc.). Implementations need to + prevent unintentional disclosure of personal information. + +
+
+ Privacy of Server Log Information + + A server is in the position to save personal data about a user's requests + over time, which might identify their reading patterns or subjects of + interest. In particular, log information gathered at an intermediary + often contains a history of user agent interaction, across a multitude + of sites, that can be traced to individual users. + + + HTTP log information is confidential in nature; its handling is often + constrained by laws and regulations. Log information needs to be securely + stored and appropriate guidelines followed for its analysis. + Anonymization of personal information within individual entries helps, + but it is generally not sufficient to prevent real log traces from being + re-identified based on correlation with other access characteristics. + As such, access traces that are keyed to a specific client are unsafe to + publish even if the key is pseudonymous. + + + To minimize the risk of theft or accidental publication, log information + ought to be purged of personally identifiable information, including + user identifiers, IP addresses, and user-provided query parameters, + as soon as that information is no longer necessary to support operational + needs for security, auditing, or fraud control. + +
+
+ Disclosure of Sensitive Information in URIs + + URIs are intended to be shared, not secured, even when they identify secure + resources. URIs are often shown on displays, added to templates when a page + is printed, and stored in a variety of unprotected bookmark lists. + Many servers, proxies, and user agents log or display the target URI + in places where it might be visible to third parties. + It is therefore unwise to include information within a URI that + is sensitive, personally identifiable, or a risk to disclose. + + + When an application uses client-side mechanisms to construct a target URI + out of user-provided information, such as the query fields of a form using + GET, potentially sensitive data might be provided that would not be + appropriate for disclosure within a URI. POST is often preferred in such + cases because it usually doesn't construct a URI; instead, POST of a form + transmits the potentially sensitive data in the request content. However, this + hinders caching and uses an unsafe method for what would otherwise be a safe + request. Alternative workarounds include transforming the user-provided data + prior to constructing the URI or filtering the data to only include common + values that are not sensitive. Likewise, redirecting the result of a query + to a different (server-generated) URI can remove potentially sensitive data + from later links and provide a cacheable response for later reuse. + + + Since the Referer header field tells a target site about the + context that resulted in a request, it has the potential to reveal + information about the user's immediate browsing history and any personal + information that might be found in the referring resource's URI. + Limitations on the Referer header field are described in to + address some of its security considerations. + +
+
+ Application Handling of Field Names + + Servers often use non-HTTP gateway interfaces and frameworks to process a received + request and produce content for the response. For historical reasons, such interfaces + often pass received field names as external variable names, using a name mapping + suitable for environment variables. + + + For example, the Common Gateway Interface (CGI) mapping of protocol-specific + meta-variables, defined by , + is applied to received header fields that do not correspond to one of CGI's + standard variables; the mapping consists of prepending "HTTP_" to each name + and changing all instances of hyphen ("-") to underscore ("_"). This same mapping + has been inherited by many other application frameworks in order to simplify + moving applications from one platform to the next. + + + In CGI, a received Content-Length field would be passed + as the meta-variable "CONTENT_LENGTH" with a string value matching the + received field's value. In contrast, a received "Content_Length" header field would + be passed as the protocol-specific meta-variable "HTTP_CONTENT_LENGTH", + which might lead to some confusion if an application mistakenly reads the + protocol-specific meta-variable instead of the default one. (This historical practice + is why discourages the creation + of new field names that contain an underscore.) + + + Unfortunately, mapping field names to different interface names can lead to + security vulnerabilities if the mapping is incomplete or ambiguous. For example, + if an attacker were to send a field named "Transfer_Encoding", a naive interface + might map that to the same variable name as the "Transfer-Encoding" field, resulting + in a potential request smuggling vulnerability (). + + + To mitigate the associated risks, implementations that perform such + mappings are advised to make the mapping unambiguous and complete + for the full range of potential octets received as a name (including those + that are discouraged or forbidden by the HTTP grammar). + For example, a field with an unusual name character might + result in the request being blocked, the specific field being removed, + or the name being passed with a different prefix to distinguish it from + other fields. + +
+
+ Disclosure of Fragment after Redirects + + Although fragment identifiers used within URI references are not sent + in requests, implementers ought to be aware that they will be visible to + the user agent and any extensions or scripts running as a result of the + response. In particular, when a redirect occurs and the original request's + fragment identifier is inherited by the new reference in + Location (), this might + have the effect of disclosing one site's fragment to another site. + If the first site uses personal information in fragments, it ought to + ensure that redirects to other sites include a (possibly empty) fragment + component in order to block that inheritance. + +
+
+ Disclosure of Product Information + + The User-Agent (), + Via (), and + Server () header fields often + reveal information about the respective sender's software systems. + In theory, this can make it easier for an attacker to exploit known + security holes; in practice, attackers tend to try all potential holes + regardless of the apparent software versions being used. + + + Proxies that serve as a portal through a network firewall ought to take + special precautions regarding the transfer of header information that might + identify hosts behind the firewall. The Via header field + allows intermediaries to replace sensitive machine names with pseudonyms. + +
+
+ Browser Fingerprinting + + Browser fingerprinting is a set of techniques for identifying a specific + user agent over time through its unique set of characteristics. These + characteristics might include information related to how it uses the underlying + transport protocol, + feature capabilities, and scripting environment, though of particular + interest here is the set of unique characteristics that might be + communicated via HTTP. Fingerprinting is considered a privacy concern + because it enables tracking of a user agent's behavior over time + () without + the corresponding controls that the user might have over other forms of + data collection (e.g., cookies). Many general-purpose user agents + (i.e., Web browsers) have taken steps to reduce their fingerprints. + + + There are a number of request header fields that might reveal information + to servers that is sufficiently unique to enable fingerprinting. + The From header field is the most obvious, though it is + expected that From will only be sent when self-identification is desired by + the user. Likewise, Cookie header fields are deliberately designed to + enable re-identification, so fingerprinting concerns only apply to + situations where cookies are disabled or restricted by the user agent's + configuration. + + + The User-Agent header field might contain enough information + to uniquely identify a specific device, usually when combined with other + characteristics, particularly if the user agent sends excessive details + about the user's system or extensions. However, the source of unique + information that is least expected by users is + proactive negotiation (), + including the Accept, Accept-Charset, + Accept-Encoding, and Accept-Language + header fields. + + + In addition to the fingerprinting concern, detailed use of the + Accept-Language header field can reveal information the + user might consider to be of a private nature. For example, understanding + a given language set might be strongly correlated to membership in a + particular ethnic group. + An approach that limits such loss of privacy would be for a user agent + to omit the sending of Accept-Language except for sites that have been + explicitly permitted, perhaps via interaction after detecting a Vary + header field that indicates language negotiation might be useful. + + + In environments where proxies are used to enhance privacy, user agents + ought to be conservative in sending proactive negotiation header fields. + General-purpose user agents that provide a high degree of header field + configurability ought to inform users about the loss of privacy that might + result if too much detail is provided. As an extreme privacy measure, + proxies could filter the proactive negotiation header fields in relayed + requests. + +
+
+ Validator Retention + + The validators defined by this specification are not intended to ensure + the validity of a representation, guard against malicious changes, or + detect on-path attacks. At best, they enable more efficient cache + updates and optimistic concurrent writes when all participants are behaving + nicely. At worst, the conditions will fail and the client will receive a + response that is no more harmful than an HTTP exchange without conditional + requests. + + + An entity tag can be abused in ways that create privacy risks. For example, + a site might deliberately construct a semantically invalid entity tag that + is unique to the user or user agent, send it in a cacheable response with a + long freshness time, and then read that entity tag in later conditional + requests as a means of re-identifying that user or user agent. Such an + identifying tag would become a persistent identifier for as long as the + user agent retained the original cache entry. User agents that cache + representations ought to ensure that the cache is cleared or replaced + whenever the user performs privacy-maintaining actions, such as clearing + stored cookies or changing to a private browsing mode. + +
+
+ Denial-of-Service Attacks Using Range + + Unconstrained multiple range requests are susceptible to denial-of-service + attacks because the effort required to request many overlapping ranges of + the same data is tiny compared to the time, memory, and bandwidth consumed + by attempting to serve the requested data in many parts. + Servers ought to ignore, coalesce, or reject egregious range requests, such + as requests for more than two overlapping ranges or for many small ranges + in a single set, particularly when the ranges are requested out of order + for no apparent reason. Multipart range requests are not designed to + support random access. + +
+
+ Authentication Considerations + + Everything about the topic of HTTP authentication is a security + consideration, so the list of considerations below is not exhaustive. + Furthermore, it is limited to security considerations regarding the + authentication framework, in general, rather than discussing all of the + potential considerations for specific authentication schemes (which ought + to be documented in the specifications that define those schemes). + Various organizations maintain topical information and links to current + research on Web application security (e.g., ), + including common pitfalls for implementing and using the authentication + schemes found in practice. + +
+ Confidentiality of Credentials + + The HTTP authentication framework does not define a single mechanism for + maintaining the confidentiality of credentials; instead, each + authentication scheme defines how the credentials are encoded prior to + transmission. While this provides flexibility for the development of future + authentication schemes, it is inadequate for the protection of existing + schemes that provide no confidentiality on their own, or that do not + sufficiently protect against replay attacks. Furthermore, if the server + expects credentials that are specific to each individual user, the exchange + of those credentials will have the effect of identifying that user even if + the content within credentials remains confidential. + + + HTTP depends on the security properties of the underlying transport- or + session-level connection to provide confidential transmission of + fields. Services that depend on individual user authentication require a + secured connection prior to exchanging credentials + (). + +
+
+ Credentials and Idle Clients + + Existing HTTP clients and user agents typically retain authentication + information indefinitely. HTTP does not provide a mechanism for the + origin server to direct clients to discard these cached credentials, since + the protocol has no awareness of how credentials are obtained or managed + by the user agent. The mechanisms for expiring or revoking credentials can + be specified as part of an authentication scheme definition. + + + Circumstances under which credential caching can interfere with the + application's security model include but are not limited to: + +
    +
  • Clients that have been idle for an extended period, following + which the server might wish to cause the client to re-prompt the + user for credentials.
  • +
  • Applications that include a session termination indication + (such as a "logout" or "commit" button on a page) after which + the server side of the application "knows" that there is no + further reason for the client to retain the credentials.
  • +
+ + User agents that cache credentials are encouraged to provide a readily + accessible mechanism for discarding cached credentials under user control. + +
+
+ Protection Spaces + + Authentication schemes that solely rely on the "realm" mechanism for + establishing a protection space will expose credentials to all resources on + an origin server. Clients that have successfully made authenticated requests + with a resource can use the same authentication credentials for other + resources on the same origin server. This makes it possible for a different + resource to harvest authentication credentials for other resources. + + + This is of particular concern when an origin server hosts resources for multiple + parties under the same origin (). + Possible mitigation strategies include restricting direct access to + authentication credentials (i.e., not making the content of the + Authorization request header field available), and separating protection + spaces by using a different host name (or port number) for each party. + +
+
+ Additional Response Fields + + Adding information to responses that are sent over an unencrypted + channel can affect security and privacy. The presence of the + Authentication-Info and Proxy-Authentication-Info + header fields alone indicates that HTTP authentication is in use. Additional + information could be exposed by the contents of the authentication-scheme + specific parameters; this will have to be considered in the definitions of these + schemes. + +
+
+
+
+ IANA Considerations + + The change controller for the following registrations is: + "IETF (iesg@ietf.org) - Internet Engineering Task Force". + +
+ URI Scheme Registration + + IANA has updated the "Uniform Resource Identifier (URI) Schemes" registry at + with the + permanent schemes listed in in . + +
+
+ Method Registration + + IANA has updated the "Hypertext Transfer Protocol (HTTP) Method Registry" at + with the + registration procedure of and the method + names summarized in the following table. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodSafeIdempotentSection
CONNECTnono + +
DELETEnoyes + +
GETyesyes + +
HEADyesyes + +
OPTIONSyesyes + +
POSTnono + +
PUTnoyes + +
TRACEyesyes + +
*nono + +
+ + + The method name "*" is reserved because using "*" as a method name would + conflict with its usage as a wildcard in some fields (e.g., + "Access-Control-Request-Method"). + +
+
+ Status Code Registration + + IANA has updated the "Hypertext Transfer Protocol (HTTP) Status Code Registry" + at with + the registration procedure of and the + status code values summarized in the following table. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescriptionSection
100Continue + +
101Switching Protocols + +
200OK + +
201Created + +
202Accepted + +
203Non-Authoritative Information + +
204No Content + +
205Reset Content + +
206Partial Content + +
300Multiple Choices + +
301Moved Permanently + +
302Found + +
303See Other + +
304Not Modified + +
305Use Proxy + +
306(Unused) + +
307Temporary Redirect + +
308Permanent Redirect + +
400Bad Request + +
401Unauthorized + +
402Payment Required + +
403Forbidden + +
404Not Found + +
405Method Not Allowed + +
406Not Acceptable + +
407Proxy Authentication Required + +
408Request Timeout + +
409Conflict + +
410Gone + +
411Length Required + +
412Precondition Failed + +
413Content Too Large + +
414URI Too Long + +
415Unsupported Media Type + +
416Range Not Satisfiable + +
417Expectation Failed + +
418(Unused) + +
421Misdirected Request + +
422Unprocessable Content + +
426Upgrade Required + +
500Internal Server Error + +
501Not Implemented + +
502Bad Gateway + +
503Service Unavailable + +
504Gateway Timeout + +
505HTTP Version Not Supported + +
+
+
+ Field Name Registration + + This specification updates the HTTP-related aspects of the existing + registration procedures for message header fields defined in . + It replaces the old procedures as they relate to HTTP by defining a new + registration procedure and moving HTTP field definitions into a separate + registry. + + + IANA has created a new registry titled "Hypertext Transfer Protocol (HTTP) + Field Name Registry" as outlined in . + + + IANA has moved all entries in the "Permanent Message Header Field + Names" and "Provisional Message Header Field Names" registries (see + ) with the + protocol 'http' to this registry and has applied the following changes: + +
    +
  1. The 'Applicable Protocol' field has been omitted.
  2. +
  3. Entries that had a status of 'standard', 'experimental', 'reserved', or + 'informational' have been made to have a status of 'permanent'.
  4. +
  5. Provisional entries without a status have been made to have a status of + 'provisional'.
  6. +
  7. Permanent entries without a status (after confirmation that the + registration document did not define one) have been made to have a status of + 'provisional'. The expert(s) can choose to update the entries' status if there is + evidence that another is more appropriate.
  8. +
+ + IANA has annotated the "Permanent Message Header Field + Names" and "Provisional Message Header Field Names" registries with the + following note to indicate that HTTP field name registrations have moved: + + + + IANA has updated the "Hypertext Transfer Protocol (HTTP) Field Name Registry" + with the field names listed in the following table. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Field NameStatusSectionComments
Acceptpermanent + + +
Accept-Charsetdeprecated + + +
Accept-Encodingpermanent + + +
Accept-Languagepermanent + + +
Accept-Rangespermanent + + +
Allowpermanent + + +
Authentication-Infopermanent + + +
Authorizationpermanent + + +
Connectionpermanent + + +
Content-Encodingpermanent + + +
Content-Languagepermanent + + +
Content-Lengthpermanent + + +
Content-Locationpermanent + + +
Content-Rangepermanent + + +
Content-Typepermanent + + +
Datepermanent + + +
ETagpermanent + + +
Expectpermanent + + +
Frompermanent + + +
Hostpermanent + + +
If-Matchpermanent + + +
If-Modified-Sincepermanent + + +
If-None-Matchpermanent + + +
If-Rangepermanent + + +
If-Unmodified-Sincepermanent + + +
Last-Modifiedpermanent + + +
Locationpermanent + + +
Max-Forwardspermanent + + +
Proxy-Authenticatepermanent + + +
Proxy-Authentication-Infopermanent + + +
Proxy-Authorizationpermanent + + +
Rangepermanent + + +
Refererpermanent + + +
Retry-Afterpermanent + + +
Serverpermanent + + +
TEpermanent + + +
Trailerpermanent + + +
Upgradepermanent + + +
User-Agentpermanent + + +
Varypermanent + + +
Viapermanent + + +
WWW-Authenticatepermanent + + +
*permanent + + (reserved)
+ + + + The field name "*" is reserved because using that name as + an HTTP header field might conflict with its special semantics in the + Vary header field (). + + + + + + + IANA has updated the "Content-MD5" entry in the new registry to have + a status of 'obsoleted' with references to + (for the definition + of the header field) and + (which removed the field + definition from the updated specification). + +
+
+ Authentication Scheme Registration + + IANA has updated the + "Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry" + at with + the registration procedure of . + No authentication schemes are defined in this document. + +
+
+ Content Coding Registration + + IANA has updated the "HTTP Content Coding Registry" at + + with the registration procedure of + and the content coding names summarized in the table below. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescriptionSection
compressUNIX "compress" data format + + +
deflate"deflate" compressed data () inside + the "zlib" data format () + +
gzipGZIP file format + + +
identityReserved + +
x-compressDeprecated (alias for compress) + +
x-gzipDeprecated (alias for gzip) + +
+
+
+ Range Unit Registration + + IANA has updated the "HTTP Range Unit Registry" at + + with the registration procedure of + and the range unit names summarized in the table below. + + + + + + + + + + + + + + + + + + + + + +
Range Unit NameDescriptionSection
bytesa range of octets + +
nonereserved as keyword to indicate range requests are not supported + +
+
+
+ Media Type Registration + + IANA has updated the "Media Types" registry at + + with the registration information in + + for the media type "multipart/byteranges". + + + IANA has updated the registry note about "q" parameters with + a link to of this document. + +
+
+ Port Registration + + IANA has updated the "Service Name and Transport Protocol Port Number + Registry" at + for the services on ports 80 and 443 that use UDP or TCP to: + +
    +
  1. use this document as "Reference", and
  2. +
  3. when currently unspecified, set "Assignee" to "IESG" and "Contact" to + "IETF_Chair".
  4. +
+
+
+ Upgrade Token Registration + + IANA has updated the + "Hypertext Transfer Protocol (HTTP) Upgrade Token Registry" at + + with the registration procedure described in + and the upgrade token names summarized in the following table. + + + + + + + + + + + + + + + + + + +
NameDescriptionExpected Version TokensSection
HTTPHypertext Transfer Protocolany DIGIT.DIGIT (e.g., "2.0") + +
+
+
+
+ + + + + + + References + + Normative References + + + HTTP Caching + + + + + + + + + + + + + + + + + + ZLIB Compressed Data Format Specification version 3.3 + + + + + + + + + This specification defines a lossless compressed data format. This memo provides information for the Internet community. This memo does not specify an Internet standard of any kind. + + + + + + + + DEFLATE Compressed Data Format Specification version 1.3 + + + + + + This specification defines a lossless compressed data format that compresses data using a combination of the LZ77 algorithm and Huffman coding, with efficiency comparable to the best currently available general-purpose compression methods. This memo provides information for the Internet community. This memo does not specify an Internet standard of any kind. + + + + + + + + GZIP file format specification version 4.3 + + + + + + This specification defines a lossless compressed data format that is compatible with the widely used GZIP utility. This memo provides information for the Internet community. This memo does not specify an Internet standard of any kind. + + + + + + + + Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types + + + + + + + + + This second document defines the general structure of the MIME media typing system and defines an initial set of media types. [STANDARDS-TRACK] + + + + + + + + Key words for use in RFCs to Indicate Requirement Levels + + + + + + In many standards track documents several words are used to signify the requirements in the specification. These words are often capitalized. This document defines these words as they should be interpreted in IETF documents. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements. + + + + + + + + + Matching of Language Tags + + + + + + + + + + + The Base16, Base32, and Base64 Data Encodings + + + + + + This document describes the commonly used base 64, base 32, and base 16 encoding schemes. It also discusses the use of line-feeds in encoded data, use of padding in encoded data, use of non-alphabet characters in encoded data, use of different encoding alphabets, and canonical encodings. [STANDARDS-TRACK] + + + + + + + + Augmented BNF for Syntax Specifications: ABNF + + + + + + + + + Internet technical specifications often need to define a formal syntax. Over the years, a modified version of Backus-Naur Form (BNF), called Augmented BNF (ABNF), has been popular among many Internet specifications. The current specification documents ABNF. It balances compactness and simplicity with reasonable representational power. The differences between standard BNF and ABNF involve naming rules, repetition, alternatives, order-independence, and value ranges. This specification also supplies additional rule definitions and encoding for a core lexical analyzer of the type common to several Internet specifications. [STANDARDS-TRACK] + + + + + + + + + Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile + + + + + + + + + + + + + + + + + + + + + This memo profiles the X.509 v3 certificate and X.509 v2 certificate revocation list (CRL) for use in the Internet. An overview of this approach and model is provided as an introduction. The X.509 v3 certificate format is described in detail, with additional information regarding the format and semantics of Internet name forms. Standard certificate extensions are described and two Internet-specific extensions are defined. A set of required certificate extensions is specified. The X.509 v2 CRL format is described in detail along with standard and Internet-specific extensions. An algorithm for X.509 certification path validation is described. An ASN.1 module and examples are provided in the appendices. [STANDARDS-TRACK] + + + + + + + + Internet Message Format + + + + + + This document specifies the Internet Message Format (IMF), a syntax for text messages that are sent between computer users, within the framework of "electronic mail" messages. This specification is a revision of Request For Comments (RFC) 2822, which itself superseded Request For Comments (RFC) 822, "Standard for the Format of ARPA Internet Text Messages", updating it to reflect current practice and incorporating incremental changes that were specified in other RFCs. [STANDARDS-TRACK] + + + + + + + + Tags for Identifying Languages + + + + + + + + + This document describes the structure, content, construction, and semantics of language tags for use in cases where it is desirable to indicate the language used in an information object. It also describes how to register values for use in language tags and the creation of user-defined extensions for private interchange. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements. + + + + + + + + + Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS) + + + + + + + + + Many application technologies enable secure communication between two entities by means of Internet Public Key Infrastructure Using X.509 (PKIX) certificates in the context of Transport Layer Security (TLS). This document specifies procedures for representing and verifying the identity of application services in such interactions. [STANDARDS-TRACK] + + + + + + + + Terminology Used in Internationalization in the IETF + + + + + + + + + This document provides a list of terms used in the IETF when discussing internationalization. The purpose is to help frame discussions of internationalization in the various areas of the IETF and to help introduce the main concepts to IETF participants. This memo documents an Internet Best Current Practice. + + + + + + + + + Case-Sensitive String Support in ABNF + + + + + + This document extends the base definition of ABNF (Augmented Backus-Naur Form) to include a way to specify US-ASCII string literals that are matched in a case-sensitive manner. + + + + + + + + Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words + + + + + + RFC 2119 specifies common key words that may be used in protocol specifications. This document aims to reduce the ambiguity by clarifying that only UPPERCASE usage of the key words have the defined special meanings. + + + + + + + + + Transmission Control Protocol + + + + + + + + + + The Transport Layer Security (TLS) Protocol Version 1.3 + + + + + + + + + Uniform Resource Identifier (URI): Generic Syntax + + + + + + + + + + + + Coded Character Set -- 7-bit American Standard Code for Information Interchange + + American National Standards Institute + + + + + + + + A Technique for High-Performance Data Compression + + + + IEEE Computer 17(6) + + + + + Informative References + + + HTTP Alternative Services + + + + + + + + + + + + Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures + + + + + + + + + This document specifies IANA registration procedures for MIME external body access types and content-transfer-encodings. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements. + + + + + + + + + Media Type Specifications and Registration Procedures + + + + + + + + + + + + This document defines procedures for the specification and registration of media types for use in HTTP, MIME, and other Internet protocols. This memo documents an Internet Best Current Practice. + + + + + + + + + + + Deprecating the "X-" Prefix and Similar Constructs in Application Protocols + + + + + + + + + + + + Historically, designers and implementers of application protocols have often distinguished between standardized and unstandardized parameters by prefixing the names of unstandardized parameters with the string "X-" or similar constructs. In practice, that convention causes more problems than it solves. Therefore, this document deprecates the convention for newly defined parameters with textual (as opposed to numerical) names in application protocols. This memo documents an Internet Best Current Practice. + + + + + + + + + + + Guidelines and Registration Procedures for URI Schemes + + + + + + + + + + + + This document updates the guidelines and recommendations, as well as the IANA registration processes, for the definition of Uniform Resource Identifier (URI) schemes. It obsoletes RFC 4395. + + + + + + + + + + BREACH: Reviving the CRIME Attack + + + + + + + + + A Survey on Web Tracking: Mechanisms, Implications, and Defenses + + + + + + + + In Proceedings of the IEEE 105(8) + + + + HTTP State Management Mechanism + + + + + + + + + Erratum ID 1912 + + RFC Errata + + + + RFC 2978 + + + + Erratum ID 5433 + + RFC Errata + + + + RFC 2978 + + + + The Most Dangerous Code in the World: Validating SSL Certificates in Non-Browser Software + + + + + + + + + + In Proceedings of the 2012 ACM Conference on Computer and Communications Security (CCS '12), pp. 38-49 + + + + HPACK: Header Compression for HTTP/2 + + + + + + + + + + Hypertext Transfer Protocol -- HTTP/1.0 + + + + + + + + + + + HTTP/1.1 + + Adobe + + + Fastly + + + greenbytes GmbH + + + + + + + + + + HTTP/2 + + + + + + + + + + HTTP/3 + + + + + + + + + Information technology -- 8-bit single-byte coded graphic character sets -- Part 1: Latin alphabet No. 1 + + International Organization for Standardization + + + + + + + + HTTP Cookies: Standards, Privacy, and Politics + + + + ACM Transactions on Internet Technology 1(2) + + + + The Open Web Application Security Project + + + + + + + + + Architectural Styles and the Design of Network-based Software Architectures + + + + Doctoral Dissertation, University of California, Irvine + + + + Classical versus Transparent IP Proxies + + + + + + This document explains "classical" and "transparent" proxy techniques and attempts to provide rules to help determine when each proxy system may be used without causing problems. This memo provides information for the Internet community. This memo does not specify an Internet standard of any kind. + + + + + + + + MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text + + + + + + This particular document is the third document in the series. It describes extensions to RFC 822 to allow non-US-ASCII text data in Internet mail header fields. [STANDARDS-TRACK] + + + + + + + + Hypertext Transfer Protocol -- HTTP/1.1 + + + + + + + + + + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. [STANDARDS-TRACK] + + + + + + + + Use and Interpretation of HTTP Version Numbers + + + + + + + + + + + + + + + HTTP request and response messages include an HTTP protocol version number. Some confusion exists concerning the proper use and interpretation of HTTP version numbers, and concerning interoperability of HTTP implementations of different protocol versions. This document is an attempt to clarify the situation. This memo provides information for the Internet community. This memo does not specify an Internet standard of any kind. + + + + + + + + Transparent Content Negotiation in HTTP + + + + + + + + + HTTP allows web site authors to put multiple versions of the same information under a single URL. Transparent content negotiation is an extensible negotiation mechanism, layered on top of HTTP, for automatically selecting the best version when the URL is accessed. This enables the smooth deployment of new web data formats and markup tags. This memo defines an Experimental Protocol for the Internet community. It does not specify an Internet standard of any kind. Discussion and suggestions for improvement are requested. + + + + + + + + Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) + + + + + + + + + MIME Encapsulation of Aggregate Documents, such as HTML (MHTML) + + + + + + + + + + + + This document a) defines the use of a MIME multipart/related structure to aggregate a text/html root resource and the subsidiary resources it references, and b) specifies a MIME content-header (Content-Location) that allow URIs in a multipart/related text/html root body part to reference subsidiary resources in other body parts of the same multipart/related structure. [STANDARDS-TRACK] + + + + + + + + Hypertext Transfer Protocol -- HTTP/1.1 + + + + + + + + + + + + + + + + + + + + + + + + HTTP has been in use by the World-Wide Web global information initiative since 1990. This specification defines the protocol referred to as "HTTP/1.1", and is an update to RFC 2068. [STANDARDS-TRACK] + + + + + + + + HTTP Authentication: Basic and Digest Access Authentication + + + + + + + + + + + + + + + + + + + + + + + + This document provides the specification for HTTP's authentication framework, the original Basic authentication scheme and a scheme based on cryptographic hashes, referred to as "Digest Access Authentication". [STANDARDS-TRACK] + + + + + + + + An HTTP Extension Framework + + + + + + + + + + + + A wide range of applications have proposed various extensions of the HTTP protocol. Current efforts span an enormous range, including distributed authoring, collaboration, printing, and remote procedure call mechanisms. These HTTP extensions are not coordinated, since there has been no standard framework for defining extensions and thus, separation of concerns. This document describes a generic extension mechanism for HTTP, which is designed to address the tension between private agreement and public specification and to accommodate extension of applications using HTTP clients, servers, and proxies. The proposal associates each extension with a globally unique identifier, and uses HTTP header fields to carry the extension identifier and related information between the parties involved in the extended communication. + + + + + + + + HTTP Over TLS + + + + + + This memo describes how to use Transport Layer Security (TLS) to secure Hypertext Transfer Protocol (HTTP) connections over the Internet. This memo provides information for the Internet community. + + + + + + + + IANA Charset Registration Procedures + + + + + + + + + Multipurpose Internet Mail Extensions (MIME) and various other Internet protocols are capable of using many different charsets. This in turn means that the ability to label different charsets is essential. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements. + + + + + + + + + Internet Web Replication and Caching Taxonomy + + + + + + + + + + + + This memo specifies standard terminology and the taxonomy of web replication and caching infrastructure as deployed today. It introduces standard concepts, and protocols used today within this application domain. This memo provides information for the Internet community. + + + + + + + + Registration Procedures for Message Header Fields + + + + + + + + + + + + The Common Gateway Interface (CGI) Version 1.1 + + + + + + + + + + DNS Security Introduction and Requirements + + + + + + + + + + + + + + + + + + The Domain Name System Security Extensions (DNSSEC) add data origin authentication and data integrity to the Domain Name System. This document introduces these extensions and describes their capabilities and limitations. This document also discusses the services that the DNS security extensions do and do not provide. Last, this document describes the interrelationships between the documents that collectively describe DNSSEC. [STANDARDS-TRACK] + + + + + + + + SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows + + + + + + + + + + + + This document describes how the Microsoft Internet Explorer (MSIE) and Internet Information Services (IIS) incorporated in Microsoft Windows 2000 use Kerberos for security enhancements of web transactions. The Hypertext Transport Protocol (HTTP) auth-scheme of "negotiate" is defined here; when the negotiation results in the selection of Kerberos, the security services of authentication and, optionally, impersonation (the IIS server assumes the windows identity of the principal that has been authenticated) are performed. This document explains how HTTP authentication utilizes the Simple and Protected GSS-API Negotiation mechanism. Details of Simple And Protected Negotiate (SPNEGO) implementation are not provided in this document. This memo provides information for the Internet community. + + + + + + + + PATCH Method for HTTP + + + + + + + + + + Network Time Protocol Version 4: Protocol and Algorithms Specification + + + + + + + + + + + + + + + The Network Time Protocol (NTP) is widely used to synchronize computer clocks in the Internet. This document describes NTP version 4 (NTPv4), which is backwards compatible with NTP version 3 (NTPv3), described in RFC 1305, as well as previous versions of the protocol. NTPv4 includes a modified protocol header to accommodate the Internet Protocol version 6 address family. NTPv4 includes fundamental improvements in the mitigation and discipline algorithms that extend the potential accuracy to the tens of microseconds with modern workstations and fast LANs. It includes a dynamic server discovery scheme, so that in many cases, specific server configuration is not required. It corrects certain errors in the NTPv3 design and implementation and includes an optional extension mechanism. [STANDARDS-TRACK] + + + + + + + + The Web Origin Concept + + + + + + This document defines the concept of an "origin", which is often used as the scope of authority or privilege by user agents. Typically, user agents isolate content retrieved from different origins to prevent malicious web site operators from interfering with the operation of benign web sites. In addition to outlining the principles that underlie the concept of origin, this document details how to determine the origin of a URI and how to serialize an origin into a string. It also defines an HTTP header field, named "Origin", that indicates which origins are associated with an HTTP request. [STANDARDS-TRACK] + + + + + + + + Additional HTTP Status Codes + + + + + + + + + This document specifies additional HyperText Transfer Protocol (HTTP) status codes for a variety of common situations. [STANDARDS-TRACK] + + + + + + + + Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is a stateless application-level protocol for distributed, collaborative, hypertext information systems. This document provides an overview of HTTP architecture and its associated terminology, defines the "http" and "https" Uniform Resource Identifier (URI) schemes, defines the HTTP/1.1 message syntax and parsing requirements, and describes related security concerns for implementations. + + + + + + + + Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is a stateless \%application- level protocol for distributed, collaborative, hypertext information systems. This document defines the semantics of HTTP/1.1 messages, as expressed by request methods, request header fields, response status codes, and response header fields, along with the payload of messages (metadata and body content) and mechanisms for content negotiation. + + + + + + + + Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is a stateless application- level protocol for distributed, collaborative, hypertext information systems. This document defines HTTP/1.1 conditional requests, including metadata header fields for indicating state changes, request header fields for making preconditions on such state, and rules for constructing the responses to a conditional request when one or more preconditions evaluate to false. + + + + + + + + Hypertext Transfer Protocol (HTTP/1.1): Range Requests + + + + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is a stateless application- level protocol for distributed, collaborative, hypertext information systems. This document defines range requests and the rules for constructing and combining responses to those requests. + + + + + + + + Hypertext Transfer Protocol (HTTP/1.1): Caching + + + + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is a stateless \%application- level protocol for distributed, collaborative, hypertext information systems. This document defines HTTP caches and the associated header fields that control cache behavior or indicate cacheable response messages. + + + + + + + + Hypertext Transfer Protocol (HTTP/1.1): Authentication + + + + + + + + + The Hypertext Transfer Protocol (HTTP) is a stateless application- level protocol for distributed, collaborative, hypermedia information systems. This document defines the HTTP Authentication framework. + + + + + + + + The Hypertext Transfer Protocol Status Code 308 (Permanent Redirect) + + + + + + This document specifies the additional Hypertext Transfer Protocol (HTTP) status code 308 (Permanent Redirect). + + + + + + + + Hypertext Transfer Protocol Version 2 (HTTP/2) + + + + + + + + + + + + This specification describes an optimized expression of the semantics of the Hypertext Transfer Protocol (HTTP), referred to as HTTP version 2 (HTTP/2). HTTP/2 enables a more efficient use of network resources and a reduced perception of latency by introducing header field compression and allowing multiple concurrent exchanges on the same connection. It also introduces unsolicited push of representations from servers to clients. + This specification is an alternative to, but does not obsolete, the HTTP/1.1 message syntax. HTTP's existing semantics remain unchanged. + + + + + + + + Returning Values from Forms: multipart/form-data + + + + + + This specification defines the multipart/form-data media type, which can be used by a wide variety of applications and transported by a wide variety of protocols as a way of returning a set of values as the result of a user filling out a form. This document obsoletes RFC 2388. + + + + + + + + HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields + + + + + + This specification defines the "Authentication-Info" and "Proxy- Authentication-Info" response header fields for use in Hypertext Transfer Protocol (HTTP) authentication schemes that need to return information once the client's authentication credentials have been accepted. + + + + + + + + HTTP Digest Access Authentication + + + + + + + + + + + + The Hypertext Transfer Protocol (HTTP) provides a simple challenge- response authentication mechanism that may be used by a server to challenge a client request and by a client to provide authentication information. This document defines the HTTP Digest Authentication scheme that can be used with the HTTP authentication mechanism. + + + + + + + + The 'Basic' HTTP Authentication Scheme + + + + + + This document defines the "Basic" Hypertext Transfer Protocol (HTTP) authentication scheme, which transmits credentials as user-id/ password pairs, encoded using Base64. + + + + + + + + Hypertext Transfer Protocol (HTTP) Client-Initiated Content-Encoding + + + + + + In HTTP, content codings allow for payload encodings such as for compression or integrity checks. In particular, the "gzip" content coding is widely used for payload data sent in response messages. + Content codings can be used in request messages as well; however, discoverability is not on par with response messages. This document extends the HTTP "Accept-Encoding" header field for use in responses, to indicate the content codings that are supported in requests. + + + + + + + + Guidelines for Writing an IANA Considerations Section in RFCs + + + + + + + + + + + + Many protocols make use of points of extensibility that use constants to identify various protocol parameters. To ensure that the values in these fields do not have conflicting uses and to promote interoperability, their allocations are often coordinated by a central record keeper. For IETF protocols, that role is filled by the Internet Assigned Numbers Authority (IANA). + To make assignments in a given registry prudently, guidance describing the conditions under which new values should be assigned, as well as when and how modifications to existing values can be made, is needed. This document defines a framework for the documentation of these guidelines by specification authors, in order to assure that the provided guidance for the IANA Considerations is clear and addresses the various issues that are likely in the operation of a registry. + This is the third edition of this document; it obsoletes RFC 5226. + + + + + + + + + Indicating Character Encoding and Language for HTTP Header Field Parameters + + + + + + By default, header field values in Hypertext Transfer Protocol (HTTP) messages cannot easily carry characters outside the US-ASCII coded character set. RFC 2231 defines an encoding mechanism for use in parameters inside Multipurpose Internet Mail Extensions (MIME) header field values. This document specifies an encoding suitable for use in HTTP header fields that is compatible with a simplified profile of the encoding defined in RFC 2231. + This document obsoletes RFC 5987. + + + + + + + + HTTP Immutable Responses + + + + + + The immutable HTTP response Cache-Control extension allows servers to identify resources that will not be updated during their freshness lifetime. This ensures that a client never needs to revalidate a cached fresh resource to be certain it has not been modified. + + + + + + + + Web Linking + + + + + + This specification defines a model for the relationships between resources on the Web ("links") and the type of those relationships ("link relation types"). + It also defines the serialisation of such links in HTTP headers with the Link header field. + + + + + + + + The ORIGIN HTTP/2 Frame + + + + + + + + + This document specifies the ORIGIN frame for HTTP/2, to indicate what origins are available on a given connection. + + + + + + + + Well-Known Uniform Resource Identifiers (URIs) + + + + + + This memo defines a path prefix for "well-known locations", "/.well-known/", in selected Uniform Resource Identifier (URI) schemes. + In doing so, it obsoletes RFC 5785 and updates the URI schemes defined in RFC 7230 to reserve that space. It also updates RFC 7595 to track URI schemes that support well-known URIs in their registry. + + + + + + + + Structured Field Values for HTTP + + + + + + + + + This document describes a set of data types and associated algorithms that are intended to make it easier and safer to define and handle HTTP header and trailer fields, known as "Structured Fields", "Structured Headers", or "Structured Trailers". It is intended for use by specifications of new HTTP fields that wish to use a common syntax that is more restrictive than traditional HTTP field values. + + + + + + + + MIME Sniffing + + WHATWG + + + + + + + HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) + + + + + + + + +
+ Collected ABNF + In the collected ABNF below, list rules are expanded per . + Accept = [ ( media-range [ weight ] ) *( OWS "," OWS ( media-range [ + weight ] ) ) ] +Accept-Charset = [ ( ( token / "*" ) [ weight ] ) *( OWS "," OWS ( ( + token / "*" ) [ weight ] ) ) ] +Accept-Encoding = [ ( codings [ weight ] ) *( OWS "," OWS ( codings [ + weight ] ) ) ] +Accept-Language = [ ( language-range [ weight ] ) *( OWS "," OWS ( + language-range [ weight ] ) ) ] +Accept-Ranges = acceptable-ranges +Allow = [ method *( OWS "," OWS method ) ] +Authentication-Info = [ auth-param *( OWS "," OWS auth-param ) ] +Authorization = credentials + +BWS = OWS + +Connection = [ connection-option *( OWS "," OWS connection-option ) + ] +Content-Encoding = [ content-coding *( OWS "," OWS content-coding ) + ] +Content-Language = [ language-tag *( OWS "," OWS language-tag ) ] +Content-Length = 1*DIGIT +Content-Location = absolute-URI / partial-URI +Content-Range = range-unit SP ( range-resp / unsatisfied-range ) +Content-Type = media-type + +Date = HTTP-date + +ETag = entity-tag +Expect = [ expectation *( OWS "," OWS expectation ) ] + +From = mailbox + +GMT = %x47.4D.54 ; GMT + +HTTP-date = IMF-fixdate / obs-date +Host = uri-host [ ":" port ] + +IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT +If-Match = "*" / [ entity-tag *( OWS "," OWS entity-tag ) ] +If-Modified-Since = HTTP-date +If-None-Match = "*" / [ entity-tag *( OWS "," OWS entity-tag ) ] +If-Range = entity-tag / HTTP-date +If-Unmodified-Since = HTTP-date + +Last-Modified = HTTP-date +Location = URI-reference + +Max-Forwards = 1*DIGIT + +OWS = *( SP / HTAB ) + +Proxy-Authenticate = [ challenge *( OWS "," OWS challenge ) ] +Proxy-Authentication-Info = [ auth-param *( OWS "," OWS auth-param ) + ] +Proxy-Authorization = credentials + +RWS = 1*( SP / HTAB ) +Range = ranges-specifier +Referer = absolute-URI / partial-URI +Retry-After = HTTP-date / delay-seconds + +Server = product *( RWS ( product / comment ) ) + +TE = [ t-codings *( OWS "," OWS t-codings ) ] +Trailer = [ field-name *( OWS "," OWS field-name ) ] + +URI-reference = <URI-reference, see [URI], Section 4.1> +Upgrade = [ protocol *( OWS "," OWS protocol ) ] +User-Agent = product *( RWS ( product / comment ) ) + +Vary = [ ( "*" / field-name ) *( OWS "," OWS ( "*" / field-name ) ) + ] +Via = [ ( received-protocol RWS received-by [ RWS comment ] ) *( OWS + "," OWS ( received-protocol RWS received-by [ RWS comment ] ) ) ] + +WWW-Authenticate = [ challenge *( OWS "," OWS challenge ) ] + +absolute-URI = <absolute-URI, see [URI], Section 4.3> +absolute-path = 1*( "/" segment ) +acceptable-ranges = range-unit *( OWS "," OWS range-unit ) +asctime-date = day-name SP date3 SP time-of-day SP year +auth-param = token BWS "=" BWS ( token / quoted-string ) +auth-scheme = token +authority = <authority, see [URI], Section 3.2> + +challenge = auth-scheme [ 1*SP ( token68 / [ auth-param *( OWS "," + OWS auth-param ) ] ) ] +codings = content-coding / "identity" / "*" +comment = "(" *( ctext / quoted-pair / comment ) ")" +complete-length = 1*DIGIT +connection-option = token +content-coding = token +credentials = auth-scheme [ 1*SP ( token68 / [ auth-param *( OWS "," + OWS auth-param ) ] ) ] +ctext = HTAB / SP / %x21-27 ; '!'-''' + / %x2A-5B ; '*'-'[' + / %x5D-7E ; ']'-'~' + / obs-text + +date1 = day SP month SP year +date2 = day "-" month "-" 2DIGIT +date3 = month SP ( 2DIGIT / ( SP DIGIT ) ) +day = 2DIGIT +day-name = %x4D.6F.6E ; Mon + / %x54.75.65 ; Tue + / %x57.65.64 ; Wed + / %x54.68.75 ; Thu + / %x46.72.69 ; Fri + / %x53.61.74 ; Sat + / %x53.75.6E ; Sun +day-name-l = %x4D.6F.6E.64.61.79 ; Monday + / %x54.75.65.73.64.61.79 ; Tuesday + / %x57.65.64.6E.65.73.64.61.79 ; Wednesday + / %x54.68.75.72.73.64.61.79 ; Thursday + / %x46.72.69.64.61.79 ; Friday + / %x53.61.74.75.72.64.61.79 ; Saturday + / %x53.75.6E.64.61.79 ; Sunday +delay-seconds = 1*DIGIT + +entity-tag = [ weak ] opaque-tag +etagc = "!" / %x23-7E ; '#'-'~' + / obs-text +expectation = token [ "=" ( token / quoted-string ) parameters ] + +field-content = field-vchar [ 1*( SP / HTAB / field-vchar ) + field-vchar ] +field-name = token +field-value = *field-content +field-vchar = VCHAR / obs-text +first-pos = 1*DIGIT + +hour = 2DIGIT +http-URI = "http://" authority path-abempty [ "?" query ] +https-URI = "https://" authority path-abempty [ "?" query ] + +incl-range = first-pos "-" last-pos +int-range = first-pos "-" [ last-pos ] + +language-range = <language-range, see [RFC4647], Section 2.1> +language-tag = <Language-Tag, see [RFC5646], Section 2.1> +last-pos = 1*DIGIT + +mailbox = <mailbox, see [RFC5322], Section 3.4> +media-range = ( "*/*" / ( type "/*" ) / ( type "/" subtype ) ) + parameters +media-type = type "/" subtype parameters +method = token +minute = 2DIGIT +month = %x4A.61.6E ; Jan + / %x46.65.62 ; Feb + / %x4D.61.72 ; Mar + / %x41.70.72 ; Apr + / %x4D.61.79 ; May + / %x4A.75.6E ; Jun + / %x4A.75.6C ; Jul + / %x41.75.67 ; Aug + / %x53.65.70 ; Sep + / %x4F.63.74 ; Oct + / %x4E.6F.76 ; Nov + / %x44.65.63 ; Dec + +obs-date = rfc850-date / asctime-date +obs-text = %x80-FF +opaque-tag = DQUOTE *etagc DQUOTE +other-range = 1*( %x21-2B ; '!'-'+' + / %x2D-7E ; '-'-'~' + ) + +parameter = parameter-name "=" parameter-value +parameter-name = token +parameter-value = ( token / quoted-string ) +parameters = *( OWS ";" OWS [ parameter ] ) +partial-URI = relative-part [ "?" query ] +path-abempty = <path-abempty, see [URI], Section 3.3> +port = <port, see [URI], Section 3.2.3> +product = token [ "/" product-version ] +product-version = token +protocol = protocol-name [ "/" protocol-version ] +protocol-name = token +protocol-version = token +pseudonym = token + +qdtext = HTAB / SP / "!" / %x23-5B ; '#'-'[' + / %x5D-7E ; ']'-'~' + / obs-text +query = <query, see [URI], Section 3.4> +quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) +quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE +qvalue = ( "0" [ "." *3DIGIT ] ) / ( "1" [ "." *3"0" ] ) + +range-resp = incl-range "/" ( complete-length / "*" ) +range-set = range-spec *( OWS "," OWS range-spec ) +range-spec = int-range / suffix-range / other-range +range-unit = token +ranges-specifier = range-unit "=" range-set +received-by = pseudonym [ ":" port ] +received-protocol = [ protocol-name "/" ] protocol-version +relative-part = <relative-part, see [URI], Section 4.2> +rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT + +second = 2DIGIT +segment = <segment, see [URI], Section 3.3> +subtype = token +suffix-length = 1*DIGIT +suffix-range = "-" suffix-length + +t-codings = "trailers" / ( transfer-coding [ weight ] ) +tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +time-of-day = hour ":" minute ":" second +token = 1*tchar +token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) + *"=" +transfer-coding = token *( OWS ";" OWS transfer-parameter ) +transfer-parameter = token BWS "=" BWS ( token / quoted-string ) +type = token + +unsatisfied-range = "*/" complete-length +uri-host = <host, see [URI], Section 3.2.2> + +weak = %x57.2F ; W/ +weight = OWS ";" OWS "q=" qvalue + +year = 4DIGIT + +
+
+ Changes from Previous RFCs +
+ Changes from RFC 2818 + + None. + +
+
+ Changes from RFC 7230 + + The sections introducing HTTP's design goals, history, architecture, + conformance criteria, protocol versioning, URIs, message routing, and + header fields have been moved here. + + + The requirement on semantic conformance has been replaced with permission to + ignore or work around implementation-specific failures. + () + + + The description of an origin and authoritative access to origin servers has + been extended for both "http" and "https" URIs to account for alternative + services and secured connections that are not necessarily based on TCP. + (Sections , , + , and ) + + + Explicit requirements have been added to check the target URI scheme's semantics + and reject requests that don't meet any associated requirements. + () + + + Parameters in media type, media range, and expectation can be empty via + one or more trailing semicolons. + () + + + "Field value" now refers to the value after multiple field lines are combined + with commas -- by far the most common use. To refer to a single header + line's value, use "field line value". + () + + + Trailer field semantics now transcend the specifics of chunked transfer coding. + The use of trailer fields has been further limited to allow generation + as a trailer field only when the sender knows the field defines that usage and + to allow merging into the header section only if the recipient knows the + corresponding field definition permits and defines how to merge. In all + other cases, implementations are encouraged either to store the trailer + fields separately or to discard them instead of merging. + () + + + The priority of the absolute form of the request URI over the Host + header field by origin servers has been made explicit to align with proxy handling. + () + + + The grammar definition for the Via field's "received-by" was + expanded in RFC 7230 due to changes in the URI grammar for host + that are not desirable for Via. For simplicity, + we have removed uri-host from the received-by production because it can + be encompassed by the existing grammar for pseudonym. In particular, this + change removed comma from the allowed set of characters for a host name in + received-by. + () + +
+
+ Changes from RFC 7231 + + Minimum URI lengths to be supported by implementations are now recommended. + () + + + The following have been clarified: CR and NUL in field values are to be rejected or + mapped to SP, and leading and trailing whitespace needs to be + stripped from field values before they are consumed. + () + + + Parameters in media type, media range, and expectation can be empty via + one or more trailing semicolons. + () + + + An abstract data type for HTTP messages has been introduced to define the + components of a message and their semantics as an abstraction across + multiple HTTP versions, rather than in terms of the specific syntax form of + HTTP/1.1 in , and reflect the contents after the + message is parsed. This makes it easier to distinguish between requirements + on the content (what is conveyed) versus requirements on the messaging + syntax (how it is conveyed) and avoids baking limitations of early protocol + versions into the future of HTTP. () + + + The terms "payload" and "payload body" have been replaced with "content", to better + align with its usage elsewhere (e.g., in field names) and to avoid confusion + with frame payloads in HTTP/2 and HTTP/3. + () + + + The term "effective request URI" has been replaced with "target URI". + () + + + Restrictions on client retries have been loosened to reflect implementation + behavior. + () + + + The fact that request bodies on GET, HEAD, and DELETE are not interoperable has been clarified. + (Sections , , and ) + + + The use of the Content-Range header field + () as a request modifier on PUT is allowed. + () + + + A superfluous requirement about setting Content-Length + has been removed from the description of the OPTIONS method. + () + + + The normative requirement to use the "message/http" media type in + TRACE responses has been removed. + () + + + List-based grammar for Expect has been restored for compatibility with + RFC 2616. + () + + + Accept and Accept-Encoding are allowed in response + messages; the latter was introduced by . + () + + + "Accept Parameters" (accept-params and accept-ext ABNF production) have + been removed from the definition of the Accept field. + () + + + The Accept-Charset field is now deprecated. + () + + + The semantics of "*" in the Vary header field when other + values are present was clarified. + () + + + Range units are compared in a case-insensitive fashion. + () + + + The use of the Accept-Ranges field is not restricted to origin servers. + () + + + The process of creating a redirected request has been clarified. + () + + + Status code 308 (previously defined in ) + has been added so that it's defined closer to status codes 301, 302, and 307. + () + + + Status code 421 (previously defined in + ) has been added because of its general + applicability. 421 is no longer defined as heuristically cacheable since + the response is specific to the connection (not the target resource). + () + + + Status code 422 (previously defined in + ) has been added because of its general + applicability. + () + +
+
+ Changes from RFC 7232 + + Previous revisions of HTTP imposed an arbitrary 60-second limit on the + determination of whether Last-Modified was a strong validator to guard + against the possibility that the Date and Last-Modified values are + generated from different clocks or at somewhat different times during the + preparation of the response. This specification has relaxed that to allow + reasonable discretion. + () + + + An edge-case requirement on If-Match and If-Unmodified-Since + has been removed that required a validator not to be sent in a 2xx + response if validation fails because the change request has already + been applied. + (Sections and + ) + + + The fact that If-Unmodified-Since does not apply to a resource without a + concept of modification time has been clarified. + () + + + Preconditions can now be evaluated before the request content is processed + rather than waiting until the response would otherwise be successful. + () + +
+
+ Changes from RFC 7233 + + Refactored the range-unit and ranges-specifier grammars to simplify + and reduce artificial distinctions between bytes and other + (extension) range units, removing the overlapping grammar of + other-range-unit by defining range units generically as a token and + placing extensions within the scope of a range-spec (other-range). + This disambiguates the role of list syntax (commas) in all range sets, + including extension range units, for indicating a range-set of more than + one range. Moving the extension grammar into range specifiers also allows + protocol specific to byte ranges to be specified separately. + + + It is now possible to define Range handling on extension methods. + () + + + Described use of the Content-Range header field + () as a request modifier to perform a + partial PUT. + () + +
+
+ Changes from RFC 7235 + + None. + +
+
+ Changes from RFC 7538 + + None. + +
+
+ Changes from RFC 7615 + + None. + +
+
+ Changes from RFC 7694 + + This specification includes the extension defined in + but leaves out examples and deployment considerations. + +
+
+
+ Acknowledgements + + Aside from the current editors, the following individuals deserve special + recognition for their contributions to early aspects of HTTP and its + core specifications: + , , , , + , , , + , + , + , , , + , , , + , , + , , , + , , + , , , , + , , + , and . + + + This document builds on the many contributions + that went into past specifications of HTTP, including + , + , + , + , + , + , + , + , + , + , + , and + . + The acknowledgements within those documents still apply. + + + Since 2014, the following contributors have helped improve this + specification by reporting bugs, asking smart questions, drafting or + reviewing text, and evaluating issues: + + + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , and + . + +
+
+ Index + + 1 + 2 + 3 + 4 + 5 + A + B + C + D + E + F + G + H + I + L + M + N + O + P + R + S + T + U + V + W + X + +
    +
  • + + 1 + +
      +
    • +
      +
      100 Continue (status code)
      +
      + + + +
      +
      100-continue (expect value)
      +
      + + + +
      +
      101 Switching Protocols (status code)
      +
      + + + +
      +
      1xx Informational (status code class)
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + 2 + +
      +
    • +
      +
      200 OK (status code)
      +
      + + + +
      +
      201 Created (status code)
      +
      + + + +
      +
      202 Accepted (status code)
      +
      + + + +
      +
      203 Non-Authoritative Information (status code)
      +
      + + + +
      +
      204 No Content (status code)
      +
      + + + +
      +
      205 Reset Content (status code)
      +
      + + + +
      +
      206 Partial Content (status code)
      +
      + + + +
      +
      2xx Successful (status code class)
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + 3 + +
      +
    • +
      +
      300 Multiple Choices (status code)
      +
      + + + +
      +
      301 Moved Permanently (status code)
      +
      + + + +
      +
      302 Found (status code)
      +
      + + + +
      +
      303 See Other (status code)
      +
      + + + +
      +
      304 Not Modified (status code)
      +
      + + + +
      +
      305 Use Proxy (status code)
      +
      + + + +
      +
      306 (Unused) (status code)
      +
      + + + +
      +
      307 Temporary Redirect (status code)
      +
      + + + +
      +
      308 Permanent Redirect (status code)
      +
      + + + +
      +
      3xx Redirection (status code class)
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + 4 + +
      +
    • +
      +
      400 Bad Request (status code)
      +
      + + + +
      +
      401 Unauthorized (status code)
      +
      + + + +
      +
      402 Payment Required (status code)
      +
      + + + +
      +
      403 Forbidden (status code)
      +
      + + + +
      +
      404 Not Found (status code)
      +
      + + + +
      +
      405 Method Not Allowed (status code)
      +
      + + + +
      +
      406 Not Acceptable (status code)
      +
      + + + +
      +
      407 Proxy Authentication Required (status code)
      +
      + + + +
      +
      408 Request Timeout (status code)
      +
      + + + +
      +
      409 Conflict (status code)
      +
      + + + +
      +
      410 Gone (status code)
      +
      + + + +
      +
      411 Length Required (status code)
      +
      + + + +
      +
      412 Precondition Failed (status code)
      +
      + + + +
      +
      413 Content Too Large (status code)
      +
      + + + +
      +
      414 URI Too Long (status code)
      +
      + + + +
      +
      415 Unsupported Media Type (status code)
      +
      + + + +
      +
      416 Range Not Satisfiable (status code)
      +
      + + + +
      +
      417 Expectation Failed (status code)
      +
      + + + +
      +
      418 (Unused) (status code)
      +
      + + + +
      +
      421 Misdirected Request (status code)
      +
      + + + +
      +
      422 Unprocessable Content (status code)
      +
      + + + +
      +
      426 Upgrade Required (status code)
      +
      + + + +
      +
      4xx Client Error (status code class)
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + 5 + +
      +
    • +
      +
      500 Internal Server Error (status code)
      +
      + + + +
      +
      501 Not Implemented (status code)
      +
      + + + +
      +
      502 Bad Gateway (status code)
      +
      + + + +
      +
      503 Service Unavailable (status code)
      +
      + + + +
      +
      504 Gateway Timeout (status code)
      +
      + + + +
      +
      505 HTTP Version Not Supported (status code)
      +
      + + + +
      +
      5xx Server Error (status code class)
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + A + +
      +
    • +
      +
      accelerator
      +
      + + + +
      +
      Accept header field
      +
      + + + +
      +
      Accept-Charset header field
      +
      + + + +
      +
      Accept-Encoding header field
      +
      + + + +
      +
      Accept-Language header field
      +
      + + + +
      +
      Accept-Ranges header field
      +
      + + + +
      +
      Allow header field
      +
      + + + +
      +
      Authentication-Info header field
      +
      + + + +
      +
      authoritative response
      +
      + + + +
      +
      Authorization header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + B + +
      +
    • +
      +
      browser
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + C + +
      +
    • +
      +
      cache
      +
      + + + +
      +
      cacheable
      +
      + + + +
      +
      client
      +
      + + + +
      +
      clock
      +
      + + + +
      +
      complete
      +
      + + + +
      +
      compress (Coding Format)
      +
      + + + +
      +
      compress (content coding)
      +
      + + + +
      +
      conditional request
      +
      + + + +
      +
      CONNECT method
      +
      + + + +
      +
      connection
      +
      + + + +
      +
      Connection header field
      +
      + + + +
      +
      content
      +
      + + + +
      +
      content coding
      +
      + + + +
      +
      content negotiation
      +
      + + + +
      +
      Content-Encoding header field
      +
      + + + +
      +
      Content-Language header field
      +
      + + + +
      +
      Content-Length header field
      +
      + + + +
      +
      Content-Location header field
      +
      + + + +
      +
      Content-MD5 header field
      +
      + + + +
      +
      Content-Range header field
      +
      + + ; + + +
      +
      Content-Type header field
      +
      + + + +
      +
      control data
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + D + +
      +
    • +
      +
      Date header field
      +
      + + + +
      +
      deflate (Coding Format)
      +
      + + + +
      +
      deflate (content coding)
      +
      + + + +
      +
      DELETE method
      +
      + + + +
      +
      Delimiters
      +
      + + + +
      +
      downstream
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + E + +
      +
    • +
      +
      effective request URI
      +
      + + + +
      +
      ETag field
      +
      + + + +
      +
      Expect header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + F + +
      +
    • +
      +
      field
      +
      + + ; + + +
      +
      field line
      +
      + + + +
      +
      field line value
      +
      + + + +
      +
      field name
      +
      + + + +
      +
      field value
      +
      + + + +
      +
      Fields
      +
      +
      +
      +
      +
      *
      +
      + + + +
      +
      Accept
      +
      + + + +
      +
      Accept-Charset
      +
      + + + +
      +
      Accept-Encoding
      +
      + + + +
      +
      Accept-Language
      +
      + + + +
      +
      Accept-Ranges
      +
      + + + +
      +
      Allow
      +
      + + + +
      +
      Authentication-Info
      +
      + + + +
      +
      Authorization
      +
      + + + +
      +
      Connection
      +
      + + + +
      +
      Content-Encoding
      +
      + + + +
      +
      Content-Language
      +
      + + + +
      +
      Content-Length
      +
      + + + +
      +
      Content-Location
      +
      + + + +
      +
      Content-MD5
      +
      + + + +
      +
      Content-Range
      +
      + + ; + + +
      +
      Content-Type
      +
      + + + +
      +
      Date
      +
      + + + +
      +
      ETag
      +
      + + + +
      +
      Expect
      +
      + + + +
      +
      From
      +
      + + + +
      +
      Host
      +
      + + + +
      +
      If-Match
      +
      + + + +
      +
      If-Modified-Since
      +
      + + + +
      +
      If-None-Match
      +
      + + + +
      +
      If-Range
      +
      + + + +
      +
      If-Unmodified-Since
      +
      + + + +
      +
      Last-Modified
      +
      + + + +
      +
      Location
      +
      + + + +
      +
      Max-Forwards
      +
      + + + +
      +
      Proxy-Authenticate
      +
      + + + +
      +
      Proxy-Authentication-Info
      +
      + + + +
      +
      Proxy-Authorization
      +
      + + + +
      +
      Range
      +
      + + + +
      +
      Referer
      +
      + + + +
      +
      Retry-After
      +
      + + + +
      +
      Server
      +
      + + + +
      +
      TE
      +
      + + + +
      +
      Trailer
      +
      + + + +
      +
      Upgrade
      +
      + + + +
      +
      User-Agent
      +
      + + + +
      +
      Vary
      +
      + + + +
      +
      Via
      +
      + + + +
      +
      WWW-Authenticate
      +
      + + + +
      +
      +
      +
      Fragment Identifiers
      +
      + + + +
      +
      From header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + G + +
      +
    • +
      +
      gateway
      +
      + + + +
      +
      GET method
      +
      + + + +
      +
      Grammar
      +
      +
      +
      +
      +
      ALPHA
      +
      + + + +
      +
      Accept
      +
      + + + +
      +
      Accept-Charset
      +
      + + + +
      +
      Accept-Encoding
      +
      + + + +
      +
      Accept-Language
      +
      + + + +
      +
      Accept-Ranges
      +
      + + + +
      +
      Allow
      +
      + + + +
      +
      Authentication-Info
      +
      + + + +
      +
      Authorization
      +
      + + + +
      +
      BWS
      +
      + + + +
      +
      CR
      +
      + + + +
      +
      CRLF
      +
      + + + +
      +
      CTL
      +
      + + + +
      +
      Connection
      +
      + + + +
      +
      Content-Encoding
      +
      + + + +
      +
      Content-Language
      +
      + + + +
      +
      Content-Length
      +
      + + + +
      +
      Content-Location
      +
      + + + +
      +
      Content-Range
      +
      + + + +
      +
      Content-Type
      +
      + + + +
      +
      DIGIT
      +
      + + + +
      +
      DQUOTE
      +
      + + + +
      +
      Date
      +
      + + + +
      +
      ETag
      +
      + + + +
      +
      Expect
      +
      + + + +
      +
      From
      +
      + + + +
      +
      GMT
      +
      + + + +
      +
      HEXDIG
      +
      + + + +
      +
      HTAB
      +
      + + + +
      +
      HTTP-date
      +
      + + + +
      +
      Host
      +
      + + + +
      +
      IMF-fixdate
      +
      + + + +
      +
      If-Match
      +
      + + + +
      +
      If-Modified-Since
      +
      + + + +
      +
      If-None-Match
      +
      + + + +
      +
      If-Range
      +
      + + + +
      +
      If-Unmodified-Since
      +
      + + + +
      +
      LF
      +
      + + + +
      +
      Last-Modified
      +
      + + + +
      +
      Location
      +
      + + + +
      +
      Max-Forwards
      +
      + + + +
      +
      OCTET
      +
      + + + +
      +
      OWS
      +
      + + + +
      +
      Proxy-Authenticate
      +
      + + + +
      +
      Proxy-Authentication-Info
      +
      + + + +
      +
      Proxy-Authorization
      +
      + + + +
      +
      RWS
      +
      + + + +
      +
      Range
      +
      + + + +
      +
      Referer
      +
      + + + +
      +
      Retry-After
      +
      + + + +
      +
      SP
      +
      + + + +
      +
      Server
      +
      + + + +
      +
      TE
      +
      + + + +
      +
      Trailer
      +
      + + + +
      +
      URI-reference
      +
      + + + +
      +
      Upgrade
      +
      + + + +
      +
      User-Agent
      +
      + + + +
      +
      VCHAR
      +
      + + + +
      +
      Vary
      +
      + + + +
      +
      Via
      +
      + + + +
      +
      WWW-Authenticate
      +
      + + + +
      +
      absolute-URI
      +
      + + + +
      +
      absolute-path
      +
      + + + +
      +
      acceptable-ranges
      +
      + + + +
      +
      asctime-date
      +
      + + + +
      +
      auth-param
      +
      + + + +
      +
      auth-scheme
      +
      + + + +
      +
      authority
      +
      + + + +
      +
      challenge
      +
      + + + +
      +
      codings
      +
      + + + +
      +
      comment
      +
      + + + +
      +
      complete-length
      +
      + + + +
      +
      connection-option
      +
      + + + +
      +
      content-coding
      +
      + + + +
      +
      credentials
      +
      + + + +
      +
      ctext
      +
      + + + +
      +
      date1
      +
      + + + +
      +
      day
      +
      + + + +
      +
      day-name
      +
      + + + +
      +
      day-name-l
      +
      + + + +
      +
      delay-seconds
      +
      + + + +
      +
      entity-tag
      +
      + + + +
      +
      etagc
      +
      + + + +
      +
      field-content
      +
      + + + +
      +
      field-name
      +
      + + ; + + +
      +
      field-value
      +
      + + + +
      +
      field-vchar
      +
      + + + +
      +
      first-pos
      +
      + + ; + + +
      +
      hour
      +
      + + + +
      +
      http-URI
      +
      + + + +
      +
      https-URI
      +
      + + + +
      +
      incl-range
      +
      + + + +
      +
      int-range
      +
      + + + +
      +
      language-range
      +
      + + + +
      +
      language-tag
      +
      + + + +
      +
      last-pos
      +
      + + ; + + +
      +
      media-range
      +
      + + + +
      +
      media-type
      +
      + + + +
      +
      method
      +
      + + + +
      +
      minute
      +
      + + + +
      +
      month
      +
      + + + +
      +
      obs-date
      +
      + + + +
      +
      obs-text
      +
      + + + +
      +
      opaque-tag
      +
      + + + +
      +
      other-range
      +
      + + + +
      +
      parameter
      +
      + + + +
      +
      parameter-name
      +
      + + + +
      +
      parameter-value
      +
      + + + +
      +
      parameters
      +
      + + + +
      +
      partial-URI
      +
      + + + +
      +
      port
      +
      + + + +
      +
      product
      +
      + + + +
      +
      product-version
      +
      + + + +
      +
      protocol-name
      +
      + + + +
      +
      protocol-version
      +
      + + + +
      +
      pseudonym
      +
      + + + +
      +
      qdtext
      +
      + + + +
      +
      query
      +
      + + + +
      +
      quoted-pair
      +
      + + + +
      +
      quoted-string
      +
      + + + +
      +
      qvalue
      +
      + + + +
      +
      range-resp
      +
      + + + +
      +
      range-set
      +
      + + + +
      +
      range-spec
      +
      + + + +
      +
      range-unit
      +
      + + + +
      +
      ranges-specifier
      +
      + + + +
      +
      received-by
      +
      + + + +
      +
      received-protocol
      +
      + + + +
      +
      rfc850-date
      +
      + + + +
      +
      second
      +
      + + + +
      +
      segment
      +
      + + + +
      +
      subtype
      +
      + + + +
      +
      suffix-length
      +
      + + + +
      +
      suffix-range
      +
      + + + +
      +
      t-codings
      +
      + + + +
      +
      tchar
      +
      + + + +
      +
      time-of-day
      +
      + + + +
      +
      token
      +
      + + + +
      +
      token68
      +
      + + + +
      +
      transfer-coding
      +
      + + + +
      +
      transfer-parameter
      +
      + + + +
      +
      type
      +
      + + + +
      +
      unsatisfied-range
      +
      + + + +
      +
      uri-host
      +
      + + + +
      +
      weak
      +
      + + + +
      +
      weight
      +
      + + + +
      +
      year
      +
      + + + +
      +
      +
      +
      gzip (Coding Format)
      +
      + + + +
      +
      gzip (content coding)
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + H + +
      +
    • +
      +
      HEAD method
      +
      + + + +
      +
      Header Fields
      +
      +
      +
      +
      +
      Accept
      +
      + + + +
      +
      Accept-Charset
      +
      + + + +
      +
      Accept-Encoding
      +
      + + + +
      +
      Accept-Language
      +
      + + + +
      +
      Accept-Ranges
      +
      + + + +
      +
      Allow
      +
      + + + +
      +
      Authentication-Info
      +
      + + + +
      +
      Authorization
      +
      + + + +
      +
      Connection
      +
      + + + +
      +
      Content-Encoding
      +
      + + + +
      +
      Content-Language
      +
      + + + +
      +
      Content-Length
      +
      + + + +
      +
      Content-Location
      +
      + + + +
      +
      Content-MD5
      +
      + + + +
      +
      Content-Range
      +
      + + ; + + +
      +
      Content-Type
      +
      + + + +
      +
      Date
      +
      + + + +
      +
      ETag
      +
      + + + +
      +
      Expect
      +
      + + + +
      +
      From
      +
      + + + +
      +
      Host
      +
      + + + +
      +
      If-Match
      +
      + + + +
      +
      If-Modified-Since
      +
      + + + +
      +
      If-None-Match
      +
      + + + +
      +
      If-Range
      +
      + + + +
      +
      If-Unmodified-Since
      +
      + + + +
      +
      Last-Modified
      +
      + + + +
      +
      Location
      +
      + + + +
      +
      Max-Forwards
      +
      + + + +
      +
      Proxy-Authenticate
      +
      + + + +
      +
      Proxy-Authentication-Info
      +
      + + + +
      +
      Proxy-Authorization
      +
      + + + +
      +
      Range
      +
      + + + +
      +
      Referer
      +
      + + + +
      +
      Retry-After
      +
      + + + +
      +
      Server
      +
      + + + +
      +
      TE
      +
      + + + +
      +
      Trailer
      +
      + + + +
      +
      Upgrade
      +
      + + + +
      +
      User-Agent
      +
      + + + +
      +
      Vary
      +
      + + + +
      +
      Via
      +
      + + + +
      +
      WWW-Authenticate
      +
      + + + +
      +
      +
      +
      header section
      +
      + + + +
      +
      Host header field
      +
      + + + +
      +
      http URI scheme
      +
      + + + +
      +
      https URI scheme
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + I + +
      +
    • +
      +
      idempotent
      +
      + + + +
      +
      If-Match header field
      +
      + + + +
      +
      If-Modified-Since header field
      +
      + + + +
      +
      If-None-Match header field
      +
      + + + +
      +
      If-Range header field
      +
      + + + +
      +
      If-Unmodified-Since header field
      +
      + + + +
      +
      inbound
      +
      + + + +
      +
      incomplete
      +
      + + + +
      +
      interception proxy
      +
      + + + +
      +
      intermediary
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + L + +
      +
    • +
      +
      Last-Modified header field
      +
      + + + +
      +
      list-based field
      +
      + + + +
      +
      Location header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + M + +
      +
    • +
      +
      Max-Forwards header field
      +
      + + + +
      +
      Media Type
      +
      +
      +
      +
      +
      multipart/byteranges
      +
      + + + +
      +
      multipart/x-byteranges
      +
      + + + +
      +
      +
      +
      message
      +
      + + ; + + +
      +
      message abstraction
      +
      + + + +
      +
      messages
      +
      + + + +
      +
      metadata
      +
      + + + +
      +
      Method
      +
      +
      +
      +
      +
      *
      +
      + + + +
      +
      CONNECT
      +
      + + + +
      +
      DELETE
      +
      + + + +
      +
      GET
      +
      + + + +
      +
      HEAD
      +
      + + + +
      +
      OPTIONS
      +
      + + + +
      +
      POST
      +
      + + + +
      +
      PUT
      +
      + + + +
      +
      TRACE
      +
      + + + +
      +
      +
      +
      multipart/byteranges Media Type
      +
      + + + +
      +
      multipart/x-byteranges Media Type
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + N + +
      +
    • +
      +
      non-transforming proxy
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + O + +
      +
    • +
      +
      OPTIONS method
      +
      + + + +
      +
      origin
      +
      + + ; + + +
      +
      origin server
      +
      + + + +
      +
      outbound
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + P + +
      +
    • +
      +
      phishing
      +
      + + + +
      +
      POST method
      +
      + + + +
      +
      Protection Space
      +
      + + + +
      +
      proxy
      +
      + + + +
      +
      Proxy-Authenticate header field
      +
      + + + +
      +
      Proxy-Authentication-Info header field
      +
      + + + +
      +
      Proxy-Authorization header field
      +
      + + + +
      +
      PUT method
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + R + +
      +
    • +
      +
      Range header field
      +
      + + + +
      +
      Realm
      +
      + + + +
      +
      recipient
      +
      + + + +
      +
      Referer header field
      +
      + + + +
      +
      representation
      +
      + + + +
      +
      request
      +
      + + + +
      +
      request target
      +
      + + + +
      +
      resource
      +
      + + ; + + +
      +
      response
      +
      + + + +
      +
      Retry-After header field
      +
      + + + +
      +
      reverse proxy
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + S + +
      +
    • +
      +
      safe
      +
      + + + +
      +
      satisfiable range
      +
      + + + +
      +
      secured
      +
      + + + +
      +
      selected representation
      +
      + + ; +; + + +
      +
      self-descriptive
      +
      + + + +
      +
      sender
      +
      + + + +
      +
      server
      +
      + + + +
      +
      Server header field
      +
      + + + +
      +
      singleton field
      +
      + + + +
      +
      spider
      +
      + + + +
      +
      Status Code
      +
      + + + +
      +
      Status Codes
      +
      +
      +
      +
      +
      Final
      +
      + + + +
      +
      Informational
      +
      + + + +
      +
      Interim
      +
      + + + +
      +
      +
      +
      Status Codes Classes
      +
      +
      +
      +
      +
      1xx Informational
      +
      + + + +
      +
      2xx Successful
      +
      + + + +
      +
      3xx Redirection
      +
      + + + +
      +
      4xx Client Error
      +
      + + + +
      +
      5xx Server Error
      +
      + + + +
      +
      +
      +
      +
    • +
    +
  • +
  • + + T + +
      +
    • +
      +
      target resource
      +
      + + + +
      +
      target URI
      +
      + + + +
      +
      TE header field
      +
      + + + +
      +
      TRACE method
      +
      + + + +
      +
      Trailer Fields
      +
      + + + +
      +
      +
      +
      +
      ETag
      +
      + + + +
      +
      +
      +
      Trailer header field
      +
      + + + +
      +
      trailer section
      +
      + + + +
      +
      trailers
      +
      + + + +
      +
      transforming proxy
      +
      + + + +
      +
      transparent proxy
      +
      + + + +
      +
      tunnel
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + U + +
      +
    • +
      +
      unsatisfiable range
      +
      + + + +
      +
      Upgrade header field
      +
      + + + +
      +
      upstream
      +
      + + + +
      +
      URI
      +
      + + + +
      +
      +
      +
      +
      origin
      +
      + + + +
      +
      +
      +
      URI reference
      +
      + + + +
      +
      URI scheme
      +
      +
      +
      +
      +
      http
      +
      + + + +
      +
      https
      +
      + + + +
      +
      +
      +
      user agent
      +
      + + + +
      +
      User-Agent header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + V + +
      +
    • +
      +
      validator
      +
      + + + +
      +
      +
      +
      +
      strong
      +
      + + + +
      +
      weak
      +
      + + + +
      +
      +
      +
      Vary header field
      +
      + + + +
      +
      Via header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + W + +
      +
    • +
      +
      WWW-Authenticate header field
      +
      + + + +
      +
      +
    • +
    +
  • +
  • + + X + +
      +
    • +
      +
      x-compress (content coding)
      +
      + + + +
      +
      x-gzip (content coding)
      +
      + + + +
      +
      +
    • +
    +
  • +
+
+
+ Authors' Addresses + + Adobe +
+ + 345 Park Ave + San Jose, CA 95110 + United States of America + + fielding@gbiv.com + https://roy.gbiv.com/ +
+
+ + Fastly +
+ + Prahran + Australia + + mnot@mnot.net + https://www.mnot.net/ +
+
+ + greenbytes GmbH +
+ + Hafenweg 16 + 48155 Münster + Germany + + julian.reschke@greenbytes.de + https://greenbytes.de/tech/webdav/ +
+
+
+
+ diff --git a/conformance/suite-rust/Cargo.lock b/conformance/suite-rust/Cargo.lock index 1fb439d..b0c0466 100644 --- a/conformance/suite-rust/Cargo.lock +++ b/conformance/suite-rust/Cargo.lock @@ -10,11 +10,11 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-rust" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] diff --git a/conformance/suite/Cargo.lock b/conformance/suite/Cargo.lock index 50dcff5..f22e752 100644 --- a/conformance/suite/Cargo.lock +++ b/conformance/suite/Cargo.lock @@ -10,7 +10,7 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "flowapi" -version = "0.2.0" +version = "0.3.0" [[package]] name = "flowapi-suite" @@ -23,7 +23,7 @@ dependencies = [ [[package]] name = "flowapi-ts" -version = "0.2.0" +version = "0.3.0" dependencies = [ "flowapi", ] diff --git a/conformance/triage-3.md b/conformance/triage-3.md new file mode 100644 index 0000000..69a4827 --- /dev/null +++ b/conformance/triage-3.md @@ -0,0 +1,178 @@ +# Triage, third pass: the SDK stage (2026-11-26) + +Why (the owner, 2026-11-26): «мы же должны детерминированно проверять, что мы следуем +спецификации официальной». The ledger (`ledger/`, O1, rule G13) held the texts a types generator +follows. flowapi now also prints an SDK: the SDK layer's table (`crates/flowapi-sdk`), its client +runtime (`crates/flowapi-sdk/src/client/core`) and the request writer O8 runs (`sdk/`). This pass +pins the texts that SDK follows, reads them, and decides the scope again for it. It adds no test: +markers were added only where an existing test already checks the id. Like `triage-2.md` it sits +beside `coverage/`, not in it (the workspace's settings deny reading `**/coverage/**`), and holds +no markers. + +Counts are `REPORT.md`'s; the ids no test names yet are in `MISSING.md`. Both are written by +`cargo run --release --bin report` in `ledger/`. + +## 1. The texts pinned + +`specs/SOURCE.md` has each file's source, date and SHA-256, and the licences. + +| Text | File | Read by | Ids | +| --- | --- | --- | ---: | +| OpenAPI 2.0 (Swagger), OAI commit `4f86429` | `openapi/2.0.md` | `markdown.rs` (tables without a leading `\|` now read) | 231 | +| RFC 6749, OAuth 2.0 | `rfc/rfc6749.txt` | `rfc_text.rs` (new) | 234 | +| RFC 6750, bearer tokens | `rfc/rfc6750.txt` | `rfc_text.rs` | 56 | +| RFC 7578, `multipart/form-data` | `rfc/rfc7578.txt` | `rfc_text.rs` | 19 | +| RFC 7617, Basic | `rfc/rfc7617.txt` | `rfc_text.rs` | 10 | +| RFC 9110, HTTP Semantics | `rfc/rfc9110.xml` (RFCXML v3) | `rfc_xml.rs` (new) | 412 | + +The four older RFCs have no XML at the RFC Editor, so their text is the copy. RFC 8414 is not +pinned: the client reads no authorization server metadata. The 3.x texts gave the same ids as +before, byte for byte (`extract`: 0 added, 0 removed). `tests/readers.rs` holds each reader to a +fixture. 18 RFC ids carry a `-2` suffix: the same six words open two sentences of one section. + +## 2. The scope, text by text + +`scope.json`'s `status` is now "decided 2026-11-24, the SDK stage 2026-11-26". Every rule whose +reason said "no data type", "run time", "Revisit at the SDK stage" or "the SDK stage's" was decided +again; an in-scope rule's `note` names the layer. No 3.x id moved out of scope. + +| Text | In scope before | In scope now | Out of scope | Covered | Lossy | Missing | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| OpenAPI 2.0 | (not pinned) | 128 | 103 | 59 | 0 | 69 | +| OpenAPI 3.0.4 | 131 | 186 | 243 | 120 | 17 | 49 | +| OpenAPI 3.1.2 | 146 | 184 | 252 | 148 | 2 | 34 | +| OpenAPI 3.2.1 | 141 | 225 | 297 | 141 | 6 | 78 | +| JSON Schema 2020-12 | 137 | 137 | 231 | 96 | 41 | 0 | +| RFC 6749 | — | 19 | 215 | 0 | 0 | 19 | +| RFC 6750 | — | 12 | 44 | 2 | 0 | 10 | +| RFC 7578 | — | 13 | 6 | 12 | 0 | 1 | +| RFC 7617 | — | 3 | 7 | 1 | 0 | 2 | +| RFC 9110 | — | 24 | 388 | 4 | 0 | 20 | +| **All** | 555 | 931 | 1786 | 583 | 66 | 282 | + +### OpenAPI 2.0 + +Explicit `oas-2.0.` rules, so that a 3.x rule decides no 2.0 id by accident; each id was read. + +| Section | Class | Layer or reason | +| --- | --- | --- | +| `swagger-object` (`swagger`, `paths`, `definitions`, `parameters`, `responses`, `consumes`, `produces`), the definitions, paths, path item, operation, parameter, items, header(s), response(s), schema and reference objects | in | The types: Swagger 2.0 read into the 3.x model (`spec/swagger.rs`), the `swagger20-*` cases of `flowapi-ts` | +| `host`, `basePath`, `schemes`, an operation's `schemes`, `securityDefinitions`, `security`, the security scheme and requirement objects | in | The SDK layer (`servers.rs`, `security.rs`), the cases `swagger20`, `swagger-host`, `swagger-nohost` | +| `tokenUrl`, `scopes`, the scopes object | in | The client runtime, which requests no token yet (section 3) | +| `authorizationUrl` | out | A grant that needs the resource owner: the caller runs it and gives the token | +| `info`, contact, license, tag, xml, external docs, example objects; `examples`; descriptions, summaries | out | Metadata, documentation and examples: no type or request depends on them | +| `allowEmptyValue` | out | A permission the client does not take | +| Each `x-` name, `swagger` being `"2.0"`, MIME types, path names, `type` values, `default` conforming, `operationId` unique, `readOnly` not required, `host` without a scheme | out | Rules for the author of a description | +| A Header Object's `collectionFormat` (decided 2026-11-26, the encoding pass) | out | A 2.0 Header Object is a response header's: the client parses no response header by its schema, as for 3.x's Header `style` and `explode` | +| A discriminator's value naming this schema or one that inherits it (same pass) | out | A rule for the author of a description | + +### OpenAPI 3.x + +| Section | Class | Layer or reason | +| --- | --- | --- | +| Servers at three levels, the Server and Server Variable Objects, 3.1's relative references in API URLs | in | The SDK layer (`servers.rs`); 3.0 and 3.2 now in whole, 3.1 was in by id | +| `components.securitySchemes`, `security`, the Security Scheme and Security Requirement Objects, 3.2's security schemes section, Appendix F | in | The SDK layer (`security.rs`) | +| `variables` default substitution, 3.2's `deprecated` scheme | in | The client runtime | +| OAuth Flows `clientCredentials`; OAuth Flow `tokenUrl`, `scopes` | in | The client runtime, which requests no token yet (section 3) | +| `implicit`, `password`, `authorizationCode`, `deviceAuthorization`, `authorizationUrl`, `deviceAuthorizationUrl` | out | A grant that needs the resource owner or a user agent: the caller runs it and gives the token, sent as a bearer token | +| `refreshUrl` | out | Refreshing is for the flows the caller runs; a client credentials grant has no refresh token (RFC 6749 4.4.3) | +| 3.2's `oauth2MetadataUrl` | out | The client reads no metadata (RFC 8414, not pinned) | +| The Encoding Object; `encoding`, `prefixEncoding`, `itemEncoding` and their sections; 3.2's non-JSON data | in | The multipart writer (`multipart.ts`, `encoding.rs`), O8 | +| Within them: keys that must exist, fields that exclude each other, `Content-Transfer-Encoding`, `schema` required | out | Rules for the author | +| Reading a multipart body by name; the additional encoding approaches; "not currently possible to correlate" | out | The client writes these bodies and reads none; permissions not taken | +| Header Object `style`, `explode`, its schema serialization, link headers, `Set-Cookie` | out | The client parses no response header by schema; a part's headers are the caller's strings | +| Header values passed through unchanged | in | The client runtime | +| Parameter `allowEmptyValue` | out | A deprecated permission not taken | +| `content` for cookies and headers (RECOMMENDED), schema serialization NOT RECOMMENDED | out | Rules for the author | +| Parsing parameters | out | The client writes parameters and parses none | +| Appendices C, D, the non-RFC 6570 combinations, the delimiters' and cookies' percent-encoding guidance | out | Guidance for a serializer built on an RFC 6570 library; the SDK writes each style by its own code (the parts O8 runs stay in by id) | +| Appendix E's statement, percent-encoding in form data, RFC 1738 interoperability, 3.2's cookie storage | out | Statements that ask nothing; the caller's data; the client stores no cookie | +| Interoperability with web browsers (WHATWG form rules) | in | O8 | +| Links, callbacks, webhooks | out | The client follows no links and only sends the described operations | +| Discriminator selection, publishing and run-time handling | out | Reworded: the client returns a body as parsed and checks no value | + +### The RFCs + +| Text | In scope | Out of scope, and why | +| --- | --- | --- | +| RFC 6749 | The client credentials grant (2.3 one method, 2.3.1 Basic and no body credentials in the URI, 3.2 POST and parameters once, 3.2.1, 4.4.2, 5.1 unknown names ignored, Appendix B's encoding, 10.3 minimal scope), and using a token (7.1, 10.3, 10.8) | The authorization and resource servers; the grants a user agent runs, refresh, native apps; registration, extensions, IANA; TLS (10.9) is the platform's fetch | +| RFC 6750 | Sending a bearer token: the Authorization header, one method, never a query, a page URL or a cookie, safeguarded, over TLS; 3.1's retry with a new token | The resource server's challenges and errors; the form and query methods, which the client never uses; certificate validation | +| RFC 7617 | No control characters in user-id or password; sent up front; not without TLS | The recipient, the challenge's parameters, protection spaces, proxies | +| RFC 7578 | The boundary, Content-Disposition and its name and filename, no `filename*`, one part per file, Content-Type, no Content-Transfer-Encoding, no other header fields, UTF-8, no coalescing, order kept | Receivers, form creators, intermediaries; two permissions not taken (percent-encoded names, `charset`) | +| RFC 9110 | No userinfo in a URI, a Content-Type for content, CRLF in a multipart body, retries (9.2.2), no content in GET, HEAD, DELETE, a Content-Type with OPTIONS content, the status classes, redirects (15.4, 301 to 308, the Location fragment), 401 and 408 | What the platform's fetch does (URIs, framing, fields, connections, TLS, 1xx), servers, intermediaries and caches; fields the client never sends of its own (Expect, User-Agent, Accept-*, If-*, Range); challenges; CONNECT and TRACE, which fetch refuses; 300 and 304; extending HTTP | + +## 3. What the decisions found + +- **OAuth client credentials.** `clientCredentials`, `tokenUrl`, `scopes` and RFC 6749's 4.4 rows + are in scope, and the client does not do them: `auth.ts` sends the token the caller gives as + a bearer token and requests none. They are the work list of the client's OAuth step (19 of RFC + 6749's 19 missing ids, 7 per 3.x version under `oauth-flow-object`). +- **RFC 7578 4.8 against OpenAPI.** "Other header fields MUST NOT be included" in a part, while + the Encoding Object's `headers` describe exactly such fields and the writer sends them. The + owner's decision (2026-11-26): flowapi follows OpenAPI, and the id is lossy with that reason + (the O8 case on a part's header values written as given). +- **The encoding pass (2026-11-26).** The Encoding Object, `prefixEncoding`, `itemEncoding`, + nesting, 3.2's non-JSON data and Appendix E's browser interoperability are covered by O8 cases + and the table's cases (`encoding*.json`, `swagger-forms.json`). A form body written from its + content (no `style`) is percent-encoded by the WHATWG rules 3.2 asks for (space as `+`, `!'()~` + encoded); one written by `style` keeps RFC 3986's. Swagger 2.0's `formData` `collectionFormat` + is read into the table as a style (`tsv` as the SDK's own `tabDelimited`). Left missing: a + parameter's `collectionFormat` in query, path and header beyond csv, ssv, pipes and multi, and + the Items Object's, which need a tab-delimited style and 2.0's delimited styles outside the + query in the core's `spec/operations/style.rs`, at its line budget (G10). Both closed the same + day: room made in the core by merging duplicated code, then `tabDelimited` and the delimited + styles in a path and a header, and `Serialization::nested` for the Items Object (O8 cases, + `crates/flowapi/tests/collection_format.rs`). +- **TLS and the mock.** RFC 6749 10.3, RFC 6750 5.3 and RFC 7617 4 ask that credentials go only + over TLS. The client sends them to whatever base URL it is given, including the mock at + `http://localhost`. A refusal of `http:` except for a loopback host would answer them; until a + test holds that, they stay missing. +- **Retries.** RFC 9110 9.2.2: a client SHOULD NOT retry a non-idempotent method on its own, nor + retry a failed retry. `retry.ts` retries any method on 408, 409, 429 and 5xx, up to + `maxRetries` (2 by default). Both ids are missing, and as written the client goes against + the first unless the server asks (`x-should-retry`). Next: a test that states the policy, then + either the change or a lossy marker with the reason. +- **Retry-After.** RFC 9110 10.2.3 states no BCP 14 sentence, so it has no id; the client's + reading of it is held by its own tests (R4) only. +- **3.0 and 3.2's servers and security.** The second pass had put only the 3.1 ids the table's + cases named in scope. The whole objects are in now, so 3.0's and 3.2's servers and security ids + are missing until their cases name them (the table reads all three versions alike). +- **The client's tests are markers now.** `.mjs` files are scanned, so `tests/client/*.mjs` can + name what they hold; this pass marked only what a test already asserts (R5's 408, R34's 303 and + its cross-origin refusal, the bearer, basic and server-variable tests in `auth.mjs`). + +## 4. Next + +A test for each missing id, or a lossy marker with its reason, in the order: the OAuth client +credentials step, the TLS rule with the mock's exception, the retry policy, then 3.0 and 3.2's +cases of the SDK table and Swagger 2.0's validation keywords. `MISSING.md` lists them by section. + +## 5. Servers and HTTP, the tests (2026-11-26) + +Every in-scope id on servers and on RFC 9110 outside section 11 now has a test that checks it: +56 ids, 14 of OpenAPI 3.0.4, 5 of 3.1.2, 17 of 3.2.1 and 20 of RFC 9110. The SDK table's cases +`servers30.json` and `servers32.json` read 3.0 and 3.2's servers as `servers.json` reads 3.1's (an +`x-` member of a Server or Server Variable Object read by no one), and `tests/table.rs` holds a +Server Object of another document, its relative URL written from the first. Two client cases, +`hosts` (3.2) and `edge` (3.1), hold the runtime in `tests/client/servers.mjs` (R43 to R45: a +URL with a user, a variable's value against its `enum`, a relative URL resolved against +`descriptionURL`) and `tests/client/http.mjs` (R46 to R55: retries, idempotency keys, status +classes, redirects, content by method). + +What the section 3 findings became, by the owner's decisions (delegated): + +- **Retries** (9.2.2). A request whose method is not idempotent is not retried on its own + unless the server answers `x-should-retry: true` or it carries an idempotency key (the config's + `defaults.idempotency_key` names the header; each call sends one random key, the same on its + retries). The default `retries` is 1, so a failed retry is not retried; a larger value is the + config's or the caller's explicit choice. A 403 is never retried (15.5.4). +- **Redirects** (15.4). Every 3xx with a `Location` is followed but 304, 305 and 306: 303 as a GET + with no content, 301 and 302 turn a POST into a GET as browsers do (the permission of 15.4.2 + and 15.4.3 taken), the rest keep the method and the content (15.4.8 holds 307 to it). A loop is + refused at once, a chain after 20, and a `Location` without a fragment keeps the request's + (10.2.2). + +One scope change: `rfc9110.15.4.1.may-user-agent-use-location-field-value` (a 300's `Location` +used for automatic redirection) is in scope now, as the client follows a 300 with a `Location` +like a 3xx no one defines (15.4 allows both); the other ids of 15.4.1 stay out, their reason +corrected (the client makes no choice from a 300's list). No lossy marker was added. diff --git a/crates/flowapi-cli/src/generate.rs b/crates/flowapi-cli/src/generate.rs index 449007e..b9265d3 100644 --- a/crates/flowapi-cli/src/generate.rs +++ b/crates/flowapi-cli/src/generate.rs @@ -91,7 +91,9 @@ fn generate(config: &str, out: &str) -> Result<(flowapi_sdk::Repo, Option) .get(at.doc.index()) .map_or_else(|| docs.describe(at), |s| s.describe(at.offset)) }; - for d in diags.all().iter().filter(|d| d.severity == Severity::Error) { + // The core's warnings too: they say how the description's operations are read (a form + // field's `collectionFormat`, a parameter's `style`), which the SDK layer takes from it. + for d in diags.all() { eprintln!("{d}\n at {}", describe(d.at)); } let program = program.ok_or_else(|| format!("flowapi: {spec} cannot be read into types"))?; diff --git a/crates/flowapi-cli/tests/generate_warnings_cli.rs b/crates/flowapi-cli/tests/generate_warnings_cli.rs new file mode 100644 index 0000000..494f29b --- /dev/null +++ b/crates/flowapi-cli/tests/generate_warnings_cli.rs @@ -0,0 +1,67 @@ +//! `flowapi generate`'s warnings about the description, as the command prints them: each once. +//! A Swagger 2.0 form's `collectionFormat` is read by the core alone (`Media::encoding`), and the +//! SDK layer takes the form's encoding from it, so a format 2.0 does not have is reported once, +//! naming the field a `formData` parameter; an Items Object's, once too. + +use std::path::Path; +use std::process::Command; + +/// A form with an array field of an unknown format and one whose inner array says `multi`. +const SPEC: &str = r#"{ + "swagger": "2.0", + "info": { "title": "forms", "version": "1" }, + "host": "forms.example", + "paths": { "/tags": { "post": { + "operationId": "postTags", + "consumes": ["application/x-www-form-urlencoded"], + "parameters": [ + { "name": "odd", "in": "formData", "type": "array", "items": { "type": "string" }, + "collectionFormat": "commas" }, + { "name": "grid", "in": "formData", "type": "array", + "items": { "type": "array", "collectionFormat": "multi", "items": { "type": "string" } } } + ], + "responses": { "204": { "description": "done" } } + } } } +}"#; + +const CONFIG: &str = "version: 1 +spec: spec.json +package: { name: forms-sdk, client: Forms, license: MIT } +resources: + tags: + methods: + create: postTags +"; + +#[test] +fn a_form_fields_bad_collection_format_is_warned_of_once() { + let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("generate_warnings"); + drop(std::fs::remove_dir_all(&dir)); + std::fs::create_dir_all(&dir).expect("a scratch directory"); + std::fs::write(dir.join("spec.json"), SPEC).expect("written"); + std::fs::write(dir.join("flowapi-sdk.yml"), CONFIG).expect("written"); + let out = Command::new(env!("CARGO_BIN_EXE_flowapi")) + .args(["generate", "flowapi-sdk.yml", "--out", "sdk"]) + .current_dir(&dir) + .output() + .expect("the command runs"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{stderr}"); + assert_eq!( + stderr.matches("`collectionFormat` commas").count(), + 1, + "{stderr}" + ); + let named = "warning[swagger.collectionFormat]: `collectionFormat` commas is not one a \ + parameter in `formData` takes: written as `csv`\n at spec.json:10:"; + assert!(stderr.contains(named), "{stderr}"); + assert_eq!( + stderr.matches("`collectionFormat` multi").count(), + 1, + "{stderr}" + ); + assert!( + stderr.contains("`collectionFormat` multi is not one an Items Object takes"), + "{stderr}" + ); +} diff --git a/crates/flowapi-rust/src/sdk/expand.rs b/crates/flowapi-rust/src/sdk/expand.rs index 5235357..6fd00b0 100644 --- a/crates/flowapi-rust/src/sdk/expand.rs +++ b/crates/flowapi-rust/src/sdk/expand.rs @@ -3,10 +3,11 @@ //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -89,6 +90,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -135,6 +138,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -157,6 +170,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -194,10 +211,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -220,7 +237,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, diff --git a/crates/flowapi-rust/src/sdk/param.rs b/crates/flowapi-rust/src/sdk/param.rs index 77f8cc8..06a5ead 100644 --- a/crates/flowapi-rust/src/sdk/param.rs +++ b/crates/flowapi-rust/src/sdk/param.rs @@ -4,7 +4,7 @@ use super::{Field, bare, field, is_json, percent}; use crate::ident::literal; -use flowapi::spec::{Location, Param, Style}; +use flowapi::spec::{Location, Param, Serialization, Style}; use std::fmt::Write; /// The statements that write the path template filled, each `{name}` its parameter's value; @@ -125,43 +125,34 @@ pub(super) fn access(locs: &[(Field<'_>, Vec>)], p: &Param) -> Option< }) } +/// A form's members written by their Encoding Objects, as the runtime takes them: by a style +/// as a query parameter of that style, or as JSON for a JSON `contentType` alone; a member whose +/// `contentType` is another is written by the form's defaults, as one not listed. +pub(super) fn parts(encoding: &[(String, Serialization)]) -> String { + let mut out = String::from("&["); + for (name, s) in encoding { + let part = match &s.media_type { + Some(t) if is_json(t) => String::from("sdk::Part::Json"), + Some(_) => continue, + None => format!("sdk::Part::Style({})", style(s, Location::Query)), + }; + let _ = write!(out, "({}, {part}), ", literal(name)); + } + out.truncate(out.trim_end_matches(", ").len()); + out.push(']'); + out +} + /// The runtime call that writes one parameter's value `v`. pub(super) fn call(p: &Param, v: &str) -> String { let s = &p.serialization; let raw = p.location == Location::Header || s.style == Style::Cookie; - let shape = if s.media_type.is_some() { - match p.location { - Location::Query | Location::Cookie => "Form", - Location::Path | Location::Header | Location::QueryString => "Simple", - } - } else { - match s.style { - Style::Simple => "Simple", - Style::Label => "Label", - Style::Matrix => "Matrix", - Style::Form => "Form", - Style::SpaceDelimited => "SpaceDelimited", - Style::PipeDelimited => "PipeDelimited", - Style::DeepObject => "Deep", - Style::Cookie => "Cookie", - } - }; - let enc = if raw { - "Raw" - } else if s.allow_reserved { - "Reserved" - } else { - "Plain" - }; let name = literal(&if raw { p.name.clone() } else { percent(&p.name) }); - let style = format!( - "const {{ sdk::Style::new(sdk::Shape::{shape}, {}, sdk::Enc::{enc}) }}", - s.explode - ); + let style = style(s, p.location); let at = format!( ".map_err(sdk::at({}, {}))?", literal(p.location.name()), @@ -181,7 +172,7 @@ pub(super) fn call(p: &Param, v: &str) -> String { Location::QueryString => { let t = s.media_type.as_deref().unwrap_or("text/plain"); if bare(t) == "application/x-www-form-urlencoded" { - format!("sdk::form(&mut query, \"&\", {v}){at};") + format!("sdk::form(&mut query, \"&\", {v}, &[]){at};") } else { format!( "sdk::query_string(&mut query, &sdk::content({v}, {}){at});", @@ -191,3 +182,76 @@ pub(super) fn call(p: &Param, v: &str) -> String { } } } + +/// The constant of a value's style in `location`: its shape, `explode` and encoder (none for a +/// header and `style: cookie`, reserved expansion for `allowReserved`). A delimited style outside +/// a query (Swagger 2.0's path and header) is `simple` joined by its delimiter; the arrays inside +/// a 2.0 value are joined by their own, outermost first. +fn style(s: &Serialization, location: Location) -> String { + let raw = location == Location::Header || s.style == Style::Cookie; + let query = location == Location::Query; + let mut more = String::new(); + let shape = if s.media_type.is_some() { + match location { + Location::Query | Location::Cookie => "Form", + Location::Path | Location::Header | Location::QueryString => "Simple", + } + } else { + match s.style { + Style::Simple => "Simple", + Style::Label => "Label", + Style::Matrix => "Matrix", + Style::Form => "Form", + Style::SpaceDelimited if query => "SpaceDelimited", + Style::PipeDelimited if query => "PipeDelimited", + Style::TabDelimited if query => "TabDelimited", + Style::SpaceDelimited | Style::PipeDelimited | Style::TabDelimited => { + let _ = write!(more, ".joined({})", literal(delimiter(s.style, raw))); + "Simple" + } + Style::DeepObject => "Deep", + Style::Cookie => "Cookie", + } + }; + if !s.nested.is_empty() { + let joins: Vec = s + .nested + .iter() + .map(|&n| literal(delimiter(n, raw))) + .collect(); + let _ = write!(more, ".nested(&[{}])", joins.join(", ")); + } + let enc = if raw { + "Raw" + } else if s.allow_reserved { + "Reserved" + } else { + "Plain" + }; + format!( + "const {{ sdk::Style::new(sdk::Shape::{shape}, {}, sdk::Enc::{enc}){more} }}", + s.explode + ) +} + +/// What joins an unexploded array's items in a style: a comma, or a delimited style's +/// delimiter, percent-encoded unless the value is written raw (a header). +fn delimiter(style: Style, raw: bool) -> &'static str { + match (style, raw) { + (Style::SpaceDelimited, true) => " ", + (Style::SpaceDelimited, false) => "%20", + (Style::PipeDelimited, true) => "|", + (Style::PipeDelimited, false) => "%7C", + (Style::TabDelimited, true) => "\t", + (Style::TabDelimited, false) => "%09", + ( + Style::Simple + | Style::Label + | Style::Matrix + | Style::Form + | Style::DeepObject + | Style::Cookie, + _, + ) => ",", + } +} diff --git a/crates/flowapi-rust/src/sdk/request.rs b/crates/flowapi-rust/src/sdk/request.rs index 8218e9b..d7b3490 100644 --- a/crates/flowapi-rust/src/sdk/request.rs +++ b/crates/flowapi-rust/src/sdk/request.rs @@ -3,9 +3,10 @@ //! `body`, an enum of its media types. Each parameter is one call of the runtime with its style //! a constant: RFC 6570's operator (3.2, Appendix C), the encoder (none for headers and `style: //! cookie`, reserved expansion for `allowReserved`) and its name percent-encoded where it goes -//! into a URI. +//! into a URI. A form body is written with its members' Encoding Objects (`spec::Media::encoding`) +//! printed beside it, as the runtime's `sdk::Part`s. -use super::param::{access, call, path}; +use super::param::{access, call, parts, path}; use super::{Field, Op, bare, field, fields, is_json, type_of}; use crate::emit::Emitter; use crate::ident::{Taken, literal, pascal}; @@ -117,9 +118,10 @@ pub(super) fn write(e: &mut Emitter<'_, '_>, out: &mut String, op: &Op<'_>) { Kind::Json => { format!("(String::from({ct}), sdk::json_body(v).map_err(sdk::in_body)?)") } - Kind::Form => { - format!("(String::from({ct}), sdk::form_body(v).map_err(sdk::in_body)?)") - } + Kind::Form => format!( + "(String::from({ct}), sdk::form_body(v, {}).map_err(sdk::in_body)?)", + parts(&m.encoding) + ), Kind::Bytes => format!("(String::from({ct}), v.clone())"), Kind::Typed => String::from("(t.clone(), v.clone())"), }; diff --git a/crates/flowapi-rust/src/sdk/runtime.rs b/crates/flowapi-rust/src/sdk/runtime.rs index cd83e21..46d86e3 100644 --- a/crates/flowapi-rust/src/sdk/runtime.rs +++ b/crates/flowapi-rust/src/sdk/runtime.rs @@ -28,7 +28,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -39,6 +40,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -50,18 +52,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -73,6 +89,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -84,8 +101,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -133,15 +164,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -231,11 +271,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -245,10 +292,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } diff --git a/crates/flowapi-rust/src/sdk/write.rs b/crates/flowapi-rust/src/sdk/write.rs index ac825b5..1a4c919 100644 --- a/crates/flowapi-rust/src/sdk/write.rs +++ b/crates/flowapi-rust/src/sdk/write.rs @@ -1,8 +1,11 @@ //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -27,6 +30,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -41,6 +47,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -53,15 +65,52 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, } } + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), + } + } + + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); + } + self.text(at, t) + } + fn enc(&mut self, t: &str) { encode(self.out, t, self.s.enc); } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -79,6 +128,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -158,6 +233,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -176,9 +256,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } diff --git a/crates/flowapi-rust/tests/cases/swagger20-fields.rs b/crates/flowapi-rust/tests/cases/swagger20-fields.rs new file mode 100644 index 0000000..0a2264f --- /dev/null +++ b/crates/flowapi-rust/tests/cases/swagger20-fields.rs @@ -0,0 +1,510 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBounds { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parameters: Option, + pub responses: GetBoundsResponses, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsParameters { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub query: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub header: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsParametersQuery { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub n: Option, + #[serde(rename = "nEnum", default, skip_serializing_if = "Option::is_none")] + pub n_enum: Option, + #[serde(rename = "nAt", default, skip_serializing_if = "Option::is_none")] + pub n_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub s: Option, + #[serde(rename = "sEnum", default, skip_serializing_if = "Option::is_none")] + pub s_enum: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub a: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub big: Option>, + #[serde(rename = "aEnum", default, skip_serializing_if = "Option::is_none")] + pub a_enum: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub m: Option>>, + #[serde(rename = "mEnum", default, skip_serializing_if = "Option::is_none")] + pub m_enum: Option>, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub enum GetBoundsParametersQuerySEnum { + #[serde(rename = "bb")] + Bb, + #[serde(rename = "bc")] + Bc, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub enum GetBoundsParametersQueryAEnumItem { + #[serde(rename = "xy")] + Xy, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsParametersHeader { + #[serde(rename = "X-Limit", default, skip_serializing_if = "Option::is_none")] + pub x_limit: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsResponses { + #[serde(rename = "200")] + pub _200: GetBoundsResponses200, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsResponses200 { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub headers: Option, + pub content: GetBoundsResponses200Content, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsResponses200Headers { + #[serde(rename = "X-Count", default, skip_serializing_if = "Option::is_none")] + pub x_count: Option, + #[serde(rename = "X-Step", default, skip_serializing_if = "Option::is_none")] + pub x_step: Option, + #[serde(rename = "X-Name", default, skip_serializing_if = "Option::is_none")] + pub x_name: Option, + #[serde(rename = "X-Code", default, skip_serializing_if = "Option::is_none")] + pub x_code: Option, + #[serde(rename = "X-Mode", default, skip_serializing_if = "Option::is_none")] + pub x_mode: Option, + #[serde(rename = "X-Tags", default, skip_serializing_if = "Option::is_none")] + pub x_tags: Option>, + #[serde(rename = "X-Grid", default, skip_serializing_if = "Option::is_none")] + pub x_grid: Option>>, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub enum GetBoundsResponses200HeadersXCode { + Bb, + Bcd, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub enum GetBoundsResponses200HeadersXMode { + #[serde(rename = "fast")] + Fast, + #[serde(rename = "slow")] + Slow, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub enum GetBoundsResponses200HeadersXTagsItem { + #[serde(rename = "a")] + A, + #[serde(rename = "b")] + B, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct GetBoundsResponses200Content { + #[serde(rename = "application/xml")] + pub application_xml: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct OptionsBounds { + pub responses: OptionsBoundsResponses, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct OptionsBoundsResponses { + #[serde(rename = "204")] + pub _204: OptionsBoundsResponses204, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct OptionsBoundsResponses204 { +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct HeadBounds { + pub responses: HeadBoundsResponses, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct HeadBoundsResponses { + #[serde(rename = "200")] + pub _200: HeadBoundsResponses200, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct HeadBoundsResponses200 { +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PatchBounds { + #[serde(rename = "requestBody", default, skip_serializing_if = "Option::is_none")] + pub request_body: Option, + pub responses: PatchBoundsResponses, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PatchBoundsRequestBody { + #[serde(rename = "application/json")] + pub application_json: PatchBoundsRequestBodyApplicationJson, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct PatchBoundsRequestBodyApplicationJson { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub a: Option, + /// Every other property. + #[serde(flatten)] + pub extra: BTreeMap, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PatchBoundsResponses { + #[serde(rename = "200")] + pub _200: PatchBoundsResponses200, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PatchBoundsResponses200 { + pub content: PatchBoundsResponses200Content, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PatchBoundsResponses200Content { + #[serde(rename = "application/json")] + pub application_json: Integer, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutGlobal { + #[serde(rename = "requestBody", default, skip_serializing_if = "Option::is_none")] + pub request_body: Option, + pub responses: PutGlobalResponses, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutGlobalRequestBody { + #[serde(rename = "application/xml")] + pub application_xml: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutGlobalResponses { + #[serde(rename = "200")] + pub _200: PutGlobalResponses200, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutGlobalResponses200 { + pub content: PutGlobalResponses200Content, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutGlobalResponses200Content { + #[serde(rename = "application/xml")] + pub application_xml: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutAlias { + #[serde(rename = "requestBody", default, skip_serializing_if = "Option::is_none")] + pub request_body: Option, + pub responses: PutAliasResponses, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutAliasRequestBody { + #[serde(rename = "application/xml")] + pub application_xml: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutAliasResponses { + #[serde(rename = "200")] + pub _200: PutAliasResponses200, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutAliasResponses200 { + pub content: PutAliasResponses200Content, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PutAliasResponses200Content { + #[serde(rename = "application/xml")] + pub application_xml: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Paths { + #[serde(rename = "/bounds")] + pub bounds: PathsBounds, + #[serde(rename = "/global")] + pub global: PathsGlobal, + #[serde(rename = "/alias")] + pub alias: PathsAlias, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PathsBounds { + pub get: GetBounds, + pub options: OptionsBounds, + pub head: HeadBounds, + pub patch: PatchBounds, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PathsGlobal { + pub put: PutGlobal, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct PathsAlias { + pub put: PutAlias, +} + +/// A JSON integer: any number with no fraction, `1.0` and `1e20` among them. Exact from +/// `i64::MIN` to `u64::MAX`, the integers serde_json reads exactly; past those serde_json reads +/// a number as an `f64` (without its `arbitrary_precision` feature), so digits past 2^53 are lost +/// before the value gets here, and it is kept as that `f64`, a whole number still. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Integer(IntegerRepr); + +/// Canonical: a value from `i64::MIN` to `u64::MAX` is always `Exact`. +#[derive(Debug, Clone, Copy, PartialEq)] +enum IntegerRepr { + Exact(i128), + /// A whole `f64` below `i64::MIN` or above `u64::MAX`. + Wide(f64), +} + +impl Default for IntegerRepr { + fn default() -> Self { + Self::Exact(0) + } +} + +impl Integer { + /// The value, when an `i64` holds it. + pub fn as_i64(&self) -> Option { + match self.0 { + IntegerRepr::Exact(v) => i64::try_from(v).ok(), + IntegerRepr::Wide(_) => None, + } + } + + /// The value, when a `u64` holds it. + pub fn as_u64(&self) -> Option { + match self.0 { + IntegerRepr::Exact(v) => u64::try_from(v).ok(), + IntegerRepr::Wide(_) => None, + } + } + + /// The value, when an `i128` holds it (exact past `u64` only as far as the `f64` was). + pub fn as_i128(&self) -> Option { + match self.0 { + IntegerRepr::Exact(v) => Some(v), + // From -2^127 up to (not including) 2^127. + IntegerRepr::Wide(v) + if (-1.701_411_834_604_692_3e38..1.701_411_834_604_692_3e38).contains(&v) => + { + Some(v as i128) + } + IntegerRepr::Wide(_) => None, + } + } + + /// The nearest `f64`. + pub fn as_f64(&self) -> f64 { + match self.0 { + IntegerRepr::Exact(v) => v as f64, + IntegerRepr::Wide(v) => v, + } + } + + /// A whole, finite `f64` as an integer; `None` for a fraction, NaN or an infinity. + pub fn from_f64(v: f64) -> Option { + if !v.is_finite() || v.fract() != 0.0 { + return None; + } + // From -2^63 up to (not including) 2^64: what `i64` and `u64` hold together. + Some(Self( + if (-9_223_372_036_854_775_808.0..18_446_744_073_709_551_616.0).contains(&v) { + IntegerRepr::Exact(v as i128) + } else { + IntegerRepr::Wide(v) + }, + )) + } +} + +impl From for Integer { + fn from(value: i64) -> Self { + Self(IntegerRepr::Exact(i128::from(value))) + } +} + +impl From for Integer { + fn from(value: u64) -> Self { + Self(IntegerRepr::Exact(i128::from(value))) + } +} + +impl From for Integer { + fn from(value: i32) -> Self { + Self(IntegerRepr::Exact(i128::from(value))) + } +} + +impl From for Integer { + fn from(value: u32) -> Self { + Self(IntegerRepr::Exact(i128::from(value))) + } +} + +impl Eq for Integer {} + +impl Ord for Integer { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (self.0, other.0) { + (IntegerRepr::Exact(a), IntegerRepr::Exact(b)) => a.cmp(&b), + (IntegerRepr::Wide(a), IntegerRepr::Wide(b)) => a.total_cmp(&b), + // A wide value lies past every exact one, on its side of zero. + (IntegerRepr::Exact(_), IntegerRepr::Wide(b)) => { + if b > 0.0 { + Ordering::Less + } else { + Ordering::Greater + } + } + (IntegerRepr::Wide(a), IntegerRepr::Exact(_)) => { + if a > 0.0 { + Ordering::Greater + } else { + Ordering::Less + } + } + } + } +} + +impl PartialOrd for Integer { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl std::hash::Hash for Integer { + fn hash(&self, state: &mut H) { + match self.0 { + IntegerRepr::Exact(v) => v.hash(state), + IntegerRepr::Wide(v) => v.to_bits().hash(state), + } + } +} + +impl std::fmt::Display for Integer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.0 { + IntegerRepr::Exact(v) => write!(f, "{v}"), + IntegerRepr::Wide(v) => write!(f, "{v:.0}"), + } + } +} + +impl Serialize for Integer { + fn serialize(&self, serializer: S) -> Result { + match self.0 { + IntegerRepr::Exact(v) => match i64::try_from(v) { + Ok(i) => serializer.serialize_i64(i), + Err(_) => serializer.serialize_u64(u64::try_from(v).unwrap_or(u64::MAX)), + }, + IntegerRepr::Wide(v) => serializer.serialize_f64(v), + } + } +} + +impl<'de> Deserialize<'de> for Integer { + fn deserialize>(deserializer: D) -> Result { + struct Reader; + impl serde::de::Visitor<'_> for Reader { + type Value = Integer; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("an integer") + } + fn visit_i64(self, v: i64) -> Result { + Ok(Integer::from(v)) + } + fn visit_u64(self, v: u64) -> Result { + Ok(Integer::from(v)) + } + fn visit_i128(self, v: i128) -> Result { + match (i64::try_from(v), u64::try_from(v)) { + (Ok(i), _) => Ok(Integer::from(i)), + (_, Ok(u)) => Ok(Integer::from(u)), + _ => Ok(Integer(IntegerRepr::Wide(v as f64))), + } + } + fn visit_u128(self, v: u128) -> Result { + match u64::try_from(v) { + Ok(u) => Ok(Integer::from(u)), + Err(_) => Ok(Integer(IntegerRepr::Wide(v as f64))), + } + } + fn visit_f64(self, v: f64) -> Result { + Integer::from_f64(v).ok_or_else(|| E::custom("a number with a fraction")) + } + } + deserializer.deserialize_any(Reader) + } +} diff --git a/crates/flowapi-rust/tests/sdk/binary.rs b/crates/flowapi-rust/tests/sdk/binary.rs index 85cf924..fa7810b 100644 --- a/crates/flowapi-rust/tests/sdk/binary.rs +++ b/crates/flowapi-rust/tests/sdk/binary.rs @@ -122,7 +122,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -133,6 +134,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -144,18 +146,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -167,6 +183,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -178,8 +195,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -227,15 +258,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -325,11 +365,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -339,10 +386,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } @@ -575,9 +622,12 @@ impl Error { mod write { //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -602,6 +652,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -616,6 +669,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -628,7 +687,44 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, + } + } + + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), + } + } + + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); } + self.text(at, t) } fn enc(&mut self, t: &str) { @@ -636,7 +732,7 @@ impl<'a> W<'a> { } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -654,6 +750,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -733,6 +855,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -751,9 +878,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } @@ -799,10 +931,11 @@ mod expand { //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -885,6 +1018,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -931,6 +1066,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -953,6 +1098,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -990,10 +1139,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -1016,7 +1165,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, diff --git a/crates/flowapi-rust/tests/sdk/bodies.rs b/crates/flowapi-rust/tests/sdk/bodies.rs index 27b692e..ecc164e 100644 --- a/crates/flowapi-rust/tests/sdk/bodies.rs +++ b/crates/flowapi-rust/tests/sdk/bodies.rs @@ -6,6 +6,8 @@ use std::collections::BTreeMap; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct Pet { pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tags: Option>, /// Every other property. #[serde(flatten)] pub extra: BTreeMap, @@ -205,7 +207,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -216,6 +219,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -227,18 +231,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -250,6 +268,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -261,8 +280,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -310,15 +343,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -408,11 +450,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -422,10 +471,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } @@ -658,9 +707,12 @@ impl Error { mod write { //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -685,6 +737,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -699,6 +754,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -711,15 +772,52 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, } } + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), + } + } + + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); + } + self.text(at, t) + } + fn enc(&mut self, t: &str) { encode(self.out, t, self.s.enc); } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -737,6 +835,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -816,6 +940,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -834,9 +963,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } @@ -882,10 +1016,11 @@ mod expand { //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -968,6 +1103,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -1014,6 +1151,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -1036,6 +1183,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -1073,10 +1224,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -1099,7 +1250,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, @@ -1474,7 +1625,7 @@ pub enum AddPetBody { pub fn add_pet_request(input: &AddPetInput) -> Result { let body = Some(match &input.body { AddPetBody::ApplicationJson(v) => (String::from("application/json"), sdk::json_body(v).map_err(sdk::in_body)?), - AddPetBody::ApplicationXWwwFormUrlencoded(v) => (String::from("application/x-www-form-urlencoded"), sdk::form_body(v).map_err(sdk::in_body)?), + AddPetBody::ApplicationXWwwFormUrlencoded(v) => (String::from("application/x-www-form-urlencoded"), sdk::form_body(v, &[("name", sdk::Part::Json), ("tags", sdk::Part::Style(const { sdk::Style::new(sdk::Shape::PipeDelimited, false, sdk::Enc::Plain) }))]).map_err(sdk::in_body)?), AddPetBody::MultipartFormData(t, v) => (t.clone(), v.clone()), AddPetBody::Text(t, v) => (t.clone(), v.clone()), }); diff --git a/crates/flowapi-rust/tests/sdk/multipart.rs b/crates/flowapi-rust/tests/sdk/multipart.rs index f168574..1143b85 100644 --- a/crates/flowapi-rust/tests/sdk/multipart.rs +++ b/crates/flowapi-rust/tests/sdk/multipart.rs @@ -371,7 +371,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -382,6 +383,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -393,18 +395,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -416,6 +432,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -427,8 +444,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -476,15 +507,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -574,11 +614,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -588,10 +635,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } @@ -824,9 +871,12 @@ impl Error { mod write { //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -851,6 +901,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -865,6 +918,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -877,7 +936,44 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, + } + } + + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), + } + } + + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); } + self.text(at, t) } fn enc(&mut self, t: &str) { @@ -885,7 +981,7 @@ impl<'a> W<'a> { } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -903,6 +999,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -982,6 +1104,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -1000,9 +1127,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } @@ -1048,10 +1180,11 @@ mod expand { //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -1134,6 +1267,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -1180,6 +1315,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -1202,6 +1347,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -1239,10 +1388,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -1265,7 +1414,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, diff --git a/crates/flowapi-rust/tests/sdk/names.rs b/crates/flowapi-rust/tests/sdk/names.rs index a354166..8f5a1ae 100644 --- a/crates/flowapi-rust/tests/sdk/names.rs +++ b/crates/flowapi-rust/tests/sdk/names.rs @@ -372,7 +372,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -383,6 +384,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -394,18 +396,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -417,6 +433,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -428,8 +445,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -477,15 +508,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -575,11 +615,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -589,10 +636,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } @@ -825,9 +872,12 @@ impl Error { mod write { //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -852,6 +902,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -866,6 +919,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -878,7 +937,44 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, + } + } + + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), + } + } + + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); } + self.text(at, t) } fn enc(&mut self, t: &str) { @@ -886,7 +982,7 @@ impl<'a> W<'a> { } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -904,6 +1000,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -983,6 +1105,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -1001,9 +1128,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } @@ -1049,10 +1181,11 @@ mod expand { //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -1135,6 +1268,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -1181,6 +1316,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -1203,6 +1348,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -1240,10 +1389,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -1266,7 +1415,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, diff --git a/crates/flowapi-rust/tests/sdk/styles.rs b/crates/flowapi-rust/tests/sdk/styles.rs index 75a4a2e..51b8476 100644 --- a/crates/flowapi-rust/tests/sdk/styles.rs +++ b/crates/flowapi-rust/tests/sdk/styles.rs @@ -430,7 +430,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -441,6 +442,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -452,18 +454,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -475,6 +491,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -486,8 +503,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -535,15 +566,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -633,11 +673,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -647,10 +694,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } @@ -883,9 +930,12 @@ impl Error { mod write { //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -910,6 +960,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -924,6 +977,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -936,7 +995,44 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, + } + } + + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), + } + } + + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); } + self.text(at, t) } fn enc(&mut self, t: &str) { @@ -944,7 +1040,7 @@ impl<'a> W<'a> { } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -962,6 +1058,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -1041,6 +1163,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -1059,9 +1186,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } @@ -1107,10 +1239,11 @@ mod expand { //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -1193,6 +1326,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -1239,6 +1374,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -1261,6 +1406,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -1298,10 +1447,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -1324,7 +1473,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, @@ -1727,7 +1876,7 @@ pub fn search_request(input: &SearchInput) -> Result>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tsv: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grid: Option>>>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] @@ -45,6 +47,12 @@ pub struct ListPetsParametersQuery { pub struct ListPetsParametersHeader { #[serde(rename = "X-Ids", default, skip_serializing_if = "Option::is_none")] pub x_ids: Option>, + #[serde(rename = "X-Words", default, skip_serializing_if = "Option::is_none")] + pub x_words: Option>, + #[serde(rename = "X-Tabs", default, skip_serializing_if = "Option::is_none")] + pub x_tabs: Option>, + #[serde(rename = "X-Many", default, skip_serializing_if = "Option::is_none")] + pub x_many: Option>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] @@ -99,6 +107,8 @@ pub struct AddPetRequestBody { #[serde(deny_unknown_fields)] pub struct AddPetRequestBodyApplicationXWwwFormUrlencoded { pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tags: Option>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] @@ -356,7 +366,8 @@ pub trait Response { } /// How a style writes a value: RFC 6570's operator (`first`, `sep`, `named`, `ifemp`; 3.2, -/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`) and the encoder. +/// Appendix C), `explode`, what joins an unexploded list (`,`, `%20`, `%7C`, `%09`) and the +/// encoder; `nest`, Swagger 2.0's, what joins the lists inside a list, outermost first. #[derive(Clone, Copy, Debug)] pub struct Style { pub first: &'static str, @@ -367,6 +378,7 @@ pub struct Style { pub join: &'static str, pub enc: Enc, pub shape: Shape, + pub nest: &'static [&'static str], } /// The styles, by what they write. @@ -378,18 +390,32 @@ pub enum Shape { Form, SpaceDelimited, PipeDelimited, + TabDelimited, Cookie, Deep, } /// What a value's text is written as: RFC 3986 percent-encoding of all but the unreserved /// characters; that with the reserved ones and percent-encoded triples kept (`allowReserved`); -/// or as it is (headers and `style: cookie`, 3.2 Appendix D). +/// as it is (headers and `style: cookie`, 3.2 Appendix D); or by WHATWG's +/// `application/x-www-form-urlencoded` rules, all but the letters, digits and `*-._` encoded and +/// a space as `+` (a form's content, 3.2 Appendix E). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Enc { Plain, Reserved, Raw, + Form, +} + +/// How a form member is written where its Encoding Object says (the description's, printed with +/// each operation): by a style, as a query parameter of that style named by its key (any of +/// `style`, `explode` and `allowReserved` written; 3.2, "Encoding Usage and Restrictions"), or as +/// its JSON (a JSON `contentType` alone). A member not listed is written by the form's defaults. +#[derive(Clone, Copy, Debug)] +pub enum Part { + Style(Style), + Json, } impl Style { @@ -401,6 +427,7 @@ impl Style { Shape::Form | Shape::Deep => ("", "&", true, true, ","), Shape::SpaceDelimited => ("", "&", true, true, "%20"), Shape::PipeDelimited => ("", "&", true, true, "%7C"), + Shape::TabDelimited => ("", "&", true, true, "%09"), Shape::Cookie => ("", "; ", true, true, ","), }; Self { @@ -412,8 +439,22 @@ impl Style { join, enc, shape, + nest: &[], } } + + /// The style with an unexploded list joined by `join` (Swagger 2.0's delimited formats in + /// a path or a header). + pub const fn joined(mut self, join: &'static str) -> Self { + self.join = join; + self + } + + /// The style with the lists inside a list joined by `nest`, outermost first. + pub const fn nested(mut self, nest: &'static [&'static str]) -> Self { + self.nest = nest; + self + } } const HEX: &[u8; 16] = b"0123456789ABCDEF"; @@ -461,15 +502,24 @@ pub fn encode(out: &mut String, t: &str, enc: Enc) { && b == b'%' && bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit) && bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit); - if unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple { + let kept = if enc == Enc::Form { + b.is_ascii_alphanumeric() || matches!(b, b'*' | b'-' | b'.' | b'_') + } else { + unreserved(b) || (enc == Enc::Reserved && reserved(b)) || triple + }; + if kept { i += if triple { 3 } else { 1 }; continue; } // `run..i` is ASCII up to a character's start: never cut inside one. out.push_str(t.get(run..i).unwrap_or("")); - out.push('%'); - out.push(char::from(HEX[usize::from(b >> 4)])); - out.push(char::from(HEX[usize::from(b & 15)])); + if enc == Enc::Form && b == b' ' { + out.push('+'); + } else { + out.push('%'); + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 15)])); + } i += 1; run = i; } @@ -559,11 +609,18 @@ fn after_dot(p: &str) -> Option<&str> { /// A value as `application/x-www-form-urlencoded`, after `sep` when `out` holds something: /// each member a pair, a list's items pairs of the same key, an object member as JSON, `null` -/// an empty value (the Encoding Object's defaults). NaN or an infinity is refused. -pub fn form(out: &mut String, sep: &str, v: &T) -> Result<(), Reason> { +/// an empty value (the Encoding Object's defaults), encoded by WHATWG's rules; a member `parts` +/// names by its [`Part`]. NaN or an infinity is refused. +pub fn form( + out: &mut String, + sep: &str, + v: &T, + parts: &[(&str, Part)], +) -> Result<(), Reason> { let lead = if out.is_empty() { "" } else { sep }; - let s = Style::new(Shape::Form, true, Enc::Plain); + let s = Style::new(Shape::Form, true, Enc::Form); let mut w = write::W::new(out, lead, "", s); + w.parts = parts; match v.serialize(expand::Ser { w: &mut w, at: write::At::Form, @@ -573,10 +630,10 @@ pub fn form(out: &mut String, sep: &str, v: &T) -> Result } } -/// A form body's bytes. -pub fn form_body(v: &T) -> Result, Reason> { +/// A form body's bytes, its members by `parts` where named. +pub fn form_body(v: &T, parts: &[(&str, Part)]) -> Result, Reason> { let mut out = String::new(); - form(&mut out, "&", v)?; + form(&mut out, "&", v, parts)?; Ok(out.into_bytes()) } @@ -809,9 +866,12 @@ impl Error { mod write { //! What one parameter's expansion writes, piece by piece: the places a value can sit //! ([`At`]) and the state of one expansion ([`W`]), RFC 6570's rules for each (§3.2.1, 3.2 -//! Appendix C). Printed inside the generated `sdk` module beside `expand`, its serde half. +//! Appendix C); a form member its Encoding Object names, by its [`Part`]. Printed inside the +//! generated `sdk` module beside `expand`, its serde half. -use super::{Shape, Style, encode}; +use super::expand::{Error, Ser}; +use super::{Enc, Part, Shape, Style, encode}; +use serde::Serialize; /// Where a value sits, which says what each of its kinds writes. #[derive(Clone, Copy, PartialEq, Eq)] @@ -836,6 +896,9 @@ pub(super) enum At { FormItem, /// What writes nothing: a `deepObject` that is not an associative array. Ignore, + /// An item of a list inside the parameter's list, that many levels down from the first + /// (Swagger 2.0's Items Object): joined by `Style::nest` at its level. + Nest(usize), } /// The state of one expansion. @@ -850,6 +913,12 @@ pub(super) struct W<'a> { pub(super) n: usize, pub(super) key: String, pub(super) path: String, + /// Whether the list inside a list being written has no item yet. + pub(super) fresh: bool, + /// A form's members its Encoding Objects say how to write, by key. + pub(super) parts: &'a [(&'a str, Part)], + /// Whether the form member being written is JSON: a string is then its JSON text. + pub(super) json: bool, } impl<'a> W<'a> { @@ -862,15 +931,52 @@ impl<'a> W<'a> { n: 0, key: String::new(), path: String::new(), + fresh: false, + parts: &[], + json: false, + } + } + + /// The [`Part`] of the form member whose key is in `key`, where its Encoding Object says. + pub(super) fn part(&self) -> Option { + let key = self.key.as_str(); + self.parts.iter().find(|(k, _)| *k == key).map(|&(_, p)| p) + } + + /// A form member written by style `s`, as a query parameter of that style named by its key + /// percent-encoded (RFC 3986, as a query's): after `&` unless it is the form's first piece. + pub(super) fn styled(&mut self, s: Style, v: &T) -> Result<(), Error> { + let mut name = String::new(); + encode(&mut name, &self.key, Enc::Plain); + let lead = if self.n == 0 { self.lead } else { "&" }; + let mut w = W::new(&mut *self.out, lead, &name, s); + match v.serialize(Ser { + w: &mut w, + at: At::Top, + }) { + Ok(wrote) => { + self.n += usize::from(wrote); + Ok(()) + } + Err(Error::NonFinite) => Err(Error::NonFinite), + Err(Error::Compound | Error::Custom(_)) => Ok(()), } } + /// A string's text; in a form member written as JSON, its JSON text. + pub(super) fn string(&mut self, at: At, t: &str) -> bool { + if self.json && matches!(at, At::FormMember | At::FormItem) { + return self.text(at, &serde_json::to_string(t).unwrap_or_default()); + } + self.text(at, t) + } + fn enc(&mut self, t: &str) { encode(self.out, t, self.s.enc); } /// Before the first piece: the lead, the operator's prefix, `name=` where it opens the list. - fn open(&mut self, list_named: bool) { + pub(super) fn open(&mut self, list_named: bool) { if self.n == 0 { self.out.push_str(self.lead); self.out.push_str(self.s.first); @@ -888,6 +994,32 @@ impl<'a> W<'a> { self.n += 1; } + /// A list inside a list opened: as an item of the parameter's list (`d` none, `name=` before + /// it where each item is a pair), or of the list at level `d`. Its items are a level down. + pub(super) fn nest(&mut self, d: Option) -> At { + match d { + None => { + self.open(true); + if self.s.explode && self.s.named { + self.out.push_str(self.name); + self.out.push('='); + } + } + Some(d) => self.join_nested(d), + } + self.fresh = true; + At::Nest(d.map_or(0, |d| d + 1)) + } + + /// Before an item of the list at level `d`: its join, unless it is the list's first. + fn join_nested(&mut self, d: usize) { + if !self.fresh { + let join = self.s.nest.get(d).copied().unwrap_or(","); + self.out.push_str(join); + } + self.fresh = false; + } + /// `name`, then `=` and the value, or for an empty value what the operator writes then. fn named(&mut self, key_is_name: bool, t: &str, empty_ok: bool) { if key_is_name { @@ -967,6 +1099,11 @@ impl<'a> W<'a> { self.key.push_str(t); true } + At::Nest(d) => { + self.join_nested(d); + self.enc(t); + true + } At::Ignore => false, } } @@ -985,9 +1122,14 @@ impl<'a> W<'a> { true } At::FormMember | At::FormItem => self.text(at, ""), - At::Item | At::Member | At::Deep | At::DeepItem | At::Key | At::Form | At::Ignore => { - false - } + At::Item + | At::Member + | At::Deep + | At::DeepItem + | At::Key + | At::Form + | At::Ignore + | At::Nest(_) => false, } } } @@ -1033,10 +1175,11 @@ mod expand { //! crate has no serde). A value is one of RFC 6570's four (§2.3): `null`, a string (a number or //! boolean as its text), a list (a sequence), or an associative array (a map or a struct, its //! members in the order they are serialized). An item or member that is itself a list or an -//! associative array is its JSON text. The `form` modes write `application/x-www-form-urlencoded`. +//! associative array is its JSON text, but for a list in a list that Swagger 2.0's Items Object +//! joins (`Style::nest`). The `form` modes write `application/x-www-form-urlencoded`. use super::write::{At, Digits, W}; -use super::{Shape, encode}; +use super::{Part, Shape, encode}; use serde::Serialize; use serde::ser; use std::fmt::{Display, Write as _}; @@ -1119,6 +1262,8 @@ impl<'w, 'a> Ser<'w, 'a> { (At::Deep, true) => At::Deep, (At::Form, true) => At::FormMember, (At::FormMember, false) => At::FormItem, + (At::Item, false) if !self.w.s.nest.is_empty() => self.w.nest(None), + (At::Nest(d), false) if d + 1 < self.w.s.nest.len() => self.w.nest(Some(d)), (At::Ignore, _) => At::Ignore, (At::Key, _) => return Err(Error::Custom(String::from("a key that is not a string"))), _ => return Err(Error::Compound), @@ -1165,6 +1310,16 @@ impl Many<'_, '_> { } fn member(&mut self, v: &T) -> Result<(), Error> { + if self.at == At::FormMember { + match self.w.part() { + Some(Part::Style(s)) => return self.w.styled(s, v), + Some(Part::Json) => self.w.json = true, + None => {} + } + let r = self.one(v); + self.w.json = false; + return r; + } if self.at != At::Deep { return self.one(v); } @@ -1187,6 +1342,10 @@ impl Many<'_, '_> { } fn end(self) -> bool { + // A list inside a list ended: the next item of the list around it is joined to it. + if matches!(self.at, At::Nest(_)) { + self.w.fresh = false; + } self.w.path.truncate(self.base); self.w.n > 0 } @@ -1224,10 +1383,10 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { Ok(self.w.text(self.at, if v { "true" } else { "false" })) } fn serialize_char(self, v: char) -> Result { - Ok(self.w.text(self.at, v.encode_utf8(&mut [0; 4]))) + Ok(self.w.string(self.at, v.encode_utf8(&mut [0; 4]))) } fn serialize_str(self, v: &str) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_bytes(self, v: &[u8]) -> Result { Ok(self.w.text(self.at, &String::from_utf8_lossy(v))) @@ -1250,7 +1409,7 @@ impl<'w, 'a> ser::Serializer for Ser<'w, 'a> { _: u32, v: &'static str, ) -> Result { - Ok(self.w.text(self.at, v)) + Ok(self.w.string(self.at, v)) } fn serialize_newtype_struct( self, @@ -1548,11 +1707,11 @@ pub fn list_pets_request(input: &ListPetsInput) -> Result = Vec::with_capacity(1); + let mut query = String::with_capacity(167); + let mut headers: Vec<(String, String)> = Vec::with_capacity(4); if let Some(v) = p.query.as_ref().and_then(|l| l.csv.as_ref()) { sdk::put(&mut query, "&", "csv", const { sdk::Style::new(sdk::Shape::Form, false, sdk::Enc::Plain) }, v).map_err(sdk::at("query", "csv"))?; } @@ -1566,11 +1725,23 @@ pub fn list_pets_request(input: &ListPetsInput) -> Result Result (String::from("application/x-www-form-urlencoded"), sdk::form_body(v).map_err(sdk::in_body)?), + AddPetBody::ApplicationXWwwFormUrlencoded(v) => (String::from("application/x-www-form-urlencoded"), sdk::form_body(v, &[("tags", sdk::Part::Style(const { sdk::Style::new(sdk::Shape::PipeDelimited, false, sdk::Enc::Plain) }))]).map_err(sdk::in_body)?), }); Ok(sdk::Request { method: "POST", @@ -1679,4 +1850,4 @@ pub fn add_pet_response(status: u16, headers: &[(String, String)], body: &[u8]) _ => Err(sdk::Error::new(status, ct, body, sdk::ErrorKind::Status)), } } -// warning[swagger.collectionFormat]: `collectionFormat` tsv has no 3.x style in `query`: written as `csv` +// warning[swagger.collectionFormat]: `collectionFormat` multi is not one a parameter in `header` takes: written as `csv` diff --git a/crates/flowapi-sdk/src/client.rs b/crates/flowapi-sdk/src/client.rs index 0157eb6..61ea950 100644 --- a/crates/flowapi-sdk/src/client.rs +++ b/crates/flowapi-sdk/src/client.rs @@ -4,12 +4,16 @@ //! `src/core/*.ts` the runtime, the same for every API (`client/core/`, printed as written); //! `src/client.ts` the client class the config names, its settings and its options; and //! `src/resources/**.ts` a class per resource of the config's tree, each method calling its -//! operation through the runtime (`client/resources.rs`). No I/O (G5): the files are returned. +//! operation through the runtime (`client/resources.rs`). The operations table and the client +//! are printed from the description's service with the config's credentials over it +//! ([`service`]). No I/O (G5): the files are returned. -mod entry; +mod comment; +pub(crate) mod entry; pub(crate) mod resources; use crate::config::{Checked, Issue, checked, issue::Issues}; +use crate::model::Service; use crate::ops::Ops; use crate::words; use flowapi::{Diagnostics, Documents, File, Program, Severity, Target}; @@ -29,7 +33,9 @@ const CORE: &[(&str, &str)] = &[ ("request.ts", include_str!("client/core/request.ts")), ("retry.ts", include_str!("client/core/retry.ts")), ("send.ts", include_str!("client/core/send.ts")), + ("servers.ts", include_str!("client/core/servers.ts")), ("streaming.ts", include_str!("client/core/streaming.ts")), + ("token.ts", include_str!("client/core/token.ts")), ]; /// What [`client_files`] made. @@ -62,7 +68,7 @@ pub(crate) fn print( issues: Vec, checked: &Checked, ) -> Generated { - let (service, diagnostics) = crate::read(docs, program); + let (service, diagnostics) = service(docs, program, checked); let mut out = Generated { files: Vec::new(), diagnostics, @@ -84,21 +90,7 @@ pub(crate) fn print( out.files .push(file(&format!("src/core/{name}"), (*text).to_owned())); } - // Each method's endpoint in the program, by its route. - let endpoints: BTreeMap = program - .endpoints() - .iter() - .enumerate() - .map(|(i, e)| (route(&e.operation), i)) - .collect(); - let methods: Vec> = checked - .resolved - .iter() - .map(|r| { - r.and_then(|i| ops.list.get(i)) - .and_then(|op| endpoints.get(&route(&op.operation)).copied()) - }) - .collect(); + let methods = endpoints(program, &ops, checked); let mut issues = Issues::default(); let ctx = resources::Context { config: c, @@ -116,6 +108,39 @@ pub(crate) fn print( out } +/// Each method's endpoint in the program, by its operation's route. +fn endpoints(program: &Program<'_>, ops: &Ops<'_, '_>, checked: &Checked) -> Vec> { + let endpoints: BTreeMap = program + .endpoints() + .iter() + .enumerate() + .map(|(i, e)| (route(&e.operation), i)) + .collect(); + checked + .resolved + .iter() + .map(|r| { + r.and_then(|i| ops.list.get(i)) + .and_then(|op| endpoints.get(&route(&op.operation)).copied()) + }) + .collect() +} + +/// The service a config's client is printed from: the description's, with the schemes the +/// config declares and its `security` over the operations' (`config/auth.rs`). +pub(crate) fn service( + docs: &Documents<'_>, + program: &Program<'_>, + checked: &Checked, +) -> (Service, Diagnostics) { + let (mut service, diagnostics) = crate::read(docs, program); + if let Some(ops) = Ops::read(docs).0 { + let methods = endpoints(program, &ops, checked); + crate::config::auth::apply(&checked.config, &mut service, &methods); + } + (service, diagnostics) +} + fn file(path: &str, text: String) -> File { File { path: path.to_owned(), diff --git a/crates/flowapi-sdk/src/client/comment.rs b/crates/flowapi-sdk/src/client/comment.rs new file mode 100644 index 0000000..aa314c1 --- /dev/null +++ b/crates/flowapi-sdk/src/client/comment.rs @@ -0,0 +1,65 @@ +//! A method's doc comment, what an editor shows on hover: the operation's summary, its +//! description's paragraphs, its route, a link to its `externalDocs` and `@deprecated` where the +//! description marks it so; all plain text (`prose.rs`), since a hover shows Markdown its own way +//! and a description's HTML or links would show as markup. + +use super::doc; +use crate::ops::Op; +use crate::prose; +use std::fmt::Write as _; + +/// A paragraph as a line of a doc comment: no `*/` ends it, and an `@` that opens it is no tag. +fn line(text: &str) -> String { + let text = doc(text); + match text.strip_prefix('@') { + Some(rest) => format!("\\@{rest}"), + None => text, + } +} + +/// The comment of a method calling `op` (`None` when the method's operation is not found) by +/// `METHOD /path`, indented for a class member. +pub(crate) fn method(op: Option<&Op>, method: &str, path: &str) -> String { + let route = format!("`{method} {}`", doc(path)); + let mut lines: Vec = Vec::new(); + if let Some(op) = op { + let summary = op.summary.as_deref().map(prose::inline); + if let Some(s) = summary.as_ref().filter(|s| !s.is_empty()) { + lines.push(line(s)); + } + for p in op + .description + .as_deref() + .map(prose::paragraphs) + .unwrap_or_default() + { + if summary.as_deref() != Some(p.as_str()) { + lines.push(line(&p)); + } + } + } + let mut tags: Vec = Vec::new(); + if let Some((url, about)) = op.and_then(|o| o.external_docs.as_ref()) { + let about = about.as_deref().map(prose::inline).unwrap_or_default(); + let see = format!("@see {} {}", doc(url), doc(&about)); + tags.push(see.trim_end().to_owned()); + } + if op.is_some_and(|o| o.deprecated) { + tags.push(String::from( + "@deprecated The API's description marks this operation deprecated.", + )); + } + if lines.is_empty() && tags.is_empty() { + return format!(" /** {route} */\n"); + } + let mut out = String::from(" /**\n"); + for l in &lines { + let _ = writeln!(out, " * {l}\n *"); + } + let _ = writeln!(out, " * {route}"); + for t in &tags { + let _ = writeln!(out, " * {t}"); + } + out.push_str(" */\n"); + out +} diff --git a/crates/flowapi-sdk/src/client/core/auth.ts b/crates/flowapi-sdk/src/client/core/auth.ts index 3f8bdda..2971088 100644 --- a/crates/flowapi-sdk/src/client/core/auth.ts +++ b/crates/flowapi-sdk/src/client/core/auth.ts @@ -3,105 +3,212 @@ // Credentials attached by the operation's security, as the operations table gives it: a list of // alternatives, any one of which is enough, each naming the schemes it needs together. The first // alternative the client can meet is sent: every scheme in it has a credential (its option, else -// its environment variable) or is one the caller sends itself in `defaultHeaders`, `defaultQuery` +// its environment variables) or is one the caller sends itself in `defaultHeaders`, `defaultQuery` // or the call's `headers` and `query` (a `null` there too: that removes it). `security: []` sends -// nothing. A credential is checked when a call needs it, not when the client is made, so a client -// made at a module's top level does not fail where no key is set. +// nothing, and an empty alternative (`{}`) is met by nothing. A credential is checked when a call +// needs it, not when the client is made, so a client made at a module's top level does not fail +// where no key is set. Each kind: an API key in its header, query parameter or cookie; HTTP +// basic's pair, its UTF-8 in base64 (RFC 7617), a user-id without `:` and neither with a control +// character; a bearer token in `Authorization` alone (RFC 6750, 2.1), never in a query, a body or +// a cookie; another HTTP scheme's credential as given; a scheme that answers a challenge or signs +// each request (`digest`, ...) is never met by the client; OAuth 2.0 and OpenID Connect a bearer +// token, given, or requested by the client credentials flow (`token.ts`); mutual TLS met by +// `true`, its certificate the transport's. Credentials go only over TLS, or to a loopback host +// (`guard`, RFC 6749 10.3, RFC 6750 5.3, RFC 7617 4), held to the call's base URL before a +// credential is read or a token requested, so a call that would be refused costs no token request. -import { SdkError } from "./errors.js"; -import { base64, readEnv } from "./platform.js"; +import { CredentialError, InsecureCredentialError } from "./errors.js"; +import { base64, platform, readEnv } from "./platform.js"; +import { type ClientCredentials, type Tokens, flowKey } from "./token.js"; /** A credential: its value, or a function that gives it (called for each request). */ export type Credential = string | (() => string | Promise); -/** HTTP basic credentials. */ -export type BasicCredential = - | { readonly username: string; readonly password: string } - | (() => { readonly username: string; readonly password: string } | Promise<{ readonly username: string; readonly password: string }>); +/** HTTP basic's user-id and password. */ +export type BasicPair = { readonly username: string; readonly password: string }; + +/** HTTP basic credentials: the pair, `username:password`, or a function that gives either. */ +export type BasicCredential = BasicPair | string | (() => BasicPair | string | Promise); /** A security scheme, as the operations table's `flowapiSecuritySchemes` gives it. */ -export type SchemeEntry = { readonly type: string; readonly in?: string; readonly name?: string; readonly scheme?: string }; +export type SchemeEntry = { + readonly type: string; + readonly in?: string; + readonly name?: string; + readonly scheme?: string; + readonly clientCredentials?: { readonly tokenUrl: string; readonly scopes: readonly string[] }; +}; -/** Where the client finds a scheme's credential: its option and environment variable. */ -export type AuthSetting = { readonly option: string; readonly env?: string }; +/** Where the client finds a scheme's credential: its option and environment variables, and the + * scopes its tokens are requested with. */ +export type AuthSetting = { + readonly option: string; + readonly env?: string; + readonly usernameEnv?: string; + readonly passwordEnv?: string; + readonly clientIdEnv?: string; + readonly clientSecretEnv?: string; + readonly scopes?: readonly string[]; +}; -/** What the chosen alternative adds to a request. */ -export type Applied = { headers: Record; query: [string, string][]; cookies: string[] }; +/** What the chosen alternative adds to a request; `renew` forgets each token it requested. */ +export type Applied = { headers: Record; query: [string, string][]; cookies: string[]; renew: (() => void)[] }; /** What the caller sends itself: header names in lower case, query keys. */ export type Given = { readonly headers: ReadonlySet; readonly query: ReadonlySet }; -type Ready = (applied: Applied) => Promise; +/** What meeting a scheme needs of the client: its options, what the caller sends, its tokens, + * the base URL a relative token URL is resolved against, and `guard`, which throws when that URL + * may not carry a credential. */ +export type Context = { + readonly options: Record; + readonly given: Given; + readonly tokens: Tokens; + readonly base: string | null; + readonly guard: () => void; +}; + +/** HTTP schemes (IANA's registry) the client cannot send up front: each answers a challenge or + * signs each request. The generator's `CHALLENGED` holds the same names. */ +const CHALLENGED = ["concealed", "digest", "dpop", "hoba", "mutual", "negotiate", "oauth", "privatetoken", "scram-sha-1", "scram-sha-256"]; + +/** RFC 6750 2.1's `b64token`. */ +const B64TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/; + +/** RFC 5234's CTL. */ +const CTL = /[\u0000-\u001f\u007f]/; + +type Ready = (applied: Applied, scopes: readonly string[]) => Promise; + +/** A credential's value, its function called. */ +async function value(v: T | (() => T | Promise)): Promise { + return typeof v === "function" ? await (v as () => T | Promise)() : v; +} + +/** Where a scheme's credential is set, as an error names it. */ +function ways(s: AuthSetting): string { + const out = [`\`${s.option}\``]; + if (s.env !== undefined) out.push(s.env); + if (s.usernameEnv !== undefined && s.passwordEnv !== undefined) out.push(`${s.usernameEnv} with ${s.passwordEnv}`); + if (s.clientIdEnv !== undefined && s.clientSecretEnv !== undefined) out.push(`${s.clientIdEnv} with ${s.clientSecretEnv}`); + return out.join(" or "); +} + +/** A string with something in it, else a `CredentialError`. */ +function text(name: string, s: AuthSetting, v: unknown): string { + if (typeof v !== "string" || v.trim() === "") throw new CredentialError(`the credential of \`${name}\` (the option \`${s.option}\`) is not a string with something in it`, [name]); + if (CTL.test(v)) throw new CredentialError(`the credential of \`${name}\` holds a control character`, [name]); + return v; +} + +/** HTTP basic's header from a pair or `username:password`, held to RFC 7617 2. */ +function basic(name: string, v: unknown): string { + const pair = typeof v === "string" ? { username: v.slice(0, Math.max(0, v.indexOf(":"))), password: v.slice(v.indexOf(":") + 1) } : (v as BasicPair | null); + if (typeof v === "string" && !v.includes(":")) throw new CredentialError(`the HTTP basic credential of \`${name}\` is not \`username:password\``, [name]); + if (pair === null || typeof pair !== "object" || typeof pair.username !== "string" || typeof pair.password !== "string") { + throw new CredentialError(`the HTTP basic credential of \`${name}\` is not \`{ username, password }\``, [name]); + } + if (pair.username.includes(":")) throw new CredentialError(`the HTTP basic user-id of \`${name}\` holds \`:\`, which RFC 7617 does not allow`, [name]); + if (CTL.test(pair.username) || CTL.test(pair.password)) throw new CredentialError(`the HTTP basic credential of \`${name}\` holds a control character`, [name]); + return `Basic ${base64(`${pair.username}:${pair.password}`)}`; +} + +/** The client's id and secret: the option's object, else the two variables. */ +function clientOf(option: unknown, s: AuthSetting): ClientCredentials | undefined { + if (typeof option === "object" && option !== null) return option as ClientCredentials; + if (option !== undefined || s.clientIdEnv === undefined || s.clientSecretEnv === undefined) return undefined; + const clientId = readEnv(s.clientIdEnv); + const clientSecret = readEnv(s.clientSecretEnv); + return clientId === undefined || clientSecret === undefined ? undefined : { clientId, clientSecret }; +} -/** How one scheme is met; `null` when it cannot be. */ -function meet(name: string, s: SchemeEntry | undefined, setting: AuthSetting | undefined, options: Record, given: Given): Ready | null { - if (s === undefined) return null; - const http = s.type === "http" || s.type === "oauth2" || s.type === "openIdConnect"; - if (http && given.headers.has("authorization")) return async () => {}; - if (s.type === "apiKey" && s.name !== undefined) { - const own = s.in === "query" ? given.query.has(s.name) : s.in === "cookie" ? given.headers.has("cookie") : given.headers.has(s.name.toLowerCase()); - if (own) return async () => {}; +/** How one scheme is met; why not, as an error names it, when it cannot be. */ +function meet(name: string, sc: SchemeEntry | undefined, s: AuthSetting | undefined, ctx: Context): Ready | string { + if (sc === undefined) return `\`${name}\` (no security scheme has that name)`; + const http = sc.type === "http" || sc.type === "oauth2" || sc.type === "openIdConnect"; + const done = async (): Promise => {}; + if (http && ctx.given.headers.has("authorization")) return done; + if (sc.type === "apiKey" && sc.name !== undefined) { + const own = sc.in === "query" ? ctx.given.query.has(sc.name) : sc.in === "cookie" ? ctx.given.headers.has("cookie") : ctx.given.headers.has(sc.name.toLowerCase()); + if (own) return done; } - if (setting === undefined) return null; - const option = options[setting.option]; - if (option === null) return null; - const value = option ?? (setting.env === undefined ? undefined : readEnv(setting.env)); - if (value === undefined) return null; - const scheme = (s.scheme ?? "").toLowerCase(); - if (s.type === "http" && scheme === "basic") { + const scheme = (sc.scheme ?? "").toLowerCase(); + if (sc.type === "http" && CHALLENGED.includes(scheme)) return `\`${name}\` (HTTP ${scheme} answers a challenge: give \`Authorization\` in the call's \`headers\`)`; + if (s === undefined) return `\`${name}\` (the client sends no credential for it)`; + const option = ctx.options[s.option]; + if (option === null) return ways(s); + if (sc.type === "mutualTLS") return option === true ? done : `\`${s.option}\` (\`true\` when \`fetch\` presents the client certificate)`; + if (sc.type === "http" && scheme === "basic") { + const user = s.usernameEnv === undefined ? undefined : readEnv(s.usernameEnv); + const password = s.passwordEnv === undefined ? undefined : readEnv(s.passwordEnv); + const pair = user === undefined || password === undefined ? undefined : { username: user, password }; + const v = option ?? (s.env === undefined ? undefined : readEnv(s.env)) ?? pair; + if (v === undefined) return ways(s); return async (applied) => { - const v = typeof value === "function" ? await (value as () => unknown)() : value; - const pair = typeof v === "string" ? v : `${(v as { username: string }).username}:${(v as { password: string }).password}`; - applied.headers["authorization"] = `Basic ${base64(pair)}`; + ctx.guard(); + applied.headers["authorization"] = basic(name, await value(v)); + }; + } + const flow = sc.type === "oauth2" ? clientOf(option, s) : undefined; + if (flow !== undefined) { + const url = flow.tokenURL ?? sc.clientCredentials?.tokenUrl; + if (url === undefined) return `\`${s.option}\` (a token: the scheme has no client credentials flow)`; + return async (applied, scopes) => { + ctx.guard(); + const wanted = flow.scopes ?? s.scopes ?? scopes; + const key = flowKey(name, url, flow.clientId, wanted); + applied.headers["authorization"] = `Bearer ${await ctx.tokens.token(key, url, ctx.base, flow, wanted)}`; + applied.renew.push(() => ctx.tokens.forget(key)); }; } - if (s.type === "http" && scheme !== "bearer") return null; - if (s.type !== "apiKey" && !http) return null; + const v = option ?? (s.env === undefined ? undefined : readEnv(s.env)); + if (v === undefined) return ways(s); + if (sc.type !== "apiKey" && !http) return `\`${name}\` (a scheme of type ${sc.type}, which the client does not send)`; return async (applied) => { - const v = typeof value === "function" ? await (value as () => unknown)() : value; - if (typeof v !== "string" || v.trim() === "") { - throw new SdkError(`the credential of \`${name}\` (the option \`${setting.option}\`) is not a string with something in it`); + ctx.guard(); + const t = text(name, s, await value(v)); + if (sc.type === "apiKey") { + if (sc.in === "query") applied.query.push([sc.name ?? "", t]); + else if (sc.in === "cookie") applied.cookies.push(`${sc.name ?? ""}=${t}`); + else applied.headers[(sc.name ?? "").toLowerCase()] = t; + } else if (sc.type === "http" && scheme !== "bearer") { + applied.headers["authorization"] = `${sc.scheme} ${t}`; + } else { + if (!B64TOKEN.test(t)) throw new CredentialError(`the token of \`${name}\` is not a bearer token (RFC 6750 2.1: letters, digits, \`-._~+/\`, then \`=\` at the end)`, [name]); + applied.headers["authorization"] = `Bearer ${t}`; } - if (http) applied.headers["authorization"] = `Bearer ${v}`; - else if (s.in === "query") applied.query.push([s.name ?? "", v]); - else if (s.in === "cookie") applied.cookies.push(`${s.name ?? ""}=${v}`); - else applied.headers[(s.name ?? "").toLowerCase()] = v; }; } -/** The credentials of the first alternative the client can meet; an `SdkError` naming the +/** The credentials of the first alternative the client can meet; a `CredentialError` naming the * options and variables when it can meet none. */ export async function authorize( what: string, security: readonly { readonly [scheme: string]: readonly string[] }[], schemes: { readonly [name: string]: SchemeEntry }, settings: { readonly [scheme: string]: AuthSetting }, - options: Record, - given: Given, + ctx: Context, ): Promise { - const applied: Applied = { headers: {}, query: [], cookies: [] }; + const applied: Applied = { headers: {}, query: [], cookies: [], renew: [] }; if (security.length === 0) return applied; + const reasons: string[] = []; for (const alternative of security) { - const ready: Ready[] = []; - for (const name of Object.keys(alternative)) { - const r = meet(name, schemes[name], settings[name], options, given); - if (r === null) break; - ready.push(r); + const ready: [Ready, readonly string[]][] = []; + const why: string[] = []; + for (const [name, scopes] of Object.entries(alternative)) { + const r = meet(name, schemes[name], settings[name], ctx); + if (typeof r === "string") why.push(r); + else ready.push([r, scopes]); } - if (ready.length !== Object.keys(alternative).length) continue; - for (const r of ready) await r(applied); + if (why.length > 0) { + reasons.push(why.join(" and ")); + continue; + } + for (const [r, scopes] of ready) await r(applied, scopes); return applied; } - const ways = security.map((a) => - Object.keys(a) - .map((name) => { - const s = settings[name]; - if (s === undefined) return `\`${name}\` (the client sends no credential for it)`; - return `\`${s.option}\`` + (s.env === undefined ? "" : ` or ${s.env}`); - }) - .join(" and "), - ); - throw new SdkError(`${what} needs a credential: set ${ways.join(", or ")}`); + const names = security.flatMap((a) => Object.keys(a)); + throw new CredentialError(`${what} needs a credential: set ${reasons.join(", or ")}`, names); } /** Every scheme the client has a credential for, each met on its own and all sent together: a @@ -109,16 +216,31 @@ export async function authorize( export async function authorizeEvery( schemes: { readonly [name: string]: SchemeEntry }, settings: { readonly [scheme: string]: AuthSetting }, - options: Record, - given: Given, + ctx: Context, ): Promise { - const out: Applied = { headers: {}, query: [], cookies: [] }; + const out: Applied = { headers: {}, query: [], cookies: [], renew: [] }; for (const name of Object.keys(settings)) { if (schemes[name] === undefined) continue; - const one = await authorize(name, [{ [name]: [] }, {}], schemes, settings, options, given); + const one = await authorize(name, [{ [name]: [] }, {}], schemes, settings, ctx); Object.assign(out.headers, one.headers); out.query.push(...one.query); out.cookies.push(...one.cookies); + out.renew.push(...one.renew); } return out; } + +/** Whether a URL may carry credentials: `https:`, or `http:` to a loopback host. */ +export function secure(url: string): boolean { + try { + const u = new (platform().URL)(url); + return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname)); + } catch { + return false; + } +} + +/** An `InsecureCredentialError` before a credential would go to `url` in the clear. */ +export function guard(url: string, allow: boolean): void { + if (!allow && !secure(url)) throw new InsecureCredentialError(url); +} diff --git a/crates/flowapi-sdk/src/client/core/calls.ts b/crates/flowapi-sdk/src/client/core/calls.ts index 399b17c..0b8af5d 100644 --- a/crates/flowapi-sdk/src/client/core/calls.ts +++ b/crates/flowapi-sdk/src/client/core/calls.ts @@ -3,7 +3,7 @@ // The calls a resource's methods make: one operation's data (`call`), a list's pages (`page`), a // stream (`stream`), and a request by method and path that no operation describes (`request`). // Each writes its request with the operation's `Request`, passing the description's encoding -// of a `multipart/form-data` body when the input gives none, and sends it through `Core.send`. +// of a form or `multipart` body when the input gives none, and sends it through `Core.send`. import { ApiCall, type Outcome } from "./call.js"; import { type Core, type Operation, type RequestOptions, type Sent } from "./core.js"; @@ -24,14 +24,16 @@ function bare(type: string): string { return (type.split(";")[0] ?? "").trim().toLowerCase(); } -/** The input with the description's encoding of its body's media type, where it gives none. */ +/** The input with the description's encoding of its body's media type (its Encoding Objects by + * name and by position), where the input gives none of its own. */ function encoded(op: Operation, input: unknown): unknown { - const body = (input as { body?: { contentType?: unknown; encoding?: unknown } } | null | undefined)?.body; - if (op.encoding === undefined || typeof body?.contentType !== "string" || body.encoding !== undefined) return input; + const body = (input as { body?: { contentType?: unknown; encoding?: unknown; prefixEncoding?: unknown; itemEncoding?: unknown } } | null | undefined)?.body; + if (op.encoding === undefined || typeof body?.contentType !== "string") return input; + if (body.encoding !== undefined || body.prefixEncoding !== undefined || body.itemEncoding !== undefined) return input; const type = bare(body.contentType); const key = Object.keys(op.encoding).find((k) => bare(k) === type); if (key === undefined) return input; - return { ...(input as object), body: { ...body, encoding: op.encoding[key] } }; + return { ...(input as object), body: { ...body, ...op.encoding[key] } }; } /** The request an operation's input makes. */ diff --git a/crates/flowapi-sdk/src/client/core/core.ts b/crates/flowapi-sdk/src/client/core/core.ts index e060d6a..4723fc0 100644 --- a/crates/flowapi-sdk/src/client/core/core.ts +++ b/crates/flowapi-sdk/src/client/core/core.ts @@ -2,22 +2,27 @@ // // The client's runtime: its options resolved once, then every call made the same way. The // operation's `Request` writes the request (no I/O, the description's styles); its -// credentials are attached by its security; the base URL, the caller's headers and query are -// added; the attempts are made and retried (`retry.ts`); a success's body is read back by -// `Response`, as bytes or as text by its `Content-Type`, and any other status thrown as an -// `APIError` with the body read the same way. No middleware: `fetch` and `fetchOptions` are -// where a caller changes how a request goes. +// credentials are attached by its security; the base URL (`servers.ts`), the caller's headers +// and query are added; a call of a method that is not idempotent gets one idempotency key for all +// its attempts, where the config names its header; the attempts are made and retried +// (`retry.ts`); a success's body is read back by `Response`, as bytes or as text by its +// `Content-Type`, and any other status thrown as an `APIError` with the body read the same way. +// A 401 to a call that sent a token the client requested itself forgets that token and makes the +// call once more with a new one (RFC 6750 3.1): the auth layer's one renewal, not a retry of +// RFC 9110's, so it spends none of `maxRetries` and is made for a POST too, as a 401 says the +// request was not applied (15.5.2). No middleware: `fetch` and `fetchOptions` are where a caller +// changes how a request goes. -import { type Applied, type AuthSetting, type SchemeEntry, authorize, authorizeEvery } from "./auth.js"; -import { APIConnectionError, APIError, APIUserAbortError, SdkError } from "./errors.js"; +import { type Applied, type AuthSetting, type Context, type SchemeEntry, authorize, authorizeEvery, guard } from "./auth.js"; +import { APIConnectionError, APIError, APIUserAbortError, SdkError, handledAs } from "./errors.js"; import { type LogLevel, type Secrets, makeLogger, maskHeaders, redactURL, secretsOf } from "./log.js"; -import { type Fetch, type FetchResponse, type Logger, type Signal, platform, readEnv } from "./platform.js"; +import { type Fetch, type FetchResponse, type Logger, type Signal, platform, randomKey, readEnv } from "./platform.js"; import { type HeadersInput, type QueryInput, addPairs, joinURL, mergeHeaders, namedHeaders, setQuery } from "./request.js"; -import { MAX_TIMER, backoff, retryable, serverDelay, sleep } from "./retry.js"; +import { MAX_TIMER, backoff, idempotent, retryable, serverDelay, sleep } from "./retry.js"; import { type Answer, type Wire, attempt, discard, readBody } from "./send.js"; +import { type ServerEntry, type ServerVariables, checkDescriptionURL, isAbsolute, refuseUserinfo, resolved, serverURL } from "./servers.js"; +import { Tokens } from "./token.js"; -/** A server of the description, as the operations table gives it. */ -export type ServerEntry = { readonly url: string; readonly variables?: { readonly [name: string]: { readonly default: string } } }; /** What the generator decided from the config: printed in the client's module. */ export type Settings = { @@ -30,6 +35,8 @@ export type Settings = { readonly timeout: number; readonly maxRetries: number; readonly maxRetryDelay: number; + /** The header a call of a method that is not idempotent sends its idempotency key in. */ + readonly idempotencyHeader?: string; readonly servers: readonly ServerEntry[]; readonly schemes: { readonly [name: string]: SchemeEntry }; readonly readsBytes: (contentType: string | null | undefined) => boolean; @@ -41,34 +48,54 @@ export type ClientOptions = { baseURL?: string | null | undefined; /** One of the config's environments, by name. */ environment?: Environment | undefined; + /** Values of the servers' variables, by name, over their defaults; each one of its `enum`. */ + serverVariables?: ServerVariables | undefined; + /** Where the description is served: a relative server URL is resolved against it. */ + descriptionURL?: string | undefined; /** Milliseconds an attempt may take, its body read; `null` for no limit. */ timeout?: number | null | undefined; - /** How many times a failed attempt is tried again. */ + /** How many times a failed attempt is tried again; a request that may not be sent twice (a + * POST or a PATCH with no idempotency key) is not, unless the server says so. */ maxRetries?: number | undefined; /** The longest wait in milliseconds a server may ask for before a retry; `null` for any. */ maxRetryDelay?: number | null | undefined; /** The most pages a list is read to before it is refused as endless. */ maxPages?: number | undefined; + /** The `fetch` requests are sent with: the platform's unless given. */ fetch?: Fetch | undefined; /** What every `fetch` is given beside the client's own members (`dispatcher`, `credentials`). */ fetchOptions?: { readonly [option: string]: unknown } | undefined; + /** Headers every request sends; the operation's own headers and a call's `headers` win over them. */ defaultHeaders?: HeadersInput | undefined; + /** Query parameters every request sends, where the operation sets none of that name; a call's `query` wins over them. */ defaultQuery?: QueryInput | undefined; + /** The least level logged (`off`, `error`, `warn`, `info`, `debug`): the log environment variable's unless given, else `warn`. */ logLevel?: LogLevel | undefined; + /** Where the log goes: `console` unless given. */ logger?: Logger | undefined; /** Follow a redirect to another origin, with the headers that carry credentials removed. */ allowCrossOriginRedirects?: boolean | undefined; + /** Send credentials over plain `http:` to a host that is not loopback (never by default). */ + allowInsecureCredentials?: boolean | undefined; }; /** What one call may change. */ export type RequestOptions = { + /** Headers of this call, over the client's and the operation's; `null` removes one. */ headers?: HeadersInput | undefined; + /** Query parameters of this call, over the client's and the operation's. */ query?: QueryInput | undefined; + /** The base URL of this call, over the client's. */ baseURL?: string | undefined; + /** Milliseconds each attempt of this call may take, its body read; `null` for no limit. */ timeout?: number | null | undefined; + /** How many times this call is tried again when it fails. */ maxRetries?: number | undefined; + /** The most pages this list is read to. */ maxPages?: number | undefined; + /** Aborts the call: it then throws `APIUserAbortError`. */ signal?: Signal | undefined; + /** What this call's `fetch` is given beside the client's `fetchOptions`. */ fetchOptions?: { readonly [option: string]: unknown } | undefined; }; @@ -78,7 +105,7 @@ export type Operation = { readonly path: string; readonly servers?: readonly ServerEntry[]; readonly security: readonly { readonly [scheme: string]: readonly string[] }[]; - readonly encoding?: { readonly [mediaType: string]: unknown }; + readonly encoding?: { readonly [mediaType: string]: { readonly encoding?: unknown; readonly prefixEncoding?: unknown; readonly itemEncoding?: unknown } }; readonly request: (input: never) => { method: string; path: string; query: string; headers: Record; body?: string | Uint8Array }; readonly response: (status: number, headers: Record, body: string | Uint8Array) => { response: string | null; body: unknown }; }; @@ -97,13 +124,6 @@ function check(name: string, value: number, integer: boolean, min: number): numb return value; } -/** A server's URL with each variable's default. */ -function serverURL(s: ServerEntry): string { - return s.url.replace(/\{([^}]*)\}/g, (all, name: string) => s.variables?.[name]?.default ?? all); -} - -const ABSOLUTE = /^[a-z][a-z0-9+.-]*:/i; - export class Core { readonly settings: Settings; readonly options: Readonly & { readonly [credential: string]: unknown }; @@ -114,7 +134,9 @@ export class Core { readonly maxPages: number; readonly log: Logger; readonly secrets: Secrets; + readonly tokens: Tokens; readonly #explicit: boolean; + readonly #descriptionURL: string | undefined; #calls = 0; constructor(settings: Settings, options: ClientOptions & { readonly [credential: string]: unknown }) { @@ -130,53 +152,103 @@ export class Core { const env = settings.baseURLEnv === undefined || options.baseURL === null ? undefined : readEnv(settings.baseURLEnv); const named = options.environment ?? settings.defaultEnvironment ?? Object.keys(settings.environments)[0]; const environment = named === undefined ? undefined : settings.environments[named]; - if (options.environment !== undefined && environment === undefined) throw new RangeError(`no environment is named \`${options.environment}\``); + if (options.environment !== undefined && environment === undefined) throw new RangeError(`no environment is named \`${options.environment}\`: give one of ${Object.keys(settings.environments).map((n) => `\`${n}\``).join(", ") || "none (the config names no environment)"}`); const first = settings.servers[0]; this.#explicit = options.baseURL != null || env !== undefined; - this.baseURL = options.baseURL ?? env ?? environment ?? (first === undefined ? null : serverURL(first)); + this.#descriptionURL = checkDescriptionURL(options.descriptionURL); + this.baseURL = options.baseURL ?? env ?? environment ?? (first === undefined ? null : this.#server(first)); this.log = makeLogger(options.logLevel, settings.logEnv, options.logger); this.secrets = secretsOf(settings.schemes); + this.tokens = new Tokens((url, headers, body) => this.#post(url, headers, body), options.allowInsecureCredentials === true); + } + + /** A token endpoint asked: one attempt with the client's `fetch` and timeout, its body text. */ + async #post(url: string, headers: Record, body: string): Promise<{ status: number; text: string }> { + const g = platform(); + const how = { fetch: this.options.fetch ?? g.fetch ?? missingFetch, fetchOptions: { ...this.options.fetchOptions }, timeout: this.timeout, signal: undefined, crossOrigin: false, secretHeaders: this.secrets.headers }; + this.log.info(`token POST ${redactURL(url, this.secrets)}`); + const answer = await attempt({ method: "POST", url, headers, body }, how); + const text = await readBody(answer, false, undefined); + this.log.info(`token ${answer.response.status}`); + return { status: answer.response.status, text: typeof text === "string" ? text : "" }; + } + + /** A server's URL: its variables' values, resolved against where the description is served. */ + #server(s: ServerEntry): string { + return resolved(serverURL(s, this.options.serverVariables), this.#descriptionURL); } /** The base URL of an operation: the call's, the client's own, the operation's servers', the * client's environment. A relative one cannot be sent to. */ #base(op: Operation | undefined, options: RequestOptions): string { const own = op?.servers?.[0]; - const base = options.baseURL ?? (this.#explicit || own === undefined ? this.baseURL : serverURL(own)); - if (base === null || !ABSOLUTE.test(base)) { - throw new SdkError(`the base URL ${JSON.stringify(base)} is not absolute: give \`baseURL\` to ${this.settings.client}`); + const base = options.baseURL ?? (this.#explicit || own === undefined ? this.baseURL : this.#server(own)); + if (base === null || !isAbsolute(base)) { + throw new SdkError(`the base URL ${JSON.stringify(base)} is not absolute: give \`baseURL\` to ${this.settings.client}, or \`descriptionURL\`, where the description is served`); } - return base; + return refuseUserinfo(base); } - /** The request a call sends, before its attempts. */ - async #wire(op: Operation | undefined, wrote: ReturnType, options: RequestOptions, url?: string): Promise { + /** The request a call sends, before its attempts, and how to forget the tokens it carries; + * `key` the idempotency key of the call's first wire, kept when it is written again. */ + async #wire(op: Operation | undefined, wrote: ReturnType, options: RequestOptions, url?: string, key?: string): Promise<{ wire: Wire; renew: (() => void)[] }> { const given = { headers: namedHeaders(this.options.defaultHeaders, options.headers), query: new Set([...Object.keys(this.options.defaultQuery ?? {}), ...Object.keys(options.query ?? {})]), }; const what = op === undefined ? `${wrote.method} ${wrote.path}` : `\`${wrote.method} ${op.path}\``; const { schemes, auth: settings } = this.settings; - const auth: Applied = op === undefined ? await authorizeEvery(schemes, settings, this.options, given) : await authorize(what, op.security, schemes, settings, this.options, given); + const base = url ?? this.#base(op, options); + const allow = this.options.allowInsecureCredentials === true; + const ctx: Context = { options: this.options, given, tokens: this.tokens, base, guard: () => guard(base, allow) }; + const auth: Applied = op === undefined ? await authorizeEvery(schemes, settings, ctx) : await authorize(what, op.security, schemes, settings, ctx); const headers = mergeHeaders(auth.headers, this.options.defaultHeaders, wrote.headers, options.headers); if (auth.cookies.length > 0) headers["cookie"] = [headers["cookie"], ...auth.cookies].filter((c) => c !== undefined && c !== "").join("; "); let full: string; if (url === undefined) { const query = setQuery(setQuery(wrote.query, this.options.defaultQuery, true), options.query, false); - full = joinURL(this.#base(op, options), wrote.path, addPairs(query, auth.query)); + full = joinURL(base, wrote.path, addPairs(query, auth.query)); } else { const q = url.indexOf("?"); full = q < 0 ? joinURL(url, "", addPairs("", auth.query)) : url.slice(0, q + 1) + addPairs(url.slice(q + 1), auth.query); } - return { method: wrote.method.toUpperCase(), url: full, headers, body: wrote.body }; + const method = wrote.method.toUpperCase(); + // Fetch sends no content with GET or HEAD (RFC 9110 9.3.1, 9.3.2); content with OPTIONS + // says what it is (9.3.7). + if (wrote.body !== undefined && (method === "GET" || method === "HEAD")) throw new SdkError(`${what}: a ${method} request carries no content`); + if (wrote.body !== undefined && method === "OPTIONS" && headers["content-type"] === undefined) throw new SdkError(`${what}: an OPTIONS request with content needs a Content-Type`); + const header = this.settings.idempotencyHeader?.toLowerCase(); + if (header !== undefined && !idempotent(method) && headers[header] === undefined) headers[header] = key ?? randomKey(); + return { wire: { method, url: full, headers, body: wrote.body }, renew: auth.renew }; } - /** A call made: its attempts, retried, and its body read by `mode`. `url` replaces the URL the - * operation's input makes (a page's `next` link). */ + /** A call made: its attempts (`#attempts`); a 401 to a token the client requested makes it once + * more with a new one, the same idempotency key and what is left of `maxRetries`. `url` + * replaces the URL the operation's input makes (a page's `next`). */ async send(op: Operation | undefined, wrote: ReturnType, options: RequestOptions = {}, mode: Mode = "data", url?: string): Promise { + const first = await this.#wire(op, wrote, options, url); + const spent = { retries: 0 }; + try { + return await this.#attempts(op, first.wire, options, mode, spent); + } catch (error) { + if (!(error instanceof APIError) || error.status !== 401 || first.renew.length === 0) throw error; + for (const forget of first.renew) forget(); + this.log.info(`401 to a requested token: requesting another, once`); + const header = this.settings.idempotencyHeader?.toLowerCase(); + const again = await this.#wire(op, wrote, options, url, header === undefined ? undefined : first.wire.headers[header]); + return await this.#attempts(op, again.wire, options, mode, spent); + } + } + + /** A call's attempts, retried, and its body read by `mode`; `spent` the retries the call made + * so far, shared by the wires of one call. */ + async #attempts(op: Operation | undefined, wire: Wire, options: RequestOptions, mode: Mode, spent: { retries: number }): Promise { const maxRetries = options.maxRetries === undefined ? this.maxRetries : check("maxRetries", options.maxRetries, true, 0); const timeout = options.timeout === undefined ? this.timeout : options.timeout === null ? null : check("timeout", options.timeout, true, 1); - const wire = await this.#wire(op, wrote, options, url); + // Sent twice, a request that is not idempotent may be applied twice (RFC 9110 9.2.2): it is + // retried only with an idempotency key, or when the server asks. + const key = this.settings.idempotencyHeader?.toLowerCase(); + const safe = idempotent(wire.method) || (key !== undefined && wire.headers[key] !== undefined); const id = `log_${++this.#calls}`; const g = platform(); const how = { @@ -187,14 +259,14 @@ export class Core { crossOrigin: this.options.allowCrossOriginRedirects === true, secretHeaders: this.secrets.headers, }; - for (let retries = 0; ; retries++) { + for (let retries = spent.retries; ; spent.retries = ++retries) { const can = retries < maxRetries; this.log.info(`${id} ${wire.method} ${redactURL(wire.url, this.secrets)}${retries > 0 ? ` (retry ${retries})` : ""}`); this.log.debug(`${id} headers`, maskHeaders(wire.headers, this.secrets)); // A connection that failed or timed out, before the headers or while the body was read, is // tried again; the caller's abort and errors of ours are not. const failed = async (error: unknown): Promise => { - const again = can && error instanceof APIConnectionError && !(error instanceof APIUserAbortError); + const again = can && safe && error instanceof APIConnectionError && !(error instanceof APIUserAbortError); this.log.info(`${id} failed: ${error instanceof Error ? error.message : String(error)}${again ? "; retrying" : ""}`); if (!again) throw error; await sleep(backoff(retries), options.signal); @@ -210,8 +282,9 @@ export class Core { const header = (name: string): string | null => answer.headers[name] ?? null; const requestId = header("x-request-id") ?? header("request-id"); this.log.info(`${id} ${r.status}`); - const ok = r.status >= 200 && r.status < 300; - if (!ok && can && retryable(r.status, header)) { + const status = handledAs(r.status); + const ok = status >= 200 && status < 300; + if (!ok && can && retryable(status, header, safe)) { const asked = serverDelay(header, Date.now()); if (asked === undefined || this.maxRetryDelay === null || asked <= this.maxRetryDelay) { discard(r); diff --git a/crates/flowapi-sdk/src/client/core/errors.ts b/crates/flowapi-sdk/src/client/core/errors.ts index 5bc1a84..97d60a5 100644 --- a/crates/flowapi-sdk/src/client/core/errors.ts +++ b/crates/flowapi-sdk/src/client/core/errors.ts @@ -1,10 +1,12 @@ // Generated by flowapi. Do not edit: generate again. // // What a call throws. Two branches under `SdkError`: `APIError`, the server answered with a -// status that is not a success (its `status` is always a number, its `body` read by the -// operation's declared response for that status), and `APIConnectionError`, no answer came (the -// connection failed, the attempt timed out, or the caller aborted). A request the input cannot -// make is `FlowapiRequestError` (the API module), thrown before anything is sent and never retried. +// status that is not a success (its `status` is always a number, the one the server sent; its +// `body` read by the operation's declared response for that status; its class by the status: a +// 5xx, or a value that is no status code, `InternalServerError`, a status no class is for +// `APIError`), and `APIConnectionError`, no answer came (the connection failed, the attempt +// timed out, or the caller aborted). A request the input cannot make is `FlowapiRequestError` +// (the API module), thrown before anything is sent and never retried. /** The root of every error the client throws itself; `name` is the class's name. */ export class SdkError extends Error { @@ -14,6 +16,12 @@ export class SdkError extends Error { } } +/** The status an answer is handled as: its own, or 500 for one that is no status code (RFC 9110, + * 15: a client treats an invalid status code as a 5xx). */ +export function handledAs(status: number): number { + return Number.isInteger(status) && status >= 100 && status <= 599 ? status : 500; +} + /** The members of a body an error's message is taken from, where it has one. */ function messageOf(body: unknown): string | undefined { if (typeof body === "string") return body === "" ? undefined : body.slice(0, 500); @@ -34,16 +42,18 @@ export class APIError extends SdkError { readonly body: TBody; readonly requestId: string | null; constructor(status: number, headers: Record, body: TBody, requestId: string | null) { - super(`${status} ${messageOf(body) ?? "status code (no body)"}`); + super(`${status} ${messageOf(body) ?? "with no message in its body"}`); this.status = status; this.headers = headers; this.body = body; this.requestId = requestId; } - /** The error of a status: its class, or `APIError` for a status no class is for. */ + /** The error of a status: its class, or `APIError` for a status no class is for; a status + * that is none is a server's error (`handledAs`). */ static of(status: number, headers: Record, body: unknown, requestId: string | null): APIError { - const Class = status >= 500 ? InternalServerError : (STATUS[status] ?? APIError); + const handled = handledAs(status); + const Class = handled >= 500 ? InternalServerError : (STATUS[handled] ?? APIError); return new Class(status, headers, body, requestId); } } @@ -88,14 +98,14 @@ export class APIConnectionError extends SdkError { /** No answer came within the attempt's `timeout`, the body read included. */ export class APIConnectionTimeoutError extends APIConnectionError { constructor(options?: { cause?: unknown }) { - super("the request timed out", options); + super("the request timed out: no answer within `timeout`; raise it on the client or on the call", options); } } /** The caller's signal aborted the call. */ export class APIUserAbortError extends APIConnectionError { constructor() { - super("the request was aborted"); + super("the request was aborted by its `signal`"); } } @@ -106,8 +116,52 @@ export class CrossOriginRedirectError extends SdkError { readonly status: number; readonly location: string; constructor(status: number, location: string) { - super(`${status} redirect to another origin, not followed: ${location}`); + super(`${status} redirect to another origin, not followed: ${location}; set \`allowCrossOriginRedirects\` to follow it without the credentials`); this.status = status; this.location = location; } } + +/** A call's security cannot be met: none of its alternatives has every credential it needs, or a + * credential given is not one its scheme can send. Thrown before anything is sent; `schemes` + * names the schemes asked for. */ +export class CredentialError extends SdkError { + readonly schemes: readonly string[]; + constructor(message: string, schemes: readonly string[]) { + super(message); + this.schemes = schemes; + } +} + +/** A request would carry credentials in the clear: over `http:` to a host that is not loopback. + * Thrown before it is sent; `allowInsecureCredentials` lets it go. */ +export class InsecureCredentialError extends SdkError { + readonly url: string; + constructor(url: string) { + super(`credentials go only over https or to a loopback host, not to ${url.replace(/[?#].*$/, "")}; set \`allowInsecureCredentials\` to send them anyway`); + this.url = url; + } +} + +/** The token endpoint refused a client credentials grant (RFC 6749 5.2), or answered with no + * token the client can use: `error` its code (`invalid_client`, ...), `description` its text. */ +export class TokenError extends SdkError { + readonly status: number; + readonly error: string; + readonly description: string | null; + readonly uri: string | null; + constructor(status: number, error: string, description: string | null, uri: string | null) { + super(`the token endpoint answered ${status} ${error}${description === null ? "" : `: ${description}`}`); + this.status = status; + this.error = error; + this.description = description; + this.uri = uri; + } + + /** The error of an answer that is not a success: its `error`, `error_description` and + * `error_uri`, else its text. */ + static of(status: number, body: { readonly [member: string]: unknown }, text: string): TokenError { + const str = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null); + return new TokenError(status, str(body["error"]) ?? "invalid_response", str(body["error_description"]) ?? (str(body["error"]) === null ? text.slice(0, 200) || null : null), str(body["error_uri"])); + } +} diff --git a/crates/flowapi-sdk/src/client/core/index.ts b/crates/flowapi-sdk/src/client/core/index.ts index 76c1c04..29af6ae 100644 --- a/crates/flowapi-sdk/src/client/core/index.ts +++ b/crates/flowapi-sdk/src/client/core/index.ts @@ -2,10 +2,10 @@ // // The runtime as the client, the resources and the package's entry import it. -export type { AuthSetting, BasicCredential, Credential, SchemeEntry } from "./auth.js"; +export type { AuthSetting, BasicCredential, BasicPair, Credential, SchemeEntry } from "./auth.js"; export { ApiCall, type Outcome } from "./call.js"; export { type Data, type Input, type RawRequest, call, page, request, stream } from "./calls.js"; -export { type ClientOptions, Core, type Operation, type RequestOptions, type ServerEntry, type Settings } from "./core.js"; +export { type ClientOptions, Core, type Operation, type RequestOptions, type Settings } from "./core.js"; export { APIConnectionError, APIConnectionTimeoutError, @@ -14,17 +14,22 @@ export { AuthenticationError, BadRequestError, ConflictError, + CredentialError, CrossOriginRedirectError, + InsecureCredentialError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, RequestTimeoutError, SdkError, + TokenError, UnprocessableEntityError, } from "./errors.js"; export type { LogLevel } from "./log.js"; export { type ItemOf, type Next, Page, PagePromise, type Paging, linkNext, nextPage } from "./pagination.js"; export type { Fetch, FetchInit, FetchResponse, Logger, Signal } from "./platform.js"; export type { HeadersInput, QueryInput } from "./request.js"; +export type { ServerEntry, ServerVariables, VariableEntry } from "./servers.js"; export { LineDecoder, type ServerSentEvent, SseDecoder, Stream, type StreamOptions } from "./streaming.js"; +export type { ClientCredentials } from "./token.js"; diff --git a/crates/flowapi-sdk/src/client/core/pagination.ts b/crates/flowapi-sdk/src/client/core/pagination.ts index 97f9bc4..f82b2a4 100644 --- a/crates/flowapi-sdk/src/client/core/pagination.ts +++ b/crates/flowapi-sdk/src/client/core/pagination.ts @@ -48,7 +48,7 @@ function at(body: unknown, path: Path): unknown { export function itemsOf(paging: Paging, body: unknown): unknown[] { const items = at(body, paging.items); if (items === undefined || items === null) return []; - if (!Array.isArray(items)) throw new SdkError(`the page's items (\`${paging.items.join(".") || "the body"}\`) are not an array`); + if (!Array.isArray(items)) throw new SdkError(`the page's items (\`${paging.items.join(".") || "the body"}\`) are not an array: the answer does not fit the list's pagination`); return items; } @@ -170,7 +170,7 @@ export class Page implements AsyncIterable { const next = this.#next; if (next === null) throw new SdkError("no next page: ask `hasNextPage()` first"); if ("refused" in next) throw new SdkError(next.refused); - if (this.#chain.pages >= this.#chain.maxPages) throw new SdkError(`more than ${this.#chain.maxPages} pages (\`maxPages\`): the list looks endless`); + if (this.#chain.pages >= this.#chain.maxPages) throw new SdkError(`more than ${this.#chain.maxPages} pages: the list looks endless; raise \`maxPages\` to read further`); return this.#fetch(next, this.#chain); } diff --git a/crates/flowapi-sdk/src/client/core/platform.ts b/crates/flowapi-sdk/src/client/core/platform.ts index fae1659..d03fedf 100644 --- a/crates/flowapi-sdk/src/client/core/platform.ts +++ b/crates/flowapi-sdk/src/client/core/platform.ts @@ -2,7 +2,7 @@ // // What the client needs of the platform, typed here so that the SDK type-checks with neither the // DOM's nor Node's declarations (`lib: ["es2022"]` alone): `fetch` and its response, abort -// signals, timers, the UTF-8 coders, `URL`, the console and the environment. Each is looked up on +// signals, timers, the UTF-8 coders, `URL`, random values, the console and the environment. Each is looked up on // `globalThis` when it is used, so a polyfill or a test's fake is seen. The platform's own // `fetch`, `Response` and `AbortSignal` are assignable to these types. @@ -72,7 +72,8 @@ type Globals = Coders & { setTimeout(callback: () => void, ms: number): unknown; clearTimeout(timer: unknown): void; AbortController: new () => { readonly signal: Signal; abort(reason?: unknown): void }; - URL: new (url: string, base?: string) => { readonly origin: string; readonly href: string; readonly protocol: string }; + URL: new (url: string, base?: string) => { readonly origin: string; readonly href: string; readonly protocol: string; readonly hostname: string; readonly username: string; readonly password: string }; + crypto?: { randomUUID?(): string; getRandomValues?(bytes: Uint8Array): Uint8Array }; console?: Logger; process?: { env?: { [name: string]: string | undefined } }; Deno?: { env?: { get(name: string): string | undefined } }; @@ -126,6 +127,19 @@ export function originOf(url: string): string | null { } } +/** A random key that names one call, the same on each of its attempts: a UUID (version 4). */ +export function randomKey(): string { + const c = platform().crypto; + if (c?.randomUUID !== undefined) return c.randomUUID(); + const b = new Uint8Array(16); + if (c?.getRandomValues !== undefined) c.getRandomValues(b); + else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256); + b[6] = ((b[6] ?? 0) & 0x0f) | 0x40; + b[8] = ((b[8] ?? 0) & 0x3f) | 0x80; + const hex = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + /** A reference resolved against a URL; `null` when it is not one. */ export function resolveURL(reference: string, base: string): string | null { try { diff --git a/crates/flowapi-sdk/src/client/core/retry.ts b/crates/flowapi-sdk/src/client/core/retry.ts index 8ae7e54..d71fbf0 100644 --- a/crates/flowapi-sdk/src/client/core/retry.ts +++ b/crates/flowapi-sdk/src/client/core/retry.ts @@ -1,12 +1,19 @@ // Generated by flowapi. Do not edit: generate again. // -// When a failed attempt is tried again, and after how long. An answer is retried when the -// server says so in `x-should-retry` (`true` or `false` decides alone), else for 408, 409, 429 -// and every status from 500; a connection that failed or timed out is retried too. The wait is -// the one the server asks for: `retry-after-ms` (0 included), else `retry-after` in seconds or as -// an HTTP date; else 0.5 s doubled for each retry already made, at most 8 s, less up to a quarter -// at random so that clients do not retry together. A wait longer than `maxRetryDelay` is not -// waited: the answer's error is thrown instead, as the server asked for more than the caller allows. +// When a failed attempt is tried again, and after how long. A request is retried on its own only +// when it is idempotent (RFC 9110, 9.2.2: PUT, DELETE and the safe methods GET, HEAD, OPTIONS and +// TRACE) or carries an idempotency key, or when the server says so in `x-should-retry: true`: a +// POST or a PATCH that failed may have been applied, and sending it again could apply it twice. +// Then an answer is retried when the server says so in `x-should-retry` (`true` or `false` +// decides alone), else for 408, 409, 429 and every status from 500; a 403 never, as the same +// credentials would be refused again (15.5.4); a connection that failed or timed out is retried +// too. A status that is not one (not an integer from 100 to 599) is read as a 5xx (15). One retry +// by default (`maxRetries: 1`), as a failed automatic retry is not retried again (9.2.2); more is +// the caller's choice. The wait is the one the server asks for: `retry-after-ms` (0 included), +// else `retry-after` in seconds or as an HTTP date; else 0.5 s doubled for each retry already +// made, at most 8 s, less up to a quarter at random so that clients do not retry together. A wait +// longer than `maxRetryDelay` is not waited: the answer's error is thrown instead, as the server +// asked for more than the caller allows. import { APIUserAbortError } from "./errors.js"; import { type Signal, platform } from "./platform.js"; @@ -14,11 +21,21 @@ import { type Signal, platform } from "./platform.js"; /** The longest a timer can wait: a longer one fires at once. */ export const MAX_TIMER = 2 ** 31 - 1; -/** Whether an answer of this status is tried again. */ -export function retryable(status: number, header: (name: string) => string | null): boolean { +/** The methods RFC 9110 9.2.2 names idempotent: PUT, DELETE and the safe methods (9.2.1). */ +const IDEMPOTENT: ReadonlySet = new Set(["GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE"]); + +/** Whether a method is idempotent: sending it twice does what sending it once does. */ +export function idempotent(method: string): boolean { + return IDEMPOTENT.has(method.toUpperCase()); +} + +/** Whether an answer of this status is tried again; `safe` when the request may be sent twice + * (an idempotent method, or an idempotency key). */ +export function retryable(status: number, header: (name: string) => string | null, safe: boolean): boolean { + if (status === 403) return false; const should = header("x-should-retry"); if (should === "true") return true; - if (should === "false") return false; + if (should === "false" || !safe) return false; return status === 408 || status === 409 || status === 429 || status >= 500; } diff --git a/crates/flowapi-sdk/src/client/core/send.ts b/crates/flowapi-sdk/src/client/core/send.ts index babf7ac..de00f33 100644 --- a/crates/flowapi-sdk/src/client/core/send.ts +++ b/crates/flowapi-sdk/src/client/core/send.ts @@ -6,9 +6,17 @@ // not by `fetch` (`redirect: "manual"`), so that one to another origin can be refused: `fetch` drops // `Authorization` there, but not an API key sent in a header of its own. A browser hides a manual // redirect from the page; there `fetchOptions: { redirect: "follow" }` gives it back to `fetch`. +// As RFC 9110 15.4 says: a 3xx with a `Location` is followed, a code no one defines (`399`) too, +// but 304 (an answer to a condition the client never sends) and 305 and 306 (deprecated and +// unused); 303 is sent again as a GET with no content (HEAD stays HEAD), 301 and 302 change a POST +// into a GET as browsers do (15.4.2, 15.4.3), 300, 307, 308 and the rest keep the method and the +// content (15.4.8, 15.4.9). A `Location` +// with no fragment keeps the request's (10.2.2). A request sent again to where it was already +// sent is a loop and refused at once; more than 20 redirects are refused too. import { APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, CrossOriginRedirectError, SdkError } from "./errors.js"; import { type Fetch, type FetchInit, type FetchResponse, type Signal, originOf, platform, resolveURL } from "./platform.js"; +import { refuseUserinfo } from "./servers.js"; /** A request as one attempt sends it. */ export type Wire = { method: string; url: string; headers: Record; body: string | Uint8Array | undefined }; @@ -36,7 +44,10 @@ export type Answer = { readonly abort: () => void; }; -const REDIRECTS = new Set([301, 302, 303, 307, 308]); +/** Whether an answer of this status with a `Location` is followed. */ +function redirects(status: number): boolean { + return status >= 300 && status <= 399 && status !== 304 && status !== 305 && status !== 306; +} const MAX_REDIRECTS = 20; /** The listener that aborts an attempt when the caller's signal does; made here so that it holds @@ -97,7 +108,9 @@ export async function attempt(wire: Wire, o: AttemptOptions): Promise { if (o.signal?.aborted) throw new APIUserAbortError(); let { method, url, body } = wire; let headers = { ...wire.headers }; + const sent = new Set(); for (let hop = 0; ; hop++) { + sent.add(`${method} ${url}`); const init: FetchInit = { ...o.fetchOptions, method, headers, signal: controller.signal, redirect: (o.fetchOptions["redirect"] as string | undefined) ?? "manual" }; if (body !== undefined) init.body = body; const f = o.fetch; @@ -106,12 +119,15 @@ export async function attempt(wire: Wire, o: AttemptOptions): Promise { throw new SdkError('the platform hides a redirect from `redirect: "manual"` (a browser does): pass `fetchOptions: { redirect: "follow" }`'); } const location = response.headers.get("location"); - if (!REDIRECTS.has(response.status) || location === null) { + if (!redirects(response.status) || location === null) { return { response, url, headers: headersOf(response), release, timedOut: () => fired, abort: listener }; } discard(response); - const next = resolveURL(location, url); + let next = resolveURL(location, url); if (next === null) throw new SdkError(`${response.status} redirect to a location that is no URL: ${location}`); + const hash = url.indexOf("#"); + if (hash >= 0 && !next.includes("#")) next += url.slice(hash); + refuseUserinfo(next); if (hop === MAX_REDIRECTS) throw new SdkError(`more than ${MAX_REDIRECTS} redirects, the last to ${next}`); if (originOf(next) !== originOf(url)) { if (!o.crossOrigin) throw new CrossOriginRedirectError(response.status, next); @@ -124,6 +140,7 @@ export async function attempt(wire: Wire, o: AttemptOptions): Promise { delete headers["content-length"]; } url = next; + if (sent.has(`${method} ${url}`)) throw new SdkError(`${response.status} redirect loop: ${method} ${url} was sent already`); } } catch (error) { release(); diff --git a/crates/flowapi-sdk/src/client/core/servers.ts b/crates/flowapi-sdk/src/client/core/servers.ts new file mode 100644 index 0000000..1b29cb1 --- /dev/null +++ b/crates/flowapi-sdk/src/client/core/servers.ts @@ -0,0 +1,74 @@ +// Generated by flowapi. Do not edit: generate again. +// +// Where a call goes. A server of the description is its URL with each `{name}` replaced: by the +// caller's `serverVariables` value of that name, else the variable's `default` (OpenAPI, Server +// Variable Object: the default is sent when no other value is given); a value outside the +// variable's `enum` is refused. A server URL may be relative to where the description is served: +// it is resolved against `descriptionURL` when the caller gives it (OpenAPI 3.1 and 3.2, +// "Relative References in API URLs": the description's retrieval URL, never its `$self`), and a +// base URL that stays relative cannot be sent to. A URL with a user name or password in it is +// refused, as an HTTP sender never writes one (RFC 9110, 4.2.4). + +import { SdkError } from "./errors.js"; +import { platform, resolveURL } from "./platform.js"; + +/** A server variable, as the operations table gives it. */ +export type VariableEntry = { readonly default: string; readonly enum?: readonly string[]; readonly description?: string }; + +/** A server of the description, as the operations table gives it. */ +export type ServerEntry = { readonly url: string; readonly variables?: { readonly [name: string]: VariableEntry } }; + +/** The caller's values of server variables, by name. */ +export type ServerVariables = { readonly [name: string]: string | undefined }; + +const ABSOLUTE = /^[a-z][a-z0-9+.-]*:/i; + +/** Whether a URL has a scheme. */ +export function isAbsolute(url: string): boolean { + return ABSOLUTE.test(url); +} + +/** A server's URL with each variable's value: the caller's, else its default. A value of the + * caller's outside the variable's `enum` is a `RangeError`; a default outside it is sent as the + * description says. */ +export function serverURL(s: ServerEntry, given: ServerVariables | undefined): string { + return s.url.replace(/\{([^}]*)\}/g, (all, name: string) => { + const v = s.variables?.[name]; + if (v === undefined) return all; + const value = given?.[name]; + if (value === undefined) return v.default; + if (v.enum !== undefined && v.enum.length > 0 && !v.enum.includes(value)) { + throw new RangeError(`\`${value}\` is not a value of the server variable \`${name}\` of ${s.url}: give one of ${v.enum.map((e) => `\`${e}\``).join(", ")}`); + } + return value; + }); +} + +/** `descriptionURL` checked: an absolute URL with no user name or password. */ +export function checkDescriptionURL(url: string | undefined): string | undefined { + if (url === undefined) return undefined; + if (!isAbsolute(url) || resolveURL(url, url) === null) throw new TypeError(`\`descriptionURL\` is ${JSON.stringify(url)}: an absolute URL is needed`); + return refuseUserinfo(url); +} + +/** A server's URL made absolute against where the description is served, when the caller says + * where; as it is otherwise. */ +export function resolved(url: string, descriptionURL: string | undefined): string { + if (isAbsolute(url) || descriptionURL === undefined) return url; + return resolveURL(url, descriptionURL) ?? url; +} + +/** A URL refused when it names a user or a password (`https://user:secret@host`): HTTP never + * sends one, and a credential there would reach every log and proxy. */ +export function refuseUserinfo(url: string): string { + let parsed: { readonly username?: string; readonly password?: string } | undefined; + try { + parsed = new (platform().URL)(url); + } catch { + return url; + } + if ((parsed.username ?? "") !== "" || (parsed.password ?? "") !== "") { + throw new SdkError("a URL with a user name or password in it is not sent: give the credential by its option"); + } + return url; +} diff --git a/crates/flowapi-sdk/src/client/core/token.ts b/crates/flowapi-sdk/src/client/core/token.ts new file mode 100644 index 0000000..1ef8551 --- /dev/null +++ b/crates/flowapi-sdk/src/client/core/token.ts @@ -0,0 +1,115 @@ +// Generated by flowapi. Do not edit: generate again. +// +// OAuth 2.0's client credentials grant (RFC 6749, 4.4), run by the client for a scheme whose +// table entry has a `clientCredentials` flow. The token endpoint (its URL resolved against the +// base URL where it is relative, its query kept as written, 3.2) is asked with POST, the body +// `grant_type=client_credentials` and the scopes once each (3.2), as +// `application/x-www-form-urlencoded` (Appendix B: UTF-8, then percent-encoded); the client +// authenticates by HTTP basic alone, its id and secret form-encoded first (2.3, 2.3.1), never in +// the body or the URI; over TLS, or to a loopback host (3.2, 10.8). The answer's +// `access_token`, `token_type` (bearer, in any case: a token of another type is not used, 7.1) +// and `expires_in` are read, any other member ignored (5.1); an error answer (5.2) is a +// `TokenError`. A token is held until a little before it expires, one request is made for the +// calls that wait on the same key, and `forget` drops a token the API refused (a 401), so that +// the next call requests another (RFC 6750 3.1). + +import { InsecureCredentialError, TokenError } from "./errors.js"; +import { base64, resolveURL } from "./platform.js"; + +/** The client's own credentials for the client credentials flow; `scopes` and `tokenURL` over + * the config's and the description's. */ +export type ClientCredentials = { + readonly clientId: string; + readonly clientSecret: string; + readonly scopes?: readonly string[] | undefined; + readonly tokenURL?: string | undefined; +}; + +/** How the token endpoint is asked: the client's `fetch`, under its timeout, redirects refused. */ +export type Post = (url: string, headers: Record, body: string) => Promise<{ readonly status: number; readonly text: string }>; + +/** A token held, and the time (ms since the epoch) it is no longer used; `null` for never. */ +type Held = { readonly token: string; readonly until: number | null }; + +/** The longest a token is dropped before it expires: 30 s, or half its life when shorter. */ +const MARGIN = 30_000; + +/** A name or value in `application/x-www-form-urlencoded` (RFC 6749 Appendix B): its UTF-8 bytes, + * each but a letter, a digit and `-._` percent-encoded, a space as `+`. */ +export function formEncode(text: string): string { + return encodeURIComponent(text) + .replace(/[!'()*~]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`) + .replace(/%20/g, "+"); +} + +/** What a held token is found by: the scheme, the endpoint, the client and the scopes. */ +export function flowKey(scheme: string, url: string, clientId: string, scopes: readonly string[]): string { + return JSON.stringify([scheme, url, clientId, [...scopes].sort()]); +} + +/** The tokens of one client. */ +export class Tokens { + readonly #held = new Map(); + readonly #asked = new Map>(); + readonly #post: Post; + readonly #insecure: boolean; + + constructor(post: Post, allowInsecure: boolean) { + this.#post = post; + this.#insecure = allowInsecure; + } + + /** A token for `key`: the one held while it is fresh, else the one being requested, else a new + * one requested of `url` (resolved against `base`). */ + token(key: string, url: string, base: string | null, client: ClientCredentials, scopes: readonly string[]): Promise { + const held = this.#held.get(key); + if (held !== undefined && (held.until === null || Date.now() < held.until)) return Promise.resolve(held.token); + const asked = this.#asked.get(key); + if (asked !== undefined) return asked; + const next = this.#request(key, url, base, client, scopes).finally(() => this.#asked.delete(key)); + this.#asked.set(key, next); + return next; + } + + /** Drops the token held for `key`. */ + forget(key: string): void { + this.#held.delete(key); + } + + async #request(key: string, url: string, base: string | null, client: ClientCredentials, scopes: readonly string[]): Promise { + const at = base === null ? url : (resolveURL(url, base) ?? url); + if (!this.#insecure && !/^https:/i.test(at) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(at)) { + throw new InsecureCredentialError(at); + } + let body = "grant_type=client_credentials"; + const once = [...new Set(scopes)]; + if (once.length > 0) body += `&scope=${formEncode(once.join(" "))}`; + const headers = { + authorization: `Basic ${base64(`${formEncode(client.clientId)}:${formEncode(client.clientSecret)}`)}`, + "content-type": "application/x-www-form-urlencoded", + accept: "application/json", + }; + const sent = Date.now(); + const answer = await this.#post(at, headers, body); + let parsed: unknown; + try { + parsed = JSON.parse(answer.text); + } catch { + parsed = undefined; + } + const o = (typeof parsed === "object" && parsed !== null ? parsed : {}) as { [member: string]: unknown }; + if (answer.status < 200 || answer.status >= 300) throw TokenError.of(answer.status, o, answer.text); + const token = o["access_token"]; + const type = o["token_type"]; + if (typeof token !== "string" || token === "") { + throw new TokenError(answer.status, "invalid_response", "the token endpoint answered without an `access_token`", null); + } + if (typeof type !== "string" || type.toLowerCase() !== "bearer") { + throw new TokenError(answer.status, "unsupported_token_type", `the token type ${JSON.stringify(type)} is not bearer: the client does not use a token it does not understand`, null); + } + const life = typeof o["expires_in"] === "string" ? Number(o["expires_in"]) : o["expires_in"]; + const until = typeof life === "number" && Number.isFinite(life) ? sent + Math.max(0, life * 1000 - Math.min(MARGIN, life * 500)) : null; + this.#held.set(key, { token, until }); + return token; + } +} diff --git a/crates/flowapi-sdk/src/client/entry.rs b/crates/flowapi-sdk/src/client/entry.rs index d4b2f56..16f7e1d 100644 --- a/crates/flowapi-sdk/src/client/entry.rs +++ b/crates/flowapi-sdk/src/client/entry.rs @@ -7,7 +7,8 @@ use super::camel; use super::resources::{class_of, member_of, path_of}; -use crate::config::model::Config; +use crate::config::auth::{has_token_flow, is_basic}; +use crate::config::model::{Config, Credential}; use crate::model::{Auth, Service}; use crate::words::{self, pascal}; use flowapi_ts::string_literal as lit; @@ -28,6 +29,11 @@ fn names(c: &Config) -> (String, String) { (client, options) } +/// The environment variable the client reads its log level from: `SHOP_LOG` for `Shop`. +pub(crate) fn log_env(client: &str) -> String { + format!("{}_LOG", words::upper(&words::words(client))) +} + /// `src/client.ts`. pub(crate) fn client(c: &Config, service: &Service) -> String { let (client, options) = names(c); @@ -71,30 +77,15 @@ pub(crate) fn client(c: &Config, service: &Service) -> String { if let Some(v) = &s.base_url_env { let _ = writeln!(out, " baseURLEnv: {},", lit(v)); } - let log = format!("{}_LOG", words::upper(&words::words(&client))); - let _ = writeln!(out, " logEnv: {},", lit(&log)); - let auth: Vec = c - .auth - .iter() - .map(|a| { - let option = camel(&words::words(&a.name)); - let env = s - .auth_env - .iter() - .find(|(n, _)| *n == a.name) - .map(|(_, v)| format!(", env: {}", lit(v))); - format!( - "{}: {{ option: {}{} }}", - lit(&a.name), - lit(&option), - env.unwrap_or_default() - ) - }) - .collect(); + let _ = writeln!(out, " logEnv: {},", lit(&log_env(&client))); + let auth: Vec = c.auth.iter().map(setting).collect(); let _ = writeln!(out, " auth: {{ {} }},", auth.join(", ")); let _ = writeln!(out, " timeout: {},", ms(s.timeout, 60.0)); - let _ = writeln!(out, " maxRetries: {},", s.retries.unwrap_or(2)); + let _ = writeln!(out, " maxRetries: {},", s.retries.unwrap_or(1)); let _ = writeln!(out, " maxRetryDelay: {},", ms(s.max_retry_delay, 60.0)); + if let Some(h) = &s.idempotency_key { + let _ = writeln!(out, " idempotencyHeader: {},", lit(h)); + } out.push_str(" servers: $api.flowapiServers,\n schemes: $api.flowapiSecuritySchemes,\n readsBytes: $api.flowapiReadsBytes,\n};\n"); options_type(c, service, &client, &options, &mut out); class(c, &client, &options, &top, &mut out); @@ -119,41 +110,146 @@ fn options_type(c: &Config, service: &Service, client: &str, options: &str, out: "export type {options} = $core.ClientOptions<{env_type}> & {{" ); for a in &c.auth { - let scheme = service.schemes.iter().find(|x| x.name == a.name); - let basic = scheme - .is_some_and(|x| matches!(&x.auth, Auth::Http { scheme, .. } if scheme == "basic")); - let env = s - .auth_env - .iter() - .find(|(n, _)| *n == a.name) - .map(|(_, v)| format!(", else `{v}`")) - .unwrap_or_default(); - let _ = writeln!( - out, - " /** The credential of the security scheme `{}`{env}; `null` reads no variable. */", - super::doc(&a.name) - ); - let kind = if basic { - "BasicCredential" + let Some(scheme) = service.schemes.iter().find(|x| x.name == a.name.name) else { + continue; + }; + let (kind, what) = match &scheme.auth { + auth if is_basic(auth) => ( + "$core.BasicCredential", + "an HTTP basic user-id and password", + ), + auth if has_token_flow(auth) => ( + "$core.Credential | $core.ClientCredentials", + "a token, or the client's id and secret to request one with", + ), + Auth::MutualTls => ( + "true", + "`true` when `fetch` presents the client certificate", + ), + Auth::ApiKey { .. } => ("$core.Credential", "the key"), + Auth::Http { .. } | Auth::OAuth2 { .. } | Auth::OpenIdConnect { .. } => { + ("$core.Credential", "the token") + } + }; + let vars: Vec = a.env.iter().map(|(_, v)| format!("`{}`", v.name)).collect(); + let env = if vars.is_empty() { + String::new() } else { - "Credential" + format!(", else {}", vars.join(", ")) }; - let option = camel(&words::words(&a.name)); - let key = if option.starts_with(|c: char| c.is_ascii_alphabetic()) { - option + let deprecated = if scheme.deprecated { + " @deprecated The description deprecates this scheme." } else { - lit(&option) + "" }; - let _ = writeln!(out, " {key}?: $core.{kind} | null | undefined;"); + let _ = writeln!( + out, + " /** The credential of the security scheme `{}`: {what}{env}; `null` reads no variable.{deprecated} */", + super::doc(&a.name.name) + ); + let _ = writeln!(out, " {}?: {kind} | null | undefined;", key(&a.name.name)); + } + let variables = server_variables(service); + if !variables.is_empty() { + out.push_str(" /** Values of the servers' variables, over their defaults. */\n"); + let members: Vec = variables + .iter() + .map(|(name, _, values)| { + let ty = if values.is_empty() { + String::from("string") + } else { + values + .iter() + .map(|v| lit(v)) + .collect::>() + .join(" | ") + }; + format!("{}?: {ty} | undefined", lit(name)) + }) + .collect(); + let _ = writeln!( + out, + " serverVariables?: {{ {} }} | undefined;", + members.join("; ") + ); } out.push_str("};\n"); } +/// Every variable of the description's servers and the operations' own, by name, with the first +/// server's default of it and the values it may take: those of its `enum` where each server that +/// has it gives one, else none (any). +pub(crate) fn server_variables(service: &Service) -> Vec<(String, String, Vec)> { + let mut out: Vec<(String, String, Option>)> = Vec::new(); + let servers = service + .servers + .iter() + .chain(service.operations.iter().flat_map(|a| a.servers.iter())); + for v in servers.flat_map(|s| s.variables.iter()) { + let values = (!v.values.is_empty()).then(|| v.values.clone()); + match out.iter_mut().find(|(n, ..)| *n == v.name) { + None => out.push((v.name.clone(), v.default.clone(), values)), + Some((_, _, seen)) => { + *seen = match (seen.take(), values) { + (Some(mut a), Some(b)) => { + for x in b { + if !a.contains(&x) { + a.push(x); + } + } + Some(a) + } + (None, _) | (_, None) => None, + } + } + } + } + out.into_iter() + .map(|(n, d, v)| (n, d, v.unwrap_or_default())) + .collect() +} + +/// A credential's option as a member's key: its scheme's name in camel case, quoted where it +/// does not open with a letter. +fn key(scheme: &str) -> String { + let option = camel(&words::words(scheme)); + if option.starts_with(|c: char| c.is_ascii_alphabetic()) { + option + } else { + lit(&option) + } +} + +/// A credential's setting: its option and the variables it is read from, and the scopes its +/// tokens are requested with. +fn setting(a: &Credential) -> String { + let mut fields = format!("option: {}", lit(&camel(&words::words(&a.name.name)))); + for (member, var) in &a.env { + let name = match *member { + "username_env_var" => "usernameEnv", + "password_env_var" => "passwordEnv", + "client_id_env_var" => "clientIdEnv", + "client_secret_env_var" => "clientSecretEnv", + _ => "env", + }; + let _ = write!(fields, ", {name}: {}", lit(&var.name)); + } + if let Some((scopes, _)) = &a.scopes { + let scopes: Vec = scopes.iter().map(|s| lit(s)).collect(); + let _ = write!(fields, ", scopes: [{}]", scopes.join(", ")); + } + format!("{}: {{ {fields} }}", lit(&a.name.name)) +} + /// The client class. fn class(c: &Config, client: &str, options: &str, top: &[usize], out: &mut String) { + let example = top + .first() + .map(|&i| format!(" (`client.{}`)", member_of(c, i))) + .unwrap_or_default(); let _ = writeln!( out, - "\n/** The API's client: a member for each resource of the config. */" + "\n/** The API's client: a member for each resource{example}, and `request` for a call no\n * operation describes. */" ); let _ = writeln!(out, "export class {client} {{"); out.push_str(" readonly #core: $core.Core;\n"); @@ -198,7 +294,8 @@ fn class(c: &Config, client: &str, options: &str, top: &[usize], out: &mut Strin )); } -/// `src/index.ts`: the client, its options, the runtime's errors and types, and the API module. +/// `src/index.ts`: the client, its options, the runtime's errors and types (those `api.md` writes +/// a method's signature with among them: `Input`, `Data`, `ItemOf`), and the API module. pub(crate) fn index(c: &Config) -> String { let (client, options) = names(c); let mut out = String::from( @@ -210,12 +307,13 @@ pub(crate) fn index(c: &Config) -> String { ); out.push_str(concat!( "export {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIError,\n APIUserAbortError,\n", - " ApiCall,\n AuthenticationError,\n BadRequestError,\n type BasicCredential,\n ConflictError,\n", - " type Credential,\n CrossOriginRedirectError,\n type Fetch,\n type FetchResponse,\n", - " type HeadersInput,\n InternalServerError,\n type LogLevel,\n type Logger,\n NotFoundError,\n", - " Page,\n PagePromise,\n PermissionDeniedError,\n type QueryInput,\n RateLimitError,\n", - " type RequestOptions,\n RequestTimeoutError,\n SdkError,\n type ServerSentEvent,\n Stream,\n", - " UnprocessableEntityError,\n} from \"./core/index.js\";\nexport * from \"./api.js\";\n", + " ApiCall,\n AuthenticationError,\n BadRequestError,\n type BasicCredential,\n type BasicPair,\n", + " type ClientCredentials,\n ConflictError,\n type Credential,\n CredentialError,\n", + " CrossOriginRedirectError,\n type Data,\n type Fetch,\n type FetchResponse,\n", + " type HeadersInput,\n type Input,\n InsecureCredentialError,\n InternalServerError,\n type ItemOf,\n type LogLevel,\n", + " type Logger,\n NotFoundError,\n type Outcome,\n Page,\n PagePromise,\n PermissionDeniedError,\n", + " type QueryInput,\n RateLimitError,\n type RawRequest,\n type RequestOptions,\n RequestTimeoutError,\n SdkError,\n type ServerSentEvent,\n Stream,\n", + " TokenError,\n UnprocessableEntityError,\n} from \"./core/index.js\";\nexport * from \"./api.js\";\n", )); out } diff --git a/crates/flowapi-sdk/src/client/resources.rs b/crates/flowapi-sdk/src/client/resources.rs index c89c606..5d9d726 100644 --- a/crates/flowapi-sdk/src/client/resources.rs +++ b/crates/flowapi-sdk/src/client/resources.rs @@ -5,7 +5,7 @@ //! methods and members in camel case, classes in Pascal case, files in kebab case. A class //! imports another under a `$` name, which no word can make, so no name of the config shadows one. -use super::{camel, doc}; +use super::{camel, comment}; use crate::config::check::{effective, find}; use crate::config::issue::Issues; use crate::config::model::{Config, Method}; @@ -61,6 +61,21 @@ pub(crate) fn member_of(c: &Config, resource: usize) -> String { .unwrap_or_default() } +/// A resource as a caller reaches it from the client: `pets.photos`. +pub(crate) fn access_of(c: &Config, resource: usize) -> String { + let mut members = Vec::new(); + let mut next = Some(resource); + while let Some(r) = next { + members.push(member_of(c, r)); + next = c.resources.get(r).and_then(|x| x.parent); + if members.len() > c.resources.len() { + break; + } + } + members.reverse(); + members.join(".") +} + /// Every resource's file. pub(crate) fn files(ctx: &Context<'_>, issues: &mut Issues) -> Vec { let c = ctx.config; @@ -87,7 +102,11 @@ pub(crate) fn files(ctx: &Context<'_>, issues: &mut Issues) -> Vec { "import {{ {class} as ${class} }} from \"./{leaf}/{file}.js\";" ); } - let _ = writeln!(text, "\n/** The resource `{}`. */", c.path(i)); + let _ = writeln!( + text, + "\n/** The methods of `client.{}`. */", + access_of(c, i) + ); let _ = writeln!(text, "export class {} {{", class_of(c, i)); text.push_str(" readonly #core: $core.Core;\n"); for &j in &children { @@ -129,21 +148,18 @@ fn method(ctx: &Context<'_>, k: usize, m: &Method, out: &mut String, issues: &mu }; let op = &e.operation; let name = camel(&words::words(&m.name.name)); - let summary = ctx + let described = ctx .resolved .get(k) .copied() .flatten() - .and_then(|i| ctx.ops.list.get(i)) - .and_then(|o| o.summary.as_deref()) - .map(|s| format!(": {}", doc(s))) - .unwrap_or_default(); - let _ = writeln!( - out, - "\n /** `{} {}`{summary} */", - flowapi_ts::sdk_method(op), - doc(&op.path) - ); + .and_then(|i| ctx.ops.list.get(i)); + out.push('\n'); + out.push_str(&comment::method( + described, + &flowapi_ts::sdk_method(op), + &op.path, + )); let optional = !op.params.iter().any(|p| p.required) && !op.body.as_ref().is_some_and(|b| b.required); let params = format!( @@ -190,7 +206,7 @@ fn method(ctx: &Context<'_>, k: usize, m: &Method, out: &mut String, issues: &mu } /// Whether every streamed 2xx response is server-sent events. -fn sse_only(op: &Operation) -> bool { +pub(crate) fn sse_only(op: &Operation) -> bool { op.responses .iter() .filter(|r| r.status.starts_with('2')) diff --git a/crates/flowapi-sdk/src/config.rs b/crates/flowapi-sdk/src/config.rs index f663352..1777cb5 100644 --- a/crates/flowapi-sdk/src/config.rs +++ b/crates/flowapi-sdk/src/config.rs @@ -5,6 +5,7 @@ //! turns an issue's offset into the YAML's line and column), the description as the core's //! [`Documents`]. No I/O (G5). +pub(crate) mod auth; mod build; pub(crate) mod check; pub(crate) mod issue; @@ -74,7 +75,8 @@ pub(crate) fn checked(docs: &Documents<'_>, config: &str) -> Checked { resolved = check::references(&c, &ops, &mut issues); names::check(&c, &ops.schema_names, &mut issues); check::methods(&c, &ops, &resolved, &mut issues); - check::rest(&c, &ops, &resolved, &mut issues); + check::rest(&c, &resolved, &mut issues); + auth::check(&c, &ops, &resolved, &mut issues); } None => { let message = String::from("the description is not an OpenAPI or Swagger description"); diff --git a/crates/flowapi-sdk/src/config/auth.rs b/crates/flowapi-sdk/src/config/auth.rs new file mode 100644 index 0000000..fb0e741 --- /dev/null +++ b/crates/flowapi-sdk/src/config/auth.rs @@ -0,0 +1,336 @@ +//! `auth` and `security`, the credentials a client sends: the schemes the description declares, +//! each given its options (`env_var`, ...), and those it lacks, declared by the config with +//! `type` and the members of their kind, as OpenAPI's Security Scheme Object names them; then +//! `security` at the top, over every operation with none of its own (as the description's +//! `security` is), and a method's own over everything. A scheme of the description may only be +//! given options: what it is stays the description's. `auth/usage.rs` holds the config to what +//! the operations then need. [`apply`] gives the service the client is printed from. + +mod usage; + +use super::issue::{Issues, closest}; +use super::model::{Config, Credential, Method, Security}; +use crate::model::{Auth, KeyLocation, Requirement, Scheme, Service, TokenFlow}; +use crate::ops::{Op, Ops}; +use flowapi::Diagnostics; + +/// HTTP authentication schemes (IANA's registry) a client cannot send up front: each answers a +/// challenge of the server's, or signs each request with a proof of its own. +pub(crate) const CHALLENGED: &[&str] = &[ + "concealed", + "digest", + "dpop", + "hoba", + "mutual", + "negotiate", + "oauth", + "privatetoken", + "scram-sha-1", + "scram-sha-256", +]; + +/// Whether a scheme's credential is HTTP basic's pair. +pub(crate) fn is_basic(auth: &Auth) -> bool { + matches!(auth, Auth::Http { scheme, .. } if scheme == "basic") +} + +/// Whether the client may request a scheme's token itself (OAuth 2.0 client credentials). +pub(crate) fn has_token_flow(auth: &Auth) -> bool { + matches!( + auth, + Auth::OAuth2 { + client_credentials: Some(_), + .. + } + ) +} + +/// The scheme a credential declares, when its `type` and the members of its kind are given. +fn declared(a: &Credential) -> Option { + let value = |n: &Option| n.as_ref().map(|n| n.name.clone()); + Some(match a.kind.as_ref()?.name.as_str() { + "apiKey" => Auth::ApiKey { + location: match value(&a.location)?.as_str() { + "header" => KeyLocation::Header, + "query" => KeyLocation::Query, + "cookie" => KeyLocation::Cookie, + _ => return None, + }, + name: value(&a.key)?, + }, + "http" => Auth::Http { + scheme: value(&a.scheme)?.to_ascii_lowercase(), + format: None, + }, + "oauth2" => { + let flow = value(&a.token_url).map(|token_url| TokenFlow { + token_url, + scopes: Vec::new(), + }); + Auth::OAuth2 { + flows: flow + .iter() + .map(|_| String::from("clientCredentials")) + .collect(), + client_credentials: flow, + } + } + "mutualTLS" => Auth::MutualTls, + _ => return None, + }) +} + +/// The description's schemes, then each one the config declares, in the config's order. +pub(crate) fn schemes(c: &Config, described: Vec) -> Vec { + let mut out = described; + for a in &c.auth { + if out.iter().any(|s| s.name == a.name.name) { + continue; + } + if let Some(auth) = declared(a) { + out.push(Scheme { + name: a.name.name.clone(), + auth, + description: a.description.clone(), + deprecated: false, + }); + } + } + out +} + +/// A config's `security` as requirements. +pub(crate) fn requirements(s: &Security) -> Vec { + s.alternatives + .iter() + .map(|alt| Requirement { + schemes: alt + .iter() + .map(|(n, scopes)| (n.name.clone(), scopes.clone())) + .collect(), + }) + .collect() +} + +/// An operation's security once the config is over it: the method's own, else (where the +/// operation has none of its own) the config's top-level, else the description's. +pub(crate) fn over( + c: &Config, + method: Option<&Method>, + security: Vec, + inherits: bool, +) -> Vec { + if let Some(own) = method.and_then(|m| m.security.as_ref()) { + return requirements(own); + } + match &c.security { + Some(top) if inherits => requirements(top), + Some(_) | None => security, + } +} + +/// What a method's operation needs once the config is over it (`over`), read from the +/// description. +pub(crate) fn needed( + c: &Config, + ops: &Ops<'_, '_>, + method: Option<&Method>, + op: &Op, +) -> Vec { + let root = ops + .doc + .security(crate::doc::ROOT, &mut Diagnostics::default()) + .unwrap_or_default(); + let (own, inherits) = ops + .doc + .effective(&op.operation, &root, &mut Diagnostics::default()); + over(c, method, own, inherits) +} + +/// The service a client is printed from: the description's, with the schemes the config +/// declares and its `security` over the operations'. `endpoints` is each method's endpoint. +pub(crate) fn apply(c: &Config, service: &mut Service, endpoints: &[Option]) { + service.schemes = schemes(c, std::mem::take(&mut service.schemes)); + for (e, access) in service.operations.iter_mut().enumerate() { + let method = c + .methods + .iter() + .zip(endpoints) + .find(|(_, at)| **at == Some(e)) + .map(|(m, _)| m); + let security = std::mem::take(&mut access.security); + access.security = over(c, method, security, access.inherits); + } +} + +/// `auth` and `security` held to the description and to what each method's operation needs. +pub(crate) fn check( + c: &Config, + ops: &Ops<'_, '_>, + resolved: &[Option], + issues: &mut Issues, +) { + let described = ops.doc.schemes(&mut Diagnostics::default()); + for a in &c.auth { + credential(a, &described, issues); + } + let all = schemes(c, described.clone()); + let names: Vec<&str> = all.iter().map(|s| s.name.as_str()).collect(); + let securities = c + .security + .iter() + .chain(c.methods.iter().filter_map(|m| m.security.as_ref())); + for s in securities { + for (n, _) in s.alternatives.iter().flatten() { + if !names.contains(&n.name.as_str()) { + let hint = + closest(&n.name, names.iter().copied()).map(|n| format!("did you mean `{n}`?")); + let message = format!( + "`{}` names no security scheme of the description or of `auth`", + n.name + ); + issues.error_hint("config.security.unknown", &n.at, message, hint); + } + } + } + usage::check(c, ops, resolved, &all, issues); +} + +/// One credential: a scheme of the description given options, or one the config declares. +fn credential(a: &Credential, described: &[Scheme], issues: &mut Issues) { + let name = &a.name.name; + let auth = match described.iter().find(|s| s.name == *name) { + Some(s) => { + if let Some(n) = a.declares() { + let message = format!( + "`{name}` is a security scheme of the description: the config may give it options (its environment variables, `scopes`), not say again what it is" + ); + issues.error("config.auth.declared", &n.at, message); + } + if s.deprecated { + let message = format!( + "`{name}` is deprecated by the description: its consumers should refrain from it" + ); + issues.warn("config.auth.deprecated", &a.name.at, message); + } + s.auth.clone() + } + None => { + let Some(auth) = declaration(a, described, issues) else { + return; + }; + auth + } + }; + options(a, &auth, issues); + match &auth { + Auth::Http { scheme, .. } if CHALLENGED.contains(&scheme.as_str()) => { + let message = format!( + "`{name}` is HTTP `{scheme}`, which answers a challenge or signs each request: the client cannot send it; give `Authorization` in a call's `headers`" + ); + issues.warn("config.auth.refused", &a.name.at, message); + } + Auth::MutualTls => { + let message = format!( + "`{name}` is a client certificate, which no request carries: give the client a `fetch` (or `fetchOptions`) that presents it, and the option `true` to say so" + ); + issues.warn("config.auth.mutual_tls", &a.name.at, message); + } + Auth::ApiKey { .. } + | Auth::Http { .. } + | Auth::OAuth2 { .. } + | Auth::OpenIdConnect { .. } => {} + } +} + +/// A scheme the description lacks, as the config declares it; `None`, with an error, when it +/// cannot be read. +fn declaration(a: &Credential, described: &[Scheme], issues: &mut Issues) -> Option { + let name = &a.name.name; + let Some(kind) = &a.kind else { + let message = if described.is_empty() { + format!("`{name}` names no security scheme: the description has none") + } else { + format!("`{name}` names no security scheme of the description") + }; + let hint = closest(name, described.iter().map(|s| s.name.as_str())) + .map(|n| format!("did you mean `{n}`?")) + .or_else(|| Some(String::from("give `type` (and the members of its kind) to declare a scheme the description lacks"))); + issues.error_hint("config.auth.unknown", &a.name.at, message, hint); + return None; + }; + let wants: &[&str] = match kind.name.as_str() { + "apiKey" => &["in", "name"], + "http" => &["scheme"], + "oauth2" | "mutualTLS" => &[], + _ => return None, + }; + let given = [ + ("scheme", &a.scheme), + ("in", &a.location), + ("name", &a.key), + ("token_url", &a.token_url), + ]; + for (member, value) in given { + let allowed = wants.contains(&member) || (member == "token_url" && kind.name == "oauth2"); + match value { + Some(v) if !allowed => { + let message = format!( + "`{member}` is no member of a scheme of type `{}`", + kind.name + ); + issues.error("config.auth.field", &v.at, message); + } + None if wants.contains(&member) => { + let message = format!("`{name}`, of type `{}`, needs `{member}`", kind.name); + issues.error("config.auth.field", &kind.at, message); + } + Some(_) | None => {} + } + } + declared(a) +} + +/// The options a credential gives, held to its scheme's kind: each pair given whole. +fn options(a: &Credential, auth: &Auth, issues: &mut Issues) { + let pairs: [(&str, &str, bool, &str); 2] = [ + ( + "username_env_var", + "password_env_var", + is_basic(auth), + "HTTP basic", + ), + ( + "client_id_env_var", + "client_secret_env_var", + has_token_flow(auth), + "OAuth 2.0 with a client credentials flow", + ), + ]; + for (one, other, fits, kind) in pairs { + for (member, pair) in [(one, other), (other, one)] { + let Some((_, n)) = a.env.iter().find(|(m, _)| *m == member) else { + continue; + }; + if !fits { + let message = format!("`{member}` is for {kind} only"); + issues.error("config.auth.option", &n.at, message); + } else if a.var(pair).is_none() { + let message = format!("`{member}` is given without `{pair}`"); + issues.error("config.auth.option", &n.at, message); + } + } + } + if let Some((_, at)) = &a.scopes + && !has_token_flow(auth) + { + let message = String::from( + "`scopes` is for OAuth 2.0 with a client credentials flow only: other tokens are the caller's", + ); + issues.error("config.auth.option", at, message); + } + if let (Auth::MutualTls, Some((_, n))) = (auth, a.env.first()) { + let message = String::from("a client certificate is read from no environment variable"); + issues.error("config.auth.option", &n.at, message); + } +} diff --git a/crates/flowapi-sdk/src/config/auth/usage.rs b/crates/flowapi-sdk/src/config/auth/usage.rs new file mode 100644 index 0000000..6595ffe --- /dev/null +++ b/crates/flowapi-sdk/src/config/auth/usage.rs @@ -0,0 +1,89 @@ +//! `auth` held to what the methods' operations need, once the config's `security` is over +//! theirs: a scheme they need that `auth` does not list is sent by no credential, one listed +//! with no environment variable only by its option, and a config whose operations need no +//! scheme at all sends nothing (`config.auth.none`), unless its top-level `security: []` says +//! so on purpose: an API that needs a credential its description does not declare needs `auth` +//! and `security` here. + +use super::{CHALLENGED, has_token_flow, is_basic, needed}; +use crate::config::check::root; +use crate::config::issue::Issues; +use crate::config::model::Config; +use crate::model::{Auth, Scheme}; +use crate::ops::Ops; + +/// Each scheme some method's operation needs, with the first method that needs it. +fn used(c: &Config, ops: &Ops<'_, '_>, resolved: &[Option]) -> Vec<(String, usize)> { + let mut out: Vec<(String, usize)> = Vec::new(); + for (i, (m, op)) in c.methods.iter().zip(resolved).enumerate() { + let Some(op) = op.and_then(|o| ops.list.get(o)) else { + continue; + }; + for r in needed(c, ops, Some(m), op) { + for (name, _) in r.schemes { + if !out.iter().any(|(n, _)| *n == name) { + out.push((name, i)); + } + } + } + } + out +} + +/// Whether a credential names the environment variables its scheme is read from. +fn has_env(c: &Config, name: &str, auth: &Auth) -> bool { + let Some(a) = c.auth.iter().find(|a| a.name.name == name) else { + return false; + }; + let pair = |x: &str, y: &str| a.var(x).is_some() && a.var(y).is_some(); + a.var("env_var").is_some() + || (is_basic(auth) && pair("username_env_var", "password_env_var")) + || (has_token_flow(auth) && pair("client_id_env_var", "client_secret_env_var")) +} + +pub(super) fn check( + c: &Config, + ops: &Ops<'_, '_>, + resolved: &[Option], + schemes: &[Scheme], + issues: &mut Issues, +) { + let used = used(c, ops, resolved); + let said = c + .security + .as_ref() + .is_some_and(|s| s.alternatives.is_empty()); + if used.is_empty() && !c.methods.is_empty() && !said { + let message = String::from( + "no operation needs a credential, by the description's `security` or the config's: the client sends none; if the API takes one, declare it under `auth` and name it in `security`; `security: []` says it takes none", + ); + let at = c.auth.first().map_or_else(root, |a| a.name.at.clone()); + issues.warn("config.auth.none", &at, message); + } + for (name, i) in used { + let Some(scheme) = schemes.iter().find(|s| s.name == name) else { + continue; + }; + let Some(m) = c.methods.get(i) else { continue }; + let place = format!("{}.{}", c.path(m.resource), m.name.name); + let listed = c.auth.iter().find(|a| a.name.name == name); + match (listed, &scheme.auth) { + (None, _) => { + let message = format!( + "`{place}` needs `{name}`, which `auth` does not list: the client sends no credential for it" + ); + issues.warn("config.auth.unlisted", &m.name.at, message); + } + // No variable gives a client certificate or answers a challenge: `credential` warned. + (Some(_), Auth::MutualTls) => {} + (Some(_), Auth::Http { scheme, .. }) if CHALLENGED.contains(&scheme.as_str()) => {} + (Some(a), auth) if !has_env(c, &name, auth) => { + let message = format!( + "`{name}` names no environment variable: the client sends it only when given its option" + ); + issues.warn("config.auth.env", &a.name.at, message); + } + (Some(_), _) => {} + } + } +} diff --git a/crates/flowapi-sdk/src/config/build.rs b/crates/flowapi-sdk/src/config/build.rs index 131c896..6dcc5b9 100644 --- a/crates/flowapi-sdk/src/config/build.rs +++ b/crates/flowapi-sdk/src/config/build.rs @@ -4,12 +4,14 @@ //! keep the format, its JSON Schema and this reader one thing. A value of the wrong type was //! reported already and is passed over. +mod members; + use super::issue::{At, Issues}; -use super::model::{Config, Method, Named, PagingRef, Resource, Scheme}; -use super::shape::{self, Field, SCHEMES}; -use crate::paging::{Paging, roles}; +use super::model::{Config, Named, Resource, Scheme}; +use super::shape::{self, Field}; use flowapi::id::NodeId; use flowapi::json::{Tree, Value}; +use members::{credential, method, scheme, security}; struct B<'a, 't> { tree: &'a Tree<'t>, @@ -135,6 +137,11 @@ pub(crate) fn build(tree: &Tree<'_>, declared: &[(NodeId, At)], issues: &mut Iss c.client = b.named(p, &at, shape::PACKAGE, "client"); c.license = b.named(p, &at, shape::PACKAGE, "license"); c.settings.repository = b.text(p, &at, shape::PACKAGE, "repository"); + c.settings.description = b.text(p, &at, shape::PACKAGE, "description"); + if let Some((k, _)) = b.field(p, &at, shape::PACKAGE, "keywords") { + let tree = b.tree; + c.settings.keywords = tree.items(k).iter().filter_map(|&n| b.string(n)).collect(); + } } if let Some((e, at)) = b.field(root, &top, shape::ROOT, "environments") { c.default_environment = b.named(e, &at, shape::ENVIRONMENTS_FIXED, "default"); @@ -150,12 +157,12 @@ pub(crate) fn build(tree: &Tree<'_>, declared: &[(NodeId, At)], issues: &mut Iss } if let Some((a, at)) = b.field(root, &top, shape::ROOT, "auth") { for (name, node, at) in b.entries(a, &at, &[]) { - if let Some(var) = b.named(node, &at, shape::AUTH, "env_var") { - c.settings.auth_env.push((name.clone(), var.name)); - } - c.auth.push(Named { name, at }); + c.auth.push(credential(&mut b, Named { name, at }, node)); } } + if let Some((s, at)) = b.field(root, &top, shape::ROOT, "security") { + c.security = Some(security(&mut b, s, &at)); + } if let Some((d, at)) = b.field(root, &top, shape::ROOT, "defaults") { let retries = b.field(d, &at, shape::DEFAULTS, "retries"); c.settings.retries = retries.and_then(|(n, _)| b.number(n)); @@ -163,6 +170,7 @@ pub(crate) fn build(tree: &Tree<'_>, declared: &[(NodeId, At)], issues: &mut Iss c.settings.timeout = timeout.and_then(|(n, _)| b.number(n)); let delay = b.field(d, &at, shape::DEFAULTS, "max_retry_delay"); c.settings.max_retry_delay = delay.and_then(|(n, _)| b.number(n)); + c.settings.idempotency_key = b.text(d, &at, shape::DEFAULTS, "idempotency_key"); c.default_paging = b.named(d, &at, shape::DEFAULTS, "pagination"); } if let Some((p, at)) = b.field(root, &top, shape::ROOT, "pagination") { @@ -204,42 +212,11 @@ fn rest(b: &mut B<'_, '_>, root: NodeId, top: &At, c: &mut Config) { c.readme.push((key, n)); } } + c.settings.title = b.text(r, &at, shape::README, "title"); c.settings.intro = b.text(r, &at, shape::README, "intro"); } } -/// A pagination scheme: its `type` chooses its members. -fn scheme(b: &mut B<'_, '_>, node: NodeId, at: &At) -> Option { - let tag = b.tree.get(node, "type").and_then(|t| b.string(t))?; - let (kind, fields) = SCHEMES.iter().find(|(name, _)| *name == tag)?; - b.field(node, at, fields, "type"); - let mut paging = Paging::new(kind, &[], &[]); - for part in ["request", "response"] { - if !fields.iter().any(|f| f.name == part) { - continue; - } - let Some((obj, at)) = b.field(node, at, fields, part) else { - continue; - }; - for role in roles(kind, part) { - if let Some(value) = b.named(obj, &at, roles(kind, part), role.name) { - let list = if part == "request" { - &mut paging.request - } else { - &mut paging.response - }; - list.push((role.name, value.name)); - } - } - } - if fields.iter().any(|f| f.name == "start") - && let Some((s, _)) = b.field(node, at, fields, "start") - { - paging.start = b.number(s); - } - Some(paging) -} - /// The resource tree, flattened, with each resource's methods. fn resources(b: &mut B<'_, '_>, map: NodeId, at: &At, c: &mut Config) { let mut stack: Vec<(NodeId, At, Option)> = vec![(map, at.clone(), None)]; @@ -270,51 +247,6 @@ fn resources(b: &mut B<'_, '_>, map: NodeId, at: &At, c: &mut Config) { } } -/// A method: an operation's name, or an object with `op` and the method's own settings. -fn method(b: &mut B<'_, '_>, name: Named, value: NodeId, resource: usize) -> Option { - let at = name.at.clone(); - let at = At { - offset: b.tree.offset(value), - ..at - }; - if let Some(op) = b.string(value) { - return Some(Method { - name, - resource, - op: Named { name: op, at }, - paging: PagingRef::Unset, - stream: None, - retries: None, - }); - } - if !b.object(value) { - return None; - } - let op = b.named(value, &at, shape::METHOD, "op")?; - let paging = match b.field(value, &at, shape::METHOD, "pagination") { - Some((p, at)) => match (b.string(p), b.tree.as_bool(p)) { - (Some(s), _) => PagingRef::Scheme(Named { name: s, at }), - (None, Some(false)) => PagingRef::Off, - (None, Some(true) | None) => PagingRef::Unset, - }, - None => PagingRef::Unset, - }; - let retries = b - .field(value, &at, shape::METHOD, "retries") - .and_then(|(n, _)| b.number(n)); - let stream = b - .field(value, &at, shape::METHOD, "stream") - .and_then(|(s, at)| (b.tree.as_bool(s) == Some(true)).then_some(at)); - Some(Method { - name, - resource, - op, - paging, - stream, - retries, - }) -} - /// A member the format names that nothing read: the reader and the format have drifted. fn unread(b: &mut B<'_, '_>, declared: &[(NodeId, At)]) { b.read.sort_unstable(); diff --git a/crates/flowapi-sdk/src/config/build/members.rs b/crates/flowapi-sdk/src/config/build/members.rs new file mode 100644 index 0000000..98110a4 --- /dev/null +++ b/crates/flowapi-sdk/src/config/build/members.rs @@ -0,0 +1,160 @@ +//! The members of a config that are objects of their own, read for `build.rs`: a pagination +//! scheme (its `type` chooses its members), a method (an operation's name, or an object with +//! `op` and the method's own settings), a credential of `auth`, and a `security`. + +use super::B; +use crate::config::issue::At; +use crate::config::model::{Credential, Method, Named, PagingRef, Security}; +use crate::config::shape::{self, SCHEMES}; +use crate::paging::{Paging, roles}; +use flowapi::id::NodeId; + +/// A pagination scheme: its `type` chooses its members. +pub(super) fn scheme(b: &mut B<'_, '_>, node: NodeId, at: &At) -> Option { + let tag = b.tree.get(node, "type").and_then(|t| b.string(t))?; + let (kind, fields) = SCHEMES.iter().find(|(name, _)| *name == tag)?; + b.field(node, at, fields, "type"); + let mut paging = Paging::new(kind, &[], &[]); + for part in ["request", "response"] { + if !fields.iter().any(|f| f.name == part) { + continue; + } + let Some((obj, at)) = b.field(node, at, fields, part) else { + continue; + }; + for role in roles(kind, part) { + if let Some(value) = b.named(obj, &at, roles(kind, part), role.name) { + let list = if part == "request" { + &mut paging.request + } else { + &mut paging.response + }; + list.push((role.name, value.name)); + } + } + } + if fields.iter().any(|f| f.name == "start") + && let Some((s, _)) = b.field(node, at, fields, "start") + { + paging.start = b.number(s); + } + Some(paging) +} + +/// A method: an operation's name, or an object with `op` and the method's own settings. +pub(super) fn method( + b: &mut B<'_, '_>, + name: Named, + value: NodeId, + resource: usize, +) -> Option { + let at = name.at.clone(); + let at = At { + offset: b.tree.offset(value), + ..at + }; + if let Some(op) = b.string(value) { + return Some(Method { + name, + resource, + op: Named { name: op, at }, + paging: PagingRef::Unset, + stream: None, + retries: None, + security: None, + }); + } + if !b.object(value) { + return None; + } + let op = b.named(value, &at, shape::METHOD, "op")?; + let paging = match b.field(value, &at, shape::METHOD, "pagination") { + Some((p, at)) => match (b.string(p), b.tree.as_bool(p)) { + (Some(s), _) => PagingRef::Scheme(Named { name: s, at }), + (None, Some(false)) => PagingRef::Off, + (None, Some(true) | None) => PagingRef::Unset, + }, + None => PagingRef::Unset, + }; + let retries = b + .field(value, &at, shape::METHOD, "retries") + .and_then(|(n, _)| b.number(n)); + let stream = b + .field(value, &at, shape::METHOD, "stream") + .and_then(|(s, at)| (b.tree.as_bool(s) == Some(true)).then_some(at)); + let security = b + .field(value, &at, shape::METHOD, "security") + .map(|(s, at)| security(b, s, &at)); + Some(Method { + name, + resource, + op, + paging, + stream, + retries, + security, + }) +} + +/// The environment variables a credential may name. +const VARS: [&str; 5] = [ + "env_var", + "username_env_var", + "password_env_var", + "client_id_env_var", + "client_secret_env_var", +]; + +/// A credential of `auth`: its options, and what a scheme it declares is. +pub(super) fn credential(b: &mut B<'_, '_>, name: Named, node: NodeId) -> Credential { + let at = name.at.clone(); + let mut c = Credential { + name, + ..Credential::default() + }; + if !b.object(node) { + return c; + } + let fields = shape::AUTH; + c.kind = b.named(node, &at, fields, "type"); + c.scheme = b.named(node, &at, fields, "scheme"); + c.location = b.named(node, &at, fields, "in"); + c.key = b.named(node, &at, fields, "name"); + c.token_url = b.named(node, &at, fields, "token_url"); + c.description = b.text(node, &at, fields, "description"); + for member in VARS { + if let Some(var) = b.named(node, &at, fields, member) { + c.env.push((member, var)); + } + } + if let Some((list, at)) = b.field(node, &at, fields, "scopes") { + let tree = b.tree; + let scopes = tree + .items(list) + .iter() + .filter_map(|&n| b.string(n)) + .collect(); + c.scopes = Some((scopes, at)); + } + c +} + +/// A `security`: each alternative's schemes, by name with where, with their scopes. +pub(super) fn security(b: &mut B<'_, '_>, list: NodeId, at: &At) -> Security { + let tree = b.tree; + let mut alternatives = Vec::new(); + for (i, &item) in tree.items(list).iter().enumerate() { + let item_at = at.child(&i.to_string(), tree.offset(item)); + let mut schemes = Vec::new(); + for (name, scopes, at) in b.entries(item, &item_at, &[]) { + let scopes = tree + .items(scopes) + .iter() + .filter_map(|&n| b.string(n)) + .collect(); + schemes.push((Named { name, at }, scopes)); + } + alternatives.push(schemes); + } + Security { alternatives } +} diff --git a/crates/flowapi-sdk/src/config/check.rs b/crates/flowapi-sdk/src/config/check.rs index 59e12a4..da38913 100644 --- a/crates/flowapi-sdk/src/config/check.rs +++ b/crates/flowapi-sdk/src/config/check.rs @@ -1,15 +1,14 @@ //! The config held to its description (study 03, section 6, items 2, 5 and 6): every reference //! names an operation, no operation is in two places, every operation is in a resource or in //! `skip`; each method's pagination fits its operation; a streamed method's response is a -//! stream; `auth` names the description's security schemes; `default` names an environment; the -//! README's methods exist. +//! stream; `default` names an environment; the README's methods exist. `auth` and `security` are +//! held in `auth.rs`. use super::issue::{At, Issues, closest}; use super::model::{Config, Method, PagingRef}; use crate::ops::{Lookup, Ops}; use crate::paging::{Paging, fit}; use crate::words; -use flowapi::Diagnostics; /// The operation each method calls, by index into `c.methods`; `None` where it names none. pub(crate) fn references(c: &Config, ops: &Ops<'_, '_>, issues: &mut Issues) -> Vec> { @@ -175,29 +174,8 @@ pub(crate) fn streams(op: &flowapi::spec::Operation) -> bool { }) } -/// `auth`, `environments.default` and `readme`, each held to what it names. -pub(crate) fn rest(c: &Config, ops: &Ops<'_, '_>, resolved: &[Option], issues: &mut Issues) { - let schemes: Vec = ops - .doc - .schemes(&mut Diagnostics::default()) - .into_iter() - .map(|s| s.name) - .collect(); - for a in &c.auth { - if !schemes.contains(&a.name) { - let message = if schemes.is_empty() { - format!( - "`{}` names no security scheme: the description has none", - a.name - ) - } else { - format!("`{}` names no security scheme of the description", a.name) - }; - let hint = closest(&a.name, schemes.iter().map(String::as_str)) - .map(|n| format!("did you mean `{n}`?")); - issues.error_hint("config.auth.unknown", &a.at, message, hint); - } - } +/// `environments.default` and `readme`, each held to what it names (`auth` is `auth.rs`'s). +pub(crate) fn rest(c: &Config, resolved: &[Option], issues: &mut Issues) { if let Some(d) = &c.default_environment && !c.environments.iter().any(|e| words::same(&e.name, &d.name)) { diff --git a/crates/flowapi-sdk/src/config/model.rs b/crates/flowapi-sdk/src/config/model.rs index cb06db0..0c9f560 100644 --- a/crates/flowapi-sdk/src/config/model.rs +++ b/crates/flowapi-sdk/src/config/model.rs @@ -5,7 +5,7 @@ use super::issue::At; use crate::paging::Paging; /// A name written as a key, with where. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub(crate) struct Named { pub(crate) name: String, pub(crate) at: At, @@ -42,6 +42,57 @@ pub(crate) struct Method { pub(crate) stream: Option, /// Its own `retries`. pub(crate) retries: Option, + /// Its own `security`. + pub(crate) security: Option, +} + +/// A `security` of the config: OpenAPI's Security Requirement Objects as written. +#[derive(Clone, Debug, Default)] +pub(crate) struct Security { + /// Each alternative: each scheme it needs, by name with where, and its scopes. + pub(crate) alternatives: Vec)>>, +} + +/// A credential of `auth`: the options its scheme is read by and, for a scheme the description +/// lacks, what that scheme is. +#[derive(Debug, Default)] +pub(crate) struct Credential { + /// The scheme's name, the key. + pub(crate) name: Named, + /// `type`, `scheme`, `in`, `name` and `token_url`: a declaration. + pub(crate) kind: Option, + pub(crate) scheme: Option, + pub(crate) location: Option, + pub(crate) key: Option, + pub(crate) token_url: Option, + pub(crate) description: Option, + /// Its environment variables, by member (`env_var`, `username_env_var`, ...). + pub(crate) env: Vec<(&'static str, Named)>, + /// `scopes`, with where. + pub(crate) scopes: Option<(Vec, At)>, +} + +impl Credential { + /// The variable of a member (`env_var`, ...), where one is given. + pub(crate) fn var(&self, member: &str) -> Option<&str> { + self.env + .iter() + .find(|(m, _)| *m == member) + .map(|(_, n)| n.name.as_str()) + } + + /// Whether it declares a scheme (gives any of `type`, `scheme`, `in`, `name`, `token_url`). + pub(crate) fn declares(&self) -> Option<&Named> { + [ + &self.kind, + &self.scheme, + &self.location, + &self.key, + &self.token_url, + ] + .into_iter() + .find_map(Option::as_ref) + } } /// What the generated client is made with beside its resources: values no check is about. @@ -51,19 +102,23 @@ pub(crate) struct Settings { pub(crate) urls: Vec<(String, String)>, /// `environments.env_var`: the variable that overrides the base URL. pub(crate) base_url_env: Option, - /// Each security scheme's `env_var`, by its name. - pub(crate) auth_env: Vec<(String, String)>, /// `defaults.retries`. pub(crate) retries: Option, /// `defaults.timeout`, in seconds. pub(crate) timeout: Option, /// `defaults.max_retry_delay`, in seconds. pub(crate) max_retry_delay: Option, + /// `defaults.idempotency_key`: the header an idempotency key is sent in. + pub(crate) idempotency_key: Option, /// `package.name`, `package.version` and `package.repository`. pub(crate) package: Option, pub(crate) version: Option, pub(crate) repository: Option, - /// `readme.intro`. + /// `package.description` and `package.keywords`. + pub(crate) description: Option, + pub(crate) keywords: Vec, + /// `readme.title` and `readme.intro`. + pub(crate) title: Option, pub(crate) intro: Option, } @@ -84,7 +139,9 @@ pub(crate) struct Config { pub(crate) generator: Option, pub(crate) environments: Vec, pub(crate) default_environment: Option, - pub(crate) auth: Vec, + pub(crate) auth: Vec, + /// The top-level `security`. + pub(crate) security: Option, pub(crate) default_paging: Option, pub(crate) schemes: Vec, pub(crate) resources: Vec, diff --git a/crates/flowapi-sdk/src/config/names.rs b/crates/flowapi-sdk/src/config/names.rs index 7eb5f64..8f01af2 100644 --- a/crates/flowapi-sdk/src/config/names.rs +++ b/crates/flowapi-sdk/src/config/names.rs @@ -113,18 +113,22 @@ pub(crate) fn check(c: &Config, schema_names: &[String], issues: &mut Issues) { let schemes: Vec<(&Named, &'static str)> = c.schemes.iter().map(|s| (&s.name, "scheme")).collect(); siblings(&schemes, "`pagination`", issues); - let auth: Vec<(&Named, &'static str)> = c.auth.iter().map(|n| (n, "credential")).collect(); + let auth: Vec<(&Named, &'static str)> = + c.auth.iter().map(|a| (&a.name, "credential")).collect(); siblings(&auth, "`auth`", issues); for a in &c.auth { - if words::words(&a.name).is_empty() { + if words::words(&a.name.name).is_empty() { let message = format!( "the scheme `{}` has no letter or digit to name its option", - a.name + a.name.name ); - issues.error("config.name.option", &a.at, message); - } else if reserved(&a.name, CLIENT_OPTIONS) { - let message = format!("the scheme `{}` would be the client's own option", a.name); - issues.error("config.name.option", &a.at, message); + issues.error("config.name.option", &a.name.at, message); + } else if reserved(&a.name.name, CLIENT_OPTIONS) { + let message = format!( + "the scheme `{}` would be the client's own option", + a.name.name + ); + issues.error("config.name.option", &a.name.at, message); } } } diff --git a/crates/flowapi-sdk/src/config/schema.rs b/crates/flowapi-sdk/src/config/schema.rs index f546b7e..52eceb8 100644 --- a/crates/flowapi-sdk/src/config/schema.rs +++ b/crates/flowapi-sdk/src/config/schema.rs @@ -73,6 +73,9 @@ fn shape(sh: &'static Shape, defs: &mut Vec<(&'static str, J)>) -> J { if *kind == Str::Url { m.push(("format", s("uri"))); } + if let Str::OneOf(_, words) = kind { + m.push(("enum", J::List(words.iter().map(|w| s(w)).collect()))); + } J::Obj(m) } Shape::Int(min, max) => J::Obj(vec![ diff --git a/crates/flowapi-sdk/src/config/shape.rs b/crates/flowapi-sdk/src/config/shape.rs index d919cf6..cbe1cfc 100644 --- a/crates/flowapi-sdk/src/config/shape.rs +++ b/crates/flowapi-sdk/src/config/shape.rs @@ -3,8 +3,13 @@ //! (`build.rs`), and `flowapi config schema` prints them as JSON Schema (`schema.rs`), so the //! three cannot drift apart. A member they do not name is an error. +mod auth; +mod package; mod schemes; +pub(crate) use auth::AUTH; +use auth::{AUTH_SCHEME, SECURITY}; +pub(crate) use package::{PACKAGE, README}; use schemes::SCHEME; pub(crate) use schemes::SCHEMES; @@ -19,6 +24,8 @@ pub(crate) enum Str { Name, /// An environment variable's name. EnvVar, + /// An HTTP header field's name, a token (RFC 9110, 5.1). + Header, /// An absolute `http` or `https` URL. Url, /// An npm package name. @@ -29,6 +36,8 @@ pub(crate) enum Str { Version, /// A package's own version: `0.1.0`, `1.0.0-beta.1`, never `x`. Release, + /// One of these words, else the issue of this code. + OneOf(&'static str, &'static [&'static str]), } /// What a value must be. @@ -116,6 +125,7 @@ static ANY: Shape = Shape::Str(Str::Any); static TEXT: Shape = Shape::Str(Str::Text); static NAME: Shape = Shape::Str(Str::Name); static ENV_VAR: Shape = Shape::Str(Str::EnvVar); +static HEADER: Shape = Shape::Str(Str::Header); static URL: Shape = Shape::Str(Str::Url); static SECONDS: Shape = Shape::Seconds; static RETRIES: Shape = Shape::Int(0, 10); @@ -131,26 +141,6 @@ pub(crate) const GENERATOR: &[Field] = &[req( "The flowapi version the SDK is generated with", )]; -pub(crate) const PACKAGE: &[Field] = &[ - req("name", &Shape::Str(Str::Package), "The npm package's name"), - f( - "version", - &Shape::Str(Str::Release), - "The package's version (0.1.0 unless given); the release tool raises it", - ), - req( - "client", - &Shape::Str(Str::Client), - "The client class's name, in PascalCase", - ), - f( - "license", - &TEXT, - "The package's license, an SPDX expression", - ), - f("repository", &TEXT, "The package's repository URL"), -]; - pub(crate) const ENVIRONMENTS_FIXED: &[Field] = &[ f( "default", @@ -164,19 +154,17 @@ pub(crate) const ENVIRONMENTS_FIXED: &[Field] = &[ ), ]; -static AUTH_SCHEME: Shape = Shape::Named("auth", &Shape::Obj(AUTH)); -pub(crate) const AUTH: &[Field] = &[f( - "env_var", - &ENV_VAR, - "The environment variable the credential is read from", -)]; - pub(crate) const DEFAULTS: &[Field] = &[ def( "retries", &RETRIES, - "2", - "How many times a failed request is retried", + "1", + "How many times a failed request is retried: a POST or a PATCH only with an idempotency key", + ), + f( + "idempotency_key", + &HEADER, + "The header each call of a POST, a PATCH or another method that is not idempotent sends a key in, the same on its retries", ), def( "timeout", @@ -218,6 +206,11 @@ pub(crate) const METHOD: &[Field] = &[ &BOOL, "Whether the response is read as a stream of events", ), + f( + "security", + &SECURITY, + "The method's security, over the description's and the config's: alternatives, each the schemes it needs with their scopes; `[]` for none", + ), ]; static METHOD_VALUE: Shape = Shape::Named("method", &Shape::Either(&[&OP, &Shape::Obj(METHOD)])); @@ -284,20 +277,6 @@ pub(crate) const SKIP: &[Field] = &[ req("reason", &TEXT, "Why the SDK leaves it out"), ]; -pub(crate) const README: &[Field] = &[ - f( - "headline_method", - &TEXT, - "The method the README shows first, as `resource.method`", - ), - f( - "pagination_method", - &TEXT, - "The method the README shows pagination with", - ), - f("intro", &TEXT, "The README's opening paragraph"), -]; - /// The config's root. pub(crate) const ROOT: &[Field] = &[ req("version", &Shape::One, "The format's version: 1"), @@ -320,7 +299,12 @@ pub(crate) const ROOT: &[Field] = &[ f( "auth", &AUTHS, - "The security schemes the client sends, by their names in the description", + "The security schemes the client sends, by their names in the description, and those it lacks", + ), + f( + "security", + &SECURITY, + "The security of every operation with none of its own, over the description's: alternatives, any one of which is enough, each the schemes it needs with their scopes; `{}` makes a credential optional, `[]` is none", ), f( "defaults", diff --git a/crates/flowapi-sdk/src/config/shape/auth.rs b/crates/flowapi-sdk/src/config/shape/auth.rs new file mode 100644 index 0000000..f0b7b75 --- /dev/null +++ b/crates/flowapi-sdk/src/config/shape/auth.rs @@ -0,0 +1,84 @@ +//! The credentials of the format: `auth`, each scheme's options and, for one the description +//! lacks, what it is; and `security`, OpenAPI's Security Requirement Objects as written. Part of +//! `shape.rs`, by which the checker, its reader and the JSON Schema all go. + +use super::{ENV_VAR, Field, Shape, Str, TEXT, URL, f}; + +pub(super) static AUTH_SCHEME: Shape = Shape::Named("auth", &Shape::Obj(AUTH)); +static AUTH_TYPE: Shape = Shape::Str(Str::OneOf( + "config.auth.type", + &["apiKey", "http", "oauth2", "mutualTLS"], +)); +static KEY_IN: Shape = Shape::Str(Str::OneOf("config.auth.in", &["header", "query", "cookie"])); +static TEXTS: Shape = Shape::List(&TEXT); + +/// A credential's members: the options the client reads it by, and for a scheme the description +/// does not declare, what it is (`type` and the members of its kind, as OpenAPI's Security +/// Scheme Object names them). +pub(crate) const AUTH: &[Field] = &[ + f( + "type", + &AUTH_TYPE, + "The kind of a scheme the description does not declare: `apiKey`, `http`, `oauth2` (a token, or one the client requests at `token_url`) or `mutualTLS`", + ), + f( + "scheme", + &TEXT, + "`http`: the HTTP authentication scheme (`bearer`, `basic`, or another of IANA's registry)", + ), + f( + "in", + &KEY_IN, + "`apiKey`: where the key goes: `header`, `query` or `cookie`", + ), + f( + "name", + &TEXT, + "`apiKey`: the name of the header, query parameter or cookie", + ), + f( + "token_url", + &URL, + "`oauth2`: the token endpoint the client requests a token at by the client credentials flow", + ), + f("description", &TEXT, "What the scheme is, for the README"), + f( + "env_var", + &ENV_VAR, + "The environment variable the credential is read from: the key or the token; for HTTP basic `username:password`", + ), + f( + "username_env_var", + &ENV_VAR, + "HTTP basic: the environment variable of the user-id, beside `password_env_var`", + ), + f( + "password_env_var", + &ENV_VAR, + "HTTP basic: the environment variable of the password, beside `username_env_var`", + ), + f( + "client_id_env_var", + &ENV_VAR, + "OAuth 2.0 client credentials: the environment variable of the client's id", + ), + f( + "client_secret_env_var", + &ENV_VAR, + "OAuth 2.0 client credentials: the environment variable of the client's secret", + ), + f( + "scopes", + &TEXTS, + "OAuth 2.0 client credentials: the scopes every token is requested with, instead of each operation's", + ), +]; + +static SCOPES: Shape = Shape::List(&TEXT); +static REQUIREMENT: Shape = Shape::Map { + key: Str::Any, + value: &SCOPES, + fixed: &[], +}; +/// OpenAPI's `security`: alternatives, each the schemes it needs with their scopes. +pub(super) static SECURITY: Shape = Shape::Named("security", &Shape::List(&REQUIREMENT)); diff --git a/crates/flowapi-sdk/src/config/shape/package.rs b/crates/flowapi-sdk/src/config/shape/package.rs new file mode 100644 index 0000000..0a5338a --- /dev/null +++ b/crates/flowapi-sdk/src/config/shape/package.rs @@ -0,0 +1,64 @@ +//! What the package and its README say of themselves: `package` (its npm name, version, class, +//! license, description and keywords) and `readme` (its title, opening paragraph and the methods +//! it shows). Part of `shape.rs`, by which the checker, its reader and the JSON Schema all go. + +use super::{Field, Shape, Str, TEXT, f, req}; + +static KEYWORDS: Shape = Shape::List(&TEXT); + +pub(crate) const PACKAGE: &[Field] = &[ + req("name", &Shape::Str(Str::Package), "The npm package's name"), + f( + "version", + &Shape::Str(Str::Release), + "The package's version (0.1.0 unless given); the release tool raises it", + ), + req( + "client", + &Shape::Str(Str::Client), + "The client class's name, in PascalCase", + ), + f( + "license", + &TEXT, + "The package's license, an SPDX expression", + ), + f("repository", &TEXT, "The package's repository URL"), + f( + "description", + &TEXT, + "One or two sentences of plain text: `package.json`'s `description` and, without \ + `readme.intro`, the README's first paragraph. Unless given, made from the description's \ + `info.title` and the first sentence of its `info.summary` or `info.description`", + ), + f( + "keywords", + &KEYWORDS, + "`package.json`'s `keywords`, for npm's search; none unless given", + ), +]; + +pub(crate) const README: &[Field] = &[ + f( + "title", + &TEXT, + "The README's heading. Unless given, the description's `info.title` without a last \ + `API`, then `TypeScript SDK` (`Twilio Studio API` is `Twilio Studio TypeScript SDK`); \ + the package's name when the description has no title", + ), + f( + "intro", + &TEXT, + "The README's first paragraph, Markdown; `package.description` unless given", + ), + f( + "headline_method", + &TEXT, + "The method the README shows first, as `resource.method`", + ), + f( + "pagination_method", + &TEXT, + "The method the README shows pagination with", + ), +]; diff --git a/crates/flowapi-sdk/src/config/strings.rs b/crates/flowapi-sdk/src/config/strings.rs index eac771f..4aad9aa 100644 --- a/crates/flowapi-sdk/src/config/strings.rs +++ b/crates/flowapi-sdk/src/config/strings.rs @@ -11,11 +11,13 @@ pub(crate) fn problem(kind: Str, s: &str) -> Option<(&'static str, String)> { Str::Text => !s.trim().is_empty(), Str::Name => words::is_name(s), Str::EnvVar => is_env_var(s), + Str::Header => is_token(s), Str::Url => is_url(s), Str::Package => is_package(s), Str::Client => is_client(s), Str::Version => is_version(s), Str::Release => is_version(s) && !s.split('-').next().unwrap_or("").ends_with(".x"), + Str::OneOf(_, words) => words.contains(&s), }; if fits { return None; @@ -29,6 +31,12 @@ pub(crate) fn problem(kind: Str, s: &str) -> Option<(&'static str, String)> { "`{s}` is not an environment variable's name: A-Z, 0-9 and `_`, not opening with a digit" ), ), + Str::Header => ( + "config.header", + format!( + "`{s}` is not a header's name: ASCII letters, digits and any of !#$%&'*+-.^_`|~, no space" + ), + ), Str::Url => ( "config.env.url", format!("`{s}` is not an absolute http or https URL with a host"), @@ -49,6 +57,10 @@ pub(crate) fn problem(kind: Str, s: &str) -> Option<(&'static str, String)> { "config.package.version", format!("`{s}` is not a package's version: `0.1.0`, or `1.0.0-beta.1`"), ), + Str::OneOf(code, words) => ( + code, + format!("`{s}` is not one of `{}`", words.join("`, `")), + ), }) } @@ -59,11 +71,13 @@ pub(crate) fn pattern(kind: Str) -> Option<&'static str> { Str::Text => Some("\\S"), Str::Name => Some(words::NAME_PATTERN), Str::EnvVar => Some("^[A-Z_][A-Z0-9_]*$"), + Str::Header => Some("^[!#$%&'*+.^_`|~0-9A-Za-z-]+$"), Str::Url => Some("^https?://[^\\s/?#]+[^\\s]*$"), Str::Package => Some("^(@[a-z0-9-~][a-z0-9-._~]*/)?[a-z0-9-~][a-z0-9-._~]*$"), Str::Client => Some("^[A-Z][A-Za-z0-9]*$"), Str::Version => Some("^[0-9]+\\.[0-9]+\\.([0-9]+|x)(-[0-9A-Za-z.-]+)?$"), Str::Release => Some("^[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?$"), + Str::OneOf(..) => None, } } @@ -75,6 +89,13 @@ fn is_env_var(s: &str) -> bool { && chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') } +/// A token (RFC 9110, 5.6.2), as a field's name is. +fn is_token(s: &str) -> bool { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c)) +} + pub(crate) fn is_url(s: &str) -> bool { let Some(rest) = s .strip_prefix("https://") diff --git a/crates/flowapi-sdk/src/draft.rs b/crates/flowapi-sdk/src/draft.rs index 6df5f49..109f0d7 100644 --- a/crates/flowapi-sdk/src/draft.rs +++ b/crates/flowapi-sdk/src/draft.rs @@ -1,14 +1,16 @@ //! `flowapi config draft`: a first config for a description, made without an agent, for an agent //! to edit. Every operation is in a resource (`naming.rs`), each `GET` of a collection that //! looks paged pages by the likeliest scheme that fits it (`paging::suggest`), the environments -//! are the description's absolute servers, `auth` its security schemes, `skip: []`. The same +//! are the description's absolute servers, `auth` its security schemes (`draft/auth.rs`), `skip: []`. The same //! description gives the same text in whatever order its paths are written, and the text passes -//! `config check` (a draft that does not is a bug of this module). +//! `config check` (a draft that does not is a bug of this module), but for the warnings of a +//! scheme no config can answer (`draft/auth.rs`). +mod auth; mod naming; use crate::doc::Doc; -use crate::model::{Auth, Server}; +use crate::model::Server; use crate::ops::Ops; use crate::out::yaml_str; use crate::paging::{Paging, suggest}; @@ -51,6 +53,13 @@ pub fn draft(docs: &Documents<'_>, spec: &str) -> Option { .filter(|g| own(g)) .map(|g| join(g, "_")) .collect(); + // The paths with a `PUT` or `PATCH`: a `POST` to an item is its `update` only without one. + let edited: BTreeSet<&str> = ops + .list + .iter() + .filter(|op| matches!(op.operation.method.as_str(), "put" | "patch")) + .map(|op| op.operation.path.as_str()) + .collect(); let mut schemes: Vec = Vec::new(); let mut resources: Vec<(String, Vec)> = Vec::new(); for (group, mut members) in groups { @@ -61,10 +70,10 @@ pub fn draft(docs: &Documents<'_>, spec: &str) -> Option { naming::resource(&group, &models, &title, &taken) }; taken.insert(name.clone()); - let names: Vec<(Vec, Vec)> = members + let names: Vec>> = members .iter() .filter_map(|&i| ops.list.get(i)) - .map(|op| naming::method(op, &group)) + .map(|op| naming::method(op, &group, edited.contains(op.operation.path.as_str()))) .collect(); let mut methods = Vec::new(); for (&i, method) in members.iter().zip(naming::methods(&names)) { @@ -92,8 +101,8 @@ pub fn draft(docs: &Documents<'_>, spec: &str) -> Option { let client = pascal(&title); head(&mut out, spec, &prose, &client); environments(&mut out, &ops.doc, &prose); - auth(&mut out, &ops.doc, &prose); - out.push_str("defaults:\n retries: 2\n timeout: 60\n max_retry_delay: 60\n"); + auth::auth(&mut out, &ops, &prose); + out.push_str("defaults:\n retries: 1\n timeout: 60\n max_retry_delay: 60\n"); if !schemes.is_empty() { out.push_str("pagination:\n"); for (s, name) in schemes.iter().zip(&names) { @@ -270,22 +279,3 @@ fn env_name(own: Option>, n: usize, before: &[(String, String)]) -> Some(_) | None => format!("server_{n}"), } } - -/// The description's security schemes by name, each read from an environment variable; a client -/// certificate is its transport's, and left out. -fn auth(out: &mut String, doc: &Doc<'_, '_>, title: &[String]) { - let mut schemes: Vec<_> = doc - .schemes(&mut Diagnostics::default()) - .into_iter() - .filter(|s| s.auth != Auth::MutualTls) - .collect(); - schemes.sort_by(|a, b| a.name.cmp(&b.name)); - if schemes.is_empty() { - return; - } - out.push_str("auth:\n"); - for s in schemes { - let env = upper(&[title.to_vec(), words(&s.name)].concat()); - let _ = writeln!(out, " {}:\n env_var: {env}", yaml_str(&s.name)); - } -} diff --git a/crates/flowapi-sdk/src/draft/auth.rs b/crates/flowapi-sdk/src/draft/auth.rs new file mode 100644 index 0000000..48f2d3d --- /dev/null +++ b/crates/flowapi-sdk/src/draft/auth.rs @@ -0,0 +1,108 @@ +//! The draft's `auth` and `security`: each security scheme of the description, with the +//! environment variables it is read from (HTTP basic's as `username:password`, a client +//! credentials flow's id and secret beside a ready token); one no variable can give (a client +//! certificate, an HTTP scheme that answers a challenge) listed with none, and it and a +//! deprecated one said why in a comment. `config check` warns of those three whatever the config +//! says, as they are the description's, and so does `config.auth.none` when no operation needs a +//! credential: they are the only issues a draft may have, and none is an error. In that case the +//! draft leaves `security` unset, with a commented example of declaring one, never writing +//! `security: []` (the config's own statement that the API takes no credentials, which would +//! silence the warning): the person, or the agent, decides from the API's own documentation and +//! never by a guess. + +use crate::config::auth::{CHALLENGED, has_token_flow, is_basic}; +use crate::doc::ROOT; +use crate::model::Auth; +use crate::ops::Ops; +use crate::out::yaml_str; +use crate::words::{upper, words}; +use flowapi::Diagnostics; +use std::fmt::Write as _; + +/// What a scheme no variable can give is, when it is one. +fn without_env(auth: &Auth) -> Option<&'static str> { + match auth { + Auth::MutualTls => Some("a client certificate: give the client a `fetch` that presents it"), + Auth::Http { scheme, .. } if CHALLENGED.contains(&scheme.as_str()) => Some( + "an HTTP scheme that answers a challenge: give `Authorization` in a call's `headers`", + ), + Auth::ApiKey { .. } + | Auth::Http { .. } + | Auth::OAuth2 { .. } + | Auth::OpenIdConnect { .. } => None, + } +} + +/// Whether some operation needs a credential, by its own `security` or the description's. +fn needed(ops: &Ops<'_, '_>) -> bool { + let mut quiet = Diagnostics::default(); + let root = ops.doc.security(ROOT, &mut quiet).unwrap_or_default(); + ops.list.iter().any(|op| { + let (own, _) = ops.doc.effective(&op.operation, &root, &mut quiet); + own.iter().any(|r| !r.schemes.is_empty()) + }) +} + +pub(super) fn auth(out: &mut String, ops: &Ops<'_, '_>, title: &[String]) { + let mut schemes = ops.doc.schemes(&mut Diagnostics::default()); + schemes.sort_by(|a, b| a.name.cmp(&b.name)); + let var = |name: &str, more: &[&str]| { + let mut w = [title.to_vec(), words(name)].concat(); + w.extend(more.iter().map(|m| (*m).to_owned())); + upper(&w) + }; + let mut listed = String::new(); + for s in &schemes { + if s.deprecated { + let _ = writeln!(listed, " # deprecated by the description: refrain from it"); + } + if let Some(what) = without_env(&s.auth) { + let _ = writeln!(listed, " # {what}\n {}: {{}}", yaml_str(&s.name)); + continue; + } + let _ = writeln!(listed, " {}:", yaml_str(&s.name)); + if is_basic(&s.auth) { + let _ = writeln!( + listed, + " env_var: {} # username:password", + var(&s.name, &[]) + ); + } else { + let _ = writeln!(listed, " env_var: {}", var(&s.name, &[])); + } + if has_token_flow(&s.auth) { + let _ = writeln!( + listed, + " client_id_env_var: {}\n client_secret_env_var: {}", + var(&s.name, &["client", "id"]), + var(&s.name, &["client", "secret"]) + ); + } + } + if !listed.is_empty() { + out.push_str("auth:\n"); + out.push_str(&listed); + } + if needed(ops) { + return; + } + let first = schemes.first().map(|s| s.name.as_str()); + let example = var("token", &[]); + out.push_str( + "# The description declares no security scheme that an operation uses. Most APIs take a\n\ + # credential: find it in the API's documentation, declare it under `auth` and name it in\n\ + # `security`, as in the example below, or write `security: []` when the API truly takes\n\ + # none. Until then `config check` warns `config.auth.none`.\n", + ); + if first.is_none() { + let _ = writeln!( + out, + "# auth:\n# token: {{ type: http, scheme: bearer, env_var: {example} }}" + ); + } + let _ = writeln!( + out, + "# security:\n# - {}: []", + yaml_str(first.unwrap_or("token")) + ); +} diff --git a/crates/flowapi-sdk/src/draft/naming.rs b/crates/flowapi-sdk/src/draft/naming.rs index c320cc5..cbcc19b 100644 --- a/crates/flowapi-sdk/src/draft/naming.rs +++ b/crates/flowapi-sdk/src/draft/naming.rs @@ -2,9 +2,12 @@ //! resource is its first tag, else its path's first static segment (a version such as `v1` //! passed over); a resource's own collection and item (its noun the path's one static //! segment) get the verbs `list`, `create`, -//! `retrieve`, `update`, `delete`; any other operation is named by its `operationId`'s words, -//! the resource's words taken off the front, else by its method and path. Names equal as words -//! are told apart by the longer name, then by a number, in the order of path and method. +//! `retrieve`, `update`, `delete`; any other operation is named by its `operationId`'s words +//! without the words its resource already says (`naming/trim.rs`), else by its method and path. +//! Names equal as words both take their longer names, then a number, in the order of path and +//! method. + +mod trim; use crate::config::{CLIENT_MEMBERS, RESOURCE_MEMBERS, reserved}; use crate::ops::Op; @@ -81,8 +84,27 @@ pub(crate) fn group(op: &Op) -> Vec { out } +/// The English plural of a name's last word, or `None` when it is plural already: a consonant and +/// `y` is `ies` (`activity`, `policy`; `key` is `keys`), a word ending in `s` after another `s`, +/// or in `x`, `z`, `ch` or `sh`, takes `es` (`address`, `box`, `branch`), a word ending in any +/// other `s` is plural already (`issues`, `repos`), else an `s`. +fn plural(name: &str) -> Option { + let consonant_y = name.strip_suffix('y').filter(|stem| { + stem.chars() + .last() + .is_some_and(|c| c.is_ascii_alphabetic() && !"aeiou".contains(c)) + }); + if let Some(stem) = consonant_y { + return Some(format!("{stem}ies")); + } + if name.ends_with("ss") || ["x", "z", "ch", "sh"].iter().any(|e| name.ends_with(e)) { + return Some(format!("{name}es")); + } + (!name.ends_with('s')).then(|| format!("{name}s")) +} + /// A resource's name that no schema, client member or the client itself has: its words, else -/// with an `s`, else with `api` and a number. +/// its plural (`plural`), else with `api` and a number. pub(crate) fn resource( w: &[String], models: &BTreeSet, @@ -99,8 +121,10 @@ pub(crate) fn resource( if free(&name) { return name; } - if !name.ends_with('s') && free(&format!("{name}s")) { - return format!("{name}s"); + if let Some(plural) = plural(&name) + && free(&plural) + { + return plural; } (1..) .map(|n| { @@ -131,18 +155,23 @@ fn same_noun(a: &[String], b: &[String]) -> bool { /// The verb of a resource's own collection or item: an operation whose path has one static /// segment, the resource's noun (`/pets`, `/pets/{id}` in `pets`; not `/admin.apps.approve` in -/// `admin_apps`, which is a call of its own). -fn verb(op: &Op, group: &[String]) -> Option<&'static str> { +/// `admin_apps`, which is a call of its own). A `POST` to an item of one parameter is its +/// `update` where the item has no `PUT` or `PATCH` (`edited`), as APIs that update by `POST` +/// write it (`/v1/prices/{price}`; not `/orgs/{org}/{product}/{action}`, which is an action). +fn verb(op: &Op, group: &[String], edited: bool) -> Option<&'static str> { match statics(&op.operation.path).as_slice() { [one] if same_noun(&words(one), group) => {} _ => return None, } - let item = op.operation.path.trim_end_matches('/').ends_with('}'); + let path = op.operation.path.trim_end_matches('/'); + let item = path.ends_with('}'); + let one_param = path.matches('{').count() == 1; match (op.operation.method.as_str(), item) { ("get", false) => Some("list"), ("post", false) => Some("create"), ("get", true) => Some("retrieve"), ("put" | "patch", true) => Some("update"), + ("post", true) if one_param && !edited => Some("update"), ("delete", true) => Some("delete"), _ => None, } @@ -157,52 +186,81 @@ fn route_words(op: &Op, skip: usize) -> Vec { w } -/// The short name of an operation in a resource, and its long one for when two short ones meet. -pub(crate) fn method(op: &Op, group: &[String]) -> (Vec, Vec) { +/// An operation's names in a resource, the shortest first, each longer one for when the one +/// before meets another's: the CRUD verb where one applies; the `operationId`'s words without the +/// resource's (`trim.rs`); those words without the resource's at their front alone; all of them +/// (else the method and the path's segments). `edited` says whether the operation's path has a +/// `PUT` or `PATCH`. +pub(crate) fn method(op: &Op, group: &[String], edited: bool) -> Vec> { let id = op .operation_id .as_deref() .map(words) .filter(|w| !w.is_empty()); - let long = id - .clone() - .filter(|w| usable(w)) - .unwrap_or_else(|| route_words(op, 0)); - let short = if let Some(v) = verb(op, group) { - vec![String::from(v)] - } else if let Some(w) = id { - let rest: Vec = if w.starts_with(group) { - w.get(group.len()..).unwrap_or(&[]).to_vec() - } else { - w.clone() - }; - let rest = if rest.is_empty() { w } else { rest }; - if usable(&rest) { - rest + let method = op.operation.method.to_ascii_lowercase(); + // A name that opens with a digit is given its method in front. + let lettered = |w: Vec| { + if usable(&w) { + w } else { - [vec![op.operation.method.to_ascii_lowercase()], rest].concat() + [vec![method.clone()], w].concat() } - } else { - route_words(op, 1) }; - (short, long) + let mut out: Vec> = Vec::new(); + if let Some(v) = verb(op, group, edited) { + out.push(vec![String::from(v)]); + } + if let Some(w) = &id { + out.push(trim::trim(w, group)); + out.push(w.strip_prefix(group).unwrap_or(w).to_vec()); + } else { + out.push(route_words(op, 1)); + } + out.push( + id.filter(|w| usable(w)) + .unwrap_or_else(|| route_words(op, 0)), + ); + // Kept when equal: the names of two operations are raised a kind at a time, so that one whose + // shorter names are one text is never raised past the others' kind (`list` by `GET /users` + // meets `GET /user`'s; the first keeps `list` as its trimmed name, the second takes + // `get_authenticated`). + out.into_iter() + .filter(|w| !w.is_empty()) + .map(lettered) + .collect() } -/// Each operation's name in one resource, `ops` in the order of path and method: the short name -/// where no other has it, else the long one, else the long one and a number. -pub(crate) fn methods(names: &[(Vec, Vec)]) -> Vec { +/// Each operation's name in one resource, `ops` in the order of path and method: its shortest +/// name where no other has it and no member of a resource is named so; where two meet, both take +/// their next longer name, until none meets or a name has no longer one; a name still shared is +/// told apart by a number, in the order of path and method. +pub(crate) fn methods(names: &[Vec>]) -> Vec { let count = |w: &Vec, all: &[Vec]| all.iter().filter(|x| *x == w).count(); - let shorts: Vec> = names.iter().map(|(s, _)| s.clone()).collect(); - let chosen: Vec> = names - .iter() - .map(|(s, l)| { - if count(s, &shorts) == 1 && !reserved(&join(s, "_"), RESOURCE_MEMBERS) { - s.clone() - } else { - l.clone() + let mut level = vec![0usize; names.len()]; + let pick = |level: &[usize]| -> Vec> { + names + .iter() + .zip(level) + .map(|(n, &l)| n.get(l).or_else(|| n.last()).cloned().unwrap_or_default()) + .collect() + }; + // Each pass raises at least one name, so the passes are as many as the names' levels at most. + let passes: usize = names.iter().map(Vec::len).sum(); + for _ in 0..passes { + let chosen = pick(&level); + let mut raised = false; + for ((l, n), w) in level.iter_mut().zip(names).zip(&chosen) { + let meets = count(w, &chosen) > 1 || reserved(&join(w, "_"), RESOURCE_MEMBERS); + if meets && *l + 1 < n.len() { + *l += 1; + raised = true; } - }) - .collect(); + } + if !raised { + break; + } + } + let chosen = pick(&level); let unique = |w: &Vec| count(w, &chosen) == 1 && !reserved(&join(w, "_"), RESOURCE_MEMBERS); let mut taken: BTreeSet = chosen diff --git a/crates/flowapi-sdk/src/draft/naming/trim.rs b/crates/flowapi-sdk/src/draft/naming/trim.rs new file mode 100644 index 0000000..cd3e994 --- /dev/null +++ b/crates/flowapi-sdk/src/draft/naming/trim.rs @@ -0,0 +1,99 @@ +//! A method's name without the words its resource already says: `client.actions` needs no +//! `actions` in `getActionsCacheRetentionLimit`, nor `client.repos` a `repos` in `reposListForOrg`. +//! A word is the resource's when the resource has it, or (for a word that is no connector such as +//! `for` or `the`) when the two are one noun but for a plural (`customer` in `customers`, `policy` +//! in `policies`). The resource's words are taken out by runs of them: +//! +//! - a run at the front or in the middle goes (`actions get actions cache` is `get cache`); +//! - a run at the end goes only when it is the verb's object (`list flow` in `flows` is `list`) +//! or a connector puts it there (`list followers for user` in `users` is `list followers`); a +//! run a word of its own qualifies stays (`list followers for authenticated user` keeps `user`, +//! whose words `authenticated user` say who, not what); +//! - a run of connectors alone stays (`for` in `workers_for_platforms` is never a resource's), +//! and so does a run beside `and` or `or`, half of a pair (`list captions or subtitles`). +//! +//! What is left may be nothing: the caller then keeps a longer name. + +#[cfg(test)] +#[path = "trim_tests.rs"] +mod tests; + +/// Words that join a name's parts and name nothing: a resource's run after one of them is where +/// the name says whose it is, not what it does. +const CONNECTORS: &[&str] = &[ + "a", "an", "the", "for", "of", "in", "to", "by", "from", "with", "on", "at", "into", +]; + +fn connector(w: &str) -> bool { + CONNECTORS.contains(&w) +} + +/// A noun without its plural: `policies` is `policy`, `pets` is `pet`, `address` stays. +fn singular(w: &str) -> String { + if let Some(stem) = w.strip_suffix("ies") + && !stem.is_empty() + { + return format!("{stem}y"); + } + match w.strip_suffix('s') { + Some(stem) if !stem.is_empty() && !stem.ends_with('s') => stem.to_owned(), + Some(_) | None => w.to_owned(), + } +} + +/// Whether `w` is a word of the resource `group`. +fn of_group(w: &str, group: &[String]) -> bool { + if group.iter().any(|g| g == w) { + return true; + } + !connector(w) && group.iter().any(|g| singular(g) == singular(w)) +} + +/// `name` without the words of `group` it repeats, by the rules above. +pub(crate) fn trim(name: &[String], group: &[String]) -> Vec { + let mine: Vec = name.iter().map(|w| of_group(w, group)).collect(); + let mut drop = vec![false; name.len()]; + // The first word that is not the resource's: the verb a run at the end may follow. + let verb = mine.iter().position(|m| !m); + let mut i = 0; + while i < name.len() { + if !mine.get(i).copied().unwrap_or(false) { + i += 1; + continue; + } + let start = i; + while mine.get(i).copied().unwrap_or(false) { + i += 1; + } + let run = name.get(start..i).unwrap_or(&[]); + let paired = [start.checked_sub(1), Some(i)] + .into_iter() + .flatten() + .filter_map(|j| name.get(j)) + .any(|w| w == "and" || w == "or"); + if paired || run.iter().all(|w| connector(w)) { + continue; + } + let before = start.checked_sub(1); + let at_end = i == name.len(); + let joined = before + .and_then(|b| name.get(b)) + .is_some_and(|w| connector(w)); + if !at_end || before.is_none() || before == verb { + drop_range(&mut drop, start, i); + } else if joined { + drop_range(&mut drop, start - 1, i); + } + } + name.iter() + .zip(drop) + .filter(|(_, d)| !d) + .map(|(w, _)| w.clone()) + .collect() +} + +fn drop_range(drop: &mut [bool], from: usize, to: usize) { + for d in drop.iter_mut().take(to).skip(from) { + *d = true; + } +} diff --git a/crates/flowapi-sdk/src/draft/naming/trim_tests.rs b/crates/flowapi-sdk/src/draft/naming/trim_tests.rs new file mode 100644 index 0000000..332da56 --- /dev/null +++ b/crates/flowapi-sdk/src/draft/naming/trim_tests.rs @@ -0,0 +1,87 @@ +//! A method's name without its resource's words, on names the corpus has: GitHub's, Stripe's, +//! Cloudflare's, Twilio's; and the runs that stay. + +use super::trim; +use crate::words::words; + +fn trimmed(name: &str, group: &str) -> String { + trim(&words(name), &words(group)).join("_") +} + +#[test] +fn a_run_at_the_front_or_in_the_middle_goes() { + let cases = [ + ( + "actions/get-actions-cache-retention-limit-for-enterprise", + "actions", + "get_cache_retention_limit_for_enterprise", + ), + ("repos/list-for-org", "repos", "list_for_org"), + ("PostCustomersCustomerCardsId", "customers", "post_cards_id"), + ( + "email-security-list-sending-domain-restrictions", + "email_security_settings", + "list_sending_domain_restrictions", + ), + ("account-user-group-list", "account_user_groups", "list"), + ]; + for (name, group, want) in cases { + assert_eq!(trimmed(name, group), want, "{name} in {group}"); + } +} + +#[test] +fn a_run_at_the_end_goes_after_the_verb_or_a_connector() { + let cases = [ + ("ListFlow", "studio_v2_flows", "list"), + ("list-abuse-reports", "abuse_reports_other", "list"), + ("users/list-followers-for-user", "users", "list_followers"), + ( + "create-a-virtual-network", + "tunnel_virtual_networks", + "create", + ), + ("get-policies", "policy", "get"), + ]; + for (name, group, want) in cases { + assert_eq!(trimmed(name, group), want, "{name} in {group}"); + } +} + +#[test] +fn a_run_a_word_qualifies_stays() { + let cases = [ + ( + "users/list-followers-for-authenticated-user", + "users", + "list_followers_for_authenticated_user", + ), + ("get-fonts-setting", "zone_settings", "get_fonts_setting"), + ( + "DeleteIncomingPhoneNumberAssignedAddOn", + "api20100401_assigned_add_on", + "delete_incoming_phone_number_assigned_add_on", + ), + ]; + for (name, group, want) in cases { + assert_eq!(trimmed(name, group), want, "{name} in {group}"); + } +} + +#[test] +fn connectors_alone_are_no_resource_and_a_plural_is_one_noun() { + assert_eq!( + trimmed("list-scripts-for-namespace", "workers_for_platforms"), + "list_scripts_for_namespace" + ); + // Half of a pair stays: `list or subtitles` would say nothing. + assert_eq!( + trimmed("list-captions-or-subtitles", "stream_subtitles_captions"), + "list_captions_or_subtitles" + ); + // `address` is no plural of `addres`, and `status` keeps its `s` against `statu`. + assert_eq!(trimmed("get-address", "addresses"), "get_address"); + assert_eq!(trimmed("get-status", "status"), "get"); + // A name that is its resource alone leaves nothing: the caller keeps a longer name. + assert!(trim(&words("pets"), &words("pets")).is_empty()); +} diff --git a/crates/flowapi-sdk/src/draft/naming_tests.rs b/crates/flowapi-sdk/src/draft/naming_tests.rs index 4c56b83..367348a 100644 --- a/crates/flowapi-sdk/src/draft/naming_tests.rs +++ b/crates/flowapi-sdk/src/draft/naming_tests.rs @@ -1,9 +1,10 @@ //! A title's words: a piece in mixed case is one word of the package's name and two or more of //! the client's (as the client is read everywhere), an acronym a word, a version a word, `api` //! put first before a digit; and the package's name is one npm takes (lower case, URL-safe). +//! Methods whose names meet both take their longer names. -use super::title; -use crate::words::{join, pascal}; +use super::{methods, title}; +use crate::words::{join, pascal, words}; /// The package's name and the client's class drafted from a title. fn named(text: &str) -> (String, String) { @@ -46,6 +47,65 @@ fn a_word_in_mixed_case_stays_one_word_of_the_package() { } } +fn w(names: &[&str]) -> Vec> { + names.iter().map(|n| words(n)).collect() +} + +#[test] +fn two_names_that_meet_both_take_their_longer_names() { + // `get_cache` twice: both are raised, and the third, which met nobody, keeps its short one. + let names = [ + w(&[ + "get_cache", + "get_actions_cache", + "actions_get_actions_cache", + ]), + w(&["get_cache", "get_cache_usage", "actions_get_cache_usage"]), + w(&["list_for_org", "repos_list_for_org"]), + ]; + assert_eq!( + methods(&names), + ["get_actions_cache", "get_cache_usage", "list_for_org"] + ); +} + +#[test] +fn names_are_raised_a_kind_at_a_time() { + // GitHub's `GET /users` and `GET /user` are both `list` by the verb; the first's trimmed name + // is `list` again, the second's `get_authenticated`: neither needs its full `operationId`. + let names = [ + w(&["list", "list", "list", "users_list"]), + w(&[ + "list", + "get_authenticated", + "get_authenticated", + "users_get_authenticated", + ]), + ]; + assert_eq!(methods(&names), ["list", "get_authenticated"]); +} + +#[test] +fn a_name_raised_into_another_raises_that_one_too_and_numbers_end_it() { + let names = [ + w(&["list", "list_runs"]), + w(&["list", "get_runs"]), + w(&["list_runs", "list_runs_for_repo"]), + w(&["delete"]), + w(&["delete"]), + ]; + assert_eq!( + methods(&names), + [ + "list_runs", + "get_runs", + "list_runs_for_repo", + "delete", + "delete_2" + ] + ); +} + #[test] fn the_package_name_is_one_npm_takes() { for text in ["Café & Co. API", " The API ", "x/y:z", "Ünïcode API"] { @@ -62,3 +122,27 @@ fn the_package_name_is_one_npm_takes() { ); } } + +/// A resource name that meets a schema's takes its English plural, a plural already stays. +#[test] +fn a_resource_takes_its_english_plural() { + let cases = [ + ("activity", Some("activities")), + ("policy", Some("policies")), + ("key", Some("keys")), + ("day", Some("days")), + ("y", Some("ys")), + ("address", Some("addresses")), + ("box", Some("boxes")), + ("branch", Some("branches")), + ("dish", Some("dishes")), + ("pet", Some("pets")), + ("issues", None), + ("repos", None), + ("actions", None), + ("activities", None), + ]; + for (name, want) in cases { + assert_eq!(super::plural(name).as_deref(), want, "{name}"); + } +} diff --git a/crates/flowapi-sdk/src/encoding.rs b/crates/flowapi-sdk/src/encoding.rs index 399f1a8..160f015 100644 --- a/crates/flowapi-sdk/src/encoding.rs +++ b/crates/flowapi-sdk/src/encoding.rs @@ -1,59 +1,78 @@ -//! What a `multipart/form-data` request body's Encoding Objects say a part is sent as: the -//! `contentType` of each property, read from the Media Object of the operation's request body -//! (a Reference Object followed). `Request` takes it as `body.encoding`, and the client -//! passes the description's when the caller gives none. A `contentType` that is a list or a range -//! names no one type to send: it is left out, with a warning, and the part goes as its value's -//! default type. Swagger 2.0 has no Encoding Object; its forms read nothing here. +//! How a request body of a form or `multipart` media type is written, as the description says: +//! the Media Type Object's `encoding` (by name, for `multipart/form-data` and +//! `application/x-www-form-urlencoded`), `prefixEncoding` and `itemEncoding` (by position, for any +//! `multipart` type, 3.2), each Encoding Object read for the fields its media type takes +//! (`headers` for `multipart`; `style`, `explode` and `allowReserved` for a form, and in 3.1 and +//! 3.2 for `multipart/form-data`; 3.2's nested `encoding`, `prefixEncoding`, `itemEncoding` for a +//! part that is itself `multipart`). Request bodies only: the Encoding Object applies to no +//! response (3.0, 3.1), and to no other media type. Where the description gives a part no type, +//! its schema may (`inspect.rs`); Swagger 2.0's forms by their fields' `collectionFormat`, as the +//! core read it (`swagger.rs`). `Request` takes the result in its body, and the client passes +//! the description's when the caller gives none. + +mod inspect; +mod print; +mod swagger; + +pub(crate) use print::literal; use crate::doc::{At, Doc, oas}; -use crate::model::Encoding; -use flowapi::Diagnostics; +use crate::model::{Encoding, Part, Parts}; +use flowapi::spec::Operation; +use flowapi::{Diagnostics, Version}; + +/// `application/x-www-form-urlencoded`. +const FORM: &str = "application/x-www-form-urlencoded"; +/// `multipart/form-data`. +const FORM_DATA: &str = "multipart/form-data"; +/// How deep nested Encoding Objects are read: 3.2 asks for one level and allows more; a deeper +/// one is a warning and left out, so no description makes reading it recurse without end (G1). +const NESTING: usize = 4; + +/// A media type without its parameters, in lower case. +fn bare(media_type: &str) -> String { + media_type + .split(';') + .next() + .unwrap_or("") + .trim() + .to_ascii_lowercase() +} + +/// The requirement a nesting too deep to read is reported under. +const NESTED: &str = "oas-3.2.encoding-object.nested-encoding.must-implementations-support-one-level-nesting-support"; + +/// The styles a form member takes (those of a `query` parameter). +const STYLES: [&str; 4] = ["form", "spaceDelimited", "pipeDelimited", "deepObject"]; impl Doc<'_, '_> { - /// The encodings of an operation's request body, one per `multipart/form-data` media type - /// that names at least one part's type, in the order written. - pub(crate) fn encodings(&self, op: Option, diags: &mut Diagnostics) -> Vec { - let Some(body) = op + /// The encodings of an operation's request body, one per form or `multipart` media type that + /// says anything of its values, in the order written. + pub(crate) fn encodings( + &self, + op: Option, + operation: &Operation, + diags: &mut Diagnostics, + ) -> Vec { + if self.version == Version::V20 { + return swagger::encodings(operation); + } + let Some(content) = op .and_then(|op| self.get(op, "requestBody")) .and_then(|b| self.resolve(b)) + .and_then(|b| self.get(b, "content")) else { return Vec::new(); }; - let Some(content) = self.get(body, "content") else { - return Vec::new(); - }; let mut out = Vec::new(); for (media_type, media) in self.members(content) { - let bare = media_type.split(';').next().unwrap_or("").trim(); - if !bare.eq_ignore_ascii_case("multipart/form-data") { + let kind = bare(&media_type); + if kind != FORM && !kind.starts_with("multipart/") { continue; } - let Some(encoding) = self.get(media, "encoding") else { - continue; - }; - let mut parts = Vec::new(); - for (name, object) in self.members(encoding) { - let Some(at) = self.get(object, "contentType") else { - continue; - }; - let Some(value) = self.str(object, "contentType") else { - continue; - }; - let value = value.trim().to_owned(); - if value.contains(',') || value.contains('*') || value.is_empty() { - let code = oas!( - self.version, - "swagger.encoding", - "encoding-object.contentType" - ); - let message = format!( - "the part `{name}` is encoded as `{value}`, a list or a range of types: no \ - one type to send it as, so it is sent as its value's default type" - ); - self.warn(diags, code, at, message); - continue; - } - parts.push((name, value)); + let mut parts = self.parts_of(media, &kind, 0, diags); + if let Some(schema) = self.get(media, "schema") { + self.inferred(&mut parts, &kind, schema); } if !parts.is_empty() { out.push(Encoding { media_type, parts }); @@ -61,4 +80,85 @@ impl Doc<'_, '_> { } out } + + /// The Encoding Objects of `holder` (a Media Type Object, or an Encoding Object for its + /// nested ones) as they apply to a value of `kind`: by name for a form and + /// `multipart/form-data`, by position (3.2) for any `multipart` type. + fn parts_of(&self, holder: At, kind: &str, depth: usize, diags: &mut Diagnostics) -> Parts { + let mut parts = Parts::default(); + if (kind == FORM || kind == FORM_DATA) + && let Some(map) = self.get(holder, "encoding") + { + for (name, object) in self.members(map) { + let part = self.part(object, kind, depth, diags); + parts.by_name.push((name, part)); + } + } + if kind.starts_with("multipart/") && self.version == Version::V32 { + if let Some(list) = self.get(holder, "prefixEncoding") { + for object in self.items(list) { + parts.prefix.push(self.part(object, kind, depth, diags)); + } + } + if let Some(object) = self.get(holder, "itemEncoding") { + parts.item = Some(Box::new(self.part(object, kind, depth, diags))); + } + } + parts + } + + /// One Encoding Object as it applies to a value written in `kind`. + fn part(&self, object: At, kind: &str, depth: usize, diags: &mut Diagnostics) -> Part { + let mut part = Part { + content_type: self + .str(object, "contentType") + .map(|t| t.trim().to_owned()) + .filter(|t| !t.is_empty()), + ..Part::default() + }; + let styled = kind == FORM + || (kind == FORM_DATA && matches!(self.version, Version::V31 | Version::V32)); + if styled { + part.style = self.style(object, diags); + part.explode = self.boolean(object, "explode"); + part.allow_reserved = self.boolean(object, "allowReserved"); + } + let inner = part.content_type.as_deref().map(bare).unwrap_or_default(); + let nests = inner.starts_with("multipart/") || inner == FORM; + if self.version == Version::V32 && nests { + if depth + 1 < NESTING { + part.parts = self.parts_of(object, &inner, depth + 1, diags); + } else { + let message = format!( + "Encoding Objects nested deeper than {NESTING} levels are not read: the \ + part is written by its value's defaults" + ); + self.warn(diags, NESTED, object, message); + } + } + part + } + + /// An Encoding Object's `style`, when it is one a form member takes; another is a warning, + /// and read as not written. + fn style(&self, object: At, diags: &mut Diagnostics) -> Option { + let at = self.get(object, "style")?; + let style = self.str(object, "style"); + if let Some(s) = style.filter(|s| STYLES.contains(&s.as_str())) { + return Some(s); + } + let code = oas!(self.version, "swagger.encoding", "encoding-object.style"); + let message = String::from( + "`style` is not one a form member takes (form, spaceDelimited, pipeDelimited, \ + deepObject): read as not written", + ); + self.warn(diags, code, at, message); + None + } + + /// A boolean member, where written. + fn boolean(&self, object: At, key: &str) -> Option { + let (doc, node) = self.get(object, key)?; + self.tree(doc)?.as_bool(node) + } } diff --git a/crates/flowapi-sdk/src/encoding/inspect.rs b/crates/flowapi-sdk/src/encoding/inspect.rs new file mode 100644 index 0000000..2d604ac --- /dev/null +++ b/crates/flowapi-sdk/src/encoding/inspect.rs @@ -0,0 +1,147 @@ +//! What the schemas say of a part where its Encoding Object does not: 3.2, "Non-JSON Data". A +//! value is serialized by inspecting the data where it can be (the runtime does: bytes are a +//! file, an object JSON); a string cannot tell whether its text is encoded bytes, so its schema +//! is inspected: the schema and every schema its `$ref` and `allOf` reach, which apply to any +//! instance. `oneOf`, `anyOf` and the rest are not looked into, so no ambiguity is resolved. A +//! string with `contentEncoding` (3.0: `format` `binary` or `byte`) defaults to +//! `application/octet-stream`, not `text/plain`; in a `multipart` type other than +//! `multipart/form-data` its part also says `Content-Transfer-Encoding`, as 3.2 makes +//! `contentEncoding` equivalent to (RFC 7578, 4.7 deprecates it for `multipart/form-data`). + +use super::FORM_DATA; +use crate::doc::{At, Doc}; +use crate::model::{Part, Parts}; +use flowapi::Version; + +/// The most schemas one inspection reads, so a cycle of references or a huge `allOf` ends. +const REACH: usize = 64; + +/// A string's bytes encoded: whether a schema says so, and by what (`contentEncoding`). +#[derive(Default)] +struct Facts { + binary: bool, + encoding: Option, +} + +impl Doc<'_, '_> { + /// The schemas that apply to every instance of `schema`: it, and those its `$ref` and `allOf` + /// reach (a 3.0 `$ref`'s siblings are not read, as 3.0 says). + fn reached(&self, schema: At) -> Vec { + let mut out: Vec = Vec::new(); + let mut stack = vec![schema]; + while let Some(s) = stack.pop() { + if out.len() >= REACH || out.contains(&s) { + continue; + } + let referred = self.get(s, "$ref").and_then(|_| self.resolve(s)); + if let Some(target) = referred { + stack.push(target); + if self.version == Version::V30 { + continue; + } + } + out.push(s); + if let Some(all) = self.get(s, "allOf") { + stack.extend(self.items(all)); + } + } + out + } + + /// Whether some schema reached from `schema` has `type` this one name. + fn typed(&self, reached: &[At], name: &str) -> bool { + reached + .iter() + .any(|&s| self.str(s, "type").as_deref() == Some(name)) + } + + /// What `schema` says of a value's bytes; an array's, of its `items`. + fn facts(&self, schema: At) -> Facts { + let mut reached = self.reached(schema); + if self.typed(&reached, "array") + && let Some(items) = reached.iter().find_map(|&s| self.get(s, "items")) + { + reached = self.reached(items); + } + let mut facts = Facts::default(); + for &s in &reached { + if self.version == Version::V30 { + let format = self.str(s, "format"); + facts.binary |= matches!(format.as_deref(), Some("binary" | "byte")); + } else if let Some(e) = self.str(s, "contentEncoding") { + facts.encoding = Some(e); + } + } + facts.binary = (facts.binary && self.typed(&reached, "string")) || facts.encoding.is_some(); + facts + } + + /// `parts` given what the media type's `schema` says where its Encoding Objects do not: + /// `multipart/form-data` by its properties' names, another `multipart` type (3.2) by its + /// items' positions (`prefixItems`, then `items`). + pub(super) fn inferred(&self, parts: &mut Parts, kind: &str, schema: At) { + let reached = self.reached(schema); + if kind == FORM_DATA { + for &s in &reached { + let Some(props) = self.get(s, "properties") else { + continue; + }; + for (name, prop) in self.members(props) { + let facts = self.facts(prop); + if !facts.binary { + continue; + } + let at = parts.by_name.iter().position(|(n, _)| *n == name); + let at = at.unwrap_or_else(|| { + parts.by_name.push((name, Part::default())); + parts.by_name.len() - 1 + }); + if let Some((_, part)) = parts.by_name.get_mut(at) { + binary(part, None); + } + } + } + } else if kind.starts_with("multipart/") && self.version == Version::V32 { + let prefix = reached.iter().find_map(|&s| self.get(s, "prefixItems")); + for (i, item) in prefix + .map(|p| self.items(p)) + .unwrap_or_default() + .into_iter() + .enumerate() + { + let facts = self.facts(item); + if facts.binary { + while parts.prefix.len() <= i { + parts.prefix.push(Part::default()); + } + if let Some(part) = parts.prefix.get_mut(i) { + binary(part, facts.encoding); + } + } + } + if let Some(items) = reached.iter().find_map(|&s| self.get(s, "items")) { + let facts = self.facts(items); + if facts.binary { + binary(parts.item.get_or_insert_with(Box::default), facts.encoding); + } + } + } + } +} + +/// A part whose value is encoded bytes: `application/octet-stream` unless its Encoding Object +/// gives a type or a style, and the encoding as `Content-Transfer-Encoding` where given and no +/// header of that name is. +fn binary(part: &mut Part, encoding: Option) { + let styled = part.style.is_some() || part.explode.is_some() || part.allow_reserved.is_some(); + if part.content_type.is_none() && !styled { + part.content_type = Some(String::from("application/octet-stream")); + } + let named = |(n, _): &(String, String)| n.eq_ignore_ascii_case("content-transfer-encoding"); + if let Some(e) = encoding + && !part.headers.iter().any(named) + { + part.headers + .push((String::from("Content-Transfer-Encoding"), e)); + } +} diff --git a/crates/flowapi-sdk/src/encoding/print.rs b/crates/flowapi-sdk/src/encoding/print.rs new file mode 100644 index 0000000..0d5d6e2 --- /dev/null +++ b/crates/flowapi-sdk/src/encoding/print.rs @@ -0,0 +1,68 @@ +//! An operation's encodings as the TypeScript object its table entry holds: by media type, the +//! Media Type Object's three fields (`encoding`, `prefixEncoding`, `itemEncoding`), each Encoding +//! Object with the fields read (`FlowapiPart` in the SDK's runtime). + +use crate::model::{Encoding, Part, Parts}; +use crate::print::object; +use flowapi_ts::string_literal as lit; + +/// `{ "": { encoding: …, prefixEncoding: …, itemEncoding: … }, … }`. +pub(crate) fn literal(encodings: &[Encoding]) -> String { + let bodies: Vec = encodings + .iter() + .map(|e| format!("{}: {}", lit(&e.media_type), object(&members(&e.parts)))) + .collect(); + object(&bodies) +} + +/// The three fields, those that say anything. +fn members(parts: &Parts) -> Vec { + let mut out = Vec::new(); + if !parts.by_name.is_empty() { + let named: Vec = parts + .by_name + .iter() + .map(|(name, p)| format!("{}: {}", lit(name), part(p))) + .collect(); + out.push(format!("encoding: {}", object(&named))); + } + if !parts.prefix.is_empty() { + let items: Vec = parts.prefix.iter().map(part).collect(); + out.push(format!("prefixEncoding: [{}]", items.join(", "))); + } + if let Some(item) = &parts.item { + out.push(format!("itemEncoding: {}", part(item))); + } + out +} + +/// One Encoding Object. +fn part(p: &Part) -> String { + let mut fields = Vec::new(); + if let Some(t) = &p.content_type { + fields.push(format!("contentType: {}", lit(t))); + } + if !p.headers.is_empty() { + let headers: Vec = p + .headers + .iter() + .map(|(n, v)| format!("{}: {}", lit(n), lit(v))) + .collect(); + fields.push(format!("headers: {}", object(&headers))); + } + if let Some(s) = &p.style { + fields.push(format!("style: {}", lit(s))); + } + if let Some(e) = p.explode { + fields.push(format!("explode: {e}")); + } + if let Some(r) = p.allow_reserved { + fields.push(format!("allowReserved: {r}")); + } + if !p.nested.is_empty() { + let styles: Vec = p.nested.iter().map(|s| lit(s)).collect(); + fields.push(format!("nested: [{}]", styles.join(", "))); + } + fields.extend(members(&p.parts)); + object(&fields) +} diff --git a/crates/flowapi-sdk/src/encoding/swagger.rs b/crates/flowapi-sdk/src/encoding/swagger.rs new file mode 100644 index 0000000..5e28820 --- /dev/null +++ b/crates/flowapi-sdk/src/encoding/swagger.rs @@ -0,0 +1,50 @@ +//! Swagger 2.0 has no Encoding Object: a `formData` array's `collectionFormat` says how it goes in +//! the form. The core reads it, and each Items Object's own for the arrays inside it, as it reads +//! one in a query (`Media::encoding`, reported there); here it is given as an Encoding Object's +//! style would say it. `csv`, the default, is `form` unexploded (`a,b`); `multi` is `form` +//! exploded (a pair or a part per item); `ssv` and `pipes` are `spaceDelimited` and +//! `pipeDelimited`; `tsv`, which no 3.x style is, is `tabDelimited` (items joined by a tab). An +//! inner array's `csv` is `form` too (`,`). + +use crate::model::{Encoding, Part, Parts}; +use flowapi::spec::{Operation, Serialization, Style}; + +/// The encodings of a 2.0 operation's form, one per media type the core lifted it under whose +/// fields include an array. +pub(super) fn encodings(operation: &Operation) -> Vec { + let Some(body) = &operation.body else { + return Vec::new(); + }; + body.content + .iter() + .filter(|m| !m.encoding.is_empty()) + .map(|m| Encoding { + media_type: m.media_type.clone(), + parts: Parts { + by_name: m + .encoding + .iter() + .map(|(n, s)| (n.clone(), part(s))) + .collect(), + ..Parts::default() + }, + }) + .collect() +} + +/// One field's Encoding Object: its style and `explode`, and its inner arrays' styles. +fn part(s: &Serialization) -> Part { + let nested = s.nested.iter().map(|&style| { + String::from(if style == Style::Simple { + "form" + } else { + style.name() + }) + }); + Part { + style: Some(String::from(s.style.name())), + explode: Some(s.explode), + nested: nested.collect(), + ..Part::default() + } +} diff --git a/crates/flowapi-sdk/src/lib.rs b/crates/flowapi-sdk/src/lib.rs index dac3ce3..cf5f66b 100644 --- a/crates/flowapi-sdk/src/lib.rs +++ b/crates/flowapi-sdk/src/lib.rs @@ -33,6 +33,7 @@ mod ops; mod out; mod paging; mod print; +mod prose; mod repo; mod security; mod servers; @@ -44,7 +45,8 @@ pub use client::{Generated, client_files}; pub use config::{Issue, check, issues_json, issues_text, schema as config_schema, spec_of}; pub use draft::draft; pub use model::{ - Access, Auth, Encoding, KeyLocation, Requirement, Scheme, Server, Service, Variable, + Access, Auth, Encoding, KeyLocation, Part, Parts, Requirement, Scheme, Server, Service, + TokenFlow, Variable, }; pub use repo::{ Change, Disk, Entry, Input, LOCK_PATH, Lock, Next, OWN_ZONES, Owner, Plan, Repo, RepoFile, @@ -74,12 +76,13 @@ pub fn read(docs: &Documents<'_>, program: &Program<'_>) -> (Service, Diagnostic .map(|e| { let items = doc.path_items(&e.operation); let op = doc.operation(&items, &e.operation); + let servers = doc.own_servers(&items, op, &mut diags); + let (security, inherits) = doc.effective(&e.operation, &security, &mut diags); Access { - servers: doc.own_servers(&items, op, &mut diags), - security: op - .and_then(|op| doc.security(op, &mut diags)) - .unwrap_or_else(|| security.clone()), - encodings: doc.encodings(op, &mut diags), + servers, + security, + inherits, + encodings: doc.encodings(op, &e.operation, &mut diags), } }) .collect(); diff --git a/crates/flowapi-sdk/src/model.rs b/crates/flowapi-sdk/src/model.rs index ca74945..d0d65cf 100644 --- a/crates/flowapi-sdk/src/model.rs +++ b/crates/flowapi-sdk/src/model.rs @@ -70,10 +70,13 @@ pub enum Auth { /// How a bearer token is formatted, a hint only (`JWT`). format: Option, }, - /// OAuth 2.0: a token the caller obtained, sent as a bearer token; the flows are named only. + /// OAuth 2.0: a token sent as a bearer token, which the caller obtained, or which the client + /// requests itself by the client credentials flow, the one flow no person takes part in. OAuth2 { /// The flows' names, as written (2.0's lifted to 3.x names). flows: Vec, + /// The client credentials flow (2.0's `application`), where it has a token URL. + client_credentials: Option, }, /// OpenID Connect: a token the caller obtained, sent as a bearer token. OpenIdConnect { @@ -85,6 +88,15 @@ pub enum Auth { MutualTls, } +/// Where the client credentials flow asks for a token, and the scopes it may ask for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TokenFlow { + /// The token endpoint as written: a URL, or a reference relative to the server's. + pub token_url: String, + /// The scopes the scheme defines, in the order written. + pub scopes: Vec, +} + /// A security scheme, by its name in the description. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Scheme { @@ -106,14 +118,56 @@ pub struct Requirement { pub schemes: Vec<(String, Vec)>, } -/// The types a `multipart/form-data` body's parts are sent as, by the description's Encoding -/// Objects. +/// How a request body of a form or `multipart` media type is written, by the description's +/// Encoding Objects (and, where they say nothing, by its schemas): what the Media Type Object's +/// `encoding`, `prefixEncoding` and `itemEncoding` say, each field read only for the media types +/// it applies to. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Encoding { /// The media type, as written (`multipart/form-data`). pub media_type: String, - /// Each part's name with its one `contentType`, in the order written. - pub parts: Vec<(String, String)>, + /// What each value is written as. + pub parts: Parts, +} + +/// Encoding Objects mapped to values: by a property's name, or by an item's position. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Parts { + /// By name (`encoding`): each property's, in the order written. + pub by_name: Vec<(String, Part)>, + /// By position (`prefixEncoding`, 3.2): the first items', in order. + pub prefix: Vec, + /// The other items' (`itemEncoding`, 3.2). + pub item: Option>, +} + +impl Parts { + /// Whether it says nothing. + #[must_use] + pub fn is_empty(&self) -> bool { + self.by_name.is_empty() && self.prefix.is_empty() && self.item.is_none() + } +} + +/// One Encoding Object as it applies to its value: only the fields its media type takes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Part { + /// The `Content-Type` it is sent as (a list or a range as written). + pub content_type: Option, + /// Header fields with a value the description fixes (a `multipart` part's + /// `Content-Transfer-Encoding`, from a schema's `contentEncoding`). + pub headers: Vec<(String, String)>, + /// `style`, where written (2.0's `tsv` as `tabDelimited`). + pub style: Option, + /// `explode`, where written. + pub explode: Option, + /// `allowReserved`, where written. + pub allow_reserved: Option, + /// Swagger 2.0: the styles that join the arrays inside an array value, outermost first, each + /// Items Object's `collectionFormat` (`csv` as `form`); empty for any other. + pub nested: Vec, + /// Nested Encoding Objects (3.2), for a part that is itself `multipart`. + pub parts: Parts, } /// What one operation asks for. @@ -125,7 +179,10 @@ pub struct Access { /// Its security: the alternatives, any one of which is enough; its own `security`, else the /// description's. Empty means no authentication. pub security: Vec, - /// Its request body's encodings, one per `multipart/form-data` media type that has one. + /// Whether `security` is the description's, the operation having none of its own: what a + /// config's `security` replaces. + pub inherits: bool, + /// Its request body's encodings, one per form or `multipart` media type that has one. pub encodings: Vec, } diff --git a/crates/flowapi-sdk/src/ops.rs b/crates/flowapi-sdk/src/ops.rs index 8a9a157..4671d02 100644 --- a/crates/flowapi-sdk/src/ops.rs +++ b/crates/flowapi-sdk/src/ops.rs @@ -1,5 +1,6 @@ //! The description's operations as a config names them: each by its `operationId`, or by its -//! route `"METHOD /path"`, with what an agent reads of it (tags, summary) and the core's reading +//! route `"METHOD /path"`, with what an agent and a doc comment read of it (tags, summary, +//! description, `deprecated`, `externalDocs`) and the core's reading //! of its parameters, body and responses (`flowapi::spec::read`; no type graph is built, so a //! description of thousands of operations is read in the time its JSON takes). @@ -18,8 +19,13 @@ pub(crate) struct Op { pub(crate) route: String, /// Its tags, in the order written. pub(crate) tags: Vec, - /// Its `summary`. + /// Its `summary` and `description`, as written (CommonMark). pub(crate) summary: Option, + pub(crate) description: Option, + /// Whether it is `deprecated: true`. + pub(crate) deprecated: bool, + /// Its `externalDocs`: the URL, and what it says of it. + pub(crate) external_docs: Option<(String, Option)>, } impl Op { @@ -58,9 +64,19 @@ impl<'d, 't> Ops<'d, 't> { .into_iter() .filter_map(|t| doc.tree(t.0)?.as_str(t.1).map(|s| s.into_owned())) .collect(); + let external = raw.and_then(|o| doc.get(o, "externalDocs")); list.push(Op { operation_id: raw.and_then(|o| doc.str(o, "operationId")), summary: raw.and_then(|o| doc.str(o, "summary")), + description: raw.and_then(|o| doc.str(o, "description")), + deprecated: raw + .and_then(|o| doc.get(o, "deprecated")) + .and_then(|(d, n)| doc.tree(d)?.as_bool(n)) + .unwrap_or(false), + external_docs: external.and_then(|e| { + let url = doc.str(e, "url")?; + Some((url, doc.str(e, "description"))) + }), route: format!( "{} {}", operation.method.to_ascii_uppercase(), diff --git a/crates/flowapi-sdk/src/print.rs b/crates/flowapi-sdk/src/print.rs index 108bd75..a351f8a 100644 --- a/crates/flowapi-sdk/src/print.rs +++ b/crates/flowapi-sdk/src/print.rs @@ -3,7 +3,7 @@ //! reading decided by that target (`sdk_bases`, `sdk_method`, `ReadAs`), so the table and the //! functions it points at cannot disagree. The same service prints the same bytes (G4). -use crate::model::{Auth, Requirement, Server, Service}; +use crate::model::{Auth, Requirement, Scheme, Server, Service}; use flowapi::Program; use flowapi_ts::{ReadAs, sdk_bases, sdk_method, string_literal as lit}; use std::fmt::Write; @@ -22,8 +22,10 @@ const SCHEMES: &str = " /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "; @@ -34,9 +36,10 @@ const OPERATIONS: &str = " * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { "; @@ -49,32 +52,7 @@ pub(crate) fn table(program: &Program<'_>, service: &Service) -> String { out.push_str("] as const;\n"); out.push_str(SCHEMES); for s in &service.schemes { - let mut fields = match &s.auth { - Auth::ApiKey { location, name } => format!( - "type: \"apiKey\", in: {}, name: {}", - lit(location.name()), - lit(name) - ), - Auth::Http { scheme, format } => { - let format = format - .as_ref() - .map(|f| format!(", bearerFormat: {}", lit(f))) - .unwrap_or_default(); - format!("type: \"http\", scheme: {}{format}", lit(scheme)) - } - Auth::OAuth2 { flows } => format!("type: \"oauth2\", flows: {}", list(flows)), - Auth::OpenIdConnect { url } => { - format!("type: \"openIdConnect\", openIdConnectUrl: {}", lit(url)) - } - Auth::MutualTls => String::from("type: \"mutualTLS\""), - }; - if let Some(d) = &s.description { - let _ = write!(fields, ", description: {}", lit(d)); - } - if s.deprecated { - fields.push_str(", deprecated: true"); - } - let _ = writeln!(out, " {}: {{ {fields} }},", lit(&s.name)); + let _ = writeln!(out, " {}: {{ {} }},", lit(&s.name), scheme(s)); } out.push_str("} as const;\n"); out.push_str(OPERATIONS); @@ -113,19 +91,8 @@ pub(crate) fn table(program: &Program<'_>, service: &Service) -> String { .collect(); let _ = writeln!(out, " responses: {},", object(&responses)); if !access.encodings.is_empty() { - let bodies: Vec = access - .encodings - .iter() - .map(|e| { - let parts: Vec = e - .parts - .iter() - .map(|(name, t)| format!("{}: {{ contentType: {} }}", lit(name), lit(t))) - .collect(); - format!("{}: {}", lit(&e.media_type), object(&parts)) - }) - .collect(); - let _ = writeln!(out, " encoding: {},", object(&bodies)); + let encodings = crate::encoding::literal(&access.encodings); + let _ = writeln!(out, " encoding: {encodings},"); } let _ = writeln!(out, " request: {base}Request,"); let _ = writeln!(out, " response: {base}Response,"); @@ -135,6 +102,50 @@ pub(crate) fn table(program: &Program<'_>, service: &Service) -> String { out } +/// A scheme's members on one line. +fn scheme(s: &Scheme) -> String { + let mut fields = match &s.auth { + Auth::ApiKey { location, name } => format!( + "type: \"apiKey\", in: {}, name: {}", + lit(location.name()), + lit(name) + ), + Auth::Http { scheme, format } => { + let format = format + .as_ref() + .map(|f| format!(", bearerFormat: {}", lit(f))) + .unwrap_or_default(); + format!("type: \"http\", scheme: {}{format}", lit(scheme)) + } + Auth::OAuth2 { + flows, + client_credentials, + } => { + let mut out = format!("type: \"oauth2\", flows: {}", list(flows)); + if let Some(f) = client_credentials { + let _ = write!( + out, + ", clientCredentials: {{ tokenUrl: {}, scopes: {} }}", + lit(&f.token_url), + list(&f.scopes) + ); + } + out + } + Auth::OpenIdConnect { url } => { + format!("type: \"openIdConnect\", openIdConnectUrl: {}", lit(url)) + } + Auth::MutualTls => String::from("type: \"mutualTLS\""), + }; + if let Some(d) = &s.description { + let _ = write!(fields, ", description: {}", lit(d)); + } + if s.deprecated { + fields.push_str(", deprecated: true"); + } + fields +} + /// A server as an object literal on one line. fn server(s: &Server) -> String { let mut out = format!("{{ url: {}", lit(&s.url)); @@ -176,7 +187,7 @@ fn requirement(r: &Requirement) -> String { } /// Members as an object literal: `{}` for none. -fn object(members: &[String]) -> String { +pub(crate) fn object(members: &[String]) -> String { if members.is_empty() { return String::from("{}"); } diff --git a/crates/flowapi-sdk/src/prose.rs b/crates/flowapi-sdk/src/prose.rs new file mode 100644 index 0000000..17cc2f0 --- /dev/null +++ b/crates/flowapi-sdk/src/prose.rs @@ -0,0 +1,241 @@ +//! A description's prose, CommonMark as OpenAPI writes it, made plain text for the places that +//! show no Markdown: `package.json`'s `description`, a doc comment, a heading. A paragraph keeps +//! its words and loses its markup: a link or an image is its text, code its content, emphasis its +//! words, an HTML tag nothing; a heading, a list item and a quote are paragraphs of their own; +//! fenced and indented code is left out. Never panics, whatever the text (G1). + +#[cfg(test)] +#[path = "prose_tests.rs"] +mod tests; + +/// The most characters of a sentence that is put where a line is short (`package.json`). +pub(crate) const MAX_SENTENCE: usize = 200; + +/// What a paragraph was in the text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Block { + Text, + Heading, + Item, +} + +/// The text's paragraphs as plain text, each on one line, none empty. +pub(crate) fn paragraphs(markdown: &str) -> Vec { + blocks(markdown).into_iter().map(|(_, t)| t).collect() +} + +fn blocks(markdown: &str) -> Vec<(Block, String)> { + let mut out: Vec<(Block, String)> = Vec::new(); + let mut open = String::new(); + let mut fence: Option<&str> = None; + let push = |kind: Block, text: &mut String, out: &mut Vec<(Block, String)>| { + let plain = inline(text); + if !plain.is_empty() { + out.push((kind, plain)); + } + text.clear(); + }; + for raw in markdown.lines() { + let line = raw.trim(); + if let Some(f) = fence { + if line.starts_with(f) { + fence = None; + } + continue; + } + if let Some(f) = ["```", "~~~"].into_iter().find(|f| line.starts_with(f)) { + push(Block::Text, &mut open, &mut out); + fence = Some(f); + continue; + } + if line.is_empty() || raw.starts_with(" ") || raw.starts_with('\t') { + push(Block::Text, &mut open, &mut out); + continue; + } + match block(line) { + (Block::Text, text) => { + if !open.is_empty() { + open.push(' '); + } + open.push_str(&text); + } + (kind, mut text) => { + push(Block::Text, &mut open, &mut out); + push(kind, &mut text, &mut out); + } + } + } + push(Block::Text, &mut open, &mut out); + out +} + +/// A line without its block marker, and what it is: a heading and a list item are paragraphs of +/// their own, a quote's line joins the paragraph it is in. +fn block(line: &str) -> (Block, String) { + let quote = line.trim_start_matches('>').trim_start(); + if quote.len() != line.len() { + return (Block::Text, quote.to_owned()); + } + let hashes = line.chars().take_while(|&c| c == '#').count(); + if (1..=6).contains(&hashes) && line.chars().nth(hashes).is_none_or(|c| c == ' ') { + let text = line + .get(hashes..) + .unwrap_or("") + .trim() + .trim_end_matches('#'); + return (Block::Heading, text.trim().to_owned()); + } + for marker in ["- ", "* ", "+ "] { + if let Some(rest) = line.strip_prefix(marker) { + return (Block::Item, format!("- {rest}")); + } + } + let digits = line.chars().take_while(char::is_ascii_digit).count(); + if digits > 0 + && let Some(rest) = line.get(digits..).and_then(|r| r.strip_prefix(". ")) + { + return (Block::Item, format!("- {rest}")); + } + (Block::Text, line.to_owned()) +} + +/// The first sentence of the text's first paragraph that is no heading, when it is a sentence of +/// at most [`MAX_SENTENCE`] characters; a sentence ends at `.`, `!` or `?` before a space and a +/// capital, or at the paragraph's end. +pub(crate) fn sentence(markdown: &str) -> Option { + let (_, first) = blocks(markdown) + .into_iter() + .find(|(kind, _)| *kind == Block::Text)?; + let chars: Vec = first.chars().collect(); + let mut end = chars.len(); + for (i, w) in chars.windows(3).enumerate() { + if let [stop, ' ', next] = w + && matches!(stop, '.' | '!' | '?') + && next.is_uppercase() + { + end = i + 1; + break; + } + } + let s: String = chars.iter().take(end).collect(); + let s = s.trim().to_owned(); + (!s.is_empty() && s.chars().count() <= MAX_SENTENCE).then_some(s) +} + +/// One paragraph's inline markup taken out, its whitespace made single spaces. +pub(crate) fn inline(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut out = String::new(); + let mut i = 0; + while let Some(&c) = chars.get(i) { + let at = |k: usize| chars.get(k).copied(); + match c { + '\\' if at(i + 1).is_some_and(|n| n.is_ascii_punctuation()) => { + out.extend(at(i + 1)); + i += 2; + } + '!' if at(i + 1) == Some('[') => i += 1, + '[' => i = link(&chars, i, &mut out), + '<' => i = angle(&chars, i, &mut out), + '`' => i += 1, + '*' | '_' => { + let before = i.checked_sub(1).and_then(at).unwrap_or(' '); + let after = at(i + 1).unwrap_or(' '); + let word = |x: char| x.is_alphanumeric(); + // A marker is emphasis only where another closes it: a lone `*` is text. + let paired = chars.iter().filter(|&&x| x == c).count() > 1; + let keep = !paired + || (before.is_whitespace() && after.is_whitespace()) + || (c == '_' && word(before) && word(after)); + if keep { + out.push(c); + } + i += 1; + } + '&' => i = entity(&chars, i, &mut out), + _ => { + out.push(c); + i += 1; + } + } + } + out.split_whitespace().collect::>().join(" ") +} + +/// The index of the first `close` after `from` at the same depth of `open`, when there is one. +fn closing(chars: &[char], from: usize, open: char, close: char) -> Option { + let mut depth = 0usize; + for (k, &c) in chars.iter().enumerate().skip(from) { + if c == open { + depth += 1; + } else if c == close { + depth = depth.checked_sub(1)?; + if depth == 0 { + return Some(k); + } + } + } + None +} + +/// `[text](url)`, `[text][ref]` and `[text]` as their text; the index after them. +fn link(chars: &[char], i: usize, out: &mut String) -> usize { + let Some(end) = closing(chars, i, '[', ']') else { + out.push('['); + return i + 1; + }; + let text: String = chars.get(i + 1..end).unwrap_or(&[]).iter().collect(); + out.push_str(&inline(&text)); + match chars.get(end + 1) { + Some('(') => closing(chars, end + 1, '(', ')').map_or(end + 1, |k| k + 1), + Some('[') => closing(chars, end + 1, '[', ']').map_or(end + 1, |k| k + 1), + Some(_) | None => end + 1, + } +} + +/// An autolink (``) as its URL, an HTML tag as nothing, else a `<`. +fn angle(chars: &[char], i: usize, out: &mut String) -> usize { + let close = chars.iter().skip(i).position(|&c| c == '>').map(|k| k + i); + let inner: String = close + .and_then(|k| chars.get(i + 1..k)) + .unwrap_or(&[]) + .iter() + .collect(); + let tag = inner + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '/' || c == '!'); + match close { + Some(k) if inner.starts_with("http://") || inner.starts_with("https://") => { + out.push_str(&inner); + k + 1 + } + Some(k) if tag && (!inner.contains(' ') || inner.contains('=')) => k + 1, + Some(_) | None => { + out.push('<'); + i + 1 + } + } +} + +/// An HTML entity as its character (the few descriptions write); the index after it. +fn entity(chars: &[char], i: usize, out: &mut String) -> usize { + const ENTITIES: &[(&str, char)] = &[ + ("&", '&'), + ("<", '<'), + (">", '>'), + (""", '"'), + ("'", '\''), + ("'", '\''), + (" ", ' '), + ]; + let rest: String = chars.iter().skip(i).take(6).collect(); + for (name, c) in ENTITIES { + if rest.starts_with(name) { + out.push(*c); + return i + name.chars().count(); + } + } + out.push('&'); + i + 1 +} diff --git a/crates/flowapi-sdk/src/prose_tests.rs b/crates/flowapi-sdk/src/prose_tests.rs new file mode 100644 index 0000000..f342040 --- /dev/null +++ b/crates/flowapi-sdk/src/prose_tests.rs @@ -0,0 +1,59 @@ +//! CommonMark made plain: the markup descriptions write (GitHub's links and notes, Stripe's code, +//! Twilio's HTML), and the first sentence a package's description takes. + +use super::{inline, paragraphs, sentence}; + +#[test] +fn inline_markup_is_taken_out_and_its_words_kept() { + let cases = [ + ( + "Lists the [repositories](https://docs.github.com/rest) of `org`.", + "Lists the repositories of org.", + ), + ("**Note:** a _new_ *field*", "Note: a new field"), + ( + "keep snake_case_words and 2 * 3", + "keep snake_case_words and 2 * 3", + ), + ("A bold link", "A bold link"), + ("See .", "See https://example.com."), + ("a < b & c > d", "a < b & c > d"), + ("an ![image](x.png) here", "an image here"), + ("escaped \\*stars\\* stay", "escaped *stars* stay"), + ("List the pets */ one page", "List the pets */ one page"), + ("[unclosed and (more", "[unclosed and (more"), + ]; + for (text, want) in cases { + assert_eq!(inline(text), want, "{text}"); + } +} + +#[test] +fn blocks_are_paragraphs_and_code_is_left_out() { + let text = "# Heading\n\nFirst line\nwraps on.\n\n```js\ncode()\n```\n\n- one\n- two\n\n> quoted\n> text\n\n indented code\n"; + assert_eq!( + paragraphs(text), + [ + "Heading", + "First line wraps on.", + "- one", + "- two", + "quoted text" + ] + ); +} + +#[test] +fn the_first_sentence_is_a_short_one_of_the_first_paragraph() { + assert_eq!( + sentence("# Shop\n\nSells pets. And more, e.g. food.").as_deref(), + Some("Sells pets.") + ); + assert_eq!( + sentence("Version 2.0 of the API, for e.g. tests").as_deref(), + Some("Version 2.0 of the API, for e.g. tests") + ); + assert_eq!(sentence(&"long ".repeat(60)), None); + assert_eq!(sentence("- only a list"), None); + assert_eq!(sentence(""), None); +} diff --git a/crates/flowapi-sdk/src/repo.rs b/crates/flowapi-sdk/src/repo.rs index e80c80b..f8db965 100644 --- a/crates/flowapi-sdk/src/repo.rs +++ b/crates/flowapi-sdk/src/repo.rs @@ -174,7 +174,7 @@ pub fn repo_files( ) else { return repo; }; - let (service, _) = crate::read(docs, program); + let (service, _) = client::service(docs, program, &check); let ctx = Ctx { config: &check.config, ops: &ops, @@ -249,17 +249,11 @@ fn calls( .get(&client::route(&o.operation)) .and_then(|&i| bases.get(i).cloned().flatten()); let Some(base) = base else { continue }; - let mut members = Vec::new(); - let mut next = Some(m.resource); - while let Some(r) = next { - members.push(resources::member_of(c, r)); - next = c.resources.get(r).and_then(|x| x.parent); - if members.len() > c.resources.len() { - break; - } - } - members.reverse(); - members.push(client::camel(&words::words(&m.name.name))); + let access = format!( + "{}.{}", + resources::access_of(c, m.resource), + client::camel(&words::words(&m.name.name)) + ); let kind = if m.stream.is_some() { Kind::Stream } else if effective(c, m).and_then(|n| find(c, &n.name)).is_some() { @@ -270,7 +264,7 @@ fn calls( out.push(Call { method: k, name: format!("{}.{}", c.path(m.resource), m.name.name), - access: members.join("."), + access, op, base, kind, diff --git a/crates/flowapi-sdk/src/repo/files/server.mjs b/crates/flowapi-sdk/src/repo/files/server.mjs index 126454e..07c6fa6 100644 --- a/crates/flowapi-sdk/src/repo/files/server.mjs +++ b/crates/flowapi-sdk/src/repo/files/server.mjs @@ -2,17 +2,20 @@ // // The API's mock server, on node:http with no dependency, answering by the routes printed from // the description beside it (routes.mjs). It is strict where a client goes wrong: a path no -// operation has is a 404, a method the path has not a 405, a required query parameter, header, -// cookie or body that is missing a 400, a body of a media type the operation does not take a -// 415. Otherwise it answers with the operation's first success status and an example value of -// its schema (the schema's example, else its default, its first enum value, else one made from -// its type and format). Each request answered is recorded, with the route it matched. +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). // // `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL // names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. import { createServer } from 'node:http' import { pathToFileURL } from 'node:url' -import routes from './routes.mjs' +import routes, { tokens } from './routes.mjs' /** A route's path as a regular expression: each `{name}` is one segment. */ function pattern(path) { @@ -69,6 +72,67 @@ function hasQuery(url, name) { return false } +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + /** What is wrong with a request for its route, with the status that says so; null for nothing. */ function problem(route, url, req, body) { for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] @@ -123,6 +187,7 @@ function handle(req, res, requests) { req.on('end', () => { const body = Buffer.concat(chunks) const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) const matches = table.filter((r) => r.regex.test(url.pathname)) if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) const route = matches.find((r) => r.method === req.method) @@ -130,6 +195,12 @@ function handle(req, res, requests) { const methods = matches.map((r) => r.method).join(', ') return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } const wrong = problem(route, url, req, body) if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) diff --git a/crates/flowapi-sdk/src/repo/mock.rs b/crates/flowapi-sdk/src/repo/mock.rs index ebbba63..883eae5 100644 --- a/crates/flowapi-sdk/src/repo/mock.rs +++ b/crates/flowapi-sdk/src/repo/mock.rs @@ -1,11 +1,15 @@ //! The mock server: `mock/server.mjs`, the same for every API (`files/server.mjs`), and //! `mock/routes.mjs`, the operations the client calls as it reads them, printed from the //! description: each one's method and path, the query parameters, headers and cookies it -//! requires, its body (whether required, the media types it takes), and its answer (the lowest -//! success status, its media type, an example value of its schema, `example.rs`). +//! requires, its body (whether required, the media types it takes), the credentials its security +//! asks for (the config's over the description's), and its answer (the lowest success status, +//! its media type, an example value of its schema, `example.rs`); and the token endpoints of the +//! client credentials flows, which the mock answers too. use super::example::{self, Value}; -use super::{Ctx, HEADER, RepoFile, generated_file}; +use super::{Call, Ctx, HEADER, RepoFile, generated_file}; +use crate::config::auth::{CHALLENGED, has_token_flow, is_basic, needed}; +use crate::model::{Auth, KeyLocation}; use crate::out::{json_list, json_str}; use flowapi::spec::{Location, Operation, Response}; use std::fmt::Write as _; @@ -30,15 +34,112 @@ fn routes(ctx: &Ctx<'_>) -> String { } seen.push(call.op); if let Some(op) = ctx.ops.list.get(call.op) { - let _ = writeln!(out, " {},", route(ctx, &op.operation)); + let _ = writeln!( + out, + " {},", + route(ctx, &op.operation, &security(ctx, call)) + ); } } out.push_str("]\n"); + let mut tokens: Vec = ctx + .service + .schemes + .iter() + .filter_map(|s| match &s.auth { + Auth::OAuth2 { + client_credentials: Some(f), + .. + } => Some(token_path(&f.token_url)), + Auth::ApiKey { .. } + | Auth::Http { .. } + | Auth::OAuth2 { .. } + | Auth::OpenIdConnect { .. } + | Auth::MutualTls => None, + }) + .collect(); + tokens.dedup(); + let _ = writeln!( + out, + "\n// The token endpoints of the client credentials flows, by path.\nexport const tokens = {}", + json_list(&tokens) + ); out } +/// The path a token URL is answered at by the mock: an absolute URL's, else the reference +/// resolved against the mock's root (where a test's client has its base URL). +pub(crate) fn token_path(url: &str) -> String { + let rest = url.split_once("://").map_or(url, |(_, r)| { + r.char_indices() + .find(|(_, c)| *c == '/') + .and_then(|(i, _)| r.get(i..)) + .unwrap_or("/") + }); + let path = rest.split(['?', '#']).next().unwrap_or(""); + if path.starts_with('/') { + path.to_owned() + } else { + format!("/{path}") + } +} + +/// A call's security as the mock checks it: alternatives, each the credentials it needs. +fn security(ctx: &Ctx<'_>, call: &Call) -> String { + let Some(op) = ctx.ops.list.get(call.op) else { + return String::from("[]"); + }; + let method = ctx.config.methods.get(call.method); + let alternatives: Vec = needed(ctx.config, ctx.ops, method, op) + .iter() + .map(|r| { + let checks: Vec = r.schemes.iter().map(|(n, _)| check(ctx, n)).collect(); + format!("[{}]", checks.join(", ")) + }) + .collect(); + format!("[{}]", alternatives.join(", ")) +} + +/// What the mock looks for of one scheme. +fn check(ctx: &Ctx<'_>, name: &str) -> String { + let scheme = ctx.service.schemes.iter().find(|s| s.name == name); + let kind = match scheme.map(|s| &s.auth) { + None => String::from("\"kind\": \"unknown\""), + Some(Auth::ApiKey { location, name }) => { + let name = if *location == KeyLocation::Header { + name.to_ascii_lowercase() + } else { + name.clone() + }; + format!( + "\"kind\": \"apiKey\", \"in\": {}, \"name\": {}", + json_str(location.name()), + json_str(&name) + ) + } + Some(auth) if is_basic(auth) => String::from("\"kind\": \"basic\""), + Some(Auth::Http { scheme, .. }) if scheme != "bearer" => { + let refused = if CHALLENGED.contains(&scheme.as_str()) { + ", \"refused\": true" + } else { + "" + }; + format!( + "\"kind\": \"http\", \"scheme\": {}{refused}", + json_str(scheme) + ) + } + Some(auth) if has_token_flow(auth) => String::from("\"kind\": \"bearer\", \"flow\": true"), + Some(Auth::MutualTls) => String::from("\"kind\": \"mutualTLS\""), + Some(Auth::Http { .. } | Auth::OAuth2 { .. } | Auth::OpenIdConnect { .. }) => { + String::from("\"kind\": \"bearer\"") + } + }; + format!("{{ \"scheme\": {}, {kind} }}", json_str(name)) +} + /// One route, as a JSON object on one line. -fn route(ctx: &Ctx<'_>, op: &Operation) -> String { +fn route(ctx: &Ctx<'_>, op: &Operation, security: &str) -> String { let doc = &ctx.ops.doc; let required = |location: Location| -> Vec { op.params @@ -75,7 +176,7 @@ fn route(ctx: &Ctx<'_>, op: &Operation) -> String { ); let (status, media, value) = success(ctx, op); format!( - "{{ \"route\": {}, \"method\": {}, \"path\": {}, \"query\": {}, \"headers\": {}, \"cookies\": {}, \"body\": {body}, \"status\": {status}, \"media\": {}, \"example\": {} }}", + "{{ \"route\": {}, \"method\": {}, \"path\": {}, \"query\": {}, \"headers\": {}, \"cookies\": {}, \"body\": {body}, \"security\": {security}, \"status\": {status}, \"media\": {}, \"example\": {} }}", json_str(&format!("{method} {}", op.path)), json_str(&method), json_str(&op.path), diff --git a/crates/flowapi-sdk/src/repo/package.rs b/crates/flowapi-sdk/src/repo/package.rs index fcabe10..09af6be 100644 --- a/crates/flowapi-sdk/src/repo/package.rs +++ b/crates/flowapi-sdk/src/repo/package.rs @@ -1,4 +1,5 @@ -//! The package: `package.json`, the TypeScript configs and the license. +//! The package: `package.json`, the TypeScript configs and the license; and the names the +//! package and its README go by (`heading`, `description`), from the config or the description. //! //! One package from the repository's root, built twice by `tsc` alone (no bundler, no tool of //! someone else's): ES modules into `dist/esm`, CommonJS into `dist/cjs` (with a @@ -14,6 +15,8 @@ use super::{Ctx, RepoFile, generated_file}; use crate::config::issue::Issues; use crate::doc::ROOT; use crate::out::json_str; +use crate::prose; +use crate::words::words; /// The TypeScript the package builds and checks with: `conformance/ts`'s. pub(crate) const TYPESCRIPT: &str = "7.0.2"; @@ -70,23 +73,120 @@ fn tsconfig() -> String { ) } -/// The description's title, for the package's description. -pub(crate) fn title(ctx: &Ctx<'_>) -> Option { +/// A member of the description's `info` as plain text, when it has some. +fn info(ctx: &Ctx<'_>, key: &str) -> Option { let doc = &ctx.ops.doc; - doc.get(ROOT, "info").and_then(|i| doc.str(i, "title")) + let text = doc.get(ROOT, "info").and_then(|i| doc.str(i, key))?; + let plain = prose::inline(&text); + (!plain.is_empty()).then_some(plain) } -fn package_json(ctx: &Ctx<'_>) -> String { - let description = title(ctx).map_or_else( - || String::from("A TypeScript client of the API"), - |t| format!("A TypeScript client of the {t} API"), +/// The API's name: `info.title` without a last `API` (and a `REST` before it), the name the +/// heading and the description put `TypeScript SDK` beside (`GitHub v3 REST API` is `GitHub v3`, +/// `Twilio - Studio` is `Twilio Studio`). +pub(crate) fn api_name(ctx: &Ctx<'_>) -> Option { + let title = info(ctx, "title")?; + // A piece of punctuation alone between words (`Twilio - Studio`) is no part of the name. + let mut words: Vec<&str> = title + .split(' ') + .filter(|w| w.chars().any(char::is_alphanumeric)) + .collect(); + for last in ["api", "rest"] { + if words.len() > 1 && words.last().is_some_and(|w| w.eq_ignore_ascii_case(last)) { + words.pop(); + } + } + let name = words.join(" "); + let name = name.trim_end_matches(['-', ':', ',', ' ']); + (!name.is_empty()).then(|| name.to_owned()) +} + +/// The README's heading: `readme.title`, else the API's name and `TypeScript SDK`, else the +/// package's name. +pub(crate) fn heading(ctx: &Ctx<'_>) -> String { + let s = &ctx.config.settings; + s.title.clone().unwrap_or_else(|| { + api_name(ctx).map_or_else( + || ctx.package().to_owned(), + |n| format!("{n} TypeScript SDK"), + ) + }) +} + +/// Words a description's first sentence may hold and still say nothing of the API. +const FILLER: &[&str] = &[ + "the", + "this", + "that", + "our", + "its", + "public", + "official", + "rest", + "restful", + "http", + "https", + "web", + "api", + "apis", + "version", + "welcome", + "documentation", + "docs", + "site", + "reference", + "for", + "and", + "you", + "your", +]; + +/// The package's description: `package.description`, else `TypeScript SDK for the API.` +/// and the first sentence of `info.summary`, else of `info.description`, where it is short and +/// says more than the title. +pub(crate) fn description(ctx: &Ctx<'_>) -> String { + if let Some(d) = &ctx.config.settings.description { + return d.clone(); + } + let mut out = api_name(ctx).map_or_else( + || String::from("TypeScript SDK for an HTTP API."), + |n| format!("TypeScript SDK for the {n} API."), ); + let doc = &ctx.ops.doc; + let about = ["summary", "description"].into_iter().find_map(|key| { + let text = doc.get(ROOT, "info").and_then(|i| doc.str(i, key))?; + prose::sentence(&text) + }); + // A sentence of the title's words and words that say nothing of an API alone (`GitHub's v3 + // REST API`, `This is the public Twilio REST API`, `Welcome to the API documentation`) is + // left out: the first sentence would repeat the title. + let title: Vec = info(ctx, "title").map(|t| words(&t)).unwrap_or_default(); + let news = |s: &String| { + words(s) + .iter() + .any(|w| w.len() > 2 && !title.contains(w) && !FILLER.contains(&w.as_str())) + }; + if let Some(mut s) = about.filter(news) { + if !s.ends_with(['.', '!', '?']) { + s.push('.'); + } + out.push(' '); + out.push_str(&s); + } + out +} + +fn package_json(ctx: &Ctx<'_>) -> String { let s = &ctx.config.settings; let mut fields = vec![ format!("\"name\": {}", json_str(ctx.package())), format!("\"version\": {}", json_str(ctx.version())), - format!("\"description\": {}", json_str(&description)), + format!("\"description\": {}", json_str(&description(ctx))), ]; + if !s.keywords.is_empty() { + let keywords: Vec = s.keywords.iter().map(|k| json_str(k)).collect(); + fields.push(format!("\"keywords\": [{}]", keywords.join(", "))); + } if let Some(l) = &ctx.config.license { fields.push(format!("\"license\": {}", json_str(&l.name))); } diff --git a/crates/flowapi-sdk/src/repo/readme.rs b/crates/flowapi-sdk/src/repo/readme.rs index be93106..053f48a 100644 --- a/crates/flowapi-sdk/src/repo/readme.rs +++ b/crates/flowapi-sdk/src/repo/readme.rs @@ -1,25 +1,34 @@ //! `README.md` and `api.md`, written from the config and the description, never by an agent: //! the counts are the methods the client has (pitfall 16 of the study: a count typed by hand -//! drifts), the headline example is `readme.headline_method` (else the first method) called with -//! what its operation requires, and a section is there only when the API has what it is about -//! (environments, pagination, streaming). `api.md` lists every method by resource with the -//! types its TypeScript signature has. +//! drifts), the heading and first paragraph are the config's (`readme.title`, `readme.intro`, +//! `package.description`) or made from the description's `info`, the headline example is +//! `readme.headline_method` (else the first method) called with what its operation requires, and +//! a section is there only when the API has what it is about (environments, pagination, +//! streaming). The sections after the usage are in `readme/sections.rs`, `api.md` in +//! `readme/api.rs`, the authentication in `readme/auth.rs`; `tests/texts.mjs` compiles every example of both against the client. -use super::suite::{args, options}; -use super::{Call, Ctx, HEADER, Kind, RepoFile, generated_file, package, texts}; -use crate::client::camel; -use crate::config::check::{effective, find}; -use crate::model::{Auth, KeyLocation}; +mod api; +mod auth; +mod sections; +mod servers; + +use super::suite::args; +use super::{Call, Ctx, HEADER, Kind, RepoFile, generated_file, package}; use crate::words; use std::fmt::Write as _; pub(crate) fn files(ctx: &Ctx<'_>) -> Vec { vec![ generated_file("README.md", readme(ctx)), - generated_file("api.md", api(ctx)), + generated_file("api.md", api::api(ctx)), ] } +/// `n things`, `1 thing`. +fn plural(n: usize, one: &str) -> String { + format!("{n} {one}{}", if n == 1 { "" } else { "s" }) +} + /// `N methods in M resources`. fn counted(ctx: &Ctx<'_>) -> String { let mut resources: Vec = ctx @@ -29,7 +38,6 @@ fn counted(ctx: &Ctx<'_>) -> String { .collect(); resources.sort_unstable(); resources.dedup(); - let plural = |n: usize, one: &str| format!("{n} {one}{}", if n == 1 { "" } else { "s" }); format!( "{} in {}", plural(ctx.calls.len(), "method"), @@ -53,36 +61,58 @@ fn headline<'c>(ctx: &'c Ctx<'_>) -> Option<&'c Call> { ctx.calls.iter().find(same).or_else(|| ctx.calls.first()) } +/// What the README passes a method: the parameters and body its operation requires, as code; +/// nothing when it requires none. +fn input(ctx: &Ctx<'_>, call: &Call) -> String { + ctx.ops + .list + .get(call.op) + .and_then(|op| args(ctx, &op.operation, true)) + .map(|v| v.js()) + .unwrap_or_default() +} + fn readme(ctx: &Ctx<'_>) -> String { let package = ctx.package(); let client = ctx.client(); - let mut out = format!("\n\n# {package}\n\n"); - let intro = ctx.config.settings.intro.clone().unwrap_or_else(|| { - let api = - package::title(ctx).map_or_else(|| String::from("the API"), |t| format!("the {t} API")); - format!("The TypeScript client of {api}, generated by flowapi from its description.") - }); - let _ = writeln!( - out, - "{intro}\n\nIt has {}; [api.md](api.md) lists them.\n", + let s = &ctx.config.settings; + let intro = s.intro.clone().unwrap_or_else(|| package::description(ctx)); + let mut out = format!( + "\n\n# {}\n\n{intro}\n\nThe `{client}` client is generated by flowapi from the API's description: {}, each listed in [api.md](api.md) with its parameters and what it returns.\n\n", + package::heading(ctx), counted(ctx) ); let _ = writeln!(out, "## Install\n\n```sh\nnpm install {package}\n```\n"); + usage(ctx, &mut out); + sections::resources(ctx, &mut out); + auth::section(ctx, &mut out); + sections::environments(ctx, &mut out); + servers::servers(ctx, &mut out); + let first = headline(ctx); + sections::errors(ctx, first, &mut out); + sections::retries(ctx, first, &mut out); + sections::paging(ctx, &mut out); + sections::logging(ctx, &mut out); + sections::requests(&mut out); + sections::closing(&mut out); + out +} + +/// The headline example, what a method takes and gives, and how the package is built. +fn usage(ctx: &Ctx<'_>, out: &mut String) { + let package = ctx.package(); + let client = ctx.client(); let _ = writeln!( out, "## Usage\n\n```ts\nimport {{ {client} }} from '{package}'\n\nconst client = new {client}()" ); - if let Some(call) = headline(ctx) { - let input = ctx - .ops - .list - .get(call.op) - .and_then(|op| args(ctx, &op.operation, true)); - let input = input.map(|v| v.js()).unwrap_or_default(); + let call = headline(ctx); + if let Some(call) = call { let _ = writeln!( out, - "\nconst result = await client.{}({input})", - call.access + "\nconst result = await client.{}({})", + call.access, + input(ctx, call) ); if call.kind == Kind::Stream { out.push_str("for await (const event of result) console.log(event)\n"); @@ -90,213 +120,17 @@ fn readme(ctx: &Ctx<'_>) -> String { out.push_str("console.log(result)\n"); } } - let _ = writeln!( - out, - "```\n\nThe package is ES modules and CommonJS both, with types for each, and has no dependency: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const {{ {client} }} = require('{package}')`; `import {client} from '{package}'` gives it too." - ); - auth(ctx, &mut out); - environments(ctx, &mut out); - let s = &ctx.config.settings; - let secs = |v: Option, d: f64| { - let v = v.unwrap_or(d); - if v.fract() == 0.0 { - format!("{v:.0}") - } else { - format!("{v}") - } - }; - let _ = writeln!( - out, - "\n## Errors\n\nA status that is not a success throws an `APIError` with its `status`, `headers` and `body`, of the class for its status: `BadRequestError` (400), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RequestTimeoutError` (408), `ConflictError` (409), `UnprocessableEntityError` (422), `RateLimitError` (429), `InternalServerError` (500 and above). No answer throws `APIConnectionError`; a timeout `APIConnectionTimeoutError`; a call aborted by its signal `APIUserAbortError`.\n\n```ts\nimport {{ APIError }} from '{package}'\n\ntry {{\n await client.{}\n}} catch (error) {{\n if (error instanceof APIError) console.log(error.status, error.body)\n else throw error\n}}\n```", - headline(ctx).map_or_else( - || String::from("request('GET', '/')"), - |c| format!("{}(/* … */)", c.access) - ) - ); - let _ = writeln!( - out, - "\n## Retries and timeouts\n\nA call that fails to connect, or is answered 408, 409, 429 or 5xx, is tried {} more times by default, waiting longer each time (never more than {} s when the server asks to wait); each attempt may take {} s, its body read. Give `maxRetries` and `timeout` (milliseconds) to the client, or to one call:\n\n```ts\nconst client = new {client}({{ maxRetries: 0, timeout: 20_000 }})\n```", - s.retries.unwrap_or(2), - secs(s.max_retry_delay, 60.0), - secs(s.timeout, 60.0), - ); - paging(ctx, &mut out); - let _ = writeln!( - out, - "\n## Requirements\n\nNode {} or later (CI runs {}), or any runtime with `fetch`. Built with TypeScript {}.\n\n## Development\n\n```sh\nnpm install\nscripts/check # lint, build, the built types, the tests against the mock server\n```\n\nThe code is generated from `flowapi-sdk.yml`: change that file and generate again ([AGENTS.md](AGENTS.md)).", - texts::NODES.first().copied().unwrap_or("20"), - texts::NODES.join(", "), - package::TYPESCRIPT - ); - out -} - -fn auth(ctx: &Ctx<'_>, out: &mut String) { - if ctx.config.auth.is_empty() { - return; - } - out.push_str("\n## Authentication\n\nEach credential is an option of the client, else read from its environment variable:\n\n| Scheme | Sent as | Option | Variable |\n| --- | --- | --- | --- |\n"); - for a in &ctx.config.auth { - let sent = ctx - .service - .schemes - .iter() - .find(|s| s.name == a.name) - .map_or_else(String::new, |s| match &s.auth { - Auth::ApiKey { location, name } => format!( - "an API key in the {} `{name}`", - match location { - KeyLocation::Header => "header", - KeyLocation::Query => "query parameter", - KeyLocation::Cookie => "cookie", - } - ), - Auth::Http { scheme, .. } if scheme == "basic" => { - String::from("HTTP basic (`{ username, password }`)") - } - Auth::Http { scheme, .. } => format!("HTTP `{scheme}`"), - Auth::OAuth2 { .. } => String::from("an OAuth 2.0 token"), - Auth::OpenIdConnect { .. } => String::from("an OpenID Connect token"), - Auth::MutualTls => String::from("a client certificate"), - }); - let var = ctx - .config - .settings - .auth_env - .iter() - .find(|(n, _)| *n == a.name) - .map_or_else(|| String::from("—"), |(_, v)| format!("`{v}`")); + out.push_str("```\n\nA method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone.\n"); + if let Some(call) = call { let _ = writeln!( out, - "| `{}` | {sent} | `{}` | {var} |", - a.name, - camel(&words::words(&a.name)) + "\n```ts\nconst {{ data, response, requestId }} = await client.{}({}).withResponse()\nconsole.log(response.status, requestId, data)\n```", + call.access, + input(ctx, call) ); } let _ = writeln!( out, - "\n```ts\nconst client = new {}({})\n```", - ctx.client(), - options(ctx, None) - ); -} - -fn environments(ctx: &Ctx<'_>, out: &mut String) { - let s = &ctx.config.settings; - if s.urls.is_empty() { - return; - } - out.push_str("\n## Environments\n\n| Environment | Base URL |\n| --- | --- |\n"); - for (name, url) in &s.urls { - let _ = writeln!(out, "| `{name}` | {url} |"); - } - let default = ctx - .config - .default_environment - .as_ref() - .map(|n| n.name.as_str()); - let first = s.urls.first().map(|(n, _)| n.as_str()); - let _ = write!( - out, - "\nThe client calls `{}` unless given `environment` or `baseURL`", - default.or(first).unwrap_or("") - ); - match &s.base_url_env { - Some(var) => { - let _ = writeln!(out, ", or `{var}` is set."); - } - None => out.push_str(".\n"), - } -} - -fn paging(ctx: &Ctx<'_>, out: &mut String) { - let c = ctx.config; - let named = |key: &str| { - c.readme - .iter() - .find(|(k, _)| *k == key) - .map(|(_, n)| n.name.clone()) - }; - let page = ctx - .calls - .iter() - .find(|k| named("pagination_method").is_some_and(|n| n == k.name)) - .or_else(|| ctx.calls.iter().find(|k| k.kind == Kind::Page)); - if let Some(call) = page { - let _ = writeln!( - out, - "\n## Pagination\n\nA list is read a page at a time; `for await` reads every item, asking for the next page as it needs one:\n\n```ts\nfor await (const item of client.{}()) console.log(item)\n\nconst page = await client.{}()\nconsole.log(page.items)\n```", - call.access, call.access - ); - } - if let Some(call) = ctx.calls.iter().find(|k| k.kind == Kind::Stream) { - let _ = writeln!( - out, - "\n## Streaming\n\nA streamed method gives its events as they come:\n\n```ts\nfor await (const event of await client.{}()) console.log(event)\n```", - call.access - ); - } -} - -fn api(ctx: &Ctx<'_>) -> String { - let c = ctx.config; - let mut out = format!( - "\n\n# API\n\n{} of `{}`.\n", - counted(ctx), - ctx.client() + "\nThe package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const {{ {client} }} = require('{package}')`; `import {client} from '{package}'` gives it too." ); - for (i, _) in c.resources.iter().enumerate() { - let calls: Vec<&Call> = ctx - .calls - .iter() - .filter(|k| c.methods.get(k.method).is_some_and(|m| m.resource == i)) - .collect(); - if calls.is_empty() { - continue; - } - let _ = writeln!(out, "\n## {}\n", c.path(i)); - for call in calls { - let Some(op) = ctx.ops.list.get(call.op) else { - continue; - }; - let o = &op.operation; - let optional = !o.params.iter().any(|p| p.required) - && !o.body.as_ref().is_some_and(|b| b.required); - let data = format!("Data", call.base); - let returns = match call.kind { - Kind::Call => format!("ApiCall<{data}>"), - Kind::Stream => String::from("ApiCall>"), - Kind::Page => { - let items = c - .methods - .get(call.method) - .and_then(|m| effective(c, m)) - .and_then(|n| find(c, &n.name)) - .and_then(|p| p.get("items")) - .unwrap_or(""); - let tuple: Vec = items - .split('.') - .filter(|m| !m.is_empty()) - .map(|m| format!("\"{m}\"")) - .collect(); - format!("PagePromise>", tuple.join(", ")) - } - }; - let summary = op - .summary - .as_deref() - .map(|s| format!(": {}", s.split_whitespace().collect::>().join(" "))) - .unwrap_or_default(); - let _ = writeln!( - out, - "- `client.{}(params{}: Input, options?: RequestOptions): {returns}` \n `{} {}`{summary}", - call.access, - if optional { "?" } else { "" }, - call.base, - op.method(), - o.path - ); - } - } - out } diff --git a/crates/flowapi-sdk/src/repo/readme/api.rs b/crates/flowapi-sdk/src/repo/readme/api.rs new file mode 100644 index 0000000..cfd7dd3 --- /dev/null +++ b/crates/flowapi-sdk/src/repo/readme/api.rs @@ -0,0 +1,87 @@ +//! `api.md`: every method by resource, each with its TypeScript signature (the types the package +//! exports, so a caller can write them), its operation's route and summary, and whether the +//! description marks it deprecated. `tests/texts.mjs` compiles each signature against the client. + +use super::super::{Call, Ctx, HEADER, Kind}; +use super::counted; +use super::sections::in_order; +use crate::client::resources::{access_of, sse_only}; +use crate::config::check::{effective, find}; +use crate::prose; +use std::fmt::Write as _; + +pub(super) fn api(ctx: &Ctx<'_>) -> String { + let c = ctx.config; + let mut out = format!( + "\n\n# API\n\nEvery method of `{}`, by resource: {}. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's:\n\n```ts\nimport type {{ ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream }} from '{}'\n```\n", + ctx.client(), + counted(ctx), + ctx.package() + ); + for i in in_order(ctx) { + let calls: Vec<&Call> = ctx + .calls + .iter() + .filter(|k| c.methods.get(k.method).is_some_and(|m| m.resource == i)) + .collect(); + if calls.is_empty() { + continue; + } + let _ = writeln!(out, "\n## client.{}\n", access_of(c, i)); + for call in calls { + method(ctx, call, &mut out); + } + } + out +} + +/// One method's line: its signature, then its route and what its operation says of itself. +fn method(ctx: &Ctx<'_>, call: &Call, out: &mut String) { + let c = ctx.config; + let Some(op) = ctx.ops.list.get(call.op) else { + return; + }; + let o = &op.operation; + let optional = + !o.params.iter().any(|p| p.required) && !o.body.as_ref().is_some_and(|b| b.required); + let data = format!("Data", call.base); + let returns = match call.kind { + Kind::Call => format!("ApiCall<{data}>"), + Kind::Stream if sse_only(o) => String::from("ApiCall>"), + Kind::Stream => String::from("ApiCall>"), + Kind::Page => { + let items = c + .methods + .get(call.method) + .and_then(|m| effective(c, m)) + .and_then(|n| find(c, &n.name)) + .and_then(|p| p.get("items")) + .unwrap_or(""); + let tuple: Vec = items + .split('.') + .filter(|m| !m.is_empty()) + .map(|m| format!("\"{m}\"")) + .collect(); + format!("PagePromise>", tuple.join(", ")) + } + }; + let about = op + .summary + .as_deref() + .map(prose::inline) + .filter(|s| !s.is_empty()) + .or_else(|| op.description.as_deref().and_then(prose::sentence)); + let mut said = about.map(|s| format!(": {s}")).unwrap_or_default(); + if op.deprecated { + said.push_str(" (deprecated)"); + } + let _ = writeln!( + out, + "- `client.{}(params{}: Input, options?: RequestOptions): {returns}` \n `{} {}`{said}", + call.access, + if optional { "?" } else { "" }, + call.base, + op.method(), + o.path + ); +} diff --git a/crates/flowapi-sdk/src/repo/readme/auth.rs b/crates/flowapi-sdk/src/repo/readme/auth.rs new file mode 100644 index 0000000..4ae2f04 --- /dev/null +++ b/crates/flowapi-sdk/src/repo/readme/auth.rs @@ -0,0 +1,157 @@ +//! The README's authentication: for each scheme of `auth`, its kind, where it goes, the option +//! it is given by and the environment variables it is read from, with their exact format; for +//! OAuth 2.0's client credentials the token URL and the scopes; then how the client chooses among +//! an operation's alternatives, and that credentials go only over TLS. A test holds that every +//! scheme of `auth` is in it. + +use crate::client::camel; +use crate::config::auth::{CHALLENGED, has_token_flow, is_basic}; +use crate::config::model::Credential; +use crate::model::{Auth, KeyLocation, Scheme}; +use crate::repo::Ctx; +use crate::repo::suite::options; +use crate::words; +use std::fmt::Write as _; + +const HOW: &str = "An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them."; + +/// A scheme's kind, where it goes, what its option takes and its variables' format. +fn row(a: &Credential, s: &Scheme) -> [String; 4] { + let var = |member: &str| a.var(member).map(|v| format!("`{v}`")); + let one = |what: &str| var("env_var").map(|v| format!("{v}: {what}")); + let (kind, sent, option, vars) = match &s.auth { + Auth::ApiKey { location, name } => { + let place = match location { + KeyLocation::Header => "the header", + KeyLocation::Query => "the query parameter", + KeyLocation::Cookie => "the cookie", + }; + ( + String::from("API key"), + format!("{place} `{name}`"), + String::from("the key"), + one("the key"), + ) + } + auth if is_basic(auth) => { + let pair = var("username_env_var") + .zip(var("password_env_var")) + .map(|(u, p)| format!("{u}: the user-id; {p}: the password")); + let vars = [one("`username:password`"), pair].into_iter().flatten(); + ( + String::from("HTTP basic"), + String::from("`Authorization: Basic `"), + String::from("`{ username, password }` (a user-id without `:`)"), + Some(vars.collect::>().join("; ")).filter(|v| !v.is_empty()), + ) + } + Auth::Http { scheme, .. } if scheme == "bearer" => ( + String::from("HTTP bearer"), + String::from("`Authorization: Bearer `"), + String::from("the token"), + one("the token"), + ), + Auth::Http { scheme, .. } if CHALLENGED.contains(&scheme.as_str()) => ( + format!("HTTP `{scheme}`"), + String::from( + "not sent: it answers a challenge; give `Authorization` in a call's `headers`", + ), + String::from("—"), + None, + ), + Auth::Http { scheme, .. } => ( + format!("HTTP `{scheme}`"), + format!("`Authorization: {scheme} `"), + String::from("the credential"), + one("the credential"), + ), + Auth::OAuth2 { + client_credentials: Some(flow), + .. + } => { + let scopes = a.scopes.as_ref().map_or_else( + || String::from("the scopes the operation needs"), + |(s, _)| words_of(s, "no scope"), + ); + let pair = var("client_id_env_var") + .zip(var("client_secret_env_var")) + .map(|(i, s)| format!("{i}: the client's id; {s}: its secret")); + let vars = [one("a token"), pair].into_iter().flatten(); + ( + String::from("OAuth 2.0 client credentials"), + format!( + "`Authorization: Bearer `, the token requested at `{}` for {scopes}", + flow.token_url + ), + String::from("a token, or `{ clientId, clientSecret }` to request one"), + Some(vars.collect::>().join("; ")).filter(|v| !v.is_empty()), + ) + } + Auth::OAuth2 { .. } | Auth::OpenIdConnect { .. } => ( + String::from(if matches!(s.auth, Auth::OAuth2 { .. }) { + "OAuth 2.0" + } else { + "OpenID Connect" + }), + String::from("`Authorization: Bearer `, a token you obtain"), + String::from("the token, or a function that gives it"), + one("the token"), + ), + Auth::MutualTls => ( + String::from("mutual TLS"), + String::from("a client certificate, which your `fetch` presents"), + String::from("`true`"), + None, + ), + }; + let deprecated = if s.deprecated { " (deprecated)" } else { "" }; + [ + format!("{kind}{deprecated}"), + sent, + option, + vars.unwrap_or_else(|| String::from("—")), + ] +} + +/// Scopes as words: `` `a`, `b` ``. +fn words_of(scopes: &[String], none: &str) -> String { + if scopes.is_empty() { + return String::from(none); + } + let list: Vec = scopes.iter().map(|s| format!("`{s}`")).collect(); + format!("the scopes {}", list.join(", ")) +} + +pub(crate) fn section(ctx: &Ctx<'_>, out: &mut String) { + if ctx.config.auth.is_empty() { + return; + } + let _ = writeln!( + out, + "\n## Authentication\n\n| Scheme | Kind | Sent as | Option | Environment variables |\n| --- | --- | --- | --- | --- |" + ); + let mut flow = false; + for a in &ctx.config.auth { + let Some(s) = ctx.service.schemes.iter().find(|s| s.name == a.name.name) else { + continue; + }; + flow |= has_token_flow(&s.auth); + let [kind, sent, option, vars] = row(a, s); + let _ = writeln!( + out, + "| `{}` | {kind} | {sent} | `{}`: {option} | {vars} |", + a.name.name, + camel(&words::words(&a.name.name)) + ); + } + let _ = writeln!(out, "\n{HOW}"); + if flow { + out.push_str("\nA token of OAuth 2.0's client credentials grant is requested at the token URL (relative to the base URL where it is relative) with the client's id and secret in HTTP basic, cached until a little before it expires, shared by the calls that wait for it, and requested again once when the API answers 401. A refusal of the token endpoint throws `TokenError` with its `error` and `description`.\n"); + } + let _ = writeln!( + out, + "\n```ts\nconst client = new {}({})\n```", + ctx.client(), + options(ctx, None) + ); +} diff --git a/crates/flowapi-sdk/src/repo/readme/sections.rs b/crates/flowapi-sdk/src/repo/readme/sections.rs new file mode 100644 index 0000000..e04b4b4 --- /dev/null +++ b/crates/flowapi-sdk/src/repo/readme/sections.rs @@ -0,0 +1,259 @@ +//! The README's sections after its usage: the resources, the environments, errors, retries and +//! timeouts, pagination, streaming, logging, a request no operation describes, and how the +//! package is built. Each example calls a method the client has with the input its operation +//! requires, so that `tests/texts.mjs` can compile it; a section is there only when the API has +//! what it is about. + +use super::super::{Call, Ctx, Kind, package, texts}; +use super::input; +use crate::client::entry::log_env; +use crate::client::resources::access_of; +use std::fmt::Write as _; + +/// Every resource with a method, as a table of `client.` and its count, each linked to +/// its section of `api.md`. +pub(super) fn resources(ctx: &Ctx<'_>, out: &mut String) { + let c = ctx.config; + let mut rows = Vec::new(); + for i in in_order(ctx) { + let n = ctx + .calls + .iter() + .filter(|k| c.methods.get(k.method).is_some_and(|m| m.resource == i)) + .count(); + if n > 0 { + let access = format!("client.{}", access_of(c, i)); + rows.push(format!( + "| [`{access}`](api.md#{}) | {n} |", + anchor(&access) + )); + } + } + if rows.is_empty() { + return; + } + let _ = writeln!( + out, + "\n## Resources\n\n| Resource | Methods |\n| --- | --- |\n{}", + rows.join("\n") + ); +} + +/// The resources in the order of their paths (`pets`, `pets.photos`, `users`), as the README and +/// `api.md` list them. +pub(super) fn in_order(ctx: &Ctx<'_>) -> Vec { + let c = ctx.config; + let mut order: Vec<(String, usize)> = (0..c.resources.len()) + .map(|i| (access_of(c, i), i)) + .collect(); + order.sort(); + order.into_iter().map(|(_, i)| i).collect() +} + +/// The anchor GitHub gives a heading: lower case, spaces as `-`, other punctuation left out. +pub(super) fn anchor(heading: &str) -> String { + heading + .chars() + .filter_map(|c| match c { + ' ' => Some('-'), + c if c.is_alphanumeric() || c == '-' || c == '_' => Some(c.to_ascii_lowercase()), + _ => None, + }) + .collect() +} + +pub(super) fn environments(ctx: &Ctx<'_>, out: &mut String) { + let s = &ctx.config.settings; + if s.urls.is_empty() { + return; + } + out.push_str("\n## Environments\n\n| Environment | Base URL |\n| --- | --- |\n"); + for (name, url) in &s.urls { + let _ = writeln!(out, "| `{name}` | {url} |"); + } + let default = ctx + .config + .default_environment + .as_ref() + .map(|n| n.name.as_str()); + let first = s.urls.first().map(|(n, _)| n.as_str()); + let chosen = default.or(first).unwrap_or(""); + let _ = write!( + out, + "\nThe client calls `{chosen}` unless it is given `environment` or `baseURL`" + ); + match &s.base_url_env { + Some(var) => { + let _ = writeln!(out, ", or `{var}` is set."); + } + None => out.push_str(".\n"), + } + if let Some((other, _)) = s.urls.iter().find(|(n, _)| n != chosen) { + let _ = writeln!( + out, + "\n```ts\nconst {} = new {}({{ environment: '{other}' }})\n```", + camel_word(other), + ctx.client() + ); + } +} + +/// An environment's name as a variable (`sandbox`, `eu_west` is `euWest`). +fn camel_word(name: &str) -> String { + crate::client::camel(&crate::words::words(name)) +} + +/// The error classes by status, as `errors.ts` throws them. +const STATUSES: &[(&str, &str)] = &[ + ("400", "BadRequestError"), + ("401", "AuthenticationError"), + ("403", "PermissionDeniedError"), + ("404", "NotFoundError"), + ("408", "RequestTimeoutError"), + ("409", "ConflictError"), + ("422", "UnprocessableEntityError"), + ("429", "RateLimitError"), + ("500 and above", "InternalServerError"), +]; + +pub(super) fn errors(ctx: &Ctx<'_>, headline: Option<&Call>, out: &mut String) { + out.push_str("\n## Errors\n\nA response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself):\n\n| Status | Class |\n| --- | --- |\n"); + for (status, class) in STATUSES { + let _ = writeln!(out, "| {status} | `{class}` |"); + } + out.push_str("\nA request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent.\n"); + if let Some(call) = headline { + let _ = writeln!( + out, + "\n```ts\nimport {{ APIError }} from '{}'\n\ntry {{\n await client.{}({})\n}} catch (error) {{\n if (error instanceof APIError) console.log(error.status, error.body)\n else throw error\n}}\n```", + ctx.package(), + call.access, + input(ctx, call) + ); + } +} + +/// Seconds as the README writes them: `60`, `0.5`. +fn secs(v: Option, default: f64) -> String { + let v = v.unwrap_or(default); + if v.fract() == 0.0 { + format!("{v:.0}") + } else { + format!("{v}") + } +} + +pub(super) fn retries(ctx: &Ctx<'_>, headline: Option<&Call>, out: &mut String) { + let s = &ctx.config.settings; + // With no retry by default, the rules of when a request is retried are said for a caller who + // sets `maxRetries`, so that no sentence claims a retry the client does not make. + let n = s.retries.unwrap_or(1); + let (lead, tries) = match n { + 0 => ( + "No request is retried by default (`maxRetries: 0`): each is sent once. With `maxRetries` set, a", + String::from("is retried"), + ), + 1 => ("A", String::from("is retried once by default")), + n => ("A", format!("is retried {n} times by default")), + }; + let again = match n { + 0 => "A retry that failed is tried again while `maxRetries` allows.", + 1 => "A retry that failed is not tried again: more retries are the caller's choice.", + _ => "This SDK's config retries more than once, so a retry that failed is tried again.", + }; + let others = match &s.idempotency_key { + Some(h) => format!( + "A call of any other method (POST, PATCH) sends a random `{h}` header, the same on each of its attempts, so that the server applies it once: it is retried like the others." + ), + None => String::from( + "A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks.", + ), + }; + let _ = writeln!( + out, + "\n## Retries and timeouts\n\n{lead} request that cannot connect, or is answered 408, 409, 429 or 5xx, {tries} when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. {others} The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. {again} Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than {} s, the error is thrown at once. Each attempt may take {} s, its body read.\n\n`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options:\n\n```ts\nconst patient = new {}({{ maxRetries: 5, timeout: 120_000 }})", + secs(s.max_retry_delay, 60.0), + secs(s.timeout, 60.0), + ctx.client() + ); + if let Some(call) = headline { + let arg = input(ctx, call); + let arg = if arg.is_empty() { + String::from("{}") + } else { + arg + }; + let _ = writeln!( + out, + "await client.{}({arg}, {{ maxRetries: 0, timeout: 5_000 }})", + call.access + ); + } + out.push_str("```\n"); +} + +pub(super) fn paging(ctx: &Ctx<'_>, out: &mut String) { + let c = ctx.config; + let named = c + .readme + .iter() + .find(|(k, _)| *k == "pagination_method") + .map(|(_, n)| n.name.clone()); + let page = ctx + .calls + .iter() + .find(|k| k.kind == Kind::Page && named.as_ref().is_some_and(|n| *n == k.name)) + .or_else(|| ctx.calls.iter().find(|k| k.kind == Kind::Page)); + if let Some(call) = page { + let arg = input(ctx, call); + let _ = writeln!( + out, + "\n## Pagination\n\nA list method is read a page at a time. `for await` over it reads every item, asking for the next page when it needs one; awaited, it gives the first page, with its `items`, `hasNextPage()` and `getNextPage()`. A list stops at 10,000 pages unless `maxPages` says otherwise.\n\n```ts\nfor await (const item of client.{0}({arg})) console.log(item)\n\nconst page = await client.{0}({arg})\nconsole.log(page.items, page.hasNextPage())\n```", + call.access + ); + } + if let Some(call) = ctx.calls.iter().find(|k| k.kind == Kind::Stream) { + let _ = writeln!( + out, + "\n## Streaming\n\nA streamed method gives its events as they come, read once; `abort()` stops the stream and closes its connection.\n\n```ts\nconst stream = await client.{}({})\nfor await (const event of stream) console.log(event)\n```", + call.access, + input(ctx, call) + ); + } +} + +pub(super) fn logging(ctx: &Ctx<'_>, out: &mut String) { + let client = ctx.client(); + let _ = writeln!( + out, + "\n## Logging\n\nThe client logs to `console` at `warn` and above. Set `{}` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere.\n\n```ts\nconst verbose = new {client}({{ logLevel: 'debug', logger: console }})\n```", + log_env(&client) + ); +} + +pub(super) fn requests(out: &mut String) { + let _ = writeln!( + out, + "\n## Requests no method makes\n\n`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`:\n\n```ts\nconst response = await client.request('GET', '/').asResponse()\nconsole.log(response.status)\n```" + ); +} + +pub(super) fn closing(out: &mut String) { + let nodes = texts::NODES; + let _ = writeln!( + out, + "\n## Requirements\n\nNode {} or later (CI runs {}), or another runtime with `fetch`. Built with TypeScript {}.\n\n## Development\n\n```sh\nnpm install\nscripts/check # lint, build, the built types, the tests against the mock server\n```\n\nThe code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says.", + nodes.first().copied().unwrap_or("20"), + join_and(nodes), + package::TYPESCRIPT, + ); +} + +/// `20, 22 and 24`. +fn join_and(items: &[&str]) -> String { + match items.split_last() { + Some((last, [])) => (*last).to_owned(), + Some((last, rest)) => format!("{} and {last}", rest.join(", ")), + None => String::new(), + } +} diff --git a/crates/flowapi-sdk/src/repo/readme/servers.rs b/crates/flowapi-sdk/src/repo/readme/servers.rs new file mode 100644 index 0000000..d332d30 --- /dev/null +++ b/crates/flowapi-sdk/src/repo/readme/servers.rs @@ -0,0 +1,78 @@ +//! The README's section on servers: the variables of the description's servers and the +//! operations' own, with a default and the values each takes, and how a client reaches a server +//! whose URL is relative to where the description is served (`descriptionURL`). Its examples are +//! compiled against the client by `tests/texts.mjs`. + +use super::super::Ctx; +use std::fmt::Write as _; + +/// The servers' variables, when they have any, and how to reach a server relative to where the +/// description is served, when one is. +pub(super) fn servers(ctx: &Ctx<'_>, out: &mut String) { + let variables = crate::client::entry::server_variables(ctx.service); + let service = ctx.service; + let all = || { + service + .servers + .iter() + .chain(service.operations.iter().flat_map(|a| a.servers.iter())) + }; + let relative = all().find(|s| !s.url.contains(':') && !s.url.starts_with('{')); + if variables.is_empty() && relative.is_none() { + return; + } + out.push_str("\n## Servers\n"); + if !variables.is_empty() { + out.push_str("\nThe servers' URLs have variables. The client sends each one's default unless `serverVariables` gives another value:\n\n| Variable | Default | Values |\n| --- | --- | --- |\n"); + for (name, default, values) in &variables { + let values = if values.is_empty() { + String::from("any") + } else { + values + .iter() + .map(|v| format!("`{v}`")) + .collect::>() + .join(", ") + }; + let _ = writeln!(out, "| `{name}` | `{default}` | {values} |"); + } + let example = variables + .iter() + .find_map(|(n, d, vs)| vs.iter().find(|v| *v != d).map(|v| (n, v))) + .or_else(|| variables.first().map(|(n, d, _)| (n, d))); + if let Some((name, value)) = example { + let _ = writeln!( + out, + "\n```ts\nconst other = new {}({{ serverVariables: {{ {}: '{value}' }} }})\n```", + ctx.client(), + js_key(name) + ); + } + if variables.iter().any(|(.., vs)| !vs.is_empty()) { + out.push_str( + "\nA value that is not one of a variable's values throws a `RangeError`.\n", + ); + } + } + if let Some(s) = relative { + let _ = writeln!( + out, + "\nA server URL may be relative to where the description is served (`{}`): give that address as `descriptionURL` to call it.\n\n```ts\nconst near = new {}({{ descriptionURL: 'https://api.example.com/openapi.json' }})\n```", + s.url, + ctx.client() + ); + } +} + +/// A member's name as a JavaScript object key: as it is when it is an identifier, else quoted. +fn js_key(name: &str) -> String { + let ident = name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_' || c == '$') + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + if ident { + name.to_owned() + } else { + format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'")) + } +} diff --git a/crates/flowapi-sdk/src/repo/suite.rs b/crates/flowapi-sdk/src/repo/suite.rs index 3bbb7a7..67366cc 100644 --- a/crates/flowapi-sdk/src/repo/suite.rs +++ b/crates/flowapi-sdk/src/repo/suite.rs @@ -4,12 +4,16 @@ //! calls every method of its resource with the parameters and body its operation requires, //! each value an example of its schema; a page is read once, a stream to its end. A call the //! mock refuses (a wrong path, method, missing parameter or media type) fails its test with the -//! mock's reason, and the route the mock matched is the operation's. +//! mock's reason, and the route the mock matched is the operation's. `tests/auth.test.mjs` +//! (`suite/auth.rs`) holds what the mock received of each kind of credential. + +mod auth; use super::example::{self, Value}; -use super::sample; use super::{Call, Ctx, HEADER, Kind, RepoFile, generated_file}; +use super::{mock, sample}; use crate::client::{camel, resources}; +use crate::config::auth::{CHALLENGED, is_basic}; use crate::model::Auth; use crate::out::json_str; use crate::words; @@ -34,6 +38,7 @@ pub(crate) fn files(ctx: &Ctx<'_>) -> Vec { let path = format!("tests/api-resources/{rel}.test.mjs"); out.push(generated_file(&path, file(ctx, &c.path(i), &up, &calls))); } + out.extend(auth::file(ctx)); out } @@ -68,7 +73,11 @@ fn file(ctx: &Ctx<'_>, resource: &str, up: &str, calls: &[&Call]) -> String { "\ntest({}, async () => {{", json_str(&format!("{}: {route}", call.name)) ); - let expr = format!("client.{}({args})", call.access); + let expr = match auth::call_options(ctx, call) { + Some(o) if args.is_empty() => format!("client.{}({{}}, {o})", call.access), + Some(o) => format!("client.{}({args}, {o})", call.access), + None => format!("client.{}({args})", call.access), + }; match call.kind { Kind::Stream => { let _ = writeln!( @@ -90,40 +99,70 @@ fn file(ctx: &Ctx<'_>, resource: &str, up: &str, calls: &[&Call]) -> String { } /// The client's options: for a test (`base_url` given), that base URL, a made-up credential for -/// each scheme the config sends (a username and password for HTTP basic) and no retries; for the -/// README, the credentials alone, each `'…'`. +/// each scheme the config sends (a username and password for HTTP basic, a client's id and +/// secret for the client credentials flow, its token endpoint the mock's) and no retries; for the +/// README, the credentials alone, each `'…'`. A scheme the client cannot send has no option. pub(crate) fn options(ctx: &Ctx<'_>, base_url: Option<&str>) -> String { let mut fields: Vec = base_url .map(|b| format!("baseURL: {b}")) .into_iter() .collect(); - let (key, user, pass) = match base_url { - Some(_) => ("'test-credential'", "'user'", "'pass'"), - None => ("'…'", "'…'", "'…'"), + let test = base_url.is_some(); + let quote = |v: &str| { + if test { + format!("'{v}'") + } else { + String::from("'…'") + } }; for a in &ctx.config.auth { - let option = camel(&words::words(&a.name)); - let basic = ctx.service.schemes.iter().any(|s| { - s.name == a.name && matches!(&s.auth, Auth::Http { scheme, .. } if scheme == "basic") - }); - let value = if basic { - format!("{{ username: {user}, password: {pass} }}") - } else { - key.to_owned() + let Some(scheme) = ctx.service.schemes.iter().find(|s| s.name == a.name.name) else { + continue; }; - let name = if option.starts_with(|c: char| c.is_ascii_alphabetic()) { - option - } else { - json_str(&option) + let value = match &scheme.auth { + auth if is_basic(auth) => format!( + "{{ username: {}, password: {} }}", + quote(auth::USERNAME), + quote(auth::PASSWORD) + ), + Auth::OAuth2 { + client_credentials: Some(f), + .. + } => { + let url = base_url + .map(|b| format!(", tokenURL: `${{{b}}}{}`", mock::token_path(&f.token_url))) + .unwrap_or_default(); + format!( + "{{ clientId: {}, clientSecret: {}{url} }}", + quote(auth::CLIENT_ID), + quote(auth::CLIENT_SECRET) + ) + } + Auth::Http { scheme, .. } if CHALLENGED.contains(&scheme.as_str()) => continue, + Auth::MutualTls => String::from("true"), + Auth::ApiKey { .. } + | Auth::Http { .. } + | Auth::OAuth2 { .. } + | Auth::OpenIdConnect { .. } => quote(auth::CREDENTIAL), }; - fields.push(format!("{name}: {value}")); + fields.push(format!("{}: {value}", option_key(&a.name.name))); } - if base_url.is_some() { + if test { fields.push(String::from("maxRetries: 0")); } format!("{{ {} }}", fields.join(", ")) } +/// A credential's option as a key of an object literal. +pub(crate) fn option_key(scheme: &str) -> String { + let option = camel(&words::words(scheme)); + if option.starts_with(|c: char| c.is_ascii_alphabetic()) { + option + } else { + json_str(&option) + } +} + /// A method's argument: the parameters its operation requires, by where they go, and its body /// when one is required (JSON first, else the first media type); `None` when it needs nothing. /// For the README (`readme`) a parameter's value is one for a person to read (`sample.rs`). diff --git a/crates/flowapi-sdk/src/repo/suite/auth.rs b/crates/flowapi-sdk/src/repo/suite/auth.rs new file mode 100644 index 0000000..6dd5f7e --- /dev/null +++ b/crates/flowapi-sdk/src/repo/suite/auth.rs @@ -0,0 +1,237 @@ +//! `tests/auth.test.mjs`: for each kind of credential the config sends, a method whose +//! operation the tests' client meets by it, called against the mock, and what the mock received +//! asserted (the header, the query parameter or the cookie, HTTP basic's pair, the bearer token, +//! the token the mock gave for the client credentials flow); and an operation with no security +//! called by a client that holds no credential, which sends none. Every credential is made up +//! and the same on every run. + +use super::super::{Call, Ctx, HEADER, Kind, RepoFile, generated_file}; +use super::{args, option_key}; +use crate::config::auth::{CHALLENGED, has_token_flow, is_basic, needed}; +use crate::model::{Auth, KeyLocation, Requirement, Scheme}; +use crate::out::json_str; +use std::fmt::Write as _; + +/// The made-up credentials of the tests' client. +pub(crate) const CREDENTIAL: &str = "test-credential"; +pub(crate) const USERNAME: &str = "user"; +pub(crate) const PASSWORD: &str = "pass"; +pub(crate) const CLIENT_ID: &str = "test-client"; +pub(crate) const CLIENT_SECRET: &str = "test-secret"; +/// The token the mock gives for a client credentials grant (`files/server.mjs`). +const MOCK_TOKEN: &str = "mock-token"; + +/// The scheme of a name the config sends, when the client can send it. +fn sendable<'s>(ctx: &'s Ctx<'_>, name: &str) -> Option<&'s Scheme> { + ctx.config.auth.iter().find(|a| a.name.name == name)?; + let s = ctx.service.schemes.iter().find(|s| s.name == name)?; + match &s.auth { + Auth::Http { scheme, .. } if CHALLENGED.contains(&scheme.as_str()) => None, + Auth::ApiKey { .. } + | Auth::Http { .. } + | Auth::OAuth2 { .. } + | Auth::OpenIdConnect { .. } + | Auth::MutualTls => Some(s), + } +} + +/// Whether a scheme's credential goes in `Authorization`. +fn authorization(auth: &Auth) -> bool { + !matches!(auth, Auth::ApiKey { .. } | Auth::MutualTls) +} + +/// The alternative the tests' client sends: the first it holds every credential of. +fn chosen<'r>(ctx: &Ctx<'_>, security: &'r [Requirement]) -> Option<&'r Requirement> { + security + .iter() + .find(|r| r.schemes.iter().all(|(n, _)| sendable(ctx, n).is_some())) +} + +/// What the mock must have received of a scheme, as assertions on `r`. +fn expected(s: &Scheme) -> Option { + let line = match &s.auth { + Auth::ApiKey { location, name } => match location { + KeyLocation::Header => format!( + "assert.equal(r.headers[{}], '{CREDENTIAL}')", + json_str(&name.to_ascii_lowercase()) + ), + KeyLocation::Query => format!( + "assert.equal(new URL(r.url, 'http://mock.invalid').searchParams.get({}), '{CREDENTIAL}')", + json_str(name) + ), + KeyLocation::Cookie => format!( + "assert.ok((r.headers.cookie ?? '').split('; ').includes({}), r.headers.cookie)", + json_str(&format!("{name}={CREDENTIAL}")) + ), + }, + auth if is_basic(auth) => format!( + "assert.equal(r.headers.authorization, `Basic ${{Buffer.from('{USERNAME}:{PASSWORD}').toString('base64')}}`)" + ), + auth if has_token_flow(auth) => format!( + "assert.equal(r.headers.authorization, 'Bearer {MOCK_TOKEN}')\n assert.ok(server.requests.some((q) => q.route === 'token'), 'the token was requested of the mock')" + ), + Auth::Http { scheme, .. } if scheme != "bearer" => { + format!("assert.equal(r.headers.authorization, '{scheme} {CREDENTIAL}')") + } + Auth::MutualTls => return None, + Auth::Http { .. } | Auth::OAuth2 { .. } | Auth::OpenIdConnect { .. } => { + format!("assert.equal(r.headers.authorization, 'Bearer {CREDENTIAL}')") + } + }; + Some(line) +} + +/// A call of a method, as a statement that runs it to its end. +fn statement(ctx: &Ctx<'_>, client: &str, call: &Call) -> String { + let args = ctx + .ops + .list + .get(call.op) + .and_then(|op| args(ctx, &op.operation, false)) + .map(|v| v.js()) + .unwrap_or_default(); + let expr = format!("{client}.{}({args})", call.access); + match call.kind { + Kind::Stream => { + format!("for await (const event of await {expr}) assert.notEqual(event, undefined)") + } + Kind::Page | Kind::Call => format!("await {expr}"), + } +} + +/// Each method's security, as the client sends it. +fn security(ctx: &Ctx<'_>, call: &Call) -> Vec { + ctx.ops.list.get(call.op).map_or_else(Vec::new, |op| { + needed(ctx.config, ctx.ops, ctx.config.methods.get(call.method), op) + }) +} + +pub(crate) fn file(ctx: &Ctx<'_>) -> Option { + let mut tests = String::new(); + for a in &ctx.config.auth { + let Some(s) = sendable(ctx, &a.name.name) else { + continue; + }; + let Some(check) = expected(s) else { continue }; + let found = ctx.calls.iter().find(|call| { + let security = security(ctx, call); + chosen(ctx, &security).is_some_and(|r| { + r.schemes.iter().any(|(n, _)| *n == s.name) + && !(authorization(&s.auth) + && r.schemes.iter().any(|(n, _)| { + *n != s.name && sendable(ctx, n).is_some_and(|o| authorization(&o.auth)) + })) + }) + }); + let Some(call) = found else { continue }; + let _ = write!( + tests, + "\ntest({}, async () => {{\n {}\n const r = last()\n if (r === null) return\n {check}\n}})\n", + json_str(&format!("{}: sent by {}", s.name, call.name)), + statement(ctx, "client", call) + ); + } + let open = ctx.calls.iter().find(|call| security(ctx, call).is_empty()); + if let Some(call) = open { + let nulls: Vec = ctx + .config + .auth + .iter() + .map(|a| format!(", {}: null", option_key(&a.name.name))) + .collect(); + let _ = write!( + tests, + "\ntest({}, async () => {{\n const none = new {}({{ baseURL: server.url, maxRetries: 0{} }})\n {}\n const r = last()\n if (r === null) return\n assert.equal(r.headers.authorization, undefined)\n{}}})\n", + json_str(&format!("no credential: {} needs none", call.name)), + ctx.client(), + nulls.concat(), + statement(ctx, "none", call), + absent(ctx) + ); + } + if tests.is_empty() { + return None; + } + let client = ctx.client(); + let mut out = format!( + "// {HEADER}\n//\n// What the mock received of each kind of credential the client sends, and a call that needs none.\n\n" + ); + out.push_str("import assert from 'node:assert/strict'\nimport { after, before, test } from 'node:test'\n"); + let _ = writeln!( + out, + "import {{ {client} }} from {}", + json_str(ctx.package()) + ); + out.push_str("import { mock } from '../mock/server.mjs'\n\nlet server\nlet client\n\nbefore(async () => {\n server = await mock()\n"); + let _ = writeln!( + out, + " client = new {client}({})\n}})\n\nafter(() => server.close())\n\n/** The request the mock answered last; `null` against a server of your own. */\nconst last = () => server.requests?.at(-1) ?? null", + super::options(ctx, Some("server.url")) + ); + out.push_str(&tests); + Some(generated_file("tests/auth.test.mjs", out)) +} + +/// The assertions that a request carries no API key of the config's schemes. +fn absent(ctx: &Ctx<'_>) -> String { + let mut out = String::new(); + for a in &ctx.config.auth { + let Some(Auth::ApiKey { location, name }) = ctx + .service + .schemes + .iter() + .find(|s| s.name == a.name.name) + .map(|s| &s.auth) + else { + continue; + }; + let line = match location { + KeyLocation::Header => format!( + "assert.equal(r.headers[{}], undefined)", + json_str(&name.to_ascii_lowercase()) + ), + KeyLocation::Query => format!( + "assert.equal(new URL(r.url, 'http://mock.invalid').searchParams.has({}), false)", + json_str(name) + ), + KeyLocation::Cookie => format!( + "assert.ok(!(r.headers.cookie ?? '').split('; ').some((c) => c.startsWith({})))", + json_str(&format!("{name}=")) + ), + }; + let _ = writeln!(out, " {line}"); + } + out +} + +/// The options a call needs when the client's own credentials meet none of its security's +/// alternatives but one whose other schemes answer a challenge: their `Authorization`, given in +/// the call's `headers` as the client's `CredentialError` says to. +pub(crate) fn call_options(ctx: &Ctx<'_>, call: &Call) -> Option { + let security = security(ctx, call); + if security.is_empty() || chosen(ctx, &security).is_some() { + return None; + } + security.iter().find_map(|r| { + let mut challenged = None; + for (n, _) in &r.schemes { + if sendable(ctx, n).is_some() { + continue; + } + match ctx + .service + .schemes + .iter() + .find(|s| s.name == *n) + .map(|s| &s.auth) + { + Some(Auth::Http { scheme, .. }) if CHALLENGED.contains(&scheme.as_str()) => { + challenged = Some(scheme.clone()); + } + Some(_) | None => return None, + } + } + challenged + .map(|scheme| format!("{{ headers: {{ Authorization: '{scheme} {CREDENTIAL}' }} }}")) + }) +} diff --git a/crates/flowapi-sdk/src/repo/texts.rs b/crates/flowapi-sdk/src/repo/texts.rs index 14a8903..2780eb9 100644 --- a/crates/flowapi-sdk/src/repo/texts.rs +++ b/crates/flowapi-sdk/src/repo/texts.rs @@ -51,7 +51,13 @@ pub(crate) fn files(ctx: &Ctx<'_>, first: bool) -> Vec { out.push(generated_file("examples/.keep", String::new())); out.push(generated_file("AGENTS.md", agents())); if first { - out.push(seed("CHANGELOG.md", String::from("# Changelog\n"))); + out.push(seed( + "CHANGELOG.md", + format!( + "# Changelog\n\nEach release of `{}`, newest first. release-please writes an entry from the commits since the release before it.\n", + ctx.package() + ), + )); out.push(seed( ".release-please-manifest.json", format!("{{\n \".\": {}\n}}\n", json_str(ctx.version())), @@ -82,13 +88,29 @@ fn agents() -> String { "\n\n# AGENTS.md\n\n\ This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API \ description its `spec` names.\n\n\ +## Where things are\n\n\ +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a \ +method per operation; `src/api.ts`: the types and each operation's request and response; \ +`src/core/`: the runtime (sending, retries, errors, pagination, streams).\n\ +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource.\n\ +- `README.md` and `api.md`: the package's documentation, every method in `api.md`.\n\n\ ## What is generated\n\n\ Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. \ Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again:\n\n\ -```sh\nnpx -y @localix-ai/flowapi@{version} generate flowapi-sdk.yml --out .\n```\n\n\ -`flowapi config check flowapi-sdk.yml` says what is wrong with the config, every issue at once. \ +```sh\nnpx -y @localix-ai/flowapi@{version} config check flowapi-sdk.yml # every issue at once\n\ +npx -y @localix-ai/flowapi@{version} generate flowapi-sdk.yml --out .\n```\n\n\ A generated file changed by hand is a conflict: generate names it, stops and writes nothing. \ A file generated before and no longer generated is deleted, unless it was changed.\n\n\ +## Changing the SDK\n\n\ +| To change | Edit in `flowapi-sdk.yml` |\n| --- | --- |\n\ +| A method's name, or which resource it is in | `resources..methods` |\n\ +| An operation left out, with why | `skip` |\n\ +| The base URLs | `environments` |\n\ +| Retries, the timeout, the default pagination | `defaults` |\n\ +| How a list pages | `pagination`, and a method's `pagination` |\n\ +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, \ +`readme.headline_method`, `readme.pagination_method` |\n\ +| `package.json`'s description and keywords | `package.description`, `package.keywords` |\n\n\ ## What is yours\n\n\ - `src/lib/` and `examples/`: generate writes a file there only while it is unchanged, and \ never overwrites one you changed.\n\ @@ -108,7 +130,7 @@ another media type. Set `TEST_API_BASE_URL` to run the tests against another ser ## Releases\n\n\ release-please opens the release pull request: it raises `package.version` in \ `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version \ -released. Publishing is a person's step.\n", +released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step.\n", version = env!("CARGO_PKG_VERSION"), ) } diff --git a/crates/flowapi-sdk/src/security.rs b/crates/flowapi-sdk/src/security.rs index 4a1292e..ebb9b85 100644 --- a/crates/flowapi-sdk/src/security.rs +++ b/crates/flowapi-sdk/src/security.rs @@ -5,20 +5,18 @@ //! with no flows; OpenID Connect with no URL) is left out, with a warning. `security` is a list //! of alternatives, each naming the schemes it needs together; an operation's replaces the //! description's, `[]` meaning none. A name no scheme is declared under is a warning, and kept: a -//! client cannot meet that alternative, and says so where it is asked to. +//! client cannot meet that alternative, and says so where it is asked to. The flows are read in +//! `security/flows.rs`, the requirements in `security/requirements.rs`. A scheme's +//! Specification Extensions (`x-` members) are read by nothing. + +mod flows; +mod requirements; use crate::doc::{At, Doc, ROOT, oas}; use crate::model::{Auth, KeyLocation, Requirement, Scheme}; +use flowapi::spec::Operation; use flowapi::{Diagnostics, Version}; -/// 2.0's OAuth 2.0 flows and their 3.x names (2.0, "Security Scheme Object", `flow`). -const FLOWS_20: [(&str, &str); 4] = [ - ("implicit", "implicit"), - ("password", "password"), - ("application", "clientCredentials"), - ("accessCode", "authorizationCode"), -]; - impl Doc<'_, '_> { /// Where the schemes are declared: 3.x's `components.securitySchemes`, 2.0's /// `securityDefinitions`. @@ -31,6 +29,22 @@ impl Doc<'_, '_> { } } + /// An operation's security: its own `security`, else the description's (`root`), with + /// whether it is the description's. + pub(crate) fn effective( + &self, + op: &Operation, + root: &[Requirement], + diags: &mut Diagnostics, + ) -> (Vec, bool) { + let items = self.path_items(op); + let own = self + .operation(&items, op) + .and_then(|at| self.security(at, diags)); + let inherits = own.is_none(); + (own.unwrap_or_else(|| root.to_vec()), inherits) + } + /// The security schemes, in the order written. pub(crate) fn schemes(&self, diags: &mut Diagnostics) -> Vec { let mut out = Vec::new(); @@ -94,7 +108,10 @@ impl Doc<'_, '_> { self.missing(name, at, "flows", diags); return None; } - Auth::OAuth2 { flows } + Auth::OAuth2 { + client_credentials: self.client_credentials(name, at, diags), + flows, + } } "openIdConnect" if v != Version::V20 => Auth::OpenIdConnect { url: self.need(name, at, "openIdConnectUrl", diags)?, @@ -157,102 +174,4 @@ impl Doc<'_, '_> { format!("security scheme `{name}` has no `{field}` it can be used by: left out"); self.warn(diags, code, at, message); } - - /// An OAuth 2.0 scheme's flows by name: 3.x's `flows` keys, 2.0's `flow` lifted. - fn flows(&self, at: At) -> Vec { - if self.version == Version::V20 { - let flow = self.str(at, "flow"); - return FLOWS_20 - .iter() - .filter(|(old, _)| flow.as_deref() == Some(*old)) - .map(|(_, new)| (*new).to_owned()) - .collect(); - } - self.get(at, "flows") - .map(|f| self.members(f).into_iter().map(|(name, _)| name).collect()) - .unwrap_or_default() - } - - /// The description's `security`: `None` when it has none or it is not a list. - pub(crate) fn security(&self, owner: At, diags: &mut Diagnostics) -> Option> { - let list = self.get(owner, "security")?; - let v = self.version; - if !self.is(list, true) { - let code = if owner == ROOT { - oas!(v, "swagger.security", "openapi-object.security") - } else { - oas!(v, "swagger.security", "operation-object.security") - }; - self.warn( - diags, - code, - list, - String::from("`security` is not a list: left out"), - ); - return None; - } - let declared: Vec = self - .declared() - .map(|d| self.members(d).into_iter().map(|(n, _)| n).collect()) - .unwrap_or_default(); - let mut out = Vec::new(); - for item in self.items(list) { - if !self.is(item, false) { - let code = oas!( - v, - "swagger.security", - "security-requirement-object.pattern-name" - ); - let message = String::from("a security requirement is not an object: left out"); - self.warn(diags, code, item, message); - continue; - } - let mut requirement = Requirement::default(); - for (name, scopes) in self.members(item) { - if !declared.contains(&name) { - let code = match v { - Version::V20 => "swagger.security", - Version::V30 => { - "oas-3.0.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared" - } - Version::V31 => { - "oas-3.1.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared" - } - Version::V32 => { - "oas-3.2.security-requirement-object.pattern-name.must-each-name-uri-correspond-security-scheme" - } - }; - let message = format!( - "a security requirement names `{name}`, which no security scheme is declared under" - ); - self.warn(diags, code, item, message); - } - requirement.schemes.retain(|(n, _)| *n != name); - requirement.schemes.push((name, self.scopes(scopes, diags))); - } - out.push(requirement); - } - Some(out) - } - - /// A requirement's scopes: a list of strings; anything else is a warning and no scope. - fn scopes(&self, at: At, diags: &mut Diagnostics) -> Vec { - let strings: Vec = self - .items(at) - .into_iter() - .filter_map(|(d, n)| Some(self.tree(d)?.as_str(n)?.into_owned())) - .collect(); - if !self.is(at, true) || strings.len() != self.items(at).len() { - let code = oas!( - self.version, - "swagger.security", - "security-requirement-object.pattern-name" - ); - let message = String::from( - "a requirement's scopes are not a list of strings: read as the strings it holds", - ); - self.warn(diags, code, at, message); - } - strings - } } diff --git a/crates/flowapi-sdk/src/security/flows.rs b/crates/flowapi-sdk/src/security/flows.rs new file mode 100644 index 0000000..644137c --- /dev/null +++ b/crates/flowapi-sdk/src/security/flows.rs @@ -0,0 +1,127 @@ +//! An OAuth 2.0 scheme's flows: their names (3.x's `flows` keys, 2.0's `flow` lifted to 3.x's +//! names), and the client credentials flow's token URL and scopes, the one flow the client runs +//! itself (2.0's `application`). The OAuth Flows Object's `x-` members are Specification +//! Extensions, no flow; so are 2.0's Scopes Object's, no scope, while 3.x's `scopes` is a plain +//! map whose every key is a scope. A token URL may be relative: the client resolves it against +//! the server's URL ("Relative References in URLs"). + +use crate::doc::{At, Doc, oas}; +use crate::model::TokenFlow; +use flowapi::{Diagnostics, Version}; + +/// 2.0's OAuth 2.0 flows and their 3.x names (2.0, "Security Scheme Object", `flow`). +const FLOWS_20: [(&str, &str); 4] = [ + ("implicit", "implicit"), + ("password", "password"), + ("application", "clientCredentials"), + ("accessCode", "authorizationCode"), +]; + +impl Doc<'_, '_> { + /// An OAuth 2.0 scheme's flows by name: 3.x's `flows` keys but its extensions, 2.0's `flow` + /// lifted. + pub(super) fn flows(&self, at: At) -> Vec { + if self.version == Version::V20 { + let flow = self.str(at, "flow"); + return FLOWS_20 + .iter() + .filter(|(old, _)| flow.as_deref() == Some(*old)) + .map(|(_, new)| (*new).to_owned()) + .collect(); + } + self.get(at, "flows") + .map(|f| { + self.members(f) + .into_iter() + .map(|(name, _)| name) + .filter(|name| !name.starts_with("x-")) + .collect() + }) + .unwrap_or_default() + } + + /// The client credentials flow: 3.x's `flows.clientCredentials`, 2.0's scheme itself when its + /// `flow` is `application`. `None` without one; `None`, with a warning, when it has no token + /// URL or one that is no URL reference. Scopes it lacks are a warning, and none. + pub(super) fn client_credentials( + &self, + name: &str, + at: At, + diags: &mut Diagnostics, + ) -> Option { + let v = self.version; + let flow = if v == Version::V20 { + (self.str(at, "flow").as_deref() == Some("application")).then_some(at)? + } else { + self.get(at, "flows") + .and_then(|f| self.get(f, "clientCredentials"))? + }; + let Some(token_url) = self.str(flow, "tokenUrl") else { + let code = oas!(v, "swagger.security", "oauth-flow-object.tokenUrl.required"); + let message = format!( + "security scheme `{name}`: the client credentials flow has no `tokenUrl`: the client requests no token for it" + ); + self.warn(diags, code, flow, message); + return None; + }; + if !is_url_reference(&token_url) { + let code = oas!( + v, + "swagger.security", + "oauth-flow-object.tokenUrl.must-form-url" + ); + let message = format!( + "security scheme `{name}`: the `tokenUrl` {token_url:?} is not in the form of a URL: the client requests no token for it" + ); + self.warn(diags, code, flow, message); + return None; + } + let scopes = match self.get(flow, "scopes") { + Some(s) if self.is(s, false) => self + .members(s) + .into_iter() + .map(|(scope, _)| scope) + .filter(|scope| v != Version::V20 || !scope.starts_with("x-")) + .collect(), + Some(_) | None => { + let code = oas!(v, "swagger.security", "oauth-flow-object.scopes.required"); + let message = format!( + "security scheme `{name}`: the client credentials flow has no `scopes` map: read as none" + ); + self.warn(diags, code, flow, message); + Vec::new() + } + }; + Some(TokenFlow { token_url, scopes }) + } +} + +/// Whether a string is an RFC 3986 URI reference: no space or control character, a `%` only +/// before two hex digits, only the characters a URI may hold, and a scheme, where it has one, +/// that opens with a letter. +pub(crate) fn is_url_reference(s: &str) -> bool { + const OTHER: &str = "-._~:/?#[]@!$&'()*+,;="; + if s.is_empty() { + return false; + } + let bytes = s.as_bytes(); + for (i, &b) in bytes.iter().enumerate() { + let fits = b.is_ascii_alphanumeric() + || OTHER.as_bytes().contains(&b) + || (b == b'%' + && bytes + .get(i + 1..i + 3) + .is_some_and(|h| h.iter().all(u8::is_ascii_hexdigit))); + if !fits { + return false; + } + } + let first = s.split(['/', '?', '#']).next().unwrap_or(""); + match first.split_once(':') { + Some((scheme, _)) => scheme + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic()), + None => true, + } +} diff --git a/crates/flowapi-sdk/src/security/requirements.rs b/crates/flowapi-sdk/src/security/requirements.rs new file mode 100644 index 0000000..a381078 --- /dev/null +++ b/crates/flowapi-sdk/src/security/requirements.rs @@ -0,0 +1,120 @@ +//! `security`: a list of alternatives, each naming the schemes it needs together with their +//! scopes (role names for a scheme that is not OAuth 2.0 or OpenID Connect, kept as written). A +//! name is looked up in the entry document's schemes wherever the requirement is written, a +//! document a Path Item's `$ref` reaches included: the resolution Appendix F recommends. 3.2 may +//! name a scheme by URI; one that names a scheme of the entry document's components +//! (`#/components/securitySchemes/`, relative to it or absolute) is that scheme. + +use crate::doc::{At, Doc, ROOT, oas}; +use crate::model::Requirement; +use flowapi::{Diagnostics, Version}; + +/// Where 3.2's URI names a scheme of the entry document's components. +const COMPONENT: &str = "#/components/securitySchemes/"; + +impl Doc<'_, '_> { + /// The description's `security`: `None` when it has none or it is not a list. + pub(crate) fn security(&self, owner: At, diags: &mut Diagnostics) -> Option> { + let list = self.get(owner, "security")?; + let v = self.version; + if !self.is(list, true) { + let code = if owner == ROOT { + oas!(v, "swagger.security", "openapi-object.security") + } else { + oas!(v, "swagger.security", "operation-object.security") + }; + self.warn( + diags, + code, + list, + String::from("`security` is not a list: left out"), + ); + return None; + } + let declared: Vec = self + .declared() + .map(|d| self.members(d).into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default(); + let mut out = Vec::new(); + for item in self.items(list) { + if !self.is(item, false) { + let code = oas!( + v, + "swagger.security", + "security-requirement-object.pattern-name" + ); + let message = String::from("a security requirement is not an object: left out"); + self.warn(diags, code, item, message); + continue; + } + let mut requirement = Requirement::default(); + for (written, scopes) in self.members(item) { + let name = self.scheme_name(&written, &declared); + if !declared.contains(&name) { + let code = match v { + Version::V20 => "swagger.security", + Version::V30 => { + "oas-3.0.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared" + } + Version::V31 => { + "oas-3.1.security-requirement-object.pattern-name.must-each-name-correspond-security-scheme-declared" + } + Version::V32 => { + "oas-3.2.security-requirement-object.pattern-name.must-each-name-uri-correspond-security-scheme" + } + }; + let message = format!( + "a security requirement names `{name}`, which no security scheme is declared under" + ); + self.warn(diags, code, item, message); + } + requirement.schemes.retain(|(n, _)| *n != name); + requirement.schemes.push((name, self.scopes(scopes, diags))); + } + out.push(requirement); + } + Some(out) + } + + /// The scheme a requirement's key names: the key, a declared name; in 3.2, a URI of a scheme + /// of the entry document's components, that scheme's name. Else the key as written. + fn scheme_name(&self, written: &str, declared: &[String]) -> String { + if self.version != Version::V32 || declared.iter().any(|d| d == written) { + return written.to_owned(); + } + let (resource, fragment) = flowapi::uri::split_fragment(written); + let here = resource.is_empty() + || flowapi::uri::decoded(&flowapi::uri::resolve(&self.base, resource)) + == flowapi::uri::decoded(flowapi::uri::split_fragment(&self.base).0); + let pointer = flowapi::uri::decoded(fragment); + let name = format!("#{pointer}") + .strip_prefix(COMPONENT) + .filter(|n| here && !n.contains('/')) + .map(|n| n.replace("~1", "/").replace("~0", "~")); + match name { + Some(n) if declared.contains(&n) => n, + Some(_) | None => written.to_owned(), + } + } + + /// A requirement's scopes: a list of strings; anything else is a warning and no scope. + fn scopes(&self, at: At, diags: &mut Diagnostics) -> Vec { + let strings: Vec = self + .items(at) + .into_iter() + .filter_map(|(d, n)| Some(self.tree(d)?.as_str(n)?.into_owned())) + .collect(); + if !self.is(at, true) || strings.len() != self.items(at).len() { + let code = oas!( + self.version, + "swagger.security", + "security-requirement-object.pattern-name" + ); + let message = String::from( + "a requirement's scopes are not a list of strings: read as the strings it holds", + ); + self.warn(diags, code, at, message); + } + strings + } +} diff --git a/crates/flowapi-sdk/src/servers.rs b/crates/flowapi-sdk/src/servers.rs index c838c2e..b3cf1f9 100644 --- a/crates/flowapi-sdk/src/servers.rs +++ b/crates/flowapi-sdk/src/servers.rs @@ -3,10 +3,14 @@ //! `servers`). Swagger 2.0: `host`, `basePath` and `schemes` lifted into servers, an operation's //! own `schemes` into servers of its own. A server that cannot be used as written (no `url`, a //! variable with no `default` or that the URL names but `variables` does not) is left out, with a -//! warning; what only breaks a SHOULD or a MUST of the author is a warning and kept. +//! warning; what only breaks a SHOULD or a MUST of the author is a warning and kept. A relative +//! URL is relative to the document that holds its Server Object (3.x, `url`; 3.1 and 3.2, +//! "Relative References in API URLs"): one of another document is printed relative to the first, +//! which the client resolves against where the description is served (`descriptionURL`). use crate::doc::{At, Doc, ROOT, oas}; use crate::model::{Server, Variable}; +use flowapi::id::DocId; use flowapi::{Diagnostics, Version}; /// The schemes a 2.0 `schemes` list may name (2.0, "Swagger Object", `schemes`). @@ -98,6 +102,12 @@ impl Doc<'_, '_> { return None; } } + let url = if at.0 == DocId::FIRST { + url + } else { + let uri = |d: DocId| self.docs.get(d).map_or("", |d| d.uri.as_str()); + rebased(uri(DocId::FIRST), uri(at.0), url) + }; Some(Server { url, name: self @@ -179,17 +189,23 @@ impl Doc<'_, '_> { /// Swagger 2.0's servers at `at` (the description, or an operation with its own `schemes`): /// one per scheme, `://`. With no `host` the URL is the base path, - /// relative to where the description is served; with a host and no `schemes`, `//...`, - /// the scheme the description is served with (2.0, `schemes`). `None` for an operation with - /// no `schemes` of its own. + /// relative to where the description is served; with a host and no `schemes` that can be used, + /// `//...`, the scheme the description is served with (2.0, `schemes`). `None` for an + /// operation with none of its own, which the description's then serve. fn lifted(&self, at: At, diags: &mut Diagnostics) -> Option> { let root = ROOT; - let own = self + let code = if at == root { + "oas-2.0.swagger-object.schemes.must-values-list-http-https-ws-wss" + } else { + "oas-2.0.operation-object.schemes.must-values-list-http-https-ws-wss" + }; + let schemes = self .get(at, "schemes") - .filter(|&l| !self.items(l).is_empty()); + .map(|list| self.transfer_schemes(list, code, diags)) + .unwrap_or_default(); let host = self.str(root, "host"); // An operation's `schemes` change nothing where there is no host: its URL is relative. - if at != root && (own.is_none() || host.is_none()) { + if at != root && (schemes.is_empty() || host.is_none()) { return None; } let mut base = self @@ -203,21 +219,8 @@ impl Doc<'_, '_> { let Some(host) = host else { return Some(vec![plain(base)]); }; - let Some(own) = own else { + if schemes.is_empty() { return Some(vec![plain(format!("//{host}{base}"))]); - }; - let mut schemes: Vec = Vec::new(); - for item in self.items(own) { - let s = self.tree(item.0).and_then(|t| t.as_str(item.1)); - match s.filter(|s| SCHEMES.contains(&s.as_ref())) { - Some(s) if !schemes.iter().any(|t| *t == s) => schemes.push(s.into_owned()), - Some(_) => {} - None => { - let message = - String::from("a scheme is none of http, https, ws, wss: left out"); - self.warn(diags, "swagger.server", item, message); - } - } } Some( schemes @@ -226,6 +229,36 @@ impl Doc<'_, '_> { .collect(), ) } + + /// A 2.0 `schemes` list's values in order, each once; one that is not a string of `SCHEMES` + /// breaks the MUST under `code`, a warning, and is not used. + fn transfer_schemes( + &self, + list: At, + code: &'static str, + diags: &mut Diagnostics, + ) -> Vec { + let mut schemes: Vec = Vec::new(); + for item in self.items(list) { + let s = self.tree(item.0).and_then(|t| t.as_str(item.1)); + match s { + Some(s) if SCHEMES.contains(&s.as_ref()) => { + if !schemes.iter().any(|t| *t == s) { + schemes.push(s.into_owned()); + } + } + Some(s) => { + let message = format!("scheme {s:?} is none of http, https, ws, wss: not used"); + self.warn(diags, code, item, message); + } + None => { + let message = String::from("a scheme that is not a string: not used"); + self.warn(diags, code, item, message); + } + } + } + schemes + } } fn plain(url: String) -> Server { @@ -237,6 +270,46 @@ fn plain(url: String) -> Server { } } +/// A server URL written in the document at `own`, as a reference from the document at `first`: +/// a relative path (`./v2`, `../v2`, `v2`) joined to `own`'s folder, then written from `first`'s. +/// A URL with a scheme, a host (`//`), an absolute path or a variable before its first `/` (a +/// templated host) is the same from either document. +fn rebased(first: &str, own: &str, url: String) -> String { + let head = url.split('/').next().unwrap_or(""); + if url.starts_with('/') || head.contains([':', '{']) { + return url; + } + let folder = |uri: &str| -> Vec { + let mut parts: Vec = uri.split('/').map(str::to_owned).collect(); + parts.pop(); + parts + }; + let mut path = folder(own); + for part in url.split('/') { + match part { + "." | "" => {} + ".." if path.last().is_some_and(|p| p != "..") => { + path.pop(); + } + _ => path.push(part.to_owned()), + } + } + let base = folder(first); + let same = base.iter().zip(&path).take_while(|(a, b)| a == b).count(); + let mut out: Vec = base + .get(same..) + .unwrap_or_default() + .iter() + .map(|_| String::from("..")) + .collect(); + out.extend(path.get(same..).unwrap_or_default().iter().cloned()); + if out.is_empty() { + String::from(".") + } else { + out.join("/") + } +} + /// The names of a URL's `{name}` expressions, in order. fn template_names(url: &str) -> Vec<&str> { let mut out = Vec::new(); diff --git a/crates/flowapi-sdk/src/summary.rs b/crates/flowapi-sdk/src/summary.rs index 4cd14ec..20e40c3 100644 --- a/crates/flowapi-sdk/src/summary.rs +++ b/crates/flowapi-sdk/src/summary.rs @@ -1,11 +1,11 @@ //! `flowapi summary`: a description told to an agent in a few kilobytes of JSON, so that it can //! write a config without reading the description: its title and version, servers, security -//! schemes, counts, tags with their operations' counts, and each operation (how a config names -//! it, method, path, tags, summary, parameters, the media types of its body and of each response, +//! schemes, the description's `security` (each alternative the schemes it needs), counts, tags with their operations' counts, and each operation (how a config names +//! it, method, path, tags, summary, its own `security` where it has one, parameters, the media types of its body and of each response, //! and the pagination it looks like it has, with why and how sure). Over the budget, the tags //! alone, and how to read on: by `--tag` or `--path`. -use crate::model::{Auth, Scheme}; +use crate::model::{Auth, Requirement, Scheme}; use crate::ops::{Op, Ops}; use crate::out::{json_list, json_str, short}; use crate::paging::suggest; @@ -76,6 +76,11 @@ pub fn summary(docs: &Documents<'_>, filter: &Filter) -> Option { .map(scheme) .collect(); let _ = write!(head, ",\n\"securitySchemes\":{{{}}}", schemes.join(",")); + let root = ops + .doc + .security(crate::doc::ROOT, &mut Diagnostics::default()) + .unwrap_or_default(); + let _ = write!(head, ",\n\"security\":{}", requirements(&root)); let tags = tags(&ops); let _ = write!( head, @@ -147,13 +152,35 @@ fn scheme(s: &Scheme) -> String { ) } Auth::Http { scheme, .. } => format!("\"type\":\"http\",\"scheme\":{}", json_str(scheme)), - Auth::OAuth2 { flows } => format!("\"type\":\"oauth2\",\"flows\":{}", json_list(flows)), + Auth::OAuth2 { + flows, + client_credentials, + } => { + let token = client_credentials + .as_ref() + .map(|f| format!(",\"tokenUrl\":{}", json_str(&f.token_url))) + .unwrap_or_default(); + format!("\"type\":\"oauth2\",\"flows\":{}{token}", json_list(flows)) + } Auth::OpenIdConnect { .. } => String::from("\"type\":\"openIdConnect\""), Auth::MutualTls => String::from("\"type\":\"mutualTLS\""), }; format!("{}:{{{fields}}}", json_str(&s.name)) } +/// Security requirements compactly: each alternative the names of the schemes it needs +/// together, `[]` for one that needs none. +fn requirements(list: &[Requirement]) -> String { + let alternatives: Vec = list + .iter() + .map(|r| { + let names: Vec = r.schemes.iter().map(|(n, _)| n.clone()).collect(); + json_list(&names) + }) + .collect(); + format!("[{}]", alternatives.join(",")) +} + /// One operation, on one line. fn operation(ops: &Ops<'_, '_>, i: usize) -> String { let Some(op) = ops.list.get(i) else { @@ -175,6 +202,14 @@ fn operation(ops: &Ops<'_, '_>, i: usize) -> String { if o.deprecated { out.push_str(",\"deprecated\":true"); } + let root = ops + .doc + .security(crate::doc::ROOT, &mut Diagnostics::default()) + .unwrap_or_default(); + let (security, inherits) = ops.doc.effective(o, &root, &mut Diagnostics::default()); + if !inherits { + let _ = write!(out, ",\"security\":{}", requirements(&security)); + } let params: Vec = o .params .iter() diff --git a/crates/flowapi-sdk/tests/cases/defaults.ts b/crates/flowapi-sdk/tests/cases/defaults.ts index ac7cf89..cc1bdad 100644 --- a/crates/flowapi-sdk/tests/cases/defaults.ts +++ b/crates/flowapi-sdk/tests/cases/defaults.ts @@ -12,8 +12,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "session": { type: "apiKey", in: "cookie", name: "sid" }, @@ -25,9 +27,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { open: { diff --git a/crates/flowapi-sdk/tests/cases/encoding-v30.json b/crates/flowapi-sdk/tests/cases/encoding-v30.json new file mode 100644 index 0000000..8d14a37 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/encoding-v30.json @@ -0,0 +1,50 @@ +{ + "openapi": "3.0.4", + "info": { "title": "encoding in 3.0", "version": "1" }, + "paths": { + "/forms": { + "post": { + "operationId": "postForm", + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "file": { "type": "string", "format": "binary" }, + "b64": { "type": "string", "format": "byte" }, + "files": { "type": "array", "items": { "type": "string", "format": "binary" } }, + "id": { "type": "string", "format": "uuid" } + } + }, + "encoding": { + "id": { "style": "form", "explode": false, "allowReserved": true, "contentType": "text/plain", "x-internal": true }, + "file": { "headers": { "X-Size": { "schema": { "type": "integer" } } } } + } + }, + "application/x-www-form-urlencoded": { + "schema": { "type": "object" }, + "encoding": { "tags": { "style": "spaceDelimited", "explode": false }, "meta": { "contentType": "application/json" } } + }, + "text/plain": { "schema": { "type": "string" }, "encoding": { "a": { "contentType": "text/csv" } } } + } + }, + "responses": { + "200": { "description": "ok", "content": { "multipart/form-data": { "schema": { "type": "object" }, "encoding": { "a": { "contentType": "text/csv" } } } } } + } + } + } + }, + "x-flowapi-covers": [ + "req: oas-3.0.media-type-object.encoding — multipart/form-data and the form: each Encoding Object by its property's name", + "req: oas-3.0.media-type-object.encoding.shall-encoding-field-only-apply-request-body — the 200's multipart encoding and text/plain's read nowhere", + "req: oas-3.0.encoding-object.style.shall-field-ignored-request-body-media-type — multipart/form-data's id: style not read in 3.0; the form's tags: read", + "req: oas-3.0.encoding-object.explode.shall-field-ignored-request-body-media-type — id: explode not read for multipart/form-data in 3.0", + "req: oas-3.0.encoding-object.allowReserved.shall-field-ignored-request-body-media-type — id: allowReserved not read for multipart/form-data in 3.0", + "req: oas-3.0.encoding-object.common-fixed-fields.may-object-extended-specification-extensions — id: x-internal read as nothing" + ], + "x-flowapi-calls": [ + {"operation": "postForm", "input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"id": "a/b", "b64": "QUJD"}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"id\"\r\nContent-Type: text/plain\r\n\r\na/b\r\n--XyZ\r\nContent-Disposition: form-data; name=\"b64\"\r\nContent-Type: application/octet-stream\r\n\r\nQUJD\r\n--XyZ--\r\n"}}, + {"operation": "postForm", "input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"tags": ["a", "b"], "meta": {"k": "v w"}}}}, "expect": {"body": "tags=a%20b&meta=%7B%22k%22%3A%22v+w%22%7D"}} + ] +} diff --git a/crates/flowapi-sdk/tests/cases/encoding-v30.ts b/crates/flowapi-sdk/tests/cases/encoding-v30.ts new file mode 100644 index 0000000..e88cee3 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/encoding-v30.ts @@ -0,0 +1,43 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + postForm: { + method: "POST", + path: "/forms", + security: [], + responses: { "200": { content: { "multipart/form-data": "bytes" } } }, + encoding: { "multipart/form-data": { encoding: { "id": { contentType: "text/plain" }, "file": { contentType: "application/octet-stream" }, "b64": { contentType: "application/octet-stream" }, "files": { contentType: "application/octet-stream" } } }, "application/x-www-form-urlencoded": { encoding: { "tags": { style: "spaceDelimited", explode: false }, "meta": { contentType: "application/json" } } } }, + request: postFormRequest, + response: postFormResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/cases/encoding-v32.json b/crates/flowapi-sdk/tests/cases/encoding-v32.json new file mode 100644 index 0000000..83bd52a --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/encoding-v32.json @@ -0,0 +1,83 @@ +{ + "openapi": "3.2.0", + "info": { "title": "encoding in 3.2", "version": "1" }, + "paths": { + "/batch": { + "post": { + "operationId": "postBatch", + "requestBody": { + "content": { + "multipart/mixed": { + "schema": { + "type": "array", + "prefixItems": [{ "type": "array" }, { "type": "array", "prefixItems": [{ "type": "object" }, { "type": "string" }, {}] }, { "$ref": "#/components/schemas/Encoded" }], + "items": { "allOf": [{ "type": "string" }, { "contentEncoding": "base64url" }] } + }, + "prefixEncoding": [ + {}, + { "contentType": "multipart/mixed", "prefixEncoding": [{ "contentType": "application/xml" }, {}, { "contentType": "image/png" }], "x-note": "nothing" }, + { "headers": { "Content-Transfer-Encoding": { "schema": { "const": "base64" } } } } + ], + "encoding": { "ignored": { "contentType": "text/csv" } } + }, + "multipart/form-data": { + "schema": { + "type": "object", + "properties": { + "scan": { "$ref": "#/components/schemas/Scan" }, + "either": { "oneOf": [{ "type": "string", "contentEncoding": "base64" }, { "type": "integer" }] }, + "shot": { "type": "string", "contentMediaType": "image/png" } + } + }, + "encoding": { + "meta": { "contentType": "multipart/form-data", "encoding": { "a": { "contentType": "application/json" } }, "headers": { "X-A": { "schema": { "type": "string" } } } }, + "shot": { "contentType": "image/jpeg" }, + "deep": { "contentType": "multipart/mixed", "itemEncoding": { "contentType": "multipart/mixed", "itemEncoding": { "contentType": "multipart/mixed", "itemEncoding": { "contentType": "multipart/mixed", "itemEncoding": { "contentType": "text/plain" } } } } } + }, + "itemEncoding": { "contentType": "text/plain" } + }, + "application/x-www-form-urlencoded": { + "schema": { "type": "object" }, + "prefixEncoding": [{ "contentType": "text/plain" }], + "encoding": { "n": { "explode": true, "headers": { "X-N": { "schema": { "type": "string" } } } } } + }, + "application/json": { "schema": {}, "itemEncoding": { "contentType": "text/plain" } } + } + }, + "responses": { "204": { "description": "done" } } + } + } + }, + "components": { + "schemas": { + "Scan": { "allOf": [{ "$ref": "#/components/schemas/Encoded" }, { "maxLength": 100 }] }, + "Encoded": { "type": "string", "contentEncoding": "base64" } + } + }, + "x-flowapi-covers": [ + "req: oas-3.2.media-type-object.prefixEncoding — multipart/mixed: its three Encoding Objects by position", + "req: oas-3.2.media-type-object.itemEncoding — multipart/mixed: the items after them by items' schema; multipart/form-data's itemEncoding kept for its array form", + "req: oas-3.2.media-type-object.prefixEncoding.shall-prefixencoding-field-only-apply-media-type — the form's prefixEncoding read nowhere", + "req: oas-3.2.media-type-object.itemEncoding.shall-itemencoding-field-only-apply-media-type — application/json's itemEncoding read nowhere", + "req: oas-3.2.media-type-object.encoding.shall-encoding-field-only-apply-media-type — multipart/mixed's encoding (by name, for no named type) read nowhere", + "req: oas-3.2.media-type-object.encoding-usage-and-restrictions.shall-each-field-own-set-media-types — encoding for the form and multipart/form-data, prefixEncoding and itemEncoding for multipart, none for JSON", + "req: oas-3.2.encoding-object.headers.shall-field-ignored-media-type-not-multipart — n: the form's headers give nothing", + "req: oas-3.2.encoding-object.style.shall-field-ignored-media-type-not-application — multipart/mixed's Encoding Objects: no style read; the form's n: explode read", + "req: oas-3.2.encoding-object.explode.shall-field-ignored-media-type-not-application — explode read for the form only here", + "req: oas-3.2.encoding-object.allowReserved.shall-field-ignored-media-type-not-application — allowReserved read for no multipart/mixed part", + "req: oas-3.2.encoding-object.encoding — meta: its nested encoding by name, read for its multipart/form-data", + "req: oas-3.2.encoding-object.prefixEncoding — the second part: its nested prefixEncoding, as 3.2's own example", + "req: oas-3.2.encoding-object.itemEncoding — deep: nested itemEncoding read", + "req: oas-3.2.encoding-object.nested-encoding.must-implementations-support-one-level-nesting-support — the second part and meta nested one level; deep read to four levels, the fifth a warning", + "req: oas-3.2.encoding-object.common-fixed-fields.may-object-extended-specification-extensions — the second part's x-note read as nothing", + "req: oas-3.2.encoding-object.content-transfer-encoding-and-contentencoding.shall-note-stated-working-binary-data-encoding — shot: image/jpeg, not contentMediaType image/png", + "req: oas-3.2.schema-object.non-json-data.must-inspecting-schemas-given-starting-point-schema — scan: contentEncoding behind $ref then allOf then $ref makes it application/octet-stream; the third part and the items likewise, with Content-Transfer-Encoding", + "req: oas-3.2.schema-object.non-json-data.must-not-implementations-inspect-subschemas-possible-reference-targets — either: a contentEncoding inside oneOf is not looked into, no type is guessed", + "req: oas-3.2.schema-object.non-json-data.must-due-limited-requirements-searching-schemas-serializers — a code generator falls back to the schemas: what the data cannot tell (a string's text encoded) the table says" + ], + "x-flowapi-calls": [ + {"operation": "postBatch", "randoms": ["22222222222222222222222222222222"], "input": {"body": {"contentType": "multipart/mixed; boundary=XyZ", "value": [[1, 2], ["", "t", "P"], "QUJD", "eHk"]}}, "expect": {"body": "--XyZ\r\nContent-Type: application/json\r\n\r\n[1,2]\r\n--XyZ\r\nContent-Type: multipart/mixed; boundary=flowapi-22222222222222222222222222222222\r\n\r\n--flowapi-22222222222222222222222222222222\r\nContent-Type: application/xml\r\n\r\n\r\n--flowapi-22222222222222222222222222222222\r\n\r\nt\r\n--flowapi-22222222222222222222222222222222\r\nContent-Type: image/png\r\n\r\nP\r\n--flowapi-22222222222222222222222222222222--\r\n\r\n--XyZ\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\n\r\nQUJD\r\n--XyZ\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64url\r\n\r\neHk\r\n--XyZ--\r\n"}}, + {"operation": "postBatch", "input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"shot": "J", "scan": "QUJD", "either": "QUJD"}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"shot\"\r\nContent-Type: image/jpeg\r\n\r\nJ\r\n--XyZ\r\nContent-Disposition: form-data; name=\"scan\"\r\nContent-Type: application/octet-stream\r\n\r\nQUJD\r\n--XyZ\r\nContent-Disposition: form-data; name=\"either\"\r\n\r\nQUJD\r\n--XyZ--\r\n"}}, + {"operation": "postBatch", "input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"n": {"a": 1, "b": 2}}}}, "expect": {"body": "a=1&b=2"}} + ] +} diff --git a/crates/flowapi-sdk/tests/cases/encoding-v32.ts b/crates/flowapi-sdk/tests/cases/encoding-v32.ts new file mode 100644 index 0000000..c32eac7 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/encoding-v32.ts @@ -0,0 +1,44 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + postBatch: { + method: "POST", + path: "/batch", + security: [], + responses: { "204": { content: {} } }, + encoding: { "multipart/mixed": { prefixEncoding: [{}, { contentType: "multipart/mixed", prefixEncoding: [{ contentType: "application/xml" }, {}, { contentType: "image/png" }] }, { contentType: "application/octet-stream", headers: { "Content-Transfer-Encoding": "base64" } }], itemEncoding: { contentType: "application/octet-stream", headers: { "Content-Transfer-Encoding": "base64url" } } }, "multipart/form-data": { encoding: { "meta": { contentType: "multipart/form-data", encoding: { "a": { contentType: "application/json" } } }, "shot": { contentType: "image/jpeg" }, "deep": { contentType: "multipart/mixed", itemEncoding: { contentType: "multipart/mixed", itemEncoding: { contentType: "multipart/mixed", itemEncoding: { contentType: "multipart/mixed" } } } }, "scan": { contentType: "application/octet-stream" } }, itemEncoding: { contentType: "text/plain" } }, "application/x-www-form-urlencoded": { encoding: { "n": { explode: true } } } }, + request: postBatchRequest, + response: postBatchResponse, + }, +} as const; +// warning[oas-3.2.encoding-object.nested-encoding.must-implementations-support-one-level-nesting-support]: Encoding Objects nested deeper than 4 levels are not read: the part is written by its value's defaults diff --git a/crates/flowapi-sdk/tests/cases/encoding.json b/crates/flowapi-sdk/tests/cases/encoding.json index 8e64a1b..5ab1435 100644 --- a/crates/flowapi-sdk/tests/cases/encoding.json +++ b/crates/flowapi-sdk/tests/cases/encoding.json @@ -12,22 +12,49 @@ "multipart/form-data": { "schema": { "type": "object", - "properties": { "photo": { "type": "string", "contentMediaType": "image/png" }, "meta": { "type": "object" }, "thumb": { "type": "string" } } + "properties": { + "photo": { "type": "string", "contentMediaType": "image/png" }, + "meta": { "type": "object" }, + "thumb": { "type": "string" }, + "tags": { "type": "array", "items": { "type": "string" } }, + "scan": { "$ref": "#/components/schemas/Scan" }, + "either": { "oneOf": [{ "type": "string", "contentEncoding": "base64" }, { "type": "integer" }] } + } }, "encoding": { - "photo": { "contentType": "image/png" }, + "photo": { "contentType": "image/jpeg", "x-note": "an extension changes nothing" }, "meta": { "contentType": "application/json; charset=utf-8", "headers": { "X-Trace": { "schema": { "type": "string" } } } }, "thumb": { "contentType": "image/png, image/jpeg" }, - "none": { "style": "form" } + "tags": { "style": "form", "explode": false, "contentType": "application/json" }, + "none": { "style": "matrix" } } }, "application/x-www-form-urlencoded": { "schema": { "type": "object" }, - "encoding": { "photo": { "contentType": "text/plain" } } + "encoding": { + "photo": { "contentType": "text/plain", "headers": { "X-Ignored": { "schema": { "type": "string" } } } }, + "ids": { "style": "pipeDelimited" }, + "path": { "allowReserved": true }, + "point": { "style": "deepObject", "explode": true } + } + }, + "multipart/mixed": { + "schema": { "type": "array", "prefixItems": [{ "type": "string", "contentEncoding": "base64" }] }, + "prefixEncoding": [{ "contentType": "text/plain" }], + "itemEncoding": { "contentType": "text/plain" } + }, + "application/json": { + "schema": { "type": "object" }, + "encoding": { "photo": { "contentType": "image/png" } } } } }, - "responses": { "201": { "description": "made" } } + "responses": { + "201": { + "description": "made", + "content": { "multipart/form-data": { "schema": { "type": "object" }, "encoding": { "photo": { "contentType": "image/png" } } } } + } + } } }, "/docs": { @@ -46,6 +73,10 @@ } }, "components": { + "schemas": { + "Scan": { "allOf": [{ "$ref": "#/components/schemas/Encoded" }, { "maxLength": 100 }] }, + "Encoded": { "type": "string", "contentEncoding": "base64" } + }, "requestBodies": { "Doc": { "content": { @@ -58,6 +89,17 @@ } }, "x-flowapi-covers": [ - "req: oas-3.1.encoding-object.contentType — a part's one type read; a list or a range of types is a warning and left out" + "req: oas-3.1.encoding-object.contentType — a part's type read as written, parameters kept; a list (thumb) kept for the caller to pick from", + "req: oas-3.1.media-type-object.encoding — the Encoding Objects of multipart/form-data and of a form, by property name", + "req: oas-3.1.media-type-object.encoding.shall-encoding-field-only-apply-request-body — uploadPhoto: its 201's encoding and its application/json's encoding read nowhere", + "req: oas-3.1.encoding-object.style.shall-field-ignored-request-body-media-type — multipart/mixed: no style read; a form's and multipart/form-data's are", + "req: oas-3.1.encoding-object.explode.shall-field-ignored-request-body-media-type — explode read only for the form and multipart/form-data", + "req: oas-3.1.encoding-object.allowReserved.shall-field-ignored-request-body-media-type — allowReserved read only for the form and multipart/form-data", + "req: oas-3.1.encoding-object.common-fixed-fields.may-object-extended-specification-extensions — photo: x-note read as nothing", + "req: oas-3.1.encoding-object.encoding-multipart-media-types.shall-note-stated-working-binary-data-encoding — photo: contentType image/jpeg, not the schema's contentMediaType image/png" + ], + "x-flowapi-calls": [ + {"operation": "uploadPhoto", "input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"photo": "J", "meta": {"k": 1}, "tags": ["a", "b"], "scan": "QUJD"}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"photo\"\r\nContent-Type: image/jpeg\r\n\r\nJ\r\n--XyZ\r\nContent-Disposition: form-data; name=\"meta\"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n{\"k\":1}\r\n--XyZ\r\nContent-Disposition: form-data; name=\"tags\"\r\n\r\na,b\r\n--XyZ\r\nContent-Disposition: form-data; name=\"scan\"\r\nContent-Type: application/octet-stream\r\n\r\nQUJD\r\n--XyZ--\r\n"}}, + {"operation": "uploadPhoto", "input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"ids": [1, 2], "path": "/a b", "point": {"x": 1}, "photo": "p q"}}}, "expect": {"body": "ids=1%7C2&path=/a%20b&point%5Bx%5D=1&photo=p+q", "headers": {"content-type": "application/x-www-form-urlencoded"}}} ] } diff --git a/crates/flowapi-sdk/tests/cases/encoding.ts b/crates/flowapi-sdk/tests/cases/encoding.ts index 60c50df..7388b1a 100644 --- a/crates/flowapi-sdk/tests/cases/encoding.ts +++ b/crates/flowapi-sdk/tests/cases/encoding.ts @@ -12,8 +12,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { } as const; @@ -23,17 +25,18 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { uploadPhoto: { method: "POST", path: "/photos", security: [], - responses: { "201": { content: {} } }, - encoding: { "multipart/form-data": { "photo": { contentType: "image/png" }, "meta": { contentType: "application/json; charset=utf-8" } } }, + responses: { "201": { content: { "multipart/form-data": "bytes" } } }, + encoding: { "multipart/form-data": { encoding: { "photo": { contentType: "image/jpeg" }, "meta": { contentType: "application/json; charset=utf-8" }, "thumb": { contentType: "image/png, image/jpeg" }, "tags": { contentType: "application/json", style: "form", explode: false }, "none": {}, "scan": { contentType: "application/octet-stream" } } }, "application/x-www-form-urlencoded": { encoding: { "photo": { contentType: "text/plain" }, "ids": { style: "pipeDelimited" }, "path": { allowReserved: true }, "point": { style: "deepObject", explode: true } } } }, request: uploadPhotoRequest, response: uploadPhotoResponse, }, @@ -42,7 +45,7 @@ export const flowapiOperations = { path: "/docs", security: [], responses: { "204": { content: {} } }, - encoding: { "multipart/form-data; charset=utf-8": { "file": { contentType: "application/pdf" } } }, + encoding: { "multipart/form-data; charset=utf-8": { encoding: { "file": { contentType: "application/pdf" } } } }, request: putDocRequest, response: putDocResponse, }, @@ -55,4 +58,4 @@ export const flowapiOperations = { response: plainResponse, }, } as const; -// warning[oas-3.1.encoding-object.contentType]: the part `thumb` is encoded as `image/png, image/jpeg`, a list or a range of types: no one type to send it as, so it is sent as its value's default type +// warning[oas-3.1.encoding-object.style]: `style` is not one a form member takes (form, spaceDelimited, pipeDelimited, deepObject): read as not written diff --git a/crates/flowapi-sdk/tests/cases/security.ts b/crates/flowapi-sdk/tests/cases/security.ts index a20c6b8..2624368 100644 --- a/crates/flowapi-sdk/tests/cases/security.ts +++ b/crates/flowapi-sdk/tests/cases/security.ts @@ -12,8 +12,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "headerKey": { type: "apiKey", in: "header", name: "X-API-Key", description: "your key" }, @@ -21,7 +23,7 @@ export const flowapiSecuritySchemes = { "cookieKey": { type: "apiKey", in: "cookie", name: "session" }, "bearer": { type: "http", scheme: "bearer", bearerFormat: "JWT" }, "basic": { type: "http", scheme: "basic" }, - "oauth": { type: "oauth2", flows: ["authorizationCode", "clientCredentials"] }, + "oauth": { type: "oauth2", flows: ["authorizationCode", "clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, "oidc": { type: "openIdConnect", openIdConnectUrl: "https://example.com/.well-known/openid-configuration" }, "cert": { type: "mutualTLS" }, "alias": { type: "http", scheme: "bearer", bearerFormat: "JWT" }, @@ -32,9 +34,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { inherits: { diff --git a/crates/flowapi-sdk/tests/cases/security30.json b/crates/flowapi-sdk/tests/cases/security30.json new file mode 100644 index 0000000..bfb9bec --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/security30.json @@ -0,0 +1,194 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "security", + "version": "1" + }, + "paths": { + "/a": { + "get": { + "operationId": "inherits", + "responses": { + "200": { + "description": "ok" + } + } + }, + "put": { + "operationId": "anonymous", + "security": [], + "responses": { + "200": { + "description": "ok" + } + } + }, + "post": { + "operationId": "token", + "security": [ + { + "client": [ + "read" + ] + }, + { + "empty": [] + }, + { + "bearer": [], + "headerKey": [] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + }, + "patch": { + "operationId": "others", + "security": [ + { + "oidc": [ + "openid" + ] + }, + { + "headerKey": [ + "admin" + ] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + } + } + }, + "security": [ + { + "headerKey": [] + }, + { + "bearer": [], + "basic": [] + } + ], + "components": { + "securitySchemes": { + "headerKey": { + "type": "apiKey", + "in": "header", + "name": "X-API-Key", + "description": "Your *key*", + "x-internal": true + }, + "noName": { + "type": "apiKey", + "in": "header" + }, + "badIn": { + "type": "apiKey", + "in": "body", + "name": "k" + }, + "bearer": { + "type": "http", + "scheme": "Bearer", + "bearerFormat": "JWT" + }, + "basic": { + "type": "http", + "scheme": "basic" + }, + "noScheme": { + "type": "http" + }, + "client": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "/token?tenant=a", + "scopes": { + "read": "Read", + "x-not": "a scope: 3.x's scopes are a plain map" + }, + "x-note": true + }, + "x-vendorFlow": { + "tokenUrl": "https://vendor.example/token", + "scopes": {} + } + } + }, + "empty": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "https://example.com/token", + "scopes": {} + } + } + }, + "noTokenUrl": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "scopes": {} + } + } + }, + "badTokenUrl": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "not a url", + "scopes": {} + } + } + }, + "noScopes": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "https://example.com/token" + } + } + }, + "noFlows": { + "type": "oauth2" + }, + "oidc": { + "type": "openIdConnect", + "openIdConnectUrl": "https://example.com/.well-known/openid-configuration" + }, + "noUrl": { + "type": "openIdConnect" + } + } + }, + "x-flowapi-covers": [ + "req: oas-3.0.openapi-object.security \u2014 the description's alternatives, inherited by `inherits`; `anonymous`'s `[]` sends none", + "req: oas-3.0.security-scheme-object.description \u2014 a scheme's description printed as written", + "req: oas-3.0.security-scheme-object.scheme \u2014 bearer and basic, read without case", + "req: oas-3.0.security-scheme-object.scheme.required \u2014 http with no scheme is left out, with a warning", + "req: oas-3.0.security-scheme-object.bearerFormat \u2014 the bearer format printed as a hint", + "req: oas-3.0.security-scheme-object.flows \u2014 the flows named, an `x-` member of them no flow", + "req: oas-3.0.security-scheme-object.flows.required \u2014 oauth2 with no flows is left out, with a warning", + "req: oas-3.0.security-scheme-object.openIdConnectUrl \u2014 the discovery URL printed", + "req: oas-3.0.security-scheme-object.openIdConnectUrl.required \u2014 OpenID Connect with no URL is left out, with a warning", + "req: oas-3.0.security-scheme-object.fixed-fields.may-object-extended-specification-extensions \u2014 headerKey's `x-internal` read as no field", + "req: oas-3.0.oauth-flows-object.clientCredentials \u2014 the client credentials flow printed, which the client runs itself", + "req: oas-3.0.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions \u2014 `x-vendorFlow` is no flow", + "req: oas-3.0.oauth-flow-object.tokenUrl \u2014 the token URL printed, a relative one with its query as written", + "req: oas-3.0.oauth-flow-object.tokenUrl.must-form-url \u2014 a token URL not in the form of a URL is a warning, and no flow", + "req: oas-3.0.oauth-flow-object.tokenUrl.required \u2014 a flow with no token URL is a warning, and no flow", + "req: oas-3.0.oauth-flow-object.scopes \u2014 the flow's scopes printed", + "req: oas-3.0.oauth-flow-object.scopes.may-map-empty \u2014 `empty` has none, and is used", + "req: oas-3.0.oauth-flow-object.scopes.required \u2014 a flow with no scopes is a warning, read as none", + "req: oas-3.0.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions \u2014 the flow's `x-note` is no field", + "req: oas-3.0.security-requirement-object.must-security-requirement-object-refer-multiple-security \u2014 `bearer` and `headerKey` together are one alternative needing both" + ] +} diff --git a/crates/flowapi-sdk/tests/cases/security30.ts b/crates/flowapi-sdk/tests/cases/security30.ts new file mode 100644 index 0000000..7c10216 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/security30.ts @@ -0,0 +1,83 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "headerKey": { type: "apiKey", in: "header", name: "X-API-Key", description: "Your *key*" }, + "bearer": { type: "http", scheme: "bearer", bearerFormat: "JWT" }, + "basic": { type: "http", scheme: "basic" }, + "client": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "/token?tenant=a", scopes: ["read", "x-not"] } }, + "empty": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "noTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "badTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "noScopes": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "oidc": { type: "openIdConnect", openIdConnectUrl: "https://example.com/.well-known/openid-configuration" }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + inherits: { + method: "GET", + path: "/a", + security: [{ "headerKey": [] }, { "bearer": [], "basic": [] }], + responses: { "200": { content: {} } }, + request: inheritsRequest, + response: inheritsResponse, + }, + anonymous: { + method: "PUT", + path: "/a", + security: [], + responses: { "200": { content: {} } }, + request: anonymousRequest, + response: anonymousResponse, + }, + token: { + method: "POST", + path: "/a", + security: [{ "client": ["read"] }, { "empty": [] }, { "bearer": [], "headerKey": [] }], + responses: { "200": { content: {} } }, + request: tokenRequest, + response: tokenResponse, + }, + others: { + method: "PATCH", + path: "/a", + security: [{ "oidc": ["openid"] }, { "headerKey": ["admin"] }], + responses: { "200": { content: {} } }, + request: othersRequest, + response: othersResponse, + }, +} as const; +// warning[oas-3.0.security-scheme-object.name.required]: security scheme `noName` has no `name` it can be used by: left out +// warning[oas-3.0.security-scheme-object.in.required]: security scheme `badIn` has no `in` it can be used by: left out +// warning[oas-3.0.security-scheme-object.scheme.required]: security scheme `noScheme` has no `scheme` it can be used by: left out +// warning[oas-3.0.oauth-flow-object.tokenUrl.required]: security scheme `noTokenUrl`: the client credentials flow has no `tokenUrl`: the client requests no token for it +// warning[oas-3.0.oauth-flow-object.tokenUrl.must-form-url]: security scheme `badTokenUrl`: the `tokenUrl` "not a url" is not in the form of a URL: the client requests no token for it +// warning[oas-3.0.oauth-flow-object.scopes.required]: security scheme `noScopes`: the client credentials flow has no `scopes` map: read as none +// warning[oas-3.0.security-scheme-object.flows.required]: security scheme `noFlows` has no `flows` it can be used by: left out +// warning[oas-3.0.security-scheme-object.openIdConnectUrl.required]: security scheme `noUrl` has no `openIdConnectUrl` it can be used by: left out diff --git a/crates/flowapi-sdk/tests/cases/security31.json b/crates/flowapi-sdk/tests/cases/security31.json new file mode 100644 index 0000000..23cb3d0 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/security31.json @@ -0,0 +1,169 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "security", + "version": "1" + }, + "paths": { + "/a": { + "get": { + "operationId": "inherits", + "responses": { + "200": { + "description": "ok" + } + } + }, + "put": { + "operationId": "anonymous", + "security": [], + "responses": { + "200": { + "description": "ok" + } + } + }, + "post": { + "operationId": "token", + "security": [ + { + "client": [ + "read" + ] + }, + { + "empty": [] + }, + { + "bearer": [], + "headerKey": [] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + }, + "patch": { + "operationId": "others", + "security": [ + { + "oidc": [ + "openid" + ] + }, + { + "headerKey": [ + "admin" + ] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + } + } + }, + "security": [ + { + "headerKey": [] + }, + { + "bearer": [], + "basic": [] + } + ], + "components": { + "securitySchemes": { + "headerKey": { + "type": "apiKey", + "in": "header", + "name": "X-API-Key", + "description": "Your *key*", + "x-internal": true + }, + "bearer": { + "type": "http", + "scheme": "Bearer", + "bearerFormat": "JWT" + }, + "basic": { + "type": "http", + "scheme": "basic" + }, + "client": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "/token?tenant=a", + "scopes": { + "read": "Read", + "x-not": "a scope: 3.x's scopes are a plain map" + }, + "x-note": true + }, + "x-vendorFlow": { + "tokenUrl": "https://vendor.example/token", + "scopes": {} + } + } + }, + "empty": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "https://example.com/token", + "scopes": {} + } + } + }, + "noTokenUrl": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "scopes": {} + } + } + }, + "badTokenUrl": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "not a url", + "scopes": {} + } + } + }, + "noScopes": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "https://example.com/token" + } + } + }, + "oidc": { + "type": "openIdConnect", + "openIdConnectUrl": "https://example.com/.well-known/openid-configuration" + }, + "cert": { + "type": "mutualTLS" + } + } + }, + "x-flowapi-covers": [ + "req: oas-3.1.security-scheme-object.fixed-fields.may-object-extended-specification-extensions \u2014 headerKey's `x-internal` read as no field", + "req: oas-3.1.oauth-flows-object.clientCredentials \u2014 the client credentials flow printed, which the client runs itself", + "req: oas-3.1.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions \u2014 `x-vendorFlow` is no flow", + "req: oas-3.1.oauth-flow-object.tokenUrl \u2014 the token URL printed, a relative one with its query as written", + "req: oas-3.1.oauth-flow-object.tokenUrl.must-form-url \u2014 a token URL not in the form of a URL is a warning, and no flow", + "req: oas-3.1.oauth-flow-object.tokenUrl.required \u2014 a flow with no token URL is a warning, and no flow", + "req: oas-3.1.oauth-flow-object.scopes \u2014 the flow's scopes printed", + "req: oas-3.1.oauth-flow-object.scopes.may-map-empty \u2014 `empty` has none, and is used", + "req: oas-3.1.oauth-flow-object.scopes.required \u2014 a flow with no scopes is a warning, read as none", + "req: oas-3.1.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions \u2014 the flow's `x-note` is no field" + ] +} diff --git a/crates/flowapi-sdk/tests/cases/security31.ts b/crates/flowapi-sdk/tests/cases/security31.ts new file mode 100644 index 0000000..e4eadfb --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/security31.ts @@ -0,0 +1,79 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "headerKey": { type: "apiKey", in: "header", name: "X-API-Key", description: "Your *key*" }, + "bearer": { type: "http", scheme: "bearer", bearerFormat: "JWT" }, + "basic": { type: "http", scheme: "basic" }, + "client": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "/token?tenant=a", scopes: ["read", "x-not"] } }, + "empty": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "noTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "badTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "noScopes": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "oidc": { type: "openIdConnect", openIdConnectUrl: "https://example.com/.well-known/openid-configuration" }, + "cert": { type: "mutualTLS" }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + inherits: { + method: "GET", + path: "/a", + security: [{ "headerKey": [] }, { "bearer": [], "basic": [] }], + responses: { "200": { content: {} } }, + request: inheritsRequest, + response: inheritsResponse, + }, + anonymous: { + method: "PUT", + path: "/a", + security: [], + responses: { "200": { content: {} } }, + request: anonymousRequest, + response: anonymousResponse, + }, + token: { + method: "POST", + path: "/a", + security: [{ "client": ["read"] }, { "empty": [] }, { "bearer": [], "headerKey": [] }], + responses: { "200": { content: {} } }, + request: tokenRequest, + response: tokenResponse, + }, + others: { + method: "PATCH", + path: "/a", + security: [{ "oidc": ["openid"] }, { "headerKey": ["admin"] }], + responses: { "200": { content: {} } }, + request: othersRequest, + response: othersResponse, + }, +} as const; +// warning[oas-3.1.oauth-flow-object.tokenUrl.required]: security scheme `noTokenUrl`: the client credentials flow has no `tokenUrl`: the client requests no token for it +// warning[oas-3.1.oauth-flow-object.tokenUrl.must-form-url]: security scheme `badTokenUrl`: the `tokenUrl` "not a url" is not in the form of a URL: the client requests no token for it +// warning[oas-3.1.oauth-flow-object.scopes.required]: security scheme `noScopes`: the client credentials flow has no `scopes` map: read as none diff --git a/crates/flowapi-sdk/tests/cases/security32.json b/crates/flowapi-sdk/tests/cases/security32.json new file mode 100644 index 0000000..1b60e7e --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/security32.json @@ -0,0 +1,223 @@ +{ + "openapi": "3.2.0", + "info": { + "title": "security", + "version": "1" + }, + "paths": { + "/a": { + "get": { + "operationId": "inherits", + "responses": { + "200": { + "description": "ok" + } + } + }, + "put": { + "operationId": "anonymous", + "security": [], + "responses": { + "200": { + "description": "ok" + } + } + }, + "post": { + "operationId": "token", + "security": [ + { + "client": [ + "read" + ] + }, + { + "empty": [] + }, + { + "bearer": [], + "headerKey": [] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + }, + "patch": { + "operationId": "others", + "security": [ + { + "oidc": [ + "openid" + ] + }, + { + "headerKey": [ + "admin" + ] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + }, + "delete": { + "operationId": "byUri", + "security": [ + { + "#/components/securitySchemes/queryKey": [], + "security32.json#/components/securitySchemes/cookieKey": [] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + } + } + }, + "security": [ + { + "headerKey": [] + }, + { + "bearer": [], + "basic": [] + } + ], + "components": { + "securitySchemes": { + "headerKey": { + "type": "apiKey", + "in": "header", + "name": "X-API-Key", + "description": "Your *key*", + "x-internal": true + }, + "noName": { + "type": "apiKey", + "in": "header" + }, + "badIn": { + "type": "apiKey", + "in": "body", + "name": "k" + }, + "bearer": { + "type": "http", + "scheme": "Bearer", + "bearerFormat": "JWT" + }, + "basic": { + "type": "http", + "scheme": "basic" + }, + "noScheme": { + "type": "http" + }, + "client": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "/token?tenant=a", + "scopes": { + "read": "Read", + "x-not": "a scope: 3.x's scopes are a plain map" + }, + "x-note": true + }, + "x-vendorFlow": { + "tokenUrl": "https://vendor.example/token", + "scopes": {} + } + } + }, + "empty": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "https://example.com/token", + "scopes": {} + } + } + }, + "noTokenUrl": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "scopes": {} + } + } + }, + "badTokenUrl": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "not a url", + "scopes": {} + } + } + }, + "noScopes": { + "type": "oauth2", + "flows": { + "clientCredentials": { + "tokenUrl": "https://example.com/token" + } + } + }, + "noFlows": { + "type": "oauth2" + }, + "oidc": { + "type": "openIdConnect", + "openIdConnectUrl": "https://example.com/.well-known/openid-configuration" + }, + "noUrl": { + "type": "openIdConnect" + }, + "queryKey": { + "type": "apiKey", + "in": "query", + "name": "api_key" + }, + "cookieKey": { + "type": "apiKey", + "in": "cookie", + "name": "session" + } + } + }, + "x-flowapi-covers": [ + "req: oas-3.2.security-scheme-object.description \u2014 a scheme's description printed as written", + "req: oas-3.2.security-scheme-object.bearerFormat \u2014 the bearer format printed as a hint", + "req: oas-3.2.security-scheme-object.flows \u2014 the flows named, an `x-` member of them no flow", + "req: oas-3.2.security-scheme-object.flows.required \u2014 oauth2 with no flows is left out, with a warning", + "req: oas-3.2.security-scheme-object.openIdConnectUrl \u2014 the discovery URL printed", + "req: oas-3.2.security-scheme-object.openIdConnectUrl.required \u2014 OpenID Connect with no URL is left out, with a warning", + "req: oas-3.2.security-scheme-object.fixed-fields.may-object-extended-specification-extensions \u2014 headerKey's `x-internal` read as no field", + "req: oas-3.2.oauth-flows-object.clientCredentials \u2014 the client credentials flow printed, which the client runs itself", + "req: oas-3.2.oauth-flows-object.fixed-fields.may-object-extended-specification-extensions \u2014 `x-vendorFlow` is no flow", + "req: oas-3.2.oauth-flow-object.tokenUrl \u2014 the token URL printed, a relative one with its query as written", + "req: oas-3.2.oauth-flow-object.tokenUrl.must-form-url \u2014 a token URL not in the form of a URL is a warning, and no flow", + "req: oas-3.2.oauth-flow-object.tokenUrl.required \u2014 a flow with no token URL is a warning, and no flow", + "req: oas-3.2.oauth-flow-object.scopes \u2014 the flow's scopes printed", + "req: oas-3.2.oauth-flow-object.scopes.may-map-empty \u2014 `empty` has none, and is used", + "req: oas-3.2.oauth-flow-object.scopes.required \u2014 a flow with no scopes is a warning, read as none", + "req: oas-3.2.oauth-flow-object.fixed-fields.may-object-extended-specification-extensions \u2014 the flow's `x-note` is no field", + "req: oas-3.2.security-requirement-object.must-security-requirement-object-refer-multiple-security \u2014 `bearer` and `headerKey` together are one alternative needing both", + "req: oas-3.2.components-object.securitySchemes \u2014 every scheme read by name", + "req: oas-3.2.security-scheme-object.name \u2014 the key's name", + "req: oas-3.2.security-scheme-object.name.required \u2014 a key with no name is left out, with a warning", + "req: oas-3.2.security-scheme-object.in \u2014 header, query and cookie keys", + "req: oas-3.2.security-scheme-object.in.required \u2014 an in no key can go in leaves the scheme out, with a warning", + "req: oas-3.2.security-requirement-object.pattern-name \u2014 each name, or URI, with its scopes", + "req: oas-3.2.security-requirement-object.pattern-name.may-other-security-scheme-types-array-contain \u2014 an API key's roles kept as written", + "req: oas-3.2.security-requirement-object.pattern-name.may-security-scheme-type-oauth2-openidconnect-value \u2014 OAuth 2.0 and OpenID Connect scopes printed" + ] +} diff --git a/crates/flowapi-sdk/tests/cases/security32.ts b/crates/flowapi-sdk/tests/cases/security32.ts new file mode 100644 index 0000000..244c807 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/security32.ts @@ -0,0 +1,93 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "headerKey": { type: "apiKey", in: "header", name: "X-API-Key", description: "Your *key*" }, + "bearer": { type: "http", scheme: "bearer", bearerFormat: "JWT" }, + "basic": { type: "http", scheme: "basic" }, + "client": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "/token?tenant=a", scopes: ["read", "x-not"] } }, + "empty": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "noTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "badTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "noScopes": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "oidc": { type: "openIdConnect", openIdConnectUrl: "https://example.com/.well-known/openid-configuration" }, + "queryKey": { type: "apiKey", in: "query", name: "api_key" }, + "cookieKey": { type: "apiKey", in: "cookie", name: "session" }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + inherits: { + method: "GET", + path: "/a", + security: [{ "headerKey": [] }, { "bearer": [], "basic": [] }], + responses: { "200": { content: {} } }, + request: inheritsRequest, + response: inheritsResponse, + }, + anonymous: { + method: "PUT", + path: "/a", + security: [], + responses: { "200": { content: {} } }, + request: anonymousRequest, + response: anonymousResponse, + }, + token: { + method: "POST", + path: "/a", + security: [{ "client": ["read"] }, { "empty": [] }, { "bearer": [], "headerKey": [] }], + responses: { "200": { content: {} } }, + request: tokenRequest, + response: tokenResponse, + }, + byUri: { + method: "DELETE", + path: "/a", + security: [{ "queryKey": [], "cookieKey": [] }], + responses: { "200": { content: {} } }, + request: byUriRequest, + response: byUriResponse, + }, + others: { + method: "PATCH", + path: "/a", + security: [{ "oidc": ["openid"] }, { "headerKey": ["admin"] }], + responses: { "200": { content: {} } }, + request: othersRequest, + response: othersResponse, + }, +} as const; +// warning[oas-3.2.security-scheme-object.name.required]: security scheme `noName` has no `name` it can be used by: left out +// warning[oas-3.2.security-scheme-object.in.required]: security scheme `badIn` has no `in` it can be used by: left out +// warning[oas-3.2.security-scheme-object.scheme.required]: security scheme `noScheme` has no `scheme` it can be used by: left out +// warning[oas-3.2.oauth-flow-object.tokenUrl.required]: security scheme `noTokenUrl`: the client credentials flow has no `tokenUrl`: the client requests no token for it +// warning[oas-3.2.oauth-flow-object.tokenUrl.must-form-url]: security scheme `badTokenUrl`: the `tokenUrl` "not a url" is not in the form of a URL: the client requests no token for it +// warning[oas-3.2.oauth-flow-object.scopes.required]: security scheme `noScopes`: the client credentials flow has no `scopes` map: read as none +// warning[oas-3.2.security-scheme-object.flows.required]: security scheme `noFlows` has no `flows` it can be used by: left out +// warning[oas-3.2.security-scheme-object.openIdConnectUrl.required]: security scheme `noUrl` has no `openIdConnectUrl` it can be used by: left out diff --git a/crates/flowapi-sdk/tests/cases/servers.json b/crates/flowapi-sdk/tests/cases/servers.json index 633ed66..dcc2150 100644 --- a/crates/flowapi-sdk/tests/cases/servers.json +++ b/crates/flowapi-sdk/tests/cases/servers.json @@ -15,12 +15,14 @@ "eu", "us" ], - "description": "where the data lives" + "description": "where the data lives", + "x-owner": "ops" }, "version": { "default": "v1" } - } + }, + "x-region-note": "an extension, read by no one" }, { "url": "/relative" @@ -140,6 +142,8 @@ "req: oas-3.1.server-variable-object.enum — the enum printed", "req: oas-3.1.server-variable-object.enum.must-not-array-empty — an empty enum is a warning and allows any value", "req: oas-3.1.server-variable-object.description — a variable's description printed", - "req: oas-3.1.server-object.url.may-url-supports-server-variables-relative-indicate — a relative URL kept, variables in another" + "req: oas-3.1.server-object.url.may-url-supports-server-variables-relative-indicate — a relative URL kept, variables in another", + "req: oas-3.1.server-object.fixed-fields.may-object-extended-specification-extensions — an `x-` member of a server read by no one, no warning", + "req: oas-3.1.server-variable-object.fixed-fields.may-object-extended-specification-extensions — an `x-` member of a variable read by no one, no warning" ] } diff --git a/crates/flowapi-sdk/tests/cases/servers.ts b/crates/flowapi-sdk/tests/cases/servers.ts index 7039253..ad332a7 100644 --- a/crates/flowapi-sdk/tests/cases/servers.ts +++ b/crates/flowapi-sdk/tests/cases/servers.ts @@ -16,8 +16,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { } as const; @@ -27,9 +29,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { listPets: { diff --git a/crates/flowapi-sdk/tests/cases/servers30.json b/crates/flowapi-sdk/tests/cases/servers30.json new file mode 100644 index 0000000..da776c8 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/servers30.json @@ -0,0 +1,152 @@ +{ + "openapi": "3.0.4", + "info": { + "title": "servers 3.0", + "version": "1" + }, + "servers": [ + { + "url": "https://{region}.api.example.com/{version}", + "description": "production", + "variables": { + "region": { + "default": "eu", + "enum": [ + "eu", + "us" + ], + "description": "where the data lives", + "x-owner": "ops" + }, + "version": { + "default": "v1" + } + }, + "x-region-note": "an extension, read by no one" + }, + { + "url": ".", + "description": "where the description is served" + }, + { + "url": "./test", + "description": "beside it" + }, + { + "url": "https://{missing}.example.com" + }, + { + "description": "no url" + }, + { + "url": "https://{host}", + "variables": { + "host": { + "enum": [ + "a" + ] + } + } + }, + { + "url": "https://{x}.example.com", + "variables": { + "x": { + "default": "z", + "enum": [ + "a", + "b" + ] + } + } + }, + { + "url": "https://{y}.example.com", + "variables": { + "y": { + "default": "y", + "enum": [] + } + } + }, + { + "url": "https://example.com/?debug=1" + } + ], + "paths": { + "/pets": { + "servers": [ + { + "url": "https://pets.example.com" + } + ], + "get": { + "operationId": "listPets", + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "array" + } + } + } + } + } + }, + "post": { + "operationId": "createPet", + "servers": [ + { + "url": "https://write.example.com", + "description": "writes" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "responses": { + "201": { + "description": "made" + } + } + } + }, + "/health": { + "servers": [], + "get": { + "operationId": "health", + "servers": [], + "responses": { + "204": { + "description": "fine" + } + } + } + } + }, + "x-flowapi-covers": [ + "req: oas-3.0.path-item-object.servers — a Path Item's servers serve its operations instead of the description's", + "req: oas-3.0.operation-object.servers — an operation's servers win over its Path Item's; an empty list overrides nothing", + "req: oas-3.0.server-object.url — the URL kept as written, variables in it", + "req: oas-3.0.server-object.url.required — a server with no url is left out, with a warning", + "req: oas-3.0.server-object.url.may-url-supports-server-variables-relative-indicate — relative URLs (`.`, `./test`, `/relative`) kept for the client to resolve against where the description is served, variables in another", + "req: oas-3.0.server-object.description — a server's description printed", + "req: oas-3.0.server-object.variables — each variable with its default, enum and description", + "req: oas-3.0.server-object.fixed-fields.may-object-extended-specification-extensions — an `x-` member of a server read by no one, no warning", + "req: oas-3.0.server-variable-object.default — the default printed", + "req: oas-3.0.server-variable-object.default.required — a variable with no default leaves its server out, with a warning", + "req: oas-3.0.server-variable-object.default.should-enum-defined-value-exist-enum-s — a default outside enum is a warning", + "req: oas-3.0.server-variable-object.enum — the enum printed", + "req: oas-3.0.server-variable-object.enum.should-not-array-empty — an empty enum is a warning and allows any value", + "req: oas-3.0.server-variable-object.description — a variable's description printed", + "req: oas-3.0.server-variable-object.fixed-fields.may-object-extended-specification-extensions — an `x-` member of a variable read by no one, no warning" + ] +} diff --git a/crates/flowapi-sdk/tests/cases/servers30.ts b/crates/flowapi-sdk/tests/cases/servers30.ts new file mode 100644 index 0000000..f41f8b3 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/servers30.ts @@ -0,0 +1,70 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://{region}.api.example.com/{version}", description: "production", variables: { "region": { default: "eu", enum: ["eu", "us"], description: "where the data lives" }, "version": { default: "v1" } } }, + { url: ".", description: "where the description is served" }, + { url: "./test", description: "beside it" }, + { url: "https://{x}.example.com", variables: { "x": { default: "z", enum: ["a", "b"] } } }, + { url: "https://{y}.example.com", variables: { "y": { default: "y" } } }, + { url: "https://example.com/?debug=1" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + listPets: { + method: "GET", + path: "/pets", + servers: [{ url: "https://pets.example.com" }], + security: [], + responses: { "200": { content: { "application/json": "json" } } }, + request: listPetsRequest, + response: listPetsResponse, + }, + createPet: { + method: "POST", + path: "/pets", + servers: [{ url: "https://write.example.com", description: "writes" }], + security: [], + responses: { "201": { content: {} } }, + request: createPetRequest, + response: createPetResponse, + }, + health: { + method: "GET", + path: "/health", + security: [], + responses: { "204": { content: {} } }, + request: healthRequest, + response: healthResponse, + }, +} as const; +// warning[server.variable]: server URL "https://{missing}.example.com" names `{missing}`, which `variables` does not define: left out +// warning[oas-3.0.server-object.url.required]: a server has no `url` string: left out +// warning[oas-3.0.server-variable-object.default.required]: variable `host` of server "https://{host}" has no `default` string: the server is left out +// warning[oas-3.0.server-variable-object.default.should-enum-defined-value-exist-enum-s]: the `default` "z" of variable `x` is not in its `enum` +// warning[oas-3.0.server-variable-object.enum.should-not-array-empty]: variable `y` has an `enum` of no string: any value is allowed diff --git a/crates/flowapi-sdk/tests/cases/servers32.json b/crates/flowapi-sdk/tests/cases/servers32.json new file mode 100644 index 0000000..7b825c9 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/servers32.json @@ -0,0 +1,155 @@ +{ + "openapi": "3.2.0", + "info": { + "title": "servers 3.2", + "version": "1" + }, + "servers": [ + { + "url": "https://{region}.api.example.com/{version}", + "description": "production", + "variables": { + "region": { + "default": "eu", + "enum": [ + "eu", + "us" + ], + "description": "where the data lives", + "x-owner": "ops" + }, + "version": { + "default": "v1" + } + }, + "x-region-note": "an extension, read by no one", + "name": "prod" + }, + { + "url": ".", + "description": "where the description is served" + }, + { + "url": "./test", + "description": "beside it" + }, + { + "url": "https://{missing}.example.com" + }, + { + "description": "no url" + }, + { + "url": "https://{host}", + "variables": { + "host": { + "enum": [ + "a" + ] + } + } + }, + { + "url": "https://{x}.example.com", + "variables": { + "x": { + "default": "z", + "enum": [ + "a", + "b" + ] + } + } + }, + { + "url": "https://{y}.example.com", + "variables": { + "y": { + "default": "y", + "enum": [] + } + } + }, + { + "url": "https://example.com/?debug=1" + } + ], + "paths": { + "/pets": { + "servers": [ + { + "url": "https://pets.example.com" + } + ], + "get": { + "operationId": "listPets", + "responses": { + "200": { + "description": "ok", + "content": { + "application/json": { + "schema": { + "type": "array" + } + } + } + } + } + }, + "post": { + "operationId": "createPet", + "servers": [ + { + "url": "https://write.example.com", + "description": "writes" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "responses": { + "201": { + "description": "made" + } + } + } + }, + "/health": { + "servers": [], + "get": { + "operationId": "health", + "servers": [], + "responses": { + "204": { + "description": "fine" + } + } + } + } + }, + "x-flowapi-covers": [ + "req: oas-3.2.path-item-object.servers — a Path Item's servers serve its operations instead of the description's", + "req: oas-3.2.operation-object.servers — an operation's servers win over its Path Item's; an empty list overrides nothing", + "req: oas-3.2.server-object.url — the URL kept as written, variables in it", + "req: oas-3.2.server-object.url.required — a server with no url is left out, with a warning", + "req: oas-3.2.server-object.url.may-url-supports-server-variables-relative-indicate — relative URLs (`.`, `./test`, `/relative`) kept for the client to resolve against where the description is served, variables in another", + "req: oas-3.2.server-object.description — a server's description printed", + "req: oas-3.2.server-object.variables — each variable with its default, enum and description", + "req: oas-3.2.server-object.fixed-fields.may-object-extended-specification-extensions — an `x-` member of a server read by no one, no warning", + "req: oas-3.2.server-variable-object.default — the default printed", + "req: oas-3.2.server-variable-object.default.required — a variable with no default leaves its server out, with a warning", + "req: oas-3.2.server-variable-object.default.must-enum-defined-value-exist-enum-s — a default outside enum is a warning", + "req: oas-3.2.server-variable-object.enum — the enum printed", + "req: oas-3.2.server-variable-object.enum.must-not-array-empty — an empty enum is a warning and allows any value", + "req: oas-3.2.server-variable-object.description — a variable's description printed", + "req: oas-3.2.server-variable-object.fixed-fields.may-object-extended-specification-extensions — an `x-` member of a variable read by no one, no warning", + "req: oas-3.2.server-object.url.must-not-query-fragment-part-url — a URL with a query is a warning", + "req: oas-3.2.server-object.name — a server's name printed" + ] +} diff --git a/crates/flowapi-sdk/tests/cases/servers32.ts b/crates/flowapi-sdk/tests/cases/servers32.ts new file mode 100644 index 0000000..31cad3b --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/servers32.ts @@ -0,0 +1,71 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://{region}.api.example.com/{version}", name: "prod", description: "production", variables: { "region": { default: "eu", enum: ["eu", "us"], description: "where the data lives" }, "version": { default: "v1" } } }, + { url: ".", description: "where the description is served" }, + { url: "./test", description: "beside it" }, + { url: "https://{x}.example.com", variables: { "x": { default: "z", enum: ["a", "b"] } } }, + { url: "https://{y}.example.com", variables: { "y": { default: "y" } } }, + { url: "https://example.com/?debug=1" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + listPets: { + method: "GET", + path: "/pets", + servers: [{ url: "https://pets.example.com" }], + security: [], + responses: { "200": { content: { "application/json": "json" } } }, + request: listPetsRequest, + response: listPetsResponse, + }, + createPet: { + method: "POST", + path: "/pets", + servers: [{ url: "https://write.example.com", description: "writes" }], + security: [], + responses: { "201": { content: {} } }, + request: createPetRequest, + response: createPetResponse, + }, + health: { + method: "GET", + path: "/health", + security: [], + responses: { "204": { content: {} } }, + request: healthRequest, + response: healthResponse, + }, +} as const; +// warning[server.variable]: server URL "https://{missing}.example.com" names `{missing}`, which `variables` does not define: left out +// warning[oas-3.2.server-object.url.required]: a server has no `url` string: left out +// warning[oas-3.2.server-variable-object.default.required]: variable `host` of server "https://{host}" has no `default` string: the server is left out +// warning[oas-3.2.server-variable-object.default.must-enum-defined-value-exist-enum-s]: the `default` "z" of variable `x` is not in its `enum` +// warning[oas-3.2.server-variable-object.enum.must-not-array-empty]: variable `y` has an `enum` of no string: any value is allowed +// warning[oas-3.2.server-object.url.must-not-query-fragment-part-url]: server URL "https://example.com/?debug=1" has a query or a fragment, which it MUST NOT diff --git a/crates/flowapi-sdk/tests/cases/swagger-forms.json b/crates/flowapi-sdk/tests/cases/swagger-forms.json new file mode 100644 index 0000000..ff723b8 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/swagger-forms.json @@ -0,0 +1,55 @@ +{ + "swagger": "2.0", + "info": { "title": "forms", "version": "1" }, + "host": "forms.example", + "paths": { + "/tags": { + "parameters": [{ "name": "shared", "in": "formData", "type": "array", "items": { "type": "string" }, "collectionFormat": "pipes" }], + "post": { + "operationId": "postTags", + "consumes": ["application/x-www-form-urlencoded"], + "parameters": [ + { "name": "csv", "in": "formData", "type": "array", "items": { "type": "string" } }, + { "name": "multi", "in": "formData", "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, + { "name": "ssv", "in": "formData", "type": "array", "items": { "type": "string" }, "collectionFormat": "ssv" }, + { "name": "tsv", "in": "formData", "type": "array", "items": { "type": "string" }, "collectionFormat": "tsv" }, + { "name": "odd", "in": "formData", "type": "array", "items": { "type": "string" }, "collectionFormat": "commas" }, + { "name": "plain", "in": "formData", "type": "string" }, + { "name": "grid", "in": "formData", "type": "array", "collectionFormat": "multi", "items": { "type": "array", "collectionFormat": "pipes", "items": { "type": "array", "items": { "type": "integer" } } } }, + { "name": "bad", "in": "formData", "type": "array", "items": { "type": "array", "collectionFormat": "multi", "items": { "type": "string" } } } + ], + "responses": { "204": { "description": "done" } } + } + }, + "/upload": { + "post": { + "operationId": "upload", + "parameters": [ + { "name": "file", "in": "formData", "type": "file", "required": true }, + { "name": "sizes", "in": "formData", "type": "array", "items": { "type": "integer" }, "collectionFormat": "csv" }, + { "name": "rows", "in": "formData", "type": "array", "items": { "type": "array", "collectionFormat": "tsv", "items": { "type": "string" } } } + ], + "responses": { "204": { "description": "done" } } + } + }, + "/plain": { + "post": { + "operationId": "plainForm", + "parameters": [{ "name": "name", "in": "formData", "type": "string" }], + "responses": { "204": { "description": "done" } } + } + } + }, + "x-flowapi-covers": [ + "req: oas-2.0.parameter-object.in — formData fields written as the form body's members, a Path Item's shared one too (tsc.mjs's calls)", + "req: oas-2.0.parameter-object.type — upload: a `file` field makes the body multipart/form-data, its array field a part of its own", + "req: oas-2.0.operation-object.consumes — postTags: the form written as the one media type it consumes", + "req: oas-2.0.items-object.collectionFormat — postTags: grid's arrays inside arrays by each level's format, bad's multi (a parameter's alone) warned and read as csv; upload: rows's inner arrays tab-joined in one part" + ], + "x-flowapi-calls": [ + {"operation": "postTags", "input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"shared": ["a", "b"], "csv": ["a", "b"], "multi": ["a", "b"], "ssv": ["a", "b"], "tsv": ["a", "b"], "odd": ["a", "b"], "plain": "p q"}}}, "expect": {"body": "shared=a%7Cb&csv=a,b&multi=a&multi=b&ssv=a%20b&tsv=a%09b&odd=a,b&plain=p+q"}}, + {"operation": "postTags", "input": {"body": {"contentType": "application/x-www-form-urlencoded", "value": {"grid": [[[1, 2], [3]], [[4]]], "bad": [["a", "b"], ["c"]]}}}, "expect": {"body": "grid=1,2%7C3&grid=4&bad=a,b,c"}}, + {"operation": "upload", "input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"sizes": [1, 2]}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"sizes\"\r\n\r\n1,2\r\n--XyZ--\r\n"}}, + {"operation": "upload", "input": {"body": {"contentType": "multipart/form-data; boundary=XyZ", "value": {"rows": [["a", "b"], ["c"]]}}}, "expect": {"body": "--XyZ\r\nContent-Disposition: form-data; name=\"rows\"\r\n\r\na\tb,c\r\n--XyZ--\r\n"}} + ] +} diff --git a/crates/flowapi-sdk/tests/cases/swagger-forms.ts b/crates/flowapi-sdk/tests/cases/swagger-forms.ts new file mode 100644 index 0000000..21fd2d6 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/swagger-forms.ts @@ -0,0 +1,60 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "//forms.example/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + postTags: { + method: "POST", + path: "/tags", + security: [], + responses: { "204": { content: {} } }, + encoding: { "application/x-www-form-urlencoded": { encoding: { "shared": { style: "pipeDelimited", explode: false }, "csv": { style: "form", explode: false }, "multi": { style: "form", explode: true }, "ssv": { style: "spaceDelimited", explode: false }, "tsv": { style: "tabDelimited", explode: false }, "odd": { style: "form", explode: false }, "grid": { style: "form", explode: true, nested: ["pipeDelimited", "form"] }, "bad": { style: "form", explode: false, nested: ["form"] } } } }, + request: postTagsRequest, + response: postTagsResponse, + }, + upload: { + method: "POST", + path: "/upload", + security: [], + responses: { "204": { content: {} } }, + encoding: { "multipart/form-data": { encoding: { "sizes": { style: "form", explode: false }, "rows": { style: "form", explode: false, nested: ["tabDelimited"] } } } }, + request: uploadRequest, + response: uploadResponse, + }, + plainForm: { + method: "POST", + path: "/plain", + security: [], + responses: { "204": { content: {} } }, + request: plainFormRequest, + response: plainFormResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/cases/swagger-host.json b/crates/flowapi-sdk/tests/cases/swagger-host.json index 2d8f84e..9aa70b6 100644 --- a/crates/flowapi-sdk/tests/cases/swagger-host.json +++ b/crates/flowapi-sdk/tests/cases/swagger-host.json @@ -1,4 +1,6 @@ {"swagger":"2.0","info":{"title":"host, no schemes","version":"1"}, + "x-flowapi-covers":[ + "req: oas-2.0.swagger-object.schemes — no schemes: //api.example.com/, the scheme the description is served with"], "host":"api.example.com", "paths":{"/x":{ "get":{"operationId":"getX","responses":{"200":{"description":"ok"}}}, diff --git a/crates/flowapi-sdk/tests/cases/swagger-host.ts b/crates/flowapi-sdk/tests/cases/swagger-host.ts index 3a32fe7..a7078e9 100644 --- a/crates/flowapi-sdk/tests/cases/swagger-host.ts +++ b/crates/flowapi-sdk/tests/cases/swagger-host.ts @@ -12,8 +12,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { } as const; @@ -23,9 +25,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { getX: { diff --git a/crates/flowapi-sdk/tests/cases/swagger-nohost.json b/crates/flowapi-sdk/tests/cases/swagger-nohost.json index ea181a5..a1438e4 100644 --- a/crates/flowapi-sdk/tests/cases/swagger-nohost.json +++ b/crates/flowapi-sdk/tests/cases/swagger-nohost.json @@ -1,4 +1,6 @@ {"swagger":"2.0","info":{"title":"no host","version":"1"}, + "x-flowapi-covers":[ + "req: oas-2.0.swagger-object.basePath.must-value-start-leading-slash — v3 read as /v3, with a warning"], "basePath":"v3","schemes":["https"], "paths":{"/y":{ "get":{"operationId":"getY","schemes":["http"],"responses":{"200":{"description":"ok"}}}}}} diff --git a/crates/flowapi-sdk/tests/cases/swagger-nohost.ts b/crates/flowapi-sdk/tests/cases/swagger-nohost.ts index e867a4e..bc329a6 100644 --- a/crates/flowapi-sdk/tests/cases/swagger-nohost.ts +++ b/crates/flowapi-sdk/tests/cases/swagger-nohost.ts @@ -12,8 +12,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { } as const; @@ -23,9 +25,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { getY: { diff --git a/crates/flowapi-sdk/tests/cases/swagger20-oauth.json b/crates/flowapi-sdk/tests/cases/swagger20-oauth.json new file mode 100644 index 0000000..ec63077 --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/swagger20-oauth.json @@ -0,0 +1,95 @@ +{ + "swagger": "2.0", + "info": { + "title": "oauth", + "version": "1" + }, + "host": "api.example.com", + "schemes": [ + "https" + ], + "securityDefinitions": { + "app": { + "type": "oauth2", + "flow": "application", + "tokenUrl": "https://example.com/token", + "description": "The *client's* own", + "x-internal": true, + "scopes": { + "pets:read": "Read pets", + "pets:write": "Write pets", + "x-note": "an extension, no scope" + } + }, + "relative": { + "type": "oauth2", + "flow": "application", + "tokenUrl": "/token", + "scopes": {} + }, + "noTokenUrl": { + "type": "oauth2", + "flow": "application", + "scopes": {} + }, + "noScopes": { + "type": "oauth2", + "flow": "application", + "tokenUrl": "https://example.com/token" + }, + "key": { + "type": "apiKey", + "in": "header", + "name": "X-Key", + "description": "A key", + "x-vendor": { + "a": 1 + } + } + }, + "security": [ + { + "app": [ + "pets:read" + ] + } + ], + "paths": { + "/pets": { + "get": { + "operationId": "listPets", + "responses": { + "200": { + "description": "ok" + } + } + }, + "post": { + "operationId": "addPet", + "security": [ + { + "app": [ + "pets:write" + ] + }, + { + "key": [] + } + ], + "responses": { + "200": { + "description": "ok" + } + } + } + } + }, + "x-flowapi-covers": [ + "req: oas-2.0.security-scheme-object.description \u2014 a scheme's description printed as written", + "req: oas-2.0.security-scheme-object.tokenUrl \u2014 the application flow's token URL printed, which the client requests at; a relative one kept as written", + "req: oas-2.0.security-scheme-object.scopes \u2014 the application flow's scopes printed; a flow with no scopes is a warning, read as none", + "req: oas-2.0.security-scheme-object.x \u2014 `x-internal` and `x-vendor` read as no field", + "req: oas-2.0.scopes-object.pattern-name \u2014 each scope by its name", + "req: oas-2.0.scopes-object.pattern-x \u2014 `x-note` is an extension, no scope" + ] +} diff --git a/crates/flowapi-sdk/tests/cases/swagger20-oauth.ts b/crates/flowapi-sdk/tests/cases/swagger20-oauth.ts new file mode 100644 index 0000000..e23f0af --- /dev/null +++ b/crates/flowapi-sdk/tests/cases/swagger20-oauth.ts @@ -0,0 +1,57 @@ + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://api.example.com/" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "app": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: ["pets:read", "pets:write"] }, description: "The *client's* own" }, + "relative": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "/token", scopes: [] } }, + "noTokenUrl": { type: "oauth2", flows: ["clientCredentials"] }, + "noScopes": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/token", scopes: [] } }, + "key": { type: "apiKey", in: "header", name: "X-Key", description: "A key" }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + listPets: { + method: "GET", + path: "/pets", + security: [{ "app": ["pets:read"] }], + responses: { "200": { content: {} } }, + request: listPetsRequest, + response: listPetsResponse, + }, + addPet: { + method: "POST", + path: "/pets", + security: [{ "app": ["pets:write"] }, { "key": [] }], + responses: { "200": { content: {} } }, + request: addPetRequest, + response: addPetResponse, + }, +} as const; +// warning[swagger.security]: security scheme `noTokenUrl`: the client credentials flow has no `tokenUrl`: the client requests no token for it +// warning[swagger.security]: security scheme `noScopes`: the client credentials flow has no `scopes` map: read as none diff --git a/crates/flowapi-sdk/tests/cases/swagger20.json b/crates/flowapi-sdk/tests/cases/swagger20.json index 0d11eef..0e8d032 100644 --- a/crates/flowapi-sdk/tests/cases/swagger20.json +++ b/crates/flowapi-sdk/tests/cases/swagger20.json @@ -1,4 +1,21 @@ {"swagger":"2.0","info":{"title":"swagger","version":"1"}, + "x-flowapi-covers":[ + "req: oas-2.0.swagger-object.host — host api.example.com:8443 in each server's URL", + "req: oas-2.0.swagger-object.host.may-include-port — the port 8443 kept", + "req: oas-2.0.swagger-object.basePath — /v2 after the host", + "req: oas-2.0.swagger-object.schemes — one server per scheme, https then http, in order", + "req: oas-2.0.swagger-object.schemes.must-values-list-http-https-ws-wss — gopher and 7 left out with a warning", + "req: oas-2.0.swagger-object.securityDefinitions — flowapiSecuritySchemes from securityDefinitions", + "req: oas-2.0.security-definitions-object.pattern-name — each scheme under its name", + "req: oas-2.0.swagger-object.security — putPets: the description's security, basic", + "req: oas-2.0.operation-object.security — listPets: its own security over the description's; watchPets: [] sends none", + "req: oas-2.0.operation-object.schemes — watchPets: wss, a server of its own", + "req: oas-2.0.operation-object.schemes.must-values-list-http-https-ws-wss — watchPets: ftp left out with a warning, wss kept; dropPets: only ftp and true, a warning each and the description's servers", + "req: oas-2.0.security-scheme-object.type — basic as http basic, apiKey, oauth2", + "req: oas-2.0.security-scheme-object.name — key and X-Key", + "req: oas-2.0.security-scheme-object.in — key in the query, X-Key in a header; cookie, which 2.0 does not define, left out", + "req: oas-2.0.security-scheme-object.flow — accessCode as authorizationCode, application as clientCredentials; noFlow left out", + "req: oas-2.0.security-requirement-object.pattern-name — listPets: code with its scope pets, key and headerKey together"], "host":"api.example.com:8443","basePath":"/v2","schemes":["https","http","gopher",7], "securityDefinitions":{ "basic":{"type":"basic"}, @@ -13,5 +30,6 @@ "paths":{"/pets":{ "get":{"operationId":"listPets","security":[{"code":["pets"]},{"key":[],"headerKey":[]}],"produces":["application/json","application/octet-stream"], "responses":{"200":{"description":"ok","schema":{"type":"array","items":{}}}}}, - "post":{"operationId":"watchPets","schemes":["wss"],"security":[],"responses":{"101":{"description":"switching"}}}, - "put":{"operationId":"putPets","responses":{"204":{"description":"done"}}}}}} + "post":{"operationId":"watchPets","schemes":["ftp","wss"],"security":[],"responses":{"101":{"description":"switching"}}}, + "put":{"operationId":"putPets","responses":{"204":{"description":"done"}}}, + "delete":{"operationId":"dropPets","schemes":["ftp",true],"responses":{"204":{"description":"done"}}}}}} diff --git a/crates/flowapi-sdk/tests/cases/swagger20.ts b/crates/flowapi-sdk/tests/cases/swagger20.ts index 10178b3..02a2f62 100644 --- a/crates/flowapi-sdk/tests/cases/swagger20.ts +++ b/crates/flowapi-sdk/tests/cases/swagger20.ts @@ -13,15 +13,17 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "basic": { type: "http", scheme: "basic" }, "key": { type: "apiKey", in: "query", name: "key" }, "headerKey": { type: "apiKey", in: "header", name: "X-Key" }, "code": { type: "oauth2", flows: ["authorizationCode"] }, - "app": { type: "oauth2", flows: ["clientCredentials"] }, + "app": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://example.com/t", scopes: [] } }, } as const; /** @@ -29,9 +31,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { listPets: { @@ -59,9 +62,21 @@ export const flowapiOperations = { request: watchPetsRequest, response: watchPetsResponse, }, + dropPets: { + method: "DELETE", + path: "/pets", + security: [{ "basic": [] }], + responses: { "204": { content: {} } }, + request: dropPetsRequest, + response: dropPetsResponse, + }, } as const; -// warning[swagger.server]: a scheme is none of http, https, ws, wss: left out -// warning[swagger.server]: a scheme is none of http, https, ws, wss: left out +// warning[oas-2.0.swagger-object.schemes.must-values-list-http-https-ws-wss]: scheme "gopher" is none of http, https, ws, wss: not used +// warning[oas-2.0.swagger-object.schemes.must-values-list-http-https-ws-wss]: a scheme that is not a string: not used +// warning[swagger.security]: security scheme `app`: the client credentials flow has no `scopes` map: read as none // warning[swagger.security]: security scheme `noFlow` has no `flows` it can be used by: left out // warning[swagger.security]: security scheme `cookie` has no `in` it can be used by: left out // warning[swagger.security]: security scheme `bearer` has a `type` "http" this version does not define: left out +// warning[oas-2.0.operation-object.schemes.must-values-list-http-https-ws-wss]: scheme "ftp" is none of http, https, ws, wss: not used +// warning[oas-2.0.operation-object.schemes.must-values-list-http-https-ws-wss]: scheme "ftp" is none of http, https, ws, wss: not used +// warning[oas-2.0.operation-object.schemes.must-values-list-http-https-ws-wss]: a scheme that is not a string: not used diff --git a/crates/flowapi-sdk/tests/cases/v32.ts b/crates/flowapi-sdk/tests/cases/v32.ts index 049c86f..1841dc3 100644 --- a/crates/flowapi-sdk/tests/cases/v32.ts +++ b/crates/flowapi-sdk/tests/cases/v32.ts @@ -12,8 +12,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "old": { type: "apiKey", in: "header", name: "X-Old", deprecated: true }, @@ -25,9 +27,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { sharedGet: { diff --git a/crates/flowapi-sdk/tests/client.rs b/crates/flowapi-sdk/tests/client.rs index 9da92b7..aa7fcb8 100644 --- a/crates/flowapi-sdk/tests/client.rs +++ b/crates/flowapi-sdk/tests/client.rs @@ -9,6 +9,9 @@ //! encoding, a download as bytes, two alternatives of security and an operation that needs none. //! auth: each kind of credential, alternatives and schemes needed together, an operation's own //! servers, a server variable, JSON lines, reserved words as names, resources three levels deep. +//! hosts (3.2): servers with variables and an `enum`, relative ones, a Path Item's and an +//! operation's own, every idempotent method but TRACE and two that are not, content with DELETE +//! and OPTIONS, an idempotency key. edge (3.1): variables and relative servers, the default retries. //! //! `generate`, ignored, writes the files for any description and config: `FLOWAPI_CLIENT_SPEC`, //! `FLOWAPI_CLIENT_CONFIG` and `FLOWAPI_CLIENT_OUT` name them (`-- --ignored generate`). diff --git a/crates/flowapi-sdk/tests/client/auth.mjs b/crates/flowapi-sdk/tests/client/auth.mjs index 8bb390a..e496b6f 100644 --- a/crates/flowapi-sdk/tests/client/auth.mjs +++ b/crates/flowapi-sdk/tests/client/auth.mjs @@ -29,6 +29,7 @@ async function clean(f) { export function tests(built) { const { SdkError } = built.auth return [ + // req: rfc6750.2.1.should-clients-make-authenticated-requests-bearer-token — Bearer t in the Authorization header ['an API key in a header, else a bearer token: the first alternative that can be met', () => clean(async () => { const fetch = stub(() => reply(200, { id: 'p1', name: 'Rex' })) await new built.shop.Shop({ fetch, apiKeyAuth: 'k', bearerAuth: 't' }).pets.retrieve({ path: { pet_id: 'p1' } }) @@ -43,6 +44,7 @@ export function tests(built) { assert.equal(fetch.calls[0].url, 'https://auth.example/v2/query?q=x&api_key=q%20k') assert.equal(fetch.calls[1].headers.cookie, 'theme=dark; session=s1') })], + // req: rfc7617.2.2.may-client-preemptively-send-corresponding-authorization-header — Basic sent with the first request, no challenge awaited ['HTTP basic: the UTF-8 pair in base64, from the option or the variable', () => clean(async () => { const fetch = stub(ok) await client(built, fetch, { basic: { username: 'jürgen', password: 'p:ß' } }).checks.basic() @@ -61,7 +63,8 @@ export function tests(built) { assert.ok(fetch.calls[2].url.endsWith('/both?api_key=k')) const e = await rejection(client(built, fetch, { token: 't' }).checks.both()) assert.ok(e instanceof SdkError, String(e)) - assert.match(e.message, /`GET \/both` needs a credential: set `queryKey` or AUTH_QUERY_KEY and `token` or AUTH_TOKEN/) + assert.match(e.message, /`GET \/both` needs a credential: set `queryKey` or AUTH_QUERY_KEY$/) + assert.ok(e instanceof built.auth.CredentialError && e.schemes.includes('QueryKey'), String(e)) assert.equal(fetch.calls.length, 3) })], ['security: [] sends nothing, whatever the client holds', () => clean(async () => { @@ -70,6 +73,7 @@ export function tests(built) { assert.equal(fetch.calls[0].url, 'https://auth.example/v2/open') assert.deepEqual(fetch.calls[0].headers, {}) })], + // req: rfc6750.2.1.should-clients-make-authenticated-requests-bearer-token — the OAuth 2.0 token sent as Bearer in the Authorization header ['an OAuth 2.0 token is a bearer token; a function is asked for each request', () => clean(async () => { const fetch = stub(ok) let n = 0 @@ -89,6 +93,8 @@ export function tests(built) { assert.equal(fetch.calls[0].headers.authorization, 'Bearer mine') assert.ok(fetch.calls[1].url.endsWith('/both?api_key=mine')) })], + // req: oas-3.0.server-variable-object.default — {version} read as its default, v2 + // req: oas-3.0.server-variable-object.default.shall-default-value-use-substitution-sent-alternate — no value given: https://auth.example/v2 ['an operation\'s own servers; a server variable\'s default; a base URL given goes over both', () => clean(async () => { const fetch = stub(ok) await client(built, fetch).checks.elsewhere() diff --git a/crates/flowapi-sdk/tests/client/auth/issues.txt b/crates/flowapi-sdk/tests/client/auth/issues.txt index e69de29..f57eee4 100644 --- a/crates/flowapi-sdk/tests/client/auth/issues.txt +++ b/crates/flowapi-sdk/tests/client/auth/issues.txt @@ -0,0 +1,4 @@ +warning[config.auth.env]: `CookieKey` names no environment variable: the client sends it only when given its option + at flowapi-sdk.yml:10:3 (/auth/CookieKey) +warning[config.auth.env]: `Oauth` names no environment variable: the client sends it only when given its option + at flowapi-sdk.yml:13:3 (/auth/Oauth) diff --git a/crates/flowapi-sdk/tests/client/auth/src/api.ts b/crates/flowapi-sdk/tests/client/auth/src/api.ts index a3d96a4..6714a5b 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/api.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/api.ts @@ -324,10 +324,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -341,6 +342,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -353,7 +355,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -378,6 +380,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -423,30 +438,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -481,6 +481,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -511,51 +599,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -571,7 +698,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -587,53 +714,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting @@ -1021,15 +1162,17 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "QueryKey": { type: "apiKey", in: "query", name: "api_key" }, "CookieKey": { type: "apiKey", in: "cookie", name: "session" }, "Basic": { type: "http", scheme: "basic" }, "Token": { type: "http", scheme: "bearer", bearerFormat: "JWT" }, - "Oauth": { type: "oauth2", flows: ["clientCredentials"] }, + "Oauth": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://auth.example/token", scopes: ["read"] } }, } as const; /** @@ -1037,9 +1180,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { byQuery: { diff --git a/crates/flowapi-sdk/tests/client/auth/src/client.ts b/crates/flowapi-sdk/tests/client/auth/src/client.ts index 70204b9..8e1af45 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/client.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/client.ts @@ -22,19 +22,22 @@ const $settings: $core.Settings = { /** The options of a `AuthClient`: the runtime's, and a credential for each security scheme it sends. */ export type AuthClientOptions = $core.ClientOptions & { - /** The credential of the security scheme `QueryKey`, else `AUTH_QUERY_KEY`; `null` reads no variable. */ + /** The credential of the security scheme `QueryKey`: the key, else `AUTH_QUERY_KEY`; `null` reads no variable. */ queryKey?: $core.Credential | null | undefined; - /** The credential of the security scheme `CookieKey`; `null` reads no variable. */ + /** The credential of the security scheme `CookieKey`: the key; `null` reads no variable. */ cookieKey?: $core.Credential | null | undefined; - /** The credential of the security scheme `Basic`, else `AUTH_BASIC`; `null` reads no variable. */ + /** The credential of the security scheme `Basic`: an HTTP basic user-id and password, else `AUTH_BASIC`; `null` reads no variable. */ basic?: $core.BasicCredential | null | undefined; - /** The credential of the security scheme `Token`, else `AUTH_TOKEN`; `null` reads no variable. */ + /** The credential of the security scheme `Token`: the token, else `AUTH_TOKEN`; `null` reads no variable. */ token?: $core.Credential | null | undefined; - /** The credential of the security scheme `Oauth`; `null` reads no variable. */ - oauth?: $core.Credential | null | undefined; + /** The credential of the security scheme `Oauth`: a token, or the client's id and secret to request one with; `null` reads no variable. */ + oauth?: $core.Credential | $core.ClientCredentials | null | undefined; + /** Values of the servers' variables, over their defaults. */ + serverVariables?: { "version"?: string | undefined } | undefined; }; -/** The API's client: a member for each resource of the config. */ +/** The API's client: a member for each resource (`client.checks`), and `request` for a call no + * operation describes. */ export class AuthClient { readonly #core: $core.Core; readonly #options: AuthClientOptions; diff --git a/crates/flowapi-sdk/tests/client/auth/src/index.ts b/crates/flowapi-sdk/tests/client/auth/src/index.ts index 4bb40bb..6ab5f7a 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/index.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/index.ts @@ -10,26 +10,36 @@ export { AuthenticationError, BadRequestError, type BasicCredential, + type BasicPair, + type ClientCredentials, ConflictError, type Credential, + CredentialError, CrossOriginRedirectError, + type Data, type Fetch, type FetchResponse, type HeadersInput, + type Input, + InsecureCredentialError, InternalServerError, + type ItemOf, type LogLevel, type Logger, NotFoundError, + type Outcome, Page, PagePromise, PermissionDeniedError, type QueryInput, RateLimitError, + type RawRequest, type RequestOptions, RequestTimeoutError, SdkError, type ServerSentEvent, Stream, + TokenError, UnprocessableEntityError, } from "./core/index.js"; export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/auth/src/resources/checks.ts b/crates/flowapi-sdk/tests/client/auth/src/resources/checks.ts index 100fd76..d786b73 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/resources/checks.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/resources/checks.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `checks`. */ +/** The methods of `client.checks`. */ export class Checks { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/auth/src/resources/default.ts b/crates/flowapi-sdk/tests/client/auth/src/resources/default.ts index 211641b..33a146c 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/resources/default.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/resources/default.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `default`. */ +/** The methods of `client.default`. */ export class Default { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/auth/src/resources/outer.ts b/crates/flowapi-sdk/tests/client/auth/src/resources/outer.ts index e9f0a1c..d6578ad 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/resources/outer.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/resources/outer.ts @@ -4,7 +4,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; import { Middle as $Middle } from "./outer/middle.js"; -/** The resource `outer`. */ +/** The methods of `client.outer`. */ export class Outer { readonly #core: $core.Core; readonly middle: $Middle; diff --git a/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle.ts b/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle.ts index d5e38fa..de07046 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle.ts @@ -4,7 +4,7 @@ import * as $api from "../../api.js"; import * as $core from "../../core/index.js"; import { Inner as $Inner } from "./middle/inner.js"; -/** The resource `outer.middle`. */ +/** The methods of `client.outer.middle`. */ export class Middle { readonly #core: $core.Core; readonly inner: $Inner; diff --git a/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle/inner.ts b/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle/inner.ts index abe21c8..c780eab 100644 --- a/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle/inner.ts +++ b/crates/flowapi-sdk/tests/client/auth/src/resources/outer/middle/inner.ts @@ -3,7 +3,7 @@ import * as $api from "../../../api.js"; import * as $core from "../../../core/index.js"; -/** The resource `outer.middle.inner`. */ +/** The methods of `client.outer.middle.inner`. */ export class Inner { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/edge/flowapi-sdk.yml b/crates/flowapi-sdk/tests/client/edge/flowapi-sdk.yml new file mode 100644 index 0000000..ddb3238 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/edge/flowapi-sdk.yml @@ -0,0 +1,12 @@ +# OpenAPI 3.1's servers as the client uses them: variables, one with an `enum`, and relative URLs +# resolved against where the description is served. No retries are set: the default, one. The +# description declares no security on purpose, and `security: []` says the API takes none. +version: 1 +spec: spec.json +package: { name: edge-sdk, client: Edge, license: MIT } +security: [] +resources: + zones: + methods: + status: status + near: near diff --git a/crates/flowapi-sdk/tests/client/edge/issues.txt b/crates/flowapi-sdk/tests/client/edge/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/client/edge/spec.json b/crates/flowapi-sdk/tests/client/edge/spec.json new file mode 100644 index 0000000..5ca82fb --- /dev/null +++ b/crates/flowapi-sdk/tests/client/edge/spec.json @@ -0,0 +1,15 @@ +{ + "openapi": "3.1.1", + "info": { "title": "Edge", "version": "1" }, + "servers": [ + { "url": "https://{zone}.edge.example/{version}", "variables": { "zone": { "default": "a", "enum": ["a", "b"] }, "version": { "default": "v3" } } }, + { "url": "../api" } + ], + "paths": { + "/status": { "get": { "operationId": "status", "summary": "Whether the edge is up", "responses": { "200": { "description": "up", "content": { "application/json": { "schema": { "type": "object", "properties": { "up": { "type": "boolean" } } } } } } } } }, + "/near": { + "servers": [{ "url": "./near" }], + "get": { "operationId": "near", "summary": "The nearest edge, beside the description", "responses": { "200": { "description": "up", "content": { "application/json": { "schema": { "type": "object", "properties": { "up": { "type": "boolean" } } } } } } } } + } + } +} diff --git a/crates/flowapi-sdk/tests/client/edge/src/api.ts b/crates/flowapi-sdk/tests/client/edge/src/api.ts new file mode 100644 index 0000000..70a7315 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/edge/src/api.ts @@ -0,0 +1,882 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +export type Status = { + responses: { + "200": { + content: { + "application/json": { + up?: boolean; + [key: string]: unknown; + }; + }; + }; + }; +}; + +export type Near = { + responses: { + "200": { + content: { + "application/json": { + up?: boolean; + [key: string]: unknown; + }; + }; + }; + }; +}; + +export type Paths = { + "/status": { + get: Status; + }; + "/near": { + get: Near; + }; +}; + +// The SDK: for each operation, a function that writes its request and one that reads its +// response. No I/O: send the request with any HTTP client, give its answer back. + +/** + * A request to send. `path` goes after the server's base URL; `query` is the query string + * without its `?`, empty for none; `body` text, or bytes (a multipart body, bytes given). + */ +export type $Request = { + method: string; + path: string; + query: string; + headers: Record; + body?: string | Uint8Array; +}; + +/** + * A request `Request` refuses to write: a value that would change what the request means + * rather than what it says. `location` is where it goes (`path`, `query`, `querystring`, + * `header`, `cookie` or `body`), `parameter` the parameter's name as the description writes it + * (`null` for the body; a multipart part's name), `reason` why: a CR, LF or NUL in a header, a + * cookie or a part's head (it would start another header), a path segment left empty or made `.` + * or `..` (a client or a server would remove it and the one before it), NaN or an infinity (JSON + * has no number for them). In a multipart body also: `null` where a part goes (`null`), a member + * of an array of parts that is not an object (`unnamed-part`), a Blob not read yet + * (`unread-blob`: `flowapiBlob` reads it), a `"` or `\` in a name or a file name (`quote`), a + * file name that is empty, `.` or `..` (`file-name`), a part header's name that is not a token or + * is `Content-Disposition` (`header-name`), a list or a range for a part's type (`media-range`), + * a boundary RFC 2046 does not allow or that a part holds (`boundary`). + */ +export class FlowapiRequestError extends Error { + readonly location: string; + readonly parameter: string | null; + readonly reason: + | "control-character" | "empty-segment" | "dot-segment" | "non-finite" | "null" | "unnamed-part" + | "unread-blob" | "quote" | "file-name" | "header-name" | "media-range" | "boundary"; + constructor(location: string, parameter: string | null, reason: FlowapiRequestError["reason"]) { + const what = location === "body" ? "the body" + (parameter === null ? "" : `'s part \`${parameter}\``) : `the ${location} parameter \`${parameter}\``; + super(`${what}: ${reason}`); + this.name = "FlowapiRequestError"; + this.location = location; + this.parameter = parameter; + this.reason = reason; + } +} + +const $unreserved = /^[A-Za-z0-9\-._~]*$/; +const $marks = /[!'()*]/g; +const $marked = /[!'()*]/; +const $kept = /%[0-9A-Fa-f]{2}|[:/?#[\]@!$&'()*+,;=]/g; + +function $mark(c: string): string { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +} + +/** RFC 3986: every character but the unreserved ones percent-encoded, as UTF-8. */ +function $enc(s: string): string { + if ($unreserved.test(s)) return s; + const e = encodeURIComponent(s); + return $marked.test(e) ? e.replace($marks, $mark) : e; +} + +/** RFC 6570's reserved expansion: reserved characters and percent-encoded triples kept. */ +function $res(s: string): string { + if ($unreserved.test(s)) return s; + $kept.lastIndex = 0; + let out = ""; + let last = 0; + let m: RegExpExecArray | null; + while ((m = $kept.exec(s)) !== null) { + out += $enc(s.slice(last, m.index)) + m[0]; + last = $kept.lastIndex; + } + return out + $enc(s.slice(last)); +} + +/** Headers and `style: cookie` take values as they are (3.2, Appendix D). */ +function $raw(s: string): string { + return s; +} + +const $dot = /^(?:\.|%2e){1,2}$/i; + +/** A value written raw, refused if it holds a CR, LF or NUL: it would end its header. */ +function $ctl(s: string | undefined, at: string, name: string): string | undefined { + if (s !== undefined && (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0)) { + throw new FlowapiRequestError(at, name, "control-character"); + } + return s; +} + +/** A path segment a parameter wrote, refused when empty or a dot segment (`.`, `..`, a dot as + * `%2E` too, as WHATWG's URL parser reads it). `pieces`: a parameter of it keeps `/` + * (`allowReserved`), and each piece between them is held to the same. */ +function $seg(s: string, name: string, pieces: boolean): string { + // A dot segment is at most 6 characters (`%2e%2e`) and starts with `.` or `%`: a longer one + // is none, and is not read (reading a string made by `+` would flatten it). + if (!pieces && s.length > 6) return s; + if (s.length === 0) throw new FlowapiRequestError("path", name, "empty-segment"); + const c = s.charCodeAt(0); + if (!pieces && c !== 46 && c !== 37) return s; + if ($dot.test(s) || (pieces && s.split("/").some((p) => $dot.test(p)))) { + throw new FlowapiRequestError("path", name, "dot-segment"); + } + return s; +} + +/** Whether a value holds NaN or an infinity anywhere. */ +function $bad(v: unknown): boolean { + if (typeof v === "number") return v - v !== 0; + if (v === null || typeof v !== "object") return false; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) if ($bad(v[i])) return true; + return false; + } + for (const key in v) if ($bad((v as Record)[key])) return true; + return false; +} + +/** A parameter's value, refused when it holds NaN or an infinity: JSON has no number for them, + * and their text would reach the server as a string. */ +function $fin(v: T, at: string, name: string): T { + if (typeof v === "number" ? v - v !== 0 : typeof v === "object" && v !== null && $bad(v)) { + throw new FlowapiRequestError(at, name, "non-finite"); + } + return v; +} + +/** A value as text: a string as it is, a number, boolean or bigint by `String`, else JSON. */ +function $str(v: unknown): string { + switch (typeof v) { + case "string": + return v; + case "number": + case "boolean": + case "bigint": + return String(v); + default: + return JSON.stringify(v) ?? ""; + } +} + +/** + * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, + * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. + */ +function $x( + v: unknown, + name: string, + first: string, + sep: string, + named: boolean, + ifemp: string, + explode: boolean, + join: string, + enc: (s: string) => string, + at: string, + pname: string, + nest?: readonly string[], +): string | undefined { + if (v === undefined) return undefined; + if (v === null) return ifemp === "=" ? name + "=" : ""; + let out = ""; + let n = 0; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) { + const item: unknown = v[i]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); + if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); + else out += (n++ ? (explode ? sep : join) : "") + s; + } + } else if (typeof v === "object") { + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const k = enc(key); + const s = enc($str(item)); + if (explode) out += (n++ ? sep : "") + k + (s === "" && named ? ifemp : "=" + s); + else out += (n++ ? join : "") + k + join + s; + } + } else { + if (typeof v === "number" && v - v !== 0) throw new FlowapiRequestError(at, pname, "non-finite"); + const s = enc($str(v)); + return first + (named ? name + (s === "" ? ifemp : "=" + s) : s); + } + if (n === 0) return undefined; + return first + (named && !explode ? name + "=" + out : out); +} + +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + +/** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an + * array's items repeat their key. */ +function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { + if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined; + const out = $members(v as Record, name, enc, ""); + return out === "" ? undefined : out; +} + +function $members(v: Record, path: string, enc: (s: string) => string, acc: string): string { + for (const key in v) { + if (!Object.prototype.hasOwnProperty.call(v, key)) continue; + const item = v[key]; + if (item === null || item === undefined) continue; + const at = path + "%5B" + enc(key) + "%5D"; + if (Array.isArray(item)) { + for (let i = 0; i < item.length; i++) { + const one: unknown = item[i]; + if (one !== null && one !== undefined) acc += (acc === "" ? "" : "&") + at + "=" + enc($str(one)); + } + } else if (typeof item === "object") { + acc = $members(item as Record, at, enc, acc); + } else { + acc += (acc === "" ? "" : "&") + at + "=" + enc($str(item)); + } + } + return acc; +} + +/** `s` added to a query string or a cookie header, after `sep`. */ +function $add(acc: string, s: string | undefined, sep: string): string { + return s === undefined ? acc : acc === "" ? s : acc + sep + s; +} + +/** The media type without its parameters, in lower case. */ +function $bare(type: string): string { + const semi = type.indexOf(";"); + return (semi < 0 ? type : type.slice(0, semi)).trim().toLowerCase(); +} + +/** `application/json` and every `+json` type (RFC 6839). */ +function $json(type: string): boolean { + const bare = $bare(type); + return bare === "application/json" || bare.endsWith("+json"); +} + +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { + if (v instanceof Uint8Array) return v; + if (!$json(type)) { + if ($bare(type) === "application/x-www-form-urlencoded") { + if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); + return $form(v, enc); + } + if (typeof v === "string") return v; + } + // `JSON.stringify` writes NaN and the infinities as `null`: with no `null` in the text there is + // none, and the value is walked only when there is one. + const text = JSON.stringify(v); + if (text !== undefined && text.indexOf("null") >= 0 && $bad(v)) { + throw new FlowapiRequestError("body", null, "non-finite"); + } + return text; +} + +/** A parameter with `content`: its value as its media type's text, then written as a string. */ +function $content(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + return $json(type) ? JSON.stringify(v) : $str(v); +} + +/** `in: querystring`: the whole query string, a form as one, any other type percent-encoded. */ +function $qs(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + if ($bare(type) === "application/x-www-form-urlencoded") return $form(v); + return $enc($json(type) ? JSON.stringify(v) : $str(v)); +} + +/** A header set when it has a value; a CR, LF or NUL in it is refused (it would end the header). */ +function $set(headers: Record, name: string, s: string | undefined): void { + if (s === undefined) return; + if (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0) { + throw new FlowapiRequestError("header", name, "control-character"); + } + headers[name] = s; +} + +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + +/** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's + * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or + * `flowapiBlob`. */ +export class FlowapiFile { + readonly data: Uint8Array; + readonly name: string | undefined; + readonly type: string | undefined; + constructor(data: Uint8Array, name: string | undefined, type: string | undefined) { + this.data = data; + this.name = name; + this.type = type; + } +} + +/** A file from bytes, or from text as its UTF-8, with the name and the type to send it as. */ +export function flowapiFile(data: Uint8Array | string, name?: string, type?: string): FlowapiFile { + return new FlowapiFile(typeof data === "string" ? $bytes(data) : data, name, type); +} + +/** What `flowapiBlob` reads of a `Blob` or a `File`, typed here so the output type-checks + * without the DOM's declarations. */ +export type $Blob = { readonly type: string; readonly name?: string; arrayBuffer(): Promise }; + +/** A `Blob` or a `File` read into a `FlowapiFile`: its bytes, `name` or else a File's own, `type` + * or else the Blob's. The one step that waits: `Request` takes bytes and stays synchronous. */ +export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); +} + +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; +}; + +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + +/** A `multipart/form-data` value as `Request` takes it: a string member may also be a file + * (the types cannot tell `format: binary` from text), an array member's items one part each. */ +type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; +type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; +type $Fields = T extends object ? { [K in keyof T]: $Member } : T; +export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; + +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; + +/** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ +function $put(request: $Request, body: $Given): void { + const v = body.value; + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); + request.headers["content-type"] = type; + request.body = bytes; + return; + } + request.headers["content-type"] = body.contentType; + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; +} + +/** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ +type $Part = { head: string; data: Uint8Array }; + +let $encoder: { encode(text: string): Uint8Array } | undefined; + +/** Text as UTF-8 bytes. */ +function $bytes(text: string): Uint8Array { + $encoder ??= new (globalThis as unknown as $Coders).TextEncoder(); + return $encoder.encode(text); +} + +const $breaks = /[\r\n\0]/; +const $quotes = /["\\]/; +const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes + * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a + * receiver could read another name. */ +function $safe(s: string, part: string | null, quoted: boolean): string { + if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); + if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); + return s; +} + +/** A file's name as its part's `filename`: its last path segment (a sender's directories are not + * the receiver's), refused when that is empty, `.` or `..`, and when the name holds a CR, LF or + * NUL anywhere (cut off with a directory, it would still be meant). */ +function $filename(name: string, part: string): string { + $safe(name, part, false); + const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1); + if (base === "" || base === "." || base === "..") throw new FlowapiRequestError("body", part, "file-name"); + return $safe(base, part, true); +} + +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { + if (v === undefined) return; + $safe(name, name, true); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); +} + +/** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's + * `blob` for a name not given, `application/octet-stream` for a type not given), strings, + * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); + // Bytes in any other view are the same bytes. + if (v instanceof ArrayBuffer) v = new Uint8Array(v); + else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; + let type = e?.contentType; + let data: Uint8Array; + if (v instanceof FlowapiFile || v instanceof Uint8Array) { + const file = v instanceof FlowapiFile ? v : undefined; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; + type = file?.type ?? type ?? "application/octet-stream"; + data = file?.data ?? (v as Uint8Array); + } else if ($unread(v)) { + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); + } else { + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); + type ??= typeof v === "object" ? "application/json" : undefined; + // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); + data = typeof s === "string" ? $bytes(s) : s; + } + if (type !== undefined) { + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); + } + const headers = e?.headers ?? {}; + for (const key of Object.keys(headers)) { + const value = headers[key]; + const lower = key.toLowerCase(); + if (value === undefined || lower === "content-type") continue; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); + } + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); +} + +/** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting + * (`flowapiBlob`), and as JSON it would be `{}`. */ +function $unread(v: unknown): boolean { + return typeof v === "object" && v !== null && typeof (v as { arrayBuffer?: unknown }).arrayBuffer === "function"; +} + +const $bchars = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; + +/** Whether `needle` occurs in `data`. */ +function $holds(data: Uint8Array, needle: Uint8Array): boolean { + const first = needle[0] ?? 0; + for (let i = data.indexOf(first); i >= 0 && i + needle.length <= data.length; i = data.indexOf(first, i + 1)) { + let j = 1; + while (j < needle.length && data[i + j] === needle[j]) j++; + if (j === needle.length) return true; + } + return false; +} + +/** Whether a boundary occurs in any part: a delimiter in a part would end it there. */ +function $collides(parts: $Part[], boundary: string): boolean { + const b = $bytes(boundary); + return parts.some((p) => p.head.indexOf(boundary) >= 0 || $holds(p.data, b)); +} + +/** A boundary of 128 random bits from `globalThis.crypto`, so no content can be made to hold it. */ +function $random(): string { + const c = (globalThis as unknown as { crypto?: { getRandomValues(b: Uint8Array): Uint8Array } }).crypto; + if (c === undefined) throw new Error("flowapi: no globalThis.crypto to draw a multipart boundary from; give one: `multipart/form-data; boundary=...`"); + let s = "flowapi-"; + for (const x of c.getRandomValues(new Uint8Array(16))) s += (x < 16 ? "0" : "") + x.toString(16); + return s; +} + +/** The parts written with a boundary (RFC 2046, 5.1.1; RFC 7578): the one the content type + * gives (`boundary=`), refused when RFC 2046 does not allow it or a part holds it, or one drawn + * at random and added to the content type, drawn again while a part holds it. */ +function $multipart(contentType: string, parts: $Part[]): [string, Uint8Array] { + const given = /;\s*boundary\s*=\s*(?:"([^"]*)"|([^;\s]*))/i.exec(contentType); + let boundary: string; + let type = contentType; + if (given !== null) { + boundary = given[1] ?? given[2] ?? ""; + if (!$bchars.test(boundary) || $collides(parts, boundary)) throw new FlowapiRequestError("body", null, "boundary"); + } else { + boundary = $random(); + for (let tries = 1; $collides(parts, boundary); tries++) { + if (tries === 8) throw new FlowapiRequestError("body", null, "boundary"); + boundary = $random(); + } + type += "; boundary=" + boundary; + } + const chunks: Uint8Array[] = []; + for (const p of parts) chunks.push($bytes(`--${boundary}\r\n${p.head}\r\n`), p.data, $bytes("\r\n")); + chunks.push($bytes(`--${boundary}--\r\n`)); + let size = 0; + for (const c of chunks) size += c.length; + const out = new Uint8Array(size); + let at = 0; + for (const c of chunks) { + out.set(c, at); + at += c.length; + } + return [type, out]; +} + +/** A response read: which response of the description it is (`null` for none), and its body. */ +type $Read = { response: string | null; status: number; mediaType: string | null; body: unknown }; + +/** Per response, as written: its status, its media types as written and their bare forms. */ +type $Table = readonly (readonly [string, readonly string[], readonly string[]])[]; + +/** The platform's UTF-8 coders (every browser, Node, Deno and Bun has them), looked up on + * `globalThis` so the output type-checks without the DOM's or Node's declarations. */ +type $Coders = { + TextDecoder: new (label: string, options: { fatal: boolean; ignoreBOM: boolean }) => { + decode(bytes: Uint8Array): string; + }; + TextEncoder: new () => { encode(text: string): Uint8Array }; +}; + +let $decoder: { decode(bytes: Uint8Array): string } | undefined; + +/** Bytes as UTF-8 text, a byte order mark kept as the character; `null` when they are not + * UTF-8 (the Rust SDK refuses them too, where `Response.text()` would replace them). */ +function $utf8(bytes: Uint8Array): string | null { + $decoder ??= new (globalThis as unknown as $Coders).TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + try { + return $decoder.decode(bytes); + } catch { + return null; + } +} + +/** A `text/*` type (a JSON one is read as JSON first). */ +function $text(bare: string): boolean { + return bare.startsWith("text/"); +} + +/** + * Whether `Response` keeps a body of this `Content-Type` as bytes: any type but JSON and + * `text/*`, and a body with none. Read such a body with `arrayBuffer()`, the others with + * `text()`; bytes are always safe to give, as they are decoded where the type is text. + */ +export function flowapiReadsBytes(contentType: string | null | undefined): boolean { + if (contentType === null || contentType === undefined) return true; + return !$json(contentType) && !$text($bare(contentType)); +} + +/** A header, its name compared without case. */ +function $header(headers: Record, name: string): string | null { + const direct = headers[name]; + if (direct !== undefined) return direct; + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === name) return headers[key] ?? null; + } + return null; +} + +/** + * The response a status picks (its code, then its range `NXX`, then `default`), the media type + * the `Content-Type` picks (exact, then `type/*`, then `*\/*`), and the body read by the type + * sent: JSON parsed, `text/*` the text, any other the bytes (a string given for it encoded as + * UTF-8: its bytes were lost before). Bytes given for JSON or text are decoded as UTF-8. A + * status or a media type the description does not name, and a JSON or text body that is not + * UTF-8 or not JSON, read as `response: null` with the body as given. + */ +function $read(table: $Table, status: number, headers: Record, body: string | Uint8Array): $Read { + const code = String(status); + const range = code.charAt(0) + "XX"; + let hit: (typeof table)[number] | undefined; + for (const r of table) if (r[0] === code) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0].toUpperCase() === range) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0] === "default") hit = hit ?? r; + const type = $header(headers, "content-type"); + if (hit === undefined) return { response: null, status, mediaType: type, body }; + if (hit[1].length === 0) return { response: hit[0], status, mediaType: null, body }; + if (type === null) return { response: null, status, mediaType: null, body }; + const bare = $bare(type); + const slash = bare.indexOf("/"); + const major = bare.slice(0, slash + 1) + "*"; + let at = hit[2].indexOf(bare); + if (at < 0) at = hit[2].indexOf(major); + if (at < 0) at = hit[2].indexOf("*/*"); + const written = hit[1][at]; + if (written === undefined) return { response: null, status, mediaType: type, body }; + const json = $json(type); + if (!json && !$text(bare)) { + const bytes = typeof body === "string" ? $bytes(body) : body; + return { response: hit[0], status, mediaType: written, body: bytes }; + } + const text = typeof body === "string" ? body : $utf8(body); + if (text === null) return { response: null, status, mediaType: type, body }; + if (!json) return { response: hit[0], status, mediaType: written, body: text }; + // An empty or broken JSON body is not the response described: the body as given, unnamed. A + // leading byte order mark is skipped (RFC 8259, 8.1), as `JSON.parse` would refuse it. + try { + return { response: hit[0], status, mediaType: written, body: JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) }; + } catch { + return { response: null, status, mediaType: type, body }; + } +} + +export function statusRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/status", query: "", headers }; + return request; +} + +const $statusResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function statusResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Status["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($statusResponse, status, headers, body) as ReturnType; +} + +export function nearRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/near", query: "", headers }; + return request; +} + +const $nearResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function nearResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Near["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($nearResponse, status, headers, body) as ReturnType; +} + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://{zone}.edge.example/{version}", variables: { "zone": { default: "a", enum: ["a", "b"] }, "version": { default: "v3" } } }, + { url: "../api" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + status: { + method: "GET", + path: "/status", + security: [], + responses: { "200": { content: { "application/json": "json" } } }, + request: statusRequest, + response: statusResponse, + }, + near: { + method: "GET", + path: "/near", + servers: [{ url: "./near" }], + security: [], + responses: { "200": { content: { "application/json": "json" } } }, + request: nearRequest, + response: nearResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/client/edge/src/client.ts b/crates/flowapi-sdk/tests/client/edge/src/client.ts new file mode 100644 index 0000000..1529e23 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/edge/src/client.ts @@ -0,0 +1,68 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "./api.js"; +import * as $core from "./core/index.js"; +import { Zones as $Zones } from "./resources/zones.js"; + +/** What the config decides of the client. */ +const $settings: $core.Settings = { + client: "Edge", + environments: { }, + logEnv: "EDGE_LOG", + auth: { }, + timeout: 60000, + maxRetries: 1, + maxRetryDelay: 60000, + servers: $api.flowapiServers, + schemes: $api.flowapiSecuritySchemes, + readsBytes: $api.flowapiReadsBytes, +}; + +/** The options of a `Edge`: the runtime's, and a credential for each security scheme it sends. */ +export type EdgeOptions = $core.ClientOptions & { + /** Values of the servers' variables, over their defaults. */ + serverVariables?: { "zone"?: "a" | "b" | undefined; "version"?: string | undefined } | undefined; +}; + +/** The API's client: a member for each resource (`client.zones`), and `request` for a call no + * operation describes. */ +export class Edge { + readonly #core: $core.Core; + readonly #options: EdgeOptions; + readonly zones: $Zones; + + constructor(options: EdgeOptions = {}) { + this.#options = { ...options }; + this.#core = new $core.Core($settings, options); + this.zones = new $Zones(this.#core); + } + + /** The base URL calls go to, unless an operation has servers of its own. */ + get baseURL(): string | null { + return this.#core.baseURL; + } + + /** Milliseconds an attempt may take, its body read; `null` for no limit. */ + get timeout(): number | null { + return this.#core.timeout; + } + + /** How many times a failed attempt is tried again. */ + get maxRetries(): number { + return this.#core.maxRetries; + } + + /** A client of the same class with these options over this one's: one given as `undefined` + * keeps this one's. */ + withOptions(options: EdgeOptions): this { + const next: Record = { ...this.#options }; + for (const [key, value] of Object.entries(options)) if (value !== undefined) next[key] = value; + return new (this.constructor as new (options: EdgeOptions) => this)(next as EdgeOptions); + } + + /** A call by method and path that no operation describes, with every credential the + * client has. */ + request(method: string, path: string, options?: $core.RawRequest): $core.ApiCall { + return $core.request(this.#core, method, path, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/edge/src/index.ts b/crates/flowapi-sdk/tests/client/edge/src/index.ts new file mode 100644 index 0000000..8756eba --- /dev/null +++ b/crates/flowapi-sdk/tests/client/edge/src/index.ts @@ -0,0 +1,45 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +export { Edge, Edge as default, type EdgeOptions } from "./client.js"; +export { + APIConnectionError, + APIConnectionTimeoutError, + APIError, + APIUserAbortError, + ApiCall, + AuthenticationError, + BadRequestError, + type BasicCredential, + type BasicPair, + type ClientCredentials, + ConflictError, + type Credential, + CredentialError, + CrossOriginRedirectError, + type Data, + type Fetch, + type FetchResponse, + type HeadersInput, + type Input, + InsecureCredentialError, + InternalServerError, + type ItemOf, + type LogLevel, + type Logger, + NotFoundError, + type Outcome, + Page, + PagePromise, + PermissionDeniedError, + type QueryInput, + RateLimitError, + type RawRequest, + type RequestOptions, + RequestTimeoutError, + SdkError, + type ServerSentEvent, + Stream, + TokenError, + UnprocessableEntityError, +} from "./core/index.js"; +export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/edge/src/resources/zones.ts b/crates/flowapi-sdk/tests/client/edge/src/resources/zones.ts new file mode 100644 index 0000000..dd26861 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/edge/src/resources/zones.ts @@ -0,0 +1,31 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.zones`. */ +export class Zones { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** + * Whether the edge is up + * + * `GET /status` + */ + status(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.status, params, options); + } + + /** + * The nearest edge, beside the description + * + * `GET /near` + */ + near(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.near, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/github/flowapi-sdk.yml b/crates/flowapi-sdk/tests/client/github/flowapi-sdk.yml new file mode 100644 index 0000000..99fa08e --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/flowapi-sdk.yml @@ -0,0 +1,31 @@ +# A description with no security schemes, as GitHub's is: the config declares the bearer token +# its API takes and makes it optional for every operation (`{}`), a method that needs none +# (`security: []`), and two schemes the description lacks for one method each: an API key in a +# header and HTTP basic read from two variables. +version: 1 +spec: spec.json +package: { name: github-like-sdk, client: GitHub, license: MIT } +auth: + Token: { type: http, scheme: bearer, env_var: GITHUB_TOKEN, description: A personal access token } + AppKey: { type: apiKey, in: header, name: X-App-Key, env_var: GITHUB_APP_KEY } + Admin: { type: http, scheme: basic, username_env_var: GITHUB_ADMIN_USER, password_env_var: GITHUB_ADMIN_PASSWORD } +security: + - Token: [] + - {} +defaults: { retries: 0 } +resources: + users: + methods: + me: users/get-authenticated + repos: + methods: + get: repos/get + meta: + methods: + get: { op: meta/get, security: [] } + apps: + methods: + hook: { op: apps/get-webhook, security: [{ AppKey: [] }] } + enterprise: + methods: + settings: { op: enterprise/get-settings, security: [{ Admin: [] }] } diff --git a/crates/flowapi-sdk/tests/client/github/issues.txt b/crates/flowapi-sdk/tests/client/github/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/client/github/spec.json b/crates/flowapi-sdk/tests/client/github/spec.json new file mode 100644 index 0000000..d4bab2e --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/spec.json @@ -0,0 +1,17 @@ +{ + "openapi": "3.0.3", + "info": { "title": "GitHub-like", "version": "1" }, + "servers": [{ "url": "https://api.github.example" }], + "paths": { + "/user": { "get": { "operationId": "users/get-authenticated", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/repos/{owner}/{repo}": { "get": { "operationId": "repos/get", "parameters": [{ "name": "owner", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "repo", "in": "path", "required": true, "schema": { "type": "string" } }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/meta": { "get": { "operationId": "meta/get", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/app/hook": { "get": { "operationId": "apps/get-webhook", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/enterprise/settings": { "get": { "operationId": "enterprise/get-settings", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } } + }, + "components": { + "responses": { + "Ok": { "description": "ok", "content": { "application/json": { "schema": { "type": "object", "properties": { "login": { "type": "string" } } } } } } + } + } +} diff --git a/crates/flowapi-sdk/tests/client/github/src/api.ts b/crates/flowapi-sdk/tests/client/github/src/api.ts new file mode 100644 index 0000000..74d67ed --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/api.ts @@ -0,0 +1,1002 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +export type UsersGetAuthenticated = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type ReposGet = { + parameters: { + path: { + owner: string; + repo: string; + }; + }; + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type MetaGet = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type AppsGetWebhook = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type EnterpriseGetSettings = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Paths = { + "/user": { + get: UsersGetAuthenticated; + }; + "/repos/{owner}/{repo}": { + get: ReposGet; + }; + "/meta": { + get: MetaGet; + }; + "/app/hook": { + get: AppsGetWebhook; + }; + "/enterprise/settings": { + get: EnterpriseGetSettings; + }; +}; + +export type ResponsesOkApplicationJson = { + login?: string; + [key: string]: unknown; +}; + +// The SDK: for each operation, a function that writes its request and one that reads its +// response. No I/O: send the request with any HTTP client, give its answer back. + +/** + * A request to send. `path` goes after the server's base URL; `query` is the query string + * without its `?`, empty for none; `body` text, or bytes (a multipart body, bytes given). + */ +export type $Request = { + method: string; + path: string; + query: string; + headers: Record; + body?: string | Uint8Array; +}; + +/** + * A request `Request` refuses to write: a value that would change what the request means + * rather than what it says. `location` is where it goes (`path`, `query`, `querystring`, + * `header`, `cookie` or `body`), `parameter` the parameter's name as the description writes it + * (`null` for the body; a multipart part's name), `reason` why: a CR, LF or NUL in a header, a + * cookie or a part's head (it would start another header), a path segment left empty or made `.` + * or `..` (a client or a server would remove it and the one before it), NaN or an infinity (JSON + * has no number for them). In a multipart body also: `null` where a part goes (`null`), a member + * of an array of parts that is not an object (`unnamed-part`), a Blob not read yet + * (`unread-blob`: `flowapiBlob` reads it), a `"` or `\` in a name or a file name (`quote`), a + * file name that is empty, `.` or `..` (`file-name`), a part header's name that is not a token or + * is `Content-Disposition` (`header-name`), a list or a range for a part's type (`media-range`), + * a boundary RFC 2046 does not allow or that a part holds (`boundary`). + */ +export class FlowapiRequestError extends Error { + readonly location: string; + readonly parameter: string | null; + readonly reason: + | "control-character" | "empty-segment" | "dot-segment" | "non-finite" | "null" | "unnamed-part" + | "unread-blob" | "quote" | "file-name" | "header-name" | "media-range" | "boundary"; + constructor(location: string, parameter: string | null, reason: FlowapiRequestError["reason"]) { + const what = location === "body" ? "the body" + (parameter === null ? "" : `'s part \`${parameter}\``) : `the ${location} parameter \`${parameter}\``; + super(`${what}: ${reason}`); + this.name = "FlowapiRequestError"; + this.location = location; + this.parameter = parameter; + this.reason = reason; + } +} + +const $unreserved = /^[A-Za-z0-9\-._~]*$/; +const $marks = /[!'()*]/g; +const $marked = /[!'()*]/; +const $kept = /%[0-9A-Fa-f]{2}|[:/?#[\]@!$&'()*+,;=]/g; + +function $mark(c: string): string { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +} + +/** RFC 3986: every character but the unreserved ones percent-encoded, as UTF-8. */ +function $enc(s: string): string { + if ($unreserved.test(s)) return s; + const e = encodeURIComponent(s); + return $marked.test(e) ? e.replace($marks, $mark) : e; +} + +/** RFC 6570's reserved expansion: reserved characters and percent-encoded triples kept. */ +function $res(s: string): string { + if ($unreserved.test(s)) return s; + $kept.lastIndex = 0; + let out = ""; + let last = 0; + let m: RegExpExecArray | null; + while ((m = $kept.exec(s)) !== null) { + out += $enc(s.slice(last, m.index)) + m[0]; + last = $kept.lastIndex; + } + return out + $enc(s.slice(last)); +} + +/** Headers and `style: cookie` take values as they are (3.2, Appendix D). */ +function $raw(s: string): string { + return s; +} + +const $dot = /^(?:\.|%2e){1,2}$/i; + +/** A value written raw, refused if it holds a CR, LF or NUL: it would end its header. */ +function $ctl(s: string | undefined, at: string, name: string): string | undefined { + if (s !== undefined && (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0)) { + throw new FlowapiRequestError(at, name, "control-character"); + } + return s; +} + +/** A path segment a parameter wrote, refused when empty or a dot segment (`.`, `..`, a dot as + * `%2E` too, as WHATWG's URL parser reads it). `pieces`: a parameter of it keeps `/` + * (`allowReserved`), and each piece between them is held to the same. */ +function $seg(s: string, name: string, pieces: boolean): string { + // A dot segment is at most 6 characters (`%2e%2e`) and starts with `.` or `%`: a longer one + // is none, and is not read (reading a string made by `+` would flatten it). + if (!pieces && s.length > 6) return s; + if (s.length === 0) throw new FlowapiRequestError("path", name, "empty-segment"); + const c = s.charCodeAt(0); + if (!pieces && c !== 46 && c !== 37) return s; + if ($dot.test(s) || (pieces && s.split("/").some((p) => $dot.test(p)))) { + throw new FlowapiRequestError("path", name, "dot-segment"); + } + return s; +} + +/** Whether a value holds NaN or an infinity anywhere. */ +function $bad(v: unknown): boolean { + if (typeof v === "number") return v - v !== 0; + if (v === null || typeof v !== "object") return false; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) if ($bad(v[i])) return true; + return false; + } + for (const key in v) if ($bad((v as Record)[key])) return true; + return false; +} + +/** A parameter's value, refused when it holds NaN or an infinity: JSON has no number for them, + * and their text would reach the server as a string. */ +function $fin(v: T, at: string, name: string): T { + if (typeof v === "number" ? v - v !== 0 : typeof v === "object" && v !== null && $bad(v)) { + throw new FlowapiRequestError(at, name, "non-finite"); + } + return v; +} + +/** A value as text: a string as it is, a number, boolean or bigint by `String`, else JSON. */ +function $str(v: unknown): string { + switch (typeof v) { + case "string": + return v; + case "number": + case "boolean": + case "bigint": + return String(v); + default: + return JSON.stringify(v) ?? ""; + } +} + +/** + * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, + * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. + */ +function $x( + v: unknown, + name: string, + first: string, + sep: string, + named: boolean, + ifemp: string, + explode: boolean, + join: string, + enc: (s: string) => string, + at: string, + pname: string, + nest?: readonly string[], +): string | undefined { + if (v === undefined) return undefined; + if (v === null) return ifemp === "=" ? name + "=" : ""; + let out = ""; + let n = 0; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) { + const item: unknown = v[i]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); + if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); + else out += (n++ ? (explode ? sep : join) : "") + s; + } + } else if (typeof v === "object") { + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const k = enc(key); + const s = enc($str(item)); + if (explode) out += (n++ ? sep : "") + k + (s === "" && named ? ifemp : "=" + s); + else out += (n++ ? join : "") + k + join + s; + } + } else { + if (typeof v === "number" && v - v !== 0) throw new FlowapiRequestError(at, pname, "non-finite"); + const s = enc($str(v)); + return first + (named ? name + (s === "" ? ifemp : "=" + s) : s); + } + if (n === 0) return undefined; + return first + (named && !explode ? name + "=" + out : out); +} + +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + +/** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an + * array's items repeat their key. */ +function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { + if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined; + const out = $members(v as Record, name, enc, ""); + return out === "" ? undefined : out; +} + +function $members(v: Record, path: string, enc: (s: string) => string, acc: string): string { + for (const key in v) { + if (!Object.prototype.hasOwnProperty.call(v, key)) continue; + const item = v[key]; + if (item === null || item === undefined) continue; + const at = path + "%5B" + enc(key) + "%5D"; + if (Array.isArray(item)) { + for (let i = 0; i < item.length; i++) { + const one: unknown = item[i]; + if (one !== null && one !== undefined) acc += (acc === "" ? "" : "&") + at + "=" + enc($str(one)); + } + } else if (typeof item === "object") { + acc = $members(item as Record, at, enc, acc); + } else { + acc += (acc === "" ? "" : "&") + at + "=" + enc($str(item)); + } + } + return acc; +} + +/** `s` added to a query string or a cookie header, after `sep`. */ +function $add(acc: string, s: string | undefined, sep: string): string { + return s === undefined ? acc : acc === "" ? s : acc + sep + s; +} + +/** The media type without its parameters, in lower case. */ +function $bare(type: string): string { + const semi = type.indexOf(";"); + return (semi < 0 ? type : type.slice(0, semi)).trim().toLowerCase(); +} + +/** `application/json` and every `+json` type (RFC 6839). */ +function $json(type: string): boolean { + const bare = $bare(type); + return bare === "application/json" || bare.endsWith("+json"); +} + +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { + if (v instanceof Uint8Array) return v; + if (!$json(type)) { + if ($bare(type) === "application/x-www-form-urlencoded") { + if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); + return $form(v, enc); + } + if (typeof v === "string") return v; + } + // `JSON.stringify` writes NaN and the infinities as `null`: with no `null` in the text there is + // none, and the value is walked only when there is one. + const text = JSON.stringify(v); + if (text !== undefined && text.indexOf("null") >= 0 && $bad(v)) { + throw new FlowapiRequestError("body", null, "non-finite"); + } + return text; +} + +/** A parameter with `content`: its value as its media type's text, then written as a string. */ +function $content(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + return $json(type) ? JSON.stringify(v) : $str(v); +} + +/** `in: querystring`: the whole query string, a form as one, any other type percent-encoded. */ +function $qs(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + if ($bare(type) === "application/x-www-form-urlencoded") return $form(v); + return $enc($json(type) ? JSON.stringify(v) : $str(v)); +} + +/** A header set when it has a value; a CR, LF or NUL in it is refused (it would end the header). */ +function $set(headers: Record, name: string, s: string | undefined): void { + if (s === undefined) return; + if (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0) { + throw new FlowapiRequestError("header", name, "control-character"); + } + headers[name] = s; +} + +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + +/** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's + * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or + * `flowapiBlob`. */ +export class FlowapiFile { + readonly data: Uint8Array; + readonly name: string | undefined; + readonly type: string | undefined; + constructor(data: Uint8Array, name: string | undefined, type: string | undefined) { + this.data = data; + this.name = name; + this.type = type; + } +} + +/** A file from bytes, or from text as its UTF-8, with the name and the type to send it as. */ +export function flowapiFile(data: Uint8Array | string, name?: string, type?: string): FlowapiFile { + return new FlowapiFile(typeof data === "string" ? $bytes(data) : data, name, type); +} + +/** What `flowapiBlob` reads of a `Blob` or a `File`, typed here so the output type-checks + * without the DOM's declarations. */ +export type $Blob = { readonly type: string; readonly name?: string; arrayBuffer(): Promise }; + +/** A `Blob` or a `File` read into a `FlowapiFile`: its bytes, `name` or else a File's own, `type` + * or else the Blob's. The one step that waits: `Request` takes bytes and stays synchronous. */ +export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); +} + +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; +}; + +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + +/** A `multipart/form-data` value as `Request` takes it: a string member may also be a file + * (the types cannot tell `format: binary` from text), an array member's items one part each. */ +type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; +type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; +type $Fields = T extends object ? { [K in keyof T]: $Member } : T; +export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; + +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; + +/** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ +function $put(request: $Request, body: $Given): void { + const v = body.value; + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); + request.headers["content-type"] = type; + request.body = bytes; + return; + } + request.headers["content-type"] = body.contentType; + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; +} + +/** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ +type $Part = { head: string; data: Uint8Array }; + +let $encoder: { encode(text: string): Uint8Array } | undefined; + +/** Text as UTF-8 bytes. */ +function $bytes(text: string): Uint8Array { + $encoder ??= new (globalThis as unknown as $Coders).TextEncoder(); + return $encoder.encode(text); +} + +const $breaks = /[\r\n\0]/; +const $quotes = /["\\]/; +const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes + * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a + * receiver could read another name. */ +function $safe(s: string, part: string | null, quoted: boolean): string { + if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); + if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); + return s; +} + +/** A file's name as its part's `filename`: its last path segment (a sender's directories are not + * the receiver's), refused when that is empty, `.` or `..`, and when the name holds a CR, LF or + * NUL anywhere (cut off with a directory, it would still be meant). */ +function $filename(name: string, part: string): string { + $safe(name, part, false); + const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1); + if (base === "" || base === "." || base === "..") throw new FlowapiRequestError("body", part, "file-name"); + return $safe(base, part, true); +} + +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { + if (v === undefined) return; + $safe(name, name, true); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); +} + +/** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's + * `blob` for a name not given, `application/octet-stream` for a type not given), strings, + * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); + // Bytes in any other view are the same bytes. + if (v instanceof ArrayBuffer) v = new Uint8Array(v); + else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; + let type = e?.contentType; + let data: Uint8Array; + if (v instanceof FlowapiFile || v instanceof Uint8Array) { + const file = v instanceof FlowapiFile ? v : undefined; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; + type = file?.type ?? type ?? "application/octet-stream"; + data = file?.data ?? (v as Uint8Array); + } else if ($unread(v)) { + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); + } else { + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); + type ??= typeof v === "object" ? "application/json" : undefined; + // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); + data = typeof s === "string" ? $bytes(s) : s; + } + if (type !== undefined) { + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); + } + const headers = e?.headers ?? {}; + for (const key of Object.keys(headers)) { + const value = headers[key]; + const lower = key.toLowerCase(); + if (value === undefined || lower === "content-type") continue; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); + } + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); +} + +/** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting + * (`flowapiBlob`), and as JSON it would be `{}`. */ +function $unread(v: unknown): boolean { + return typeof v === "object" && v !== null && typeof (v as { arrayBuffer?: unknown }).arrayBuffer === "function"; +} + +const $bchars = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; + +/** Whether `needle` occurs in `data`. */ +function $holds(data: Uint8Array, needle: Uint8Array): boolean { + const first = needle[0] ?? 0; + for (let i = data.indexOf(first); i >= 0 && i + needle.length <= data.length; i = data.indexOf(first, i + 1)) { + let j = 1; + while (j < needle.length && data[i + j] === needle[j]) j++; + if (j === needle.length) return true; + } + return false; +} + +/** Whether a boundary occurs in any part: a delimiter in a part would end it there. */ +function $collides(parts: $Part[], boundary: string): boolean { + const b = $bytes(boundary); + return parts.some((p) => p.head.indexOf(boundary) >= 0 || $holds(p.data, b)); +} + +/** A boundary of 128 random bits from `globalThis.crypto`, so no content can be made to hold it. */ +function $random(): string { + const c = (globalThis as unknown as { crypto?: { getRandomValues(b: Uint8Array): Uint8Array } }).crypto; + if (c === undefined) throw new Error("flowapi: no globalThis.crypto to draw a multipart boundary from; give one: `multipart/form-data; boundary=...`"); + let s = "flowapi-"; + for (const x of c.getRandomValues(new Uint8Array(16))) s += (x < 16 ? "0" : "") + x.toString(16); + return s; +} + +/** The parts written with a boundary (RFC 2046, 5.1.1; RFC 7578): the one the content type + * gives (`boundary=`), refused when RFC 2046 does not allow it or a part holds it, or one drawn + * at random and added to the content type, drawn again while a part holds it. */ +function $multipart(contentType: string, parts: $Part[]): [string, Uint8Array] { + const given = /;\s*boundary\s*=\s*(?:"([^"]*)"|([^;\s]*))/i.exec(contentType); + let boundary: string; + let type = contentType; + if (given !== null) { + boundary = given[1] ?? given[2] ?? ""; + if (!$bchars.test(boundary) || $collides(parts, boundary)) throw new FlowapiRequestError("body", null, "boundary"); + } else { + boundary = $random(); + for (let tries = 1; $collides(parts, boundary); tries++) { + if (tries === 8) throw new FlowapiRequestError("body", null, "boundary"); + boundary = $random(); + } + type += "; boundary=" + boundary; + } + const chunks: Uint8Array[] = []; + for (const p of parts) chunks.push($bytes(`--${boundary}\r\n${p.head}\r\n`), p.data, $bytes("\r\n")); + chunks.push($bytes(`--${boundary}--\r\n`)); + let size = 0; + for (const c of chunks) size += c.length; + const out = new Uint8Array(size); + let at = 0; + for (const c of chunks) { + out.set(c, at); + at += c.length; + } + return [type, out]; +} + +/** A response read: which response of the description it is (`null` for none), and its body. */ +type $Read = { response: string | null; status: number; mediaType: string | null; body: unknown }; + +/** Per response, as written: its status, its media types as written and their bare forms. */ +type $Table = readonly (readonly [string, readonly string[], readonly string[]])[]; + +/** The platform's UTF-8 coders (every browser, Node, Deno and Bun has them), looked up on + * `globalThis` so the output type-checks without the DOM's or Node's declarations. */ +type $Coders = { + TextDecoder: new (label: string, options: { fatal: boolean; ignoreBOM: boolean }) => { + decode(bytes: Uint8Array): string; + }; + TextEncoder: new () => { encode(text: string): Uint8Array }; +}; + +let $decoder: { decode(bytes: Uint8Array): string } | undefined; + +/** Bytes as UTF-8 text, a byte order mark kept as the character; `null` when they are not + * UTF-8 (the Rust SDK refuses them too, where `Response.text()` would replace them). */ +function $utf8(bytes: Uint8Array): string | null { + $decoder ??= new (globalThis as unknown as $Coders).TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + try { + return $decoder.decode(bytes); + } catch { + return null; + } +} + +/** A `text/*` type (a JSON one is read as JSON first). */ +function $text(bare: string): boolean { + return bare.startsWith("text/"); +} + +/** + * Whether `Response` keeps a body of this `Content-Type` as bytes: any type but JSON and + * `text/*`, and a body with none. Read such a body with `arrayBuffer()`, the others with + * `text()`; bytes are always safe to give, as they are decoded where the type is text. + */ +export function flowapiReadsBytes(contentType: string | null | undefined): boolean { + if (contentType === null || contentType === undefined) return true; + return !$json(contentType) && !$text($bare(contentType)); +} + +/** A header, its name compared without case. */ +function $header(headers: Record, name: string): string | null { + const direct = headers[name]; + if (direct !== undefined) return direct; + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === name) return headers[key] ?? null; + } + return null; +} + +/** + * The response a status picks (its code, then its range `NXX`, then `default`), the media type + * the `Content-Type` picks (exact, then `type/*`, then `*\/*`), and the body read by the type + * sent: JSON parsed, `text/*` the text, any other the bytes (a string given for it encoded as + * UTF-8: its bytes were lost before). Bytes given for JSON or text are decoded as UTF-8. A + * status or a media type the description does not name, and a JSON or text body that is not + * UTF-8 or not JSON, read as `response: null` with the body as given. + */ +function $read(table: $Table, status: number, headers: Record, body: string | Uint8Array): $Read { + const code = String(status); + const range = code.charAt(0) + "XX"; + let hit: (typeof table)[number] | undefined; + for (const r of table) if (r[0] === code) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0].toUpperCase() === range) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0] === "default") hit = hit ?? r; + const type = $header(headers, "content-type"); + if (hit === undefined) return { response: null, status, mediaType: type, body }; + if (hit[1].length === 0) return { response: hit[0], status, mediaType: null, body }; + if (type === null) return { response: null, status, mediaType: null, body }; + const bare = $bare(type); + const slash = bare.indexOf("/"); + const major = bare.slice(0, slash + 1) + "*"; + let at = hit[2].indexOf(bare); + if (at < 0) at = hit[2].indexOf(major); + if (at < 0) at = hit[2].indexOf("*/*"); + const written = hit[1][at]; + if (written === undefined) return { response: null, status, mediaType: type, body }; + const json = $json(type); + if (!json && !$text(bare)) { + const bytes = typeof body === "string" ? $bytes(body) : body; + return { response: hit[0], status, mediaType: written, body: bytes }; + } + const text = typeof body === "string" ? body : $utf8(body); + if (text === null) return { response: null, status, mediaType: type, body }; + if (!json) return { response: hit[0], status, mediaType: written, body: text }; + // An empty or broken JSON body is not the response described: the body as given, unnamed. A + // leading byte order mark is skipped (RFC 8259, 8.1), as `JSON.parse` would refuse it. + try { + return { response: hit[0], status, mediaType: written, body: JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) }; + } catch { + return { response: null, status, mediaType: type, body }; + } +} + +export function usersGetAuthenticatedRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/user", query: "", headers }; + return request; +} + +const $usersGetAuthenticatedResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function usersGetAuthenticatedResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: UsersGetAuthenticated["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($usersGetAuthenticatedResponse, status, headers, body) as ReturnType; +} + +export function reposGetRequest(input: NonNullable): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/repos/" + $seg(($x(input.path?.["owner"], "owner", "", ",", false, "", false, ",", $enc, "path", "owner") ?? ""), "owner", false) + "/" + $seg(($x(input.path?.["repo"], "repo", "", ",", false, "", false, ",", $enc, "path", "repo") ?? ""), "repo", false), query: "", headers }; + return request; +} + +const $reposGetResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function reposGetResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: ReposGet["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($reposGetResponse, status, headers, body) as ReturnType; +} + +export function metaGetRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/meta", query: "", headers }; + return request; +} + +const $metaGetResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function metaGetResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: MetaGet["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($metaGetResponse, status, headers, body) as ReturnType; +} + +export function appsGetWebhookRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/app/hook", query: "", headers }; + return request; +} + +const $appsGetWebhookResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function appsGetWebhookResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: AppsGetWebhook["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($appsGetWebhookResponse, status, headers, body) as ReturnType; +} + +export function enterpriseGetSettingsRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/enterprise/settings", query: "", headers }; + return request; +} + +const $enterpriseGetSettingsResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function enterpriseGetSettingsResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: EnterpriseGetSettings["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($enterpriseGetSettingsResponse, status, headers, body) as ReturnType; +} + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://api.github.example" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "Token": { type: "http", scheme: "bearer", description: "A personal access token" }, + "AppKey": { type: "apiKey", in: "header", name: "X-App-Key" }, + "Admin": { type: "http", scheme: "basic" }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + usersGetAuthenticated: { + method: "GET", + path: "/user", + security: [{ "Token": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: usersGetAuthenticatedRequest, + response: usersGetAuthenticatedResponse, + }, + reposGet: { + method: "GET", + path: "/repos/{owner}/{repo}", + security: [{ "Token": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: reposGetRequest, + response: reposGetResponse, + }, + metaGet: { + method: "GET", + path: "/meta", + security: [], + responses: { "200": { content: { "application/json": "json" } } }, + request: metaGetRequest, + response: metaGetResponse, + }, + appsGetWebhook: { + method: "GET", + path: "/app/hook", + security: [{ "AppKey": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: appsGetWebhookRequest, + response: appsGetWebhookResponse, + }, + enterpriseGetSettings: { + method: "GET", + path: "/enterprise/settings", + security: [{ "Admin": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: enterpriseGetSettingsRequest, + response: enterpriseGetSettingsResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/client/github/src/client.ts b/crates/flowapi-sdk/tests/client/github/src/client.ts new file mode 100644 index 0000000..7f08e04 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/client.ts @@ -0,0 +1,84 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "./api.js"; +import * as $core from "./core/index.js"; +import { Users as $Users } from "./resources/users.js"; +import { Repos as $Repos } from "./resources/repos.js"; +import { Meta as $Meta } from "./resources/meta.js"; +import { Apps as $Apps } from "./resources/apps.js"; +import { Enterprise as $Enterprise } from "./resources/enterprise.js"; + +/** What the config decides of the client. */ +const $settings: $core.Settings = { + client: "GitHub", + environments: { }, + logEnv: "GIT_HUB_LOG", + auth: { "Token": { option: "token", env: "GITHUB_TOKEN" }, "AppKey": { option: "appKey", env: "GITHUB_APP_KEY" }, "Admin": { option: "admin", usernameEnv: "GITHUB_ADMIN_USER", passwordEnv: "GITHUB_ADMIN_PASSWORD" } }, + timeout: 60000, + maxRetries: 0, + maxRetryDelay: 60000, + servers: $api.flowapiServers, + schemes: $api.flowapiSecuritySchemes, + readsBytes: $api.flowapiReadsBytes, +}; + +/** The options of a `GitHub`: the runtime's, and a credential for each security scheme it sends. */ +export type GitHubOptions = $core.ClientOptions & { + /** The credential of the security scheme `Token`: the token, else `GITHUB_TOKEN`; `null` reads no variable. */ + token?: $core.Credential | null | undefined; + /** The credential of the security scheme `AppKey`: the key, else `GITHUB_APP_KEY`; `null` reads no variable. */ + appKey?: $core.Credential | null | undefined; + /** The credential of the security scheme `Admin`: an HTTP basic user-id and password, else `GITHUB_ADMIN_USER`, `GITHUB_ADMIN_PASSWORD`; `null` reads no variable. */ + admin?: $core.BasicCredential | null | undefined; +}; + +/** The API's client: a member for each resource (`client.users`), and `request` for a call no + * operation describes. */ +export class GitHub { + readonly #core: $core.Core; + readonly #options: GitHubOptions; + readonly users: $Users; + readonly repos: $Repos; + readonly meta: $Meta; + readonly apps: $Apps; + readonly enterprise: $Enterprise; + + constructor(options: GitHubOptions = {}) { + this.#options = { ...options }; + this.#core = new $core.Core($settings, options); + this.users = new $Users(this.#core); + this.repos = new $Repos(this.#core); + this.meta = new $Meta(this.#core); + this.apps = new $Apps(this.#core); + this.enterprise = new $Enterprise(this.#core); + } + + /** The base URL calls go to, unless an operation has servers of its own. */ + get baseURL(): string | null { + return this.#core.baseURL; + } + + /** Milliseconds an attempt may take, its body read; `null` for no limit. */ + get timeout(): number | null { + return this.#core.timeout; + } + + /** How many times a failed attempt is tried again. */ + get maxRetries(): number { + return this.#core.maxRetries; + } + + /** A client of the same class with these options over this one's: one given as `undefined` + * keeps this one's. */ + withOptions(options: GitHubOptions): this { + const next: Record = { ...this.#options }; + for (const [key, value] of Object.entries(options)) if (value !== undefined) next[key] = value; + return new (this.constructor as new (options: GitHubOptions) => this)(next as GitHubOptions); + } + + /** A call by method and path that no operation describes, with every credential the + * client has. */ + request(method: string, path: string, options?: $core.RawRequest): $core.ApiCall { + return $core.request(this.#core, method, path, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/github/src/index.ts b/crates/flowapi-sdk/tests/client/github/src/index.ts new file mode 100644 index 0000000..12a447a --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/index.ts @@ -0,0 +1,45 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +export { GitHub, GitHub as default, type GitHubOptions } from "./client.js"; +export { + APIConnectionError, + APIConnectionTimeoutError, + APIError, + APIUserAbortError, + ApiCall, + AuthenticationError, + BadRequestError, + type BasicCredential, + type BasicPair, + type ClientCredentials, + ConflictError, + type Credential, + CredentialError, + CrossOriginRedirectError, + type Data, + type Fetch, + type FetchResponse, + type HeadersInput, + type Input, + InsecureCredentialError, + InternalServerError, + type ItemOf, + type LogLevel, + type Logger, + NotFoundError, + type Outcome, + Page, + PagePromise, + PermissionDeniedError, + type QueryInput, + RateLimitError, + type RawRequest, + type RequestOptions, + RequestTimeoutError, + SdkError, + type ServerSentEvent, + Stream, + TokenError, + UnprocessableEntityError, +} from "./core/index.js"; +export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/github/src/resources/apps.ts b/crates/flowapi-sdk/tests/client/github/src/resources/apps.ts new file mode 100644 index 0000000..85fe29b --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/resources/apps.ts @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.apps`. */ +export class Apps { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /app/hook` */ + hook(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.appsGetWebhook, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/github/src/resources/enterprise.ts b/crates/flowapi-sdk/tests/client/github/src/resources/enterprise.ts new file mode 100644 index 0000000..2dd06cd --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/resources/enterprise.ts @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.enterprise`. */ +export class Enterprise { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /enterprise/settings` */ + settings(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.enterpriseGetSettings, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/github/src/resources/meta.ts b/crates/flowapi-sdk/tests/client/github/src/resources/meta.ts new file mode 100644 index 0000000..956de5b --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/resources/meta.ts @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.meta`. */ +export class Meta { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /meta` */ + get(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.metaGet, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/github/src/resources/repos.ts b/crates/flowapi-sdk/tests/client/github/src/resources/repos.ts new file mode 100644 index 0000000..984d55f --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/resources/repos.ts @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.repos`. */ +export class Repos { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /repos/{owner}/{repo}` */ + get(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.reposGet, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/github/src/resources/users.ts b/crates/flowapi-sdk/tests/client/github/src/resources/users.ts new file mode 100644 index 0000000..ec7c484 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/github/src/resources/users.ts @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.users`. */ +export class Users { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /user` */ + me(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.usersGetAuthenticated, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/hosts/flowapi-sdk.yml b/crates/flowapi-sdk/tests/client/hosts/flowapi-sdk.yml new file mode 100644 index 0000000..33610ae --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/flowapi-sdk.yml @@ -0,0 +1,34 @@ +# Where requests go and how HTTP is used: a server with variables (one with an `enum`), one +# relative to where the description is served, a Path Item's and an operation's own servers (a +# variable there too), every method RFC 9110 names idempotent but TRACE and two it does not (POST, +# PATCH), content with DELETE and OPTIONS, and an idempotency key for the methods that need one; +# an optional OAuth 2.0 client the description lacks, so that the retries, the redirects and the +# servers meet the credentials. +version: 1 +spec: spec.json +package: { name: hosts-sdk, client: Hosts, license: MIT } +auth: + Client: + type: oauth2 + token_url: https://login.hosts.example/oauth/token + client_id_env_var: HOSTS_CLIENT_ID + client_secret_env_var: HOSTS_CLIENT_SECRET +security: + - Client: [] + - {} +defaults: { idempotency_key: Idempotency-Key } +resources: + items: + methods: + all: listItems + create: createItem + replace: replaceItem + edit: editItem + delete: deleteItem + check: checkItem + describe: describeItem + purge: purgeItems + places: + methods: + local: localStatus + edge: edgeStatus diff --git a/crates/flowapi-sdk/tests/client/hosts/issues.txt b/crates/flowapi-sdk/tests/client/hosts/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/client/hosts/spec.json b/crates/flowapi-sdk/tests/client/hosts/spec.json new file mode 100644 index 0000000..48f4383 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/spec.json @@ -0,0 +1,47 @@ +{ + "openapi": "3.2.0", + "info": { "title": "Hosts", "version": "1", "description": "Items kept in two regions." }, + "servers": [ + { "url": "https://{region}.hosts.example/{version}", "variables": { "region": { "default": "eu", "enum": ["eu", "us"] }, "version": { "default": "v1" } } }, + { "url": "./local" } + ], + "paths": { + "/items": { + "get": { "operationId": "listItems", "summary": "Every item", "responses": { "200": { "$ref": "#/components/responses/Items" } } }, + "post": { "operationId": "createItem", "summary": "Add an item", "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } } }, "responses": { "201": { "$ref": "#/components/responses/One" } } } + }, + "/items/{id}": { + "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "integer" } }], + "put": { "operationId": "replaceItem", "summary": "Replace an item", "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } } }, "responses": { "200": { "$ref": "#/components/responses/One" } } }, + "patch": { "operationId": "editItem", "summary": "Change an item", "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } } }, "responses": { "200": { "$ref": "#/components/responses/One" } } }, + "delete": { "operationId": "deleteItem", "summary": "Remove an item", "responses": { "204": { "description": "gone" } } }, + "head": { "operationId": "checkItem", "summary": "Whether an item is there", "responses": { "200": { "description": "there" } } }, + "options": { "operationId": "describeItem", "summary": "What an item allows, asked with a note", "requestBody": { "content": { "text/plain": { "schema": { "type": "string" } } } }, "responses": { "204": { "description": "allowed" } } } + }, + "/purge": { + "delete": { "operationId": "purgeItems", "summary": "Remove the items named", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "array", "items": { "type": "integer" } } } } }, "responses": { "204": { "description": "gone" } } } + }, + "/status": { + "servers": [{ "url": "." }], + "get": { "operationId": "localStatus", "summary": "The status where the description is served", "responses": { "200": { "$ref": "#/components/responses/Status" } } } + }, + "/edge": { + "get": { + "operationId": "edgeStatus", + "summary": "The status at an edge", + "servers": [{ "url": "https://{zone}.edge.example", "variables": { "zone": { "default": "a", "enum": ["a", "b"] } } }], + "responses": { "200": { "$ref": "#/components/responses/Status" } } + } + } + }, + "components": { + "schemas": { + "Item": { "type": "object", "required": ["name"], "properties": { "id": { "type": "integer" }, "name": { "type": "string" } } } + }, + "responses": { + "One": { "description": "the item", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item" } } } }, + "Items": { "description": "the items", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/Item" } } } } }, + "Status": { "description": "the status", "content": { "application/json": { "schema": { "type": "object", "properties": { "up": { "type": "boolean" } } } } } } + } + } +} diff --git a/crates/flowapi-sdk/tests/client/hosts/src/api.ts b/crates/flowapi-sdk/tests/client/hosts/src/api.ts new file mode 100644 index 0000000..4ede017 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/src/api.ts @@ -0,0 +1,1212 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +export type Item = { + id?: number; + name: string; + [key: string]: unknown; +}; + +export type ListItems = { + responses: { + "200": { + content: { + "application/json": Item[]; + }; + }; + }; +}; + +export type CreateItem = { + requestBody: { + "application/json": Item; + }; + responses: { + "201": { + content: { + "application/json": Item; + }; + }; + }; +}; + +export type ReplaceItem = { + parameters: { + path: { + id: number; + }; + }; + requestBody: { + "application/json": Item; + }; + responses: { + "200": { + content: { + "application/json": Item; + }; + }; + }; +}; + +export type DeleteItem = { + parameters: { + path: { + id: number; + }; + }; + responses: { + "204": Record; + }; +}; + +export type DescribeItem = { + parameters: { + path: { + id: number; + }; + }; + requestBody?: { + "text/plain": string; + }; + responses: { + "204": Record; + }; +}; + +export type CheckItem = { + parameters: { + path: { + id: number; + }; + }; + responses: { + "200": Record; + }; +}; + +export type EditItem = { + parameters: { + path: { + id: number; + }; + }; + requestBody: { + "application/json": Item; + }; + responses: { + "200": { + content: { + "application/json": Item; + }; + }; + }; +}; + +export type PurgeItems = { + requestBody: { + "application/json": number[]; + }; + responses: { + "204": Record; + }; +}; + +export type LocalStatus = { + responses: { + "200": { + content: { + "application/json": ResponsesStatusApplicationJson; + }; + }; + }; +}; + +export type EdgeStatus = { + responses: { + "200": { + content: { + "application/json": ResponsesStatusApplicationJson; + }; + }; + }; +}; + +export type Paths = { + "/items": { + get: ListItems; + post: CreateItem; + }; + "/items/{id}": { + put: ReplaceItem; + delete: DeleteItem; + options: DescribeItem; + head: CheckItem; + patch: EditItem; + }; + "/purge": { + delete: PurgeItems; + }; + "/status": { + get: LocalStatus; + }; + "/edge": { + get: EdgeStatus; + }; +}; + +export type ResponsesStatusApplicationJson = { + up?: boolean; + [key: string]: unknown; +}; + +// The SDK: for each operation, a function that writes its request and one that reads its +// response. No I/O: send the request with any HTTP client, give its answer back. + +/** + * A request to send. `path` goes after the server's base URL; `query` is the query string + * without its `?`, empty for none; `body` text, or bytes (a multipart body, bytes given). + */ +export type $Request = { + method: string; + path: string; + query: string; + headers: Record; + body?: string | Uint8Array; +}; + +/** + * A request `Request` refuses to write: a value that would change what the request means + * rather than what it says. `location` is where it goes (`path`, `query`, `querystring`, + * `header`, `cookie` or `body`), `parameter` the parameter's name as the description writes it + * (`null` for the body; a multipart part's name), `reason` why: a CR, LF or NUL in a header, a + * cookie or a part's head (it would start another header), a path segment left empty or made `.` + * or `..` (a client or a server would remove it and the one before it), NaN or an infinity (JSON + * has no number for them). In a multipart body also: `null` where a part goes (`null`), a member + * of an array of parts that is not an object (`unnamed-part`), a Blob not read yet + * (`unread-blob`: `flowapiBlob` reads it), a `"` or `\` in a name or a file name (`quote`), a + * file name that is empty, `.` or `..` (`file-name`), a part header's name that is not a token or + * is `Content-Disposition` (`header-name`), a list or a range for a part's type (`media-range`), + * a boundary RFC 2046 does not allow or that a part holds (`boundary`). + */ +export class FlowapiRequestError extends Error { + readonly location: string; + readonly parameter: string | null; + readonly reason: + | "control-character" | "empty-segment" | "dot-segment" | "non-finite" | "null" | "unnamed-part" + | "unread-blob" | "quote" | "file-name" | "header-name" | "media-range" | "boundary"; + constructor(location: string, parameter: string | null, reason: FlowapiRequestError["reason"]) { + const what = location === "body" ? "the body" + (parameter === null ? "" : `'s part \`${parameter}\``) : `the ${location} parameter \`${parameter}\``; + super(`${what}: ${reason}`); + this.name = "FlowapiRequestError"; + this.location = location; + this.parameter = parameter; + this.reason = reason; + } +} + +const $unreserved = /^[A-Za-z0-9\-._~]*$/; +const $marks = /[!'()*]/g; +const $marked = /[!'()*]/; +const $kept = /%[0-9A-Fa-f]{2}|[:/?#[\]@!$&'()*+,;=]/g; + +function $mark(c: string): string { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +} + +/** RFC 3986: every character but the unreserved ones percent-encoded, as UTF-8. */ +function $enc(s: string): string { + if ($unreserved.test(s)) return s; + const e = encodeURIComponent(s); + return $marked.test(e) ? e.replace($marks, $mark) : e; +} + +/** RFC 6570's reserved expansion: reserved characters and percent-encoded triples kept. */ +function $res(s: string): string { + if ($unreserved.test(s)) return s; + $kept.lastIndex = 0; + let out = ""; + let last = 0; + let m: RegExpExecArray | null; + while ((m = $kept.exec(s)) !== null) { + out += $enc(s.slice(last, m.index)) + m[0]; + last = $kept.lastIndex; + } + return out + $enc(s.slice(last)); +} + +/** Headers and `style: cookie` take values as they are (3.2, Appendix D). */ +function $raw(s: string): string { + return s; +} + +const $dot = /^(?:\.|%2e){1,2}$/i; + +/** A value written raw, refused if it holds a CR, LF or NUL: it would end its header. */ +function $ctl(s: string | undefined, at: string, name: string): string | undefined { + if (s !== undefined && (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0)) { + throw new FlowapiRequestError(at, name, "control-character"); + } + return s; +} + +/** A path segment a parameter wrote, refused when empty or a dot segment (`.`, `..`, a dot as + * `%2E` too, as WHATWG's URL parser reads it). `pieces`: a parameter of it keeps `/` + * (`allowReserved`), and each piece between them is held to the same. */ +function $seg(s: string, name: string, pieces: boolean): string { + // A dot segment is at most 6 characters (`%2e%2e`) and starts with `.` or `%`: a longer one + // is none, and is not read (reading a string made by `+` would flatten it). + if (!pieces && s.length > 6) return s; + if (s.length === 0) throw new FlowapiRequestError("path", name, "empty-segment"); + const c = s.charCodeAt(0); + if (!pieces && c !== 46 && c !== 37) return s; + if ($dot.test(s) || (pieces && s.split("/").some((p) => $dot.test(p)))) { + throw new FlowapiRequestError("path", name, "dot-segment"); + } + return s; +} + +/** Whether a value holds NaN or an infinity anywhere. */ +function $bad(v: unknown): boolean { + if (typeof v === "number") return v - v !== 0; + if (v === null || typeof v !== "object") return false; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) if ($bad(v[i])) return true; + return false; + } + for (const key in v) if ($bad((v as Record)[key])) return true; + return false; +} + +/** A parameter's value, refused when it holds NaN or an infinity: JSON has no number for them, + * and their text would reach the server as a string. */ +function $fin(v: T, at: string, name: string): T { + if (typeof v === "number" ? v - v !== 0 : typeof v === "object" && v !== null && $bad(v)) { + throw new FlowapiRequestError(at, name, "non-finite"); + } + return v; +} + +/** A value as text: a string as it is, a number, boolean or bigint by `String`, else JSON. */ +function $str(v: unknown): string { + switch (typeof v) { + case "string": + return v; + case "number": + case "boolean": + case "bigint": + return String(v); + default: + return JSON.stringify(v) ?? ""; + } +} + +/** + * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, + * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. + */ +function $x( + v: unknown, + name: string, + first: string, + sep: string, + named: boolean, + ifemp: string, + explode: boolean, + join: string, + enc: (s: string) => string, + at: string, + pname: string, + nest?: readonly string[], +): string | undefined { + if (v === undefined) return undefined; + if (v === null) return ifemp === "=" ? name + "=" : ""; + let out = ""; + let n = 0; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) { + const item: unknown = v[i]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); + if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); + else out += (n++ ? (explode ? sep : join) : "") + s; + } + } else if (typeof v === "object") { + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const k = enc(key); + const s = enc($str(item)); + if (explode) out += (n++ ? sep : "") + k + (s === "" && named ? ifemp : "=" + s); + else out += (n++ ? join : "") + k + join + s; + } + } else { + if (typeof v === "number" && v - v !== 0) throw new FlowapiRequestError(at, pname, "non-finite"); + const s = enc($str(v)); + return first + (named ? name + (s === "" ? ifemp : "=" + s) : s); + } + if (n === 0) return undefined; + return first + (named && !explode ? name + "=" + out : out); +} + +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + +/** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an + * array's items repeat their key. */ +function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { + if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined; + const out = $members(v as Record, name, enc, ""); + return out === "" ? undefined : out; +} + +function $members(v: Record, path: string, enc: (s: string) => string, acc: string): string { + for (const key in v) { + if (!Object.prototype.hasOwnProperty.call(v, key)) continue; + const item = v[key]; + if (item === null || item === undefined) continue; + const at = path + "%5B" + enc(key) + "%5D"; + if (Array.isArray(item)) { + for (let i = 0; i < item.length; i++) { + const one: unknown = item[i]; + if (one !== null && one !== undefined) acc += (acc === "" ? "" : "&") + at + "=" + enc($str(one)); + } + } else if (typeof item === "object") { + acc = $members(item as Record, at, enc, acc); + } else { + acc += (acc === "" ? "" : "&") + at + "=" + enc($str(item)); + } + } + return acc; +} + +/** `s` added to a query string or a cookie header, after `sep`. */ +function $add(acc: string, s: string | undefined, sep: string): string { + return s === undefined ? acc : acc === "" ? s : acc + sep + s; +} + +/** The media type without its parameters, in lower case. */ +function $bare(type: string): string { + const semi = type.indexOf(";"); + return (semi < 0 ? type : type.slice(0, semi)).trim().toLowerCase(); +} + +/** `application/json` and every `+json` type (RFC 6839). */ +function $json(type: string): boolean { + const bare = $bare(type); + return bare === "application/json" || bare.endsWith("+json"); +} + +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { + if (v instanceof Uint8Array) return v; + if (!$json(type)) { + if ($bare(type) === "application/x-www-form-urlencoded") { + if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); + return $form(v, enc); + } + if (typeof v === "string") return v; + } + // `JSON.stringify` writes NaN and the infinities as `null`: with no `null` in the text there is + // none, and the value is walked only when there is one. + const text = JSON.stringify(v); + if (text !== undefined && text.indexOf("null") >= 0 && $bad(v)) { + throw new FlowapiRequestError("body", null, "non-finite"); + } + return text; +} + +/** A parameter with `content`: its value as its media type's text, then written as a string. */ +function $content(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + return $json(type) ? JSON.stringify(v) : $str(v); +} + +/** `in: querystring`: the whole query string, a form as one, any other type percent-encoded. */ +function $qs(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + if ($bare(type) === "application/x-www-form-urlencoded") return $form(v); + return $enc($json(type) ? JSON.stringify(v) : $str(v)); +} + +/** A header set when it has a value; a CR, LF or NUL in it is refused (it would end the header). */ +function $set(headers: Record, name: string, s: string | undefined): void { + if (s === undefined) return; + if (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0) { + throw new FlowapiRequestError("header", name, "control-character"); + } + headers[name] = s; +} + +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + +/** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's + * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or + * `flowapiBlob`. */ +export class FlowapiFile { + readonly data: Uint8Array; + readonly name: string | undefined; + readonly type: string | undefined; + constructor(data: Uint8Array, name: string | undefined, type: string | undefined) { + this.data = data; + this.name = name; + this.type = type; + } +} + +/** A file from bytes, or from text as its UTF-8, with the name and the type to send it as. */ +export function flowapiFile(data: Uint8Array | string, name?: string, type?: string): FlowapiFile { + return new FlowapiFile(typeof data === "string" ? $bytes(data) : data, name, type); +} + +/** What `flowapiBlob` reads of a `Blob` or a `File`, typed here so the output type-checks + * without the DOM's declarations. */ +export type $Blob = { readonly type: string; readonly name?: string; arrayBuffer(): Promise }; + +/** A `Blob` or a `File` read into a `FlowapiFile`: its bytes, `name` or else a File's own, `type` + * or else the Blob's. The one step that waits: `Request` takes bytes and stays synchronous. */ +export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); +} + +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; +}; + +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + +/** A `multipart/form-data` value as `Request` takes it: a string member may also be a file + * (the types cannot tell `format: binary` from text), an array member's items one part each. */ +type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; +type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; +type $Fields = T extends object ? { [K in keyof T]: $Member } : T; +export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; + +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; + +/** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ +function $put(request: $Request, body: $Given): void { + const v = body.value; + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); + request.headers["content-type"] = type; + request.body = bytes; + return; + } + request.headers["content-type"] = body.contentType; + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; +} + +/** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ +type $Part = { head: string; data: Uint8Array }; + +let $encoder: { encode(text: string): Uint8Array } | undefined; + +/** Text as UTF-8 bytes. */ +function $bytes(text: string): Uint8Array { + $encoder ??= new (globalThis as unknown as $Coders).TextEncoder(); + return $encoder.encode(text); +} + +const $breaks = /[\r\n\0]/; +const $quotes = /["\\]/; +const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes + * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a + * receiver could read another name. */ +function $safe(s: string, part: string | null, quoted: boolean): string { + if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); + if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); + return s; +} + +/** A file's name as its part's `filename`: its last path segment (a sender's directories are not + * the receiver's), refused when that is empty, `.` or `..`, and when the name holds a CR, LF or + * NUL anywhere (cut off with a directory, it would still be meant). */ +function $filename(name: string, part: string): string { + $safe(name, part, false); + const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1); + if (base === "" || base === "." || base === "..") throw new FlowapiRequestError("body", part, "file-name"); + return $safe(base, part, true); +} + +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { + if (v === undefined) return; + $safe(name, name, true); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); +} + +/** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's + * `blob` for a name not given, `application/octet-stream` for a type not given), strings, + * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); + // Bytes in any other view are the same bytes. + if (v instanceof ArrayBuffer) v = new Uint8Array(v); + else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; + let type = e?.contentType; + let data: Uint8Array; + if (v instanceof FlowapiFile || v instanceof Uint8Array) { + const file = v instanceof FlowapiFile ? v : undefined; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; + type = file?.type ?? type ?? "application/octet-stream"; + data = file?.data ?? (v as Uint8Array); + } else if ($unread(v)) { + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); + } else { + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); + type ??= typeof v === "object" ? "application/json" : undefined; + // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); + data = typeof s === "string" ? $bytes(s) : s; + } + if (type !== undefined) { + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); + } + const headers = e?.headers ?? {}; + for (const key of Object.keys(headers)) { + const value = headers[key]; + const lower = key.toLowerCase(); + if (value === undefined || lower === "content-type") continue; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); + } + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); +} + +/** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting + * (`flowapiBlob`), and as JSON it would be `{}`. */ +function $unread(v: unknown): boolean { + return typeof v === "object" && v !== null && typeof (v as { arrayBuffer?: unknown }).arrayBuffer === "function"; +} + +const $bchars = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; + +/** Whether `needle` occurs in `data`. */ +function $holds(data: Uint8Array, needle: Uint8Array): boolean { + const first = needle[0] ?? 0; + for (let i = data.indexOf(first); i >= 0 && i + needle.length <= data.length; i = data.indexOf(first, i + 1)) { + let j = 1; + while (j < needle.length && data[i + j] === needle[j]) j++; + if (j === needle.length) return true; + } + return false; +} + +/** Whether a boundary occurs in any part: a delimiter in a part would end it there. */ +function $collides(parts: $Part[], boundary: string): boolean { + const b = $bytes(boundary); + return parts.some((p) => p.head.indexOf(boundary) >= 0 || $holds(p.data, b)); +} + +/** A boundary of 128 random bits from `globalThis.crypto`, so no content can be made to hold it. */ +function $random(): string { + const c = (globalThis as unknown as { crypto?: { getRandomValues(b: Uint8Array): Uint8Array } }).crypto; + if (c === undefined) throw new Error("flowapi: no globalThis.crypto to draw a multipart boundary from; give one: `multipart/form-data; boundary=...`"); + let s = "flowapi-"; + for (const x of c.getRandomValues(new Uint8Array(16))) s += (x < 16 ? "0" : "") + x.toString(16); + return s; +} + +/** The parts written with a boundary (RFC 2046, 5.1.1; RFC 7578): the one the content type + * gives (`boundary=`), refused when RFC 2046 does not allow it or a part holds it, or one drawn + * at random and added to the content type, drawn again while a part holds it. */ +function $multipart(contentType: string, parts: $Part[]): [string, Uint8Array] { + const given = /;\s*boundary\s*=\s*(?:"([^"]*)"|([^;\s]*))/i.exec(contentType); + let boundary: string; + let type = contentType; + if (given !== null) { + boundary = given[1] ?? given[2] ?? ""; + if (!$bchars.test(boundary) || $collides(parts, boundary)) throw new FlowapiRequestError("body", null, "boundary"); + } else { + boundary = $random(); + for (let tries = 1; $collides(parts, boundary); tries++) { + if (tries === 8) throw new FlowapiRequestError("body", null, "boundary"); + boundary = $random(); + } + type += "; boundary=" + boundary; + } + const chunks: Uint8Array[] = []; + for (const p of parts) chunks.push($bytes(`--${boundary}\r\n${p.head}\r\n`), p.data, $bytes("\r\n")); + chunks.push($bytes(`--${boundary}--\r\n`)); + let size = 0; + for (const c of chunks) size += c.length; + const out = new Uint8Array(size); + let at = 0; + for (const c of chunks) { + out.set(c, at); + at += c.length; + } + return [type, out]; +} + +/** A response read: which response of the description it is (`null` for none), and its body. */ +type $Read = { response: string | null; status: number; mediaType: string | null; body: unknown }; + +/** Per response, as written: its status, its media types as written and their bare forms. */ +type $Table = readonly (readonly [string, readonly string[], readonly string[]])[]; + +/** The platform's UTF-8 coders (every browser, Node, Deno and Bun has them), looked up on + * `globalThis` so the output type-checks without the DOM's or Node's declarations. */ +type $Coders = { + TextDecoder: new (label: string, options: { fatal: boolean; ignoreBOM: boolean }) => { + decode(bytes: Uint8Array): string; + }; + TextEncoder: new () => { encode(text: string): Uint8Array }; +}; + +let $decoder: { decode(bytes: Uint8Array): string } | undefined; + +/** Bytes as UTF-8 text, a byte order mark kept as the character; `null` when they are not + * UTF-8 (the Rust SDK refuses them too, where `Response.text()` would replace them). */ +function $utf8(bytes: Uint8Array): string | null { + $decoder ??= new (globalThis as unknown as $Coders).TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + try { + return $decoder.decode(bytes); + } catch { + return null; + } +} + +/** A `text/*` type (a JSON one is read as JSON first). */ +function $text(bare: string): boolean { + return bare.startsWith("text/"); +} + +/** + * Whether `Response` keeps a body of this `Content-Type` as bytes: any type but JSON and + * `text/*`, and a body with none. Read such a body with `arrayBuffer()`, the others with + * `text()`; bytes are always safe to give, as they are decoded where the type is text. + */ +export function flowapiReadsBytes(contentType: string | null | undefined): boolean { + if (contentType === null || contentType === undefined) return true; + return !$json(contentType) && !$text($bare(contentType)); +} + +/** A header, its name compared without case. */ +function $header(headers: Record, name: string): string | null { + const direct = headers[name]; + if (direct !== undefined) return direct; + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === name) return headers[key] ?? null; + } + return null; +} + +/** + * The response a status picks (its code, then its range `NXX`, then `default`), the media type + * the `Content-Type` picks (exact, then `type/*`, then `*\/*`), and the body read by the type + * sent: JSON parsed, `text/*` the text, any other the bytes (a string given for it encoded as + * UTF-8: its bytes were lost before). Bytes given for JSON or text are decoded as UTF-8. A + * status or a media type the description does not name, and a JSON or text body that is not + * UTF-8 or not JSON, read as `response: null` with the body as given. + */ +function $read(table: $Table, status: number, headers: Record, body: string | Uint8Array): $Read { + const code = String(status); + const range = code.charAt(0) + "XX"; + let hit: (typeof table)[number] | undefined; + for (const r of table) if (r[0] === code) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0].toUpperCase() === range) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0] === "default") hit = hit ?? r; + const type = $header(headers, "content-type"); + if (hit === undefined) return { response: null, status, mediaType: type, body }; + if (hit[1].length === 0) return { response: hit[0], status, mediaType: null, body }; + if (type === null) return { response: null, status, mediaType: null, body }; + const bare = $bare(type); + const slash = bare.indexOf("/"); + const major = bare.slice(0, slash + 1) + "*"; + let at = hit[2].indexOf(bare); + if (at < 0) at = hit[2].indexOf(major); + if (at < 0) at = hit[2].indexOf("*/*"); + const written = hit[1][at]; + if (written === undefined) return { response: null, status, mediaType: type, body }; + const json = $json(type); + if (!json && !$text(bare)) { + const bytes = typeof body === "string" ? $bytes(body) : body; + return { response: hit[0], status, mediaType: written, body: bytes }; + } + const text = typeof body === "string" ? body : $utf8(body); + if (text === null) return { response: null, status, mediaType: type, body }; + if (!json) return { response: hit[0], status, mediaType: written, body: text }; + // An empty or broken JSON body is not the response described: the body as given, unnamed. A + // leading byte order mark is skipped (RFC 8259, 8.1), as `JSON.parse` would refuse it. + try { + return { response: hit[0], status, mediaType: written, body: JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) }; + } catch { + return { response: null, status, mediaType: type, body }; + } +} + +export function listItemsRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/items", query: "", headers }; + return request; +} + +const $listItemsResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function listItemsResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: ListItems["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($listItemsResponse, status, headers, body) as ReturnType; +} + +export function createItemRequest(input: { body: { contentType: "application/json" | `application/json;${string}`; value: NonNullable["application/json"] } }): $Request { + const headers: Record = {}; + const request: $Request = { method: "POST", path: "/items", query: "", headers }; + if (input.body !== undefined) $put(request, input.body); + return request; +} + +const $createItemResponse: $Table = [["201", ["application/json"], ["application/json"]]]; +export function createItemResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "201"; status: 201; mediaType: "application/json"; body: CreateItem["responses"]["201"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($createItemResponse, status, headers, body) as ReturnType; +} + +export function replaceItemRequest(input: NonNullable & { body: { contentType: "application/json" | `application/json;${string}`; value: NonNullable["application/json"] } }): $Request { + const headers: Record = {}; + const request: $Request = { method: "PUT", path: "/items/" + $seg(($x(input.path?.["id"], "id", "", ",", false, "", false, ",", $enc, "path", "id") ?? ""), "id", false), query: "", headers }; + if (input.body !== undefined) $put(request, input.body); + return request; +} + +const $replaceItemResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function replaceItemResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: ReplaceItem["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($replaceItemResponse, status, headers, body) as ReturnType; +} + +export function deleteItemRequest(input: NonNullable): $Request { + const headers: Record = {}; + const request: $Request = { method: "DELETE", path: "/items/" + $seg(($x(input.path?.["id"], "id", "", ",", false, "", false, ",", $enc, "path", "id") ?? ""), "id", false), query: "", headers }; + return request; +} + +const $deleteItemResponse: $Table = [["204", [], []]]; +export function deleteItemResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "204"; status: 204; mediaType: null; body: string | Uint8Array } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($deleteItemResponse, status, headers, body) as ReturnType; +} + +export function describeItemRequest(input: NonNullable & { body?: { contentType: "text/plain" | `text/plain;${string}`; value: NonNullable["text/plain"] } }): $Request { + const headers: Record = {}; + const request: $Request = { method: "OPTIONS", path: "/items/" + $seg(($x(input.path?.["id"], "id", "", ",", false, "", false, ",", $enc, "path", "id") ?? ""), "id", false), query: "", headers }; + if (input.body !== undefined) $put(request, input.body); + return request; +} + +const $describeItemResponse: $Table = [["204", [], []]]; +export function describeItemResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "204"; status: 204; mediaType: null; body: string | Uint8Array } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($describeItemResponse, status, headers, body) as ReturnType; +} + +export function checkItemRequest(input: NonNullable): $Request { + const headers: Record = {}; + const request: $Request = { method: "HEAD", path: "/items/" + $seg(($x(input.path?.["id"], "id", "", ",", false, "", false, ",", $enc, "path", "id") ?? ""), "id", false), query: "", headers }; + return request; +} + +const $checkItemResponse: $Table = [["200", [], []]]; +export function checkItemResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: null; body: string | Uint8Array } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($checkItemResponse, status, headers, body) as ReturnType; +} + +export function editItemRequest(input: NonNullable & { body: { contentType: "application/json" | `application/json;${string}`; value: NonNullable["application/json"] } }): $Request { + const headers: Record = {}; + const request: $Request = { method: "PATCH", path: "/items/" + $seg(($x(input.path?.["id"], "id", "", ",", false, "", false, ",", $enc, "path", "id") ?? ""), "id", false), query: "", headers }; + if (input.body !== undefined) $put(request, input.body); + return request; +} + +const $editItemResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function editItemResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: EditItem["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($editItemResponse, status, headers, body) as ReturnType; +} + +export function purgeItemsRequest(input: { body: { contentType: "application/json" | `application/json;${string}`; value: NonNullable["application/json"] } }): $Request { + const headers: Record = {}; + const request: $Request = { method: "DELETE", path: "/purge", query: "", headers }; + if (input.body !== undefined) $put(request, input.body); + return request; +} + +const $purgeItemsResponse: $Table = [["204", [], []]]; +export function purgeItemsResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "204"; status: 204; mediaType: null; body: string | Uint8Array } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($purgeItemsResponse, status, headers, body) as ReturnType; +} + +export function localStatusRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/status", query: "", headers }; + return request; +} + +const $localStatusResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function localStatusResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: LocalStatus["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($localStatusResponse, status, headers, body) as ReturnType; +} + +export function edgeStatusRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/edge", query: "", headers }; + return request; +} + +const $edgeStatusResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function edgeStatusResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: EdgeStatus["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($edgeStatusResponse, status, headers, body) as ReturnType; +} + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://{region}.hosts.example/{version}", variables: { "region": { default: "eu", enum: ["eu", "us"] }, "version": { default: "v1" } } }, + { url: "./local" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "Client": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://login.hosts.example/oauth/token", scopes: [] } }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + listItems: { + method: "GET", + path: "/items", + security: [{ "Client": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: listItemsRequest, + response: listItemsResponse, + }, + createItem: { + method: "POST", + path: "/items", + security: [{ "Client": [] }, {}], + responses: { "201": { content: { "application/json": "json" } } }, + request: createItemRequest, + response: createItemResponse, + }, + replaceItem: { + method: "PUT", + path: "/items/{id}", + security: [{ "Client": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: replaceItemRequest, + response: replaceItemResponse, + }, + deleteItem: { + method: "DELETE", + path: "/items/{id}", + security: [{ "Client": [] }, {}], + responses: { "204": { content: {} } }, + request: deleteItemRequest, + response: deleteItemResponse, + }, + describeItem: { + method: "OPTIONS", + path: "/items/{id}", + security: [{ "Client": [] }, {}], + responses: { "204": { content: {} } }, + request: describeItemRequest, + response: describeItemResponse, + }, + checkItem: { + method: "HEAD", + path: "/items/{id}", + security: [{ "Client": [] }, {}], + responses: { "200": { content: {} } }, + request: checkItemRequest, + response: checkItemResponse, + }, + editItem: { + method: "PATCH", + path: "/items/{id}", + security: [{ "Client": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: editItemRequest, + response: editItemResponse, + }, + purgeItems: { + method: "DELETE", + path: "/purge", + security: [{ "Client": [] }, {}], + responses: { "204": { content: {} } }, + request: purgeItemsRequest, + response: purgeItemsResponse, + }, + localStatus: { + method: "GET", + path: "/status", + servers: [{ url: "." }], + security: [{ "Client": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: localStatusRequest, + response: localStatusResponse, + }, + edgeStatus: { + method: "GET", + path: "/edge", + servers: [{ url: "https://{zone}.edge.example", variables: { "zone": { default: "a", enum: ["a", "b"] } } }], + security: [{ "Client": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: edgeStatusRequest, + response: edgeStatusResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/client/hosts/src/client.ts b/crates/flowapi-sdk/tests/client/hosts/src/client.ts new file mode 100644 index 0000000..b7379b5 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/src/client.ts @@ -0,0 +1,74 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "./api.js"; +import * as $core from "./core/index.js"; +import { Items as $Items } from "./resources/items.js"; +import { Places as $Places } from "./resources/places.js"; + +/** What the config decides of the client. */ +const $settings: $core.Settings = { + client: "Hosts", + environments: { }, + logEnv: "HOSTS_LOG", + auth: { "Client": { option: "client", clientIdEnv: "HOSTS_CLIENT_ID", clientSecretEnv: "HOSTS_CLIENT_SECRET" } }, + timeout: 60000, + maxRetries: 1, + maxRetryDelay: 60000, + idempotencyHeader: "Idempotency-Key", + servers: $api.flowapiServers, + schemes: $api.flowapiSecuritySchemes, + readsBytes: $api.flowapiReadsBytes, +}; + +/** The options of a `Hosts`: the runtime's, and a credential for each security scheme it sends. */ +export type HostsOptions = $core.ClientOptions & { + /** The credential of the security scheme `Client`: a token, or the client's id and secret to request one with, else `HOSTS_CLIENT_ID`, `HOSTS_CLIENT_SECRET`; `null` reads no variable. */ + client?: $core.Credential | $core.ClientCredentials | null | undefined; + /** Values of the servers' variables, over their defaults. */ + serverVariables?: { "region"?: "eu" | "us" | undefined; "version"?: string | undefined; "zone"?: "a" | "b" | undefined } | undefined; +}; + +/** The API's client: a member for each resource (`client.items`), and `request` for a call no + * operation describes. */ +export class Hosts { + readonly #core: $core.Core; + readonly #options: HostsOptions; + readonly items: $Items; + readonly places: $Places; + + constructor(options: HostsOptions = {}) { + this.#options = { ...options }; + this.#core = new $core.Core($settings, options); + this.items = new $Items(this.#core); + this.places = new $Places(this.#core); + } + + /** The base URL calls go to, unless an operation has servers of its own. */ + get baseURL(): string | null { + return this.#core.baseURL; + } + + /** Milliseconds an attempt may take, its body read; `null` for no limit. */ + get timeout(): number | null { + return this.#core.timeout; + } + + /** How many times a failed attempt is tried again. */ + get maxRetries(): number { + return this.#core.maxRetries; + } + + /** A client of the same class with these options over this one's: one given as `undefined` + * keeps this one's. */ + withOptions(options: HostsOptions): this { + const next: Record = { ...this.#options }; + for (const [key, value] of Object.entries(options)) if (value !== undefined) next[key] = value; + return new (this.constructor as new (options: HostsOptions) => this)(next as HostsOptions); + } + + /** A call by method and path that no operation describes, with every credential the + * client has. */ + request(method: string, path: string, options?: $core.RawRequest): $core.ApiCall { + return $core.request(this.#core, method, path, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/hosts/src/index.ts b/crates/flowapi-sdk/tests/client/hosts/src/index.ts new file mode 100644 index 0000000..5b6fe0b --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/src/index.ts @@ -0,0 +1,45 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +export { Hosts, Hosts as default, type HostsOptions } from "./client.js"; +export { + APIConnectionError, + APIConnectionTimeoutError, + APIError, + APIUserAbortError, + ApiCall, + AuthenticationError, + BadRequestError, + type BasicCredential, + type BasicPair, + type ClientCredentials, + ConflictError, + type Credential, + CredentialError, + CrossOriginRedirectError, + type Data, + type Fetch, + type FetchResponse, + type HeadersInput, + type Input, + InsecureCredentialError, + InternalServerError, + type ItemOf, + type LogLevel, + type Logger, + NotFoundError, + type Outcome, + Page, + PagePromise, + PermissionDeniedError, + type QueryInput, + RateLimitError, + type RawRequest, + type RequestOptions, + RequestTimeoutError, + SdkError, + type ServerSentEvent, + Stream, + TokenError, + UnprocessableEntityError, +} from "./core/index.js"; +export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/hosts/src/resources/items.ts b/crates/flowapi-sdk/tests/client/hosts/src/resources/items.ts new file mode 100644 index 0000000..e7cd52f --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/src/resources/items.ts @@ -0,0 +1,85 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.items`. */ +export class Items { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** + * Every item + * + * `GET /items` + */ + all(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.listItems, params, options); + } + + /** + * Add an item + * + * `POST /items` + */ + create(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.createItem, params, options); + } + + /** + * Replace an item + * + * `PUT /items/{id}` + */ + replace(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.replaceItem, params, options); + } + + /** + * Change an item + * + * `PATCH /items/{id}` + */ + edit(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.editItem, params, options); + } + + /** + * Remove an item + * + * `DELETE /items/{id}` + */ + delete(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.deleteItem, params, options); + } + + /** + * Whether an item is there + * + * `HEAD /items/{id}` + */ + check(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.checkItem, params, options); + } + + /** + * What an item allows, asked with a note + * + * `OPTIONS /items/{id}` + */ + describe(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.describeItem, params, options); + } + + /** + * Remove the items named + * + * `DELETE /purge` + */ + purge(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.purgeItems, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/hosts/src/resources/places.ts b/crates/flowapi-sdk/tests/client/hosts/src/resources/places.ts new file mode 100644 index 0000000..7a149a3 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/hosts/src/resources/places.ts @@ -0,0 +1,31 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.places`. */ +export class Places { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** + * The status where the description is served + * + * `GET /status` + */ + local(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.localStatus, params, options); + } + + /** + * The status at an edge + * + * `GET /edge` + */ + edge(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.edgeStatus, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/http.mjs b/crates/flowapi-sdk/tests/client/http.mjs new file mode 100644 index 0000000..2ff8327 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/http.mjs @@ -0,0 +1,193 @@ +// How the client uses HTTP (RFC 9110): which requests it sends twice, how it reads a status, how +// it follows a redirect, and what content each method carries. Each test names the pitfall it holds +// (R, the runtime's list): R46 a request that is not idempotent retried, R47 its idempotency key, +// R48 a failed retry retried, R49 a 403 repeated, R50 a status no class is known for, or none, R51 +// a redirect's method, R52 a redirect loop, R53 a redirect's fragment, R54 content with GET, HEAD +// and DELETE, R55 content with OPTIONS. +import { assert, rejection, reply, stub, timed } from './stub.mjs' + +const ok = () => reply(200, { ok: true }) +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +/** A shop client (retries 2, no idempotency key), quiet. */ +function shop(built, fetch, more = {}) { + return new built.shop.Shop({ fetch, apiKeyAuth: 'key-1', logLevel: 'off', timeout: null, ...more }) +} + +/** A hosts client (retries 1, `Idempotency-Key`), quiet. */ +function hosts(built, fetch, more = {}) { + return new built.hosts.Hosts({ fetch, logLevel: 'off', timeout: null, ...more }) +} + +/** A fetch whose first answer is `first` (a status, or a thrown error), then 200. */ +function once(first, headers = {}) { + return stub((_, __, n) => { + if (n > 1) return ok() + if (typeof first === 'number') return reply(first, 'no', headers) + throw first + }) +} + +/** A response with a status no `Response` can be made with. */ +function odd(status) { + return { status, headers: new Headers(), url: '', type: 'basic', body: null, text: async () => '', arrayBuffer: async () => new ArrayBuffer(0) } +} + +export function tests(built) { + const { APIError, InternalServerError, SdkError } = built.shop + return [ + // req: rfc9110.9.2.2.should-not-client-automatically-retry-request-non-idempotent — POST, PATCH and QUERY not retried on a 503 or a failed connection; PUT, DELETE and the safe methods are; the server's x-should-retry: true is the means to know + ['R46: a request that is not idempotent is not retried unless the server asks', () => timed(async () => { + for (const method of ['POST', 'PATCH', 'QUERY']) { + for (const first of [503, new TypeError('fetch failed')]) { + const fetch = once(first) + await rejection(shop(built, fetch).request(method, '/x', { body: { a: 1 } })) + assert.equal(fetch.calls.length, 1, `${method} ${first}`) + } + const asked = once(503, { 'x-should-retry': 'true' }) + await shop(built, asked).request(method, '/x') + assert.equal(asked.calls.length, 2, `${method} asked`) + } + for (const method of ['GET', 'HEAD', 'OPTIONS', 'TRACE', 'PUT', 'DELETE', 'put']) { + for (const first of [503, new TypeError('fetch failed')]) { + const fetch = once(first) + await shop(built, fetch).request(method, '/x') + assert.equal(fetch.calls.length, 2, `${method} ${first}`) + } + } + })], + // req: rfc9110.9.2.2.should-not-client-automatically-retry-request-non-idempotent — an idempotency key is the means to know a POST or a PATCH was not applied twice: with it, they are retried + ['R47: a call of a method that is not idempotent sends one idempotency key on all its attempts', () => timed(async () => { + const fetch = once(503) + const client = hosts(built, fetch) + await client.items.create({ body: { contentType: 'application/json', value: { name: 'a' } } }) + const [first, second] = fetch.calls.map((c) => c.headers['idempotency-key']) + assert.ok(UUID.test(first) && first === second, `${first} ${second}`) + const failed = once(new TypeError('fetch failed')) + await hosts(built, failed).items.edit({ path: { id: 1 }, body: { contentType: 'application/json', value: { name: 'b' } } }) + assert.equal(failed.calls.length, 2) + assert.equal(failed.calls[0].headers['idempotency-key'], failed.calls[1].headers['idempotency-key']) + const each = stub(ok) + await client.withOptions({ fetch: each }).items.create({ body: { contentType: 'application/json', value: { name: 'a' } } }) + await client.withOptions({ fetch: each }).request('POST', '/items') + await client.withOptions({ fetch: each }).items.all() + await client.withOptions({ fetch: each }).items.replace({ path: { id: 1 }, body: { contentType: 'application/json', value: { name: 'c' } } }) + const keys = each.calls.map((c) => c.headers['idempotency-key']) + assert.ok(UUID.test(keys[0]) && UUID.test(keys[1]) && keys[0] !== keys[1] && keys[0] !== first, keys.join(' ')) + assert.deepEqual(keys.slice(2), [undefined, undefined]) + const mine = once(500) + await hosts(built, mine).items.create({ body: { contentType: 'application/json', value: { name: 'a' } } }, { headers: { 'Idempotency-Key': 'mine-1' } }) + assert.deepEqual(mine.calls.map((c) => c.headers['idempotency-key']), ['mine-1', 'mine-1']) + })], + // req: rfc9110.9.2.2.should-not-client-automatically-retry-failed-automatic-retry — one retry by default: a retry that failed is the error; more only when the caller asks + ['R48: a failed retry is not retried by default; maxRetries above 1 is the caller\'s', () => timed(async () => { + const fetch = stub(() => reply(503, 'busy')) + const e = await rejection(new built.edge.Edge({ fetch, logLevel: 'off' }).zones.status()) + assert.ok(e instanceof built.edge.InternalServerError) + assert.equal(fetch.calls.length, 2) + await rejection(new built.edge.Edge({ fetch, logLevel: 'off', maxRetries: 2 }).zones.status()) + assert.equal(fetch.calls.length, 5) + assert.equal(new built.edge.Edge({ fetch }).maxRetries, 1) + })], + // req: rfc9110.15.5.4.should-not-client-automatically-repeat-request-same-credentials — a 403 is never retried, whatever x-should-retry says + ['R49: a 403 is not sent again with the same credentials', () => timed(async () => { + for (const headers of [{}, { 'x-should-retry': 'true' }]) { + const fetch = once(403, headers) + assert.ok((await rejection(shop(built, fetch).system.health())) instanceof built.shop.PermissionDeniedError) + assert.equal(fetch.calls.length, 1) + } + })], + // req: rfc9110.15.must-however-client-understand-class-any-status — 299 a success, 499 a client's error not retried like 400, 599 a server's retried like 500, 399 with no Location an error like 300 (R51: with one, followed as a 300 is) + // req: rfc9110.15.should-client-receives-response-invalid-status-code — 600, 0 and 99.5 read as a 5xx: InternalServerError, retried + ['R50: a status no code is known for is its class\'s x00; a status that is none is a 5xx', () => timed(async () => { + const cases = [[299, 1, null], [499, 1, APIError], [599, 3, InternalServerError], [399, 1, APIError], [304, 1, APIError]] + for (const [status, calls, error] of cases) { + const fetch = stub(() => reply(status, status === 304 ? null : { ok: status }, status === 399 ? {} : { location: '/elsewhere' })) + const p = shop(built, fetch).request('GET', '/x') + if (error === null) assert.deepEqual(await p, { ok: 299 }) + else { + const e = await rejection(p) + assert.ok(e.constructor === error && e.status === status, `${status}: ${e}`) + } + assert.equal(fetch.calls.length, calls, String(status)) + } + for (const status of [600, 0, 99.5]) { + const fetch = stub(() => odd(status)) + const e = await rejection(shop(built, fetch).request('GET', '/x')) + assert.ok(e instanceof InternalServerError && e.status === status, String(e)) + assert.equal(fetch.calls.length, 3) + } + })], + // req: rfc9110.15.4.2.may-user-agent-use-location-field-value — a 301 followed + // req: rfc9110.15.4.2.may-note-historical-reasons-user-agent-change — a POST redirected by 301 is sent again as a GET with no content, as browsers do; a PUT stays a PUT + // req: rfc9110.15.4.3.may-user-agent-use-location-field-value — a 302 followed + // req: rfc9110.15.4.3.may-note-historical-reasons-user-agent-change — a POST redirected by 302 is sent again as a GET with no content + // req: rfc9110.15.4.8.may-user-agent-use-location-field-value — a 307 followed + // req: rfc9110.15.4.8.must-not-307-temporary-redirect-status-code-indicates — a POST redirected by 307 stays a POST with its content + // req: rfc9110.15.4.9.may-user-agent-use-location-field-value — a 308 followed, method and content kept + // req: rfc9110.15.4.1.may-user-agent-use-location-field-value — a 300 with a Location followed, method and content kept + // req: rfc9110.15.4.may-location-header-field-section-10-2 — a 399, which no one defines, with a Location followed as a 300 is; a 304, 305 or 306 with one is not + ['R51: a redirect\'s method: 301 and 302 turn a POST into a GET; 300, 307, 308 and a code no one defines keep it and its content', async () => { + const cases = [[301, 'POST', 'GET'], [302, 'POST', 'GET'], [301, 'PUT', 'PUT'], [307, 'POST', 'POST'], [308, 'POST', 'POST'], [308, 'PATCH', 'PATCH'], [300, 'POST', 'POST'], [399, 'POST', 'POST']] + for (const [status, method, then] of cases) { + const fetch = stub((url) => (url.endsWith('/a') ? reply(status, null, { location: '/v1/b' }) : ok())) + assert.deepEqual(await shop(built, fetch).request(method, '/a', { body: { n: 1 } }), { ok: true }) + const second = fetch.calls[1] + const kept = then === method + assert.deepEqual([second.url, second.init.method, second.init.body, second.headers['content-type']], ['https://api.shop.example/v1/b', then, kept ? '{"n":1}' : undefined, kept ? 'application/json' : undefined], `${status} ${method}`) + } + for (const status of [304, 305, 306]) { + const fetch = stub(() => reply(status, null, { location: '/v1/b' })) + assert.equal((await rejection(shop(built, fetch).request('GET', '/a'))).status, status) + assert.equal(fetch.calls.length, 1, String(status)) + } + }], + // req: rfc9110.15.4.should-client-detect-intervene-cyclical-redirections-i — a request sent again where it went is refused at once; more than 20 redirects are refused + ['R52: a redirect loop is refused at once, a long chain after 20', async () => { + const loop = stub((url) => reply(302, null, { location: url.endsWith('/a') ? '/v1/b' : '/v1/a' })) + const e = await rejection(shop(built, loop).request('GET', '/a')) + assert.ok(e instanceof SdkError && /redirect loop: GET https:\/\/api\.shop\.example\/v1\/a/.test(e.message), String(e)) + assert.equal(loop.calls.length, 2) + const chain = stub((url) => reply(307, null, { location: `/v1/r${Number(url.split('/r').at(-1) ?? 0) + 1}` })) + const long = await rejection(shop(built, chain).request('GET', '/r0')) + assert.ok(long instanceof SdkError && /more than 20 redirects/.test(long.message), String(long)) + assert.equal(chain.calls.length, 21) + }], + // req: rfc9110.10.2.2.must-location-value-provided-3xx-redirection-response — a Location with no fragment inherits the request's; one with a fragment keeps its own + ['R53: a redirect keeps the request\'s fragment where the Location has none', async () => { + const at = (url) => new URL(url).pathname + const fetch = stub((url) => (at(url) === '/v1/a' ? reply(302, null, { location: '/v1/b' }) : at(url) === '/v1/b' ? reply(302, null, { location: '/v1/c#own' }) : ok())) + await shop(built, fetch).request('GET', '/a#top') + assert.deepEqual(fetch.calls.map((c) => c.url), ['https://api.shop.example/v1/a#top', 'https://api.shop.example/v1/b#top', 'https://api.shop.example/v1/c#own']) + }], + // req: rfc9110.9.3.1.should-not-client-generate-content-get-request-unless — a GET sends no content: one given is refused before anything is sent + // req: rfc9110.9.3.2.should-not-client-generate-content-head-request-unless — the same for HEAD + // req: rfc9110.9.3.5.should-not-client-generate-content-delete-request-unless — a DELETE sends content only where the description says it takes one (the server's indication) + ['R54: GET, HEAD and DELETE send no content unless the description declares it', async () => { + const fetch = stub((_, init) => (init.method === 'GET' ? reply(200, []) : reply(init.method === 'HEAD' ? 200 : 204, null))) + const client = hosts(built, fetch) + await client.items.all() + await client.items.check({ path: { id: 1 } }) + await client.items.delete({ path: { id: 1 } }) + await client.items.purge({ body: { contentType: 'application/json', value: [1, 2] } }) + assert.deepEqual(fetch.calls.map((c) => [c.init.method, c.init.body, c.headers['content-type']]), [['GET', undefined, undefined], ['HEAD', undefined, undefined], ['DELETE', undefined, undefined], ['DELETE', '[1,2]', 'application/json']]) + for (const method of ['GET', 'HEAD']) { + const e = await rejection(client.request(method, '/items', { body: { a: 1 } })) + assert.ok(e instanceof built.hosts.SdkError && /carries no content/.test(e.message), String(e)) + } + assert.equal(fetch.calls.length, 4) + }], + // req: rfc9110.9.3.7.must-client-generates-options-request-containing-content — content with OPTIONS goes with its Content-Type; without one it is refused + ['R55: an OPTIONS request with content sends its Content-Type', async () => { + const fetch = stub(() => reply(204, null)) + const client = hosts(built, fetch) + await client.items.describe({ path: { id: 1 }, body: { contentType: 'text/plain', value: 'why' } }) + await client.items.describe({ path: { id: 1 } }) + await client.request('OPTIONS', '/items', { body: { a: 1 } }) + assert.deepEqual(fetch.calls.map((c) => [c.init.body, c.headers['content-type']]), [['why', 'text/plain'], [undefined, undefined], ['{"a":1}', 'application/json']]) + const e = await rejection(client.items.describe({ path: { id: 1 }, body: { contentType: 'text/plain', value: 'why' } }, { headers: { 'Content-Type': null } })) + assert.ok(e instanceof built.hosts.SdkError && /needs a Content-Type/.test(e.message), String(e)) + assert.equal(fetch.calls.length, 3) + }], + ] +} diff --git a/crates/flowapi-sdk/tests/client/layers.mjs b/crates/flowapi-sdk/tests/client/layers.mjs new file mode 100644 index 0000000..dcc1dbd --- /dev/null +++ b/crates/flowapi-sdk/tests/client/layers.mjs @@ -0,0 +1,120 @@ +// Where the credentials meet the client's use of HTTP (the `hosts` case, its optional OAuth 2.0 +// client, and the `tokens` and `auth` cases): the auth layer's renewal beside RFC 9110's retries, +// the token request beside the retry layer, credentials beside redirects and the servers. Each +// test names the pitfall it holds (R, the runtime's list): R56 a 401 renewal counted as a retry, +// or made with another idempotency key, R57 a POST sent more than twice through a renewal, R58 the +// retries made anew after a renewal, R59 a token request retried or redirected to another origin, +// R60 a credential carried by a redirect to another origin, R61 a credential sent in the clear to +// a base URL the servers resolved to `http:`. +import { assert, rejection, reply, stub, timed } from './stub.mjs' + +const credentials = { clientId: 'id', clientSecret: 'secret' } +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +const ok = () => reply(200, [{ id: 1, name: 'a' }]) +/** Asks for a retry at once, so that no backoff is waited. */ +const now = { 'retry-after-ms': '0' } + +const isToken = (url) => new URL(url).pathname.endsWith('/token') + +/** A fetch answering a token endpoint by `token(n)`, its n-th request, and the API by `api(n)`. */ +function server(api, token = (n) => reply(200, { access_token: `tok${n}`, token_type: 'Bearer', expires_in: 3600 })) { + let tokens = 0 + let calls = 0 + const fetch = stub((url, init) => (isToken(url) ? token(++tokens, url, init) : api(++calls, url, init))) + return Object.assign(fetch, { api: () => fetch.calls.filter((c) => !isToken(c.url)), asked: () => fetch.calls.filter((c) => isToken(c.url)) }) +} + +/** A hosts client with the client's own id and secret, quiet. */ +function hosts(built, fetch, more = {}) { + return new built.hosts.Hosts({ fetch, logLevel: 'off', timeout: null, client: credentials, ...more }) +} + +const item = { body: { contentType: 'application/json', value: { name: 'a' } } } + +export function tests(built) { + const { APIConnectionError, CrossOriginRedirectError, InsecureCredentialError, InternalServerError, TokenError } = built.hosts + return [ + ['R56: a 401 renewal is the auth layer\'s one, made with no retry left, and keeps the call\'s idempotency key', () => timed(async () => { + const fetch = server((n) => (n === 1 ? reply(401, { error: 'expired' }) : reply(201, { id: 1, name: 'a' }))) + await hosts(built, fetch, { maxRetries: 0 }).items.create(item) + const [first, again] = fetch.api() + assert.equal(fetch.api().length, 2) + assert.deepEqual([first.init.method, again.init.method], ['POST', 'POST']) + assert.deepEqual([first.headers.authorization, again.headers.authorization], ['Bearer tok1', 'Bearer tok2']) + assert.match(first.headers['idempotency-key'], UUID) + assert.equal(again.headers['idempotency-key'], first.headers['idempotency-key'], 'the renewed call is the same call') + })], + // req: rfc9110.9.2.2.should-not-client-automatically-retry-request-non-idempotent — a POST after a renewal is not retried on its own + ['R57: a POST is sent at most twice through a renewal, whatever maxRetries says', () => timed(async () => { + const make = (fetch) => new built.tokens.Tokens({ fetch, logLevel: 'off', timeout: null, maxRetries: 3, client: credentials }) + const down = server((n) => (n === 1 ? reply(401, { error: 'expired' }) : reply(503, 'down', now))) + await assert.rejects(make(down).things.write(), built.tokens.InternalServerError) + assert.deepEqual(down.api().map((c) => c.init.method), ['POST', 'POST']) + const denied = server(() => reply(401, { error: 'no' })) + await assert.rejects(make(denied).things.write(), built.tokens.AuthenticationError) + assert.deepEqual(denied.calls.map((c) => (isToken(c.url) ? 'token' : c.init.method)), ['token', 'POST', 'token', 'POST']) + })], + ['R58: the retries of a call are counted across its renewal: what is left after it, not maxRetries again', () => timed(async () => { + const answers = [() => reply(503, 'down', now), () => reply(401, { error: 'expired' }), () => reply(503, 'down', now), ok] + const fetch = server((n) => answers[n - 1]()) + await assert.rejects(hosts(built, fetch, { maxRetries: 1 }).items.all(), InternalServerError) + assert.equal(fetch.api().length, 3, '503, its retry 401, the renewed call 503 with no retry left') + const plenty = server((n) => answers[n - 1]()) + await hosts(built, plenty, { maxRetries: 2 }).items.all() + assert.equal(plenty.api().length, 4) + })], + // req: rfc6749.3.2.must-client-use-http-post-method-making — the token request is a POST, sent once + ['R59: a token request is never retried by the retry layer, nor followed to another origin', () => timed(async () => { + const busy = server(ok, () => reply(503, { error: 'temporarily_unavailable' }, now)) + await assert.rejects(hosts(built, busy, { maxRetries: 3 }).items.all(), (e) => e instanceof TokenError && e.status === 503) + assert.deepEqual([busy.asked().length, busy.api().length], [1, 0]) + assert.equal(busy.asked()[0].init.method, 'POST') + const failing = server(ok, () => { + throw new TypeError('fetch failed') + }) + await assert.rejects(hosts(built, failing, { maxRetries: 3 }).items.all(), APIConnectionError) + assert.deepEqual([failing.asked().length, failing.api().length], [1, 0]) + const moved = server(ok, () => reply(307, null, { location: 'https://elsewhere.example/token' })) + const e = await rejection(hosts(built, moved, { allowCrossOriginRedirects: true }).items.all()) + assert.ok(e instanceof CrossOriginRedirectError, String(e)) + assert.ok(!moved.calls.some((c) => c.url.startsWith('https://elsewhere.example')), 'the client secret stayed home') + })], + // req: rfc9110.15.4.should-automatically-following-redirected-request-user-agent — Authorization and Cookie removed when the redirect leaves the origin + ['R60: a redirect to another origin carries no credential: refused by default, stripped when allowed', () => timed(async () => { + const away = (location) => server((n) => (n === 1 ? reply(307, null, { location }) : ok())) + const refused = away('https://other.example/items') + await assert.rejects(hosts(built, refused).items.all(), CrossOriginRedirectError) + assert.equal(refused.api().length, 1) + const allowed = away('https://other.example/items') + await hosts(built, allowed, { allowCrossOriginRedirects: true }).items.all() + assert.deepEqual(allowed.api().map((c) => [c.url, c.headers.authorization]), [['https://eu.hosts.example/v1/items', 'Bearer tok1'], ['https://other.example/items', undefined]]) + const home = away('https://eu.hosts.example/v1/moved') + await hosts(built, home).items.all() + assert.equal(home.api()[1].headers.authorization, 'Bearer tok1', 'the same origin keeps it') + const cookies = stub((_, __, n) => (n === 1 ? reply(307, null, { location: 'https://other.example/cookie' }) : ok())) + await new built.auth.AuthClient({ fetch: cookies, logLevel: 'off', cookieKey: 'c1', allowCrossOriginRedirects: true }).checks.cookie({ cookie: { theme: 'dark' } }) + assert.match(cookies.calls[0].headers.cookie, /c1/) + assert.equal(cookies.calls[1].headers.cookie, undefined) + })], + // req: rfc6750.5.3.must-always-use-tls-https-clients-always — a bearer token only over TLS, to the URL the servers resolved to + ['R61: the TLS rule holds the base URL the servers resolved, a relative one against descriptionURL', () => timed(async () => { + const plain = { descriptionURL: 'http://docs.hosts.example/api/openapi.json' } + const given = server(ok) + const e = await rejection(hosts(built, given, { ...plain, client: 'tok' }).places.local()) + assert.ok(e instanceof InsecureCredentialError && e.message.includes('http://docs.hosts.example/api/'), String(e)) + assert.equal(given.calls.length, 0) + const requested = server(ok) + await assert.rejects(hosts(built, requested, plain).places.local(), InsecureCredentialError) + assert.equal(requested.api().length, 0, 'the API never saw the token') + const none = server(ok) + await hosts(built, none, { ...plain, client: null }).places.local() + await hosts(built, none, { ...plain, client: 'tok', allowInsecureCredentials: true }).places.local() + await hosts(built, none, { descriptionURL: 'https://docs.hosts.example/api/openapi.json', client: 'tok' }).places.local() + assert.deepEqual(none.api().map((c) => [c.url, c.headers.authorization]), [ + ['http://docs.hosts.example/api/status', undefined], + ['http://docs.hosts.example/api/status', 'Bearer tok'], + ['https://docs.hosts.example/api/status', 'Bearer tok'], + ]) + })], + ] +} diff --git a/crates/flowapi-sdk/tests/client/mock.mjs b/crates/flowapi-sdk/tests/client/mock.mjs index e03fe02..ee44b13 100644 --- a/crates/flowapi-sdk/tests/client/mock.mjs +++ b/crates/flowapi-sdk/tests/client/mock.mjs @@ -4,7 +4,11 @@ // `POST /orgs/{org}/secret-scanning/custom-patterns` was answered as // `POST /orgs/{org}/{security_product}/{enablement}`), M2 two templated paths ordered by the first // segment where one is literal and the other a template, the literal one first; both whatever -// the order routes.mjs lists them in. +// the order routes.mjs lists them in. M3 a request that meets none of its operation's security +// alternatives is a 401 naming what each lacks (the mock never checked credentials, so a client +// that sent none passed its tests), and one alternative met, or `{}`, is enough. M4 a token +// endpoint gives a token only to a client credentials grant as RFC 6749 asks for one: POST, form +// encoded, each parameter once, the client in HTTP basic and not in the body. import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { request } from 'node:http' import { tmpdir } from 'node:os' @@ -14,9 +18,9 @@ import { assert } from './stub.mjs' const server = fileURLToPath(new URL('../../src/repo/files/server.mjs', import.meta.url)) -const route = (method, path) => ({ +const route = (method, path, security = []) => ({ route: `${method} ${path}`, method, path, query: [], headers: [], cookies: [], - body: null, status: 200, media: null, example: null, + body: null, security, status: 200, media: null, example: null, }) const routes = [ @@ -27,24 +31,24 @@ const routes = [ ] /** A request by node:http (the platform's fetch keeps timers another test may have faked). */ -function ask(url, method) { +function ask(url, method, headers = {}, body = undefined) { return new Promise((resolve, reject) => { - const req = request(url, { method }, (res) => { + const req = request(url, { method, headers }, (res) => { const chunks = [] res.on('data', (c) => chunks.push(c)) res.on('end', () => resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString() })) }) req.on('error', reject) - req.end() + req.end(body) }) } -/** The route the mock server matched for each request, its routes listed in `order`. */ -async function matched(order, requests) { +/** `f` run against the mock server on these routes and token endpoints, in a temporary folder. */ +async function withMock(order, tokens, f) { const dir = mkdtempSync(join(tmpdir(), 'flowapi-mock-')) try { copyFileSync(server, join(dir, 'server.mjs')) - writeFileSync(join(dir, 'routes.mjs'), `export default ${JSON.stringify(order)}\n`) + writeFileSync(join(dir, 'routes.mjs'), `export default ${JSON.stringify(order)}\nexport const tokens = ${JSON.stringify(tokens)}\n`) writeFileSync(join(dir, 'package.json'), '{"type":"module"}') const { mock } = await import(pathToFileURL(join(dir, 'server.mjs')).href) const saved = process.env.TEST_API_BASE_URL @@ -52,13 +56,7 @@ async function matched(order, requests) { const m = await mock() if (saved !== undefined) process.env.TEST_API_BASE_URL = saved try { - const out = [] - for (const [method, path] of requests) { - const res = await ask(`${m.url}${path}`, method) - assert.equal(res.status, 200, `${method} ${path}: ${res.text}`) - out.push(m.requests.at(-1).route) - } - return out + return await f(m) } finally { await m.close() } @@ -67,6 +65,25 @@ async function matched(order, requests) { } } +/** The route the mock server matched for each request, its routes listed in `order`. */ +function matched(order, requests) { + return withMock(order, [], async (m) => { + const out = [] + for (const [method, path] of requests) { + const res = await ask(`${m.url}${path}`, method) + assert.equal(res.status, 200, `${method} ${path}: ${res.text}`) + out.push(m.requests.at(-1).route) + } + return out + }) +} + +const key = { scheme: 'Key', kind: 'apiKey', in: 'header', name: 'x-key' } +const bearer = { scheme: 'Token', kind: 'bearer' } +const basic = { scheme: 'Basic', kind: 'basic' } +const form = { 'content-type': 'application/x-www-form-urlencoded' } +const pair = `Basic ${Buffer.from('id:secret').toString('base64')}` + export function tests() { const orders = [routes, [...routes].reverse()] return [ @@ -86,5 +103,37 @@ export function tests() { assert.deepEqual(await matched(order, [['GET', '/a/b/b'], ['GET', '/a/c/b']]), ['GET /a/b/{y}', 'GET /a/{x}/b']) } }], + ['M3: a request that meets no security alternative is a 401 naming what each lacks', () => withMock([ + route('GET', '/both', [[key, bearer], [basic]]), + route('GET', '/maybe', [[bearer], []]), + ], [], async (m) => { + const none = await ask(`${m.url}/both`, 'GET') + assert.equal(none.status, 401) + assert.deepEqual(JSON.parse(none.text).missing, [['Key', 'Token'], ['Basic']]) + assert.match(JSON.parse(none.text).error, /send Key and Token, or Basic/) + const half = await ask(`${m.url}/both`, 'GET', { 'x-key': 'k' }) + assert.deepEqual(JSON.parse(half.text).missing, [['Token'], ['Basic']]) + assert.equal((await ask(`${m.url}/both`, 'GET', { 'x-key': 'k', authorization: 'Bearer t' })).status, 200) + assert.equal((await ask(`${m.url}/both`, 'GET', { authorization: pair })).status, 200) + assert.equal((await ask(`${m.url}/both`, 'GET', { authorization: 'Bearer not a token' })).status, 401) + assert.equal((await ask(`${m.url}/maybe`, 'GET')).status, 200) + })], + ['M4: a token endpoint answers a client credentials grant as RFC 6749 4.4 asks for it', () => withMock([], ['/token'], async (m) => { + const ok = await ask(`${m.url}/token`, 'POST', { ...form, authorization: pair }, 'grant_type=client_credentials&scope=read') + assert.equal(ok.status, 200, ok.text) + assert.deepEqual(JSON.parse(ok.text), { access_token: 'mock-token', token_type: 'Bearer', expires_in: 3600, scope: 'read' }) + assert.equal(m.requests.at(-1).route, 'token') + const refused = async (status, error, headers, body, method = 'POST') => { + const r = await ask(`${m.url}/token`, method, headers, body) + assert.equal(r.status, status, r.text) + assert.equal(JSON.parse(r.text).error, error) + } + await refused(401, 'invalid_client', form, 'grant_type=client_credentials&client_id=id&client_secret=secret') + await refused(401, 'invalid_client', { ...form, authorization: pair }, 'grant_type=client_credentials&client_secret=secret') + await refused(400, 'unsupported_grant_type', { ...form, authorization: pair }, 'grant_type=password') + await refused(400, 'invalid_request', { ...form, authorization: pair }, 'grant_type=client_credentials&grant_type=client_credentials') + await refused(400, 'invalid_request', { 'content-type': 'application/json', authorization: pair }, '{}') + await refused(405, 'invalid_request', { authorization: pair }, undefined, 'GET') + })], ] } diff --git a/crates/flowapi-sdk/tests/client/runtime.mjs b/crates/flowapi-sdk/tests/client/runtime.mjs index 1a25085..7d5b09f 100644 --- a/crates/flowapi-sdk/tests/client/runtime.mjs +++ b/crates/flowapi-sdk/tests/client/runtime.mjs @@ -70,6 +70,7 @@ export function tests(built) { assert.equal(fetch.calls.length, 7) }) }], + // req: rfc9110.15.5.9.may-client-outstanding-request-transit-repeat-request — a 408 retried ['R5: which statuses are retried; x-should-retry decides alone', async () => { const cases = [[408, {}, 2], [409, {}, 2], [429, {}, 2], [500, {}, 2], [503, {}, 2], [400, {}, 1], [404, {}, 1], [503, { 'x-should-retry': 'false' }, 1], [400, { 'x-should-retry': 'true' }, 2]] for (const [status, headers, calls] of cases) { diff --git a/crates/flowapi-sdk/tests/client/schemes.mjs b/crates/flowapi-sdk/tests/client/schemes.mjs new file mode 100644 index 0000000..b4f10ab --- /dev/null +++ b/crates/flowapi-sdk/tests/client/schemes.mjs @@ -0,0 +1,157 @@ +// Every kind of scheme the `tokens`, `github` and `swagger` cases declare, as the client sends it: +// credentials only over TLS or to a loopback host, a bearer token only in `Authorization`, HTTP +// basic's control characters refused, an HTTP scheme the client cannot answer refused, a client +// certificate said to be given, `{}` making a credential optional, schemes the config declares +// for a description with none, Swagger 2.0's, and no credential in a log line or across origins. +import { readFileSync } from 'node:fs' +import { assert, reply, stub } from './stub.mjs' + +const ok = () => reply(200, { ok: true }) +const env = ['GITHUB_TOKEN', 'GITHUB_APP_KEY', 'GITHUB_ADMIN_USER', 'GITHUB_ADMIN_PASSWORD', 'SWAGGER_BASIC', 'SWAGGER_HEADER_KEY', 'SWAGGER_QUERY_KEY', 'SWAGGER_CLIENT_ID', 'SWAGGER_CLIENT_SECRET', 'TOKENS_KEY', 'TOKENS_GNAP', 'TOKENS_OIDC'] + +/** Runs `f` with the variables `set` set and the cases' other credential variables unset. */ +async function clean(set, f) { + const before = env.map((k) => process.env[k]) + for (const k of env) delete process.env[k] + Object.assign(process.env, set) + try { + return await f() + } finally { + env.forEach((k, i) => { + if (before[i] === undefined) delete process.env[k] + else process.env[k] = before[i] + }) + } +} + +export function tests(built) { + // Each case has its own runtime, so an error is known by its class's name. + const credential = (e) => e?.name === 'CredentialError' + const insecure = (e) => e?.name === 'InsecureCredentialError' + const tokens = (fetch, more = {}) => new built.tokens.Tokens({ fetch, logLevel: 'off', maxRetries: 0, ...more }) + return [ + // req: rfc6750.5.3.must-always-use-tls-https-clients-always — a bearer token only over https, or to a loopback host + // req: rfc6749.10.3.must-access-token-credentials-well-any-confidential — no token sent in the clear + // req: rfc7617.4.should-not-because-basic-authentication-involves-cleartext-transmission — basic's pair too + // req: rfc6750.5.2.must-not-therefore-bearer-tokens-stored-cookies-sent — a cookie credential is held to the same rule + // req: rfc6750.5.3.must-not-don-t-store-bearer-tokens-cookies — the client keeps no cookie: a bearer token goes in no cookie + ['credentials over http: refused before sending but to a loopback host or with allowInsecureCredentials', () => clean({}, async () => { + const fetch = stub(ok) + await assert.rejects(tokens(fetch, { oidc: 't', baseURL: 'http://api.example' }).others.oidc(), insecure) + await assert.rejects(new built.swagger.Swagger({ fetch, basic: 'u:p', baseURL: 'http://api.example' }).pets.list(), insecure) + await assert.rejects(new built.auth.AuthClient({ fetch, cookieKey: 's', baseURL: 'http://api.example' }).checks.cookie({ cookie: { theme: 'x' } }), insecure) + assert.equal(fetch.calls.length, 0) + for (const base of ['http://localhost:3000', 'http://127.0.0.1', 'http://[::1]:8080']) await tokens(fetch, { oidc: 't', baseURL: base }).others.oidc() + await tokens(fetch, { oidc: 't', baseURL: 'http://api.example', allowInsecureCredentials: true }).others.oidc() + await new built.github.GitHub({ fetch, token: null, baseURL: 'http://api.example' }).meta.get() + assert.equal(fetch.calls.length, 5, 'a call that carries no credential goes over http') + assert.ok(fetch.calls.every((c) => c.headers.cookie === undefined), 'no bearer token in a cookie') + })], + // req: rfc6750.2.must-not-clients-use-more-one-method-transmit — the token in one place only + // req: rfc6750.2.2.must-not-client-use-method-unless-all-following — never in a form body + // req: rfc6750.2.3.should-not-because-security-weaknesses-associated-uri-method — never in the URI + // req: rfc6750.5.3.should-instead-bearer-tokens-passed-http-message — in the Authorization header + // req: rfc6750.5.3.should-not-don-t-pass-bearer-tokens-page — no token in a page URL + ['a bearer token goes in Authorization alone: not in the query, the body or a cookie', () => clean({}, async () => { + const fetch = stub(ok) + await tokens(fetch, { oidc: 'abc.def-1~+/==' }).others.oidc() + await tokens(fetch, { client: 'xyz' }).things.write() + for (const c of fetch.calls) { + assert.ok(!c.url.includes('abc') && !c.url.includes('xyz') && !c.url.includes('access_token'), c.url) + assert.equal(c.init.body, undefined) + assert.equal(c.headers.cookie, undefined) + } + assert.deepEqual(fetch.calls.map((c) => c.headers.authorization), ['Bearer abc.def-1~+/==', 'Bearer xyz']) + await assert.rejects(tokens(fetch, { oidc: 'a b' }).others.oidc(), (e) => credential(e) && /RFC 6750 2\.1/.test(e.message)) + })], + // req: rfc7617.2.must-not-user-id-password-contain-any-control — a control character in either half is refused + ['HTTP basic: a control character in the user-id or the password, or a user-id with a colon, is refused', () => clean({}, async () => { + const fetch = stub(ok) + const call = (basic) => new built.swagger.Swagger({ fetch, basic }).pets.list() + await assert.rejects(call({ username: 'a\u0001', password: 'p' }), credential) + await assert.rejects(call({ username: 'a', password: 'p\n' }), credential) + await assert.rejects(call({ username: 'a:b', password: 'p' }), /RFC 7617/) + await assert.rejects(call('no-colon'), credential) + assert.equal(fetch.calls.length, 0) + await call('ü:p:ß') + assert.equal(fetch.calls[0].headers.authorization, 'Basic ' + Buffer.from('ü:p:ß', 'utf8').toString('base64')) + })], + ['an HTTP scheme sent as given; one that answers a challenge refused, unless the call gives Authorization', () => clean({ TOKENS_GNAP: 'g1' }, async () => { + const fetch = stub(ok) + await tokens(fetch).others.gnap() + assert.equal(fetch.calls[0].headers.authorization, 'gnap g1') + await assert.rejects(tokens(fetch, { digest: 'x' }).others.digest(), (e) => credential(e) && /digest answers a challenge/.test(e.message)) + await tokens(fetch).others.digest({}, { headers: { Authorization: 'Digest username="u", response="r"' } }) + assert.equal(fetch.calls[1].headers.authorization, 'Digest username="u", response="r"') + })], + // req: oas-3.2.security-scheme-object.deprecated.should-consumers-refrain-usage-declared-scheme — a deprecated scheme still works, its option marked @deprecated and the config warned (tests/client/tokens/issues.txt) + ['a client certificate is `true`; `{}` makes a credential optional; a deprecated key still sent', () => clean({}, async () => { + const fetch = stub(ok) + await assert.rejects(tokens(fetch).others.cert(), (e) => credential(e) && /cert/.test(e.message)) + await tokens(fetch, { cert: true }).others.cert() + await tokens(fetch).others.optional() + await tokens(fetch, { legacy: 'k' }).others.optional() + await assert.rejects(tokens(fetch).others.legacy(), credential) + process.env.TOKENS_KEY = 'from-env' + await tokens(fetch).others.legacy() + assert.deepEqual(fetch.calls.map((c) => [c.headers.authorization, c.headers['x-api-key']]), [[undefined, undefined], [undefined, undefined], [undefined, 'k'], [undefined, 'from-env']]) + const kept = (file) => readFileSync(new URL(`./tokens/${file}`, import.meta.url), 'utf8') + assert.match(kept('src/client.ts'), /`Legacy`[^\n]*@deprecated[^\n]*\n {2}legacy\?:/) + assert.match(kept('issues.txt'), /warning\[config\.auth\.deprecated\]: `Legacy` is deprecated/) + })], + ['schemes the config declares for a description with none: an optional token, none, a key, basic from two variables', () => clean({}, async () => { + const fetch = stub(ok) + const gh = (more) => new built.github.GitHub({ fetch, ...more }) + await gh().users.me() + process.env.GITHUB_TOKEN = 'ghp_1' + await gh().users.me() + await gh().meta.get() + await assert.rejects(gh().apps.hook(), (e) => credential(e) && /GITHUB_APP_KEY/.test(e.message)) + await gh({ appKey: 'app' }).apps.hook() + await assert.rejects(gh().enterprise.settings(), (e) => /GITHUB_ADMIN_USER with GITHUB_ADMIN_PASSWORD/.test(e.message)) + Object.assign(process.env, { GITHUB_ADMIN_USER: 'root', GITHUB_ADMIN_PASSWORD: 'pw' }) + await gh().enterprise.settings() + assert.deepEqual(fetch.calls.map((c) => [c.url, c.headers.authorization, c.headers['x-app-key']]), [ + ['https://api.github.example/user', undefined, undefined], + ['https://api.github.example/user', 'Bearer ghp_1', undefined], + ['https://api.github.example/meta', undefined, undefined], + ['https://api.github.example/app/hook', undefined, 'app'], + ['https://api.github.example/enterprise/settings', 'Basic ' + Buffer.from('root:pw').toString('base64'), undefined], + ]) + })], + ["Swagger 2.0: basic by default, a header key else a query key, the application flow's token, none", () => clean({ SWAGGER_BASIC: 'u:p', SWAGGER_QUERY_KEY: 'q' }, async () => { + const fetch = stub((url) => (String(url).endsWith('/oauth/token') ? reply(200, { access_token: 'sw', token_type: 'Bearer' }) : ok())) + const sw = (more) => new built.swagger.Swagger({ fetch, ...more }) + await sw().pets.list() + await sw().pets.add() + await sw({ header: 'h' }).pets.add() + await sw({ app: { clientId: 'c', clientSecret: 's' } }).pets.mine() + await sw({ basic: null }).health.get() + const [list, byQuery, byHeader, token, mine, health] = fetch.calls + assert.equal(list.headers.authorization, 'Basic ' + Buffer.from('u:p').toString('base64')) + assert.equal(byQuery.url, 'https://api.swagger.example/v1/pets?key=q') + assert.deepEqual([byHeader.headers['x-key'], byHeader.url], ['h', 'https://api.swagger.example/v1/pets']) + assert.deepEqual([token.url, token.init.body], ['https://swagger.example/oauth/token', 'grant_type=client_credentials&scope=pets%3Aread']) + assert.equal(mine.headers.authorization, 'Bearer sw') + assert.equal(health.headers.authorization, undefined) + })], + ['no credential in a log line: headers masked, a key in the query redacted, the token request without its secret', () => clean({}, async () => { + const lines = [] + const logger = Object.fromEntries(['error', 'warn', 'info', 'debug'].map((l) => [l, (...a) => lines.push(JSON.stringify(a))])) + const fetch = stub((url) => (String(url).includes('/oauth/token') ? reply(200, { access_token: 'SECRET-TOKEN', token_type: 'Bearer' }) : ok())) + await tokens(fetch, { logLevel: 'debug', logger, client: { clientId: 'id', clientSecret: 'SECRET-CLIENT' }, legacy: 'SECRET-KEY' }).things.list() + await tokens(fetch, { logLevel: 'debug', logger, legacy: 'SECRET-KEY' }).others.legacy() + await new built.swagger.Swagger({ fetch, logLevel: 'debug', logger, query: 'SECRET-QUERY' }).pets.add() + assert.ok(lines.length > 4, 'something was logged') + for (const line of lines) assert.ok(!/SECRET|U0VDUkVU/.test(line), line) + })], + ['a redirect to another origin drops every credential header when it is followed', () => clean({}, async () => { + const fetch = stub((url, init, n) => (n === 1 ? reply(302, '', { location: 'https://elsewhere.example/x' }) : ok())) + await tokens(fetch, { gnap: 'g', allowCrossOriginRedirects: true }).others.gnap() + const legacy = stub((url, init, n) => (n === 1 ? reply(307, '', { location: 'https://elsewhere.example/x' }) : ok())) + await tokens(legacy, { legacy: 'k', allowCrossOriginRedirects: true }).others.legacy() + assert.deepEqual([fetch.calls[0].headers.authorization, fetch.calls[1].headers.authorization], ['gnap g', undefined]) + assert.deepEqual([legacy.calls[0].headers['x-api-key'], legacy.calls[1].headers['x-api-key']], ['k', undefined]) + })], + ] +} diff --git a/crates/flowapi-sdk/tests/client/servers.mjs b/crates/flowapi-sdk/tests/client/servers.mjs new file mode 100644 index 0000000..c42a4d0 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/servers.mjs @@ -0,0 +1,86 @@ +// Where a call goes: the servers of the description as the client uses them. Each test names the +// pitfall it holds (R, the runtime's list): R43 a URL with a user or a password, R44 a server +// variable's value (the caller's, else its default; one outside its `enum` refused), R45 a relative +// server URL, resolved against where the description is served. `hosts` is OpenAPI 3.2, `edge` +// 3.1: the runtime reads both alike, and each version's statements are held by its own case. +import { assert, rejection, reply, stub } from './stub.mjs' + +const ok = () => reply(200, { up: true }) + +function hosts(built, fetch, more = {}) { + return new built.hosts.Hosts({ fetch, logLevel: 'off', timeout: null, ...more }) +} + +function edge(built, fetch, more = {}) { + return new built.edge.Edge({ fetch, logLevel: 'off', timeout: null, ...more }) +} + +export function tests(built) { + const { SdkError } = built.hosts + return [ + // req: rfc9110.4.2.4.must-not-sender-generate-userinfo-subcomponent-delimiter-http — a base URL, a description URL or a redirect's Location with a user or a password is never sent + ['R43: a URL with a user or a password is refused, never sent nor logged', async () => { + const fetch = stub(ok) + const e = await rejection(hosts(built, fetch, { baseURL: 'https://me:secret@h.example' }).places.local()) + assert.ok(e instanceof SdkError && /user name or password/.test(e.message) && !e.message.includes('secret'), String(e)) + assert.throws(() => hosts(built, fetch, { descriptionURL: 'https://me@d.example/openapi.json' }), /user name or password/) + assert.equal(fetch.calls.length, 0) + const away = stub((url) => (url.includes('/items') ? reply(302, null, { location: 'https://me:secret@eu.hosts.example/v1/other' }) : ok())) + const r = await rejection(hosts(built, away).items.all()) + assert.ok(r instanceof SdkError && /user name or password/.test(r.message), String(r)) + assert.equal(away.calls.length, 1) + }], + // req: oas-3.2.server-variable-object.default — the default sent: eu and v1 + // req: oas-3.2.server-variable-object.default.shall-default-value-use-substitution-sent-alternate — no value given: https://eu.hosts.example/v1; one given replaces it + // req: oas-3.2.server-variable-object.enum — `region` takes eu or us; mars is refused before anything is sent + // req: oas-3.2.server-object.variables — each `{name}` of the URL replaced by its variable's value + // req: oas-3.2.operation-object.servers — an operation's own server, its variable checked against its enum when it is used + ['R44: a server variable is the caller\'s value, else its default; a value outside its enum is refused', async () => { + const fetch = stub(ok) + await hosts(built, fetch).items.all() + await hosts(built, fetch, { serverVariables: { region: 'us', version: 'v2' } }).items.all() + await hosts(built, fetch).places.edge() + await hosts(built, fetch, { serverVariables: { zone: 'b' } }).places.edge() + await hosts(built, fetch, { serverVariables: { region: 'us' }, baseURL: 'https://mine.example' }).items.all() + assert.deepEqual(fetch.calls.map((c) => c.url), ['https://eu.hosts.example/v1/items', 'https://us.hosts.example/v2/items', 'https://a.edge.example/edge', 'https://b.edge.example/edge', 'https://mine.example/items']) + assert.equal(hosts(built, fetch, { serverVariables: { version: 'anything/at all' } }).baseURL, 'https://eu.hosts.example/anything/at all') + assert.throws(() => hosts(built, fetch, { serverVariables: { region: 'mars' } }), (e) => e instanceof RangeError && /`mars` is not a value of the server variable `region`.*`eu`, `us`/.test(e.message)) + const zone = await rejection(hosts(built, fetch, { serverVariables: { zone: 'c' } }).places.edge()) + assert.ok(zone instanceof RangeError && /`c` is not a value of the server variable `zone`/.test(zone.message), String(zone)) + assert.equal(fetch.calls.length, 5) + }], + // req: oas-3.1.server-variable-object.default — the default sent: a and v3 + // req: oas-3.1.server-variable-object.default.shall-default-value-use-substitution-sent-alternate — no value given: https://a.edge.example/v3; one given replaces it + // req: oas-3.1.server-variable-object.enum — `zone` takes a or b; z is refused + ['R44: the same in OpenAPI 3.1', async () => { + const fetch = stub(ok) + await edge(built, fetch).zones.status() + await edge(built, fetch, { serverVariables: { zone: 'b', version: 'v4' } }).zones.status() + assert.deepEqual(fetch.calls.map((c) => c.url), ['https://a.edge.example/v3/status', 'https://b.edge.example/v4/status']) + assert.throws(() => edge(built, fetch, { serverVariables: { zone: 'z' } }), RangeError) + }], + // req: oas-3.2.server-object.relative-references-in-api-urls.may-unless-specified-otherwise-all-fields-urls — a server URL `.` resolved against the description's retrieval URL, as the specification's example + // req: oas-3.2.server-object.relative-references-in-api-urls.may-note-themselves-relative-referring-document — `.` of a Path Item is the description's own folder + // req: oas-3.2.server-object.url.may-url-supports-server-variables-relative-indicate — a relative URL sends to where the description is served; without `descriptionURL` it cannot be sent + // req: oas-3.2.path-item-object.servers — a Path Item's relative server serves its operation + ['R45: a relative server URL is resolved against where the description is served', async () => { + const fetch = stub(ok) + const none = await rejection(hosts(built, fetch).places.local()) + assert.ok(none instanceof SdkError && /not absolute.*`descriptionURL`/.test(none.message), String(none)) + await hosts(built, fetch, { descriptionURL: 'https://device1.example.com' }).places.local() + await hosts(built, fetch, { descriptionURL: 'https://device1.example.com/specs/hosts.json' }).places.local() + await hosts(built, fetch, { descriptionURL: 'https://device1.example.com/specs/hosts.json' }).items.all() + assert.deepEqual(fetch.calls.map((c) => c.url), ['https://device1.example.com/status', 'https://device1.example.com/specs/status', 'https://eu.hosts.example/v1/items']) + assert.throws(() => hosts(built, fetch, { descriptionURL: '/specs/hosts.json' }), (e) => e instanceof TypeError && /absolute URL/.test(e.message)) + }], + // req: oas-3.1.relative-references-in-api-urls.may-unless-specified-otherwise-all-fields-urls — `./near` of a Path Item resolved against the description's URL + // req: oas-3.1.relative-references-in-api-urls.may-note-themselves-relative-referring-document — relative to the description that holds it, its folder + // req: oas-3.1.server-object.url.may-url-supports-server-variables-relative-indicate — the relative URL sent to where the description is served + ['R45: the same in OpenAPI 3.1', async () => { + const fetch = stub(ok) + await edge(built, fetch, { descriptionURL: 'https://cdn.example/specs/edge.json' }).zones.near() + assert.deepEqual(fetch.calls.map((c) => c.url), ['https://cdn.example/specs/near/near']) + assert.ok((await rejection(edge(built, fetch).zones.near())) instanceof built.edge.SdkError) + }], + ] +} diff --git a/crates/flowapi-sdk/tests/client/shop/flowapi-sdk.yml b/crates/flowapi-sdk/tests/client/shop/flowapi-sdk.yml index d97d1ce..972ee01 100644 --- a/crates/flowapi-sdk/tests/client/shop/flowapi-sdk.yml +++ b/crates/flowapi-sdk/tests/client/shop/flowapi-sdk.yml @@ -2,7 +2,7 @@ # download read as bytes, two alternatives of security and one operation that needs none. version: 1 spec: spec.json -package: { name: "@shop/sdk", version: 1.2.0, client: Shop, license: MIT, repository: https://github.com/shop/sdk } +package: { name: "@shop/sdk", version: 1.2.0, client: Shop, license: MIT, repository: https://github.com/shop/sdk, keywords: [pets, shop] } environments: production: https://api.shop.example/v1 sandbox: https://sandbox.shop.example/v1 diff --git a/crates/flowapi-sdk/tests/client/shop/spec.json b/crates/flowapi-sdk/tests/client/shop/spec.json index dcdc9ae..59af016 100644 --- a/crates/flowapi-sdk/tests/client/shop/spec.json +++ b/crates/flowapi-sdk/tests/client/shop/spec.json @@ -1,6 +1,6 @@ { "openapi": "3.1.0", - "info": { "title": "Shop", "version": "1" }, + "info": { "title": "Shop API", "version": "1", "description": "Sells **pets** and their photos. The [guide](https://shop.example/docs) says more.\n\n## Limits\n\nA hundred calls a minute." }, "servers": [{ "url": "https://api.shop.example/v1" }], "security": [{ "ApiKeyAuth": [] }, { "BearerAuth": [] }], "paths": { @@ -20,6 +20,9 @@ }, "post": { "operationId": "createPet", + "summary": "Add a pet", + "description": "Adds a pet to the shop.\n\nIts `name` must be unique: a taken one is answered `409`.\n\n```json\n{ \"name\": \"Rex\" }\n```\n\n@internal is no tag here.", + "externalDocs": { "url": "https://shop.example/docs/pets", "description": "Pets, in the [guide](https://shop.example/docs)" }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } }, "responses": { "201": { "description": "made", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" } } } }, @@ -45,6 +48,7 @@ }, "delete": { "operationId": "deletePet", + "deprecated": true, "responses": { "204": { "description": "gone" } } } }, diff --git a/crates/flowapi-sdk/tests/client/shop/src/api.ts b/crates/flowapi-sdk/tests/client/shop/src/api.ts index 6ff5405..74c3537 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/api.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/api.ts @@ -99,6 +99,9 @@ export type GetPet = { }; }; +/** + * @deprecated + */ export type DeletePet = { parameters: { path: { @@ -290,6 +293,7 @@ export type Paths = { }; "/pets/{pet_id}": { get: GetPet; + /** @deprecated */ delete: DeletePet; patch: UpdatePet; }; @@ -464,10 +468,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -481,6 +486,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -493,7 +499,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -518,6 +524,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -563,30 +582,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -621,6 +625,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -651,51 +743,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -711,7 +842,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -727,53 +858,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting @@ -1054,7 +1199,7 @@ export function listPhotosResponse( return $read($listPhotosResponse, status, headers, body) as ReturnType; } -export function uploadPhotoRequest(input: NonNullable & { body: { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding } }): $Request { +export function uploadPhotoRequest(input: NonNullable & { body: { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart } }): $Request { const headers: Record = {}; const request: $Request = { method: "POST", path: "/pets/" + $seg(($x(input.path?.["pet_id"], "pet_id", "", ",", false, "", false, ",", $enc, "path", "pet_id") ?? ""), "pet_id", false) + "/photos", query: "", headers }; if (input.body !== undefined) $put(request, input.body); @@ -1212,8 +1357,10 @@ export const flowapiServers = [ /** * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a * cookie under `name`; `http` as `Authorization: `; `oauth2` and - * `openIdConnect` a token the caller obtained, sent as a bearer token. `mutualTLS` is a client - * certificate, which no request carries: a client cannot send it, only its transport can. + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. */ export const flowapiSecuritySchemes = { "ApiKeyAuth": { type: "apiKey", in: "header", name: "X-API-Key" }, @@ -1225,9 +1372,10 @@ export const flowapiSecuritySchemes = { * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the - * answer sends, as `flowapiReadsBytes` says); by `multipart/form-data` media type, the type - * each part is sent as (`encoding`, the description's Encoding Objects: give it as - * `body.encoding`); and its `Request` and `Response`. + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. */ export const flowapiOperations = { listPets: { @@ -1283,7 +1431,7 @@ export const flowapiOperations = { path: "/pets/{pet_id}/photos", security: [{ "ApiKeyAuth": [] }, { "BearerAuth": [] }], responses: { "201": { content: { "application/json": "json" } } }, - encoding: { "multipart/form-data": { "photo": { contentType: "image/png" } } }, + encoding: { "multipart/form-data": { encoding: { "photo": { contentType: "image/png" } } } }, request: uploadPhotoRequest, response: uploadPhotoResponse, }, diff --git a/crates/flowapi-sdk/tests/client/shop/src/client.ts b/crates/flowapi-sdk/tests/client/shop/src/client.ts index 262569a..c67762f 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/client.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/client.ts @@ -28,13 +28,14 @@ const $settings: $core.Settings = { /** The options of a `Shop`: the runtime's, and a credential for each security scheme it sends. */ export type ShopOptions = $core.ClientOptions<"production" | "sandbox"> & { - /** The credential of the security scheme `ApiKeyAuth`, else `SHOP_API_KEY`; `null` reads no variable. */ + /** The credential of the security scheme `ApiKeyAuth`: the key, else `SHOP_API_KEY`; `null` reads no variable. */ apiKeyAuth?: $core.Credential | null | undefined; - /** The credential of the security scheme `BearerAuth`, else `SHOP_TOKEN`; `null` reads no variable. */ + /** The credential of the security scheme `BearerAuth`: the token, else `SHOP_TOKEN`; `null` reads no variable. */ bearerAuth?: $core.Credential | null | undefined; }; -/** The API's client: a member for each resource of the config. */ +/** The API's client: a member for each resource (`client.pets`), and `request` for a call no + * operation describes. */ export class Shop { readonly #core: $core.Core; readonly #options: ShopOptions; diff --git a/crates/flowapi-sdk/tests/client/shop/src/index.ts b/crates/flowapi-sdk/tests/client/shop/src/index.ts index 362c982..798f70e 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/index.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/index.ts @@ -10,26 +10,36 @@ export { AuthenticationError, BadRequestError, type BasicCredential, + type BasicPair, + type ClientCredentials, ConflictError, type Credential, + CredentialError, CrossOriginRedirectError, + type Data, type Fetch, type FetchResponse, type HeadersInput, + type Input, + InsecureCredentialError, InternalServerError, + type ItemOf, type LogLevel, type Logger, NotFoundError, + type Outcome, Page, PagePromise, PermissionDeniedError, type QueryInput, RateLimitError, + type RawRequest, type RequestOptions, RequestTimeoutError, SdkError, type ServerSentEvent, Stream, + TokenError, UnprocessableEntityError, } from "./core/index.js"; export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/events.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/events.ts index adc7e04..52b4e9f 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/events.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/events.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `events`. */ +/** The methods of `client.events`. */ export class Events { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/owners.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/owners.ts index bcb8212..5085f2a 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/owners.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/owners.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `owners`. */ +/** The methods of `client.owners`. */ export class Owners { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/pages.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/pages.ts index ef67c79..991074c 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/pages.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/pages.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `pages`. */ +/** The methods of `client.pages`. */ export class Pages { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/pets.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/pets.ts index 2710357..440df4d 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/pets.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/pets.ts @@ -4,7 +4,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; import { Photos as $Photos } from "./pets/photos.js"; -/** The resource `pets`. */ +/** The methods of `client.pets`. */ export class Pets { readonly #core: $core.Core; readonly photos: $Photos; @@ -14,17 +14,36 @@ export class Pets { this.photos = new $Photos(core); } - /** `GET /pets`: List the pets *\/ one page at a time */ + /** + * List the pets *\/ one page at a time + * + * `GET /pets` + */ list(params: $core.Input = {}, options?: $core.RequestOptions): $core.PagePromise<$core.ItemOf<$core.Data, ["data"]>> { return $core.page(this.#core, $api.flowapiOperations.listPets, params, { type: "cursor", cursor: ["query", "page_token"], limit: ["query", "limit"], items: ["data"], next: ["next_page_token"], hasMore: ["has_more"] }, options); } - /** `POST /pets` */ + /** + * Add a pet + * + * Adds a pet to the shop. + * + * Its name must be unique: a taken one is answered 409. + * + * \@internal is no tag here. + * + * `POST /pets` + * @see https://shop.example/docs/pets Pets, in the guide + */ create(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { return $core.call(this.#core, $api.flowapiOperations.createPet, params, options); } - /** `GET /pets/{pet_id}`: One pet */ + /** + * One pet + * + * `GET /pets/{pet_id}` + */ retrieve(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { return $core.call(this.#core, $api.flowapiOperations.getPet, params, options, 0); } @@ -34,7 +53,10 @@ export class Pets { return $core.call(this.#core, $api.flowapiOperations.updatePet, params, options); } - /** `DELETE /pets/{pet_id}` */ + /** + * `DELETE /pets/{pet_id}` + * @deprecated The API's description marks this operation deprecated. + */ delete(params: $core.Input, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { return $core.call(this.#core, $api.flowapiOperations.deletePet, params, options); } diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/pets/photos.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/pets/photos.ts index 05393a9..315ac27 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/pets/photos.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/pets/photos.ts @@ -3,7 +3,7 @@ import * as $api from "../../api.js"; import * as $core from "../../core/index.js"; -/** The resource `pets.photos`. */ +/** The methods of `client.pets.photos`. */ export class Photos { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/system.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/system.ts index 7bd0340..1789583 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/system.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/system.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `system`. */ +/** The methods of `client.system`. */ export class System { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/tags.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/tags.ts index 7644fd1..ac708d0 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/tags.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/tags.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `tags`. */ +/** The methods of `client.tags`. */ export class Tags { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/shop/src/resources/users.ts b/crates/flowapi-sdk/tests/client/shop/src/resources/users.ts index 623ea9b..ca3116f 100644 --- a/crates/flowapi-sdk/tests/client/shop/src/resources/users.ts +++ b/crates/flowapi-sdk/tests/client/shop/src/resources/users.ts @@ -3,7 +3,7 @@ import * as $api from "../api.js"; import * as $core from "../core/index.js"; -/** The resource `users`. */ +/** The methods of `client.users`. */ export class Users { readonly #core: $core.Core; diff --git a/crates/flowapi-sdk/tests/client/swagger/flowapi-sdk.yml b/crates/flowapi-sdk/tests/client/swagger/flowapi-sdk.yml new file mode 100644 index 0000000..727b4c3 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/flowapi-sdk.yml @@ -0,0 +1,21 @@ +# Swagger 2.0's securityDefinitions: basic, API keys in a header and in the query (alternatives), +# and an OAuth 2.0 `application` flow (client credentials) whose scopes hold an extension; a +# scheme's extension; an operation that needs none. +version: 1 +spec: spec.json +package: { name: swagger-sdk, client: Swagger, license: MIT } +auth: + basic: { env_var: SWAGGER_BASIC } + header: { env_var: SWAGGER_HEADER_KEY } + query: { env_var: SWAGGER_QUERY_KEY } + app: { client_id_env_var: SWAGGER_CLIENT_ID, client_secret_env_var: SWAGGER_CLIENT_SECRET } +defaults: { retries: 0 } +resources: + pets: + methods: + list: listPets + add: addPet + mine: myPets + health: + methods: + get: health diff --git a/crates/flowapi-sdk/tests/client/swagger/issues.txt b/crates/flowapi-sdk/tests/client/swagger/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/client/swagger/spec.json b/crates/flowapi-sdk/tests/client/swagger/spec.json new file mode 100644 index 0000000..aaa8289 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/spec.json @@ -0,0 +1,28 @@ +{ + "swagger": "2.0", + "info": { "title": "Swagger", "version": "1" }, + "host": "api.swagger.example", + "basePath": "/v1", + "schemes": ["https"], + "produces": ["application/json"], + "security": [{ "basic": [] }], + "securityDefinitions": { + "basic": { "type": "basic", "description": "A user and password", "x-vendor": "kept out" }, + "header": { "type": "apiKey", "in": "header", "name": "X-Key" }, + "query": { "type": "apiKey", "in": "query", "name": "key" }, + "app": { + "type": "oauth2", + "flow": "application", + "tokenUrl": "https://swagger.example/oauth/token", + "scopes": { "pets:read": "Read pets", "x-note": "an extension, no scope" } + } + }, + "paths": { + "/pets": { + "get": { "operationId": "listPets", "responses": { "200": { "description": "ok", "schema": { "type": "object" } } } }, + "post": { "operationId": "addPet", "security": [{ "header": [] }, { "query": [] }], "responses": { "200": { "description": "ok", "schema": { "type": "object" } } } } + }, + "/pets/mine": { "get": { "operationId": "myPets", "security": [{ "app": ["pets:read"] }], "responses": { "200": { "description": "ok", "schema": { "type": "object" } } } } }, + "/health": { "get": { "operationId": "health", "security": [], "responses": { "200": { "description": "ok", "schema": { "type": "object" } } } } } + } +} diff --git a/crates/flowapi-sdk/tests/client/swagger/src/api.ts b/crates/flowapi-sdk/tests/client/swagger/src/api.ts new file mode 100644 index 0000000..30f760d --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/src/api.ts @@ -0,0 +1,960 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +export type ListPets = { + responses: { + "200": { + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + }; +}; + +export type AddPet = { + responses: { + "200": { + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + }; +}; + +export type MyPets = { + responses: { + "200": { + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + }; +}; + +export type Health = { + responses: { + "200": { + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + }; +}; + +export type Paths = { + "/pets": { + get: ListPets; + post: AddPet; + }; + "/pets/mine": { + get: MyPets; + }; + "/health": { + get: Health; + }; +}; + +// The SDK: for each operation, a function that writes its request and one that reads its +// response. No I/O: send the request with any HTTP client, give its answer back. + +/** + * A request to send. `path` goes after the server's base URL; `query` is the query string + * without its `?`, empty for none; `body` text, or bytes (a multipart body, bytes given). + */ +export type $Request = { + method: string; + path: string; + query: string; + headers: Record; + body?: string | Uint8Array; +}; + +/** + * A request `Request` refuses to write: a value that would change what the request means + * rather than what it says. `location` is where it goes (`path`, `query`, `querystring`, + * `header`, `cookie` or `body`), `parameter` the parameter's name as the description writes it + * (`null` for the body; a multipart part's name), `reason` why: a CR, LF or NUL in a header, a + * cookie or a part's head (it would start another header), a path segment left empty or made `.` + * or `..` (a client or a server would remove it and the one before it), NaN or an infinity (JSON + * has no number for them). In a multipart body also: `null` where a part goes (`null`), a member + * of an array of parts that is not an object (`unnamed-part`), a Blob not read yet + * (`unread-blob`: `flowapiBlob` reads it), a `"` or `\` in a name or a file name (`quote`), a + * file name that is empty, `.` or `..` (`file-name`), a part header's name that is not a token or + * is `Content-Disposition` (`header-name`), a list or a range for a part's type (`media-range`), + * a boundary RFC 2046 does not allow or that a part holds (`boundary`). + */ +export class FlowapiRequestError extends Error { + readonly location: string; + readonly parameter: string | null; + readonly reason: + | "control-character" | "empty-segment" | "dot-segment" | "non-finite" | "null" | "unnamed-part" + | "unread-blob" | "quote" | "file-name" | "header-name" | "media-range" | "boundary"; + constructor(location: string, parameter: string | null, reason: FlowapiRequestError["reason"]) { + const what = location === "body" ? "the body" + (parameter === null ? "" : `'s part \`${parameter}\``) : `the ${location} parameter \`${parameter}\``; + super(`${what}: ${reason}`); + this.name = "FlowapiRequestError"; + this.location = location; + this.parameter = parameter; + this.reason = reason; + } +} + +const $unreserved = /^[A-Za-z0-9\-._~]*$/; +const $marks = /[!'()*]/g; +const $marked = /[!'()*]/; +const $kept = /%[0-9A-Fa-f]{2}|[:/?#[\]@!$&'()*+,;=]/g; + +function $mark(c: string): string { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +} + +/** RFC 3986: every character but the unreserved ones percent-encoded, as UTF-8. */ +function $enc(s: string): string { + if ($unreserved.test(s)) return s; + const e = encodeURIComponent(s); + return $marked.test(e) ? e.replace($marks, $mark) : e; +} + +/** RFC 6570's reserved expansion: reserved characters and percent-encoded triples kept. */ +function $res(s: string): string { + if ($unreserved.test(s)) return s; + $kept.lastIndex = 0; + let out = ""; + let last = 0; + let m: RegExpExecArray | null; + while ((m = $kept.exec(s)) !== null) { + out += $enc(s.slice(last, m.index)) + m[0]; + last = $kept.lastIndex; + } + return out + $enc(s.slice(last)); +} + +/** Headers and `style: cookie` take values as they are (3.2, Appendix D). */ +function $raw(s: string): string { + return s; +} + +const $dot = /^(?:\.|%2e){1,2}$/i; + +/** A value written raw, refused if it holds a CR, LF or NUL: it would end its header. */ +function $ctl(s: string | undefined, at: string, name: string): string | undefined { + if (s !== undefined && (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0)) { + throw new FlowapiRequestError(at, name, "control-character"); + } + return s; +} + +/** A path segment a parameter wrote, refused when empty or a dot segment (`.`, `..`, a dot as + * `%2E` too, as WHATWG's URL parser reads it). `pieces`: a parameter of it keeps `/` + * (`allowReserved`), and each piece between them is held to the same. */ +function $seg(s: string, name: string, pieces: boolean): string { + // A dot segment is at most 6 characters (`%2e%2e`) and starts with `.` or `%`: a longer one + // is none, and is not read (reading a string made by `+` would flatten it). + if (!pieces && s.length > 6) return s; + if (s.length === 0) throw new FlowapiRequestError("path", name, "empty-segment"); + const c = s.charCodeAt(0); + if (!pieces && c !== 46 && c !== 37) return s; + if ($dot.test(s) || (pieces && s.split("/").some((p) => $dot.test(p)))) { + throw new FlowapiRequestError("path", name, "dot-segment"); + } + return s; +} + +/** Whether a value holds NaN or an infinity anywhere. */ +function $bad(v: unknown): boolean { + if (typeof v === "number") return v - v !== 0; + if (v === null || typeof v !== "object") return false; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) if ($bad(v[i])) return true; + return false; + } + for (const key in v) if ($bad((v as Record)[key])) return true; + return false; +} + +/** A parameter's value, refused when it holds NaN or an infinity: JSON has no number for them, + * and their text would reach the server as a string. */ +function $fin(v: T, at: string, name: string): T { + if (typeof v === "number" ? v - v !== 0 : typeof v === "object" && v !== null && $bad(v)) { + throw new FlowapiRequestError(at, name, "non-finite"); + } + return v; +} + +/** A value as text: a string as it is, a number, boolean or bigint by `String`, else JSON. */ +function $str(v: unknown): string { + switch (typeof v) { + case "string": + return v; + case "number": + case "boolean": + case "bigint": + return String(v); + default: + return JSON.stringify(v) ?? ""; + } +} + +/** + * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, + * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. + */ +function $x( + v: unknown, + name: string, + first: string, + sep: string, + named: boolean, + ifemp: string, + explode: boolean, + join: string, + enc: (s: string) => string, + at: string, + pname: string, + nest?: readonly string[], +): string | undefined { + if (v === undefined) return undefined; + if (v === null) return ifemp === "=" ? name + "=" : ""; + let out = ""; + let n = 0; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) { + const item: unknown = v[i]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); + if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); + else out += (n++ ? (explode ? sep : join) : "") + s; + } + } else if (typeof v === "object") { + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const k = enc(key); + const s = enc($str(item)); + if (explode) out += (n++ ? sep : "") + k + (s === "" && named ? ifemp : "=" + s); + else out += (n++ ? join : "") + k + join + s; + } + } else { + if (typeof v === "number" && v - v !== 0) throw new FlowapiRequestError(at, pname, "non-finite"); + const s = enc($str(v)); + return first + (named ? name + (s === "" ? ifemp : "=" + s) : s); + } + if (n === 0) return undefined; + return first + (named && !explode ? name + "=" + out : out); +} + +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + +/** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an + * array's items repeat their key. */ +function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { + if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined; + const out = $members(v as Record, name, enc, ""); + return out === "" ? undefined : out; +} + +function $members(v: Record, path: string, enc: (s: string) => string, acc: string): string { + for (const key in v) { + if (!Object.prototype.hasOwnProperty.call(v, key)) continue; + const item = v[key]; + if (item === null || item === undefined) continue; + const at = path + "%5B" + enc(key) + "%5D"; + if (Array.isArray(item)) { + for (let i = 0; i < item.length; i++) { + const one: unknown = item[i]; + if (one !== null && one !== undefined) acc += (acc === "" ? "" : "&") + at + "=" + enc($str(one)); + } + } else if (typeof item === "object") { + acc = $members(item as Record, at, enc, acc); + } else { + acc += (acc === "" ? "" : "&") + at + "=" + enc($str(item)); + } + } + return acc; +} + +/** `s` added to a query string or a cookie header, after `sep`. */ +function $add(acc: string, s: string | undefined, sep: string): string { + return s === undefined ? acc : acc === "" ? s : acc + sep + s; +} + +/** The media type without its parameters, in lower case. */ +function $bare(type: string): string { + const semi = type.indexOf(";"); + return (semi < 0 ? type : type.slice(0, semi)).trim().toLowerCase(); +} + +/** `application/json` and every `+json` type (RFC 6839). */ +function $json(type: string): boolean { + const bare = $bare(type); + return bare === "application/json" || bare.endsWith("+json"); +} + +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { + if (v instanceof Uint8Array) return v; + if (!$json(type)) { + if ($bare(type) === "application/x-www-form-urlencoded") { + if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); + return $form(v, enc); + } + if (typeof v === "string") return v; + } + // `JSON.stringify` writes NaN and the infinities as `null`: with no `null` in the text there is + // none, and the value is walked only when there is one. + const text = JSON.stringify(v); + if (text !== undefined && text.indexOf("null") >= 0 && $bad(v)) { + throw new FlowapiRequestError("body", null, "non-finite"); + } + return text; +} + +/** A parameter with `content`: its value as its media type's text, then written as a string. */ +function $content(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + return $json(type) ? JSON.stringify(v) : $str(v); +} + +/** `in: querystring`: the whole query string, a form as one, any other type percent-encoded. */ +function $qs(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + if ($bare(type) === "application/x-www-form-urlencoded") return $form(v); + return $enc($json(type) ? JSON.stringify(v) : $str(v)); +} + +/** A header set when it has a value; a CR, LF or NUL in it is refused (it would end the header). */ +function $set(headers: Record, name: string, s: string | undefined): void { + if (s === undefined) return; + if (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0) { + throw new FlowapiRequestError("header", name, "control-character"); + } + headers[name] = s; +} + +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + +/** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's + * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or + * `flowapiBlob`. */ +export class FlowapiFile { + readonly data: Uint8Array; + readonly name: string | undefined; + readonly type: string | undefined; + constructor(data: Uint8Array, name: string | undefined, type: string | undefined) { + this.data = data; + this.name = name; + this.type = type; + } +} + +/** A file from bytes, or from text as its UTF-8, with the name and the type to send it as. */ +export function flowapiFile(data: Uint8Array | string, name?: string, type?: string): FlowapiFile { + return new FlowapiFile(typeof data === "string" ? $bytes(data) : data, name, type); +} + +/** What `flowapiBlob` reads of a `Blob` or a `File`, typed here so the output type-checks + * without the DOM's declarations. */ +export type $Blob = { readonly type: string; readonly name?: string; arrayBuffer(): Promise }; + +/** A `Blob` or a `File` read into a `FlowapiFile`: its bytes, `name` or else a File's own, `type` + * or else the Blob's. The one step that waits: `Request` takes bytes and stays synchronous. */ +export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); +} + +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; +}; + +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + +/** A `multipart/form-data` value as `Request` takes it: a string member may also be a file + * (the types cannot tell `format: binary` from text), an array member's items one part each. */ +type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; +type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; +type $Fields = T extends object ? { [K in keyof T]: $Member } : T; +export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; + +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; + +/** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ +function $put(request: $Request, body: $Given): void { + const v = body.value; + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); + request.headers["content-type"] = type; + request.body = bytes; + return; + } + request.headers["content-type"] = body.contentType; + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; +} + +/** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ +type $Part = { head: string; data: Uint8Array }; + +let $encoder: { encode(text: string): Uint8Array } | undefined; + +/** Text as UTF-8 bytes. */ +function $bytes(text: string): Uint8Array { + $encoder ??= new (globalThis as unknown as $Coders).TextEncoder(); + return $encoder.encode(text); +} + +const $breaks = /[\r\n\0]/; +const $quotes = /["\\]/; +const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes + * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a + * receiver could read another name. */ +function $safe(s: string, part: string | null, quoted: boolean): string { + if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); + if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); + return s; +} + +/** A file's name as its part's `filename`: its last path segment (a sender's directories are not + * the receiver's), refused when that is empty, `.` or `..`, and when the name holds a CR, LF or + * NUL anywhere (cut off with a directory, it would still be meant). */ +function $filename(name: string, part: string): string { + $safe(name, part, false); + const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1); + if (base === "" || base === "." || base === "..") throw new FlowapiRequestError("body", part, "file-name"); + return $safe(base, part, true); +} + +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { + if (v === undefined) return; + $safe(name, name, true); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); +} + +/** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's + * `blob` for a name not given, `application/octet-stream` for a type not given), strings, + * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); + // Bytes in any other view are the same bytes. + if (v instanceof ArrayBuffer) v = new Uint8Array(v); + else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; + let type = e?.contentType; + let data: Uint8Array; + if (v instanceof FlowapiFile || v instanceof Uint8Array) { + const file = v instanceof FlowapiFile ? v : undefined; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; + type = file?.type ?? type ?? "application/octet-stream"; + data = file?.data ?? (v as Uint8Array); + } else if ($unread(v)) { + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); + } else { + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); + type ??= typeof v === "object" ? "application/json" : undefined; + // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); + data = typeof s === "string" ? $bytes(s) : s; + } + if (type !== undefined) { + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); + } + const headers = e?.headers ?? {}; + for (const key of Object.keys(headers)) { + const value = headers[key]; + const lower = key.toLowerCase(); + if (value === undefined || lower === "content-type") continue; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); + } + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); +} + +/** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting + * (`flowapiBlob`), and as JSON it would be `{}`. */ +function $unread(v: unknown): boolean { + return typeof v === "object" && v !== null && typeof (v as { arrayBuffer?: unknown }).arrayBuffer === "function"; +} + +const $bchars = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; + +/** Whether `needle` occurs in `data`. */ +function $holds(data: Uint8Array, needle: Uint8Array): boolean { + const first = needle[0] ?? 0; + for (let i = data.indexOf(first); i >= 0 && i + needle.length <= data.length; i = data.indexOf(first, i + 1)) { + let j = 1; + while (j < needle.length && data[i + j] === needle[j]) j++; + if (j === needle.length) return true; + } + return false; +} + +/** Whether a boundary occurs in any part: a delimiter in a part would end it there. */ +function $collides(parts: $Part[], boundary: string): boolean { + const b = $bytes(boundary); + return parts.some((p) => p.head.indexOf(boundary) >= 0 || $holds(p.data, b)); +} + +/** A boundary of 128 random bits from `globalThis.crypto`, so no content can be made to hold it. */ +function $random(): string { + const c = (globalThis as unknown as { crypto?: { getRandomValues(b: Uint8Array): Uint8Array } }).crypto; + if (c === undefined) throw new Error("flowapi: no globalThis.crypto to draw a multipart boundary from; give one: `multipart/form-data; boundary=...`"); + let s = "flowapi-"; + for (const x of c.getRandomValues(new Uint8Array(16))) s += (x < 16 ? "0" : "") + x.toString(16); + return s; +} + +/** The parts written with a boundary (RFC 2046, 5.1.1; RFC 7578): the one the content type + * gives (`boundary=`), refused when RFC 2046 does not allow it or a part holds it, or one drawn + * at random and added to the content type, drawn again while a part holds it. */ +function $multipart(contentType: string, parts: $Part[]): [string, Uint8Array] { + const given = /;\s*boundary\s*=\s*(?:"([^"]*)"|([^;\s]*))/i.exec(contentType); + let boundary: string; + let type = contentType; + if (given !== null) { + boundary = given[1] ?? given[2] ?? ""; + if (!$bchars.test(boundary) || $collides(parts, boundary)) throw new FlowapiRequestError("body", null, "boundary"); + } else { + boundary = $random(); + for (let tries = 1; $collides(parts, boundary); tries++) { + if (tries === 8) throw new FlowapiRequestError("body", null, "boundary"); + boundary = $random(); + } + type += "; boundary=" + boundary; + } + const chunks: Uint8Array[] = []; + for (const p of parts) chunks.push($bytes(`--${boundary}\r\n${p.head}\r\n`), p.data, $bytes("\r\n")); + chunks.push($bytes(`--${boundary}--\r\n`)); + let size = 0; + for (const c of chunks) size += c.length; + const out = new Uint8Array(size); + let at = 0; + for (const c of chunks) { + out.set(c, at); + at += c.length; + } + return [type, out]; +} + +/** A response read: which response of the description it is (`null` for none), and its body. */ +type $Read = { response: string | null; status: number; mediaType: string | null; body: unknown }; + +/** Per response, as written: its status, its media types as written and their bare forms. */ +type $Table = readonly (readonly [string, readonly string[], readonly string[]])[]; + +/** The platform's UTF-8 coders (every browser, Node, Deno and Bun has them), looked up on + * `globalThis` so the output type-checks without the DOM's or Node's declarations. */ +type $Coders = { + TextDecoder: new (label: string, options: { fatal: boolean; ignoreBOM: boolean }) => { + decode(bytes: Uint8Array): string; + }; + TextEncoder: new () => { encode(text: string): Uint8Array }; +}; + +let $decoder: { decode(bytes: Uint8Array): string } | undefined; + +/** Bytes as UTF-8 text, a byte order mark kept as the character; `null` when they are not + * UTF-8 (the Rust SDK refuses them too, where `Response.text()` would replace them). */ +function $utf8(bytes: Uint8Array): string | null { + $decoder ??= new (globalThis as unknown as $Coders).TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + try { + return $decoder.decode(bytes); + } catch { + return null; + } +} + +/** A `text/*` type (a JSON one is read as JSON first). */ +function $text(bare: string): boolean { + return bare.startsWith("text/"); +} + +/** + * Whether `Response` keeps a body of this `Content-Type` as bytes: any type but JSON and + * `text/*`, and a body with none. Read such a body with `arrayBuffer()`, the others with + * `text()`; bytes are always safe to give, as they are decoded where the type is text. + */ +export function flowapiReadsBytes(contentType: string | null | undefined): boolean { + if (contentType === null || contentType === undefined) return true; + return !$json(contentType) && !$text($bare(contentType)); +} + +/** A header, its name compared without case. */ +function $header(headers: Record, name: string): string | null { + const direct = headers[name]; + if (direct !== undefined) return direct; + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === name) return headers[key] ?? null; + } + return null; +} + +/** + * The response a status picks (its code, then its range `NXX`, then `default`), the media type + * the `Content-Type` picks (exact, then `type/*`, then `*\/*`), and the body read by the type + * sent: JSON parsed, `text/*` the text, any other the bytes (a string given for it encoded as + * UTF-8: its bytes were lost before). Bytes given for JSON or text are decoded as UTF-8. A + * status or a media type the description does not name, and a JSON or text body that is not + * UTF-8 or not JSON, read as `response: null` with the body as given. + */ +function $read(table: $Table, status: number, headers: Record, body: string | Uint8Array): $Read { + const code = String(status); + const range = code.charAt(0) + "XX"; + let hit: (typeof table)[number] | undefined; + for (const r of table) if (r[0] === code) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0].toUpperCase() === range) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0] === "default") hit = hit ?? r; + const type = $header(headers, "content-type"); + if (hit === undefined) return { response: null, status, mediaType: type, body }; + if (hit[1].length === 0) return { response: hit[0], status, mediaType: null, body }; + if (type === null) return { response: null, status, mediaType: null, body }; + const bare = $bare(type); + const slash = bare.indexOf("/"); + const major = bare.slice(0, slash + 1) + "*"; + let at = hit[2].indexOf(bare); + if (at < 0) at = hit[2].indexOf(major); + if (at < 0) at = hit[2].indexOf("*/*"); + const written = hit[1][at]; + if (written === undefined) return { response: null, status, mediaType: type, body }; + const json = $json(type); + if (!json && !$text(bare)) { + const bytes = typeof body === "string" ? $bytes(body) : body; + return { response: hit[0], status, mediaType: written, body: bytes }; + } + const text = typeof body === "string" ? body : $utf8(body); + if (text === null) return { response: null, status, mediaType: type, body }; + if (!json) return { response: hit[0], status, mediaType: written, body: text }; + // An empty or broken JSON body is not the response described: the body as given, unnamed. A + // leading byte order mark is skipped (RFC 8259, 8.1), as `JSON.parse` would refuse it. + try { + return { response: hit[0], status, mediaType: written, body: JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) }; + } catch { + return { response: null, status, mediaType: type, body }; + } +} + +export function listPetsRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/pets", query: "", headers }; + return request; +} + +const $listPetsResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function listPetsResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: ListPets["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($listPetsResponse, status, headers, body) as ReturnType; +} + +export function addPetRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "POST", path: "/pets", query: "", headers }; + return request; +} + +const $addPetResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function addPetResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: AddPet["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($addPetResponse, status, headers, body) as ReturnType; +} + +export function myPetsRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/pets/mine", query: "", headers }; + return request; +} + +const $myPetsResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function myPetsResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: MyPets["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($myPetsResponse, status, headers, body) as ReturnType; +} + +export function healthRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/health", query: "", headers }; + return request; +} + +const $healthResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function healthResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Health["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($healthResponse, status, headers, body) as ReturnType; +} + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://api.swagger.example/v1" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "basic": { type: "http", scheme: "basic", description: "A user and password" }, + "header": { type: "apiKey", in: "header", name: "X-Key" }, + "query": { type: "apiKey", in: "query", name: "key" }, + "app": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://swagger.example/oauth/token", scopes: ["pets:read"] } }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + listPets: { + method: "GET", + path: "/pets", + security: [{ "basic": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: listPetsRequest, + response: listPetsResponse, + }, + addPet: { + method: "POST", + path: "/pets", + security: [{ "header": [] }, { "query": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: addPetRequest, + response: addPetResponse, + }, + myPets: { + method: "GET", + path: "/pets/mine", + security: [{ "app": ["pets:read"] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: myPetsRequest, + response: myPetsResponse, + }, + health: { + method: "GET", + path: "/health", + security: [], + responses: { "200": { content: { "application/json": "json" } } }, + request: healthRequest, + response: healthResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/client/swagger/src/client.ts b/crates/flowapi-sdk/tests/client/swagger/src/client.ts new file mode 100644 index 0000000..6b2d630 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/src/client.ts @@ -0,0 +1,77 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "./api.js"; +import * as $core from "./core/index.js"; +import { Pets as $Pets } from "./resources/pets.js"; +import { Health as $Health } from "./resources/health.js"; + +/** What the config decides of the client. */ +const $settings: $core.Settings = { + client: "Swagger", + environments: { }, + logEnv: "SWAGGER_LOG", + auth: { "basic": { option: "basic", env: "SWAGGER_BASIC" }, "header": { option: "header", env: "SWAGGER_HEADER_KEY" }, "query": { option: "query", env: "SWAGGER_QUERY_KEY" }, "app": { option: "app", clientIdEnv: "SWAGGER_CLIENT_ID", clientSecretEnv: "SWAGGER_CLIENT_SECRET" } }, + timeout: 60000, + maxRetries: 0, + maxRetryDelay: 60000, + servers: $api.flowapiServers, + schemes: $api.flowapiSecuritySchemes, + readsBytes: $api.flowapiReadsBytes, +}; + +/** The options of a `Swagger`: the runtime's, and a credential for each security scheme it sends. */ +export type SwaggerOptions = $core.ClientOptions & { + /** The credential of the security scheme `basic`: an HTTP basic user-id and password, else `SWAGGER_BASIC`; `null` reads no variable. */ + basic?: $core.BasicCredential | null | undefined; + /** The credential of the security scheme `header`: the key, else `SWAGGER_HEADER_KEY`; `null` reads no variable. */ + header?: $core.Credential | null | undefined; + /** The credential of the security scheme `query`: the key, else `SWAGGER_QUERY_KEY`; `null` reads no variable. */ + query?: $core.Credential | null | undefined; + /** The credential of the security scheme `app`: a token, or the client's id and secret to request one with, else `SWAGGER_CLIENT_ID`, `SWAGGER_CLIENT_SECRET`; `null` reads no variable. */ + app?: $core.Credential | $core.ClientCredentials | null | undefined; +}; + +/** The API's client: a member for each resource (`client.pets`), and `request` for a call no + * operation describes. */ +export class Swagger { + readonly #core: $core.Core; + readonly #options: SwaggerOptions; + readonly pets: $Pets; + readonly health: $Health; + + constructor(options: SwaggerOptions = {}) { + this.#options = { ...options }; + this.#core = new $core.Core($settings, options); + this.pets = new $Pets(this.#core); + this.health = new $Health(this.#core); + } + + /** The base URL calls go to, unless an operation has servers of its own. */ + get baseURL(): string | null { + return this.#core.baseURL; + } + + /** Milliseconds an attempt may take, its body read; `null` for no limit. */ + get timeout(): number | null { + return this.#core.timeout; + } + + /** How many times a failed attempt is tried again. */ + get maxRetries(): number { + return this.#core.maxRetries; + } + + /** A client of the same class with these options over this one's: one given as `undefined` + * keeps this one's. */ + withOptions(options: SwaggerOptions): this { + const next: Record = { ...this.#options }; + for (const [key, value] of Object.entries(options)) if (value !== undefined) next[key] = value; + return new (this.constructor as new (options: SwaggerOptions) => this)(next as SwaggerOptions); + } + + /** A call by method and path that no operation describes, with every credential the + * client has. */ + request(method: string, path: string, options?: $core.RawRequest): $core.ApiCall { + return $core.request(this.#core, method, path, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/swagger/src/index.ts b/crates/flowapi-sdk/tests/client/swagger/src/index.ts new file mode 100644 index 0000000..7b7492a --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/src/index.ts @@ -0,0 +1,45 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +export { Swagger, Swagger as default, type SwaggerOptions } from "./client.js"; +export { + APIConnectionError, + APIConnectionTimeoutError, + APIError, + APIUserAbortError, + ApiCall, + AuthenticationError, + BadRequestError, + type BasicCredential, + type BasicPair, + type ClientCredentials, + ConflictError, + type Credential, + CredentialError, + CrossOriginRedirectError, + type Data, + type Fetch, + type FetchResponse, + type HeadersInput, + type Input, + InsecureCredentialError, + InternalServerError, + type ItemOf, + type LogLevel, + type Logger, + NotFoundError, + type Outcome, + Page, + PagePromise, + PermissionDeniedError, + type QueryInput, + RateLimitError, + type RawRequest, + type RequestOptions, + RequestTimeoutError, + SdkError, + type ServerSentEvent, + Stream, + TokenError, + UnprocessableEntityError, +} from "./core/index.js"; +export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/swagger/src/resources/health.ts b/crates/flowapi-sdk/tests/client/swagger/src/resources/health.ts new file mode 100644 index 0000000..a32693b --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/src/resources/health.ts @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.health`. */ +export class Health { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /health` */ + get(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.health, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/swagger/src/resources/pets.ts b/crates/flowapi-sdk/tests/client/swagger/src/resources/pets.ts new file mode 100644 index 0000000..d6f00ec --- /dev/null +++ b/crates/flowapi-sdk/tests/client/swagger/src/resources/pets.ts @@ -0,0 +1,28 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.pets`. */ +export class Pets { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /pets` */ + list(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.listPets, params, options); + } + + /** `POST /pets` */ + add(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.addPet, params, options); + } + + /** `GET /pets/mine` */ + mine(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.myPets, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/tokens.mjs b/crates/flowapi-sdk/tests/client/tokens.mjs new file mode 100644 index 0000000..1bde0be --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens.mjs @@ -0,0 +1,152 @@ +// OAuth 2.0's client credentials grant run by the client (the `tokens` case): how the token is +// asked for, what is read of the answer, how long it is held, one request for the calls that wait +// on it, and a 401 that asks for another once. Each pitfall named is one a client gets wrong. +import { assert, reply, stub } from './stub.mjs' + +const API = 'https://api.tokens.example/v1' +const TOKEN_URL = 'https://api.tokens.example/oauth/token?tenant=main' + +/** Whether a request goes to a token endpoint. */ +const isToken = (url) => new URL(url).pathname.endsWith('/token') + +/** A fetch that answers the token endpoint by `token(n)` (its n-th request) and the API by + * `api(n)`; `asked` the token requests, `calls` every request. */ +function server({ token = () => reply(200, { access_token: 'tok1', token_type: 'Bearer', expires_in: 3600 }), api = () => reply(200, { ok: true }) } = {}) { + let tokens = 0 + let calls = 0 + const fetch = stub((url, init) => (isToken(url) ? token(++tokens, url, init) : api(++calls, url, init))) + return Object.assign(fetch, { asked: () => fetch.calls.filter((c) => isToken(c.url)) }) +} + +const credentials = { clientId: 'my client', clientSecret: 'sé:cret' } + +function client(built, fetch, more = {}) { + return new built.tokens.Tokens({ fetch, logLevel: 'off', maxRetries: 0, client: credentials, ...more }) +} + +export function tests(built) { + const { AuthenticationError, PermissionDeniedError, TokenError, InsecureCredentialError } = built.tokens + return [ + // req: rfc6749.3.2.must-client-use-http-post-method-making — the token request is a POST + // req: rfc6749.3.2.must-endpoint-uri-include-application-x-www — `?tenant=main` kept on the token URL + // req: rfc6749.4.4.2.required-grant-type — `grant_type` sent + // req: rfc6749.4.4.2.must-value-set-client-credentials — as `client_credentials` + // req: rfc6749.4.4.2.optional-scope — `scope` sent with the operation's scopes + // req: rfc6749.2.3.1.may-clients-possession-client-password-use-http — the client authenticates by HTTP basic + // req: rfc6749.3.2.1.must-confidential-clients-other-clients-issued-client — with its id and secret on every token request + // req: rfc6749.4.4.2.must-client-authenticate-authorization-server-described-section — as 3.2.1 says + // req: rfc6749.2.3.1.must-not-parameters-only-transmitted-request-body-included — no credential in the token URL + // req: rfc6749.2.3.1.not-recommended-including-client-credentials-request-body-using — no `client_id` or `client_secret` in the body + // req: rfc6749.2.3.must-not-client-use-more-one-authentication-method — basic alone, nothing else + // req: rfc6749.B.must-address-shortcoming-generating-payloads-using-media — the id and secret UTF-8, then form-encoded, before base64 + ['client credentials: a POST of the form to the token URL kept with its query, the client by HTTP basic alone', async () => { + const fetch = server() + await client(built, fetch).things.list() + const [t, call] = fetch.calls + assert.equal(t.url, TOKEN_URL) + assert.equal(t.init.method, 'POST') + assert.equal(t.headers['content-type'], 'application/x-www-form-urlencoded') + assert.equal(t.init.body, 'grant_type=client_credentials&scope=read') + assert.equal(t.headers.authorization, 'Basic ' + Buffer.from('my+client:s%C3%A9%3Acret', 'utf8').toString('base64')) + assert.ok(!/client_(id|secret)/.test(t.init.body) && !/my|cret/.test(t.url), 'no client credential in the body or the URL') + assert.equal(call.url, `${API}/things`) + assert.equal(call.headers.authorization, 'Bearer tok1') + }], + // req: rfc6749.3.2.must-not-request-response-parameters-included-more-once — each parameter, and each scope, once + // req: rfc6749.10.3.should-client-request-access-tokens-minimal-scope — the scopes of the operation called, not every scope + ['the scopes the operation needs, each once; another set of scopes is another token', async () => { + const fetch = server({ token: (n) => reply(200, { access_token: `tok${n}`, token_type: 'bearer', expires_in: '3600' }) }) + const c = client(built, fetch) + await c.things.list() + await c.things.list() + await c.things.write() + await c.things.write() + const bodies = fetch.asked().map((t) => t.init.body) + assert.deepEqual(bodies, ['grant_type=client_credentials&scope=read', 'grant_type=client_credentials&scope=read+write']) + for (const b of bodies) assert.equal(new URLSearchParams(b).getAll('grant_type').length, 1) + assert.deepEqual(fetch.calls.filter((c) => !isToken(c.url)).map((c) => c.headers.authorization), ['Bearer tok1', 'Bearer tok1', 'Bearer tok2', 'Bearer tok2']) + const own = server() + await client(built, own, { partner: { ...credentials, scopes: ['a', 'b', 'a'] } }).others.partner() + assert.equal(own.asked()[0].init.body, 'grant_type=client_credentials&scope=a+b') + assert.equal(own.asked()[0].url, 'https://login.tokens.example/token') + }], + ['a token is held until a little before it expires; one that expires at once is asked for again', async () => { + const fetch = server({ token: (n) => reply(200, { access_token: `tok${n}`, token_type: 'Bearer', expires_in: 0 }) }) + const c = client(built, fetch) + await c.things.list() + await c.things.list() + assert.equal(fetch.asked().length, 2) + const lasting = server({ token: (n) => reply(200, { access_token: `tok${n}`, token_type: 'Bearer' }) }) + const d = client(built, lasting) + await d.things.list() + await d.things.list() + assert.equal(lasting.asked().length, 1, 'with no expires_in the token is held') + }], + ['calls that wait on the same token make one token request', async () => { + let release + const gate = new Promise((r) => (release = r)) + const fetch = server({ token: async () => (await gate, reply(200, { access_token: 'tok', token_type: 'Bearer', expires_in: 60 })) }) + const c = client(built, fetch) + const all = Promise.all([c.things.list(), c.things.list(), c.things.list()]) + await new Promise((r) => setTimeout(r, 5)) + release() + await all + assert.equal(fetch.asked().length, 1) + }], + // req: rfc6749.5.1.must-client-ignore-unrecognized-value-names-response — members the client does not know are ignored + // req: rfc6749.7.1.must-not-client-use-access-token-does-not — a token of a type other than bearer is not used + ['the answer: unknown members ignored; a token of a type the client does not know is never sent', async () => { + const fetch = server({ token: () => reply(200, { access_token: 'tok', token_type: 'Bearer', expires_in: 60, refresh_hint: { x: 1 }, scope: 'read' }) }) + await client(built, fetch).things.list() + assert.equal(fetch.calls[1].headers.authorization, 'Bearer tok') + const mac = server({ token: () => reply(200, { access_token: 'tok', token_type: 'mac' }) }) + await assert.rejects(client(built, mac).things.list(), (e) => e instanceof TokenError && e.error === 'unsupported_token_type') + assert.equal(mac.calls.length, 1, 'the API was not called') + const none = server({ token: () => reply(200, { token_type: 'Bearer' }) }) + await assert.rejects(client(built, none).things.list(), (e) => e instanceof TokenError && e.error === 'invalid_response') + }], + ['an error answer of the token endpoint is a TokenError with its code, description and URI', async () => { + const fetch = server({ token: () => reply(401, { error: 'invalid_client', error_description: 'unknown client', error_uri: 'https://docs.example/e' }) }) + await assert.rejects(client(built, fetch).things.list(), (e) => e instanceof TokenError && e.status === 401 && e.error === 'invalid_client' && e.description === 'unknown client' && e.uri === 'https://docs.example/e') + const text = server({ token: () => reply(500, 'down') }) + await assert.rejects(client(built, text).things.list(), (e) => e instanceof TokenError && e.status === 500 && e.description === 'down') + }], + // req: rfc6750.3.1.may-client-request-new-access-token-retry — a 401 to a token the client requested: another token, the call once more + ['a 401 to a requested token drops it and makes the call once more with a new one; never twice', async () => { + const fetch = server({ token: (n) => reply(200, { access_token: `tok${n}`, token_type: 'Bearer', expires_in: 3600 }), api: (n) => reply(n === 1 ? 401 : 200, { ok: n !== 1 }) }) + const c = client(built, fetch) + await c.things.list() + assert.deepEqual(fetch.calls.map((x) => x.headers.authorization), [fetch.calls[0].headers.authorization, 'Bearer tok1', fetch.calls[0].headers.authorization, 'Bearer tok2']) + const always = server({ api: () => reply(401, { error: 'no' }) }) + await assert.rejects(client(built, always).things.list(), AuthenticationError) + assert.equal(always.calls.length, 4, 'token, call, token, call: one renewal') + }], + // req: rfc9110.15.5.4.should-not-client-automatically-repeat-request-same-credentials — a 403 is not repeated, nor a 401 to a token the caller gave + ['a 403, and a 401 to a token the caller gave, are not repeated with the same credentials', async () => { + const denied = server({ api: () => reply(403, { error: 'forbidden' }) }) + await assert.rejects(client(built, denied, { maxRetries: 3 }).things.list(), PermissionDeniedError) + assert.equal(denied.calls.length, 2, 'one token request, one call') + const given = server({ api: () => reply(401, { error: 'no' }) }) + await assert.rejects(client(built, given, { client: 'caller-token', maxRetries: 3 }).things.list(), AuthenticationError) + assert.equal(given.calls.length, 1) + assert.equal(given.calls[0].headers.authorization, 'Bearer caller-token') + }], + // req: rfc6749.10.3.must-access-token-credentials-only-transmitted-using — the token endpoint only over TLS + // req: rfc6749.10.8.must-not-access-tokens-refresh-tokens-resource-owner — client credentials never sent in the clear + // req: rfc6750.5.2.must-second-confidentiality-protection-exchanges-between-client — both exchanges, with the token endpoint and with the API + ['the token endpoint only over https or to a loopback host, unless allowInsecureCredentials', async () => { + const fetch = server() + await assert.rejects(client(built, fetch, { client: { ...credentials, tokenURL: 'http://login.example/token' } }).things.list(), InsecureCredentialError) + assert.equal(fetch.calls.length, 0) + await client(built, fetch, { client: { ...credentials, tokenURL: 'http://localhost:8080/token' }, baseURL: 'http://127.0.0.1:9/v1' }).things.list() + await client(built, fetch, { client: { ...credentials, tokenURL: 'http://login.example/token' }, allowInsecureCredentials: true }).things.list() + assert.deepEqual(fetch.asked().map((t) => t.url), ['http://localhost:8080/token', 'http://login.example/token']) + }], + ['a call the TLS rule refuses requests no token: the rule holds the base URL before a token is asked for', async () => { + const fetch = server() + const over = { client: { ...credentials, tokenURL: 'https://login.tokens.example/token' }, baseURL: 'http://api.tokens.example/v1' } + await assert.rejects(client(built, fetch, over).things.list(), (e) => e instanceof InsecureCredentialError && e.message.includes('http://api.tokens.example/v1')) + assert.equal(fetch.calls.length, 0, 'no token request for a call that is not sent') + }], + ] +} diff --git a/crates/flowapi-sdk/tests/client/tokens/flowapi-sdk.yml b/crates/flowapi-sdk/tests/client/tokens/flowapi-sdk.yml new file mode 100644 index 0000000..e547bce --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/flowapi-sdk.yml @@ -0,0 +1,30 @@ +# OAuth 2.0's client credentials flow run by the client (a token URL relative to the server with a +# query of its own, scopes by operation; another with the config's scopes), a deprecated API key, +# an alternative that is `{}`, an HTTP scheme sent as given (GNAP), one that answers a challenge +# (Digest), a client certificate, and OpenID Connect named by URI (3.2). +version: 1 +spec: spec.json +package: { name: tokens-sdk, client: Tokens, license: MIT } +auth: + Client: { client_id_env_var: TOKENS_CLIENT_ID, client_secret_env_var: TOKENS_CLIENT_SECRET } + Partner: { env_var: TOKENS_PARTNER_TOKEN, client_id_env_var: TOKENS_PARTNER_ID, client_secret_env_var: TOKENS_PARTNER_SECRET, scopes: [partner.read] } + Legacy: { env_var: TOKENS_KEY } + Gnap: { env_var: TOKENS_GNAP } + Digest: {} + Cert: {} + Oidc: { env_var: TOKENS_OIDC } +defaults: { retries: 0 } +resources: + things: + methods: + list: listThings + write: writeThing + others: + methods: + partner: partner + legacy: legacy + optional: optional + gnap: gnap + digest: digest + cert: cert + oidc: oidc diff --git a/crates/flowapi-sdk/tests/client/tokens/issues.txt b/crates/flowapi-sdk/tests/client/tokens/issues.txt new file mode 100644 index 0000000..a6c697a --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/issues.txt @@ -0,0 +1,6 @@ +warning[config.auth.deprecated]: `Legacy` is deprecated by the description: its consumers should refrain from it + at flowapi-sdk.yml:11:3 (/auth/Legacy) +warning[config.auth.refused]: `Digest` is HTTP `digest`, which answers a challenge or signs each request: the client cannot send it; give `Authorization` in a call's `headers` + at flowapi-sdk.yml:13:3 (/auth/Digest) +warning[config.auth.mutual_tls]: `Cert` is a client certificate, which no request carries: give the client a `fetch` (or `fetchOptions`) that presents it, and the option `true` to say so + at flowapi-sdk.yml:14:3 (/auth/Cert) diff --git a/crates/flowapi-sdk/tests/client/tokens/spec.json b/crates/flowapi-sdk/tests/client/tokens/spec.json new file mode 100644 index 0000000..7c76a7c --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/spec.json @@ -0,0 +1,41 @@ +{ + "openapi": "3.2.0", + "info": { "title": "Tokens", "version": "1" }, + "servers": [{ "url": "https://api.tokens.example/v1" }], + "security": [{ "Client": ["read"] }], + "paths": { + "/things": { + "get": { "operationId": "listThings", "responses": { "200": { "$ref": "#/components/responses/Ok" } } }, + "post": { "operationId": "writeThing", "security": [{ "Client": ["read", "write"] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } + }, + "/partner": { "get": { "operationId": "partner", "security": [{ "Partner": [] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/legacy": { "get": { "operationId": "legacy", "security": [{ "Legacy": [] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/optional": { "get": { "operationId": "optional", "security": [{ "Legacy": [] }, {}], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/gnap": { "get": { "operationId": "gnap", "security": [{ "Gnap": [] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/digest": { "get": { "operationId": "digest", "security": [{ "Digest": [] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/cert": { "get": { "operationId": "cert", "security": [{ "Cert": [] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/oidc": { "get": { "operationId": "oidc", "security": [{ "#/components/securitySchemes/Oidc": ["openid"] }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } } + }, + "components": { + "responses": { + "Ok": { "description": "ok", "content": { "application/json": { "schema": { "type": "object", "properties": { "ok": { "type": "boolean" } } } } } } + }, + "securitySchemes": { + "Client": { + "type": "oauth2", + "description": "The client's own credentials", + "flows": { + "clientCredentials": { "tokenUrl": "/oauth/token?tenant=main", "scopes": { "read": "Read things", "write": "Write things" }, "x-note": "an extension of the flow" }, + "x-vendor": { "tokenUrl": "https://nowhere.example" } + }, + "x-internal": true + }, + "Partner": { "type": "oauth2", "flows": { "clientCredentials": { "tokenUrl": "https://login.tokens.example/token", "scopes": {} } } }, + "Legacy": { "type": "apiKey", "in": "header", "name": "X-Api-Key", "deprecated": true }, + "Gnap": { "type": "http", "scheme": "GNAP" }, + "Digest": { "type": "http", "scheme": "Digest" }, + "Cert": { "type": "mutualTLS" }, + "Oidc": { "type": "openIdConnect", "openIdConnectUrl": "https://login.tokens.example/.well-known/openid-configuration" } + } + } +} diff --git a/crates/flowapi-sdk/tests/client/tokens/src/api.ts b/crates/flowapi-sdk/tests/client/tokens/src/api.ts new file mode 100644 index 0000000..6147c05 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/src/api.ts @@ -0,0 +1,1150 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +export type ListThings = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type WriteThing = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Partner = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Legacy = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Optional = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Gnap = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Digest = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Cert = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Oidc = { + responses: { + "200": { + content: { + "application/json": ResponsesOkApplicationJson; + }; + }; + }; +}; + +export type Paths = { + "/things": { + get: ListThings; + post: WriteThing; + }; + "/partner": { + get: Partner; + }; + "/legacy": { + get: Legacy; + }; + "/optional": { + get: Optional; + }; + "/gnap": { + get: Gnap; + }; + "/digest": { + get: Digest; + }; + "/cert": { + get: Cert; + }; + "/oidc": { + get: Oidc; + }; +}; + +export type ResponsesOkApplicationJson = { + ok?: boolean; + [key: string]: unknown; +}; + +// The SDK: for each operation, a function that writes its request and one that reads its +// response. No I/O: send the request with any HTTP client, give its answer back. + +/** + * A request to send. `path` goes after the server's base URL; `query` is the query string + * without its `?`, empty for none; `body` text, or bytes (a multipart body, bytes given). + */ +export type $Request = { + method: string; + path: string; + query: string; + headers: Record; + body?: string | Uint8Array; +}; + +/** + * A request `Request` refuses to write: a value that would change what the request means + * rather than what it says. `location` is where it goes (`path`, `query`, `querystring`, + * `header`, `cookie` or `body`), `parameter` the parameter's name as the description writes it + * (`null` for the body; a multipart part's name), `reason` why: a CR, LF or NUL in a header, a + * cookie or a part's head (it would start another header), a path segment left empty or made `.` + * or `..` (a client or a server would remove it and the one before it), NaN or an infinity (JSON + * has no number for them). In a multipart body also: `null` where a part goes (`null`), a member + * of an array of parts that is not an object (`unnamed-part`), a Blob not read yet + * (`unread-blob`: `flowapiBlob` reads it), a `"` or `\` in a name or a file name (`quote`), a + * file name that is empty, `.` or `..` (`file-name`), a part header's name that is not a token or + * is `Content-Disposition` (`header-name`), a list or a range for a part's type (`media-range`), + * a boundary RFC 2046 does not allow or that a part holds (`boundary`). + */ +export class FlowapiRequestError extends Error { + readonly location: string; + readonly parameter: string | null; + readonly reason: + | "control-character" | "empty-segment" | "dot-segment" | "non-finite" | "null" | "unnamed-part" + | "unread-blob" | "quote" | "file-name" | "header-name" | "media-range" | "boundary"; + constructor(location: string, parameter: string | null, reason: FlowapiRequestError["reason"]) { + const what = location === "body" ? "the body" + (parameter === null ? "" : `'s part \`${parameter}\``) : `the ${location} parameter \`${parameter}\``; + super(`${what}: ${reason}`); + this.name = "FlowapiRequestError"; + this.location = location; + this.parameter = parameter; + this.reason = reason; + } +} + +const $unreserved = /^[A-Za-z0-9\-._~]*$/; +const $marks = /[!'()*]/g; +const $marked = /[!'()*]/; +const $kept = /%[0-9A-Fa-f]{2}|[:/?#[\]@!$&'()*+,;=]/g; + +function $mark(c: string): string { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +} + +/** RFC 3986: every character but the unreserved ones percent-encoded, as UTF-8. */ +function $enc(s: string): string { + if ($unreserved.test(s)) return s; + const e = encodeURIComponent(s); + return $marked.test(e) ? e.replace($marks, $mark) : e; +} + +/** RFC 6570's reserved expansion: reserved characters and percent-encoded triples kept. */ +function $res(s: string): string { + if ($unreserved.test(s)) return s; + $kept.lastIndex = 0; + let out = ""; + let last = 0; + let m: RegExpExecArray | null; + while ((m = $kept.exec(s)) !== null) { + out += $enc(s.slice(last, m.index)) + m[0]; + last = $kept.lastIndex; + } + return out + $enc(s.slice(last)); +} + +/** Headers and `style: cookie` take values as they are (3.2, Appendix D). */ +function $raw(s: string): string { + return s; +} + +const $dot = /^(?:\.|%2e){1,2}$/i; + +/** A value written raw, refused if it holds a CR, LF or NUL: it would end its header. */ +function $ctl(s: string | undefined, at: string, name: string): string | undefined { + if (s !== undefined && (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0)) { + throw new FlowapiRequestError(at, name, "control-character"); + } + return s; +} + +/** A path segment a parameter wrote, refused when empty or a dot segment (`.`, `..`, a dot as + * `%2E` too, as WHATWG's URL parser reads it). `pieces`: a parameter of it keeps `/` + * (`allowReserved`), and each piece between them is held to the same. */ +function $seg(s: string, name: string, pieces: boolean): string { + // A dot segment is at most 6 characters (`%2e%2e`) and starts with `.` or `%`: a longer one + // is none, and is not read (reading a string made by `+` would flatten it). + if (!pieces && s.length > 6) return s; + if (s.length === 0) throw new FlowapiRequestError("path", name, "empty-segment"); + const c = s.charCodeAt(0); + if (!pieces && c !== 46 && c !== 37) return s; + if ($dot.test(s) || (pieces && s.split("/").some((p) => $dot.test(p)))) { + throw new FlowapiRequestError("path", name, "dot-segment"); + } + return s; +} + +/** Whether a value holds NaN or an infinity anywhere. */ +function $bad(v: unknown): boolean { + if (typeof v === "number") return v - v !== 0; + if (v === null || typeof v !== "object") return false; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) if ($bad(v[i])) return true; + return false; + } + for (const key in v) if ($bad((v as Record)[key])) return true; + return false; +} + +/** A parameter's value, refused when it holds NaN or an infinity: JSON has no number for them, + * and their text would reach the server as a string. */ +function $fin(v: T, at: string, name: string): T { + if (typeof v === "number" ? v - v !== 0 : typeof v === "object" && v !== null && $bad(v)) { + throw new FlowapiRequestError(at, name, "non-finite"); + } + return v; +} + +/** A value as text: a string as it is, a number, boolean or bigint by `String`, else JSON. */ +function $str(v: unknown): string { + switch (typeof v) { + case "string": + return v; + case "number": + case "boolean": + case "bigint": + return String(v); + default: + return JSON.stringify(v) ?? ""; + } +} + +/** + * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, + * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. + */ +function $x( + v: unknown, + name: string, + first: string, + sep: string, + named: boolean, + ifemp: string, + explode: boolean, + join: string, + enc: (s: string) => string, + at: string, + pname: string, + nest?: readonly string[], +): string | undefined { + if (v === undefined) return undefined; + if (v === null) return ifemp === "=" ? name + "=" : ""; + let out = ""; + let n = 0; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) { + const item: unknown = v[i]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); + if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); + else out += (n++ ? (explode ? sep : join) : "") + s; + } + } else if (typeof v === "object") { + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === null || item === undefined) continue; + if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { + throw new FlowapiRequestError(at, pname, "non-finite"); + } + const k = enc(key); + const s = enc($str(item)); + if (explode) out += (n++ ? sep : "") + k + (s === "" && named ? ifemp : "=" + s); + else out += (n++ ? join : "") + k + join + s; + } + } else { + if (typeof v === "number" && v - v !== 0) throw new FlowapiRequestError(at, pname, "non-finite"); + const s = enc($str(v)); + return first + (named ? name + (s === "" ? ifemp : "=" + s) : s); + } + if (n === 0) return undefined; + return first + (named && !explode ? name + "=" + out : out); +} + +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + +/** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an + * array's items repeat their key. */ +function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { + if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined; + const out = $members(v as Record, name, enc, ""); + return out === "" ? undefined : out; +} + +function $members(v: Record, path: string, enc: (s: string) => string, acc: string): string { + for (const key in v) { + if (!Object.prototype.hasOwnProperty.call(v, key)) continue; + const item = v[key]; + if (item === null || item === undefined) continue; + const at = path + "%5B" + enc(key) + "%5D"; + if (Array.isArray(item)) { + for (let i = 0; i < item.length; i++) { + const one: unknown = item[i]; + if (one !== null && one !== undefined) acc += (acc === "" ? "" : "&") + at + "=" + enc($str(one)); + } + } else if (typeof item === "object") { + acc = $members(item as Record, at, enc, acc); + } else { + acc += (acc === "" ? "" : "&") + at + "=" + enc($str(item)); + } + } + return acc; +} + +/** `s` added to a query string or a cookie header, after `sep`. */ +function $add(acc: string, s: string | undefined, sep: string): string { + return s === undefined ? acc : acc === "" ? s : acc + sep + s; +} + +/** The media type without its parameters, in lower case. */ +function $bare(type: string): string { + const semi = type.indexOf(";"); + return (semi < 0 ? type : type.slice(0, semi)).trim().toLowerCase(); +} + +/** `application/json` and every `+json` type (RFC 6839). */ +function $json(type: string): boolean { + const bare = $bare(type); + return bare === "application/json" || bare.endsWith("+json"); +} + +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { + if (v instanceof Uint8Array) return v; + if (!$json(type)) { + if ($bare(type) === "application/x-www-form-urlencoded") { + if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); + return $form(v, enc); + } + if (typeof v === "string") return v; + } + // `JSON.stringify` writes NaN and the infinities as `null`: with no `null` in the text there is + // none, and the value is walked only when there is one. + const text = JSON.stringify(v); + if (text !== undefined && text.indexOf("null") >= 0 && $bad(v)) { + throw new FlowapiRequestError("body", null, "non-finite"); + } + return text; +} + +/** A parameter with `content`: its value as its media type's text, then written as a string. */ +function $content(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + return $json(type) ? JSON.stringify(v) : $str(v); +} + +/** `in: querystring`: the whole query string, a form as one, any other type percent-encoded. */ +function $qs(v: unknown, type: string): string | undefined { + if (v === undefined) return undefined; + if ($bare(type) === "application/x-www-form-urlencoded") return $form(v); + return $enc($json(type) ? JSON.stringify(v) : $str(v)); +} + +/** A header set when it has a value; a CR, LF or NUL in it is refused (it would end the header). */ +function $set(headers: Record, name: string, s: string | undefined): void { + if (s === undefined) return; + if (s.indexOf("\r") >= 0 || s.indexOf("\n") >= 0 || s.indexOf("\0") >= 0) { + throw new FlowapiRequestError("header", name, "control-character"); + } + headers[name] = s; +} + +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + +/** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's + * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or + * `flowapiBlob`. */ +export class FlowapiFile { + readonly data: Uint8Array; + readonly name: string | undefined; + readonly type: string | undefined; + constructor(data: Uint8Array, name: string | undefined, type: string | undefined) { + this.data = data; + this.name = name; + this.type = type; + } +} + +/** A file from bytes, or from text as its UTF-8, with the name and the type to send it as. */ +export function flowapiFile(data: Uint8Array | string, name?: string, type?: string): FlowapiFile { + return new FlowapiFile(typeof data === "string" ? $bytes(data) : data, name, type); +} + +/** What `flowapiBlob` reads of a `Blob` or a `File`, typed here so the output type-checks + * without the DOM's declarations. */ +export type $Blob = { readonly type: string; readonly name?: string; arrayBuffer(): Promise }; + +/** A `Blob` or a `File` read into a `FlowapiFile`: its bytes, `name` or else a File's own, `type` + * or else the Blob's. The one step that waits: `Request` takes bytes and stays synchronous. */ +export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); +} + +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; +}; + +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + +/** A `multipart/form-data` value as `Request` takes it: a string member may also be a file + * (the types cannot tell `format: binary` from text), an array member's items one part each. */ +type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; +type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; +type $Fields = T extends object ? { [K in keyof T]: $Member } : T; +export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; + +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; + +/** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ +function $put(request: $Request, body: $Given): void { + const v = body.value; + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); + request.headers["content-type"] = type; + request.body = bytes; + return; + } + request.headers["content-type"] = body.contentType; + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; +} + +/** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ +type $Part = { head: string; data: Uint8Array }; + +let $encoder: { encode(text: string): Uint8Array } | undefined; + +/** Text as UTF-8 bytes. */ +function $bytes(text: string): Uint8Array { + $encoder ??= new (globalThis as unknown as $Coders).TextEncoder(); + return $encoder.encode(text); +} + +const $breaks = /[\r\n\0]/; +const $quotes = /["\\]/; +const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +/** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes + * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a + * receiver could read another name. */ +function $safe(s: string, part: string | null, quoted: boolean): string { + if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); + if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); + return s; +} + +/** A file's name as its part's `filename`: its last path segment (a sender's directories are not + * the receiver's), refused when that is empty, `.` or `..`, and when the name holds a CR, LF or + * NUL anywhere (cut off with a directory, it would still be meant). */ +function $filename(name: string, part: string): string { + $safe(name, part, false); + const base = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1); + if (base === "" || base === "." || base === "..") throw new FlowapiRequestError("body", part, "file-name"); + return $safe(base, part, true); +} + +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { + if (v === undefined) return; + $safe(name, name, true); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); +} + +/** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's + * `blob` for a name not given, `application/octet-stream` for a type not given), strings, + * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); + // Bytes in any other view are the same bytes. + if (v instanceof ArrayBuffer) v = new Uint8Array(v); + else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; + let type = e?.contentType; + let data: Uint8Array; + if (v instanceof FlowapiFile || v instanceof Uint8Array) { + const file = v instanceof FlowapiFile ? v : undefined; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; + type = file?.type ?? type ?? "application/octet-stream"; + data = file?.data ?? (v as Uint8Array); + } else if ($unread(v)) { + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); + } else { + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); + type ??= typeof v === "object" ? "application/json" : undefined; + // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); + data = typeof s === "string" ? $bytes(s) : s; + } + if (type !== undefined) { + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); + } + const headers = e?.headers ?? {}; + for (const key of Object.keys(headers)) { + const value = headers[key]; + const lower = key.toLowerCase(); + if (value === undefined || lower === "content-type") continue; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); + } + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); +} + +/** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting + * (`flowapiBlob`), and as JSON it would be `{}`. */ +function $unread(v: unknown): boolean { + return typeof v === "object" && v !== null && typeof (v as { arrayBuffer?: unknown }).arrayBuffer === "function"; +} + +const $bchars = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; + +/** Whether `needle` occurs in `data`. */ +function $holds(data: Uint8Array, needle: Uint8Array): boolean { + const first = needle[0] ?? 0; + for (let i = data.indexOf(first); i >= 0 && i + needle.length <= data.length; i = data.indexOf(first, i + 1)) { + let j = 1; + while (j < needle.length && data[i + j] === needle[j]) j++; + if (j === needle.length) return true; + } + return false; +} + +/** Whether a boundary occurs in any part: a delimiter in a part would end it there. */ +function $collides(parts: $Part[], boundary: string): boolean { + const b = $bytes(boundary); + return parts.some((p) => p.head.indexOf(boundary) >= 0 || $holds(p.data, b)); +} + +/** A boundary of 128 random bits from `globalThis.crypto`, so no content can be made to hold it. */ +function $random(): string { + const c = (globalThis as unknown as { crypto?: { getRandomValues(b: Uint8Array): Uint8Array } }).crypto; + if (c === undefined) throw new Error("flowapi: no globalThis.crypto to draw a multipart boundary from; give one: `multipart/form-data; boundary=...`"); + let s = "flowapi-"; + for (const x of c.getRandomValues(new Uint8Array(16))) s += (x < 16 ? "0" : "") + x.toString(16); + return s; +} + +/** The parts written with a boundary (RFC 2046, 5.1.1; RFC 7578): the one the content type + * gives (`boundary=`), refused when RFC 2046 does not allow it or a part holds it, or one drawn + * at random and added to the content type, drawn again while a part holds it. */ +function $multipart(contentType: string, parts: $Part[]): [string, Uint8Array] { + const given = /;\s*boundary\s*=\s*(?:"([^"]*)"|([^;\s]*))/i.exec(contentType); + let boundary: string; + let type = contentType; + if (given !== null) { + boundary = given[1] ?? given[2] ?? ""; + if (!$bchars.test(boundary) || $collides(parts, boundary)) throw new FlowapiRequestError("body", null, "boundary"); + } else { + boundary = $random(); + for (let tries = 1; $collides(parts, boundary); tries++) { + if (tries === 8) throw new FlowapiRequestError("body", null, "boundary"); + boundary = $random(); + } + type += "; boundary=" + boundary; + } + const chunks: Uint8Array[] = []; + for (const p of parts) chunks.push($bytes(`--${boundary}\r\n${p.head}\r\n`), p.data, $bytes("\r\n")); + chunks.push($bytes(`--${boundary}--\r\n`)); + let size = 0; + for (const c of chunks) size += c.length; + const out = new Uint8Array(size); + let at = 0; + for (const c of chunks) { + out.set(c, at); + at += c.length; + } + return [type, out]; +} + +/** A response read: which response of the description it is (`null` for none), and its body. */ +type $Read = { response: string | null; status: number; mediaType: string | null; body: unknown }; + +/** Per response, as written: its status, its media types as written and their bare forms. */ +type $Table = readonly (readonly [string, readonly string[], readonly string[]])[]; + +/** The platform's UTF-8 coders (every browser, Node, Deno and Bun has them), looked up on + * `globalThis` so the output type-checks without the DOM's or Node's declarations. */ +type $Coders = { + TextDecoder: new (label: string, options: { fatal: boolean; ignoreBOM: boolean }) => { + decode(bytes: Uint8Array): string; + }; + TextEncoder: new () => { encode(text: string): Uint8Array }; +}; + +let $decoder: { decode(bytes: Uint8Array): string } | undefined; + +/** Bytes as UTF-8 text, a byte order mark kept as the character; `null` when they are not + * UTF-8 (the Rust SDK refuses them too, where `Response.text()` would replace them). */ +function $utf8(bytes: Uint8Array): string | null { + $decoder ??= new (globalThis as unknown as $Coders).TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + try { + return $decoder.decode(bytes); + } catch { + return null; + } +} + +/** A `text/*` type (a JSON one is read as JSON first). */ +function $text(bare: string): boolean { + return bare.startsWith("text/"); +} + +/** + * Whether `Response` keeps a body of this `Content-Type` as bytes: any type but JSON and + * `text/*`, and a body with none. Read such a body with `arrayBuffer()`, the others with + * `text()`; bytes are always safe to give, as they are decoded where the type is text. + */ +export function flowapiReadsBytes(contentType: string | null | undefined): boolean { + if (contentType === null || contentType === undefined) return true; + return !$json(contentType) && !$text($bare(contentType)); +} + +/** A header, its name compared without case. */ +function $header(headers: Record, name: string): string | null { + const direct = headers[name]; + if (direct !== undefined) return direct; + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === name) return headers[key] ?? null; + } + return null; +} + +/** + * The response a status picks (its code, then its range `NXX`, then `default`), the media type + * the `Content-Type` picks (exact, then `type/*`, then `*\/*`), and the body read by the type + * sent: JSON parsed, `text/*` the text, any other the bytes (a string given for it encoded as + * UTF-8: its bytes were lost before). Bytes given for JSON or text are decoded as UTF-8. A + * status or a media type the description does not name, and a JSON or text body that is not + * UTF-8 or not JSON, read as `response: null` with the body as given. + */ +function $read(table: $Table, status: number, headers: Record, body: string | Uint8Array): $Read { + const code = String(status); + const range = code.charAt(0) + "XX"; + let hit: (typeof table)[number] | undefined; + for (const r of table) if (r[0] === code) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0].toUpperCase() === range) hit = hit ?? r; + if (hit === undefined) for (const r of table) if (r[0] === "default") hit = hit ?? r; + const type = $header(headers, "content-type"); + if (hit === undefined) return { response: null, status, mediaType: type, body }; + if (hit[1].length === 0) return { response: hit[0], status, mediaType: null, body }; + if (type === null) return { response: null, status, mediaType: null, body }; + const bare = $bare(type); + const slash = bare.indexOf("/"); + const major = bare.slice(0, slash + 1) + "*"; + let at = hit[2].indexOf(bare); + if (at < 0) at = hit[2].indexOf(major); + if (at < 0) at = hit[2].indexOf("*/*"); + const written = hit[1][at]; + if (written === undefined) return { response: null, status, mediaType: type, body }; + const json = $json(type); + if (!json && !$text(bare)) { + const bytes = typeof body === "string" ? $bytes(body) : body; + return { response: hit[0], status, mediaType: written, body: bytes }; + } + const text = typeof body === "string" ? body : $utf8(body); + if (text === null) return { response: null, status, mediaType: type, body }; + if (!json) return { response: hit[0], status, mediaType: written, body: text }; + // An empty or broken JSON body is not the response described: the body as given, unnamed. A + // leading byte order mark is skipped (RFC 8259, 8.1), as `JSON.parse` would refuse it. + try { + return { response: hit[0], status, mediaType: written, body: JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) }; + } catch { + return { response: null, status, mediaType: type, body }; + } +} + +export function listThingsRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/things", query: "", headers }; + return request; +} + +const $listThingsResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function listThingsResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: ListThings["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($listThingsResponse, status, headers, body) as ReturnType; +} + +export function writeThingRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "POST", path: "/things", query: "", headers }; + return request; +} + +const $writeThingResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function writeThingResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: WriteThing["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($writeThingResponse, status, headers, body) as ReturnType; +} + +export function partnerRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/partner", query: "", headers }; + return request; +} + +const $partnerResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function partnerResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Partner["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($partnerResponse, status, headers, body) as ReturnType; +} + +export function legacyRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/legacy", query: "", headers }; + return request; +} + +const $legacyResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function legacyResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Legacy["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($legacyResponse, status, headers, body) as ReturnType; +} + +export function optionalRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/optional", query: "", headers }; + return request; +} + +const $optionalResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function optionalResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Optional["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($optionalResponse, status, headers, body) as ReturnType; +} + +export function gnapRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/gnap", query: "", headers }; + return request; +} + +const $gnapResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function gnapResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Gnap["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($gnapResponse, status, headers, body) as ReturnType; +} + +export function digestRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/digest", query: "", headers }; + return request; +} + +const $digestResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function digestResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Digest["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($digestResponse, status, headers, body) as ReturnType; +} + +export function certRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/cert", query: "", headers }; + return request; +} + +const $certResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function certResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Cert["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($certResponse, status, headers, body) as ReturnType; +} + +export function oidcRequest(): $Request { + const headers: Record = {}; + const request: $Request = { method: "GET", path: "/oidc", query: "", headers }; + return request; +} + +const $oidcResponse: $Table = [["200", ["application/json"], ["application/json"]]]; +export function oidcResponse( + status: number, + headers: Record, + body: string | Uint8Array, +): + | { response: "200"; status: 200; mediaType: "application/json"; body: Oidc["responses"]["200"]["content"]["application/json"] } + | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { + return $read($oidcResponse, status, headers, body) as ReturnType; +} + +/** + * The servers the description names, in its order (`servers`; Swagger 2.0's `host`, `basePath` + * and `schemes`). A URL may be relative to where the description is served (`/v1`, or `//host` + * for its scheme); each `{name}` in it is a variable, its `default` unless the caller gives a + * value (one of its `enum`, where it has one). + */ +export const flowapiServers = [ + { url: "https://api.tokens.example/v1" }, +] as const; + +/** + * The security schemes, by name: `apiKey` a key sent `in` a header, a query parameter or a + * cookie under `name`; `http` as `Authorization: `; `oauth2` and + * `openIdConnect` a token sent as a bearer token, which the caller obtained or, for OAuth 2.0's + * `clientCredentials` flow, the client requests at its `tokenUrl` (relative to the server's URL + * where it is relative) for the scopes it needs. `mutualTLS` is a client certificate, which no + * request carries: a client cannot send it, only its transport can. + */ +export const flowapiSecuritySchemes = { + "Client": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "/oauth/token?tenant=main", scopes: ["read", "write"] }, description: "The client's own credentials" }, + "Partner": { type: "oauth2", flows: ["clientCredentials"], clientCredentials: { tokenUrl: "https://login.tokens.example/token", scopes: [] } }, + "Legacy": { type: "apiKey", in: "header", name: "X-Api-Key", deprecated: true }, + "Gnap": { type: "http", scheme: "gnap" }, + "Digest": { type: "http", scheme: "digest" }, + "Cert": { type: "mutualTLS" }, + "Oidc": { type: "openIdConnect", openIdConnectUrl: "https://login.tokens.example/.well-known/openid-configuration" }, +} as const; + +/** + * Each operation, by the name of its functions: its method and path; the servers that serve it + * instead of `flowapiServers`, where it has its own; its security, alternatives of which any one + * is enough, each naming the schemes it needs with their scopes (`[]`: none); how each response's + * body is read, by media type (`json`, `text`, `bytes`, or `sent`: by the `Content-Type` the + * answer sends, as `flowapiReadsBytes` says); by form and `multipart` media type, how the body's + * values are written (`encoding`: the description's Encoding Objects by name and by position, + * given as the body's `encoding`, `prefixEncoding` and `itemEncoding`); and its `Request` + * and `Response`. + */ +export const flowapiOperations = { + listThings: { + method: "GET", + path: "/things", + security: [{ "Client": ["read"] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: listThingsRequest, + response: listThingsResponse, + }, + writeThing: { + method: "POST", + path: "/things", + security: [{ "Client": ["read", "write"] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: writeThingRequest, + response: writeThingResponse, + }, + partner: { + method: "GET", + path: "/partner", + security: [{ "Partner": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: partnerRequest, + response: partnerResponse, + }, + legacy: { + method: "GET", + path: "/legacy", + security: [{ "Legacy": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: legacyRequest, + response: legacyResponse, + }, + optional: { + method: "GET", + path: "/optional", + security: [{ "Legacy": [] }, {}], + responses: { "200": { content: { "application/json": "json" } } }, + request: optionalRequest, + response: optionalResponse, + }, + gnap: { + method: "GET", + path: "/gnap", + security: [{ "Gnap": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: gnapRequest, + response: gnapResponse, + }, + digest: { + method: "GET", + path: "/digest", + security: [{ "Digest": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: digestRequest, + response: digestResponse, + }, + cert: { + method: "GET", + path: "/cert", + security: [{ "Cert": [] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: certRequest, + response: certResponse, + }, + oidc: { + method: "GET", + path: "/oidc", + security: [{ "Oidc": ["openid"] }], + responses: { "200": { content: { "application/json": "json" } } }, + request: oidcRequest, + response: oidcResponse, + }, +} as const; diff --git a/crates/flowapi-sdk/tests/client/tokens/src/client.ts b/crates/flowapi-sdk/tests/client/tokens/src/client.ts new file mode 100644 index 0000000..91f32a9 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/src/client.ts @@ -0,0 +1,83 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "./api.js"; +import * as $core from "./core/index.js"; +import { Things as $Things } from "./resources/things.js"; +import { Others as $Others } from "./resources/others.js"; + +/** What the config decides of the client. */ +const $settings: $core.Settings = { + client: "Tokens", + environments: { }, + logEnv: "TOKENS_LOG", + auth: { "Client": { option: "client", clientIdEnv: "TOKENS_CLIENT_ID", clientSecretEnv: "TOKENS_CLIENT_SECRET" }, "Partner": { option: "partner", env: "TOKENS_PARTNER_TOKEN", clientIdEnv: "TOKENS_PARTNER_ID", clientSecretEnv: "TOKENS_PARTNER_SECRET", scopes: ["partner.read"] }, "Legacy": { option: "legacy", env: "TOKENS_KEY" }, "Gnap": { option: "gnap", env: "TOKENS_GNAP" }, "Digest": { option: "digest" }, "Cert": { option: "cert" }, "Oidc": { option: "oidc", env: "TOKENS_OIDC" } }, + timeout: 60000, + maxRetries: 0, + maxRetryDelay: 60000, + servers: $api.flowapiServers, + schemes: $api.flowapiSecuritySchemes, + readsBytes: $api.flowapiReadsBytes, +}; + +/** The options of a `Tokens`: the runtime's, and a credential for each security scheme it sends. */ +export type TokensOptions = $core.ClientOptions & { + /** The credential of the security scheme `Client`: a token, or the client's id and secret to request one with, else `TOKENS_CLIENT_ID`, `TOKENS_CLIENT_SECRET`; `null` reads no variable. */ + client?: $core.Credential | $core.ClientCredentials | null | undefined; + /** The credential of the security scheme `Partner`: a token, or the client's id and secret to request one with, else `TOKENS_PARTNER_TOKEN`, `TOKENS_PARTNER_ID`, `TOKENS_PARTNER_SECRET`; `null` reads no variable. */ + partner?: $core.Credential | $core.ClientCredentials | null | undefined; + /** The credential of the security scheme `Legacy`: the key, else `TOKENS_KEY`; `null` reads no variable. @deprecated The description deprecates this scheme. */ + legacy?: $core.Credential | null | undefined; + /** The credential of the security scheme `Gnap`: the token, else `TOKENS_GNAP`; `null` reads no variable. */ + gnap?: $core.Credential | null | undefined; + /** The credential of the security scheme `Digest`: the token; `null` reads no variable. */ + digest?: $core.Credential | null | undefined; + /** The credential of the security scheme `Cert`: `true` when `fetch` presents the client certificate; `null` reads no variable. */ + cert?: true | null | undefined; + /** The credential of the security scheme `Oidc`: the token, else `TOKENS_OIDC`; `null` reads no variable. */ + oidc?: $core.Credential | null | undefined; +}; + +/** The API's client: a member for each resource (`client.things`), and `request` for a call no + * operation describes. */ +export class Tokens { + readonly #core: $core.Core; + readonly #options: TokensOptions; + readonly things: $Things; + readonly others: $Others; + + constructor(options: TokensOptions = {}) { + this.#options = { ...options }; + this.#core = new $core.Core($settings, options); + this.things = new $Things(this.#core); + this.others = new $Others(this.#core); + } + + /** The base URL calls go to, unless an operation has servers of its own. */ + get baseURL(): string | null { + return this.#core.baseURL; + } + + /** Milliseconds an attempt may take, its body read; `null` for no limit. */ + get timeout(): number | null { + return this.#core.timeout; + } + + /** How many times a failed attempt is tried again. */ + get maxRetries(): number { + return this.#core.maxRetries; + } + + /** A client of the same class with these options over this one's: one given as `undefined` + * keeps this one's. */ + withOptions(options: TokensOptions): this { + const next: Record = { ...this.#options }; + for (const [key, value] of Object.entries(options)) if (value !== undefined) next[key] = value; + return new (this.constructor as new (options: TokensOptions) => this)(next as TokensOptions); + } + + /** A call by method and path that no operation describes, with every credential the + * client has. */ + request(method: string, path: string, options?: $core.RawRequest): $core.ApiCall { + return $core.request(this.#core, method, path, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/tokens/src/index.ts b/crates/flowapi-sdk/tests/client/tokens/src/index.ts new file mode 100644 index 0000000..bcfd7f5 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/src/index.ts @@ -0,0 +1,45 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +export { Tokens, Tokens as default, type TokensOptions } from "./client.js"; +export { + APIConnectionError, + APIConnectionTimeoutError, + APIError, + APIUserAbortError, + ApiCall, + AuthenticationError, + BadRequestError, + type BasicCredential, + type BasicPair, + type ClientCredentials, + ConflictError, + type Credential, + CredentialError, + CrossOriginRedirectError, + type Data, + type Fetch, + type FetchResponse, + type HeadersInput, + type Input, + InsecureCredentialError, + InternalServerError, + type ItemOf, + type LogLevel, + type Logger, + NotFoundError, + type Outcome, + Page, + PagePromise, + PermissionDeniedError, + type QueryInput, + RateLimitError, + type RawRequest, + type RequestOptions, + RequestTimeoutError, + SdkError, + type ServerSentEvent, + Stream, + TokenError, + UnprocessableEntityError, +} from "./core/index.js"; +export * from "./api.js"; diff --git a/crates/flowapi-sdk/tests/client/tokens/src/resources/others.ts b/crates/flowapi-sdk/tests/client/tokens/src/resources/others.ts new file mode 100644 index 0000000..5fb42cf --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/src/resources/others.ts @@ -0,0 +1,48 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.others`. */ +export class Others { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /partner` */ + partner(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.partner, params, options); + } + + /** `GET /legacy` */ + legacy(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.legacy, params, options); + } + + /** `GET /optional` */ + optional(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.optional, params, options); + } + + /** `GET /gnap` */ + gnap(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.gnap, params, options); + } + + /** `GET /digest` */ + digest(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.digest, params, options); + } + + /** `GET /cert` */ + cert(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.cert, params, options); + } + + /** `GET /oidc` */ + oidc(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.oidc, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/tokens/src/resources/things.ts b/crates/flowapi-sdk/tests/client/tokens/src/resources/things.ts new file mode 100644 index 0000000..3e1b422 --- /dev/null +++ b/crates/flowapi-sdk/tests/client/tokens/src/resources/things.ts @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +import * as $api from "../api.js"; +import * as $core from "../core/index.js"; + +/** The methods of `client.things`. */ +export class Things { + readonly #core: $core.Core; + + constructor(core: $core.Core) { + this.#core = core; + } + + /** `GET /things` */ + list(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.listThings, params, options); + } + + /** `POST /things` */ + write(params: $core.Input = {}, options?: $core.RequestOptions): $core.ApiCall<$core.Data> { + return $core.call(this.#core, $api.flowapiOperations.writeThing, params, options); + } +} diff --git a/crates/flowapi-sdk/tests/client/wire.mjs b/crates/flowapi-sdk/tests/client/wire.mjs index 0b256ce..f1f1bf3 100644 --- a/crates/flowapi-sdk/tests/client/wire.mjs +++ b/crates/flowapi-sdk/tests/client/wire.mjs @@ -114,10 +114,10 @@ export function tests(built) { ['R28: fetch is called with no this', async () => { assert.equal(await shop(built, stub(() => reply(200, 'up', { 'content-type': 'text/plain' }))).system.health(), 'up') }], - ['R29: the logs mask credentials, secret query parameters, a URL\'s user and fragment', async () => { + ['R29: the logs mask credentials, secret query parameters, a URL\'s fragment (a URL with a user is never sent: R43)', async () => { const log = recorder() const fetch = stub(() => reply(200, { ok: true })) - const shopClient = shop(built, fetch, { logLevel: 'debug', logger: log.logger, baseURL: 'https://me:pw@h.example/v1#frag', bearerAuth: 'tok-secret' }) + const shopClient = shop(built, fetch, { logLevel: 'debug', logger: log.logger, baseURL: 'https://h.example/v1#frag', bearerAuth: 'tok-secret' }) await shopClient.pets.retrieve({ path: { pet_id: 'p1' } }, { headers: { cookie: 'sid=cookie-secret' } }) const auth = new built.auth.AuthClient({ fetch, queryKey: 'query-secret', token: 'tok-secret', logLevel: 'debug', logger: log.logger }) await auth.checks.both() @@ -148,6 +148,8 @@ export function tests(built) { await b.pets.retrieve({ path: { pet_id: 'p1' } }) assert.equal(fetch.calls[0].headers['x-api-key'], 'k') }], + // req: rfc9110.15.4.should-automatically-following-redirected-request-user-agent — a 303 followed as GET with no body or Content-Type, the other headers sent again + // req: rfc6750.5.3.must-safeguard-bearer-tokens-client-implementations-ensure — a redirect to another origin refused, and allowed only without the credentials (the logs mask them: R29) ['R34: a redirect to another origin is refused; allowed, it loses the credentials', async () => { const away = (url) => (url.startsWith('https://api.') ? reply(307, null, { location: 'https://evil.example/steal' }) : reply(200, pet)) const refused = stub(away) diff --git a/crates/flowapi-sdk/tests/config.rs b/crates/flowapi-sdk/tests/config.rs index 4e2a762..26c8eeb 100644 --- a/crates/flowapi-sdk/tests/config.rs +++ b/crates/flowapi-sdk/tests/config.rs @@ -63,6 +63,23 @@ const EXPECTED: &[(&str, &[&str])] = &[ "config.schema.empty", ], ), + ( + "auth", + &[ + "config.auth.declared", + "config.auth.unknown", + "config.auth.field", + "config.auth.type", + "config.auth.in", + "config.auth.option", + "config.auth.refused", + "config.auth.mutual_tls", + "config.security.unknown", + "config.auth.env", + "config.auth.unlisted", + ], + ), + ("auth-none", &["config.auth.none"]), ( "names", &[ diff --git a/crates/flowapi-sdk/tests/config/auth-none.txt b/crates/flowapi-sdk/tests/config/auth-none.txt new file mode 100644 index 0000000..bc87b3e --- /dev/null +++ b/crates/flowapi-sdk/tests/config/auth-none.txt @@ -0,0 +1,2 @@ +warning[config.auth.none]: no operation needs a credential, by the description's `security` or the config's: the client sends none; if the API takes one, declare it under `auth` and name it in `security`; `security: []` says it takes none + at auth-none.yml:3:1 (/) diff --git a/crates/flowapi-sdk/tests/config/auth-none.yml b/crates/flowapi-sdk/tests/config/auth-none.yml new file mode 100644 index 0000000..7eb8021 --- /dev/null +++ b/crates/flowapi-sdk/tests/config/auth-none.yml @@ -0,0 +1,22 @@ +# No operation needs a credential once the config's `security` is over them (`{}` alone), and +# the config does not say so with `security: []`: the client sends none, which is warned of. +version: 1 +spec: spec.json +package: { name: petshop, client: PetShop } +security: + - {} +resources: + pets: + methods: + list: listPets +skip: + - { op: createPet, reason: elsewhere } + - { op: getPet, reason: elsewhere } + - { op: updatePet, reason: elsewhere } + - { op: deletePet, reason: elsewhere } + - { op: listPhotos, reason: elsewhere } + - { op: listOwners, reason: elsewhere } + - { op: streamEvents, reason: elsewhere } + - { op: getCollision, reason: elsewhere } + - { op: listUsers, reason: elsewhere } + - { op: "GET /internal/health", reason: not public } diff --git a/crates/flowapi-sdk/tests/config/auth.txt b/crates/flowapi-sdk/tests/config/auth.txt new file mode 100644 index 0000000..6827943 --- /dev/null +++ b/crates/flowapi-sdk/tests/config/auth.txt @@ -0,0 +1,43 @@ +error[config.auth.declared]: `ApiKeyAuth` is a security scheme of the description: the config may give it options (its environment variables, `scopes`), not say again what it is + at auth.yml:11:23 (/auth/ApiKeyAuth/type) +error[config.auth.unknown]: `bearr` names no security scheme of the description + at auth.yml:12:3 (/auth/bearr) + hint: did you mean `bearer`? +error[config.auth.unknown]: `Nothing` names no security scheme of the description + at auth.yml:13:3 (/auth/Nothing) + hint: give `type` (and the members of its kind) to declare a scheme the description lacks +error[config.auth.field]: `NoName`, of type `apiKey`, needs `name` + at auth.yml:14:19 (/auth/NoName/type) +error[config.auth.field]: `in` is no member of a scheme of type `http` + at auth.yml:15:44 (/auth/Extra/in) +error[config.auth.field]: `token_url` is no member of a scheme of type `http` + at auth.yml:15:63 (/auth/Extra/token_url) +error[config.auth.type]: `/auth/Wrong/type`: `openIdConnect` is not one of `apiKey`, `http`, `oauth2`, `mutualTLS` + at auth.yml:16:12 (/auth/Wrong/type) +error[config.auth.in]: `/auth/BadIn/in`: `body` is not one of `header`, `query`, `cookie` + at auth.yml:17:26 (/auth/BadIn/in) +error[config.auth.option]: `username_env_var` is given without `password_env_var` + at auth.yml:18:56 (/auth/Half/username_env_var) +error[config.auth.option]: `password_env_var` is for HTTP basic only + at auth.yml:19:61 (/auth/NotBasic/password_env_var) +error[config.auth.option]: `scopes` is for OAuth 2.0 with a client credentials flow only: other tokens are the caller's + at auth.yml:19:88 (/auth/NotBasic/scopes) +error[config.auth.option]: `client_id_env_var` is for OAuth 2.0 with a client credentials flow only + at auth.yml:20:46 (/auth/NoFlow/client_id_env_var) +error[config.auth.option]: `client_secret_env_var` is for OAuth 2.0 with a client credentials flow only + at auth.yml:20:82 (/auth/NoFlow/client_secret_env_var) +warning[config.auth.refused]: `Digest` is HTTP `digest`, which answers a challenge or signs each request: the client cannot send it; give `Authorization` in a call's `headers` + at auth.yml:21:3 (/auth/Digest) +warning[config.auth.mutual_tls]: `Cert` is a client certificate, which no request carries: give the client a `fetch` (or `fetchOptions`) that presents it, and the option `true` to say so + at auth.yml:22:3 (/auth/Cert) +error[config.auth.option]: a client certificate is read from no environment variable + at auth.yml:22:37 (/auth/Cert/env_var) +warning[config.auth.env]: `Plain` names no environment variable: the client sends it only when given its option + at auth.yml:23:3 (/auth/Plain) +error[config.security.unknown]: `Nowhere` names no security scheme of the description or of `auth` + at auth.yml:26:5 (/security/1/Nowhere) +warning[config.auth.unlisted]: `pets.get` needs `bearer`, which `auth` does not list: the client sends no credential for it + at auth.yml:32:7 (/resources/pets/methods/get) +error[config.security.unknown]: `Bearer` names no security scheme of the description or of `auth` + at auth.yml:34:45 (/resources/pets/methods/delete/security/0/Bearer) + hint: did you mean `bearer`? diff --git a/crates/flowapi-sdk/tests/config/auth.yml b/crates/flowapi-sdk/tests/config/auth.yml new file mode 100644 index 0000000..d942fbd --- /dev/null +++ b/crates/flowapi-sdk/tests/config/auth.yml @@ -0,0 +1,41 @@ +# `auth` and `security` wrong in every way the checker knows: a scheme of the description said +# again, a name no scheme has (with and without a hint), a declared scheme missing a member of +# its kind or given another kind's, a type and an `in` no scheme has, options of another kind or +# without their pair, `scopes` and a variable where they cannot be, a scheme that answers a +# challenge, a client certificate, a name `security` uses that nothing declares, a used scheme +# with no variable, and one used that `auth` does not list. +version: 1 +spec: spec.json +package: { name: petshop, client: PetShop } +auth: + ApiKeyAuth: { type: apiKey, in: header, name: X-Other, env_var: PET_SHOP_API_KEY } + bearr: { env_var: PET_SHOP_TOKEN } + Nothing: {} + NoName: { type: apiKey, in: query } + Extra: { type: http, scheme: bearer, in: header, token_url: https://login.example/token } + Wrong: { type: openIdConnect } + BadIn: { type: apiKey, in: body, name: k } + Half: { type: http, scheme: basic, username_env_var: PET_SHOP_USER } + NotBasic: { type: http, scheme: bearer, password_env_var: PET_SHOP_PASSWORD, scopes: [a] } + NoFlow: { type: oauth2, client_id_env_var: PET_SHOP_ID, client_secret_env_var: PET_SHOP_SECRET } + Digest: { type: http, scheme: Digest } + Cert: { type: mutualTLS, env_var: PET_SHOP_CERT } + Plain: { type: http, scheme: gnap } +security: + - Plain: [] + - Nowhere: [] +resources: + pets: + methods: + list: listPets + create: { op: createPet, security: [{ Digest: [] }, { Cert: [] }] } + get: { op: getPet, security: [{ bearer: [] }] } + update: { op: updatePet, security: [{ ApiKeyAuth: [] }] } + delete: { op: deletePet, security: [{ Bearer: [] }] } +skip: + - { op: listPhotos, reason: elsewhere } + - { op: listOwners, reason: elsewhere } + - { op: streamEvents, reason: elsewhere } + - { op: getCollision, reason: elsewhere } + - { op: listUsers, reason: elsewhere } + - { op: "GET /internal/health", reason: not public } diff --git a/crates/flowapi-sdk/tests/config/format.txt b/crates/flowapi-sdk/tests/config/format.txt index 7a7b790..5cda2d4 100644 --- a/crates/flowapi-sdk/tests/config/format.txt +++ b/crates/flowapi-sdk/tests/config/format.txt @@ -4,6 +4,8 @@ error[config.package.name]: `/package/name`: `PetShop` is not an npm package nam at format.yml:6:12 (/package/name) error[config.package.client]: `/package/client`: `petShop` is not a class name in PascalCase: a capital, then letters and digits at format.yml:6:27 (/package/client) +error[config.schema.type]: `/package/keywords` is a string; it is an array + at format.yml:6:44 (/package/keywords) error[config.env.url]: `/environments/production`: `api.petshop.example` is not an absolute http or https URL with a host at format.yml:8:3 (/environments/production) error[config.name.invalid]: `2nd` is not a name: ASCII letters, digits, `_` and `-`, opening with a letter @@ -16,6 +18,8 @@ error[config.schema.range]: `/defaults/timeout` is 0; it is a number of seconds at format.yml:11:27 (/defaults/timeout) error[config.schema.range]: `/defaults/max_retry_delay` is -1; it is a number of seconds above 0 at format.yml:11:39 (/defaults/max_retry_delay) +error[config.header]: `/defaults/idempotency_key`: `Idempotency Key` is not a header's name: ASCII letters, digits and any of !#$%&'*+-.^_`|~, no space + at format.yml:11:60 (/defaults/idempotency_key) error[config.pagination.type]: `cursr` is not a pagination scheme's type: one of cursor, last_item_id, offset, page, link, single at format.yml:14:11 (/pagination/cursor/type) hint: did you mean `cursor`? @@ -26,10 +30,10 @@ error[config.schema.required]: `/pagination/paged/request` needs `page`: The par error[config.schema.unknown]: `pages` is not a member of `/pagination/paged/request` (it has page, per_page) at format.yml:17:16 (/pagination/paged/request/pages) hint: did you mean `page`? -error[config.schema.unknown]: `resoures` is not a member of `/` (it has version, generator, spec, package, environments, auth, defaults, pagination, resources, skip, readme) +error[config.schema.unknown]: `resoures` is not a member of `/` (it has version, generator, spec, package, environments, auth, security, defaults, pagination, resources, skip, readme) at format.yml:18:1 (/resoures) hint: did you mean `resources`? -error[config.schema.unknown]: `overrides` is not a member of `/` (it has version, generator, spec, package, environments, auth, defaults, pagination, resources, skip, readme) +error[config.schema.unknown]: `overrides` is not a member of `/` (it has version, generator, spec, package, environments, auth, security, defaults, pagination, resources, skip, readme) at format.yml:19:1 (/overrides) error[config.coverage]: `getPet` is in no resource and not in `skip` at format.yml:21:3 (/resources) @@ -61,7 +65,9 @@ error[config.coverage]: `GET /internal/health` is in no resource and not in `ski error[config.schema.unknown]: `methds` is not a member of `/resources/pets` (it has methods, resources) at format.yml:22:5 (/resources/pets/methds) hint: did you mean `methods`? -error[config.schema.unknown]: `pagniation` is not a member of `/resources/pets/methods/list` (it has op, pagination, retries, stream) +warning[config.auth.unlisted]: `pets.list` needs `ApiKeyAuth`, which `auth` does not list: the client sends no credential for it + at format.yml:24:7 (/resources/pets/methods/list) +error[config.schema.unknown]: `pagniation` is not a member of `/resources/pets/methods/list` (it has op, pagination, retries, stream, security) at format.yml:24:29 (/resources/pets/methods/list/pagniation) hint: did you mean `pagination`? error[config.schema.range]: `/resources/pets/methods/list/retries` is 11; it is an integer from 0 to 10 diff --git a/crates/flowapi-sdk/tests/config/format.yml b/crates/flowapi-sdk/tests/config/format.yml index 38378cc..b75ab1f 100644 --- a/crates/flowapi-sdk/tests/config/format.yml +++ b/crates/flowapi-sdk/tests/config/format.yml @@ -3,12 +3,12 @@ # values of the wrong type or out of range, required members missing, strings of the wrong kind. version: 2 spec: spec.json -package: { name: PetShop, client: petShop } +package: { name: PetShop, client: petShop, keywords: pets } environments: production: api.petshop.example 2nd: https://api.petshop.example env_var: pet_shop_url -defaults: { retries: "2", timeout: 0, max_retry_delay: -1 } +defaults: { retries: "2", timeout: 0, max_retry_delay: -1, idempotency_key: "Idempotency Key" } pagination: cursor: type: cursr diff --git a/crates/flowapi-sdk/tests/config/names.txt b/crates/flowapi-sdk/tests/config/names.txt index c2410a1..6d0065e 100644 --- a/crates/flowapi-sdk/tests/config/names.txt +++ b/crates/flowapi-sdk/tests/config/names.txt @@ -1,6 +1,8 @@ error[config.name.duplicate]: the environment `Production` and the environment `production` are one name (`production`) in `environments` at names.yml:11:3 (/environments/Production) hint: rename one; `production` is at /environments/production +warning[config.auth.unlisted]: `pets.list_all` needs `ApiKeyAuth`, which `auth` does not list: the client sends no credential for it + at names.yml:15:7 (/resources/pets/methods/list_all) error[config.name.duplicate]: the method `listAll` and the method `list_all` are one name (`list all`) in `pets` at names.yml:16:7 (/resources/pets/methods/listAll) hint: rename one; `list_all` is at /resources/pets/methods/list_all diff --git a/crates/flowapi-sdk/tests/config/paging.txt b/crates/flowapi-sdk/tests/config/paging.txt index 7188932..08962b8 100644 --- a/crates/flowapi-sdk/tests/config/paging.txt +++ b/crates/flowapi-sdk/tests/config/paging.txt @@ -1,9 +1,10 @@ -warning[config.generator.version]: the config pins flowapi 9.9.9, and this is flowapi 0.2.0 +warning[config.generator.version]: the config pins flowapi 9.9.9, and this is flowapi 0.3.0 at paging.yml:9:23 (/generator/flowapi) error[config.env.default]: no environment is named `prod` at paging.yml:14:12 (/environments/default) error[config.auth.unknown]: `ApiKey` names no security scheme of the description at paging.yml:16:3 (/auth/ApiKey) + hint: give `type` (and the members of its kind) to declare a scheme the description lacks error[config.coverage]: `deletePet` is in no resource and not in `skip` at paging.yml:34:3 (/resources) hint: name it under a resource's `methods`, or add it to `skip` with a reason @@ -29,6 +30,8 @@ error[config.pagination.mismatch]: `pets.list` (GET /pets) pages by `wrong`: `re at paging.yml:36:7 (/resources/pets/methods/list) error[config.pagination.missing]: `pets.list` (GET /pets) pages by `wrong`: `response.next`: the response has no `next_token` (it has `data`, `next_page_token`, `has_more`) at paging.yml:36:7 (/resources/pets/methods/list) +warning[config.auth.unlisted]: `pets.list` needs `ApiKeyAuth`, which `auth` does not list: the client sends no credential for it + at paging.yml:36:7 (/resources/pets/methods/list) error[config.stream.media]: `GET /pets` answers no 2xx response as a stream (`text/event-stream`, JSON lines) at paging.yml:36:56 (/resources/pets/methods/list/stream) error[config.pagination.link]: `pets.list_linked` (GET /pets) pages by `both`: `response.next`: a link scheme names one of `next` (a path in the body) or `header` diff --git a/crates/flowapi-sdk/tests/config/refs.txt b/crates/flowapi-sdk/tests/config/refs.txt index 726fcae..9af60b6 100644 --- a/crates/flowapi-sdk/tests/config/refs.txt +++ b/crates/flowapi-sdk/tests/config/refs.txt @@ -25,6 +25,8 @@ error[config.op.unknown]: `listPet` names no operation of the description error[config.op.unknown]: `GET /pets/{petId}` names no operation of the description at refs.yml:11:17 (/resources/pets/methods/retrieve) hint: did you mean `GET /pets/{pet_id}`? +warning[config.auth.unlisted]: `pets.update` needs `ApiKeyAuth`, which `auth` does not list: the client sends no credential for it + at refs.yml:12:7 (/resources/pets/methods/update) error[config.op.twice]: `createPet` is in two places: pets.create and pets.make at refs.yml:14:19 (/resources/pets/methods/make/op) error[config.op.twice]: `deletePet` is in two places: pets.delete and skip diff --git a/crates/flowapi-sdk/tests/config/valid.yml b/crates/flowapi-sdk/tests/config/valid.yml index dac72a9..d60d958 100644 --- a/crates/flowapi-sdk/tests/config/valid.yml +++ b/crates/flowapi-sdk/tests/config/valid.yml @@ -1,12 +1,14 @@ # Every member of the format, each naming what the description has: no issue. version: 1 -generator: { flowapi: "0.2.x" } +generator: { flowapi: "0.3.x" } spec: spec.json package: name: "@petshop/sdk" client: PetShop license: MIT repository: https://github.com/petshop/sdk + description: The TypeScript SDK of the Pet Shop API, unofficial. + keywords: [pets, shop] environments: production: https://api.petshop.example/v1 sandbox: https://sandbox.petshop.example/v1 @@ -14,6 +16,18 @@ environments: env_var: PET_SHOP_BASE_URL auth: ApiKeyAuth: { env_var: PET_SHOP_API_KEY } + bearer: { env_var: PET_SHOP_TOKEN } + Session: { type: apiKey, in: cookie, name: sid, env_var: PET_SHOP_SESSION, description: A session } + Admin: { type: http, scheme: basic, username_env_var: PET_SHOP_USER, password_env_var: PET_SHOP_PASSWORD } + Client: + type: oauth2 + token_url: https://login.petshop.example/token + client_id_env_var: PET_SHOP_CLIENT_ID + client_secret_env_var: PET_SHOP_CLIENT_SECRET + scopes: [pets.read] +security: + - ApiKeyAuth: [] + - bearer: [] defaults: { retries: 2, timeout: 60, max_retry_delay: 30, pagination: cursor } pagination: cursor: @@ -46,7 +60,7 @@ resources: create: createPet get: { op: getPet, retries: 0 } update: "PATCH /pets/{pet_id}" - delete: delete /pets/{pet_id} + delete: { op: "delete /pets/{pet_id}", security: [{ Admin: [] }, { Client: [pets.write], Session: [] }] } resources: photos: methods: @@ -59,10 +73,10 @@ resources: stream: { op: streamEvents, stream: true } collisions: methods: - get: getCollision + get: { op: getCollision, security: [] } users: methods: list: { op: listUsers, pagination: one } skip: - { op: "GET /internal/health", reason: not public } -readme: { headline_method: pets.list, pagination_method: pets.photos.list, intro: "The Pet Shop API." } +readme: { title: Pet Shop SDK, headline_method: pets.list, pagination_method: pets.photos.list, intro: "The Pet Shop API." } diff --git a/crates/flowapi-sdk/tests/draft.rs b/crates/flowapi-sdk/tests/draft.rs index fdf83c5..2d56480 100644 --- a/crates/flowapi-sdk/tests/draft.rs +++ b/crates/flowapi-sdk/tests/draft.rs @@ -45,6 +45,14 @@ fn issues(name: &str, spec: &str, yaml: &str) -> String { flowapi_sdk::issues_text(&found, "draft.yml", &|o| config.place(o)) } +/// The codes of an issues text, as its lines open them (`warning[config.auth.none`). +fn codes(found: &str) -> Vec<&str> { + found + .lines() + .filter_map(|l| l.split_once(']').map(|(c, _)| c)) + .collect() +} + /// A JSON value written with each object's members in the order `reverse` says: sorted (as /// `serde_json` keeps them), or the reverse. fn write(v: &Value, reverse: bool, out: &mut String) { @@ -111,10 +119,13 @@ fn drafts_print_as_kept_and_pass_check() { for (name, spec, kept) in cases() { let text = std::fs::read_to_string(&spec).expect("the description"); let printed = draft(&name, &text); - assert_eq!( - issues(&name, &text, &printed), - "", - "{name}: the draft fails its own check:\n{printed}" + // A draft has no issue but, where the description needs no credential, `config.auth.none`. + let found = issues(&name, &text, &printed); + let silent = !printed.contains("\n# security:\n"); + assert!( + (silent && found.is_empty()) + || (!silent && codes(&found) == ["warning[config.auth.none"]), + "{name}: the draft fails its own check:\n{found}\n{printed}" ); if bless { std::fs::write(&kept, &printed).expect("written"); @@ -156,3 +167,57 @@ fn a_schema_has_no_draft() { docs.add("s.json", r#"{"type":"string"}"#).expect("JSON"); assert_eq!(flowapi_sdk::draft(&docs, "s.json"), None); } + +/// A description whose schemes no config can answer in full (a client certificate, an HTTP +/// scheme that answers a challenge, a deprecated scheme): its draft lists each, and the only +/// issues are the three warnings of what the description holds. +#[test] +fn a_draft_warns_only_of_what_the_description_holds() { + let spec = root().join("client/tokens/spec.json"); + let text = std::fs::read_to_string(&spec).expect("the description"); + let printed = draft("tokens.json", &text); + for listed in [ + " Cert: {}", + " Digest: {}", + " Legacy:\n env_var: TOKENS_LEGACY", + " client_id_env_var: TOKENS_CLIENT_CLIENT_ID", + ] { + assert!(printed.contains(listed), "{listed:?} in:\n{printed}"); + } + let issues = issues("tokens.json", &text, &printed); + assert_eq!( + codes(&issues), + [ + "warning[config.auth.mutual_tls", + "warning[config.auth.refused", + "warning[config.auth.deprecated" + ], + "{issues}" + ); +} + +/// A description that declares no security: its draft leaves `security` unset (never +/// `security: []`, the config's own word that the API takes no credentials), so `config check` +/// gives exactly one warning, `config.auth.none`, and no error. +#[test] +fn a_draft_without_security_warns_that_there_is_no_auth() { + for name in ["github.json", "rpc.json"] { + let text = std::fs::read_to_string(root().join("draft").join(name)).expect("description"); + let printed = draft(name, &text); + assert!( + !printed.lines().any(|l| l.starts_with("security:")), + "{name}: a live security in:\n{printed}" + ); + assert!( + printed.contains("# security:\n# - "), + "{name}: no example" + ); + let found = issues(name, &text, &printed); + assert_eq!( + codes(&found), + ["warning[config.auth.none"], + "{name}: {found}" + ); + assert!(!found.contains("error["), "{name}: {found}"); + } +} diff --git a/crates/flowapi-sdk/tests/draft/github.json b/crates/flowapi-sdk/tests/draft/github.json new file mode 100644 index 0000000..d4bab2e --- /dev/null +++ b/crates/flowapi-sdk/tests/draft/github.json @@ -0,0 +1,17 @@ +{ + "openapi": "3.0.3", + "info": { "title": "GitHub-like", "version": "1" }, + "servers": [{ "url": "https://api.github.example" }], + "paths": { + "/user": { "get": { "operationId": "users/get-authenticated", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/repos/{owner}/{repo}": { "get": { "operationId": "repos/get", "parameters": [{ "name": "owner", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "repo", "in": "path", "required": true, "schema": { "type": "string" } }], "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/meta": { "get": { "operationId": "meta/get", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/app/hook": { "get": { "operationId": "apps/get-webhook", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } }, + "/enterprise/settings": { "get": { "operationId": "enterprise/get-settings", "responses": { "200": { "$ref": "#/components/responses/Ok" } } } } + }, + "components": { + "responses": { + "Ok": { "description": "ok", "content": { "application/json": { "schema": { "type": "object", "properties": { "login": { "type": "string" } } } } } } + } + } +} diff --git a/crates/flowapi-sdk/tests/draft/github.yml b/crates/flowapi-sdk/tests/draft/github.yml new file mode 100644 index 0000000..e71fe32 --- /dev/null +++ b/crates/flowapi-sdk/tests/draft/github.yml @@ -0,0 +1,43 @@ +# A first flowapi-sdk.yml, drafted by `flowapi config draft` from the description: rename +# resources and methods, page what pages, then `flowapi config check` it. +version: 1 +generator: + flowapi: "0.3.0" +spec: github.json +package: + name: github-like + version: 0.1.0 + client: GitHubLike +environments: + production: "https://api.github.example" + default: production + env_var: GITHUB_LIKE_BASE_URL +# The description declares no security scheme that an operation uses. Most APIs take a +# credential: find it in the API's documentation, declare it under `auth` and name it in +# `security`, as in the example below, or write `security: []` when the API truly takes +# none. Until then `config check` warns `config.auth.none`. +# auth: +# token: { type: http, scheme: bearer, env_var: GITHUB_LIKE_TOKEN } +# security: +# - token: [] +defaults: + retries: 1 + timeout: 60 + max_retry_delay: 60 +resources: + app: + methods: + get_webhook: apps/get-webhook # GET /app/hook + enterprise: + methods: + get_settings: enterprise/get-settings # GET /enterprise/settings + meta: + methods: + list: meta/get # GET /meta + repos: + methods: + retrieve: repos/get # GET /repos/{owner}/{repo} + user: + methods: + list: users/get-authenticated # GET /user +skip: [] diff --git a/crates/flowapi-sdk/tests/draft/rpc.yml b/crates/flowapi-sdk/tests/draft/rpc.yml index 0af7c5f..3ba1420 100644 --- a/crates/flowapi-sdk/tests/draft/rpc.yml +++ b/crates/flowapi-sdk/tests/draft/rpc.yml @@ -2,7 +2,7 @@ # resources and methods, page what pages, then `flowapi config check` it. version: 1 generator: - flowapi: "0.2.0" + flowapi: "0.3.0" spec: rpc.json package: name: chat @@ -15,8 +15,14 @@ environments: auth: token: env_var: CHAT_TOKEN +# The description declares no security scheme that an operation uses. Most APIs take a +# credential: find it in the API's documentation, declare it under `auth` and name it in +# `security`, as in the example below, or write `security: []` when the API truly takes +# none. Until then `config check` warns `config.auth.none`. +# security: +# - token: [] defaults: - retries: 2 + retries: 1 timeout: 60 max_retry_delay: 60 pagination: diff --git a/crates/flowapi-sdk/tests/draft/shop.yml b/crates/flowapi-sdk/tests/draft/shop.yml index 9b9a681..ecf0ff8 100644 --- a/crates/flowapi-sdk/tests/draft/shop.yml +++ b/crates/flowapi-sdk/tests/draft/shop.yml @@ -2,7 +2,7 @@ # resources and methods, page what pages, then `flowapi config check` it. version: 1 generator: - flowapi: "0.2.0" + flowapi: "0.3.0" spec: spec.json package: name: pet-shop @@ -19,7 +19,7 @@ auth: bearer: env_var: PET_SHOP_BEARER defaults: - retries: 2 + retries: 1 timeout: 60 max_retry_delay: 60 pagination: diff --git a/crates/flowapi-sdk/tests/draft/stripe.yml b/crates/flowapi-sdk/tests/draft/stripe.yml index 9d47d55..3eb916e 100644 --- a/crates/flowapi-sdk/tests/draft/stripe.yml +++ b/crates/flowapi-sdk/tests/draft/stripe.yml @@ -2,7 +2,7 @@ # resources and methods, page what pages, then `flowapi config check` it. version: 1 generator: - flowapi: "0.2.0" + flowapi: "0.3.0" spec: stripe.json package: name: payhub-v1-rest-api @@ -14,9 +14,15 @@ environments: env_var: PAYHUB_V1_REST_API_BASE_URL auth: basicAuth: - env_var: PAYHUB_V1_REST_API_BASIC_AUTH + env_var: PAYHUB_V1_REST_API_BASIC_AUTH # username:password +# The description declares no security scheme that an operation uses. Most APIs take a +# credential: find it in the API's documentation, declare it under `auth` and name it in +# `security`, as in the example below, or write `security: []` when the API truly takes +# none. Until then `config check` warns `config.auth.none`. +# security: +# - basicAuth: [] defaults: - retries: 2 + retries: 1 timeout: 60 max_retry_delay: 60 pagination: @@ -37,8 +43,8 @@ resources: create: PostCustomers # POST /v1/customers delete: DeleteCustomersCustomer # DELETE /v1/customers/{customer} retrieve: GetCustomersCustomer # GET /v1/customers/{customer} - post_customers_customer: PostCustomersCustomer # POST /v1/customers/{customer} - get_customers_customer_sources: GetCustomersCustomerSources # GET /v1/customers/{customer}/sources + update: PostCustomersCustomer # POST /v1/customers/{customer} + get_sources: GetCustomersCustomerSources # GET /v1/customers/{customer}/sources request_api: methods: list: GetRequest # GET /v1/request diff --git a/crates/flowapi-sdk/tests/draft/swagger.yml b/crates/flowapi-sdk/tests/draft/swagger.yml index 80fb8e1..9cf8273 100644 --- a/crates/flowapi-sdk/tests/draft/swagger.yml +++ b/crates/flowapi-sdk/tests/draft/swagger.yml @@ -2,7 +2,7 @@ # resources and methods, page what pages, then `flowapi config check` it. version: 1 generator: - flowapi: "0.2.0" + flowapi: "0.3.0" spec: swagger.json package: name: api-2nd-hand-market @@ -17,8 +17,14 @@ auth: env_var: API_2ND_HAND_MARKET_KEY oauth: env_var: API_2ND_HAND_MARKET_OAUTH +# The description declares no security scheme that an operation uses. Most APIs take a +# credential: find it in the API's documentation, declare it under `auth` and name it in +# `security`, as in the example below, or write `security: []` when the API truly takes +# none. Until then `config check` warns `config.auth.none`. +# security: +# - key: [] defaults: - retries: 2 + retries: 1 timeout: 60 max_retry_delay: 60 pagination: diff --git a/crates/flowapi-sdk/tests/repo.rs b/crates/flowapi-sdk/tests/repo.rs index 779ee5c..c6af7f6 100644 --- a/crates/flowapi-sdk/tests/repo.rs +++ b/crates/flowapi-sdk/tests/repo.rs @@ -57,7 +57,9 @@ fn case(name: &str) -> (String, String) { fn repositories_print_as_kept() { let bless = std::env::var_os("FLOWAPI_BLESS").is_some(); let mut changed = Vec::new(); - for name in ["auth", "shop"] { + for name in [ + "auth", "edge", "github", "hosts", "shop", "swagger", "tokens", + ] { let (spec, config) = case(name); let (repo, found) = generate(&spec, &config, None); assert!(!found.contains("error["), "{name}: {found}"); @@ -216,3 +218,43 @@ fn the_package_version_is_exact_and_printed() { package.text ); } + +/// The README's authentication section has a row for every security scheme the client knows +/// (the table's `flowapiSecuritySchemes`: the description's and the config's), whatever its kind. +#[test] +fn the_readme_names_every_security_scheme() { + for name in ["auth", "github", "shop", "swagger", "tokens"] { + let (spec, config) = case(name); + let (repo, _) = generate(&spec, &config, None); + let text = |path: &str| { + repo.files + .iter() + .find(|f| f.path == path) + .map(|f| f.text.clone()) + .expect(path) + }; + let api = text("src/api.ts"); + let table = api + .split("export const flowapiSecuritySchemes = {\n") + .nth(1) + .and_then(|t| t.split("} as const;").next()) + .expect("the schemes"); + let schemes: Vec<&str> = table + .lines() + .filter_map(|l| l.trim().strip_prefix('"')?.split('"').next()) + .collect(); + assert!(!schemes.is_empty(), "{name}: no scheme"); + let readme = text("README.md"); + let section = readme + .split("## Authentication\n") + .nth(1) + .and_then(|t| t.split("\n## ").next()) + .expect("an authentication section"); + for s in schemes { + assert!( + section.contains(&format!("| `{s}` |")), + "{name}: `{s}` is not in:\n{section}" + ); + } + } +} diff --git a/crates/flowapi-sdk/tests/repo/auth/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/auth/.flowapi/lock.json index 8884cf3..9632496 100644 --- a/crates/flowapi-sdk/tests/repo/auth/.flowapi/lock.json +++ b/crates/flowapi-sdk/tests/repo/auth/.flowapi/lock.json @@ -1,50 +1,53 @@ { "version": 1, - "flowapi": "0.2.0", + "flowapi": "0.3.0", "spec_sha256": "5f6b2648b7f138cf1e945772fc7f04ab81538057cb3b7666f2594dc00a845187", "config_sha256": "1bd9d8d3aaa11a79dcbac52938dd6ca965b53b49f9c3707e3a1ff33f7066a4c9", "configured_endpoints": 12, "files": { ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", - "AGENTS.md": "5b8c401fd037e88eb5d07f48d10e51065408c0860bb26e5955b114860e3df2ca", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", "LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", - "README.md": "fdf3824dafd81d853dd37d59c66cf028adac0894d360664143b741c6be057128", - "api.md": "4f818e51b51b3b24c963f65080ee3bb8af6a0594040c06f6319f0ff011076fe7", + "README.md": "cebc3313fe956f5601704399c4fc2976a8fda05af54d691eff110162da9af5d5", + "api.md": "8b5ef3231c39952d7862884ac0188587887c476f7b354541080827e1cdcfb53c", "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "mock/routes.mjs": "3cfdfa5cf6185e39cd3b6b27f4974b8579771b2f1c74ddcaac3c79f50868dbd7", - "mock/server.mjs": "6172f681d001cdff8a293de45151012c2f825c7993a3794e1537b1895fd64f71", - "package.json": "d5bbc079574bf848f20decc807ed99b248e4d4d4c2831e9307842c89151bec86", + "mock/routes.mjs": "1b01bef784b5eca1d36019987286a13b1f807553ad407068647d18f2621e8f06", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "a16e7516ee3be494f569616a0135c45bb4877cf400b4520f5f07dafcfa4568c6", "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", - "src/api.ts": "bb9b687c3752be970bdbdbe9aebede7d7fd604e4892c6d05fec49a7e8ca4b9b3", - "src/client.ts": "db7f3db5fc4a333f53d46e75e4459e4e45d5a14cb2d52ce13dd0157d5fd9bee9", - "src/core/auth.ts": "40626554be57a4b868baeaa13cefc25f8567ec76b159b94f6cd142127d03377d", + "src/api.ts": "35ce0766c50ee9a5b6ad9093c8d30ba7237c40a6050e0064970a13f46e96b253", + "src/client.ts": "a1fab8d65c33663b2f45af4f7c6ff487d13475d95b552497f0d5e44de4814cee", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", - "src/core/calls.ts": "8249d7157c961e7519341bd1d98ccb9c0951b5c5427aa3a2f6a5b38ac8022645", - "src/core/core.ts": "b40ae6c13aa2788e3648fadda0dd849ffbee184c64e8a9480ce2bc003f79a5c4", - "src/core/errors.ts": "b227f946d0a6ef82f9e8941db86b3935017b0a7a2fe90b239d3ba56702a059ee", - "src/core/index.ts": "4dd5b2242a5822ba8163d2b2386b7b77ec561b074ebe131b053e7a5f5dc3bc70", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", - "src/core/pagination.ts": "44b241a1f4c35a644a5d0b93f9044b1c4fee3b8e52893c1175411421d61916c1", - "src/core/platform.ts": "565f9b36d6c770a3b9f8401c735676d8b1333a64161b258a2945d9cfb45c0d04", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", - "src/core/retry.ts": "90739bf0a613264a45a587b937f4b2557010c1c19d963a73ca01bf9a493560e7", - "src/core/send.ts": "04040dfbf9490182489db3a739be2d8cda0cdf896f711e0df8bf551c88b17bc8", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", - "src/index.ts": "32131b761be3e05154ad6f0e5a711a20a5e841348e99566fe3ad34eafc998a1f", - "src/resources/checks.ts": "cca2c642c3862f14f742fa26886b046abbf8fc463c5a87a18a8cb97c3d56fd6d", - "src/resources/default.ts": "1fac72d8e682119d1a570e8c1998e47a268d92149894035529a2080cdafa275a", - "src/resources/outer.ts": "7141c120e57832302796b74e6027aa7d2253abd1dd02547a97c4c2c5cbe44d98", - "src/resources/outer/middle.ts": "4b10e7c6df637650523e7ea8ac61d7a391fed11f5d8f0af0e2a3079bdc683068", - "src/resources/outer/middle/inner.ts": "cc0727cf000b6b4c20f3180ff28ebe48ae629f36d4bfed33835d9d6781689244", - "tests/api-resources/checks.test.mjs": "bdf152ab778cf03807ad5c113b06a5659ac7bea78157b121c27010daa8e02f05", - "tests/api-resources/default.test.mjs": "8020dc836e5e07f861f36427a8709d680f90919dc73932d0d43548573a01208e", - "tests/api-resources/outer/middle/inner.test.mjs": "65e8a93ed3e32187a8e13fd58ae76545983066729a05b0d7037246df5bc00690", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "44758ef747b1a346e9b79fecbc189dcae97204754233ac4e9f85d52d9e354fbe", + "src/resources/checks.ts": "5900df18d03954fae15d0603d7c40c833d5f9497389044ee0df01a4f3465fcba", + "src/resources/default.ts": "b6eb61d9ed6b4aadb30e1155af468754d81e3e35cf19d38329e512c9c8ee92fa", + "src/resources/outer.ts": "874a37f4b611a4b8f4be41146112b546ade291c9b6d6ea12598158904eeeb522", + "src/resources/outer/middle.ts": "23c22dec7744684a2192c88d0e3aea640a138ed2233e5c0ffbd93a101fe3fe28", + "src/resources/outer/middle/inner.ts": "bf2496b1c5036c8d5ea71afad3ee2b0d463129662210247f638c05e179022234", + "tests/api-resources/checks.test.mjs": "fd97d7c21ef27787ced0513a8ccf635ec8f42827f5d5df5219835aebeb9935b7", + "tests/api-resources/default.test.mjs": "7fbacf277964023367e1a5a7fed8fd9026f9d393693551b65237541cff9c7281", + "tests/api-resources/outer/middle/inner.test.mjs": "3591c6f2e45b27e24311ebf072fa1f355bee65857950af1bfb645e35c10085cc", + "tests/auth.test.mjs": "d8c99fc7821a34bf02da01f33af399654d791ff9bd6d00205ae1a60be5df51e7", "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", diff --git a/crates/flowapi-sdk/tests/repo/auth/AGENTS.md b/crates/flowapi-sdk/tests/repo/auth/AGENTS.md index 46490a5..1ca1d14 100644 --- a/crates/flowapi-sdk/tests/repo/auth/AGENTS.md +++ b/crates/flowapi-sdk/tests/repo/auth/AGENTS.md @@ -4,15 +4,34 @@ This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + ## What is generated Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: ```sh -npx -y @localix-ai/flowapi@0.2.0 generate flowapi-sdk.yml --out . +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . ``` -`flowapi config check flowapi-sdk.yml` says what is wrong with the config, every issue at once. A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | ## What is yours @@ -35,4 +54,4 @@ The mock (`mock/routes.mjs`) answers each operation with an example of its schem ## Releases -release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released. Publishing is a person's step. +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/auth/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/auth/CHANGELOG.md index 825c32f..f588820 100644 --- a/crates/flowapi-sdk/tests/repo/auth/CHANGELOG.md +++ b/crates/flowapi-sdk/tests/repo/auth/CHANGELOG.md @@ -1 +1,3 @@ # Changelog + +Each release of `auth-sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/auth/README.md b/crates/flowapi-sdk/tests/repo/auth/README.md index 31f5d3d..89e3e36 100644 --- a/crates/flowapi-sdk/tests/repo/auth/README.md +++ b/crates/flowapi-sdk/tests/repo/auth/README.md @@ -1,10 +1,10 @@ -# auth-sdk +# Auth TypeScript SDK -The TypeScript client of the Auth API, generated by flowapi from its description. +TypeScript SDK for the Auth API. -It has 12 methods in 3 resources; [api.md](api.md) lists them. +The `AuthClient` client is generated by flowapi from the API's description: 12 methods in 3 resources, each listed in [api.md](api.md) with its parameters and what it returns. ## Install @@ -23,33 +23,76 @@ const result = await client.checks.queryKey() console.log(result) ``` -The package is ES modules and CommonJS both, with types for each, and has no dependency: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { AuthClient } = require('auth-sdk')`; `import AuthClient from 'auth-sdk'` gives it too. +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.checks.queryKey().withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { AuthClient } = require('auth-sdk')`; `import AuthClient from 'auth-sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.checks`](api.md#clientchecks) | 9 | +| [`client.default`](api.md#clientdefault) | 2 | +| [`client.outer.middle.inner`](api.md#clientoutermiddleinner) | 1 | ## Authentication -Each credential is an option of the client, else read from its environment variable: +| Scheme | Kind | Sent as | Option | Environment variables | +| --- | --- | --- | --- | --- | +| `QueryKey` | API key | the query parameter `api_key` | `queryKey`: the key | `AUTH_QUERY_KEY`: the key | +| `CookieKey` | API key | the cookie `session` | `cookieKey`: the key | — | +| `Basic` | HTTP basic | `Authorization: Basic ` | `basic`: `{ username, password }` (a user-id without `:`) | `AUTH_BASIC`: `username:password` | +| `Token` | HTTP bearer | `Authorization: Bearer ` | `token`: the token | `AUTH_TOKEN`: the token | +| `Oauth` | OAuth 2.0 client credentials | `Authorization: Bearer `, the token requested at `https://auth.example/token` for the scopes the operation needs | `oauth`: a token, or `{ clientId, clientSecret }` to request one | — | + +An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them. + +A token of OAuth 2.0's client credentials grant is requested at the token URL (relative to the base URL where it is relative) with the client's id and secret in HTTP basic, cached until a little before it expires, shared by the calls that wait for it, and requested again once when the API answers 401. A refusal of the token endpoint throws `TokenError` with its `error` and `description`. + +```ts +const client = new AuthClient({ queryKey: '…', cookieKey: '…', basic: { username: '…', password: '…' }, token: '…', oauth: { clientId: '…', clientSecret: '…' } }) +``` + +## Servers + +The servers' URLs have variables. The client sends each one's default unless `serverVariables` gives another value: -| Scheme | Sent as | Option | Variable | -| --- | --- | --- | --- | -| `QueryKey` | an API key in the query parameter `api_key` | `queryKey` | `AUTH_QUERY_KEY` | -| `CookieKey` | an API key in the cookie `session` | `cookieKey` | — | -| `Basic` | HTTP basic (`{ username, password }`) | `basic` | `AUTH_BASIC` | -| `Token` | HTTP `bearer` | `token` | `AUTH_TOKEN` | -| `Oauth` | an OAuth 2.0 token | `oauth` | — | +| Variable | Default | Values | +| --- | --- | --- | +| `version` | `v2` | any | ```ts -const client = new AuthClient({ queryKey: '…', cookieKey: '…', basic: { username: '…', password: '…' }, token: '…', oauth: '…' }) +const other = new AuthClient({ serverVariables: { version: 'v2' } }) ``` ## Errors -A status that is not a success throws an `APIError` with its `status`, `headers` and `body`, of the class for its status: `BadRequestError` (400), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RequestTimeoutError` (408), `ConflictError` (409), `UnprocessableEntityError` (422), `RateLimitError` (429), `InternalServerError` (500 and above). No answer throws `APIConnectionError`; a timeout `APIConnectionTimeoutError`; a call aborted by its signal `APIUserAbortError`. +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. ```ts import { APIError } from 'auth-sdk' try { - await client.checks.queryKey(/* … */) + await client.checks.queryKey() } catch (error) { if (error instanceof APIError) console.log(error.status, error.body) else throw error @@ -58,23 +101,44 @@ try { ## Retries and timeouts -A call that fails to connect, or is answered 408, 409, 429 or 5xx, is tried 0 more times by default, waiting longer each time (never more than 60 s when the server asks to wait); each attempt may take 60 s, its body read. Give `maxRetries` and `timeout` (milliseconds) to the client, or to one call: +No request is retried by default (`maxRetries: 0`): each is sent once. With `maxRetries` set, a request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. A retry that failed is tried again while `maxRetries` allows. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 60 s, the error is thrown at once. Each attempt may take 60 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: ```ts -const client = new AuthClient({ maxRetries: 0, timeout: 20_000 }) +const patient = new AuthClient({ maxRetries: 5, timeout: 120_000 }) +await client.checks.queryKey({}, { maxRetries: 0, timeout: 5_000 }) ``` ## Streaming -A streamed method gives its events as they come: +A streamed method gives its events as they come, read once; `abort()` stops the stream and closes its connection. + +```ts +const stream = await client.checks.lines() +for await (const event of stream) console.log(event) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `AUTH_CLIENT_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new AuthClient({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: ```ts -for await (const event of await client.checks.lines()) console.log(event) +const response = await client.request('GET', '/').asResponse() +console.log(response.status) ``` ## Requirements -Node 20 or later (CI runs 20, 22, 24), or any runtime with `fetch`. Built with TypeScript 7.0.2. +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. ## Development @@ -83,4 +147,4 @@ npm install scripts/check # lint, build, the built types, the tests against the mock server ``` -The code is generated from `flowapi-sdk.yml`: change that file and generate again ([AGENTS.md](AGENTS.md)). +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/auth/api.md b/crates/flowapi-sdk/tests/repo/auth/api.md index 76507d2..f0052ad 100644 --- a/crates/flowapi-sdk/tests/repo/auth/api.md +++ b/crates/flowapi-sdk/tests/repo/auth/api.md @@ -2,9 +2,13 @@ # API -12 methods in 3 resources of `AuthClient`. +Every method of `AuthClient`, by resource: 12 methods in 3 resources. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: -## checks +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from 'auth-sdk' +``` + +## client.checks - `client.checks.queryKey(params?: Input, options?: RequestOptions): ApiCall>` `GET /query` @@ -22,17 +26,17 @@ `GET /oauth` - `client.checks.elsewhere(params?: Input, options?: RequestOptions): ApiCall>` `GET /elsewhere` -- `client.checks.lines(params?: Input, options?: RequestOptions): ApiCall>` +- `client.checks.lines(params?: Input, options?: RequestOptions): ApiCall>` `GET /lines` -## default +## client.default - `client.default.delete(params: Input, options?: RequestOptions): ApiCall>` `DELETE /things/{id}` - `client.default.new(params: Input, options?: RequestOptions): ApiCall>` `PUT /things/{id}` -## outer.middle.inner +## client.outer.middle.inner - `client.outer.middle.inner.get(params?: Input, options?: RequestOptions): ApiCall>` `GET /deep` diff --git a/crates/flowapi-sdk/tests/repo/auth/issues.txt b/crates/flowapi-sdk/tests/repo/auth/issues.txt index e69de29..f57eee4 100644 --- a/crates/flowapi-sdk/tests/repo/auth/issues.txt +++ b/crates/flowapi-sdk/tests/repo/auth/issues.txt @@ -0,0 +1,4 @@ +warning[config.auth.env]: `CookieKey` names no environment variable: the client sends it only when given its option + at flowapi-sdk.yml:10:3 (/auth/CookieKey) +warning[config.auth.env]: `Oauth` names no environment variable: the client sends it only when given its option + at flowapi-sdk.yml:13:3 (/auth/Oauth) diff --git a/crates/flowapi-sdk/tests/repo/auth/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/auth/mock/routes.mjs index 817d475..b55f721 100644 --- a/crates/flowapi-sdk/tests/repo/auth/mock/routes.mjs +++ b/crates/flowapi-sdk/tests/repo/auth/mock/routes.mjs @@ -3,16 +3,19 @@ // The operations the client calls, as the mock server answers them (server.mjs). export default [ - { "route": "GET /query", "method": "GET", "path": "/query", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /cookie", "method": "GET", "path": "/cookie", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /basic", "method": "GET", "path": "/basic", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /either", "method": "GET", "path": "/either", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /both", "method": "GET", "path": "/both", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /open", "method": "GET", "path": "/open", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /oauth", "method": "GET", "path": "/oauth", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /elsewhere", "method": "GET", "path": "/elsewhere", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /lines", "method": "GET", "path": "/lines", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/x-ndjson", "example": {} }, - { "route": "DELETE /things/{id}", "method": "DELETE", "path": "/things/{id}", "query": [], "headers": [], "cookies": [], "body": null, "status": 204, "media": null, "example": null }, - { "route": "PUT /things/{id}", "method": "PUT", "path": "/things/{id}", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, - { "route": "GET /deep", "method": "GET", "path": "/deep", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /query", "method": "GET", "path": "/query", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "QueryKey", "kind": "apiKey", "in": "query", "name": "api_key" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /cookie", "method": "GET", "path": "/cookie", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "CookieKey", "kind": "apiKey", "in": "cookie", "name": "session" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /basic", "method": "GET", "path": "/basic", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Basic", "kind": "basic" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /either", "method": "GET", "path": "/either", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Token", "kind": "bearer" }], [{ "scheme": "Basic", "kind": "basic" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /both", "method": "GET", "path": "/both", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "QueryKey", "kind": "apiKey", "in": "query", "name": "api_key" }, { "scheme": "Token", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /open", "method": "GET", "path": "/open", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /oauth", "method": "GET", "path": "/oauth", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Oauth", "kind": "bearer", "flow": true }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /elsewhere", "method": "GET", "path": "/elsewhere", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /lines", "method": "GET", "path": "/lines", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/x-ndjson", "example": {} }, + { "route": "DELETE /things/{id}", "method": "DELETE", "path": "/things/{id}", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 204, "media": null, "example": null }, + { "route": "PUT /things/{id}", "method": "PUT", "path": "/things/{id}", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /deep", "method": "GET", "path": "/deep", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"ok": false} }, ] + +// The token endpoints of the client credentials flows, by path. +export const tokens = ["/token"] diff --git a/crates/flowapi-sdk/tests/repo/auth/mock/server.mjs b/crates/flowapi-sdk/tests/repo/auth/mock/server.mjs index 126454e..07c6fa6 100644 --- a/crates/flowapi-sdk/tests/repo/auth/mock/server.mjs +++ b/crates/flowapi-sdk/tests/repo/auth/mock/server.mjs @@ -2,17 +2,20 @@ // // The API's mock server, on node:http with no dependency, answering by the routes printed from // the description beside it (routes.mjs). It is strict where a client goes wrong: a path no -// operation has is a 404, a method the path has not a 405, a required query parameter, header, -// cookie or body that is missing a 400, a body of a media type the operation does not take a -// 415. Otherwise it answers with the operation's first success status and an example value of -// its schema (the schema's example, else its default, its first enum value, else one made from -// its type and format). Each request answered is recorded, with the route it matched. +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). // // `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL // names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. import { createServer } from 'node:http' import { pathToFileURL } from 'node:url' -import routes from './routes.mjs' +import routes, { tokens } from './routes.mjs' /** A route's path as a regular expression: each `{name}` is one segment. */ function pattern(path) { @@ -69,6 +72,67 @@ function hasQuery(url, name) { return false } +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + /** What is wrong with a request for its route, with the status that says so; null for nothing. */ function problem(route, url, req, body) { for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] @@ -123,6 +187,7 @@ function handle(req, res, requests) { req.on('end', () => { const body = Buffer.concat(chunks) const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) const matches = table.filter((r) => r.regex.test(url.pathname)) if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) const route = matches.find((r) => r.method === req.method) @@ -130,6 +195,12 @@ function handle(req, res, requests) { const methods = matches.map((r) => r.method).join(', ') return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } const wrong = problem(route, url, req, body) if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) diff --git a/crates/flowapi-sdk/tests/repo/auth/package.json b/crates/flowapi-sdk/tests/repo/auth/package.json index b7bfb2a..d095f34 100644 --- a/crates/flowapi-sdk/tests/repo/auth/package.json +++ b/crates/flowapi-sdk/tests/repo/auth/package.json @@ -1,7 +1,7 @@ { "name": "auth-sdk", "version": "0.1.0", - "description": "A TypeScript client of the Auth API", + "description": "TypeScript SDK for the Auth API.", "license": "Apache-2.0", "type": "module", "sideEffects": false, diff --git a/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/checks.test.mjs b/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/checks.test.mjs index f360f75..0b57fcd 100644 --- a/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/checks.test.mjs +++ b/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/checks.test.mjs @@ -12,7 +12,7 @@ let client before(async () => { server = await mock() - client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: 'test-credential', maxRetries: 0 }) + client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, maxRetries: 0 }) }) after(() => server.close()) diff --git a/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/default.test.mjs b/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/default.test.mjs index 6272a9b..76a26b4 100644 --- a/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/default.test.mjs +++ b/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/default.test.mjs @@ -12,7 +12,7 @@ let client before(async () => { server = await mock() - client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: 'test-credential', maxRetries: 0 }) + client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, maxRetries: 0 }) }) after(() => server.close()) diff --git a/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/outer/middle/inner.test.mjs b/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/outer/middle/inner.test.mjs index 36a49a0..975651e 100644 --- a/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/outer/middle/inner.test.mjs +++ b/crates/flowapi-sdk/tests/repo/auth/tests/api-resources/outer/middle/inner.test.mjs @@ -12,7 +12,7 @@ let client before(async () => { server = await mock() - client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: 'test-credential', maxRetries: 0 }) + client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, maxRetries: 0 }) }) after(() => server.close()) diff --git a/crates/flowapi-sdk/tests/repo/auth/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/auth/tests/auth.test.mjs new file mode 100644 index 0000000..083af27 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/auth/tests/auth.test.mjs @@ -0,0 +1,67 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { AuthClient } from "auth-sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new AuthClient({ baseURL: server.url, queryKey: 'test-credential', cookieKey: 'test-credential', basic: { username: 'user', password: 'pass' }, token: 'test-credential', oauth: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("QueryKey: sent by checks.query_key", async () => { + await client.checks.queryKey() + const r = last() + if (r === null) return + assert.equal(new URL(r.url, 'http://mock.invalid').searchParams.get("api_key"), 'test-credential') +}) + +test("CookieKey: sent by checks.cookie", async () => { + await client.checks.cookie() + const r = last() + if (r === null) return + assert.ok((r.headers.cookie ?? '').split('; ').includes("session=test-credential"), r.headers.cookie) +}) + +test("Basic: sent by checks.basic", async () => { + await client.checks.basic() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, `Basic ${Buffer.from('user:pass').toString('base64')}`) +}) + +test("Token: sent by checks.either", async () => { + await client.checks.either() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer test-credential') +}) + +test("Oauth: sent by checks.oauth", async () => { + await client.checks.oauth() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer mock-token') + assert.ok(server.requests.some((q) => q.route === 'token'), 'the token was requested of the mock') +}) + +test("no credential: checks.open needs none", async () => { + const none = new AuthClient({ baseURL: server.url, maxRetries: 0, queryKey: null, cookieKey: null, basic: null, token: null, oauth: null }) + await none.checks.open() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, undefined) + assert.equal(new URL(r.url, 'http://mock.invalid').searchParams.has("api_key"), false) + assert.ok(!(r.headers.cookie ?? '').split('; ').some((c) => c.startsWith("session="))) +}) diff --git a/crates/flowapi-sdk/tests/repo/edge/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/edge/.flowapi/lock.json new file mode 100644 index 0000000..d868bdc --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/.flowapi/lock.json @@ -0,0 +1,51 @@ +{ + "version": 1, + "flowapi": "0.3.0", + "spec_sha256": "a5ece88b1d94c286cd27baacd318e67414f3a28e5d5ed6ff5754fc3ff8512e09", + "config_sha256": "65906f1f03639d29a69e8bca3a2ac16ee0be467f35ae87cf83ed6866407aefa1", + "configured_endpoints": 2, + "files": { + ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", + ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", + "LICENSE": "30f472de515b8cb8117d19d1062d66e351ce6bbb9ebf886cbf65606fece4aee2", + "README.md": "713b75dcc34e8723d4c516c9c028b9cda39af3a28e0864adc4300728c62096e6", + "api.md": "4cbf0ec1bf5cf5d7492cee8a45538b02d773f9be774aa00b1309201483e6644e", + "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mock/routes.mjs": "32d2514b78dfba5cf7b39b3d07536eb64eae802725074f172ad6d8d66f3b3306", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "d7a893d523dd2a7bdae0e21ae70ee1dfa757246eb11f2ef5ed534491a21626e0", + "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", + "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", + "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", + "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", + "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", + "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", + "src/api.ts": "00b049cbda036c94ca6e288b367fc4c1e291348e1174a1b4377bbd49d9cc124e", + "src/client.ts": "47c3b85b1cea582c3f46e4b0590d6d7fcbcce90c258a6369f71abde7c743ac42", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", + "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", + "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", + "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", + "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "0d1d4325368ab59cec25b69f6dae6c5ae6593f085d46a2cca3493a3c9286ca3f", + "src/resources/zones.ts": "9f706e0748075a9dc18b0182b982fdeff5b6262155baf6bd77c7a3a8102dc4f8", + "tests/api-resources/zones.test.mjs": "49e4a0090a21b5734465113494be148a75e325a70a4df4bfcc13453b3cb25c39", + "tests/auth.test.mjs": "7154ad6b5324bff4782ee3cb7527a04944a01e7a4517f4a279b2687d0ead9e34", + "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", + "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", + "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", + "tsconfig.json": "8f8513b3a8e2fc81d06a2f3b0057d1e2881ca78722bd4b704766f0ad27ab7498" + }, + "names": {} +} diff --git a/crates/flowapi-sdk/tests/repo/edge/.github/workflows/ci.yml b/crates/flowapi-sdk/tests/repo/edge/.github/workflows/ci.yml new file mode 100644 index 0000000..e31da6b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: npm install --no-audit --no-fund + - run: scripts/check diff --git a/crates/flowapi-sdk/tests/repo/edge/.gitignore b/crates/flowapi-sdk/tests/repo/edge/.gitignore new file mode 100644 index 0000000..6c15117 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/.gitignore @@ -0,0 +1,4 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +node_modules/ +dist/ +*.tgz diff --git a/crates/flowapi-sdk/tests/repo/edge/.release-please-manifest.json b/crates/flowapi-sdk/tests/repo/edge/.release-please-manifest.json new file mode 100644 index 0000000..466df71 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} diff --git a/crates/flowapi-sdk/tests/repo/edge/AGENTS.md b/crates/flowapi-sdk/tests/repo/edge/AGENTS.md new file mode 100644 index 0000000..1ca1d14 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/AGENTS.md @@ -0,0 +1,57 @@ + + +# AGENTS.md + +This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. + +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + +## What is generated + +Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: + +```sh +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . +``` + +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | + +## What is yours + +- `src/lib/` and `examples/`: generate writes a file there only while it is unchanged, and never overwrites one you changed. +- `CHANGELOG.md` and `.release-please-manifest.json`: written on the first generation, then the release tool's. +- Every file the lock does not list: generate never touches it. + +## Commands + +```sh +npm install # TypeScript, the one development dependency +scripts/check # everything: lint, build, the built types, the tests +scripts/build # dist/esm and dist/cjs, then both loaded by the package's name +scripts/lint # the types, no node: module in the client, the tests parsed +scripts/test # node --test over tests/, against the mock server each file starts +scripts/mock # the mock server on port 4010, for trying the client by hand +``` + +The mock (`mock/routes.mjs`) answers each operation with an example of its schema and refuses a request its operation would refuse: a wrong path or method, a missing parameter, a body of another media type. Set `TEST_API_BASE_URL` to run the tests against another server. + +## Releases + +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/edge/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/edge/CHANGELOG.md new file mode 100644 index 0000000..782560f --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +Each release of `edge-sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/edge/LICENSE b/crates/flowapi-sdk/tests/repo/edge/LICENSE new file mode 100644 index 0000000..6a039ff --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) The edge-sdk authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/flowapi-sdk/tests/repo/edge/README.md b/crates/flowapi-sdk/tests/repo/edge/README.md new file mode 100644 index 0000000..06c70ca --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/README.md @@ -0,0 +1,130 @@ + + +# Edge TypeScript SDK + +TypeScript SDK for the Edge API. + +The `Edge` client is generated by flowapi from the API's description: 2 methods in 1 resource, each listed in [api.md](api.md) with its parameters and what it returns. + +## Install + +```sh +npm install edge-sdk +``` + +## Usage + +```ts +import { Edge } from 'edge-sdk' + +const client = new Edge() + +const result = await client.zones.status() +console.log(result) +``` + +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.zones.status().withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { Edge } = require('edge-sdk')`; `import Edge from 'edge-sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.zones`](api.md#clientzones) | 2 | + +## Servers + +The servers' URLs have variables. The client sends each one's default unless `serverVariables` gives another value: + +| Variable | Default | Values | +| --- | --- | --- | +| `zone` | `a` | `a`, `b` | +| `version` | `v3` | any | + +```ts +const other = new Edge({ serverVariables: { zone: 'b' } }) +``` + +A value that is not one of a variable's values throws a `RangeError`. + +A server URL may be relative to where the description is served (`../api`): give that address as `descriptionURL` to call it. + +```ts +const near = new Edge({ descriptionURL: 'https://api.example.com/openapi.json' }) +``` + +## Errors + +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. + +```ts +import { APIError } from 'edge-sdk' + +try { + await client.zones.status() +} catch (error) { + if (error instanceof APIError) console.log(error.status, error.body) + else throw error +} +``` + +## Retries and timeouts + +A request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried once by default when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. A retry that failed is not tried again: more retries are the caller's choice. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 60 s, the error is thrown at once. Each attempt may take 60 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: + +```ts +const patient = new Edge({ maxRetries: 5, timeout: 120_000 }) +await client.zones.status({}, { maxRetries: 0, timeout: 5_000 }) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `EDGE_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new Edge({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: + +```ts +const response = await client.request('GET', '/').asResponse() +console.log(response.status) +``` + +## Requirements + +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. + +## Development + +```sh +npm install +scripts/check # lint, build, the built types, the tests against the mock server +``` + +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/edge/api.md b/crates/flowapi-sdk/tests/repo/edge/api.md new file mode 100644 index 0000000..fe76558 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/api.md @@ -0,0 +1,16 @@ + + +# API + +Every method of `Edge`, by resource: 2 methods in 1 resource. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: + +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from 'edge-sdk' +``` + +## client.zones + +- `client.zones.status(params?: Input, options?: RequestOptions): ApiCall>` + `GET /status`: Whether the edge is up +- `client.zones.near(params?: Input, options?: RequestOptions): ApiCall>` + `GET /near`: The nearest edge, beside the description diff --git a/crates/flowapi-sdk/tests/repo/edge/examples/.keep b/crates/flowapi-sdk/tests/repo/edge/examples/.keep new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/edge/issues.txt b/crates/flowapi-sdk/tests/repo/edge/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/edge/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/edge/mock/routes.mjs new file mode 100644 index 0000000..1a04d26 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/mock/routes.mjs @@ -0,0 +1,11 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The operations the client calls, as the mock server answers them (server.mjs). + +export default [ + { "route": "GET /status", "method": "GET", "path": "/status", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"up": false} }, + { "route": "GET /near", "method": "GET", "path": "/near", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"up": false} }, +] + +// The token endpoints of the client credentials flows, by path. +export const tokens = [] diff --git a/crates/flowapi-sdk/tests/repo/edge/mock/server.mjs b/crates/flowapi-sdk/tests/repo/edge/mock/server.mjs new file mode 100644 index 0000000..07c6fa6 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/mock/server.mjs @@ -0,0 +1,237 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The API's mock server, on node:http with no dependency, answering by the routes printed from +// the description beside it (routes.mjs). It is strict where a client goes wrong: a path no +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). +// +// `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL +// names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. +import { createServer } from 'node:http' +import { pathToFileURL } from 'node:url' +import routes, { tokens } from './routes.mjs' + +/** A route's path as a regular expression: each `{name}` is one segment. */ +function pattern(path) { + const parts = path + .split(/(\{[^}/]+\})/) + .map((p) => (/^\{[^}/]+\}$/.test(p) ? '([^/]+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))) + return new RegExp(`^${parts.join('')}$`) +} + +/** Each segment of a path by how specific it is: 2 literal, 1 a template beside text, 0 a template. */ +const ranks = (path) => path.split('/').map((s) => (!s.includes('{') ? 2 : /^\{[^}/]+\}$/.test(s) ? 0 : 1)) + +/** + * The more specific route first (OpenAPI's Paths Object matches a concrete path before a templated + * one): at the first segment where the two differ in kind, the more literal one; then the shorter + * path, which never matches the same URL. Routes as specific as each other are ambiguous by the + * specification and keep the order of routes.mjs (the client's resources and methods). + */ +function specific(a, b) { + const x = ranks(a.path) + const y = ranks(b.path) + const i = x.findIndex((r, n) => r !== y[n]) + if (i === -1 || i >= y.length) return x.length - y.length + return y[i] - x[i] +} + +// Sorted once, stably: a request takes the first route that matches its path and method. +const table = routes.map((r) => ({ ...r, regex: pattern(r.path) })).sort(specific) + +/** A media type without its parameters, in lower case. */ +const bare = (type) => (type ?? '').split(';')[0].trim().toLowerCase() + +// Whether a media range (`image/png`, `image/*`, `*/*`) takes a media type. +function takes(range, type) { + const r = bare(range) + if (r === '*/*') return true + if (r.endsWith('/*')) return type.startsWith(r.slice(0, -1)) + return r === type +} + +/** The names of a Cookie header's cookies. */ +function cookieNames(header) { + const names = new Set() + for (const part of (header ?? '').split(';')) { + const name = part.split('=')[0].trim() + if (name !== '') names.add(name) + } + return names +} + +/** Whether the query has a parameter: by its name, or as `name[...]` for an object's members. */ +function hasQuery(url, name) { + for (const key of url.searchParams.keys()) if (key === name || key.startsWith(`${name}[`)) return true + return false +} + +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + +/** What is wrong with a request for its route, with the status that says so; null for nothing. */ +function problem(route, url, req, body) { + for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] + for (const name of route.headers) if (req.headers[name] === undefined) return [400, `the header ${name} is required`] + const jar = cookieNames(req.headers.cookie) + for (const name of route.cookies) if (!jar.has(name)) return [400, `the cookie ${name} is required`] + if (body.length === 0) return route.body?.required ? [400, 'the operation requires a body'] : null + if (route.body === null) return [400, 'the operation takes no body'] + const type = bare(req.headers['content-type']) + if (!route.body.media.some((m) => takes(m, type))) { + return [415, `the body's media type ${type || '(none)'} is not one of ${route.body.media.join(', ')}`] + } + if (type === 'application/json' || type.endsWith('+json')) { + try { + JSON.parse(body.toString('utf8')) + } catch { + return [400, 'the body is not JSON'] + } + } + return null +} + +function fail(res, status, message) { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: message })) +} + +/** The route's answer: its status, and its example in its media type. */ +function answer(res, route) { + if (route.media === null || [204, 205, 304].includes(route.status)) { + res.writeHead(route.status) + res.end() + return + } + const media = route.media.includes('*') ? 'application/octet-stream' : route.media + const type = bare(media) + const json = JSON.stringify(route.example) + const text = typeof route.example === 'string' ? route.example : json + let body + if (type === 'text/event-stream') body = `data: ${text}\n\n` + else if (type === 'application/x-ndjson' || type === 'application/jsonl') body = `${json}\n` + else if (type === 'application/json' || type.endsWith('+json')) body = json + else if (type.startsWith('text/') || type.endsWith('+xml') || type === 'application/xml') body = text + else body = Buffer.from([1, 2, 3]) + res.writeHead(route.status, { 'content-type': media }) + res.end(body) +} + +function handle(req, res, requests) { + const chunks = [] + req.on('data', (c) => chunks.push(c)) + req.on('end', () => { + const body = Buffer.concat(chunks) + const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) + const matches = table.filter((r) => r.regex.test(url.pathname)) + if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) + const route = matches.find((r) => r.method === req.method) + if (route === undefined) { + const methods = matches.map((r) => r.method).join(', ') + return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) + } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } + const wrong = problem(route, url, req, body) + if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) + requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) + answer(res, route) + }) +} + +/** + * Starts the mock server on `port` (0, the default, for a free one) of 127.0.0.1. Resolves to its + * `url`, the `requests` it answered and `close()`. When TEST_API_BASE_URL is set it starts nothing: + * `url` is that address and `requests` is null. + */ +export async function mock({ port = 0 } = {}) { + const external = process.env.TEST_API_BASE_URL + if (external) return { url: external.replace(/\/+$/, ''), requests: null, close: async () => {} } + const requests = [] + const server = createServer((req, res) => handle(req, res, requests)) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, '127.0.0.1', resolve) + }) + const close = () => + new Promise((resolve) => { + server.close(() => resolve()) + server.closeAllConnections() + }) + return { url: `http://127.0.0.1:${server.address().port}`, requests, close } +} + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + const port = Number(process.argv[2] ?? 4010) + const { url } = await mock({ port }) + console.log(`the mock server answers at ${url}`) +} diff --git a/crates/flowapi-sdk/tests/repo/edge/package.json b/crates/flowapi-sdk/tests/repo/edge/package.json new file mode 100644 index 0000000..6cedd86 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/package.json @@ -0,0 +1,26 @@ +{ + "name": "edge-sdk", + "version": "0.1.0", + "description": "TypeScript SDK for the Edge API.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "engines": { "node": ">=20" }, + "main": "./dist/cjs/index.js", + "types": "./dist/cjs/index.d.ts", + "exports": { + ".": { + "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, + "require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" } + }, + "./package.json": "./package.json" + }, + "files": ["dist"], + "scripts": { + "build": "scripts/build", + "lint": "scripts/lint", + "test": "scripts/test", + "check": "scripts/check" + }, + "devDependencies": { "typescript": "7.0.2" } +} diff --git a/crates/flowapi-sdk/tests/repo/edge/release-please-config.json b/crates/flowapi-sdk/tests/repo/edge/release-please-config.json new file mode 100644 index 0000000..897e118 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/release-please-config.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "node", + "include-v-in-tag": true, + "bump-minor-pre-major": true, + "changelog-path": "CHANGELOG.md", + "extra-files": [{ "type": "yaml", "path": "flowapi-sdk.yml", "jsonpath": "$.package.version" }] + } + } +} diff --git a/crates/flowapi-sdk/tests/repo/edge/scripts/build b/crates/flowapi-sdk/tests/repo/edge/scripts/build new file mode 100644 index 0000000..6dd941a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/scripts/build @@ -0,0 +1,21 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The package built twice from src/ by tsc alone: ES modules into dist/esm, CommonJS into +# dist/cjs, each with its declarations; then loaded by its own name with require and import, as +# a user loads it. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/build: $tsc is missing: run npm install first" >&2 + exit 1 +fi +rm -rf dist +"$tsc" -p tsconfig.build.json +"$tsc" -p tsconfig.cjs.json +printf '{ "type": "commonjs" }\n' > dist/cjs/package.json +name=$(node -p 'require("./package.json").name') +# CommonJS: the module, its client class both `default` and by its name, as the README takes it. +node -e 'const m = require(process.argv[1]); if (typeof m.default !== "function" || m[m.default.name] !== m.default) throw new Error("require(" + process.argv[1] + ") gives no client class by its name")' "$name" +node --input-type=module -e 'const m = await import(process.argv[1]); if (typeof m.default !== "function") throw new Error("import(" + process.argv[1] + ") gives no client class")' "$name" diff --git a/crates/flowapi-sdk/tests/repo/edge/scripts/check b/crates/flowapi-sdk/tests/repo/edge/scripts/check new file mode 100644 index 0000000..e0be85d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/scripts/check @@ -0,0 +1,11 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Everything a change must pass: lint, the build, the built declarations type-checked on their +# own (skipLibCheck off), the tests. +set -eu +cd "$(dirname "$0")/.." +scripts/lint +scripts/build +node_modules/.bin/tsc -p tsconfig.dist.json +SDK_BUILT=1 scripts/test diff --git a/crates/flowapi-sdk/tests/repo/edge/scripts/lint b/crates/flowapi-sdk/tests/repo/edge/scripts/lint new file mode 100644 index 0000000..7126bd5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/scripts/lint @@ -0,0 +1,22 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The sources type-checked; no node: module in the generated client, which runs wherever fetch +# does; the mock server and the tests parsed. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/lint: $tsc is missing: run npm install first" >&2 + exit 1 +fi +"$tsc" -p tsconfig.json +found=$(find src -name '*.ts' ! -path 'src/lib/*' -exec grep -l -e 'from "node:' -e "from 'node:" {} + || true) +if [ -n "$found" ]; then + echo "scripts/lint: a node: module is imported by the client, which must run without Node:" >&2 + echo "$found" >&2 + exit 1 +fi +for f in mock/*.mjs $(find tests -name '*.mjs' | sort); do + node --check "$f" +done diff --git a/crates/flowapi-sdk/tests/repo/edge/scripts/mock b/crates/flowapi-sdk/tests/repo/edge/scripts/mock new file mode 100644 index 0000000..c7fad1c --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/scripts/mock @@ -0,0 +1,7 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The mock server on a port (4010 unless given), until stopped: for trying the client by hand. +set -eu +cd "$(dirname "$0")/.." +exec node mock/server.mjs "${1:-4010}" diff --git a/crates/flowapi-sdk/tests/repo/edge/scripts/test b/crates/flowapi-sdk/tests/repo/edge/scripts/test new file mode 100644 index 0000000..d78cf2a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/scripts/test @@ -0,0 +1,19 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Every test of tests/ by node --test, against the mock server each test file starts on a free +# port (or against TEST_API_BASE_URL when it is set). The package is built first, unless +# SDK_BUILT=1 says it was just built. +set -eu +cd "$(dirname "$0")/.." +if [ "${SDK_BUILT:-}" != 1 ]; then + scripts/build +fi +files=$(find tests -name '*.test.mjs' | sort) +if [ -z "$files" ]; then + echo "scripts/test: no tests under tests/" >&2 + exit 1 +fi +# The files one by one as arguments: every Node from 20 reads them so, globs or not. +# shellcheck disable=SC2086 +node --test $files diff --git a/crates/flowapi-sdk/tests/repo/edge/tests/api-resources/zones.test.mjs b/crates/flowapi-sdk/tests/repo/edge/tests/api-resources/zones.test.mjs new file mode 100644 index 0000000..87686e9 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/tests/api-resources/zones.test.mjs @@ -0,0 +1,28 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `zones` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Edge } from "edge-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Edge({ baseURL: server.url, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("zones.status: GET /status", async () => { + await client.zones.status() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /status") +}) + +test("zones.near: GET /near", async () => { + await client.zones.near() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /near") +}) diff --git a/crates/flowapi-sdk/tests/repo/edge/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/edge/tests/auth.test.mjs new file mode 100644 index 0000000..d22d3b0 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/tests/auth.test.mjs @@ -0,0 +1,29 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Edge } from "edge-sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Edge({ baseURL: server.url, maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("no credential: zones.status needs none", async () => { + const none = new Edge({ baseURL: server.url, maxRetries: 0 }) + await none.zones.status() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, undefined) +}) diff --git a/crates/flowapi-sdk/tests/repo/edge/tsconfig.build.json b/crates/flowapi-sdk/tests/repo/edge/tsconfig.build.json new file mode 100644 index 0000000..6034cd3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "rootDir": "src", + "outDir": "dist/esm" + } +} diff --git a/crates/flowapi-sdk/tests/repo/edge/tsconfig.cjs.json b/crates/flowapi-sdk/tests/repo/edge/tsconfig.cjs.json new file mode 100644 index 0000000..cae8db8 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.build.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs" + } +} diff --git a/crates/flowapi-sdk/tests/repo/edge/tsconfig.dist.json b/crates/flowapi-sdk/tests/repo/edge/tsconfig.dist.json new file mode 100644 index 0000000..f52d18a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/tsconfig.dist.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "skipLibCheck": false, + "noEmit": true + }, + "include": ["dist/**/*.d.ts"] +} diff --git a/crates/flowapi-sdk/tests/repo/edge/tsconfig.json b/crates/flowapi-sdk/tests/repo/edge/tsconfig.json new file mode 100644 index 0000000..9ee3b9b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/edge/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "rootDir": "src", + "noEmit": true + }, + "include": ["src"] +} diff --git a/crates/flowapi-sdk/tests/repo/github/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/github/.flowapi/lock.json new file mode 100644 index 0000000..c4f31be --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/.flowapi/lock.json @@ -0,0 +1,59 @@ +{ + "version": 1, + "flowapi": "0.3.0", + "spec_sha256": "7b17bc22fd2d95bc7bdc3bdef3222b1aeaf9e1f7bef67160a0007d6019b18ae0", + "config_sha256": "1921be2e29f0a67a36bff603e22e036c9c1476da8f554a2806d013b050c0b6bb", + "configured_endpoints": 5, + "files": { + ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", + ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", + "LICENSE": "f8af98c4f94e046a9d786f425dc6a305787c570e7b0a3b0d17bff33ca32d0872", + "README.md": "c6e27de7aee83880f1b20583bfaaf8d5dc7699dfd3fa66b0e39e8800b430925e", + "api.md": "99cbafdbd16d0b3b5f8ef624ec025bb00bb8516ce004e8922275a8089e621945", + "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mock/routes.mjs": "53bb58641b6d1412279e80a69d6e88d1a7fd877c8777b32426102ef7a5cbb505", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "3ab339b653e0af4cba954f80bcb9ebfaf8bef0e6d247e5d5ebc8ed1854325517", + "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", + "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", + "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", + "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", + "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", + "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", + "src/api.ts": "1e29d80713fba2835b0f1c0047b8b2a63773a9a09782781955319c26048cabc2", + "src/client.ts": "ff25ebcc6e132cd20ee4813f744d39f6598c91d3b6e9f131bc85baba6dfa6860", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", + "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", + "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", + "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", + "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "5ceb3853f55c4773d0b4ea6c1c231211b829fd44a2b845e1054212edec8cf1ae", + "src/resources/apps.ts": "f79a4cae1be2ffbd58bfdfd8fb14586e6f38365e1a50b478429ee90e24c54df2", + "src/resources/enterprise.ts": "cd976d17925e7fa2c424e6a23d5207f198f445be0e1a3fb68d245d17ef7597ce", + "src/resources/meta.ts": "761361e26128eb45e440b9584e11a719a5c0b52f96a876809c72efa05cf90113", + "src/resources/repos.ts": "52f46ac74667fbb67f17de0e9d07f6363ea36cd443556d4fee9af1a95479eaac", + "src/resources/users.ts": "001d27a87b9f0055c3d170a851454e1404bb4ca4d201bdf03b8746f131695dd5", + "tests/api-resources/apps.test.mjs": "cadd3305fae25915ad541339030887b3a42731641faf756ac361c89fcd5166fc", + "tests/api-resources/enterprise.test.mjs": "7bc634f0a85b11393a90dee358f4c35417955ae062d8708ce9c4cad5238c0c37", + "tests/api-resources/meta.test.mjs": "3abd1d0179522166a90034e45211cfff157b236d0d6086f5af90a3bb921a4665", + "tests/api-resources/repos.test.mjs": "19013f2caba78ad7f928444e3adddcec980b65d51bb6d89aaafea69845a79c56", + "tests/api-resources/users.test.mjs": "b2a5caf16f3aa2efe33474ced0c7bb5c7c9a02eaf55eca9f7c78a2d028782848", + "tests/auth.test.mjs": "f8c40f6f71f562ae5cd9fe39e35c978bdfff28e8dc29601a8728cd2715224e68", + "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", + "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", + "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", + "tsconfig.json": "8f8513b3a8e2fc81d06a2f3b0057d1e2881ca78722bd4b704766f0ad27ab7498" + }, + "names": {} +} diff --git a/crates/flowapi-sdk/tests/repo/github/.github/workflows/ci.yml b/crates/flowapi-sdk/tests/repo/github/.github/workflows/ci.yml new file mode 100644 index 0000000..e31da6b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: npm install --no-audit --no-fund + - run: scripts/check diff --git a/crates/flowapi-sdk/tests/repo/github/.gitignore b/crates/flowapi-sdk/tests/repo/github/.gitignore new file mode 100644 index 0000000..6c15117 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/.gitignore @@ -0,0 +1,4 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +node_modules/ +dist/ +*.tgz diff --git a/crates/flowapi-sdk/tests/repo/github/.release-please-manifest.json b/crates/flowapi-sdk/tests/repo/github/.release-please-manifest.json new file mode 100644 index 0000000..466df71 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} diff --git a/crates/flowapi-sdk/tests/repo/github/AGENTS.md b/crates/flowapi-sdk/tests/repo/github/AGENTS.md new file mode 100644 index 0000000..1ca1d14 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/AGENTS.md @@ -0,0 +1,57 @@ + + +# AGENTS.md + +This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. + +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + +## What is generated + +Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: + +```sh +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . +``` + +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | + +## What is yours + +- `src/lib/` and `examples/`: generate writes a file there only while it is unchanged, and never overwrites one you changed. +- `CHANGELOG.md` and `.release-please-manifest.json`: written on the first generation, then the release tool's. +- Every file the lock does not list: generate never touches it. + +## Commands + +```sh +npm install # TypeScript, the one development dependency +scripts/check # everything: lint, build, the built types, the tests +scripts/build # dist/esm and dist/cjs, then both loaded by the package's name +scripts/lint # the types, no node: module in the client, the tests parsed +scripts/test # node --test over tests/, against the mock server each file starts +scripts/mock # the mock server on port 4010, for trying the client by hand +``` + +The mock (`mock/routes.mjs`) answers each operation with an example of its schema and refuses a request its operation would refuse: a wrong path or method, a missing parameter, a body of another media type. Set `TEST_API_BASE_URL` to run the tests against another server. + +## Releases + +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/github/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/github/CHANGELOG.md new file mode 100644 index 0000000..4327a3e --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +Each release of `github-like-sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/github/LICENSE b/crates/flowapi-sdk/tests/repo/github/LICENSE new file mode 100644 index 0000000..51caf63 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) The github-like-sdk authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/flowapi-sdk/tests/repo/github/README.md b/crates/flowapi-sdk/tests/repo/github/README.md new file mode 100644 index 0000000..3ab5c67 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/README.md @@ -0,0 +1,127 @@ + + +# GitHub-like TypeScript SDK + +TypeScript SDK for the GitHub-like API. + +The `GitHub` client is generated by flowapi from the API's description: 5 methods in 5 resources, each listed in [api.md](api.md) with its parameters and what it returns. + +## Install + +```sh +npm install github-like-sdk +``` + +## Usage + +```ts +import { GitHub } from 'github-like-sdk' + +const client = new GitHub() + +const result = await client.users.me() +console.log(result) +``` + +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.users.me().withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { GitHub } = require('github-like-sdk')`; `import GitHub from 'github-like-sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.apps`](api.md#clientapps) | 1 | +| [`client.enterprise`](api.md#cliententerprise) | 1 | +| [`client.meta`](api.md#clientmeta) | 1 | +| [`client.repos`](api.md#clientrepos) | 1 | +| [`client.users`](api.md#clientusers) | 1 | + +## Authentication + +| Scheme | Kind | Sent as | Option | Environment variables | +| --- | --- | --- | --- | --- | +| `Token` | HTTP bearer | `Authorization: Bearer ` | `token`: the token | `GITHUB_TOKEN`: the token | +| `AppKey` | API key | the header `X-App-Key` | `appKey`: the key | `GITHUB_APP_KEY`: the key | +| `Admin` | HTTP basic | `Authorization: Basic ` | `admin`: `{ username, password }` (a user-id without `:`) | `GITHUB_ADMIN_USER`: the user-id; `GITHUB_ADMIN_PASSWORD`: the password | + +An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them. + +```ts +const client = new GitHub({ token: '…', appKey: '…', admin: { username: '…', password: '…' } }) +``` + +## Errors + +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. + +```ts +import { APIError } from 'github-like-sdk' + +try { + await client.users.me() +} catch (error) { + if (error instanceof APIError) console.log(error.status, error.body) + else throw error +} +``` + +## Retries and timeouts + +No request is retried by default (`maxRetries: 0`): each is sent once. With `maxRetries` set, a request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. A retry that failed is tried again while `maxRetries` allows. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 60 s, the error is thrown at once. Each attempt may take 60 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: + +```ts +const patient = new GitHub({ maxRetries: 5, timeout: 120_000 }) +await client.users.me({}, { maxRetries: 0, timeout: 5_000 }) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `GIT_HUB_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new GitHub({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: + +```ts +const response = await client.request('GET', '/').asResponse() +console.log(response.status) +``` + +## Requirements + +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. + +## Development + +```sh +npm install +scripts/check # lint, build, the built types, the tests against the mock server +``` + +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/github/api.md b/crates/flowapi-sdk/tests/repo/github/api.md new file mode 100644 index 0000000..eec1173 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/api.md @@ -0,0 +1,34 @@ + + +# API + +Every method of `GitHub`, by resource: 5 methods in 5 resources. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: + +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from 'github-like-sdk' +``` + +## client.apps + +- `client.apps.hook(params?: Input, options?: RequestOptions): ApiCall>` + `GET /app/hook` + +## client.enterprise + +- `client.enterprise.settings(params?: Input, options?: RequestOptions): ApiCall>` + `GET /enterprise/settings` + +## client.meta + +- `client.meta.get(params?: Input, options?: RequestOptions): ApiCall>` + `GET /meta` + +## client.repos + +- `client.repos.get(params: Input, options?: RequestOptions): ApiCall>` + `GET /repos/{owner}/{repo}` + +## client.users + +- `client.users.me(params?: Input, options?: RequestOptions): ApiCall>` + `GET /user` diff --git a/crates/flowapi-sdk/tests/repo/github/examples/.keep b/crates/flowapi-sdk/tests/repo/github/examples/.keep new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/github/issues.txt b/crates/flowapi-sdk/tests/repo/github/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/github/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/github/mock/routes.mjs new file mode 100644 index 0000000..584cd74 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/mock/routes.mjs @@ -0,0 +1,14 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The operations the client calls, as the mock server answers them (server.mjs). + +export default [ + { "route": "GET /user", "method": "GET", "path": "/user", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Token", "kind": "bearer" }], []], "status": 200, "media": "application/json", "example": {"login": "string"} }, + { "route": "GET /repos/{owner}/{repo}", "method": "GET", "path": "/repos/{owner}/{repo}", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Token", "kind": "bearer" }], []], "status": 200, "media": "application/json", "example": {"login": "string"} }, + { "route": "GET /meta", "method": "GET", "path": "/meta", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {"login": "string"} }, + { "route": "GET /app/hook", "method": "GET", "path": "/app/hook", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "AppKey", "kind": "apiKey", "in": "header", "name": "x-app-key" }]], "status": 200, "media": "application/json", "example": {"login": "string"} }, + { "route": "GET /enterprise/settings", "method": "GET", "path": "/enterprise/settings", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Admin", "kind": "basic" }]], "status": 200, "media": "application/json", "example": {"login": "string"} }, +] + +// The token endpoints of the client credentials flows, by path. +export const tokens = [] diff --git a/crates/flowapi-sdk/tests/repo/github/mock/server.mjs b/crates/flowapi-sdk/tests/repo/github/mock/server.mjs new file mode 100644 index 0000000..07c6fa6 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/mock/server.mjs @@ -0,0 +1,237 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The API's mock server, on node:http with no dependency, answering by the routes printed from +// the description beside it (routes.mjs). It is strict where a client goes wrong: a path no +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). +// +// `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL +// names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. +import { createServer } from 'node:http' +import { pathToFileURL } from 'node:url' +import routes, { tokens } from './routes.mjs' + +/** A route's path as a regular expression: each `{name}` is one segment. */ +function pattern(path) { + const parts = path + .split(/(\{[^}/]+\})/) + .map((p) => (/^\{[^}/]+\}$/.test(p) ? '([^/]+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))) + return new RegExp(`^${parts.join('')}$`) +} + +/** Each segment of a path by how specific it is: 2 literal, 1 a template beside text, 0 a template. */ +const ranks = (path) => path.split('/').map((s) => (!s.includes('{') ? 2 : /^\{[^}/]+\}$/.test(s) ? 0 : 1)) + +/** + * The more specific route first (OpenAPI's Paths Object matches a concrete path before a templated + * one): at the first segment where the two differ in kind, the more literal one; then the shorter + * path, which never matches the same URL. Routes as specific as each other are ambiguous by the + * specification and keep the order of routes.mjs (the client's resources and methods). + */ +function specific(a, b) { + const x = ranks(a.path) + const y = ranks(b.path) + const i = x.findIndex((r, n) => r !== y[n]) + if (i === -1 || i >= y.length) return x.length - y.length + return y[i] - x[i] +} + +// Sorted once, stably: a request takes the first route that matches its path and method. +const table = routes.map((r) => ({ ...r, regex: pattern(r.path) })).sort(specific) + +/** A media type without its parameters, in lower case. */ +const bare = (type) => (type ?? '').split(';')[0].trim().toLowerCase() + +// Whether a media range (`image/png`, `image/*`, `*/*`) takes a media type. +function takes(range, type) { + const r = bare(range) + if (r === '*/*') return true + if (r.endsWith('/*')) return type.startsWith(r.slice(0, -1)) + return r === type +} + +/** The names of a Cookie header's cookies. */ +function cookieNames(header) { + const names = new Set() + for (const part of (header ?? '').split(';')) { + const name = part.split('=')[0].trim() + if (name !== '') names.add(name) + } + return names +} + +/** Whether the query has a parameter: by its name, or as `name[...]` for an object's members. */ +function hasQuery(url, name) { + for (const key of url.searchParams.keys()) if (key === name || key.startsWith(`${name}[`)) return true + return false +} + +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + +/** What is wrong with a request for its route, with the status that says so; null for nothing. */ +function problem(route, url, req, body) { + for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] + for (const name of route.headers) if (req.headers[name] === undefined) return [400, `the header ${name} is required`] + const jar = cookieNames(req.headers.cookie) + for (const name of route.cookies) if (!jar.has(name)) return [400, `the cookie ${name} is required`] + if (body.length === 0) return route.body?.required ? [400, 'the operation requires a body'] : null + if (route.body === null) return [400, 'the operation takes no body'] + const type = bare(req.headers['content-type']) + if (!route.body.media.some((m) => takes(m, type))) { + return [415, `the body's media type ${type || '(none)'} is not one of ${route.body.media.join(', ')}`] + } + if (type === 'application/json' || type.endsWith('+json')) { + try { + JSON.parse(body.toString('utf8')) + } catch { + return [400, 'the body is not JSON'] + } + } + return null +} + +function fail(res, status, message) { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: message })) +} + +/** The route's answer: its status, and its example in its media type. */ +function answer(res, route) { + if (route.media === null || [204, 205, 304].includes(route.status)) { + res.writeHead(route.status) + res.end() + return + } + const media = route.media.includes('*') ? 'application/octet-stream' : route.media + const type = bare(media) + const json = JSON.stringify(route.example) + const text = typeof route.example === 'string' ? route.example : json + let body + if (type === 'text/event-stream') body = `data: ${text}\n\n` + else if (type === 'application/x-ndjson' || type === 'application/jsonl') body = `${json}\n` + else if (type === 'application/json' || type.endsWith('+json')) body = json + else if (type.startsWith('text/') || type.endsWith('+xml') || type === 'application/xml') body = text + else body = Buffer.from([1, 2, 3]) + res.writeHead(route.status, { 'content-type': media }) + res.end(body) +} + +function handle(req, res, requests) { + const chunks = [] + req.on('data', (c) => chunks.push(c)) + req.on('end', () => { + const body = Buffer.concat(chunks) + const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) + const matches = table.filter((r) => r.regex.test(url.pathname)) + if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) + const route = matches.find((r) => r.method === req.method) + if (route === undefined) { + const methods = matches.map((r) => r.method).join(', ') + return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) + } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } + const wrong = problem(route, url, req, body) + if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) + requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) + answer(res, route) + }) +} + +/** + * Starts the mock server on `port` (0, the default, for a free one) of 127.0.0.1. Resolves to its + * `url`, the `requests` it answered and `close()`. When TEST_API_BASE_URL is set it starts nothing: + * `url` is that address and `requests` is null. + */ +export async function mock({ port = 0 } = {}) { + const external = process.env.TEST_API_BASE_URL + if (external) return { url: external.replace(/\/+$/, ''), requests: null, close: async () => {} } + const requests = [] + const server = createServer((req, res) => handle(req, res, requests)) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, '127.0.0.1', resolve) + }) + const close = () => + new Promise((resolve) => { + server.close(() => resolve()) + server.closeAllConnections() + }) + return { url: `http://127.0.0.1:${server.address().port}`, requests, close } +} + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + const port = Number(process.argv[2] ?? 4010) + const { url } = await mock({ port }) + console.log(`the mock server answers at ${url}`) +} diff --git a/crates/flowapi-sdk/tests/repo/github/package.json b/crates/flowapi-sdk/tests/repo/github/package.json new file mode 100644 index 0000000..ef93002 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/package.json @@ -0,0 +1,26 @@ +{ + "name": "github-like-sdk", + "version": "0.1.0", + "description": "TypeScript SDK for the GitHub-like API.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "engines": { "node": ">=20" }, + "main": "./dist/cjs/index.js", + "types": "./dist/cjs/index.d.ts", + "exports": { + ".": { + "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, + "require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" } + }, + "./package.json": "./package.json" + }, + "files": ["dist"], + "scripts": { + "build": "scripts/build", + "lint": "scripts/lint", + "test": "scripts/test", + "check": "scripts/check" + }, + "devDependencies": { "typescript": "7.0.2" } +} diff --git a/crates/flowapi-sdk/tests/repo/github/release-please-config.json b/crates/flowapi-sdk/tests/repo/github/release-please-config.json new file mode 100644 index 0000000..897e118 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/release-please-config.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "node", + "include-v-in-tag": true, + "bump-minor-pre-major": true, + "changelog-path": "CHANGELOG.md", + "extra-files": [{ "type": "yaml", "path": "flowapi-sdk.yml", "jsonpath": "$.package.version" }] + } + } +} diff --git a/crates/flowapi-sdk/tests/repo/github/scripts/build b/crates/flowapi-sdk/tests/repo/github/scripts/build new file mode 100644 index 0000000..6dd941a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/scripts/build @@ -0,0 +1,21 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The package built twice from src/ by tsc alone: ES modules into dist/esm, CommonJS into +# dist/cjs, each with its declarations; then loaded by its own name with require and import, as +# a user loads it. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/build: $tsc is missing: run npm install first" >&2 + exit 1 +fi +rm -rf dist +"$tsc" -p tsconfig.build.json +"$tsc" -p tsconfig.cjs.json +printf '{ "type": "commonjs" }\n' > dist/cjs/package.json +name=$(node -p 'require("./package.json").name') +# CommonJS: the module, its client class both `default` and by its name, as the README takes it. +node -e 'const m = require(process.argv[1]); if (typeof m.default !== "function" || m[m.default.name] !== m.default) throw new Error("require(" + process.argv[1] + ") gives no client class by its name")' "$name" +node --input-type=module -e 'const m = await import(process.argv[1]); if (typeof m.default !== "function") throw new Error("import(" + process.argv[1] + ") gives no client class")' "$name" diff --git a/crates/flowapi-sdk/tests/repo/github/scripts/check b/crates/flowapi-sdk/tests/repo/github/scripts/check new file mode 100644 index 0000000..e0be85d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/scripts/check @@ -0,0 +1,11 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Everything a change must pass: lint, the build, the built declarations type-checked on their +# own (skipLibCheck off), the tests. +set -eu +cd "$(dirname "$0")/.." +scripts/lint +scripts/build +node_modules/.bin/tsc -p tsconfig.dist.json +SDK_BUILT=1 scripts/test diff --git a/crates/flowapi-sdk/tests/repo/github/scripts/lint b/crates/flowapi-sdk/tests/repo/github/scripts/lint new file mode 100644 index 0000000..7126bd5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/scripts/lint @@ -0,0 +1,22 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The sources type-checked; no node: module in the generated client, which runs wherever fetch +# does; the mock server and the tests parsed. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/lint: $tsc is missing: run npm install first" >&2 + exit 1 +fi +"$tsc" -p tsconfig.json +found=$(find src -name '*.ts' ! -path 'src/lib/*' -exec grep -l -e 'from "node:' -e "from 'node:" {} + || true) +if [ -n "$found" ]; then + echo "scripts/lint: a node: module is imported by the client, which must run without Node:" >&2 + echo "$found" >&2 + exit 1 +fi +for f in mock/*.mjs $(find tests -name '*.mjs' | sort); do + node --check "$f" +done diff --git a/crates/flowapi-sdk/tests/repo/github/scripts/mock b/crates/flowapi-sdk/tests/repo/github/scripts/mock new file mode 100644 index 0000000..c7fad1c --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/scripts/mock @@ -0,0 +1,7 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The mock server on a port (4010 unless given), until stopped: for trying the client by hand. +set -eu +cd "$(dirname "$0")/.." +exec node mock/server.mjs "${1:-4010}" diff --git a/crates/flowapi-sdk/tests/repo/github/scripts/test b/crates/flowapi-sdk/tests/repo/github/scripts/test new file mode 100644 index 0000000..d78cf2a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/scripts/test @@ -0,0 +1,19 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Every test of tests/ by node --test, against the mock server each test file starts on a free +# port (or against TEST_API_BASE_URL when it is set). The package is built first, unless +# SDK_BUILT=1 says it was just built. +set -eu +cd "$(dirname "$0")/.." +if [ "${SDK_BUILT:-}" != 1 ]; then + scripts/build +fi +files=$(find tests -name '*.test.mjs' | sort) +if [ -z "$files" ]; then + echo "scripts/test: no tests under tests/" >&2 + exit 1 +fi +# The files one by one as arguments: every Node from 20 reads them so, globs or not. +# shellcheck disable=SC2086 +node --test $files diff --git a/crates/flowapi-sdk/tests/repo/github/tests/api-resources/apps.test.mjs b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/apps.test.mjs new file mode 100644 index 0000000..427c343 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/apps.test.mjs @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `apps` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { GitHub } from "github-like-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new GitHub({ baseURL: server.url, token: 'test-credential', appKey: 'test-credential', admin: { username: 'user', password: 'pass' }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("apps.hook: GET /app/hook", async () => { + await client.apps.hook() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /app/hook") +}) diff --git a/crates/flowapi-sdk/tests/repo/github/tests/api-resources/enterprise.test.mjs b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/enterprise.test.mjs new file mode 100644 index 0000000..99afc87 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/enterprise.test.mjs @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `enterprise` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { GitHub } from "github-like-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new GitHub({ baseURL: server.url, token: 'test-credential', appKey: 'test-credential', admin: { username: 'user', password: 'pass' }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("enterprise.settings: GET /enterprise/settings", async () => { + await client.enterprise.settings() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /enterprise/settings") +}) diff --git a/crates/flowapi-sdk/tests/repo/github/tests/api-resources/meta.test.mjs b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/meta.test.mjs new file mode 100644 index 0000000..bbd5684 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/meta.test.mjs @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `meta` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { GitHub } from "github-like-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new GitHub({ baseURL: server.url, token: 'test-credential', appKey: 'test-credential', admin: { username: 'user', password: 'pass' }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("meta.get: GET /meta", async () => { + await client.meta.get() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /meta") +}) diff --git a/crates/flowapi-sdk/tests/repo/github/tests/api-resources/repos.test.mjs b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/repos.test.mjs new file mode 100644 index 0000000..464cce2 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/repos.test.mjs @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `repos` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { GitHub } from "github-like-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new GitHub({ baseURL: server.url, token: 'test-credential', appKey: 'test-credential', admin: { username: 'user', password: 'pass' }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("repos.get: GET /repos/{owner}/{repo}", async () => { + await client.repos.get({ path: { owner: "string", repo: "string" } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /repos/{owner}/{repo}") +}) diff --git a/crates/flowapi-sdk/tests/repo/github/tests/api-resources/users.test.mjs b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/users.test.mjs new file mode 100644 index 0000000..5f4346a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tests/api-resources/users.test.mjs @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `users` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { GitHub } from "github-like-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new GitHub({ baseURL: server.url, token: 'test-credential', appKey: 'test-credential', admin: { username: 'user', password: 'pass' }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("users.me: GET /user", async () => { + await client.users.me() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /user") +}) diff --git a/crates/flowapi-sdk/tests/repo/github/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/github/tests/auth.test.mjs new file mode 100644 index 0000000..0f96fda --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tests/auth.test.mjs @@ -0,0 +1,51 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { GitHub } from "github-like-sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new GitHub({ baseURL: server.url, token: 'test-credential', appKey: 'test-credential', admin: { username: 'user', password: 'pass' }, maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("Token: sent by users.me", async () => { + await client.users.me() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer test-credential') +}) + +test("AppKey: sent by apps.hook", async () => { + await client.apps.hook() + const r = last() + if (r === null) return + assert.equal(r.headers["x-app-key"], 'test-credential') +}) + +test("Admin: sent by enterprise.settings", async () => { + await client.enterprise.settings() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, `Basic ${Buffer.from('user:pass').toString('base64')}`) +}) + +test("no credential: meta.get needs none", async () => { + const none = new GitHub({ baseURL: server.url, maxRetries: 0, token: null, appKey: null, admin: null }) + await none.meta.get() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, undefined) + assert.equal(r.headers["x-app-key"], undefined) +}) diff --git a/crates/flowapi-sdk/tests/repo/github/tsconfig.build.json b/crates/flowapi-sdk/tests/repo/github/tsconfig.build.json new file mode 100644 index 0000000..6034cd3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "rootDir": "src", + "outDir": "dist/esm" + } +} diff --git a/crates/flowapi-sdk/tests/repo/github/tsconfig.cjs.json b/crates/flowapi-sdk/tests/repo/github/tsconfig.cjs.json new file mode 100644 index 0000000..cae8db8 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.build.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs" + } +} diff --git a/crates/flowapi-sdk/tests/repo/github/tsconfig.dist.json b/crates/flowapi-sdk/tests/repo/github/tsconfig.dist.json new file mode 100644 index 0000000..f52d18a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tsconfig.dist.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "skipLibCheck": false, + "noEmit": true + }, + "include": ["dist/**/*.d.ts"] +} diff --git a/crates/flowapi-sdk/tests/repo/github/tsconfig.json b/crates/flowapi-sdk/tests/repo/github/tsconfig.json new file mode 100644 index 0000000..9ee3b9b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/github/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "rootDir": "src", + "noEmit": true + }, + "include": ["src"] +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/hosts/.flowapi/lock.json new file mode 100644 index 0000000..41d4dba --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/.flowapi/lock.json @@ -0,0 +1,53 @@ +{ + "version": 1, + "flowapi": "0.3.0", + "spec_sha256": "e4b9f2f959ef8117fe3866f447115e339cd0035e34d2589263b75dcb27bc2a19", + "config_sha256": "fc268764e708533c719e15e75e6cd17ebe51a04b6b2015e4ee308646ee492919", + "configured_endpoints": 10, + "files": { + ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", + ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", + "LICENSE": "77702c67cf238a0bb2f74f8f13a7b1c2ae8f31bdef792b8b635162fe07a20b61", + "README.md": "992078b37fbd521e97c7065cb362a8ba7b7879074185773698102b63a3905d01", + "api.md": "384b0f9771393aa9b3cfe9cfa4075c1f204df2598d976a92a8c2a2b9f9ef66c6", + "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mock/routes.mjs": "7083162a54afac64dd2f535d6276dd1ded0239ff07387c692a5451e993870abb", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "96cb11f72c86a0f781dc5c20b447a2c35966c592e63e32a6a37c789ee4532eea", + "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", + "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", + "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", + "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", + "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", + "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", + "src/api.ts": "47862206c7af673fc65b1d9adbf18a3982f5f9274cde292fc1b72af4ab8c37df", + "src/client.ts": "aaf06a6222e88429e152a30d5840dbbaa5c0c1bdeb4f9f4a6084cbb1672e3687", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", + "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", + "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", + "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", + "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "e38b92b2e8e9db9b1ce6d93cf5f1ef9623a999e77e7566b0729d5eccfcf0b8f3", + "src/resources/items.ts": "9d328514db34f97bb888a0c53bd6acfbcde61e364c1b33540f8d927e18fc8f17", + "src/resources/places.ts": "d365052c95dfd60949d886751e5983795c3e7024fa67625e810e01ebc718a117", + "tests/api-resources/items.test.mjs": "92c5ead4fed4363a1ee59afb7b306d3c63adfdb7ab0dfb0f097623e95fd2d287", + "tests/api-resources/places.test.mjs": "7e1d6438ffaa869bac034b6b6e553967a1a87f886e628c957ed71c8cc9a285ad", + "tests/auth.test.mjs": "292bc2606c1f6acd345174f15d7f159462824f0e06efd2da29be7108d6667a73", + "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", + "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", + "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", + "tsconfig.json": "8f8513b3a8e2fc81d06a2f3b0057d1e2881ca78722bd4b704766f0ad27ab7498" + }, + "names": {} +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/.github/workflows/ci.yml b/crates/flowapi-sdk/tests/repo/hosts/.github/workflows/ci.yml new file mode 100644 index 0000000..e31da6b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: npm install --no-audit --no-fund + - run: scripts/check diff --git a/crates/flowapi-sdk/tests/repo/hosts/.gitignore b/crates/flowapi-sdk/tests/repo/hosts/.gitignore new file mode 100644 index 0000000..6c15117 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/.gitignore @@ -0,0 +1,4 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +node_modules/ +dist/ +*.tgz diff --git a/crates/flowapi-sdk/tests/repo/hosts/.release-please-manifest.json b/crates/flowapi-sdk/tests/repo/hosts/.release-please-manifest.json new file mode 100644 index 0000000..466df71 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/AGENTS.md b/crates/flowapi-sdk/tests/repo/hosts/AGENTS.md new file mode 100644 index 0000000..1ca1d14 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/AGENTS.md @@ -0,0 +1,57 @@ + + +# AGENTS.md + +This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. + +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + +## What is generated + +Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: + +```sh +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . +``` + +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | + +## What is yours + +- `src/lib/` and `examples/`: generate writes a file there only while it is unchanged, and never overwrites one you changed. +- `CHANGELOG.md` and `.release-please-manifest.json`: written on the first generation, then the release tool's. +- Every file the lock does not list: generate never touches it. + +## Commands + +```sh +npm install # TypeScript, the one development dependency +scripts/check # everything: lint, build, the built types, the tests +scripts/build # dist/esm and dist/cjs, then both loaded by the package's name +scripts/lint # the types, no node: module in the client, the tests parsed +scripts/test # node --test over tests/, against the mock server each file starts +scripts/mock # the mock server on port 4010, for trying the client by hand +``` + +The mock (`mock/routes.mjs`) answers each operation with an example of its schema and refuses a request its operation would refuse: a wrong path or method, a missing parameter, a body of another media type. Set `TEST_API_BASE_URL` to run the tests against another server. + +## Releases + +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/hosts/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/hosts/CHANGELOG.md new file mode 100644 index 0000000..519c820 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +Each release of `hosts-sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/hosts/LICENSE b/crates/flowapi-sdk/tests/repo/hosts/LICENSE new file mode 100644 index 0000000..2561efd --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) The hosts-sdk authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/flowapi-sdk/tests/repo/hosts/README.md b/crates/flowapi-sdk/tests/repo/hosts/README.md new file mode 100644 index 0000000..bde3ebe --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/README.md @@ -0,0 +1,146 @@ + + +# Hosts TypeScript SDK + +TypeScript SDK for the Hosts API. Items kept in two regions. + +The `Hosts` client is generated by flowapi from the API's description: 10 methods in 2 resources, each listed in [api.md](api.md) with its parameters and what it returns. + +## Install + +```sh +npm install hosts-sdk +``` + +## Usage + +```ts +import { Hosts } from 'hosts-sdk' + +const client = new Hosts() + +const result = await client.items.all() +console.log(result) +``` + +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.items.all().withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { Hosts } = require('hosts-sdk')`; `import Hosts from 'hosts-sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.items`](api.md#clientitems) | 8 | +| [`client.places`](api.md#clientplaces) | 2 | + +## Authentication + +| Scheme | Kind | Sent as | Option | Environment variables | +| --- | --- | --- | --- | --- | +| `Client` | OAuth 2.0 client credentials | `Authorization: Bearer `, the token requested at `https://login.hosts.example/oauth/token` for the scopes the operation needs | `client`: a token, or `{ clientId, clientSecret }` to request one | `HOSTS_CLIENT_ID`: the client's id; `HOSTS_CLIENT_SECRET`: its secret | + +An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them. + +A token of OAuth 2.0's client credentials grant is requested at the token URL (relative to the base URL where it is relative) with the client's id and secret in HTTP basic, cached until a little before it expires, shared by the calls that wait for it, and requested again once when the API answers 401. A refusal of the token endpoint throws `TokenError` with its `error` and `description`. + +```ts +const client = new Hosts({ client: { clientId: '…', clientSecret: '…' } }) +``` + +## Servers + +The servers' URLs have variables. The client sends each one's default unless `serverVariables` gives another value: + +| Variable | Default | Values | +| --- | --- | --- | +| `region` | `eu` | `eu`, `us` | +| `version` | `v1` | any | +| `zone` | `a` | `a`, `b` | + +```ts +const other = new Hosts({ serverVariables: { region: 'us' } }) +``` + +A value that is not one of a variable's values throws a `RangeError`. + +A server URL may be relative to where the description is served (`./local`): give that address as `descriptionURL` to call it. + +```ts +const near = new Hosts({ descriptionURL: 'https://api.example.com/openapi.json' }) +``` + +## Errors + +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. + +```ts +import { APIError } from 'hosts-sdk' + +try { + await client.items.all() +} catch (error) { + if (error instanceof APIError) console.log(error.status, error.body) + else throw error +} +``` + +## Retries and timeouts + +A request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried once by default when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A call of any other method (POST, PATCH) sends a random `Idempotency-Key` header, the same on each of its attempts, so that the server applies it once: it is retried like the others. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. A retry that failed is not tried again: more retries are the caller's choice. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 60 s, the error is thrown at once. Each attempt may take 60 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: + +```ts +const patient = new Hosts({ maxRetries: 5, timeout: 120_000 }) +await client.items.all({}, { maxRetries: 0, timeout: 5_000 }) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `HOSTS_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new Hosts({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: + +```ts +const response = await client.request('GET', '/').asResponse() +console.log(response.status) +``` + +## Requirements + +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. + +## Development + +```sh +npm install +scripts/check # lint, build, the built types, the tests against the mock server +``` + +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/hosts/api.md b/crates/flowapi-sdk/tests/repo/hosts/api.md new file mode 100644 index 0000000..1f09b25 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/api.md @@ -0,0 +1,35 @@ + + +# API + +Every method of `Hosts`, by resource: 10 methods in 2 resources. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: + +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from 'hosts-sdk' +``` + +## client.items + +- `client.items.all(params?: Input, options?: RequestOptions): ApiCall>` + `GET /items`: Every item +- `client.items.create(params: Input, options?: RequestOptions): ApiCall>` + `POST /items`: Add an item +- `client.items.replace(params: Input, options?: RequestOptions): ApiCall>` + `PUT /items/{id}`: Replace an item +- `client.items.edit(params: Input, options?: RequestOptions): ApiCall>` + `PATCH /items/{id}`: Change an item +- `client.items.delete(params: Input, options?: RequestOptions): ApiCall>` + `DELETE /items/{id}`: Remove an item +- `client.items.check(params: Input, options?: RequestOptions): ApiCall>` + `HEAD /items/{id}`: Whether an item is there +- `client.items.describe(params: Input, options?: RequestOptions): ApiCall>` + `OPTIONS /items/{id}`: What an item allows, asked with a note +- `client.items.purge(params: Input, options?: RequestOptions): ApiCall>` + `DELETE /purge`: Remove the items named + +## client.places + +- `client.places.local(params?: Input, options?: RequestOptions): ApiCall>` + `GET /status`: The status where the description is served +- `client.places.edge(params?: Input, options?: RequestOptions): ApiCall>` + `GET /edge`: The status at an edge diff --git a/crates/flowapi-sdk/tests/repo/hosts/examples/.keep b/crates/flowapi-sdk/tests/repo/hosts/examples/.keep new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/hosts/issues.txt b/crates/flowapi-sdk/tests/repo/hosts/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/hosts/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/hosts/mock/routes.mjs new file mode 100644 index 0000000..f417bd4 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/mock/routes.mjs @@ -0,0 +1,19 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The operations the client calls, as the mock server answers them (server.mjs). + +export default [ + { "route": "GET /items", "method": "GET", "path": "/items", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 200, "media": "application/json", "example": [{"id": 1, "name": "string"}] }, + { "route": "POST /items", "method": "POST", "path": "/items", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["application/json"] }, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 201, "media": "application/json", "example": {"id": 1, "name": "string"} }, + { "route": "PUT /items/{id}", "method": "PUT", "path": "/items/{id}", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["application/json"] }, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 200, "media": "application/json", "example": {"id": 1, "name": "string"} }, + { "route": "PATCH /items/{id}", "method": "PATCH", "path": "/items/{id}", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["application/json"] }, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 200, "media": "application/json", "example": {"id": 1, "name": "string"} }, + { "route": "DELETE /items/{id}", "method": "DELETE", "path": "/items/{id}", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 204, "media": null, "example": null }, + { "route": "HEAD /items/{id}", "method": "HEAD", "path": "/items/{id}", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 200, "media": null, "example": null }, + { "route": "OPTIONS /items/{id}", "method": "OPTIONS", "path": "/items/{id}", "query": [], "headers": [], "cookies": [], "body": { "required": false, "media": ["text/plain"] }, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 204, "media": null, "example": null }, + { "route": "DELETE /purge", "method": "DELETE", "path": "/purge", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["application/json"] }, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 204, "media": null, "example": null }, + { "route": "GET /status", "method": "GET", "path": "/status", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 200, "media": "application/json", "example": {"up": false} }, + { "route": "GET /edge", "method": "GET", "path": "/edge", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }], []], "status": 200, "media": "application/json", "example": {"up": false} }, +] + +// The token endpoints of the client credentials flows, by path. +export const tokens = ["/oauth/token"] diff --git a/crates/flowapi-sdk/tests/repo/hosts/mock/server.mjs b/crates/flowapi-sdk/tests/repo/hosts/mock/server.mjs new file mode 100644 index 0000000..07c6fa6 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/mock/server.mjs @@ -0,0 +1,237 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The API's mock server, on node:http with no dependency, answering by the routes printed from +// the description beside it (routes.mjs). It is strict where a client goes wrong: a path no +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). +// +// `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL +// names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. +import { createServer } from 'node:http' +import { pathToFileURL } from 'node:url' +import routes, { tokens } from './routes.mjs' + +/** A route's path as a regular expression: each `{name}` is one segment. */ +function pattern(path) { + const parts = path + .split(/(\{[^}/]+\})/) + .map((p) => (/^\{[^}/]+\}$/.test(p) ? '([^/]+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))) + return new RegExp(`^${parts.join('')}$`) +} + +/** Each segment of a path by how specific it is: 2 literal, 1 a template beside text, 0 a template. */ +const ranks = (path) => path.split('/').map((s) => (!s.includes('{') ? 2 : /^\{[^}/]+\}$/.test(s) ? 0 : 1)) + +/** + * The more specific route first (OpenAPI's Paths Object matches a concrete path before a templated + * one): at the first segment where the two differ in kind, the more literal one; then the shorter + * path, which never matches the same URL. Routes as specific as each other are ambiguous by the + * specification and keep the order of routes.mjs (the client's resources and methods). + */ +function specific(a, b) { + const x = ranks(a.path) + const y = ranks(b.path) + const i = x.findIndex((r, n) => r !== y[n]) + if (i === -1 || i >= y.length) return x.length - y.length + return y[i] - x[i] +} + +// Sorted once, stably: a request takes the first route that matches its path and method. +const table = routes.map((r) => ({ ...r, regex: pattern(r.path) })).sort(specific) + +/** A media type without its parameters, in lower case. */ +const bare = (type) => (type ?? '').split(';')[0].trim().toLowerCase() + +// Whether a media range (`image/png`, `image/*`, `*/*`) takes a media type. +function takes(range, type) { + const r = bare(range) + if (r === '*/*') return true + if (r.endsWith('/*')) return type.startsWith(r.slice(0, -1)) + return r === type +} + +/** The names of a Cookie header's cookies. */ +function cookieNames(header) { + const names = new Set() + for (const part of (header ?? '').split(';')) { + const name = part.split('=')[0].trim() + if (name !== '') names.add(name) + } + return names +} + +/** Whether the query has a parameter: by its name, or as `name[...]` for an object's members. */ +function hasQuery(url, name) { + for (const key of url.searchParams.keys()) if (key === name || key.startsWith(`${name}[`)) return true + return false +} + +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + +/** What is wrong with a request for its route, with the status that says so; null for nothing. */ +function problem(route, url, req, body) { + for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] + for (const name of route.headers) if (req.headers[name] === undefined) return [400, `the header ${name} is required`] + const jar = cookieNames(req.headers.cookie) + for (const name of route.cookies) if (!jar.has(name)) return [400, `the cookie ${name} is required`] + if (body.length === 0) return route.body?.required ? [400, 'the operation requires a body'] : null + if (route.body === null) return [400, 'the operation takes no body'] + const type = bare(req.headers['content-type']) + if (!route.body.media.some((m) => takes(m, type))) { + return [415, `the body's media type ${type || '(none)'} is not one of ${route.body.media.join(', ')}`] + } + if (type === 'application/json' || type.endsWith('+json')) { + try { + JSON.parse(body.toString('utf8')) + } catch { + return [400, 'the body is not JSON'] + } + } + return null +} + +function fail(res, status, message) { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: message })) +} + +/** The route's answer: its status, and its example in its media type. */ +function answer(res, route) { + if (route.media === null || [204, 205, 304].includes(route.status)) { + res.writeHead(route.status) + res.end() + return + } + const media = route.media.includes('*') ? 'application/octet-stream' : route.media + const type = bare(media) + const json = JSON.stringify(route.example) + const text = typeof route.example === 'string' ? route.example : json + let body + if (type === 'text/event-stream') body = `data: ${text}\n\n` + else if (type === 'application/x-ndjson' || type === 'application/jsonl') body = `${json}\n` + else if (type === 'application/json' || type.endsWith('+json')) body = json + else if (type.startsWith('text/') || type.endsWith('+xml') || type === 'application/xml') body = text + else body = Buffer.from([1, 2, 3]) + res.writeHead(route.status, { 'content-type': media }) + res.end(body) +} + +function handle(req, res, requests) { + const chunks = [] + req.on('data', (c) => chunks.push(c)) + req.on('end', () => { + const body = Buffer.concat(chunks) + const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) + const matches = table.filter((r) => r.regex.test(url.pathname)) + if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) + const route = matches.find((r) => r.method === req.method) + if (route === undefined) { + const methods = matches.map((r) => r.method).join(', ') + return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) + } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } + const wrong = problem(route, url, req, body) + if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) + requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) + answer(res, route) + }) +} + +/** + * Starts the mock server on `port` (0, the default, for a free one) of 127.0.0.1. Resolves to its + * `url`, the `requests` it answered and `close()`. When TEST_API_BASE_URL is set it starts nothing: + * `url` is that address and `requests` is null. + */ +export async function mock({ port = 0 } = {}) { + const external = process.env.TEST_API_BASE_URL + if (external) return { url: external.replace(/\/+$/, ''), requests: null, close: async () => {} } + const requests = [] + const server = createServer((req, res) => handle(req, res, requests)) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, '127.0.0.1', resolve) + }) + const close = () => + new Promise((resolve) => { + server.close(() => resolve()) + server.closeAllConnections() + }) + return { url: `http://127.0.0.1:${server.address().port}`, requests, close } +} + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + const port = Number(process.argv[2] ?? 4010) + const { url } = await mock({ port }) + console.log(`the mock server answers at ${url}`) +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/package.json b/crates/flowapi-sdk/tests/repo/hosts/package.json new file mode 100644 index 0000000..28730f3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/package.json @@ -0,0 +1,26 @@ +{ + "name": "hosts-sdk", + "version": "0.1.0", + "description": "TypeScript SDK for the Hosts API. Items kept in two regions.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "engines": { "node": ">=20" }, + "main": "./dist/cjs/index.js", + "types": "./dist/cjs/index.d.ts", + "exports": { + ".": { + "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, + "require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" } + }, + "./package.json": "./package.json" + }, + "files": ["dist"], + "scripts": { + "build": "scripts/build", + "lint": "scripts/lint", + "test": "scripts/test", + "check": "scripts/check" + }, + "devDependencies": { "typescript": "7.0.2" } +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/release-please-config.json b/crates/flowapi-sdk/tests/repo/hosts/release-please-config.json new file mode 100644 index 0000000..897e118 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/release-please-config.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "node", + "include-v-in-tag": true, + "bump-minor-pre-major": true, + "changelog-path": "CHANGELOG.md", + "extra-files": [{ "type": "yaml", "path": "flowapi-sdk.yml", "jsonpath": "$.package.version" }] + } + } +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/scripts/build b/crates/flowapi-sdk/tests/repo/hosts/scripts/build new file mode 100644 index 0000000..6dd941a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/scripts/build @@ -0,0 +1,21 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The package built twice from src/ by tsc alone: ES modules into dist/esm, CommonJS into +# dist/cjs, each with its declarations; then loaded by its own name with require and import, as +# a user loads it. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/build: $tsc is missing: run npm install first" >&2 + exit 1 +fi +rm -rf dist +"$tsc" -p tsconfig.build.json +"$tsc" -p tsconfig.cjs.json +printf '{ "type": "commonjs" }\n' > dist/cjs/package.json +name=$(node -p 'require("./package.json").name') +# CommonJS: the module, its client class both `default` and by its name, as the README takes it. +node -e 'const m = require(process.argv[1]); if (typeof m.default !== "function" || m[m.default.name] !== m.default) throw new Error("require(" + process.argv[1] + ") gives no client class by its name")' "$name" +node --input-type=module -e 'const m = await import(process.argv[1]); if (typeof m.default !== "function") throw new Error("import(" + process.argv[1] + ") gives no client class")' "$name" diff --git a/crates/flowapi-sdk/tests/repo/hosts/scripts/check b/crates/flowapi-sdk/tests/repo/hosts/scripts/check new file mode 100644 index 0000000..e0be85d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/scripts/check @@ -0,0 +1,11 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Everything a change must pass: lint, the build, the built declarations type-checked on their +# own (skipLibCheck off), the tests. +set -eu +cd "$(dirname "$0")/.." +scripts/lint +scripts/build +node_modules/.bin/tsc -p tsconfig.dist.json +SDK_BUILT=1 scripts/test diff --git a/crates/flowapi-sdk/tests/repo/hosts/scripts/lint b/crates/flowapi-sdk/tests/repo/hosts/scripts/lint new file mode 100644 index 0000000..7126bd5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/scripts/lint @@ -0,0 +1,22 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The sources type-checked; no node: module in the generated client, which runs wherever fetch +# does; the mock server and the tests parsed. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/lint: $tsc is missing: run npm install first" >&2 + exit 1 +fi +"$tsc" -p tsconfig.json +found=$(find src -name '*.ts' ! -path 'src/lib/*' -exec grep -l -e 'from "node:' -e "from 'node:" {} + || true) +if [ -n "$found" ]; then + echo "scripts/lint: a node: module is imported by the client, which must run without Node:" >&2 + echo "$found" >&2 + exit 1 +fi +for f in mock/*.mjs $(find tests -name '*.mjs' | sort); do + node --check "$f" +done diff --git a/crates/flowapi-sdk/tests/repo/hosts/scripts/mock b/crates/flowapi-sdk/tests/repo/hosts/scripts/mock new file mode 100644 index 0000000..c7fad1c --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/scripts/mock @@ -0,0 +1,7 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The mock server on a port (4010 unless given), until stopped: for trying the client by hand. +set -eu +cd "$(dirname "$0")/.." +exec node mock/server.mjs "${1:-4010}" diff --git a/crates/flowapi-sdk/tests/repo/hosts/scripts/test b/crates/flowapi-sdk/tests/repo/hosts/scripts/test new file mode 100644 index 0000000..d78cf2a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/scripts/test @@ -0,0 +1,19 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Every test of tests/ by node --test, against the mock server each test file starts on a free +# port (or against TEST_API_BASE_URL when it is set). The package is built first, unless +# SDK_BUILT=1 says it was just built. +set -eu +cd "$(dirname "$0")/.." +if [ "${SDK_BUILT:-}" != 1 ]; then + scripts/build +fi +files=$(find tests -name '*.test.mjs' | sort) +if [ -z "$files" ]; then + echo "scripts/test: no tests under tests/" >&2 + exit 1 +fi +# The files one by one as arguments: every Node from 20 reads them so, globs or not. +# shellcheck disable=SC2086 +node --test $files diff --git a/crates/flowapi-sdk/tests/repo/hosts/tests/api-resources/items.test.mjs b/crates/flowapi-sdk/tests/repo/hosts/tests/api-resources/items.test.mjs new file mode 100644 index 0000000..058ee84 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tests/api-resources/items.test.mjs @@ -0,0 +1,58 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `items` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Hosts } from "hosts-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Hosts({ baseURL: server.url, client: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("items.all: GET /items", async () => { + await client.items.all() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /items") +}) + +test("items.create: POST /items", async () => { + await client.items.create({ body: { contentType: "application/json", value: { name: "string" } } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "POST /items") +}) + +test("items.replace: PUT /items/{id}", async () => { + await client.items.replace({ path: { id: 1 }, body: { contentType: "application/json", value: { name: "string" } } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "PUT /items/{id}") +}) + +test("items.edit: PATCH /items/{id}", async () => { + await client.items.edit({ path: { id: 1 }, body: { contentType: "application/json", value: { name: "string" } } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "PATCH /items/{id}") +}) + +test("items.delete: DELETE /items/{id}", async () => { + await client.items.delete({ path: { id: 1 } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "DELETE /items/{id}") +}) + +test("items.check: HEAD /items/{id}", async () => { + await client.items.check({ path: { id: 1 } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "HEAD /items/{id}") +}) + +test("items.describe: OPTIONS /items/{id}", async () => { + await client.items.describe({ path: { id: 1 } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "OPTIONS /items/{id}") +}) + +test("items.purge: DELETE /purge", async () => { + await client.items.purge({ body: { contentType: "application/json", value: [1] } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "DELETE /purge") +}) diff --git a/crates/flowapi-sdk/tests/repo/hosts/tests/api-resources/places.test.mjs b/crates/flowapi-sdk/tests/repo/hosts/tests/api-resources/places.test.mjs new file mode 100644 index 0000000..bffbe17 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tests/api-resources/places.test.mjs @@ -0,0 +1,28 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `places` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Hosts } from "hosts-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Hosts({ baseURL: server.url, client: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("places.local: GET /status", async () => { + await client.places.local() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /status") +}) + +test("places.edge: GET /edge", async () => { + await client.places.edge() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /edge") +}) diff --git a/crates/flowapi-sdk/tests/repo/hosts/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/hosts/tests/auth.test.mjs new file mode 100644 index 0000000..8f8324d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tests/auth.test.mjs @@ -0,0 +1,29 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Hosts } from "hosts-sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Hosts({ baseURL: server.url, client: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("Client: sent by items.all", async () => { + await client.items.all() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer mock-token') + assert.ok(server.requests.some((q) => q.route === 'token'), 'the token was requested of the mock') +}) diff --git a/crates/flowapi-sdk/tests/repo/hosts/tsconfig.build.json b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.build.json new file mode 100644 index 0000000..6034cd3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "rootDir": "src", + "outDir": "dist/esm" + } +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/tsconfig.cjs.json b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.cjs.json new file mode 100644 index 0000000..cae8db8 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.build.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs" + } +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/tsconfig.dist.json b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.dist.json new file mode 100644 index 0000000..f52d18a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.dist.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "skipLibCheck": false, + "noEmit": true + }, + "include": ["dist/**/*.d.ts"] +} diff --git a/crates/flowapi-sdk/tests/repo/hosts/tsconfig.json b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.json new file mode 100644 index 0000000..9ee3b9b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/hosts/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "rootDir": "src", + "noEmit": true + }, + "include": ["src"] +} diff --git a/crates/flowapi-sdk/tests/repo/shop/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/shop/.flowapi/lock.json index 948dd06..7e6eb72 100644 --- a/crates/flowapi-sdk/tests/repo/shop/.flowapi/lock.json +++ b/crates/flowapi-sdk/tests/repo/shop/.flowapi/lock.json @@ -1,50 +1,52 @@ { "version": 1, - "flowapi": "0.2.0", - "spec_sha256": "077372b56a5ca5e57c67708b89e0352ca23190a36ccc6b9038de5a8c7a8b3056", - "config_sha256": "9c1bc5b4b5514b05133e42a769182babe2685668c554d9f21156fa4ceffa16da", + "flowapi": "0.3.0", + "spec_sha256": "5d94682b80db94ab5e6075e867df23567e0d46cb66767a5da6e78e8946247c84", + "config_sha256": "627affcae69b305dddeeec21275d7d82a11f9ed2b0a59f764245ee938b4be3e6", "configured_endpoints": 14, "files": { ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", - "AGENTS.md": "5b8c401fd037e88eb5d07f48d10e51065408c0860bb26e5955b114860e3df2ca", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", "LICENSE": "4d0908a6bbb74cde7f970212dc74a5e2dcef439a74294f3677474ecb1de87f9b", - "README.md": "ff919382a3254c523d550ac136dcc05f6b609877d8f5b5cb6bde184da0fa4703", - "api.md": "83ce77b6ae20bfa3c1e8cbde6937371096c0003c99117aeb8aad8487196aebce", + "README.md": "886f09539f6f47f7c7fdbb8de36101cd16e5910c8ecaa75edf5b70c76bb63331", + "api.md": "28ce35b8f6b91d4c1d8d6625e1a3d7ad4d800a888773c63a90d7afae42778094", "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "mock/routes.mjs": "1905d833c489f157a8caf823dee784ff516b69e95b906e134441c5a4fd1d01e4", - "mock/server.mjs": "6172f681d001cdff8a293de45151012c2f825c7993a3794e1537b1895fd64f71", - "package.json": "5a16ca1ab62a7641fb2bda95b98c1a615d04c413d47fc815cdd81a313bdddb19", + "mock/routes.mjs": "f0a84b12a40aba28f2190a4c92622a8f6fe933b21f8300b25ae7a60268d27f31", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "ee2b63a643e95096c0162b7c8608cb5941290078a8dd53aff71429e034466c5c", "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", - "src/api.ts": "d3d693da8d300b70c6fa6be7d5b7b6e98f6fd65c0475c6df59f910b9acd17041", - "src/client.ts": "579a70e8111cdd582a876b2fe9b4fce8b87bf7010e358805e340a1586c2b7249", - "src/core/auth.ts": "40626554be57a4b868baeaa13cefc25f8567ec76b159b94f6cd142127d03377d", + "src/api.ts": "6a4c2dd32d09a1ea4901a60d48fc86da65c6cc24f74774a50a889569ac85e70c", + "src/client.ts": "b84fb419e22523129222aaa4ab6c0ebdc86f03646aa3e88e0cbaebb2852a7d01", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", - "src/core/calls.ts": "8249d7157c961e7519341bd1d98ccb9c0951b5c5427aa3a2f6a5b38ac8022645", - "src/core/core.ts": "b40ae6c13aa2788e3648fadda0dd849ffbee184c64e8a9480ce2bc003f79a5c4", - "src/core/errors.ts": "b227f946d0a6ef82f9e8941db86b3935017b0a7a2fe90b239d3ba56702a059ee", - "src/core/index.ts": "4dd5b2242a5822ba8163d2b2386b7b77ec561b074ebe131b053e7a5f5dc3bc70", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", - "src/core/pagination.ts": "44b241a1f4c35a644a5d0b93f9044b1c4fee3b8e52893c1175411421d61916c1", - "src/core/platform.ts": "565f9b36d6c770a3b9f8401c735676d8b1333a64161b258a2945d9cfb45c0d04", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", - "src/core/retry.ts": "90739bf0a613264a45a587b937f4b2557010c1c19d963a73ca01bf9a493560e7", - "src/core/send.ts": "04040dfbf9490182489db3a739be2d8cda0cdf896f711e0df8bf551c88b17bc8", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", - "src/index.ts": "91ae079dcebf1c65b549a879c6b7c968dd81ed05901c47dd821eb3c1bea6bcc6", - "src/resources/events.ts": "47dd0ef94ee0293a2af6d93d42eba030e79da4f96d5cbf24fd30f5b3adf7f791", - "src/resources/owners.ts": "2f4a019bc4c70b5c8222819e5afdff4fecf008aa46e6063dd8210ebcfd577a24", - "src/resources/pages.ts": "64ce9721d0ca7d499d0bfdb17cffd18aa36f626e4b491283c55ea4e8849638cf", - "src/resources/pets.ts": "ccf4577e92a0f38c4963ceb5e317d4de0fcbb98f04ed1e59cfd6e1a8bdc55976", - "src/resources/pets/photos.ts": "41509f0f319e75bf7894d058c7fd6ed71121898acaa4574fda5db46c0df63108", - "src/resources/system.ts": "0c763e73320b209628d77ece73982dd7b839b09843168aee0d434bcabd104d17", - "src/resources/tags.ts": "68e7fa1b25f1d17f7647a4a7dd3ba703599f914509a125a55010a158ce26e719", - "src/resources/users.ts": "51929f1d86b48b845a6b8fb8a2e3134ed9bdeca19728bb43e481e2eec1fe2b9d", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "9ac647564f3cc01f8b5006a56fc4bcb4277be4f47dab881124d69a170f04062f", + "src/resources/events.ts": "95fa8d3549215097b04b305b9b9cb781db3487af3687a906ecc49e9008403433", + "src/resources/owners.ts": "d7b1db7f45c67ee73f93f425a02afd417882a3a6e4b1daae174e640b7f98bb0a", + "src/resources/pages.ts": "19043837675f7d6f07ea54b9918b4b57abda04144256551fdfa96f8c28e5ebec", + "src/resources/pets.ts": "ff0567443a7547bb3d9b3329f196e65af202e6e033acb609f2695b24eb158199", + "src/resources/pets/photos.ts": "397a486260f14d98d0c67658ff45c47be16a99bdcfca333507ba04650fd55566", + "src/resources/system.ts": "7d44113473bc6ea0484f6d11bd43fa251aad6905c5d9691b29e7bdb5e1cbe844", + "src/resources/tags.ts": "14c08115c71c58fdd9ea175934de4fc5c99f69b60a4cb890b5d86c3d6c62deba", + "src/resources/users.ts": "809743d3589dc69ed780819f88dfaa2e9b10ef32007080b83f2543bce2ce1960", "tests/api-resources/events.test.mjs": "17860356877b643273b3ee06803555e213daa961a886c449425179333e25eb49", "tests/api-resources/owners.test.mjs": "5d45088bdffe8742017fcc75598b3062915c55ec03b1fffd698b3b67232ba40c", "tests/api-resources/pages.test.mjs": "c4162c03f286629d021802f766dcf2edaafe7e3565c69e3792df259ea96f2c8c", @@ -53,6 +55,7 @@ "tests/api-resources/system.test.mjs": "e16ffd64e20c93e2bf01b03e4d80e38565f1f05dfc699b3da5f8a14d68bb37eb", "tests/api-resources/tags.test.mjs": "e9b6e97ff44f5b2be703c0b874c3f65227210bad10fed12a8ab12bec0ab2028f", "tests/api-resources/users.test.mjs": "3bc0e6115318d374063428d5478d677a097dd0d7afd8da9ab3c3ec2115f4a6f4", + "tests/auth.test.mjs": "cfd21fe8b66335042a184d7a0afecd099e54afaca0b7280bf81642404f17ab52", "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", diff --git a/crates/flowapi-sdk/tests/repo/shop/AGENTS.md b/crates/flowapi-sdk/tests/repo/shop/AGENTS.md index 46490a5..1ca1d14 100644 --- a/crates/flowapi-sdk/tests/repo/shop/AGENTS.md +++ b/crates/flowapi-sdk/tests/repo/shop/AGENTS.md @@ -4,15 +4,34 @@ This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + ## What is generated Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: ```sh -npx -y @localix-ai/flowapi@0.2.0 generate flowapi-sdk.yml --out . +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . ``` -`flowapi config check flowapi-sdk.yml` says what is wrong with the config, every issue at once. A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | ## What is yours @@ -35,4 +54,4 @@ The mock (`mock/routes.mjs`) answers each operation with an example of its schem ## Releases -release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released. Publishing is a person's step. +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/shop/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/shop/CHANGELOG.md index 825c32f..cdd124d 100644 --- a/crates/flowapi-sdk/tests/repo/shop/CHANGELOG.md +++ b/crates/flowapi-sdk/tests/repo/shop/CHANGELOG.md @@ -1 +1,3 @@ # Changelog + +Each release of `@shop/sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/shop/README.md b/crates/flowapi-sdk/tests/repo/shop/README.md index b00d6d7..86229e8 100644 --- a/crates/flowapi-sdk/tests/repo/shop/README.md +++ b/crates/flowapi-sdk/tests/repo/shop/README.md @@ -1,10 +1,10 @@ -# @shop/sdk +# Shop TypeScript SDK -The TypeScript client of the Shop API, generated by flowapi from its description. +TypeScript SDK for the Shop API. Sells pets and their photos. -It has 14 methods in 8 resources; [api.md](api.md) lists them. +The `Shop` client is generated by flowapi from the API's description: 14 methods in 8 resources, each listed in [api.md](api.md) with its parameters and what it returns. ## Install @@ -23,16 +23,36 @@ const result = await client.pets.retrieve({ path: { pet_id: "pet_id" } }) console.log(result) ``` -The package is ES modules and CommonJS both, with types for each, and has no dependency: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { Shop } = require('@shop/sdk')`; `import Shop from '@shop/sdk'` gives it too. +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.pets.retrieve({ path: { pet_id: "pet_id" } }).withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { Shop } = require('@shop/sdk')`; `import Shop from '@shop/sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.events`](api.md#clientevents) | 1 | +| [`client.owners`](api.md#clientowners) | 1 | +| [`client.pages`](api.md#clientpages) | 1 | +| [`client.pets`](api.md#clientpets) | 5 | +| [`client.pets.photos`](api.md#clientpetsphotos) | 3 | +| [`client.system`](api.md#clientsystem) | 1 | +| [`client.tags`](api.md#clienttags) | 1 | +| [`client.users`](api.md#clientusers) | 1 | ## Authentication -Each credential is an option of the client, else read from its environment variable: +| Scheme | Kind | Sent as | Option | Environment variables | +| --- | --- | --- | --- | --- | +| `ApiKeyAuth` | API key | the header `X-API-Key` | `apiKeyAuth`: the key | `SHOP_API_KEY`: the key | +| `BearerAuth` | HTTP bearer | `Authorization: Bearer ` | `bearerAuth`: the token | `SHOP_TOKEN`: the token | -| Scheme | Sent as | Option | Variable | -| --- | --- | --- | --- | -| `ApiKeyAuth` | an API key in the header `X-API-Key` | `apiKeyAuth` | `SHOP_API_KEY` | -| `BearerAuth` | HTTP `bearer` | `bearerAuth` | `SHOP_TOKEN` | +An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them. ```ts const client = new Shop({ apiKeyAuth: '…', bearerAuth: '…' }) @@ -45,17 +65,35 @@ const client = new Shop({ apiKeyAuth: '…', bearerAuth: '…' }) | `production` | https://api.shop.example/v1 | | `sandbox` | https://sandbox.shop.example/v1 | -The client calls `production` unless given `environment` or `baseURL`, or `SHOP_BASE_URL` is set. +The client calls `production` unless it is given `environment` or `baseURL`, or `SHOP_BASE_URL` is set. + +```ts +const sandbox = new Shop({ environment: 'sandbox' }) +``` ## Errors -A status that is not a success throws an `APIError` with its `status`, `headers` and `body`, of the class for its status: `BadRequestError` (400), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RequestTimeoutError` (408), `ConflictError` (409), `UnprocessableEntityError` (422), `RateLimitError` (429), `InternalServerError` (500 and above). No answer throws `APIConnectionError`; a timeout `APIConnectionTimeoutError`; a call aborted by its signal `APIUserAbortError`. +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. ```ts import { APIError } from '@shop/sdk' try { - await client.pets.retrieve(/* … */) + await client.pets.retrieve({ path: { pet_id: "pet_id" } }) } catch (error) { if (error instanceof APIError) console.log(error.status, error.body) else throw error @@ -64,34 +102,55 @@ try { ## Retries and timeouts -A call that fails to connect, or is answered 408, 409, 429 or 5xx, is tried 2 more times by default, waiting longer each time (never more than 20 s when the server asks to wait); each attempt may take 30 s, its body read. Give `maxRetries` and `timeout` (milliseconds) to the client, or to one call: +A request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried 2 times by default when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. This SDK's config retries more than once, so a retry that failed is tried again. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 20 s, the error is thrown at once. Each attempt may take 30 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: ```ts -const client = new Shop({ maxRetries: 0, timeout: 20_000 }) +const patient = new Shop({ maxRetries: 5, timeout: 120_000 }) +await client.pets.retrieve({ path: { pet_id: "pet_id" } }, { maxRetries: 0, timeout: 5_000 }) ``` ## Pagination -A list is read a page at a time; `for await` reads every item, asking for the next page as it needs one: +A list method is read a page at a time. `for await` over it reads every item, asking for the next page when it needs one; awaited, it gives the first page, with its `items`, `hasNextPage()` and `getNextPage()`. A list stops at 10,000 pages unless `maxPages` says otherwise. ```ts for await (const item of client.pets.list()) console.log(item) const page = await client.pets.list() -console.log(page.items) +console.log(page.items, page.hasNextPage()) ``` ## Streaming -A streamed method gives its events as they come: +A streamed method gives its events as they come, read once; `abort()` stops the stream and closes its connection. + +```ts +const stream = await client.events.stream() +for await (const event of stream) console.log(event) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `SHOP_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new Shop({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: ```ts -for await (const event of await client.events.stream()) console.log(event) +const response = await client.request('GET', '/').asResponse() +console.log(response.status) ``` ## Requirements -Node 20 or later (CI runs 20, 22, 24), or any runtime with `fetch`. Built with TypeScript 7.0.2. +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. ## Development @@ -100,4 +159,4 @@ npm install scripts/check # lint, build, the built types, the tests against the mock server ``` -The code is generated from `flowapi-sdk.yml`: change that file and generate again ([AGENTS.md](AGENTS.md)). +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/shop/api.md b/crates/flowapi-sdk/tests/repo/shop/api.md index d960bc5..664a5df 100644 --- a/crates/flowapi-sdk/tests/repo/shop/api.md +++ b/crates/flowapi-sdk/tests/repo/shop/api.md @@ -2,52 +2,41 @@ # API -14 methods in 8 resources of `Shop`. +Every method of `Shop`, by resource: 14 methods in 8 resources. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: -## pets +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from '@shop/sdk' +``` -- `client.pets.list(params?: Input, options?: RequestOptions): PagePromise, ["data"]>>` - `GET /pets`: List the pets */ one page at a time -- `client.pets.create(params: Input, options?: RequestOptions): ApiCall>` - `POST /pets` -- `client.pets.retrieve(params: Input, options?: RequestOptions): ApiCall>` - `GET /pets/{pet_id}`: One pet -- `client.pets.update(params: Input, options?: RequestOptions): ApiCall>` - `PATCH /pets/{pet_id}` -- `client.pets.delete(params: Input, options?: RequestOptions): ApiCall>` - `DELETE /pets/{pet_id}` +## client.events -## owners +- `client.events.stream(params?: Input, options?: RequestOptions): ApiCall>` + `GET /events` + +## client.owners - `client.owners.list(params?: Input, options?: RequestOptions): PagePromise, []>>` `GET /owners` -## users - -- `client.users.list(params?: Input, options?: RequestOptions): PagePromise, ["data"]>>` - `GET /users` - -## pages +## client.pages - `client.pages.list(params?: Input, options?: RequestOptions): PagePromise, ["items"]>>` `GET /pages` -## tags - -- `client.tags.list(params?: Input, options?: RequestOptions): PagePromise, ["tags"]>>` - `GET /tags` +## client.pets -## events - -- `client.events.stream(params?: Input, options?: RequestOptions): ApiCall>` - `GET /events` - -## system - -- `client.system.health(params?: Input, options?: RequestOptions): ApiCall>` - `GET /health` +- `client.pets.list(params?: Input, options?: RequestOptions): PagePromise, ["data"]>>` + `GET /pets`: List the pets */ one page at a time +- `client.pets.create(params: Input, options?: RequestOptions): ApiCall>` + `POST /pets`: Add a pet +- `client.pets.retrieve(params: Input, options?: RequestOptions): ApiCall>` + `GET /pets/{pet_id}`: One pet +- `client.pets.update(params: Input, options?: RequestOptions): ApiCall>` + `PATCH /pets/{pet_id}` +- `client.pets.delete(params: Input, options?: RequestOptions): ApiCall>` + `DELETE /pets/{pet_id}` (deprecated) -## pets.photos +## client.pets.photos - `client.pets.photos.list(params: Input, options?: RequestOptions): PagePromise, ["items"]>>` `GET /pets/{pet_id}/photos` @@ -55,3 +44,18 @@ `POST /pets/{pet_id}/photos` - `client.pets.photos.download(params: Input, options?: RequestOptions): ApiCall>` `GET /pets/{pet_id}/photos/{photo_id}/raw` + +## client.system + +- `client.system.health(params?: Input, options?: RequestOptions): ApiCall>` + `GET /health` + +## client.tags + +- `client.tags.list(params?: Input, options?: RequestOptions): PagePromise, ["tags"]>>` + `GET /tags` + +## client.users + +- `client.users.list(params?: Input, options?: RequestOptions): PagePromise, ["data"]>>` + `GET /users` diff --git a/crates/flowapi-sdk/tests/repo/shop/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/shop/mock/routes.mjs index 3f9c433..3fb1a07 100644 --- a/crates/flowapi-sdk/tests/repo/shop/mock/routes.mjs +++ b/crates/flowapi-sdk/tests/repo/shop/mock/routes.mjs @@ -3,18 +3,21 @@ // The operations the client calls, as the mock server answers them (server.mjs). export default [ - { "route": "GET /pets", "method": "GET", "path": "/pets", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"data": [{"id": "string", "name": "string"}], "next_page_token": "string", "has_more": false} }, - { "route": "POST /pets", "method": "POST", "path": "/pets", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["application/json"] }, "status": 201, "media": "application/json", "example": {"id": "string", "name": "string"} }, - { "route": "GET /pets/{pet_id}", "method": "GET", "path": "/pets/{pet_id}", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"id": "string", "name": "string"} }, - { "route": "PATCH /pets/{pet_id}", "method": "PATCH", "path": "/pets/{pet_id}", "query": [], "headers": [], "cookies": [], "body": { "required": false, "media": ["application/merge-patch+json"] }, "status": 200, "media": "application/json", "example": {"id": "string", "name": "string"} }, - { "route": "DELETE /pets/{pet_id}", "method": "DELETE", "path": "/pets/{pet_id}", "query": [], "headers": [], "cookies": [], "body": null, "status": 204, "media": null, "example": null }, - { "route": "GET /owners", "method": "GET", "path": "/owners", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": [{"login": "string"}] }, - { "route": "GET /users", "method": "GET", "path": "/users", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"data": [{"id": "string"}], "has_more": false} }, - { "route": "GET /pages", "method": "GET", "path": "/pages", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"items": ["string"], "total_pages": 1} }, - { "route": "GET /tags", "method": "GET", "path": "/tags", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"tags": ["string"]} }, - { "route": "GET /events", "method": "GET", "path": "/events", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "text/event-stream", "example": "string" }, - { "route": "GET /health", "method": "GET", "path": "/health", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "text/plain", "example": "string" }, - { "route": "GET /pets/{pet_id}/photos", "method": "GET", "path": "/pets/{pet_id}/photos", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/json", "example": {"items": [{"id": "string"}], "total": 1} }, - { "route": "POST /pets/{pet_id}/photos", "method": "POST", "path": "/pets/{pet_id}/photos", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["multipart/form-data"] }, "status": 201, "media": "application/json", "example": {"id": "string"} }, - { "route": "GET /pets/{pet_id}/photos/{photo_id}/raw", "method": "GET", "path": "/pets/{pet_id}/photos/{photo_id}/raw", "query": [], "headers": [], "cookies": [], "body": null, "status": 200, "media": "application/octet-stream", "example": null }, + { "route": "GET /pets", "method": "GET", "path": "/pets", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"data": [{"id": "string", "name": "string"}], "next_page_token": "string", "has_more": false} }, + { "route": "POST /pets", "method": "POST", "path": "/pets", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["application/json"] }, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 201, "media": "application/json", "example": {"id": "string", "name": "string"} }, + { "route": "GET /pets/{pet_id}", "method": "GET", "path": "/pets/{pet_id}", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"id": "string", "name": "string"} }, + { "route": "PATCH /pets/{pet_id}", "method": "PATCH", "path": "/pets/{pet_id}", "query": [], "headers": [], "cookies": [], "body": { "required": false, "media": ["application/merge-patch+json"] }, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"id": "string", "name": "string"} }, + { "route": "DELETE /pets/{pet_id}", "method": "DELETE", "path": "/pets/{pet_id}", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 204, "media": null, "example": null }, + { "route": "GET /owners", "method": "GET", "path": "/owners", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": [{"login": "string"}] }, + { "route": "GET /users", "method": "GET", "path": "/users", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"data": [{"id": "string"}], "has_more": false} }, + { "route": "GET /pages", "method": "GET", "path": "/pages", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"items": ["string"], "total_pages": 1} }, + { "route": "GET /tags", "method": "GET", "path": "/tags", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"tags": ["string"]} }, + { "route": "GET /events", "method": "GET", "path": "/events", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "text/event-stream", "example": "string" }, + { "route": "GET /health", "method": "GET", "path": "/health", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "text/plain", "example": "string" }, + { "route": "GET /pets/{pet_id}/photos", "method": "GET", "path": "/pets/{pet_id}/photos", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"items": [{"id": "string"}], "total": 1} }, + { "route": "POST /pets/{pet_id}/photos", "method": "POST", "path": "/pets/{pet_id}/photos", "query": [], "headers": [], "cookies": [], "body": { "required": true, "media": ["multipart/form-data"] }, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 201, "media": "application/json", "example": {"id": "string"} }, + { "route": "GET /pets/{pet_id}/photos/{photo_id}/raw", "method": "GET", "path": "/pets/{pet_id}/photos/{photo_id}/raw", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "ApiKeyAuth", "kind": "apiKey", "in": "header", "name": "x-api-key" }], [{ "scheme": "BearerAuth", "kind": "bearer" }]], "status": 200, "media": "application/octet-stream", "example": null }, ] + +// The token endpoints of the client credentials flows, by path. +export const tokens = [] diff --git a/crates/flowapi-sdk/tests/repo/shop/mock/server.mjs b/crates/flowapi-sdk/tests/repo/shop/mock/server.mjs index 126454e..07c6fa6 100644 --- a/crates/flowapi-sdk/tests/repo/shop/mock/server.mjs +++ b/crates/flowapi-sdk/tests/repo/shop/mock/server.mjs @@ -2,17 +2,20 @@ // // The API's mock server, on node:http with no dependency, answering by the routes printed from // the description beside it (routes.mjs). It is strict where a client goes wrong: a path no -// operation has is a 404, a method the path has not a 405, a required query parameter, header, -// cookie or body that is missing a 400, a body of a media type the operation does not take a -// 415. Otherwise it answers with the operation's first success status and an example value of -// its schema (the schema's example, else its default, its first enum value, else one made from -// its type and format). Each request answered is recorded, with the route it matched. +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). // // `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL // names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. import { createServer } from 'node:http' import { pathToFileURL } from 'node:url' -import routes from './routes.mjs' +import routes, { tokens } from './routes.mjs' /** A route's path as a regular expression: each `{name}` is one segment. */ function pattern(path) { @@ -69,6 +72,67 @@ function hasQuery(url, name) { return false } +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + /** What is wrong with a request for its route, with the status that says so; null for nothing. */ function problem(route, url, req, body) { for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] @@ -123,6 +187,7 @@ function handle(req, res, requests) { req.on('end', () => { const body = Buffer.concat(chunks) const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) const matches = table.filter((r) => r.regex.test(url.pathname)) if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) const route = matches.find((r) => r.method === req.method) @@ -130,6 +195,12 @@ function handle(req, res, requests) { const methods = matches.map((r) => r.method).join(', ') return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } const wrong = problem(route, url, req, body) if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) diff --git a/crates/flowapi-sdk/tests/repo/shop/package.json b/crates/flowapi-sdk/tests/repo/shop/package.json index 6dada5f..9283ac3 100644 --- a/crates/flowapi-sdk/tests/repo/shop/package.json +++ b/crates/flowapi-sdk/tests/repo/shop/package.json @@ -1,7 +1,8 @@ { "name": "@shop/sdk", "version": "1.2.0", - "description": "A TypeScript client of the Shop API", + "description": "TypeScript SDK for the Shop API. Sells pets and their photos.", + "keywords": ["pets", "shop"], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/shop/sdk" }, "type": "module", diff --git a/crates/flowapi-sdk/tests/repo/shop/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/shop/tests/auth.test.mjs new file mode 100644 index 0000000..8cde7b5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/shop/tests/auth.test.mjs @@ -0,0 +1,37 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Shop } from "@shop/sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Shop({ baseURL: server.url, apiKeyAuth: 'test-credential', bearerAuth: 'test-credential', maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("ApiKeyAuth: sent by pets.list", async () => { + await client.pets.list() + const r = last() + if (r === null) return + assert.equal(r.headers["x-api-key"], 'test-credential') +}) + +test("no credential: system.health needs none", async () => { + const none = new Shop({ baseURL: server.url, maxRetries: 0, apiKeyAuth: null, bearerAuth: null }) + await none.system.health() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, undefined) + assert.equal(r.headers["x-api-key"], undefined) +}) diff --git a/crates/flowapi-sdk/tests/repo/swagger/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/swagger/.flowapi/lock.json new file mode 100644 index 0000000..1a55427 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/.flowapi/lock.json @@ -0,0 +1,53 @@ +{ + "version": 1, + "flowapi": "0.3.0", + "spec_sha256": "2bcbfe3037359119aea489abd7435aa38bbc13c39a1f22388a1996b4a45e7cdb", + "config_sha256": "ed2e44682f5b8fcc27c2b22ebe59d1ee803b42d4f2ff313eccb9a87f437895b3", + "configured_endpoints": 4, + "files": { + ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", + ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", + "LICENSE": "d1b3d7282d1e2a6d5d81dc97bf965dd8f8bef6e510b734e2bfcd7902adbc0a7f", + "README.md": "4f28338c527c097b3451e4032196d648ecdcf30c1150a928c2a3db9bf1776e5d", + "api.md": "51a938204ea03fc5f4bae5d9c87e26e8829dd5d3c3e48e09c7aa0d33db5c245a", + "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mock/routes.mjs": "ad378dfe37822f3b6996b175662bfd59aab02492a133a596548a826dc066598b", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "c964fe2b1bd20eded10f223e807d031ff054a7b3c6d0e1af185d80cc16d89d34", + "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", + "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", + "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", + "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", + "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", + "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", + "src/api.ts": "458ff19389045e0b768ffaccfc0887c21615f3ffe32698db6a98b56419798d73", + "src/client.ts": "eb660d9e742fab655f1fb0aa5f796d6ca30a0e91843a3771b29178661c04003a", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", + "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", + "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", + "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", + "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "5ecaedfd7b11f6ed5395d8cabadbed96ee68f7cc02eaea99fd2f1c247b61be04", + "src/resources/health.ts": "c5df11ca6c304a6321f80c931468d7569b87f06d4083d142dd3ca955713ac404", + "src/resources/pets.ts": "affebb2695d7b421e16a17a4b1c100c95aac92798f8f235b6e0f3222baa117e3", + "tests/api-resources/health.test.mjs": "d711e5397aeadf3a4f5b3e30c8947907f82013f4246a9edffeed09229364ef6a", + "tests/api-resources/pets.test.mjs": "b6e253abd5671d2a3d908285470f15568da0397500a83c7344005892d2493a56", + "tests/auth.test.mjs": "6e628973cab98c75be59554b07dd928de6c75b75f4c01cb3d3aa98fde3a28bcd", + "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", + "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", + "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", + "tsconfig.json": "8f8513b3a8e2fc81d06a2f3b0057d1e2881ca78722bd4b704766f0ad27ab7498" + }, + "names": {} +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/.github/workflows/ci.yml b/crates/flowapi-sdk/tests/repo/swagger/.github/workflows/ci.yml new file mode 100644 index 0000000..e31da6b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: npm install --no-audit --no-fund + - run: scripts/check diff --git a/crates/flowapi-sdk/tests/repo/swagger/.gitignore b/crates/flowapi-sdk/tests/repo/swagger/.gitignore new file mode 100644 index 0000000..6c15117 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/.gitignore @@ -0,0 +1,4 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +node_modules/ +dist/ +*.tgz diff --git a/crates/flowapi-sdk/tests/repo/swagger/.release-please-manifest.json b/crates/flowapi-sdk/tests/repo/swagger/.release-please-manifest.json new file mode 100644 index 0000000..466df71 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/AGENTS.md b/crates/flowapi-sdk/tests/repo/swagger/AGENTS.md new file mode 100644 index 0000000..1ca1d14 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/AGENTS.md @@ -0,0 +1,57 @@ + + +# AGENTS.md + +This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. + +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + +## What is generated + +Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: + +```sh +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . +``` + +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | + +## What is yours + +- `src/lib/` and `examples/`: generate writes a file there only while it is unchanged, and never overwrites one you changed. +- `CHANGELOG.md` and `.release-please-manifest.json`: written on the first generation, then the release tool's. +- Every file the lock does not list: generate never touches it. + +## Commands + +```sh +npm install # TypeScript, the one development dependency +scripts/check # everything: lint, build, the built types, the tests +scripts/build # dist/esm and dist/cjs, then both loaded by the package's name +scripts/lint # the types, no node: module in the client, the tests parsed +scripts/test # node --test over tests/, against the mock server each file starts +scripts/mock # the mock server on port 4010, for trying the client by hand +``` + +The mock (`mock/routes.mjs`) answers each operation with an example of its schema and refuses a request its operation would refuse: a wrong path or method, a missing parameter, a body of another media type. Set `TEST_API_BASE_URL` to run the tests against another server. + +## Releases + +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/swagger/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/swagger/CHANGELOG.md new file mode 100644 index 0000000..0430207 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +Each release of `swagger-sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/swagger/LICENSE b/crates/flowapi-sdk/tests/repo/swagger/LICENSE new file mode 100644 index 0000000..c1d2413 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) The swagger-sdk authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/flowapi-sdk/tests/repo/swagger/README.md b/crates/flowapi-sdk/tests/repo/swagger/README.md new file mode 100644 index 0000000..2f6a31e --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/README.md @@ -0,0 +1,127 @@ + + +# Swagger TypeScript SDK + +TypeScript SDK for the Swagger API. + +The `Swagger` client is generated by flowapi from the API's description: 4 methods in 2 resources, each listed in [api.md](api.md) with its parameters and what it returns. + +## Install + +```sh +npm install swagger-sdk +``` + +## Usage + +```ts +import { Swagger } from 'swagger-sdk' + +const client = new Swagger() + +const result = await client.pets.list() +console.log(result) +``` + +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.pets.list().withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { Swagger } = require('swagger-sdk')`; `import Swagger from 'swagger-sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.health`](api.md#clienthealth) | 1 | +| [`client.pets`](api.md#clientpets) | 3 | + +## Authentication + +| Scheme | Kind | Sent as | Option | Environment variables | +| --- | --- | --- | --- | --- | +| `basic` | HTTP basic | `Authorization: Basic ` | `basic`: `{ username, password }` (a user-id without `:`) | `SWAGGER_BASIC`: `username:password` | +| `header` | API key | the header `X-Key` | `header`: the key | `SWAGGER_HEADER_KEY`: the key | +| `query` | API key | the query parameter `key` | `query`: the key | `SWAGGER_QUERY_KEY`: the key | +| `app` | OAuth 2.0 client credentials | `Authorization: Bearer `, the token requested at `https://swagger.example/oauth/token` for the scopes the operation needs | `app`: a token, or `{ clientId, clientSecret }` to request one | `SWAGGER_CLIENT_ID`: the client's id; `SWAGGER_CLIENT_SECRET`: its secret | + +An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them. + +A token of OAuth 2.0's client credentials grant is requested at the token URL (relative to the base URL where it is relative) with the client's id and secret in HTTP basic, cached until a little before it expires, shared by the calls that wait for it, and requested again once when the API answers 401. A refusal of the token endpoint throws `TokenError` with its `error` and `description`. + +```ts +const client = new Swagger({ basic: { username: '…', password: '…' }, header: '…', query: '…', app: { clientId: '…', clientSecret: '…' } }) +``` + +## Errors + +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. + +```ts +import { APIError } from 'swagger-sdk' + +try { + await client.pets.list() +} catch (error) { + if (error instanceof APIError) console.log(error.status, error.body) + else throw error +} +``` + +## Retries and timeouts + +No request is retried by default (`maxRetries: 0`): each is sent once. With `maxRetries` set, a request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. A retry that failed is tried again while `maxRetries` allows. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 60 s, the error is thrown at once. Each attempt may take 60 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: + +```ts +const patient = new Swagger({ maxRetries: 5, timeout: 120_000 }) +await client.pets.list({}, { maxRetries: 0, timeout: 5_000 }) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `SWAGGER_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new Swagger({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: + +```ts +const response = await client.request('GET', '/').asResponse() +console.log(response.status) +``` + +## Requirements + +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. + +## Development + +```sh +npm install +scripts/check # lint, build, the built types, the tests against the mock server +``` + +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/swagger/api.md b/crates/flowapi-sdk/tests/repo/swagger/api.md new file mode 100644 index 0000000..fcd8f7a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/api.md @@ -0,0 +1,23 @@ + + +# API + +Every method of `Swagger`, by resource: 4 methods in 2 resources. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: + +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from 'swagger-sdk' +``` + +## client.health + +- `client.health.get(params?: Input, options?: RequestOptions): ApiCall>` + `GET /health` + +## client.pets + +- `client.pets.list(params?: Input, options?: RequestOptions): ApiCall>` + `GET /pets` +- `client.pets.add(params?: Input, options?: RequestOptions): ApiCall>` + `POST /pets` +- `client.pets.mine(params?: Input, options?: RequestOptions): ApiCall>` + `GET /pets/mine` diff --git a/crates/flowapi-sdk/tests/repo/swagger/examples/.keep b/crates/flowapi-sdk/tests/repo/swagger/examples/.keep new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/swagger/issues.txt b/crates/flowapi-sdk/tests/repo/swagger/issues.txt new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/swagger/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/swagger/mock/routes.mjs new file mode 100644 index 0000000..bdb992a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/mock/routes.mjs @@ -0,0 +1,13 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The operations the client calls, as the mock server answers them (server.mjs). + +export default [ + { "route": "GET /pets", "method": "GET", "path": "/pets", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "basic", "kind": "basic" }]], "status": 200, "media": "application/json", "example": {} }, + { "route": "POST /pets", "method": "POST", "path": "/pets", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "header", "kind": "apiKey", "in": "header", "name": "x-key" }], [{ "scheme": "query", "kind": "apiKey", "in": "query", "name": "key" }]], "status": 200, "media": "application/json", "example": {} }, + { "route": "GET /pets/mine", "method": "GET", "path": "/pets/mine", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "app", "kind": "bearer", "flow": true }]], "status": 200, "media": "application/json", "example": {} }, + { "route": "GET /health", "method": "GET", "path": "/health", "query": [], "headers": [], "cookies": [], "body": null, "security": [], "status": 200, "media": "application/json", "example": {} }, +] + +// The token endpoints of the client credentials flows, by path. +export const tokens = ["/oauth/token"] diff --git a/crates/flowapi-sdk/tests/repo/swagger/mock/server.mjs b/crates/flowapi-sdk/tests/repo/swagger/mock/server.mjs new file mode 100644 index 0000000..07c6fa6 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/mock/server.mjs @@ -0,0 +1,237 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The API's mock server, on node:http with no dependency, answering by the routes printed from +// the description beside it (routes.mjs). It is strict where a client goes wrong: a path no +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). +// +// `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL +// names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. +import { createServer } from 'node:http' +import { pathToFileURL } from 'node:url' +import routes, { tokens } from './routes.mjs' + +/** A route's path as a regular expression: each `{name}` is one segment. */ +function pattern(path) { + const parts = path + .split(/(\{[^}/]+\})/) + .map((p) => (/^\{[^}/]+\}$/.test(p) ? '([^/]+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))) + return new RegExp(`^${parts.join('')}$`) +} + +/** Each segment of a path by how specific it is: 2 literal, 1 a template beside text, 0 a template. */ +const ranks = (path) => path.split('/').map((s) => (!s.includes('{') ? 2 : /^\{[^}/]+\}$/.test(s) ? 0 : 1)) + +/** + * The more specific route first (OpenAPI's Paths Object matches a concrete path before a templated + * one): at the first segment where the two differ in kind, the more literal one; then the shorter + * path, which never matches the same URL. Routes as specific as each other are ambiguous by the + * specification and keep the order of routes.mjs (the client's resources and methods). + */ +function specific(a, b) { + const x = ranks(a.path) + const y = ranks(b.path) + const i = x.findIndex((r, n) => r !== y[n]) + if (i === -1 || i >= y.length) return x.length - y.length + return y[i] - x[i] +} + +// Sorted once, stably: a request takes the first route that matches its path and method. +const table = routes.map((r) => ({ ...r, regex: pattern(r.path) })).sort(specific) + +/** A media type without its parameters, in lower case. */ +const bare = (type) => (type ?? '').split(';')[0].trim().toLowerCase() + +// Whether a media range (`image/png`, `image/*`, `*/*`) takes a media type. +function takes(range, type) { + const r = bare(range) + if (r === '*/*') return true + if (r.endsWith('/*')) return type.startsWith(r.slice(0, -1)) + return r === type +} + +/** The names of a Cookie header's cookies. */ +function cookieNames(header) { + const names = new Set() + for (const part of (header ?? '').split(';')) { + const name = part.split('=')[0].trim() + if (name !== '') names.add(name) + } + return names +} + +/** Whether the query has a parameter: by its name, or as `name[...]` for an object's members. */ +function hasQuery(url, name) { + for (const key of url.searchParams.keys()) if (key === name || key.startsWith(`${name}[`)) return true + return false +} + +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + +/** What is wrong with a request for its route, with the status that says so; null for nothing. */ +function problem(route, url, req, body) { + for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] + for (const name of route.headers) if (req.headers[name] === undefined) return [400, `the header ${name} is required`] + const jar = cookieNames(req.headers.cookie) + for (const name of route.cookies) if (!jar.has(name)) return [400, `the cookie ${name} is required`] + if (body.length === 0) return route.body?.required ? [400, 'the operation requires a body'] : null + if (route.body === null) return [400, 'the operation takes no body'] + const type = bare(req.headers['content-type']) + if (!route.body.media.some((m) => takes(m, type))) { + return [415, `the body's media type ${type || '(none)'} is not one of ${route.body.media.join(', ')}`] + } + if (type === 'application/json' || type.endsWith('+json')) { + try { + JSON.parse(body.toString('utf8')) + } catch { + return [400, 'the body is not JSON'] + } + } + return null +} + +function fail(res, status, message) { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: message })) +} + +/** The route's answer: its status, and its example in its media type. */ +function answer(res, route) { + if (route.media === null || [204, 205, 304].includes(route.status)) { + res.writeHead(route.status) + res.end() + return + } + const media = route.media.includes('*') ? 'application/octet-stream' : route.media + const type = bare(media) + const json = JSON.stringify(route.example) + const text = typeof route.example === 'string' ? route.example : json + let body + if (type === 'text/event-stream') body = `data: ${text}\n\n` + else if (type === 'application/x-ndjson' || type === 'application/jsonl') body = `${json}\n` + else if (type === 'application/json' || type.endsWith('+json')) body = json + else if (type.startsWith('text/') || type.endsWith('+xml') || type === 'application/xml') body = text + else body = Buffer.from([1, 2, 3]) + res.writeHead(route.status, { 'content-type': media }) + res.end(body) +} + +function handle(req, res, requests) { + const chunks = [] + req.on('data', (c) => chunks.push(c)) + req.on('end', () => { + const body = Buffer.concat(chunks) + const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) + const matches = table.filter((r) => r.regex.test(url.pathname)) + if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) + const route = matches.find((r) => r.method === req.method) + if (route === undefined) { + const methods = matches.map((r) => r.method).join(', ') + return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) + } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } + const wrong = problem(route, url, req, body) + if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) + requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) + answer(res, route) + }) +} + +/** + * Starts the mock server on `port` (0, the default, for a free one) of 127.0.0.1. Resolves to its + * `url`, the `requests` it answered and `close()`. When TEST_API_BASE_URL is set it starts nothing: + * `url` is that address and `requests` is null. + */ +export async function mock({ port = 0 } = {}) { + const external = process.env.TEST_API_BASE_URL + if (external) return { url: external.replace(/\/+$/, ''), requests: null, close: async () => {} } + const requests = [] + const server = createServer((req, res) => handle(req, res, requests)) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, '127.0.0.1', resolve) + }) + const close = () => + new Promise((resolve) => { + server.close(() => resolve()) + server.closeAllConnections() + }) + return { url: `http://127.0.0.1:${server.address().port}`, requests, close } +} + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + const port = Number(process.argv[2] ?? 4010) + const { url } = await mock({ port }) + console.log(`the mock server answers at ${url}`) +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/package.json b/crates/flowapi-sdk/tests/repo/swagger/package.json new file mode 100644 index 0000000..5a6cd25 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/package.json @@ -0,0 +1,26 @@ +{ + "name": "swagger-sdk", + "version": "0.1.0", + "description": "TypeScript SDK for the Swagger API.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "engines": { "node": ">=20" }, + "main": "./dist/cjs/index.js", + "types": "./dist/cjs/index.d.ts", + "exports": { + ".": { + "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, + "require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" } + }, + "./package.json": "./package.json" + }, + "files": ["dist"], + "scripts": { + "build": "scripts/build", + "lint": "scripts/lint", + "test": "scripts/test", + "check": "scripts/check" + }, + "devDependencies": { "typescript": "7.0.2" } +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/release-please-config.json b/crates/flowapi-sdk/tests/repo/swagger/release-please-config.json new file mode 100644 index 0000000..897e118 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/release-please-config.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "node", + "include-v-in-tag": true, + "bump-minor-pre-major": true, + "changelog-path": "CHANGELOG.md", + "extra-files": [{ "type": "yaml", "path": "flowapi-sdk.yml", "jsonpath": "$.package.version" }] + } + } +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/scripts/build b/crates/flowapi-sdk/tests/repo/swagger/scripts/build new file mode 100644 index 0000000..6dd941a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/scripts/build @@ -0,0 +1,21 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The package built twice from src/ by tsc alone: ES modules into dist/esm, CommonJS into +# dist/cjs, each with its declarations; then loaded by its own name with require and import, as +# a user loads it. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/build: $tsc is missing: run npm install first" >&2 + exit 1 +fi +rm -rf dist +"$tsc" -p tsconfig.build.json +"$tsc" -p tsconfig.cjs.json +printf '{ "type": "commonjs" }\n' > dist/cjs/package.json +name=$(node -p 'require("./package.json").name') +# CommonJS: the module, its client class both `default` and by its name, as the README takes it. +node -e 'const m = require(process.argv[1]); if (typeof m.default !== "function" || m[m.default.name] !== m.default) throw new Error("require(" + process.argv[1] + ") gives no client class by its name")' "$name" +node --input-type=module -e 'const m = await import(process.argv[1]); if (typeof m.default !== "function") throw new Error("import(" + process.argv[1] + ") gives no client class")' "$name" diff --git a/crates/flowapi-sdk/tests/repo/swagger/scripts/check b/crates/flowapi-sdk/tests/repo/swagger/scripts/check new file mode 100644 index 0000000..e0be85d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/scripts/check @@ -0,0 +1,11 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Everything a change must pass: lint, the build, the built declarations type-checked on their +# own (skipLibCheck off), the tests. +set -eu +cd "$(dirname "$0")/.." +scripts/lint +scripts/build +node_modules/.bin/tsc -p tsconfig.dist.json +SDK_BUILT=1 scripts/test diff --git a/crates/flowapi-sdk/tests/repo/swagger/scripts/lint b/crates/flowapi-sdk/tests/repo/swagger/scripts/lint new file mode 100644 index 0000000..7126bd5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/scripts/lint @@ -0,0 +1,22 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The sources type-checked; no node: module in the generated client, which runs wherever fetch +# does; the mock server and the tests parsed. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/lint: $tsc is missing: run npm install first" >&2 + exit 1 +fi +"$tsc" -p tsconfig.json +found=$(find src -name '*.ts' ! -path 'src/lib/*' -exec grep -l -e 'from "node:' -e "from 'node:" {} + || true) +if [ -n "$found" ]; then + echo "scripts/lint: a node: module is imported by the client, which must run without Node:" >&2 + echo "$found" >&2 + exit 1 +fi +for f in mock/*.mjs $(find tests -name '*.mjs' | sort); do + node --check "$f" +done diff --git a/crates/flowapi-sdk/tests/repo/swagger/scripts/mock b/crates/flowapi-sdk/tests/repo/swagger/scripts/mock new file mode 100644 index 0000000..c7fad1c --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/scripts/mock @@ -0,0 +1,7 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The mock server on a port (4010 unless given), until stopped: for trying the client by hand. +set -eu +cd "$(dirname "$0")/.." +exec node mock/server.mjs "${1:-4010}" diff --git a/crates/flowapi-sdk/tests/repo/swagger/scripts/test b/crates/flowapi-sdk/tests/repo/swagger/scripts/test new file mode 100644 index 0000000..d78cf2a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/scripts/test @@ -0,0 +1,19 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Every test of tests/ by node --test, against the mock server each test file starts on a free +# port (or against TEST_API_BASE_URL when it is set). The package is built first, unless +# SDK_BUILT=1 says it was just built. +set -eu +cd "$(dirname "$0")/.." +if [ "${SDK_BUILT:-}" != 1 ]; then + scripts/build +fi +files=$(find tests -name '*.test.mjs' | sort) +if [ -z "$files" ]; then + echo "scripts/test: no tests under tests/" >&2 + exit 1 +fi +# The files one by one as arguments: every Node from 20 reads them so, globs or not. +# shellcheck disable=SC2086 +node --test $files diff --git a/crates/flowapi-sdk/tests/repo/swagger/tests/api-resources/health.test.mjs b/crates/flowapi-sdk/tests/repo/swagger/tests/api-resources/health.test.mjs new file mode 100644 index 0000000..7c85542 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tests/api-resources/health.test.mjs @@ -0,0 +1,23 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `health` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Swagger } from "swagger-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Swagger({ baseURL: server.url, basic: { username: 'user', password: 'pass' }, header: 'test-credential', query: 'test-credential', app: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("health.get: GET /health", async () => { + await client.health.get() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /health") +}) diff --git a/crates/flowapi-sdk/tests/repo/swagger/tests/api-resources/pets.test.mjs b/crates/flowapi-sdk/tests/repo/swagger/tests/api-resources/pets.test.mjs new file mode 100644 index 0000000..7a00cd4 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tests/api-resources/pets.test.mjs @@ -0,0 +1,33 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `pets` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Swagger } from "swagger-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Swagger({ baseURL: server.url, basic: { username: 'user', password: 'pass' }, header: 'test-credential', query: 'test-credential', app: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +test("pets.list: GET /pets", async () => { + await client.pets.list() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /pets") +}) + +test("pets.add: POST /pets", async () => { + await client.pets.add() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "POST /pets") +}) + +test("pets.mine: GET /pets/mine", async () => { + await client.pets.mine() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /pets/mine") +}) diff --git a/crates/flowapi-sdk/tests/repo/swagger/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/swagger/tests/auth.test.mjs new file mode 100644 index 0000000..bdd58e3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tests/auth.test.mjs @@ -0,0 +1,53 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Swagger } from "swagger-sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Swagger({ baseURL: server.url, basic: { username: 'user', password: 'pass' }, header: 'test-credential', query: 'test-credential', app: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("basic: sent by pets.list", async () => { + await client.pets.list() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, `Basic ${Buffer.from('user:pass').toString('base64')}`) +}) + +test("header: sent by pets.add", async () => { + await client.pets.add() + const r = last() + if (r === null) return + assert.equal(r.headers["x-key"], 'test-credential') +}) + +test("app: sent by pets.mine", async () => { + await client.pets.mine() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer mock-token') + assert.ok(server.requests.some((q) => q.route === 'token'), 'the token was requested of the mock') +}) + +test("no credential: health.get needs none", async () => { + const none = new Swagger({ baseURL: server.url, maxRetries: 0, basic: null, header: null, query: null, app: null }) + await none.health.get() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, undefined) + assert.equal(r.headers["x-key"], undefined) + assert.equal(new URL(r.url, 'http://mock.invalid').searchParams.has("key"), false) +}) diff --git a/crates/flowapi-sdk/tests/repo/swagger/tsconfig.build.json b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.build.json new file mode 100644 index 0000000..6034cd3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "rootDir": "src", + "outDir": "dist/esm" + } +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/tsconfig.cjs.json b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.cjs.json new file mode 100644 index 0000000..cae8db8 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.build.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs" + } +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/tsconfig.dist.json b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.dist.json new file mode 100644 index 0000000..f52d18a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.dist.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "skipLibCheck": false, + "noEmit": true + }, + "include": ["dist/**/*.d.ts"] +} diff --git a/crates/flowapi-sdk/tests/repo/swagger/tsconfig.json b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.json new file mode 100644 index 0000000..9ee3b9b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/swagger/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "rootDir": "src", + "noEmit": true + }, + "include": ["src"] +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/.flowapi/lock.json b/crates/flowapi-sdk/tests/repo/tokens/.flowapi/lock.json new file mode 100644 index 0000000..7c0b925 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/.flowapi/lock.json @@ -0,0 +1,53 @@ +{ + "version": 1, + "flowapi": "0.3.0", + "spec_sha256": "f313787d6956e208bbc209a7e20aedf49a3900d60bb4841a6047b861d8b495d8", + "config_sha256": "245de3e0614fd6ce90a62a22d07f89e5163caeec8e610eb8129f27e534cde0e3", + "configured_endpoints": 9, + "files": { + ".github/workflows/ci.yml": "319d85a3444b69e1e1b131745159c0b6f90c817a1b79995cb4e1a6f319d7f907", + ".gitignore": "e36fab51e2c0e068b3d45372618aad54844c6df08f80714b20d8dc4855363e0a", + "AGENTS.md": "4bada00a97dd22a645d53a39b06e0e5fca9881c2ac47cd62fdfe38d5c6e6aa6b", + "LICENSE": "b1655bfec026cbec1a095aaf6a999321004f6381f5cf7cdd051bf51d1fc8ca49", + "README.md": "8150cc9153b97a6587c6369d7170c8a3a877586a601d1f42f88a1babfb1f4f2f", + "api.md": "214cb17c3497b168a312c97003407307bdf66bd08a7ced2226ede7129fa4cb4f", + "examples/.keep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mock/routes.mjs": "e96716aa9cb1e925322e24fe1cb6887d7aed5db41ab643c7e96cea9a6dd092e4", + "mock/server.mjs": "2120b1ee35f72c04990c63f4543c3aaa13767f39a3053525dd315d4dc4560e03", + "package.json": "f89fb69ccc9ee0cafc7d3fda717e9b9a355d192c063c75253d917ce7e9fee287", + "release-please-config.json": "61715a1506b46e9e85c37bae4776acb71026d18a747084ab02713b556d0f6a06", + "scripts/build": "005b9d53d7ef68915b4fe807c39e6041f514905a4cb3749f416719b2aea329d0", + "scripts/check": "61ff2f685a621caf0ca368807c86af911a04a680217d67e1c8e2e2e8766fac29", + "scripts/lint": "780bf10052bb3fd55d3a9ccc55e428b553b1cbedd1e64e848e64c22ffdb68163", + "scripts/mock": "e50dfc2cd67f9177e3ca7d1098d34cbb54bdb06797f770d10a8e66d7753c13a5", + "scripts/test": "62a1d9b8fa147a3c9a5598a25d1b8c5453ebeac5e464c72ef6b051412ef4152b", + "src/api.ts": "e983aae6d9b240bfdaf3361b23d778a662b7fee48880b6fb2095be6b799c9ff1", + "src/client.ts": "5ce252887a30b5f9c6d528c7f638f939c7bfce9b1bb4f9ef26d9bafce8ce2ce0", + "src/core/auth.ts": "89558744d4b0860fed96696896458f20299dc687652f0780c88fb994d148b2e0", + "src/core/call.ts": "9b716346a364857728fb90fc7704d5d7b029bfea33e4e51f8e6a107b986e9bc7", + "src/core/calls.ts": "815c9930791b346cff1dd11492d837ed7756c68612008e2a526af35c50e63c7f", + "src/core/core.ts": "6d1f617c66fd99298aee50e75558cf747abebd7315e653cb15987b6556ec457d", + "src/core/errors.ts": "bffda178858ac5e8873b209029cf74582f18ee1ba9aa8cf42245bda5280e3706", + "src/core/index.ts": "107ccb83d1d4aa015d71e72b5e7623c9a34a75c553f7eadf32da7ec752d43f55", + "src/core/log.ts": "9f611e2bfd2b065988d6a13b88a3f476bf1b8e154671a582f6f619c12b6c742d", + "src/core/pagination.ts": "8d9c1e3d0374e92f11045458ef03ce4a8a2a23479ffeba74ca5a0b3b796aa737", + "src/core/platform.ts": "66389d001f7f71045b4cd92d3d7946d785b9ddee6f93cdc9dbbcb6a0e760fbff", + "src/core/request.ts": "a264ff805223cc1ca101b4bbafe3f9c93b33fc41502179e4a470f5bce930a535", + "src/core/retry.ts": "9fa07a861101cab26c1d649d4fc7beb2c246bbb015b49779ac5a62a486691c4e", + "src/core/send.ts": "99aac7354ffd4518a9bad6c587aaa4b43ab2068f87d422faf5d4374c4b82c7ae", + "src/core/servers.ts": "6b55e3cbc459ce8862ab508e481174b57cc0e86b00ebbd7c16cc86b478c9a70f", + "src/core/streaming.ts": "0f306c364e148ff72b673df528740935873c896fa896ab90ac50cb62ee1dbe58", + "src/core/token.ts": "9c546a8598dd863bc9a1cbb02a3391570c40c86878a16541c2e6248c73ed1ab9", + "src/index.ts": "a3d2405273accf9bba72ab33d3b9ce0af840736d26fc1a0abd564581e3421c1d", + "src/resources/others.ts": "0b184aa9166aabd1e3f0686cece512e80255bd87dc6ae8de6b6e780bbd9c57d3", + "src/resources/things.ts": "c09d8a9e7cdecf8d426e7413dd1f70799f3dc3fff70f8806bb392c18825e5abd", + "tests/api-resources/others.test.mjs": "08a604b5a5bf3ed46eb8b04fdccc3f58cc945ad62cbd8cd20e40fbe2e8463d7e", + "tests/api-resources/things.test.mjs": "7eee902b5a7eecc46106cddfd21caab58acce991c7263048fd2c510a9afd7a8f", + "tests/auth.test.mjs": "9c44920aedb4bc0dbba799a7ecb2eadd189e0a2b761e351844327302e16d0da0", + "tsconfig.build.json": "ac87e35b1e5b5b1a87f4c36b86c3973f6fb47e97aa00bfea157782a03d1be5df", + "tsconfig.cjs.json": "c9fb71cc1b6f79d307fee4d8c4fbc4cac59676e312b6d941452ae5a1cca7a220", + "tsconfig.dist.json": "87c76b8736b62f08151e2c47d8a383e66249e6d3b684da8ebcae8102081f2091", + "tsconfig.json": "8f8513b3a8e2fc81d06a2f3b0057d1e2881ca78722bd4b704766f0ad27ab7498" + }, + "names": {} +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/.github/workflows/ci.yml b/crates/flowapi-sdk/tests/repo/tokens/.github/workflows/ci.yml new file mode 100644 index 0000000..e31da6b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. + +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + node: [20, 22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: npm install --no-audit --no-fund + - run: scripts/check diff --git a/crates/flowapi-sdk/tests/repo/tokens/.gitignore b/crates/flowapi-sdk/tests/repo/tokens/.gitignore new file mode 100644 index 0000000..6c15117 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/.gitignore @@ -0,0 +1,4 @@ +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +node_modules/ +dist/ +*.tgz diff --git a/crates/flowapi-sdk/tests/repo/tokens/.release-please-manifest.json b/crates/flowapi-sdk/tests/repo/tokens/.release-please-manifest.json new file mode 100644 index 0000000..466df71 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "0.1.0" +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/AGENTS.md b/crates/flowapi-sdk/tests/repo/tokens/AGENTS.md new file mode 100644 index 0000000..1ca1d14 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/AGENTS.md @@ -0,0 +1,57 @@ + + +# AGENTS.md + +This repository is a TypeScript SDK generated by flowapi from `flowapi-sdk.yml` and the API description its `spec` names. + +## Where things are + +- `src/client.ts`: the client class and its options; `src/resources/`: a class per resource, a method per operation; `src/api.ts`: the types and each operation's request and response; `src/core/`: the runtime (sending, retries, errors, pagination, streams). +- `mock/`: the mock server the tests run against; `tests/api-resources/`: a test per resource. +- `README.md` and `api.md`: the package's documentation, every method in `api.md`. + +## What is generated + +Every file listed under `files` in `.flowapi/lock.json`, with the hash of what was written. Do not edit one: change `flowapi-sdk.yml` (or the description) and generate again: + +```sh +npx -y @localix-ai/flowapi@0.3.0 config check flowapi-sdk.yml # every issue at once +npx -y @localix-ai/flowapi@0.3.0 generate flowapi-sdk.yml --out . +``` + +A generated file changed by hand is a conflict: generate names it, stops and writes nothing. A file generated before and no longer generated is deleted, unless it was changed. + +## Changing the SDK + +| To change | Edit in `flowapi-sdk.yml` | +| --- | --- | +| A method's name, or which resource it is in | `resources..methods` | +| An operation left out, with why | `skip` | +| The base URLs | `environments` | +| Retries, the timeout, the default pagination | `defaults` | +| How a list pages | `pagination`, and a method's `pagination` | +| The README's heading, first paragraph and examples | `readme.title`, `readme.intro`, `readme.headline_method`, `readme.pagination_method` | +| `package.json`'s description and keywords | `package.description`, `package.keywords` | + +## What is yours + +- `src/lib/` and `examples/`: generate writes a file there only while it is unchanged, and never overwrites one you changed. +- `CHANGELOG.md` and `.release-please-manifest.json`: written on the first generation, then the release tool's. +- Every file the lock does not list: generate never touches it. + +## Commands + +```sh +npm install # TypeScript, the one development dependency +scripts/check # everything: lint, build, the built types, the tests +scripts/build # dist/esm and dist/cjs, then both loaded by the package's name +scripts/lint # the types, no node: module in the client, the tests parsed +scripts/test # node --test over tests/, against the mock server each file starts +scripts/mock # the mock server on port 4010, for trying the client by hand +``` + +The mock (`mock/routes.mjs`) answers each operation with an example of its schema and refuses a request its operation would refuse: a wrong path or method, a missing parameter, a body of another media type. Set `TEST_API_BASE_URL` to run the tests against another server. + +## Releases + +release-please opens the release pull request: it raises `package.version` in `flowapi-sdk.yml` and `package.json` together, so the next generation prints the version released, and writes the release's entry in `CHANGELOG.md`. Publishing is a person's step. diff --git a/crates/flowapi-sdk/tests/repo/tokens/CHANGELOG.md b/crates/flowapi-sdk/tests/repo/tokens/CHANGELOG.md new file mode 100644 index 0000000..d99436d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +Each release of `tokens-sdk`, newest first. release-please writes an entry from the commits since the release before it. diff --git a/crates/flowapi-sdk/tests/repo/tokens/LICENSE b/crates/flowapi-sdk/tests/repo/tokens/LICENSE new file mode 100644 index 0000000..725c8b2 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) The tokens-sdk authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/flowapi-sdk/tests/repo/tokens/README.md b/crates/flowapi-sdk/tests/repo/tokens/README.md new file mode 100644 index 0000000..8ffee49 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/README.md @@ -0,0 +1,130 @@ + + +# Tokens TypeScript SDK + +TypeScript SDK for the Tokens API. + +The `Tokens` client is generated by flowapi from the API's description: 9 methods in 2 resources, each listed in [api.md](api.md) with its parameters and what it returns. + +## Install + +```sh +npm install tokens-sdk +``` + +## Usage + +```ts +import { Tokens } from 'tokens-sdk' + +const client = new Tokens() + +const result = await client.things.list() +console.log(result) +``` + +A method takes its operation's parameters in one object, grouped by where each goes (`path`, `query`, `header`, `cookie`), with a body as `body: { contentType, value }`; it gives the response's body, read as the description says. A second argument changes one call (`headers`, `query`, `timeout`, `maxRetries`, `signal`). `withResponse()` gives the body with the raw response and the server's request id, `asResponse()` the raw response alone. + +```ts +const { data, response, requestId } = await client.things.list().withResponse() +console.log(response.status, requestId, data) +``` + +The package is built twice, as ES modules and as CommonJS, each with its types, and depends on nothing: it calls the platform's `fetch`. From CommonJS the client is taken by its name, `const { Tokens } = require('tokens-sdk')`; `import Tokens from 'tokens-sdk'` gives it too. + +## Resources + +| Resource | Methods | +| --- | --- | +| [`client.others`](api.md#clientothers) | 7 | +| [`client.things`](api.md#clientthings) | 2 | + +## Authentication + +| Scheme | Kind | Sent as | Option | Environment variables | +| --- | --- | --- | --- | --- | +| `Client` | OAuth 2.0 client credentials | `Authorization: Bearer `, the token requested at `/oauth/token?tenant=main` for the scopes the operation needs | `client`: a token, or `{ clientId, clientSecret }` to request one | `TOKENS_CLIENT_ID`: the client's id; `TOKENS_CLIENT_SECRET`: its secret | +| `Partner` | OAuth 2.0 client credentials | `Authorization: Bearer `, the token requested at `https://login.tokens.example/token` for the scopes `partner.read` | `partner`: a token, or `{ clientId, clientSecret }` to request one | `TOKENS_PARTNER_TOKEN`: a token; `TOKENS_PARTNER_ID`: the client's id; `TOKENS_PARTNER_SECRET`: its secret | +| `Legacy` | API key (deprecated) | the header `X-Api-Key` | `legacy`: the key | `TOKENS_KEY`: the key | +| `Gnap` | HTTP `gnap` | `Authorization: gnap ` | `gnap`: the credential | `TOKENS_GNAP`: the credential | +| `Digest` | HTTP `digest` | not sent: it answers a challenge; give `Authorization` in a call's `headers` | `digest`: — | — | +| `Cert` | mutual TLS | a client certificate, which your `fetch` presents | `cert`: `true` | — | +| `Oidc` | OpenID Connect | `Authorization: Bearer `, a token you obtain | `oidc`: the token, or a function that gives it | `TOKENS_OIDC`: the token | + +An operation's security is a list of alternatives: the client sends the first one it holds every credential of, and an operation that needs none sends none. Each credential is an option of the client, else read from its environment variables when a call needs it; a call none of whose alternatives can be met throws `CredentialError`, naming the options and variables, before anything is sent. Credentials go only over `https:`, or to `localhost`, `127.0.0.1` and `[::1]`: elsewhere a call over plain `http:` throws `InsecureCredentialError`, unless the client is given `allowInsecureCredentials: true`. The log writes each as `***`, and a redirect to another origin is not followed unless `allowCrossOriginRedirects` is set, and then without them. + +A token of OAuth 2.0's client credentials grant is requested at the token URL (relative to the base URL where it is relative) with the client's id and secret in HTTP basic, cached until a little before it expires, shared by the calls that wait for it, and requested again once when the API answers 401. A refusal of the token endpoint throws `TokenError` with its `error` and `description`. + +```ts +const client = new Tokens({ client: { clientId: '…', clientSecret: '…' }, partner: { clientId: '…', clientSecret: '…' }, legacy: '…', gnap: '…', cert: true, oidc: '…' }) +``` + +## Errors + +A response whose status is not a success throws an `APIError` with its `status`, `headers`, `body` and `requestId`, of the class for its status (any other status is an `APIError` itself): + +| Status | Class | +| --- | --- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 408 | `RequestTimeoutError` | +| 409 | `ConflictError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| 500 and above | `InternalServerError` | + +A request that gets no answer throws `APIConnectionError`: `APIConnectionTimeoutError` when an attempt took longer than its `timeout`, `APIUserAbortError` when its `signal` aborted it. These, and every other error the client throws itself, are `SdkError`s. A parameter the description does not allow throws `FlowapiRequestError` before anything is sent. + +```ts +import { APIError } from 'tokens-sdk' + +try { + await client.things.list() +} catch (error) { + if (error instanceof APIError) console.log(error.status, error.body) + else throw error +} +``` + +## Retries and timeouts + +No request is retried by default (`maxRetries: 0`): each is sent once. With `maxRetries` set, a request that cannot connect, or is answered 408, 409, 429 or 5xx, is retried when sending it twice does what sending it once does: its method is GET, HEAD, OPTIONS, TRACE, PUT or DELETE. A POST or a PATCH that failed may have been applied already, so it is retried only when the server's `x-should-retry: true` asks. The server's `x-should-retry` header decides first, where it sends one; a 403 is never retried. A retry that failed is tried again while `maxRetries` allows. Before each retry the client waits as long as the server asks in `retry-after-ms` or `Retry-After`, else 0.5 s doubled for each retry made, at most 8 s; when the server asks for more than 60 s, the error is thrown at once. Each attempt may take 60 s, its body read. + +`maxRetries`, `timeout` and `maxRetryDelay` change these for the client, the last two in milliseconds; `maxRetries` and `timeout` change them for one call, in its options: + +```ts +const patient = new Tokens({ maxRetries: 5, timeout: 120_000 }) +await client.things.list({}, { maxRetries: 0, timeout: 5_000 }) +``` + +## Logging + +The client logs to `console` at `warn` and above. Set `TOKENS_LOG` to `off`, `error`, `warn`, `info` or `debug`, or give `logLevel`: at `info` it writes a line for each attempt, at `debug` the request's URL and headers too, with every credential written as `***`. `logger` sends the lines elsewhere. + +```ts +const verbose = new Tokens({ logLevel: 'debug', logger: console }) +``` + +## Requests no method makes + +`client.request(method, path, options)` sends a request no operation of the description has, with the client's base URL, credentials, retries and errors; `asResponse()` gives the raw `Response`: + +```ts +const response = await client.request('GET', '/').asResponse() +console.log(response.status) +``` + +## Requirements + +Node 20 or later (CI runs 20, 22 and 24), or another runtime with `fetch`. Built with TypeScript 7.0.2. + +## Development + +```sh +npm install +scripts/check # lint, build, the built types, the tests against the mock server +``` + +The code is generated from `flowapi-sdk.yml` by flowapi: change that file and generate again, as [AGENTS.md](AGENTS.md) says. diff --git a/crates/flowapi-sdk/tests/repo/tokens/api.md b/crates/flowapi-sdk/tests/repo/tokens/api.md new file mode 100644 index 0000000..25fe7ab --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/api.md @@ -0,0 +1,33 @@ + + +# API + +Every method of `Tokens`, by resource: 9 methods in 2 resources. A method takes its operation's parameters (`params`) and the options of one call (`options`); the types are the package's: + +```ts +import type { ApiCall, Data, Input, ItemOf, PagePromise, RequestOptions, ServerSentEvent, Stream } from 'tokens-sdk' +``` + +## client.others + +- `client.others.partner(params?: Input, options?: RequestOptions): ApiCall>` + `GET /partner` +- `client.others.legacy(params?: Input, options?: RequestOptions): ApiCall>` + `GET /legacy` +- `client.others.optional(params?: Input, options?: RequestOptions): ApiCall>` + `GET /optional` +- `client.others.gnap(params?: Input, options?: RequestOptions): ApiCall>` + `GET /gnap` +- `client.others.digest(params?: Input, options?: RequestOptions): ApiCall>` + `GET /digest` +- `client.others.cert(params?: Input, options?: RequestOptions): ApiCall>` + `GET /cert` +- `client.others.oidc(params?: Input, options?: RequestOptions): ApiCall>` + `GET /oidc` + +## client.things + +- `client.things.list(params?: Input, options?: RequestOptions): ApiCall>` + `GET /things` +- `client.things.write(params?: Input, options?: RequestOptions): ApiCall>` + `POST /things` diff --git a/crates/flowapi-sdk/tests/repo/tokens/examples/.keep b/crates/flowapi-sdk/tests/repo/tokens/examples/.keep new file mode 100644 index 0000000..e69de29 diff --git a/crates/flowapi-sdk/tests/repo/tokens/issues.txt b/crates/flowapi-sdk/tests/repo/tokens/issues.txt new file mode 100644 index 0000000..a6c697a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/issues.txt @@ -0,0 +1,6 @@ +warning[config.auth.deprecated]: `Legacy` is deprecated by the description: its consumers should refrain from it + at flowapi-sdk.yml:11:3 (/auth/Legacy) +warning[config.auth.refused]: `Digest` is HTTP `digest`, which answers a challenge or signs each request: the client cannot send it; give `Authorization` in a call's `headers` + at flowapi-sdk.yml:13:3 (/auth/Digest) +warning[config.auth.mutual_tls]: `Cert` is a client certificate, which no request carries: give the client a `fetch` (or `fetchOptions`) that presents it, and the option `true` to say so + at flowapi-sdk.yml:14:3 (/auth/Cert) diff --git a/crates/flowapi-sdk/tests/repo/tokens/mock/routes.mjs b/crates/flowapi-sdk/tests/repo/tokens/mock/routes.mjs new file mode 100644 index 0000000..5fd94de --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/mock/routes.mjs @@ -0,0 +1,18 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The operations the client calls, as the mock server answers them (server.mjs). + +export default [ + { "route": "GET /things", "method": "GET", "path": "/things", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "POST /things", "method": "POST", "path": "/things", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Client", "kind": "bearer", "flow": true }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /partner", "method": "GET", "path": "/partner", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Partner", "kind": "bearer", "flow": true }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /legacy", "method": "GET", "path": "/legacy", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Legacy", "kind": "apiKey", "in": "header", "name": "x-api-key" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /optional", "method": "GET", "path": "/optional", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Legacy", "kind": "apiKey", "in": "header", "name": "x-api-key" }], []], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /gnap", "method": "GET", "path": "/gnap", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Gnap", "kind": "http", "scheme": "gnap" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /digest", "method": "GET", "path": "/digest", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Digest", "kind": "http", "scheme": "digest", "refused": true }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /cert", "method": "GET", "path": "/cert", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Cert", "kind": "mutualTLS" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, + { "route": "GET /oidc", "method": "GET", "path": "/oidc", "query": [], "headers": [], "cookies": [], "body": null, "security": [[{ "scheme": "Oidc", "kind": "bearer" }]], "status": 200, "media": "application/json", "example": {"ok": false} }, +] + +// The token endpoints of the client credentials flows, by path. +export const tokens = ["/oauth/token","/token"] diff --git a/crates/flowapi-sdk/tests/repo/tokens/mock/server.mjs b/crates/flowapi-sdk/tests/repo/tokens/mock/server.mjs new file mode 100644 index 0000000..07c6fa6 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/mock/server.mjs @@ -0,0 +1,237 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// The API's mock server, on node:http with no dependency, answering by the routes printed from +// the description beside it (routes.mjs). It is strict where a client goes wrong: a path no +// operation has is a 404, a method the path has not a 405, a request that meets none of the +// operation's security alternatives a 401 naming what each lacks, a required query parameter, +// header, cookie or body that is missing a 400, a body of a media type the operation does not +// take a 415. Otherwise it answers with the operation's first success status and an example value +// of its schema (the schema's example, else its default, its first enum value, else one made from +// its type and format). A token endpoint of a client credentials flow answers a token to a POST +// that asks for it as RFC 6749 4.4 says, else an RFC 6749 5.2 error. Each request answered is +// recorded, with the route it matched (`token` for a token endpoint's). +// +// `mock()` starts it on a free port for a test file (and starts nothing when TEST_API_BASE_URL +// names a server to test against instead); `node mock/server.mjs [port]` runs it by hand. +import { createServer } from 'node:http' +import { pathToFileURL } from 'node:url' +import routes, { tokens } from './routes.mjs' + +/** A route's path as a regular expression: each `{name}` is one segment. */ +function pattern(path) { + const parts = path + .split(/(\{[^}/]+\})/) + .map((p) => (/^\{[^}/]+\}$/.test(p) ? '([^/]+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))) + return new RegExp(`^${parts.join('')}$`) +} + +/** Each segment of a path by how specific it is: 2 literal, 1 a template beside text, 0 a template. */ +const ranks = (path) => path.split('/').map((s) => (!s.includes('{') ? 2 : /^\{[^}/]+\}$/.test(s) ? 0 : 1)) + +/** + * The more specific route first (OpenAPI's Paths Object matches a concrete path before a templated + * one): at the first segment where the two differ in kind, the more literal one; then the shorter + * path, which never matches the same URL. Routes as specific as each other are ambiguous by the + * specification and keep the order of routes.mjs (the client's resources and methods). + */ +function specific(a, b) { + const x = ranks(a.path) + const y = ranks(b.path) + const i = x.findIndex((r, n) => r !== y[n]) + if (i === -1 || i >= y.length) return x.length - y.length + return y[i] - x[i] +} + +// Sorted once, stably: a request takes the first route that matches its path and method. +const table = routes.map((r) => ({ ...r, regex: pattern(r.path) })).sort(specific) + +/** A media type without its parameters, in lower case. */ +const bare = (type) => (type ?? '').split(';')[0].trim().toLowerCase() + +// Whether a media range (`image/png`, `image/*`, `*/*`) takes a media type. +function takes(range, type) { + const r = bare(range) + if (r === '*/*') return true + if (r.endsWith('/*')) return type.startsWith(r.slice(0, -1)) + return r === type +} + +/** The names of a Cookie header's cookies. */ +function cookieNames(header) { + const names = new Set() + for (const part of (header ?? '').split(';')) { + const name = part.split('=')[0].trim() + if (name !== '') names.add(name) + } + return names +} + +/** Whether the query has a parameter: by its name, or as `name[...]` for an object's members. */ +function hasQuery(url, name) { + for (const key of url.searchParams.keys()) if (key === name || key.startsWith(`${name}[`)) return true + return false +} + +/** The token the token endpoints give. */ +const MOCK_TOKEN = 'mock-token' + +/** HTTP basic's pair, decoded, when `Authorization` holds one. */ +function basicPair(header) { + const m = /^Basic ([A-Za-z0-9+/]+=*)$/i.exec(header ?? '') + const pair = m === null ? '' : Buffer.from(m[1], 'base64').toString('utf8') + return pair.includes(':') ? pair : null +} + +/** Whether a request carries one scheme's credential, as its route names it. */ +function carries(check, url, req) { + const auth = req.headers.authorization ?? '' + switch (check.kind) { + case 'apiKey': + if (check.in === 'query') return (url.searchParams.get(check.name) ?? '') !== '' + if (check.in === 'cookie') return cookieNames(req.headers.cookie).has(check.name) + return (req.headers[check.name] ?? '') !== '' + case 'basic': + return basicPair(auth) !== null + case 'bearer': + return /^Bearer [A-Za-z0-9\-._~+/]+=*$/i.test(auth) + case 'http': + return auth.toLowerCase().startsWith(`${check.scheme.toLowerCase()} `) + case 'mutualTLS': + // The mock serves no TLS, so no certificate can be seen: one is taken as presented. + return true + default: + return false + } +} + +/** What each of a route's security alternatives lacks, by scheme; null when one is met. */ +function unauthorized(route, url, req) { + if (route.security.length === 0) return null + const missing = route.security.map((alt) => alt.filter((c) => !carries(c, url, req)).map((c) => c.scheme)) + return missing.some((m) => m.length === 0) ? null : missing +} + +function tokenError(res, status, error, description) { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ error, error_description: description })) +} + +/** A token endpoint's answer to a client credentials grant. */ +function token(req, res, body, requests) { + if (req.method !== 'POST') return tokenError(res, 405, 'invalid_request', 'a token is requested with POST') + if (bare(req.headers['content-type']) !== 'application/x-www-form-urlencoded') { + return tokenError(res, 400, 'invalid_request', 'the body is not application/x-www-form-urlencoded') + } + const form = new URLSearchParams(body.toString('utf8')) + if ([...new Set(form.keys())].some((k) => form.getAll(k).length > 1)) return tokenError(res, 400, 'invalid_request', 'a parameter is given twice') + if (form.get('grant_type') !== 'client_credentials') return tokenError(res, 400, 'unsupported_grant_type', 'the grant is not client_credentials') + if (form.has('client_secret') || basicPair(req.headers.authorization) === null) { + return tokenError(res, 401, 'invalid_client', 'the client authenticates by HTTP basic alone') + } + requests.push({ route: 'token', method: req.method, url: req.url, headers: req.headers, body }) + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) + res.end(JSON.stringify({ access_token: MOCK_TOKEN, token_type: 'Bearer', expires_in: 3600, scope: form.get('scope') ?? '' })) +} + +/** What is wrong with a request for its route, with the status that says so; null for nothing. */ +function problem(route, url, req, body) { + for (const name of route.query) if (!hasQuery(url, name)) return [400, `the query parameter ${name} is required`] + for (const name of route.headers) if (req.headers[name] === undefined) return [400, `the header ${name} is required`] + const jar = cookieNames(req.headers.cookie) + for (const name of route.cookies) if (!jar.has(name)) return [400, `the cookie ${name} is required`] + if (body.length === 0) return route.body?.required ? [400, 'the operation requires a body'] : null + if (route.body === null) return [400, 'the operation takes no body'] + const type = bare(req.headers['content-type']) + if (!route.body.media.some((m) => takes(m, type))) { + return [415, `the body's media type ${type || '(none)'} is not one of ${route.body.media.join(', ')}`] + } + if (type === 'application/json' || type.endsWith('+json')) { + try { + JSON.parse(body.toString('utf8')) + } catch { + return [400, 'the body is not JSON'] + } + } + return null +} + +function fail(res, status, message) { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: message })) +} + +/** The route's answer: its status, and its example in its media type. */ +function answer(res, route) { + if (route.media === null || [204, 205, 304].includes(route.status)) { + res.writeHead(route.status) + res.end() + return + } + const media = route.media.includes('*') ? 'application/octet-stream' : route.media + const type = bare(media) + const json = JSON.stringify(route.example) + const text = typeof route.example === 'string' ? route.example : json + let body + if (type === 'text/event-stream') body = `data: ${text}\n\n` + else if (type === 'application/x-ndjson' || type === 'application/jsonl') body = `${json}\n` + else if (type === 'application/json' || type.endsWith('+json')) body = json + else if (type.startsWith('text/') || type.endsWith('+xml') || type === 'application/xml') body = text + else body = Buffer.from([1, 2, 3]) + res.writeHead(route.status, { 'content-type': media }) + res.end(body) +} + +function handle(req, res, requests) { + const chunks = [] + req.on('data', (c) => chunks.push(c)) + req.on('end', () => { + const body = Buffer.concat(chunks) + const url = new URL(req.url ?? '/', 'http://mock.invalid') + if (tokens.includes(url.pathname)) return token(req, res, body, requests) + const matches = table.filter((r) => r.regex.test(url.pathname)) + if (matches.length === 0) return fail(res, 404, `no operation has the path ${url.pathname}`) + const route = matches.find((r) => r.method === req.method) + if (route === undefined) { + const methods = matches.map((r) => r.method).join(', ') + return fail(res, 405, `${url.pathname} takes ${methods}, not ${req.method}`) + } + const lacking = unauthorized(route, url, req) + if (lacking !== null) { + res.writeHead(401, { 'content-type': 'application/json' }) + const ways = lacking.map((m) => m.join(' and ')).join(', or ') + return res.end(JSON.stringify({ error: `${route.route}: no alternative of its security is met: send ${ways}`, missing: lacking })) + } + const wrong = problem(route, url, req, body) + if (wrong !== null) return fail(res, wrong[0], `${route.route}: ${wrong[1]}`) + requests.push({ route: route.route, method: req.method, url: req.url, headers: req.headers, body }) + answer(res, route) + }) +} + +/** + * Starts the mock server on `port` (0, the default, for a free one) of 127.0.0.1. Resolves to its + * `url`, the `requests` it answered and `close()`. When TEST_API_BASE_URL is set it starts nothing: + * `url` is that address and `requests` is null. + */ +export async function mock({ port = 0 } = {}) { + const external = process.env.TEST_API_BASE_URL + if (external) return { url: external.replace(/\/+$/, ''), requests: null, close: async () => {} } + const requests = [] + const server = createServer((req, res) => handle(req, res, requests)) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, '127.0.0.1', resolve) + }) + const close = () => + new Promise((resolve) => { + server.close(() => resolve()) + server.closeAllConnections() + }) + return { url: `http://127.0.0.1:${server.address().port}`, requests, close } +} + +if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) { + const port = Number(process.argv[2] ?? 4010) + const { url } = await mock({ port }) + console.log(`the mock server answers at ${url}`) +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/package.json b/crates/flowapi-sdk/tests/repo/tokens/package.json new file mode 100644 index 0000000..1fc0df5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/package.json @@ -0,0 +1,26 @@ +{ + "name": "tokens-sdk", + "version": "0.1.0", + "description": "TypeScript SDK for the Tokens API.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "engines": { "node": ">=20" }, + "main": "./dist/cjs/index.js", + "types": "./dist/cjs/index.d.ts", + "exports": { + ".": { + "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, + "require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" } + }, + "./package.json": "./package.json" + }, + "files": ["dist"], + "scripts": { + "build": "scripts/build", + "lint": "scripts/lint", + "test": "scripts/test", + "check": "scripts/check" + }, + "devDependencies": { "typescript": "7.0.2" } +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/release-please-config.json b/crates/flowapi-sdk/tests/repo/tokens/release-please-config.json new file mode 100644 index 0000000..897e118 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/release-please-config.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "node", + "include-v-in-tag": true, + "bump-minor-pre-major": true, + "changelog-path": "CHANGELOG.md", + "extra-files": [{ "type": "yaml", "path": "flowapi-sdk.yml", "jsonpath": "$.package.version" }] + } + } +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/scripts/build b/crates/flowapi-sdk/tests/repo/tokens/scripts/build new file mode 100644 index 0000000..6dd941a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/scripts/build @@ -0,0 +1,21 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The package built twice from src/ by tsc alone: ES modules into dist/esm, CommonJS into +# dist/cjs, each with its declarations; then loaded by its own name with require and import, as +# a user loads it. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/build: $tsc is missing: run npm install first" >&2 + exit 1 +fi +rm -rf dist +"$tsc" -p tsconfig.build.json +"$tsc" -p tsconfig.cjs.json +printf '{ "type": "commonjs" }\n' > dist/cjs/package.json +name=$(node -p 'require("./package.json").name') +# CommonJS: the module, its client class both `default` and by its name, as the README takes it. +node -e 'const m = require(process.argv[1]); if (typeof m.default !== "function" || m[m.default.name] !== m.default) throw new Error("require(" + process.argv[1] + ") gives no client class by its name")' "$name" +node --input-type=module -e 'const m = await import(process.argv[1]); if (typeof m.default !== "function") throw new Error("import(" + process.argv[1] + ") gives no client class")' "$name" diff --git a/crates/flowapi-sdk/tests/repo/tokens/scripts/check b/crates/flowapi-sdk/tests/repo/tokens/scripts/check new file mode 100644 index 0000000..e0be85d --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/scripts/check @@ -0,0 +1,11 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Everything a change must pass: lint, the build, the built declarations type-checked on their +# own (skipLibCheck off), the tests. +set -eu +cd "$(dirname "$0")/.." +scripts/lint +scripts/build +node_modules/.bin/tsc -p tsconfig.dist.json +SDK_BUILT=1 scripts/test diff --git a/crates/flowapi-sdk/tests/repo/tokens/scripts/lint b/crates/flowapi-sdk/tests/repo/tokens/scripts/lint new file mode 100644 index 0000000..7126bd5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/scripts/lint @@ -0,0 +1,22 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The sources type-checked; no node: module in the generated client, which runs wherever fetch +# does; the mock server and the tests parsed. +set -eu +cd "$(dirname "$0")/.." +tsc=node_modules/.bin/tsc +if [ ! -x "$tsc" ]; then + echo "scripts/lint: $tsc is missing: run npm install first" >&2 + exit 1 +fi +"$tsc" -p tsconfig.json +found=$(find src -name '*.ts' ! -path 'src/lib/*' -exec grep -l -e 'from "node:' -e "from 'node:" {} + || true) +if [ -n "$found" ]; then + echo "scripts/lint: a node: module is imported by the client, which must run without Node:" >&2 + echo "$found" >&2 + exit 1 +fi +for f in mock/*.mjs $(find tests -name '*.mjs' | sort); do + node --check "$f" +done diff --git a/crates/flowapi-sdk/tests/repo/tokens/scripts/mock b/crates/flowapi-sdk/tests/repo/tokens/scripts/mock new file mode 100644 index 0000000..c7fad1c --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/scripts/mock @@ -0,0 +1,7 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# The mock server on a port (4010 unless given), until stopped: for trying the client by hand. +set -eu +cd "$(dirname "$0")/.." +exec node mock/server.mjs "${1:-4010}" diff --git a/crates/flowapi-sdk/tests/repo/tokens/scripts/test b/crates/flowapi-sdk/tests/repo/tokens/scripts/test new file mode 100644 index 0000000..d78cf2a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/scripts/test @@ -0,0 +1,19 @@ +#!/bin/sh +# Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +# +# Every test of tests/ by node --test, against the mock server each test file starts on a free +# port (or against TEST_API_BASE_URL when it is set). The package is built first, unless +# SDK_BUILT=1 says it was just built. +set -eu +cd "$(dirname "$0")/.." +if [ "${SDK_BUILT:-}" != 1 ]; then + scripts/build +fi +files=$(find tests -name '*.test.mjs' | sort) +if [ -z "$files" ]; then + echo "scripts/test: no tests under tests/" >&2 + exit 1 +fi +# The files one by one as arguments: every Node from 20 reads them so, globs or not. +# shellcheck disable=SC2086 +node --test $files diff --git a/crates/flowapi-sdk/tests/repo/tokens/tests/api-resources/others.test.mjs b/crates/flowapi-sdk/tests/repo/tokens/tests/api-resources/others.test.mjs new file mode 100644 index 0000000..b73aec5 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tests/api-resources/others.test.mjs @@ -0,0 +1,53 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `others` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Tokens } from "tokens-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Tokens({ baseURL: server.url, client: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, partner: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, legacy: 'test-credential', gnap: 'test-credential', cert: true, oidc: 'test-credential', maxRetries: 0 }) +}) + +after(() => server.close()) + +test("others.partner: GET /partner", async () => { + await client.others.partner() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /partner") +}) + +test("others.legacy: GET /legacy", async () => { + await client.others.legacy() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /legacy") +}) + +test("others.optional: GET /optional", async () => { + await client.others.optional() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /optional") +}) + +test("others.gnap: GET /gnap", async () => { + await client.others.gnap() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /gnap") +}) + +test("others.digest: GET /digest", async () => { + await client.others.digest({}, { headers: { Authorization: 'digest test-credential' } }) + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /digest") +}) + +test("others.cert: GET /cert", async () => { + await client.others.cert() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /cert") +}) + +test("others.oidc: GET /oidc", async () => { + await client.others.oidc() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /oidc") +}) diff --git a/crates/flowapi-sdk/tests/repo/tokens/tests/api-resources/things.test.mjs b/crates/flowapi-sdk/tests/repo/tokens/tests/api-resources/things.test.mjs new file mode 100644 index 0000000..7690cd3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tests/api-resources/things.test.mjs @@ -0,0 +1,28 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// Every method of `things` called against the mock server. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Tokens } from "tokens-sdk" +import { mock } from '../../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Tokens({ baseURL: server.url, client: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, partner: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, legacy: 'test-credential', gnap: 'test-credential', cert: true, oidc: 'test-credential', maxRetries: 0 }) +}) + +after(() => server.close()) + +test("things.list: GET /things", async () => { + await client.things.list() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "GET /things") +}) + +test("things.write: POST /things", async () => { + await client.things.write() + if (server.requests !== null) assert.equal(server.requests.at(-1)?.route, "POST /things") +}) diff --git a/crates/flowapi-sdk/tests/repo/tokens/tests/auth.test.mjs b/crates/flowapi-sdk/tests/repo/tokens/tests/auth.test.mjs new file mode 100644 index 0000000..51ae721 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tests/auth.test.mjs @@ -0,0 +1,58 @@ +// Generated by flowapi from flowapi-sdk.yml and the API description. Do not edit: generate again. +// +// What the mock received of each kind of credential the client sends, and a call that needs none. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { Tokens } from "tokens-sdk" +import { mock } from '../mock/server.mjs' + +let server +let client + +before(async () => { + server = await mock() + client = new Tokens({ baseURL: server.url, client: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/oauth/token` }, partner: { clientId: 'test-client', clientSecret: 'test-secret', tokenURL: `${server.url}/token` }, legacy: 'test-credential', gnap: 'test-credential', cert: true, oidc: 'test-credential', maxRetries: 0 }) +}) + +after(() => server.close()) + +/** The request the mock answered last; `null` against a server of your own. */ +const last = () => server.requests?.at(-1) ?? null + +test("Client: sent by things.list", async () => { + await client.things.list() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer mock-token') + assert.ok(server.requests.some((q) => q.route === 'token'), 'the token was requested of the mock') +}) + +test("Partner: sent by others.partner", async () => { + await client.others.partner() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer mock-token') + assert.ok(server.requests.some((q) => q.route === 'token'), 'the token was requested of the mock') +}) + +test("Legacy: sent by others.legacy", async () => { + await client.others.legacy() + const r = last() + if (r === null) return + assert.equal(r.headers["x-api-key"], 'test-credential') +}) + +test("Gnap: sent by others.gnap", async () => { + await client.others.gnap() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'gnap test-credential') +}) + +test("Oidc: sent by others.oidc", async () => { + await client.others.oidc() + const r = last() + if (r === null) return + assert.equal(r.headers.authorization, 'Bearer test-credential') +}) diff --git a/crates/flowapi-sdk/tests/repo/tokens/tsconfig.build.json b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.build.json new file mode 100644 index 0000000..6034cd3 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "rootDir": "src", + "outDir": "dist/esm" + } +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/tsconfig.cjs.json b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.cjs.json new file mode 100644 index 0000000..cae8db8 --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.build.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs" + } +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/tsconfig.dist.json b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.dist.json new file mode 100644 index 0000000..f52d18a --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.dist.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "skipLibCheck": false, + "noEmit": true + }, + "include": ["dist/**/*.d.ts"] +} diff --git a/crates/flowapi-sdk/tests/repo/tokens/tsconfig.json b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.json new file mode 100644 index 0000000..9ee3b9b --- /dev/null +++ b/crates/flowapi-sdk/tests/repo/tokens/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["es2022"], + "module": "nodenext", + "strict": true, + "exactOptionalPropertyTypes": true, + "types": [], + "rootDir": "src", + "noEmit": true + }, + "include": ["src"] +} diff --git a/crates/flowapi-sdk/tests/schema.json b/crates/flowapi-sdk/tests/schema.json index 7b8c98b..bfbea1c 100644 --- a/crates/flowapi-sdk/tests/schema.json +++ b/crates/flowapi-sdk/tests/schema.json @@ -56,6 +56,19 @@ "type": "string", "pattern": "\\S", "description": "The package's repository URL" + }, + "description": { + "type": "string", + "pattern": "\\S", + "description": "One or two sentences of plain text: `package.json`'s `description` and, without `readme.intro`, the README's first paragraph. Unless given, made from the description's `info.title` and the first sentence of its `info.summary` or `info.description`" + }, + "keywords": { + "type": "array", + "items": { + "type": "string", + "pattern": "\\S" + }, + "description": "`package.json`'s `keywords`, for npm's search; none unless given" } }, "required": [ @@ -94,7 +107,11 @@ "additionalProperties": { "$ref": "#/$defs/auth" }, - "description": "The security schemes the client sends, by their names in the description" + "description": "The security schemes the client sends, by their names in the description, and those it lacks" + }, + "security": { + "$ref": "#/$defs/security", + "description": "The security of every operation with none of its own, over the description's: alternatives, any one of which is enough, each the schemes it needs with their scopes; `{}` makes a credential optional, `[]` is none" }, "defaults": { "type": "object", @@ -103,8 +120,13 @@ "type": "integer", "minimum": 0, "maximum": 10, - "description": "How many times a failed request is retried", - "default": 2 + "description": "How many times a failed request is retried: a POST or a PATCH only with an idempotency key", + "default": 1 + }, + "idempotency_key": { + "type": "string", + "pattern": "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$", + "description": "The header each call of a POST, a PATCH or another method that is not idempotent sends a key in, the same on its retries" }, "timeout": { "type": "number", @@ -157,6 +179,16 @@ "readme": { "type": "object", "properties": { + "title": { + "type": "string", + "pattern": "\\S", + "description": "The README's heading. Unless given, the description's `info.title` without a last `API`, then `TypeScript SDK` (`Twilio Studio API` is `Twilio Studio TypeScript SDK`); the package's name when the description has no title" + }, + "intro": { + "type": "string", + "pattern": "\\S", + "description": "The README's first paragraph, Markdown; `package.description` unless given" + }, "headline_method": { "type": "string", "pattern": "\\S", @@ -166,11 +198,6 @@ "type": "string", "pattern": "\\S", "description": "The method the README shows pagination with" - }, - "intro": { - "type": "string", - "pattern": "\\S", - "description": "The README's opening paragraph" } }, "additionalProperties": false, @@ -188,10 +215,78 @@ "auth": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": [ + "apiKey", + "http", + "oauth2", + "mutualTLS" + ], + "description": "The kind of a scheme the description does not declare: `apiKey`, `http`, `oauth2` (a token, or one the client requests at `token_url`) or `mutualTLS`" + }, + "scheme": { + "type": "string", + "pattern": "\\S", + "description": "`http`: the HTTP authentication scheme (`bearer`, `basic`, or another of IANA's registry)" + }, + "in": { + "type": "string", + "enum": [ + "header", + "query", + "cookie" + ], + "description": "`apiKey`: where the key goes: `header`, `query` or `cookie`" + }, + "name": { + "type": "string", + "pattern": "\\S", + "description": "`apiKey`: the name of the header, query parameter or cookie" + }, + "token_url": { + "type": "string", + "pattern": "^https?://[^\\s/?#]+[^\\s]*$", + "format": "uri", + "description": "`oauth2`: the token endpoint the client requests a token at by the client credentials flow" + }, + "description": { + "type": "string", + "pattern": "\\S", + "description": "What the scheme is, for the README" + }, "env_var": { "type": "string", "pattern": "^[A-Z_][A-Z0-9_]*$", - "description": "The environment variable the credential is read from" + "description": "The environment variable the credential is read from: the key or the token; for HTTP basic `username:password`" + }, + "username_env_var": { + "type": "string", + "pattern": "^[A-Z_][A-Z0-9_]*$", + "description": "HTTP basic: the environment variable of the user-id, beside `password_env_var`" + }, + "password_env_var": { + "type": "string", + "pattern": "^[A-Z_][A-Z0-9_]*$", + "description": "HTTP basic: the environment variable of the password, beside `username_env_var`" + }, + "client_id_env_var": { + "type": "string", + "pattern": "^[A-Z_][A-Z0-9_]*$", + "description": "OAuth 2.0 client credentials: the environment variable of the client's id" + }, + "client_secret_env_var": { + "type": "string", + "pattern": "^[A-Z_][A-Z0-9_]*$", + "description": "OAuth 2.0 client credentials: the environment variable of the client's secret" + }, + "scopes": { + "type": "array", + "items": { + "type": "string", + "pattern": "\\S" + }, + "description": "OAuth 2.0 client credentials: the scopes every token is requested with, instead of each operation's" } }, "additionalProperties": false @@ -231,6 +326,10 @@ "stream": { "type": "boolean", "description": "Whether the response is read as a stream of events" + }, + "security": { + "$ref": "#/$defs/security", + "description": "The method's security, over the description's and the config's: alternatives, each the schemes it needs with their scopes; `[]` for none" } }, "required": [ @@ -587,6 +686,19 @@ }, "additionalProperties": false }, + "security": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string", + "pattern": "\\S" + } + } + } + }, "skip": { "type": "object", "properties": { diff --git a/crates/flowapi-sdk/tests/schema.rs b/crates/flowapi-sdk/tests/schema.rs index e83e8dc..93c79b9 100644 --- a/crates/flowapi-sdk/tests/schema.rs +++ b/crates/flowapi-sdk/tests/schema.rs @@ -193,6 +193,9 @@ fn a_member_the_schema_does_not_name_is_refused_everywhere() { "/resources", "/resources/entry/methods", "/resources/entry/resources", + // A security requirement: scheme names, each with its scopes. + "/security/0", + "/resources/entry/methods/entry/security/0", ]; for at in places.iter().filter(|p| !maps.contains(&p.as_str())) { let mut wrong = config.clone(); diff --git a/crates/flowapi-sdk/tests/summary/shop-index.json b/crates/flowapi-sdk/tests/summary/shop-index.json index ccf9ec7..e3ede29 100644 --- a/crates/flowapi-sdk/tests/summary/shop-index.json +++ b/crates/flowapi-sdk/tests/summary/shop-index.json @@ -1,6 +1,7 @@ {"info":{"title":"Pet Shop","version":"1.2.0"}, "servers":["https://api.petshop.example/v1","https://sandbox.petshop.example/v1"], "securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"X-Api-Key"},"bearer":{"type":"http","scheme":"bearer"}}, +"security":[["ApiKeyAuth"]], "counts":{"operations":11,"shown":11,"tags":6,"schemas":5}, "tags":[{"name":"pets","operations":6},{"name":"owners","operations":1},{"name":"events","operations":1},{"name":"collision","operations":1},{"name":"users","operations":1},{"name":"","operations":1}], -"truncated":{"bytes":3416,"max":1000,"next":"the operations are over the budget and left out: read one tag at a time with --tag , or a part of the API with --path , or raise --max-bytes"}} +"truncated":{"bytes":3445,"max":1000,"next":"the operations are over the budget and left out: read one tag at a time with --tag , or a part of the API with --path , or raise --max-bytes"}} diff --git a/crates/flowapi-sdk/tests/summary/shop-path.json b/crates/flowapi-sdk/tests/summary/shop-path.json index a378b7b..8dd96bc 100644 --- a/crates/flowapi-sdk/tests/summary/shop-path.json +++ b/crates/flowapi-sdk/tests/summary/shop-path.json @@ -1,6 +1,7 @@ {"info":{"title":"Pet Shop","version":"1.2.0"}, "servers":["https://api.petshop.example/v1","https://sandbox.petshop.example/v1"], "securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"X-Api-Key"},"bearer":{"type":"http","scheme":"bearer"}}, +"security":[["ApiKeyAuth"]], "counts":{"operations":11,"shown":4,"tags":6,"schemas":5}, "filter":{"tag":null,"path":"/pets/"}, "tags":[{"name":"pets","operations":6},{"name":"owners","operations":1},{"name":"events","operations":1},{"name":"collision","operations":1},{"name":"users","operations":1},{"name":"","operations":1}], diff --git a/crates/flowapi-sdk/tests/summary/shop-tag.json b/crates/flowapi-sdk/tests/summary/shop-tag.json index fa99106..bc10b7a 100644 --- a/crates/flowapi-sdk/tests/summary/shop-tag.json +++ b/crates/flowapi-sdk/tests/summary/shop-tag.json @@ -1,6 +1,7 @@ {"info":{"title":"Pet Shop","version":"1.2.0"}, "servers":["https://api.petshop.example/v1","https://sandbox.petshop.example/v1"], "securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"X-Api-Key"},"bearer":{"type":"http","scheme":"bearer"}}, +"security":[["ApiKeyAuth"]], "counts":{"operations":11,"shown":6,"tags":6,"schemas":5}, "filter":{"tag":"Pets","path":null}, "tags":[{"name":"pets","operations":6},{"name":"owners","operations":1},{"name":"events","operations":1},{"name":"collision","operations":1},{"name":"users","operations":1},{"name":"","operations":1}], diff --git a/crates/flowapi-sdk/tests/summary/shop.json b/crates/flowapi-sdk/tests/summary/shop.json index 4c06d62..4b64749 100644 --- a/crates/flowapi-sdk/tests/summary/shop.json +++ b/crates/flowapi-sdk/tests/summary/shop.json @@ -1,6 +1,7 @@ {"info":{"title":"Pet Shop","version":"1.2.0"}, "servers":["https://api.petshop.example/v1","https://sandbox.petshop.example/v1"], "securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"X-Api-Key"},"bearer":{"type":"http","scheme":"bearer"}}, +"security":[["ApiKeyAuth"]], "counts":{"operations":11,"shown":11,"tags":6,"schemas":5}, "tags":[{"name":"pets","operations":6},{"name":"owners","operations":1},{"name":"events","operations":1},{"name":"collision","operations":1},{"name":"users","operations":1},{"name":"","operations":1}], "operations":[ diff --git a/crates/flowapi-sdk/tests/table.rs b/crates/flowapi-sdk/tests/table.rs index 86b420e..28abf94 100644 --- a/crates/flowapi-sdk/tests/table.rs +++ b/crates/flowapi-sdk/tests/table.rs @@ -4,7 +4,9 @@ //! writes them anew; a change to one is read in review like code. `tests/tsc.mjs` type-checks //! each kept table after the `--sdk` output it is appended to, and imports it under Node. //! -//! servers.json: servers with variables (`enum`, `description`), a relative one, and each one +//! servers.json (3.1), servers30.json and servers32.json (the same in 3.0 and 3.2, with `.` and +//! `./test`, relative to where the description is served): servers with variables (`enum`, +//! `description`, an `x-` member read by no one), a relative one, and each one //! left out (a variable not defined, no `url`, no `default`) or kept with a warning (a `default` //! outside `enum`, an empty `enum`, a query in the URL); a Path Item's servers, an operation's //! over them, and empty lists that override nothing. defaults.json: 3.0 with no servers (`/`) @@ -17,10 +19,15 @@ //! `schemes` (the description's own scheme). swagger-nohost.json: no host (a relative URL, an //! operation's `schemes` changing nothing) and a `basePath` without `/`. v32.json: a server's //! `name`, a deprecated scheme, a Path Item behind `$ref` with servers and an -//! `additionalOperations` method, a requirement named by URI, the `query` method. encoding.json: -//! a multipart body's Encoding Objects (a part's type with parameters, a list of types left out -//! with a warning, an object with no `contentType`), one behind a request body's `$ref`, a form's -//! encoding not read, a multipart body with none. +//! `additionalOperations` method, a requirement named by URI, the `query` method. encoding.json +//! (3.1): `multipart/form-data`'s and a form's Encoding Objects by name (a part's type with +//! parameters, a list of types kept, styles, a type inferred from `contentEncoding` through +//! `$ref` and `allOf`, never `oneOf`), one behind a request body's `$ref`, responses' and JSON's +//! encoding not read, a multipart body with none. encoding-v30.json: 3.0's fields (no style for +//! `multipart/form-data`, `format: binary` and `byte`). encoding-v32.json: `prefixEncoding`, +//! `itemEncoding`, nesting and its depth bound, `Content-Transfer-Encoding` from +//! `contentEncoding`. swagger-forms.json: 2.0's `formData` `collectionFormat` as styles. +//! A case's `x-flowapi-calls` are requests `tests/tsc.mjs` writes through its table. //! //! Each case names the requirements it covers in `x-flowapi-covers` (the ledger reads them). #![expect( @@ -95,3 +102,69 @@ fn a_schema_reads_nothing() { assert_eq!(service, flowapi_sdk::Service::default()); assert!(diags.all().is_empty()); } + +/// A Server Object of another document: a relative URL is relative to that document, printed +/// relative to the first; one with a scheme, a host, an absolute path or a templated host as it is. +// req: oas-3.1.relative-references-in-api-urls.may-note-themselves-relative-referring-document — `./v2` of `paths/pets.json` is `paths/v2` from the description +// req: oas-3.2.server-object.relative-references-in-api-urls.may-note-themselves-relative-referring-document — the same in 3.2 +#[test] +fn servers_of_another_document_are_relative_to_it() { + for version in ["3.1.0", "3.2.0"] { + let root = format!( + r#"{{"openapi":"{version}","info":{{"title":"t","version":"1"}},"paths":{{"/pets":{{"$ref":"paths/pets.json"}}}}}}"# + ); + let pets = r#"{"servers":[{"url":"./v2"},{"url":"../shared/v1"},{"url":"."},{"url":"/abs"},{"url":"//h.example/x"},{"url":"https://a.example/{v}","variables":{"v":{"default":"1"}}},{"url":"{scheme}://b.example","variables":{"scheme":{"default":"https"}}}],"get":{"operationId":"listPets","responses":{"204":{"description":"none"}}}}"#; + let mut docs = Documents::new(); + docs.add("api/openapi.json", &root).expect("JSON"); + docs.add("api/paths/pets.json", pets).expect("JSON"); + let target = flowapi_ts::TypeScript::new("out.ts").with_sdk(); + let (program, _) = flowapi::program(&docs, &target); + let (text, _) = flowapi_sdk::table(&docs, &program.expect("no error")); + let want = r#"servers: [{ url: "paths/v2" }, { url: "shared/v1" }, { url: "paths" }, { url: "/abs" }, { url: "//h.example/x" }, { url: "https://a.example/{v}", variables: { "v": { default: "1" } } }, { url: "{scheme}://b.example", variables: { "scheme": { default: "https" } } }],"#; + assert!(text.contains(want), "{version}:\n{text}"); + } +} + +// req: oas-3.0.appendix-f-resolving-security-requirements-in-a-referenced-document.recommended-however-documented-section-tools-resolve-component — a name in a referenced document's operation resolves from the entry document +// req: oas-3.1.appendix-f-resolving-security-requirements-in-a-referenced-document.recommended-however-documented-section-tools-resolve-component — the same in 3.1 +// req: oas-3.2.security-schemes.recommended-implementation-defined-whether-component-name-used — 3.2: resolved from the entry document, the RECOMMENDED choice +/// Appendix F: an operation in a referenced document names `Key`, which both documents declare +/// differently; the entry document's is the one sent, in every version that has the appendix. +#[test] +fn security_names_resolve_from_the_entry_document() { + for version in ["3.0.3", "3.1.0", "3.2.0"] { + let entry = format!( + r#"{{"openapi":"{version}","info":{{"title":"t","version":"1"}},"servers":[{{"url":"https://x"}}], + "paths":{{"/a":{{"$ref":"other.json#/paths/~1a"}}}}, + "components":{{"securitySchemes":{{"Key":{{"type":"apiKey","in":"header","name":"X-Entry"}}}}}}}}"# + ); + let other = format!( + r#"{{"openapi":"{version}","info":{{"title":"o","version":"1"}}, + "paths":{{"/a":{{"get":{{"operationId":"get","security":[{{"Key":[]}}],"responses":{{"200":{{"description":"ok"}}}}}}}}}}, + "components":{{"securitySchemes":{{"Key":{{"type":"apiKey","in":"query","name":"other"}}}}}}}}"# + ); + let mut docs = Documents::new(); + docs.add("entry.json", &entry).expect("JSON"); + docs.add("other.json", &other).expect("JSON"); + let target = flowapi_ts::TypeScript::new("out.ts").with_sdk(); + let (program, _) = flowapi::program(&docs, &target); + let (service, diags) = flowapi_sdk::read(&docs, &program.expect("no error")); + let get = service.operations.first().expect("one operation"); + let names: Vec<&str> = get + .security + .iter() + .flat_map(|r| r.schemes.iter().map(|(n, _)| n.as_str())) + .collect(); + assert_eq!(names, ["Key"], "{version}"); + let key = service + .schemes + .iter() + .find(|s| s.name == "Key") + .expect("Key"); + assert!( + matches!(&key.auth, flowapi_sdk::Auth::ApiKey { name, .. } if name == "X-Entry"), + "{version}: {key:?}" + ); + assert!(diags.all().is_empty(), "{version}: {:?}", diags.all()); + } +} diff --git a/crates/flowapi-sdk/tests/texts.mjs b/crates/flowapi-sdk/tests/texts.mjs new file mode 100644 index 0000000..7bd49d7 --- /dev/null +++ b/crates/flowapi-sdk/tests/texts.mjs @@ -0,0 +1,160 @@ +// The texts a generated SDK shows its users, held to its client: for each repository kept in +// tests/repo/ beside the client kept in tests/client/ under the same name, +// - every TypeScript block of README.md compiles against the client (the package's name read as +// its src/index.ts; a block that uses `client` without making one is given a `Shop`-like +// `declare const client`), the headline example first among them; +// - every method line of api.md is a signature the client's method has: `const m: (params…) => +// R = client..` compiles, with the types api.md says to import; +// - api.md lists as many methods as src/resources/ defines, and README.md names every resource +// api.md has; +// - README.md's retries section says what the client's `maxRetries` and `idempotencyHeader` do: +// no retry claimed for a client that makes none by default, the idempotency key's header named +// where it has one, else that a POST or a PATCH waits for `x-should-retry: true`; +// - no text holds a placeholder: `TODO` or `FIXME`, `"string"` as an example value, a comment +// standing for arguments (`/* … */`), or a section with nothing under its heading. +// The compiler is the oracles' (conformance/ts), under strict and exactOptionalPropertyTypes. +// Run from the repository root, after `(cd conformance/ts && npm ci)`: +// node crates/flowapi-sdk/tests/texts.mjs +// Exits 1 when anything fails. +import { execFileSync } from 'node:child_process' +import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +const tsc = resolve('conformance/ts/node_modules/.bin/tsc') +const repos = 'crates/flowapi-sdk/tests/repo' +const clients = 'crates/flowapi-sdk/tests/client' +const core = 'crates/flowapi-sdk/src/client/core' +const strict = ['--ignoreConfig', '--strict', '--exactOptionalPropertyTypes', '--target', 'es2022', '--module', 'nodenext', '--lib', 'es2022,dom', '--noEmit', '--pretty', 'false'] +const failures = [] +const index = "'../src/index.js'" + +/** The texts of a generated repository a user reads. */ +const TEXTS = ['README.md', 'api.md', 'AGENTS.md', 'CHANGELOG.md', 'package.json'] + +/** The placeholders no text may hold, each with what it is. */ +const PLACEHOLDERS = [ + [/\b(TODO|FIXME)\b/, 'a TODO left in'], + [/[:=(,[]\s*["']string["']/, '"string" as an example value'], + [/\/\*\s*(…|\.\.\.)\s*\*\//, 'a comment standing for arguments'], +] + +/** Headings with nothing under them before the next heading of the same level or above. */ +/** What README.md's retries section gets wrong about a client of these settings. */ +function retriesSays(readme, max, key) { + const section = /## Retries and timeouts\n\n([^\n]*)/.exec(readme)?.[1] + if (section === undefined) return ['no "Retries and timeouts" section'] + const out = [] + const marker = 'With `maxRetries` set, ' + if (max === 0) { + const lead = 'No request is retried by default (`maxRetries: 0`): each is sent once.' + const head = section.split(marker)[0] + if (!head.startsWith(lead) || !section.includes(marker)) out.push('maxRetries is 0, and the retries section does not say no request is retried') + else if (/retried|tried again/.test(head.slice(lead.length))) out.push(`maxRetries is 0, and the retries section claims a retry: ${JSON.stringify(head)}`) + } else { + const by = max === 1 ? 'is retried once by default' : `is retried ${max} times by default` + if (!section.includes(by) || section.includes(marker)) out.push(`maxRetries is ${max}, and the retries section does not say "${by}"`) + } + if (key !== undefined && !section.includes(`random \`${key}\` header`)) out.push(`the idempotency key's header ${key} is not named`) + if (key === undefined && !section.includes('retried only when the server\'s `x-should-retry: true` asks')) { + out.push('no idempotency key, and the retries section does not say a POST waits for x-should-retry') + } + return out +} + +function emptySections(text) { + const lines = text.split('\n') + const out = [] + lines.forEach((line, i) => { + const h = /^(#{1,6}) /.exec(line) + if (h === null) return + const next = lines.slice(i + 1).find((l) => l.trim() !== '') + const nh = next === undefined ? null : /^(#{1,6}) /.exec(next) + if (next === undefined || (nh !== null && nh[1].length <= h[1].length)) out.push(line) + }) + return out +} + +const root = mkdtempSync(join(tmpdir(), 'flowapi-texts-')) +for (const name of readdirSync(repos).filter((n) => existsSync(join(clients, n, 'src'))).sort()) { + const repo = join(repos, name) + const dir = join(root, name) + cpSync(join(clients, name, 'src'), join(dir, 'src'), { recursive: true }) + cpSync(core, join(dir, 'src', 'core'), { recursive: true }) + mkdirSync(join(dir, 'docs')) + writeFileSync(join(dir, 'package.json'), '{"type":"module"}') + const pkg = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf8')).name + const client = /export class (\w+)/.exec(readFileSync(join(dir, 'src', 'client.ts'), 'utf8'))[1] + const ofPackage = (code) => code.replaceAll(`'${pkg}'`, index).replaceAll(`"${pkg}"`, index) + const readme = readFileSync(join(repo, 'README.md'), 'utf8') + const api = readFileSync(join(repo, 'api.md'), 'utf8') + const docs = [] + + // README.md: each block a module of its own. + const blocks = [...readme.matchAll(/```ts\n([\s\S]*?)```/g)].map((m) => ofPackage(m[1])) + if (blocks.length === 0) failures.push(`${name}: README.md has no TypeScript example`) + blocks.forEach((code, i) => { + const prelude = [] + if (!new RegExp(`import \\{[^}]*\\b${client}\\b`).test(code)) prelude.push(`import { ${client} } from ${index}`) + if (!/\bconst client\b/.test(code)) prelude.push(`declare const client: ${client}`) + const file = join(dir, 'docs', `readme-${i}.ts`) + writeFileSync(file, `${prelude.join('\n')}\n${code}export {}\n`) + docs.push(file) + }) + + // api.md: each method line as a value of the signature it writes. + const imports = ofPackage(/```ts\n([\s\S]*?)```/.exec(api)?.[1] ?? '') + const lines = [...api.matchAll(/^- `client\.([\w.]+)\((.*)\): (.+)` $/gm)] + const values = new Set(lines.flatMap((m) => [...`${m[2]} ${m[3]}`.matchAll(/typeof (\w+)/g)].map((t) => t[1]))) + const checks = lines.map((m, i) => `export const m${i}: (${m[2]}) => ${m[3]} = client.${m[1]}`) + const apiFile = join(dir, 'docs', 'api.ts') + writeFileSync(apiFile, [ + imports.trim(), + `import { ${client}${values.size > 0 ? `, ${[...values].join(', ')}` : ''} } from ${index}`, + `declare const client: ${client}`, + ...checks, + ].join('\n') + '\n') + docs.push(apiFile) + const files = readdirSync(join(dir, 'src'), { recursive: true }).filter((f) => f.endsWith('.ts')).map((f) => join(dir, 'src', f)) + try { + execFileSync(tsc, [...strict, ...files, ...docs], { encoding: 'utf8' }) + } catch (e) { + failures.push(`${name}: an example of README.md or a signature of api.md does not compile against the client:\n${e.stdout}`) + } + + // Every method in api.md, every resource in README.md. + const resources = readdirSync(join(dir, 'src', 'resources'), { recursive: true }).filter((f) => f.endsWith('.ts')) + const methods = resources + .map((f) => readFileSync(join(dir, 'src', 'resources', f), 'utf8')) + .reduce((n, text) => n + [...text.matchAll(/^ {2}(?!constructor)\w+\(params/gm)].length, 0) + if (methods !== lines.length) failures.push(`${name}: api.md lists ${lines.length} methods, the client has ${methods}`) + for (const [, access] of api.matchAll(/^## (client\.[\w.]+)$/gm)) { + if (!readme.includes(`\`${access}\``)) failures.push(`${name}: README.md does not name the resource ${access}`) + } + + // No placeholder in any text, nor in the client's doc comments. + const texts = TEXTS.filter((t) => existsSync(join(repo, t))).map((t) => [t, readFileSync(join(repo, t), 'utf8')]) + for (const f of ['client.ts', ...resources.map((r) => `resources/${r}`)]) { + texts.push([`src/${f}`, readFileSync(join(dir, 'src', f), 'utf8')]) + } + for (const [file, text] of texts) { + for (const [pattern, what] of PLACEHOLDERS) { + const hit = pattern.exec(text) + if (hit !== null) failures.push(`${name}/${file}: ${what}: ${JSON.stringify(hit[0])}`) + } + if (file.endsWith('.md')) { + for (const h of emptySections(text)) failures.push(`${name}/${file}: the section "${h}" is empty`) + } + } + const source = readFileSync(join(dir, 'src', 'client.ts'), 'utf8') + const max = Number(/^\s*maxRetries: (\d+),$/m.exec(source)?.[1]) + const key = /^\s*idempotencyHeader: "([^"]+)",$/m.exec(source)?.[1] + for (const problem of retriesSays(readme, max, key)) failures.push(`${name}/README.md: ${problem}`) + console.log(`${name}: ${blocks.length} README examples and ${lines.length} api.md signatures compiled`) +} +rmSync(root, { recursive: true, force: true }) +if (failures.length > 0) { + console.error(failures.join('\n\n')) + process.exit(1) +} +console.log('the texts hold to their clients') diff --git a/crates/flowapi-sdk/tests/tsc.mjs b/crates/flowapi-sdk/tests/tsc.mjs index 27c14a6..e56d405 100644 --- a/crates/flowapi-sdk/tests/tsc.mjs +++ b/crates/flowapi-sdk/tests/tsc.mjs @@ -3,7 +3,10 @@ // TypeScript compiler the oracles use checks the whole under strict and exactOptionalPropertyTypes // and emits JavaScript, and Node imports it: every operation's `request` and `response` is the // SDK's function, its method a string, and every scheme a requirement names is in -// `flowapiSecuritySchemes` unless the kept diagnostics say why not. +// `flowapiSecuritySchemes` unless the kept diagnostics say why not. A case's `x-flowapi-calls` +// write requests through the table as the client does: an operation's `request` given the input, +// its body with the table's encoding of its media type where the input gives none (calls.ts), +// and the body and headers compared exactly: the description's encoding read, then written. // Run from the repository root after `cargo build --release -p flowapi-cli`: // node crates/flowapi-sdk/tests/tsc.mjs [path/to/flowapi] // Exits 1 when anything fails. @@ -58,8 +61,40 @@ for (const name of names) { } } } +// The table's encoding of a body's media type put in the input as the client's `encoded` does. +const bare = (t) => (t.split(';')[0] ?? '').trim().toLowerCase() +function encoded(entry, input) { + const body = input.body + if (entry.encoding === undefined || body === undefined || 'encoding' in body || 'prefixEncoding' in body || 'itemEncoding' in body) return input + const key = Object.keys(entry.encoding).find((k) => bare(k) === bare(body.contentType)) + return key === undefined ? input : { ...input, body: { ...body, ...entry.encoding[key] } } +} +let calls = 0 +for (const name of names) { + const described = JSON.parse(readFileSync(join(cases, `${name}.json`), 'utf8')) + const m = await import(pathToFileURL(resolve(out, 'js', `${name}.js`)).href) + for (const call of described['x-flowapi-calls'] ?? []) { + calls++ + const entry = m.flowapiOperations[call.operation] + // A call's `randoms` (hex, 16 bytes each) are what `crypto.getRandomValues` gives, in turn. + const real = Object.getOwnPropertyDescriptor(globalThis, 'crypto') + const queue = (call.randoms ?? []).map((h) => Uint8Array.from(h.match(/../g), (b) => parseInt(b, 16))) + if (call.randoms) Object.defineProperty(globalThis, 'crypto', { configurable: true, value: { getRandomValues: (b) => { b.set(queue.shift()); return b } } }) + let r + try { + r = entry.request(encoded(entry, call.input)) + } finally { + Object.defineProperty(globalThis, 'crypto', real) + } + const body = r.body instanceof Uint8Array ? new TextDecoder().decode(r.body) : r.body + if (body !== call.expect.body) failures.push(`${name}.${call.operation}: body ${JSON.stringify(body)}, want ${JSON.stringify(call.expect.body)}`) + for (const [k, v] of Object.entries(call.expect.headers ?? {})) { + if (r.headers[k] !== v) failures.push(`${name}.${call.operation}: header ${k} ${JSON.stringify(r.headers[k])}, want ${JSON.stringify(v)}`) + } + } +} if (failures.length > 0) { console.error(failures.join('\n')) process.exit(1) } -console.log(`${names.length} tables type-checked and imported`) +console.log(`${names.length} tables type-checked and imported, ${calls} requests written through them`) diff --git a/crates/flowapi-ts/src/sdk.rs b/crates/flowapi-ts/src/sdk.rs index eaaa1e1..2354ce2 100644 --- a/crates/flowapi-ts/src/sdk.rs +++ b/crates/flowapi-ts/src/sdk.rs @@ -2,8 +2,9 @@ //! operation, `Request(input)`, which writes the request the input makes (path, query, //! headers, body) and sends nothing, and `Response(status, headers, body)`, which reads an //! answer back into the response the description names. A runtime of a few functions is printed -//! once before them (`sdk/runtime.ts` writes requests, `sdk/multipart.ts` their -//! `multipart/form-data` bodies, `sdk/read.ts` reads responses); the output imports nothing. What a call does not depend +//! once before them (`sdk/runtime.ts` writes requests, `sdk/form.ts` their form bodies, +//! `sdk/multipart.ts` their `multipart` bodies, `sdk/read.ts` reads responses); the output +//! imports nothing. What a call does not depend //! on is decided here, once: path templates are split, names percent-encoded and each //! parameter's style chosen as the arguments of one call. @@ -15,9 +16,10 @@ pub use request::method; use flowapi::Program; use std::collections::BTreeSet; -/// The runtime every operation's functions call, printed once: writing a request, its multipart -/// body, then reading a response. +/// The runtime every operation's functions call, printed once: writing a request, its form and +/// multipart bodies, then reading a response. const RUNTIME: &str = include_str!("sdk/runtime.ts"); +const FORM: &str = include_str!("sdk/form.ts"); const MULTIPART: &str = include_str!("sdk/multipart.ts"); const READ: &str = include_str!("sdk/read.ts"); @@ -27,6 +29,7 @@ pub(crate) fn sdk(out: &mut String, p: &Program<'_>) { return; } out.push_str(RUNTIME); + out.push_str(FORM); out.push_str(MULTIPART); out.push_str(READ); let decls: Vec> = endpoints.iter().map(|e| p.name_of(e.ty)).collect(); diff --git a/crates/flowapi-ts/src/sdk/form.ts b/crates/flowapi-ts/src/sdk/form.ts new file mode 100644 index 0000000..4752422 --- /dev/null +++ b/crates/flowapi-ts/src/sdk/form.ts @@ -0,0 +1,88 @@ + +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} diff --git a/crates/flowapi-ts/src/sdk/multipart.ts b/crates/flowapi-ts/src/sdk/multipart.ts index 9ad0a96..eb65cae 100644 --- a/crates/flowapi-ts/src/sdk/multipart.ts +++ b/crates/flowapi-ts/src/sdk/multipart.ts @@ -29,51 +29,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; + +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -89,7 +128,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -105,53 +144,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting diff --git a/crates/flowapi-ts/src/sdk/request.rs b/crates/flowapi-ts/src/sdk/request.rs index 281ef93..841bdc7 100644 --- a/crates/flowapi-ts/src/sdk/request.rs +++ b/crates/flowapi-ts/src/sdk/request.rs @@ -51,18 +51,18 @@ pub(super) fn write(out: &mut String, e: &Endpoint, decl: &str, base: &str) { }; let typed = format!("NonNullable<{decl}[\"requestBody\"]>[{}]", lit(t)); let kind = bare(t); - // `multipart/form-data` is written from its parts, by the Encoding Object's - // defaults and the `encoding` given; another multipart type is the caller's to - // write (its boundary goes in the content type); a type neither JSON, text nor a - // form, or a range, may be given as bytes. + // `multipart/form-data` is written from its parts, by the Encoding Objects + // given by name or position; another multipart type from an array, a part per + // item by position, or as the caller wrote it (its boundary goes in the content + // type); a form by the Encoding Objects given by name; a type neither JSON, text + // nor a form, or a range, may be given as bytes. let (value, more) = if kind == "multipart/form-data" { - (format!("$Form<{typed}>"), "; encoding?: FlowapiEncoding") + (format!("$Form<{typed}>"), "; encoding?: FlowapiEncoding; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart") } else if kind.starts_with("multipart/") { - (String::from("string | Uint8Array"), "") - } else if ReadAs::of(t) == ReadAs::Json - || ReadAs::of(t) == ReadAs::Text - || kind == "application/x-www-form-urlencoded" - { + (format!("$Mixed<{typed}> | string | Uint8Array"), "; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart") + } else if kind == "application/x-www-form-urlencoded" { + (typed, "; encoding?: FlowapiEncoding") + } else if ReadAs::of(t) == ReadAs::Json || ReadAs::of(t) == ReadAs::Text { (typed, "") } else { (format!("{typed} | Uint8Array"), "") @@ -160,18 +160,34 @@ fn expand(p: &Param) -> String { } else { lit(&percent(&p.name)) }; + // A delimited style is `form` in a query and `simple` elsewhere (Swagger 2.0's path and + // header) but for what joins an unexploded array: its delimiter, encoded in a URI. + let delimited = |join| match p.location { + Location::Query => ("", "&", true, "=", join), + Location::Path | Location::Header | Location::QueryString | Location::Cookie => { + ("", ",", false, "", join) + } + }; let (first, sep, named, ifemp, join) = match style { Style::Simple => ("", ",", false, "", ","), Style::Label => (".", ".", false, "", ","), Style::Matrix => (";", ";", true, "", ","), Style::Form => ("", "&", true, "=", ","), - Style::SpaceDelimited => ("", "&", true, "=", "%20"), - Style::PipeDelimited => ("", "&", true, "=", "%7C"), + Style::SpaceDelimited | Style::PipeDelimited | Style::TabDelimited => { + delimited(delimiter(style, raw)) + } Style::Cookie => ("", "; ", true, "=", ","), Style::DeepObject => return format!("$deep({}, {name}, {enc})", finite(p)), }; + // Swagger 2.0: the joins of the arrays inside the value, outermost first. + let nested = if s.nested.is_empty() { + String::new() + } else { + let joins: Vec = s.nested.iter().map(|&n| lit(delimiter(n, raw))).collect(); + format!(", [{}]", joins.join(", ")) + }; format!( - "$x({value}, {name}, {}, {}, {named}, {}, {}, {}, {enc}, {}, {})", + "$x({value}, {name}, {}, {}, {named}, {}, {}, {}, {enc}, {}, {}{nested})", lit(first), lit(sep), lit(ifemp), @@ -182,6 +198,28 @@ fn expand(p: &Param) -> String { ) } +/// What joins an unexploded array's items in a style: a comma, or a delimited style's +/// delimiter, percent-encoded unless the value is written raw (a header). +fn delimiter(style: Style, raw: bool) -> &'static str { + match (style, raw) { + (Style::SpaceDelimited, true) => " ", + (Style::SpaceDelimited, false) => "%20", + (Style::PipeDelimited, true) => "|", + (Style::PipeDelimited, false) => "%7C", + (Style::TabDelimited, true) => "\t", + (Style::TabDelimited, false) => "%09", + ( + Style::Simple + | Style::Label + | Style::Matrix + | Style::Form + | Style::DeepObject + | Style::Cookie, + _, + ) => ",", + } +} + /// One parameter's statement: added to the query, the cookie header or the headers. A path /// parameter goes into the path, written by [`path`]. fn param(out: &mut String, p: &Param) { diff --git a/crates/flowapi-ts/src/sdk/runtime.ts b/crates/flowapi-ts/src/sdk/runtime.ts index ad06837..8c422ef 100644 --- a/crates/flowapi-ts/src/sdk/runtime.ts +++ b/crates/flowapi-ts/src/sdk/runtime.ts @@ -143,10 +143,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -160,6 +161,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -172,7 +174,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -197,6 +199,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -242,30 +257,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } diff --git a/crates/flowapi-ts/tests/cases/swagger20-fields.json b/crates/flowapi-ts/tests/cases/swagger20-fields.json new file mode 100644 index 0000000..0b374c3 --- /dev/null +++ b/crates/flowapi-ts/tests/cases/swagger20-fields.json @@ -0,0 +1,39 @@ +{"swagger":"2.0","info":{"title":"fields","version":"1"}, + "consumes":["application/xml"],"produces":["application/xml"], + "paths":{ + "/bounds":{ + "get":{"operationId":"getBounds", + "parameters":[ + {"name":"n","in":"query","type":"integer","format":"int64","minimum":1,"exclusiveMinimum":true,"maximum":10,"exclusiveMaximum":true,"multipleOf":2,"default":4}, + {"name":"nEnum","in":"query","type":"integer","enum":[0,1,2,3,4,5,6,7],"minimum":2,"exclusiveMinimum":true,"maximum":6,"exclusiveMaximum":true,"multipleOf":2}, + {"name":"nAt","in":"query","type":"integer","enum":[0,1,2,3],"minimum":1,"maximum":2}, + {"name":"s","in":"query","type":"string","format":"date","minLength":2,"maxLength":8,"pattern":"^[a-z]+$"}, + {"name":"sEnum","in":"query","type":"string","enum":["a","bb","bc","ccc","dddd"],"minLength":2,"maxLength":3,"pattern":"^b"}, + {"name":"a","in":"query","type":"array","minItems":1,"maxItems":3,"uniqueItems":true, + "items":{"type":"string","format":"byte","minLength":1,"maxLength":3,"pattern":"^x","default":"x"}}, + {"name":"big","in":"query","type":"array","minItems":2,"maxItems":1000,"items":{"type":"string"}}, + {"name":"aEnum","in":"query","type":"array","items":{"type":"string","enum":["x","xy","yy","xyzw"],"minLength":2,"maxLength":3,"pattern":"^x"}}, + {"name":"m","in":"query","type":"array", + "items":{"type":"array","minItems":1,"maxItems":2,"uniqueItems":true, + "items":{"type":"number","format":"float","minimum":0,"exclusiveMinimum":true,"maximum":9,"exclusiveMaximum":true,"multipleOf":3}}}, + {"name":"mEnum","in":"query","type":"array", + "items":{"type":"integer","enum":[0,3,4,6,9,12],"minimum":0,"exclusiveMinimum":true,"maximum":9,"exclusiveMaximum":true,"multipleOf":3}}, + {"name":"X-Limit","in":"header","type":"integer","default":20}], + "responses":{"200":{"description":"ok","schema":{"type":"string"}, + "headers":{ + "X-Count":{"type":"integer","format":"int32","minimum":0,"exclusiveMinimum":true,"maximum":100,"exclusiveMaximum":true,"multipleOf":5,"default":5}, + "X-Step":{"type":"integer","enum":[0,5,7,10,15],"minimum":0,"exclusiveMinimum":true,"maximum":15,"exclusiveMaximum":true,"multipleOf":5}, + "X-Name":{"type":"string","minLength":1,"maxLength":4,"pattern":"^[A-Z]","default":"A"}, + "X-Code":{"type":"string","enum":["a","Bb","Bcd","Cc","Bcdef"],"minLength":2,"maxLength":3,"pattern":"^B"}, + "X-Mode":{"type":"string","enum":["fast","slow"]}, + "X-Tags":{"type":"array","minItems":1,"maxItems":4,"uniqueItems":true,"items":{"type":"string","enum":["a","b"]}}, + "X-Grid":{"type":"array","items":{"type":"array","items":{"type":"integer","format":"int64"}}}}}}}, + "options":{"operationId":"optionsBounds","responses":{"204":{"description":"allowed"}}}, + "head":{"operationId":"headBounds","responses":{"200":{"description":"there"}}}, + "patch":{"operationId":"patchBounds","consumes":[],"produces":[], + "parameters":[{"name":"body","in":"body","schema":{"type":"object","properties":{"a":{"type":"string"}}}}], + "responses":{"200":{"description":"patched","schema":{"type":"integer"}}}}}, + "/global":{ + "put":{"parameters":[{"name":"body","in":"body","schema":{"type":"string"}}], + "responses":{"200":{"description":"kept","schema":{"type":"string"}}}}}, + "/alias":{"$ref":"#/paths/~1global"}}} diff --git a/crates/flowapi-ts/tests/cases/swagger20-fields.ts b/crates/flowapi-ts/tests/cases/swagger20-fields.ts new file mode 100644 index 0000000..a2860c3 --- /dev/null +++ b/crates/flowapi-ts/tests/cases/swagger20-fields.ts @@ -0,0 +1,106 @@ +// Generated by flowapi from an API description. Do not edit: generate again. + +export type GetBounds = { + parameters?: { + query?: { + n?: number; + nEnum?: 4; + nAt?: 1 | 2; + s?: string; + sEnum?: "bb" | "bc"; + a?: [string, string?, string?]; + big?: [string, string, ...string[]]; + aEnum?: "xy"[]; + m?: [number, number?][]; + mEnum?: (3 | 6)[]; + }; + header?: { + "X-Limit"?: number; + }; + }; + responses: { + "200": { + headers?: { + "X-Count"?: number; + "X-Step"?: 5 | 10; + "X-Name"?: string; + "X-Code"?: "Bb" | "Bcd"; + "X-Mode"?: "fast" | "slow"; + "X-Tags"?: ["a" | "b", ("a" | "b")?, ("a" | "b")?, ("a" | "b")?]; + "X-Grid"?: number[][]; + }; + content: { + "application/xml": string; + }; + }; + }; +}; + +export type OptionsBounds = { + responses: { + "204": Record; + }; +}; + +export type HeadBounds = { + responses: { + "200": Record; + }; +}; + +export type PatchBounds = { + requestBody?: { + "application/json": { + a?: string; + [key: string]: unknown; + }; + }; + responses: { + "200": { + content: { + "application/json": number; + }; + }; + }; +}; + +export type PutGlobal = { + requestBody?: { + "application/xml": string; + }; + responses: { + "200": { + content: { + "application/xml": string; + }; + }; + }; +}; + +export type PutAlias = { + requestBody?: { + "application/xml": string; + }; + responses: { + "200": { + content: { + "application/xml": string; + }; + }; + }; +}; + +export type Paths = { + "/bounds": { + get: GetBounds; + options: OptionsBounds; + head: HeadBounds; + patch: PatchBounds; + }; + "/global": { + put: PutGlobal; + }; + "/alias": { + put: PutAlias; + }; +}; diff --git a/crates/flowapi-ts/tests/print.rs b/crates/flowapi-ts/tests/print.rs index 650e414..a491ea8 100644 --- a/crates/flowapi-ts/tests/print.rs +++ b/crates/flowapi-ts/tests/print.rs @@ -328,14 +328,112 @@ fn generate(uri: &str, text: &str) -> String { // req: oas-3.1.header-object.deprecated — headers.json: @deprecated on the header X-Old // req: oas-3.0.header-object.deprecated — headers.json's reader serves 3.0 the same way // req: oas-3.2.header-object.deprecated — headers.json's reader serves 3.2 the same way -// swagger20-*.json: Swagger 2.0, which the ledger does not hold (no requirement ids). Petstore: +// swagger20-*.json: Swagger 2.0 (the ledger's oas-2.0 ids). +// req: oas-2.0.swagger-object.swagger — swagger20-petstore.json: the document read as Swagger 2.0 +// req: oas-2.0.swagger-object.definitions — swagger20-petstore.json: Category, Tag, Pet, ApiResponse as named types +// req: oas-2.0.definitions-object.pattern-name — swagger20-petstore.json: each definition's name names its type +// req: oas-2.0.swagger-object.consumes — swagger20-petstore.json: AddPet: the body under each of the global consumes +// req: oas-2.0.swagger-object.produces — swagger20-petstore.json: GetPetById: the response under the global produces +// req: oas-2.0.swagger-object.paths — swagger20-petstore.json: every operation's type +// req: oas-2.0.paths-object.pattern-path — swagger20-petstore.json: /pet/{petId}: path parameters from the template +// req: oas-2.0.swagger-object.parameters — swagger20-petstore.json: FindPetsByStatus: limit from #/parameters/Limit +// req: oas-2.0.parameters-definitions-object.pattern-name — swagger20-petstore.json: #/parameters/Limit found by its name +// req: oas-2.0.swagger-object.responses — swagger20-petstore.json: #/responses/BadRequest followed +// req: oas-2.0.responses-definitions-object.pattern-name — swagger20-petstore.json: #/responses/BadRequest found by its name +// req: oas-2.0.reference-object.$ref — swagger20-petstore.json: #/definitions, #/parameters and #/responses references followed +// req: oas-2.0.path-item-object.get — swagger20-petstore.json: GetPetById +// req: oas-2.0.path-item-object.put — swagger20-petstore.json: UpdatePet +// req: oas-2.0.path-item-object.post — swagger20-petstore.json: AddPet +// req: oas-2.0.path-item-object.delete — swagger20-petstore.json: DeletePet +// req: oas-2.0.path-item-object.parameters — swagger20-petstore.json: petId from the Path Item in each of its operations +// req: oas-2.0.operation-object.operationId — swagger20-petstore.json: each type named by its operationId +// req: oas-2.0.operation-object.operationId.may-tools-libraries-use-operationid-uniquely-identify — swagger20-petstore.json: each type named by its operationId +// req: oas-2.0.operation-object.consumes — swagger20-petstore.json: UpdatePet: its own consumes over the global ones +// req: oas-2.0.operation-object.produces — swagger20-petstore.json: FindPetsByStatus: its own produces over the global ones +// req: oas-2.0.operation-object.parameters — swagger20-petstore.json: FindPetsByStatus: query parameters +// req: oas-2.0.operation-object.responses — swagger20-petstore.json: each response by status +// req: oas-2.0.operation-object.deprecated — swagger20-petstore.json: DeletePet: @deprecated +// req: oas-2.0.parameter-object.name — swagger20-petstore.json: each parameter by its name +// req: oas-2.0.parameter-object.in — swagger20-petstore.json: query, path, header and body parameters apart +// req: oas-2.0.parameter-object.required — swagger20-petstore.json: FindPetsByStatus: status required +// req: oas-2.0.parameter-object.required.may-otherwise-property-included-default-value-false — swagger20-petstore.json: FindPetsByStatus: limit, without required, optional +// req: oas-2.0.parameter-object.schema — swagger20-petstore.json: AddPet: the body's schema +// req: oas-2.0.parameter-object.type — swagger20-petstore.json: petId: integer as number +// req: oas-2.0.parameter-object.items — swagger20-petstore.json: FindPetsByStatus: status an array of its items +// req: oas-2.0.items-object.type — swagger20-petstore.json: FindPetsByStatus: status items strings +// req: oas-2.0.items-object.enum — swagger20-petstore.json: FindPetsByStatus: status items one of available, pending, sold +// req: oas-2.0.responses-object.pattern-http-status-code — swagger20-petstore.json: each response by its status +// req: oas-2.0.responses-object.default — swagger20-petstore.json: GetPetById: the default response +// req: oas-2.0.response-object.schema — swagger20-petstore.json: FindPetsByStatus: Pet[] under each produced type +// req: oas-2.0.response-object.headers — swagger20-petstore.json: FindPetsByStatus: X-Rate-Limit and X-Expires-After +// req: oas-2.0.headers-object.pattern-name — swagger20-petstore.json: X-Rate-Limit by its name +// req: oas-2.0.header-object.type — swagger20-petstore.json: X-Rate-Limit: integer as number +// req: oas-2.0.parameter-object.enum — swagger20-forms.json: UpdatePetWithForm: status one of available, sold +// req: oas-2.0.schema-object.discriminator — swagger20-schema.json: Pet: discriminator read as a property's name, the type unchanged +// req: oas-2.0.schema-object.readOnly — swagger20-schema.json: Pet: a required readOnly id optional +// req: oas-2.0.schema-object.pattern-x — swagger20-schema.json: Ext: x-internal read and kept, never an error +// lossy: oas-2.0.schema-object.readOnly.must-not-means-sent-part-response-but-sent — swagger20-schema.json: Pet: one type for requests and responses: a read-only property is optional there, not absent from requests +// req: oas-2.0.path-item-object.$ref — swagger20-fields.json: PutAlias: /alias's operations read from the Path Item its $ref names +// req: oas-2.0.path-item-object.options — swagger20-fields.json: OptionsBounds +// req: oas-2.0.path-item-object.head — swagger20-fields.json: HeadBounds +// req: oas-2.0.path-item-object.patch — swagger20-fields.json: PatchBounds +// req: oas-2.0.operation-object.consumes.may-empty-value-used-clear-global-definition — swagger20-fields.json: PatchBounds: consumes [] clears the global application/xml (the body under application/json, the default) +// req: oas-2.0.operation-object.produces.may-empty-value-used-clear-global-definition — swagger20-fields.json: PatchBounds: produces [] clears the global application/xml (the response under application/json); PutGlobal keeps the global ones +// lossy: oas-2.0.parameter-object.format — swagger20-fields.json: no TS type checks a format; the type of `type` alone (n int64 -> number, s date -> string) +// req: oas-2.0.parameter-object.default — swagger20-fields.json: X-Limit, n: a default leaves the parameter optional and its type unnarrowed (the server's value, not a literal) +// lossy: oas-2.0.parameter-object.maximum — swagger20-fields.json: TypeScript's number has no bound (n stays number); read: an enum is narrowed by it (nAt 1 | 2) +// lossy: oas-2.0.parameter-object.exclusiveMaximum — swagger20-fields.json: TypeScript's number has no bound (n stays number); read in 2.0's boolean form: nEnum (4) drops 6 +// lossy: oas-2.0.parameter-object.minimum — swagger20-fields.json: TypeScript's number has no bound (n stays number); read: an enum is narrowed by it (nAt 1 | 2) +// lossy: oas-2.0.parameter-object.exclusiveMinimum — swagger20-fields.json: TypeScript's number has no bound (n stays number); read in 2.0's boolean form: nEnum (4) drops 2 +// lossy: oas-2.0.parameter-object.multipleOf — swagger20-fields.json: TypeScript's number has no step (n stays number); read: nEnum (4) drops 3 and 5 +// lossy: oas-2.0.parameter-object.maxLength — swagger20-fields.json: TypeScript's string has no length (s stays string); read: sEnum drops dddd +// lossy: oas-2.0.parameter-object.minLength — swagger20-fields.json: TypeScript's string has no length (s stays string); read: sEnum drops a +// lossy: oas-2.0.parameter-object.pattern — swagger20-fields.json: flowapi evaluates no regular expression for a plain string (s stays string); an enum is narrowed by it (sEnum "bb" | "bc") +// lossy: oas-2.0.parameter-object.maxItems — swagger20-fields.json: a short bound is a tuple (a: one to three), a long one is not (big: two or more, maxItems 1000 not held) +// req: oas-2.0.parameter-object.minItems — swagger20-fields.json: a and big: tuples of at least one and two items +// lossy: oas-2.0.parameter-object.uniqueItems — swagger20-fields.json: no TS type checks uniqueness (a) +// lossy: oas-2.0.items-object.format — swagger20-fields.json: no TS type checks a format (a's items byte -> string, m's float -> number) +// req: oas-2.0.items-object.items — swagger20-fields.json: m: an array of arrays of numbers by the nested Items Object +// req: oas-2.0.items-object.default — swagger20-fields.json: a's items: a default leaves them string, no literal +// lossy: oas-2.0.items-object.maximum — swagger20-fields.json: TypeScript's number has no bound (m's items stay number); read: mEnum's items 3 | 6 +// lossy: oas-2.0.items-object.exclusiveMaximum — swagger20-fields.json: TypeScript's number has no bound; read in 2.0's boolean form: mEnum's items drop 9 +// lossy: oas-2.0.items-object.minimum — swagger20-fields.json: TypeScript's number has no bound; read: mEnum's items 3 | 6 +// lossy: oas-2.0.items-object.exclusiveMinimum — swagger20-fields.json: TypeScript's number has no bound; read in 2.0's boolean form: mEnum's items drop 0 +// lossy: oas-2.0.items-object.multipleOf — swagger20-fields.json: TypeScript's number has no step; read: mEnum's items drop 4 +// lossy: oas-2.0.items-object.maxLength — swagger20-fields.json: TypeScript's string has no length (a's items stay string); read: aEnum's items drop xyzw +// lossy: oas-2.0.items-object.minLength — swagger20-fields.json: TypeScript's string has no length (a's items stay string); read: aEnum's items drop x +// lossy: oas-2.0.items-object.pattern — swagger20-fields.json: no regular expression evaluated for a plain string (a's items); an enum is narrowed by it (aEnum's items "xy") +// req: oas-2.0.items-object.maxItems — swagger20-fields.json: m's inner arrays: at most two, a tuple +// req: oas-2.0.items-object.minItems — swagger20-fields.json: m's inner arrays: at least one +// lossy: oas-2.0.items-object.uniqueItems — swagger20-fields.json: no TS type checks uniqueness (m's inner arrays) +// lossy: oas-2.0.header-object.format — swagger20-fields.json: no TS type checks a format (X-Count int32 -> number, X-Grid int64 -> number) +// req: oas-2.0.header-object.items — swagger20-fields.json: X-Grid: an array of arrays of numbers +// req: oas-2.0.header-object.default — swagger20-fields.json: X-Count, X-Name: a default leaves the header's type unnarrowed +// lossy: oas-2.0.header-object.maximum — swagger20-fields.json: TypeScript's number has no bound (X-Count stays number); read: X-Step 5 | 10 +// lossy: oas-2.0.header-object.exclusiveMaximum — swagger20-fields.json: TypeScript's number has no bound; read in 2.0's boolean form: X-Step drops 15 +// lossy: oas-2.0.header-object.minimum — swagger20-fields.json: TypeScript's number has no bound; read: X-Step 5 | 10 +// lossy: oas-2.0.header-object.exclusiveMinimum — swagger20-fields.json: TypeScript's number has no bound; read in 2.0's boolean form: X-Step drops 0 +// lossy: oas-2.0.header-object.multipleOf — swagger20-fields.json: TypeScript's number has no step; read: X-Step drops 7 +// lossy: oas-2.0.header-object.maxLength — swagger20-fields.json: TypeScript's string has no length (X-Name stays string); read: X-Code drops Bcdef +// lossy: oas-2.0.header-object.minLength — swagger20-fields.json: TypeScript's string has no length (X-Name stays string); read: X-Code drops a +// lossy: oas-2.0.header-object.pattern — swagger20-fields.json: no regular expression evaluated for a plain string (X-Name); an enum is narrowed by it (X-Code drops Cc) +// req: oas-2.0.header-object.maxItems — swagger20-fields.json: X-Tags: at most four, a tuple +// req: oas-2.0.header-object.minItems — swagger20-fields.json: X-Tags: at least one +// lossy: oas-2.0.header-object.uniqueItems — swagger20-fields.json: no TS type checks uniqueness (X-Tags) +// req: oas-2.0.header-object.enum — swagger20-fields.json: X-Mode: "fast" | "slow" +// Petstore: // `definitions` as named types, `body` under each type of `consumes`, a response's `schema` under // each of `produces`, non-body parameters and headers as their own schemas, `#/parameters/…` // and `#/responses/…` followed, `trace` not a method. Forms: `formData` as a closed form under // the form types of `consumes`, the operation's fields winning over the Path Item's, `file` as // any value, a body beside a form warned about. Schema: `x-nullable`, `discriminator` as a name, // `$ref` overriding its siblings, 3.x-only keywords (`anyOf`, `nullable`, `writeOnly`, `const`) -// meaning nothing, a required `readOnly` property optional. +// meaning nothing, a required `readOnly` property optional. Fields: the Parameter, Items and +// Header Objects' validation keywords (2.0's boolean `exclusiveMinimum` and `exclusiveMaximum` +// too) narrowing an `enum` and leaving a plain value as wide as its type, `minItems` and +// `maxItems` as tuples, `default` and `format` changing no type, nested Items Objects, `options`, +// `head` and `patch`, a Path Item behind `$ref`, and empty `consumes` and `produces` clearing the +// global ones. #[test] fn cases_print_as_kept() { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/cases"); @@ -390,6 +488,62 @@ fn deep_inputs_do_not_overflow() { assert!(generate("nested.json", &nested).contains("export type Root")); } +// req: oas-2.0.swagger-object.pattern-x — swagger_extensions_change_nothing: an `x-` field of the Swagger Object changes neither the types nor the SDK +// req: oas-2.0.paths-object.pattern-x — swagger_extensions_change_nothing: an `x-` key of the Paths Object is no path +// req: oas-2.0.path-item-object.pattern-x — swagger_extensions_change_nothing: an `x-` key of a Path Item is no operation +// req: oas-2.0.operation-object.pattern-x — swagger_extensions_change_nothing: an `x-` field of an Operation Object changes nothing +// req: oas-2.0.parameter-object.pattern-x — swagger_extensions_change_nothing: an `x-` field of a query, header and body parameter changes nothing +// req: oas-2.0.items-object.pattern-x — swagger_extensions_change_nothing: an `x-` field of an Items Object, nested too, changes nothing +// req: oas-2.0.responses-object.pattern-x — swagger_extensions_change_nothing: an `x-` key of the Responses Object is no status +// req: oas-2.0.response-object.pattern-x — swagger_extensions_change_nothing: an `x-` field of a Response Object changes nothing +// req: oas-2.0.header-object.pattern-x — swagger_extensions_change_nothing: an `x-` field of a response's Header Object changes nothing +/// A Swagger 2.0 description with an `x-` field on every object that takes one prints the same +/// types and the same SDK as without them: a reader ignores extensions (2.0, "Vendor +/// Extensions"). Their values are each kind 2.0 allows: `null`, a primitive, an array, an object. +#[test] +fn swagger_extensions_change_nothing() { + let doc = |x: &[&str; 9]| { + format!( + r#"{{"swagger":"2.0","info":{{"title":"x","version":"1"}}{}, + "paths":{{{}"/p/{{id}}":{{{}"get":{{"operationId":"getP"{}, + "parameters":[ + {{"name":"id","in":"path","required":true,"type":"string"{}}}, + {{"name":"q","in":"query","type":"array","items":{{"type":"array","items":{{"type":"integer"{}}}}}}}, + {{"name":"body","in":"body","schema":{{"type":"object"}}}}], + "responses":{{{}"200":{{"description":"ok","schema":{{"type":"string"}}{}, + "headers":{{"X-N":{{"type":"integer"{}}}}}}}}}}}}}}}}}"#, + x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8] + ) + }; + let with = doc(&[ + r#","x-api":{"a":[1,null]}"#, + r#""x-paths":"not a path","#, + r#""x-item":{"get":{"responses":{}}},"#, + r#","x-op":true"#, + r#","x-param":null"#, + r#","x-items":[1,"two"]"#, + r#""x-status":{"description":"not a status"},"#, + r#","x-response":3.5"#, + r#","x-header":"h""#, + ]); + let without = doc(&[""; 9]); + assert_ne!(with, without); + for sdk in [false, true] { + let print = |text: &str| { + let mut docs = Documents::new(); + docs.add("x.json", text).expect("JSON"); + let target = flowapi_ts::TypeScript::new("out.ts"); + let target = if sdk { target.with_sdk() } else { target }; + let (output, diags) = flowapi::generate(&docs, &target); + let files = output.map(|o| o.files.into_iter().map(|f| f.text).collect::()); + (files.expect("output"), diags.all().len()) + }; + let (printed, warnings) = print(&with); + assert_eq!((printed.clone(), warnings), print(&without), "sdk {sdk}"); + assert!(printed.contains("GetP"), "sdk {sdk}: {printed}"); + } +} + /// G4: the same input prints the same bytes, every time. #[test] fn output_is_deterministic() { diff --git a/crates/flowapi-ts/tests/sdk.rs b/crates/flowapi-ts/tests/sdk.rs index 5dd2739..3b8eaa2 100644 --- a/crates/flowapi-ts/tests/sdk.rs +++ b/crates/flowapi-ts/tests/sdk.rs @@ -15,7 +15,8 @@ //! multipart.json: a `multipart/form-data` body as its parts (`$Form`: a string member may be a //! file, an array's items one part each) with its `encoding` given, 3.2's array of objects, //! another multipart type and a binary type or a range given as bytes. -//! swagger20.json: `collectionFormat` as 3.x styles, `tsv` warned about. reserved.json: schemas +//! swagger20.json: `collectionFormat` as 3.x styles in a path, a query and a header, nested +//! arrays joined by their Items Objects' own, `multi` in a header warned about. reserved.json: schemas //! named as the global types the output names (`Record`, `Object`, and the SDK's `NonNullable`, //! `ReturnType`, `RegExpExecArray`, `Uint8Array`, `ArrayBuffer`, `Promise`, and its exports //! `FlowapiRequestError`, `FlowapiFile`, `FlowapiEncoding`) are declared under other names, with a diff --git a/crates/flowapi-ts/tests/sdk/binary.ts b/crates/flowapi-ts/tests/sdk/binary.ts index 221bcd0..5e59176 100644 --- a/crates/flowapi-ts/tests/sdk/binary.ts +++ b/crates/flowapi-ts/tests/sdk/binary.ts @@ -179,10 +179,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -196,6 +197,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -208,7 +210,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -233,6 +235,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -278,30 +293,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -336,6 +336,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -366,51 +454,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -426,7 +553,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -442,53 +569,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting diff --git a/crates/flowapi-ts/tests/sdk/bodies.json b/crates/flowapi-ts/tests/sdk/bodies.json index dbd4550..31884bf 100644 --- a/crates/flowapi-ts/tests/sdk/bodies.json +++ b/crates/flowapi-ts/tests/sdk/bodies.json @@ -8,9 +8,9 @@ "post":{"operationId":"addPet", "requestBody":{"required":true,"content":{ "application/json":{"schema":{"$ref":"#/components/schemas/Pet"}}, - "application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/Pet"}}, + "application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/Pet"},"encoding":{"name":{"contentType":"application/json"},"tags":{"style":"pipeDelimited"}}}, "multipart/form-data":{"schema":{"$ref":"#/components/schemas/Pet"}}, "text/*":{"schema":{"type":"string"}}}}, "responses":{"201":{"description":"made","headers":{"Location":{"schema":{"type":"string"}}}}}}, "patch":{"operationId":"patchPet","requestBody":{"content":{"application/merge-patch+json":{"schema":{"type":"object"}}}},"responses":{}}}}, - "components":{"schemas":{"Pet":{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}}}} + "components":{"schemas":{"Pet":{"type":"object","properties":{"name":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}}},"required":["name"]}}}} diff --git a/crates/flowapi-ts/tests/sdk/bodies.ts b/crates/flowapi-ts/tests/sdk/bodies.ts index 00f6e4f..fca3d95 100644 --- a/crates/flowapi-ts/tests/sdk/bodies.ts +++ b/crates/flowapi-ts/tests/sdk/bodies.ts @@ -2,6 +2,7 @@ export type Pet = { name: string; + tags?: string[]; [key: string]: unknown; }; @@ -209,10 +210,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -226,6 +228,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -238,7 +241,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -263,6 +266,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -308,30 +324,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -366,6 +367,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -396,51 +485,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -456,7 +584,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -472,53 +600,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting @@ -705,7 +847,7 @@ export function getPetsResponse( return $read($getPetsResponse, status, headers, body) as ReturnType; } -export function addPetRequest(input: { body: { contentType: "application/json" | `application/json;${string}`; value: NonNullable["application/json"] } | { contentType: "application/x-www-form-urlencoded" | `application/x-www-form-urlencoded;${string}`; value: NonNullable["application/x-www-form-urlencoded"] } | { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding } | { contentType: string; value: NonNullable["text/*"] | Uint8Array } }): $Request { +export function addPetRequest(input: { body: { contentType: "application/json" | `application/json;${string}`; value: NonNullable["application/json"] } | { contentType: "application/x-www-form-urlencoded" | `application/x-www-form-urlencoded;${string}`; value: NonNullable["application/x-www-form-urlencoded"]; encoding?: FlowapiEncoding } | { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart } | { contentType: string; value: NonNullable["text/*"] | Uint8Array } }): $Request { const headers: Record = {}; const request: $Request = { method: "POST", path: "/pets", query: "", headers }; if (input.body !== undefined) $put(request, input.body); diff --git a/crates/flowapi-ts/tests/sdk/multipart.ts b/crates/flowapi-ts/tests/sdk/multipart.ts index 13b5184..029a84b 100644 --- a/crates/flowapi-ts/tests/sdk/multipart.ts +++ b/crates/flowapi-ts/tests/sdk/multipart.ts @@ -195,10 +195,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -212,6 +213,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -224,7 +226,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -249,6 +251,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -294,30 +309,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -352,6 +352,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -382,51 +470,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -442,7 +569,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -458,53 +585,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting @@ -670,7 +811,7 @@ function $read(table: $Table, status: number, headers: Record, b } } -export function uploadPhotosRequest(input: NonNullable & { body: { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding } | { contentType: "multipart/mixed" | `multipart/mixed;${string}`; value: string | Uint8Array } | { contentType: "application/octet-stream" | `application/octet-stream;${string}`; value: NonNullable["application/octet-stream"] | Uint8Array } | { contentType: string; value: NonNullable["image/*"] | Uint8Array } }): $Request { +export function uploadPhotosRequest(input: NonNullable & { body: { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart } | { contentType: "multipart/mixed" | `multipart/mixed;${string}`; value: $Mixed["multipart/mixed"]> | string | Uint8Array; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart } | { contentType: "application/octet-stream" | `application/octet-stream;${string}`; value: NonNullable["application/octet-stream"] | Uint8Array } | { contentType: string; value: NonNullable["image/*"] | Uint8Array } }): $Request { const headers: Record = {}; const request: $Request = { method: "POST", path: "/pets/" + $seg(($x(input.path?.["id"], "id", "", ",", false, "", false, ",", $enc, "path", "id") ?? ""), "id", false) + "/photos", query: "", headers }; if (input.body !== undefined) $put(request, input.body); @@ -688,7 +829,7 @@ export function uploadPhotosResponse( return $read($uploadPhotosResponse, status, headers, body) as ReturnType; } -export function orderedRequest(input: { body?: { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding } }): $Request { +export function orderedRequest(input: { body?: { contentType: "multipart/form-data" | `multipart/form-data;${string}`; value: $Form["multipart/form-data"]>; encoding?: FlowapiEncoding; prefixEncoding?: readonly (FlowapiPart | undefined)[]; itemEncoding?: FlowapiPart } }): $Request { const headers: Record = {}; const request: $Request = { method: "POST", path: "/forms", query: "", headers }; if (input.body !== undefined) $put(request, input.body); diff --git a/crates/flowapi-ts/tests/sdk/reserved.ts b/crates/flowapi-ts/tests/sdk/reserved.ts index 53812ec..3a4fff2 100644 --- a/crates/flowapi-ts/tests/sdk/reserved.ts +++ b/crates/flowapi-ts/tests/sdk/reserved.ts @@ -195,10 +195,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -212,6 +213,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -224,7 +226,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -249,6 +251,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -294,30 +309,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -352,6 +352,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -382,51 +470,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -442,7 +569,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -458,53 +585,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting diff --git a/crates/flowapi-ts/tests/sdk/styles.ts b/crates/flowapi-ts/tests/sdk/styles.ts index 4739799..ba83897 100644 --- a/crates/flowapi-ts/tests/sdk/styles.ts +++ b/crates/flowapi-ts/tests/sdk/styles.ts @@ -218,10 +218,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -235,6 +236,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -247,7 +249,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -272,6 +274,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -317,30 +332,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -375,6 +375,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -405,51 +493,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -465,7 +592,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -481,53 +608,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting diff --git a/crates/flowapi-ts/tests/sdk/swagger20.json b/crates/flowapi-ts/tests/sdk/swagger20.json index 320f72a..5eab1de 100644 --- a/crates/flowapi-ts/tests/sdk/swagger20.json +++ b/crates/flowapi-ts/tests/sdk/swagger20.json @@ -1,14 +1,18 @@ {"swagger":"2.0","info":{"title":"swagger","version":"1"},"basePath":"/v1", "paths":{"/pets/{ids}":{"get":{"operationId":"listPets", "parameters":[ - {"name":"ids","in":"path","required":true,"type":"array","items":{"type":"integer"}}, + {"name":"ids","in":"path","required":true,"type":"array","items":{"type":"integer"},"collectionFormat":"pipes"}, {"name":"csv","in":"query","type":"array","items":{"type":"string"}}, {"name":"multi","in":"query","type":"array","items":{"type":"string"},"collectionFormat":"multi"}, {"name":"ssv","in":"query","type":"array","items":{"type":"string"},"collectionFormat":"ssv"}, {"name":"pipes","in":"query","type":"array","items":{"type":"string"},"collectionFormat":"pipes"}, {"name":"tsv","in":"query","type":"array","items":{"type":"string"},"collectionFormat":"tsv"}, - {"name":"X-Ids","in":"header","type":"array","items":{"type":"string"}}], + {"name":"grid","in":"query","type":"array","collectionFormat":"multi","items":{"type":"array","collectionFormat":"pipes","items":{"type":"array","items":{"type":"integer"}}}}, + {"name":"X-Ids","in":"header","type":"array","items":{"type":"string"}}, + {"name":"X-Words","in":"header","type":"array","items":{"type":"string"},"collectionFormat":"ssv"}, + {"name":"X-Tabs","in":"header","type":"array","items":{"type":"string"},"collectionFormat":"tsv"}, + {"name":"X-Many","in":"header","type":"array","items":{"type":"string"},"collectionFormat":"multi"}], "responses":{"200":{"description":"ok","schema":{"type":"array","items":{"type":"string"}}}}}, "post":{"operationId":"addPet","consumes":["application/x-www-form-urlencoded"], - "parameters":[{"name":"ids","in":"path","required":true,"type":"string"},{"name":"name","in":"formData","required":true,"type":"string"}], + "parameters":[{"name":"ids","in":"path","required":true,"type":"string"},{"name":"name","in":"formData","required":true,"type":"string"},{"name":"tags","in":"formData","type":"array","items":{"type":"string"},"collectionFormat":"pipes"}], "responses":{"201":{"description":"made"}}}}}} diff --git a/crates/flowapi-ts/tests/sdk/swagger20.ts b/crates/flowapi-ts/tests/sdk/swagger20.ts index 141917f..e6a6c35 100644 --- a/crates/flowapi-ts/tests/sdk/swagger20.ts +++ b/crates/flowapi-ts/tests/sdk/swagger20.ts @@ -11,9 +11,13 @@ export type ListPets = { ssv?: string[]; pipes?: string[]; tsv?: string[]; + grid?: number[][][]; }; header?: { "X-Ids"?: string[]; + "X-Words"?: string[]; + "X-Tabs"?: string[]; + "X-Many"?: string[]; }; }; responses: { @@ -34,6 +38,7 @@ export type AddPet = { requestBody: { "application/x-www-form-urlencoded": { name: string; + tags?: string[]; }; }; responses: { @@ -192,10 +197,11 @@ function $str(v: unknown): string { /** * One variable expanded by RFC 6570 (§3.2, Appendix A): `first` and `sep` are the operator's, * `named` and `ifemp` too; `join` is what separates the members of an unexploded array or - * object (`,`, or `%20` and `%7C` for the space and pipe styles). `undefined` is nothing to - * write: an absent value, an empty array or object (§2.3). `null` writes the "undefined" column - * of the spec's Style Examples: `name=` for form and cookie, nothing else. NaN or an infinity - * anywhere in the value is refused, as the parameter `pname` in `at`. + * object (`,`, or `%20`, `%7C` and `%09` for the space, pipe and tab styles). `undefined` is + * nothing to write: an absent value, an empty array or object (§2.3). `null` writes the + * "undefined" column of the spec's Style Examples: `name=` for form and cookie, nothing else. + * NaN or an infinity anywhere in the value is refused, as the parameter `pname` in `at`. + * `nest`, Swagger 2.0's, joins the arrays inside an array value, outermost first. */ function $x( v: unknown, @@ -209,6 +215,7 @@ function $x( enc: (s: string) => string, at: string, pname: string, + nest?: readonly string[], ): string | undefined { if (v === undefined) return undefined; if (v === null) return ifemp === "=" ? name + "=" : ""; @@ -221,7 +228,7 @@ function $x( if (typeof item === "number" ? item - item !== 0 : typeof item === "object" && $bad(item)) { throw new FlowapiRequestError(at, pname, "non-finite"); } - const s = enc($str(item)); + const s = nest !== undefined && Array.isArray(item) ? $nest(item, nest, 0, enc) : enc($str(item)); if (explode && named) out += (n++ ? sep : "") + name + (s === "" ? ifemp : "=" + s); else out += (n++ ? (explode ? sep : join) : "") + s; } @@ -246,6 +253,19 @@ function $x( return first + (named && !explode ? name + "=" + out : out); } +/** An array inside an array value (Swagger 2.0's Items Object), its items joined by `nest[d]` + * and an array among them a level deeper; past the last level, or an object, its JSON text. */ +function $nest(v: readonly unknown[], nest: readonly string[], d: number, enc: (s: string) => string): string { + let out = ""; + let n = 0; + for (const item of v) { + if (item === null || item === undefined) continue; + const s = Array.isArray(item) && d + 1 < nest.length ? $nest(item, nest, d + 1, enc) : enc($str(item)); + out += (n++ ? (nest[d] ?? ",") : "") + s; + } + return out; +} + /** `deepObject`: `name[key]=value` for each member; a nested object goes a level deeper, an * array's items repeat their key. */ function $deep(v: unknown, name: string, enc: (s: string) => string): string | undefined { @@ -291,30 +311,15 @@ function $json(type: string): boolean { return bare === "application/json" || bare.endsWith("+json"); } -/** An object as `application/x-www-form-urlencoded`: each member a pair, an array's items - * pairs of the same name, an object member as JSON (the Encoding Object's defaults). */ -function $form(v: unknown): string { - if (v === null || typeof v !== "object") return v === undefined ? "" : $enc($str(v)); - let out = ""; - for (const key of Object.keys(v)) { - const item = (v as Record)[key]; - if (item === undefined) continue; - for (const one of Array.isArray(item) ? item : [item]) { - out += (out === "" ? "" : "&") + $enc(key) + "=" + $enc(one === null ? "" : $str(one)); - } - } - return out; -} - -/** A body in its media type: bytes as given, JSON, a form, or text as given (anything else as - * JSON). NaN or an infinity in a JSON or form body is refused: `JSON.stringify` would write - * `null`. */ -function $body(type: string, v: unknown): string | Uint8Array { +/** A body in its media type: bytes as given, JSON, a form (by the Encoding Objects `enc`), or + * text as given (anything else as JSON). NaN or an infinity in a JSON or form body is refused: + * `JSON.stringify` would write `null`. */ +function $body(type: string, v: unknown, enc?: FlowapiEncoding): string | Uint8Array { if (v instanceof Uint8Array) return v; if (!$json(type)) { if ($bare(type) === "application/x-www-form-urlencoded") { if ($bad(v)) throw new FlowapiRequestError("body", null, "non-finite"); - return $form(v); + return $form(v, enc); } if (typeof v === "string") return v; } @@ -349,6 +354,94 @@ function $set(headers: Record, name: string, s: string | undefin headers[name] = s; } +/** WHATWG's `application/x-www-form-urlencoded` byte serializer: the UTF-8 of every character but + * the ASCII letters and digits and `*-._` percent-encoded, a space as `+` (3.2, "Encoding the + * `x-www-form-urlencoded` Media Type"; Appendix E, browsers). What it writes is also valid RFC + * 3986 query text. */ +function $wenc(s: string): string { + if ($unreserved.test(s) && s.indexOf("~") < 0) return s; + return encodeURIComponent(s).replace($wmarks, $mark).replace($space, "+"); +} + +const $wmarks = /[!'()~]/g; +const $space = /%20/g; + +/** Whether an Encoding Object serializes its value by style: any of `style`, `explode` and + * `allowReserved` written makes it so, and its `contentType` is then not used. */ +function $styled(e: FlowapiPart): boolean { + return e.style !== undefined || e.explode !== undefined || e.allowReserved !== undefined; +} + +/** The join of an unexploded array or object in each style a form takes (2.0's `tsv` as + * `tabDelimited`), as written in a URI. */ +function $joins(style: string): string { + return style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : style === "tabDelimited" ? "\t" : ","; +} + +/** A member of a form serialized by style, as a `query` parameter of that style is: `style` + * `form` unless written, `explode` true for `form` unless written, `allowReserved` keeping the + * reserved characters, the arrays inside an array joined by `nested`; no leading `?`. */ +function $stylePairs(v: unknown, key: string, e: FlowapiPart): string | undefined { + const style = e.style ?? "form"; + const enc = e.allowReserved === true ? $res : $enc; + const name = $enc(key); + if (style === "deepObject") return $deep(v, name, enc); + const join = style === "form" ? "," : $enc($joins(style)); + const nest = e.nested?.map((s) => (s === "form" ? "," : $enc($joins(s)))); + return $x(v, name, "", "&", true, "=", e.explode ?? style === "form", join, enc, "body", key, nest); +} + +/** An object as `application/x-www-form-urlencoded`. A member whose Encoding Object (`enc`, by + * its name) has a style is serialized by it; any other is serialized by its `contentType`, JSON + * for a JSON type and for an object, else its text (a string as it is), then encoded by WHATWG's + * rules; an array's items are pairs of the same name, `null` an empty value. */ +function $form(v: unknown, enc?: FlowapiEncoding): string { + if (v === null || typeof v !== "object") return v === undefined ? "" : $wenc($str(v)); + let out = ""; + for (const key of Object.keys(v)) { + const item = (v as Record)[key]; + if (item === undefined) continue; + const e = enc?.[key]; + if (e !== undefined && $styled(e)) { + out = $add(out, $stylePairs(item, key, e), "&"); + continue; + } + const json = e?.contentType !== undefined && $json(e.contentType); + for (const one of Array.isArray(item) ? item : [item]) { + const s = one === null ? "" : json ? JSON.stringify(one) : $str(one); + out += (out === "" ? "" : "&") + $wenc(key) + "=" + $wenc(s); + } + } + return out; +} + +/** A `multipart/form-data` member serialized by style (3.1, 3.2): as a form member is, but each + * pair its own part and no percent-encoding (`allowReserved` has no effect). `form` exploded + * makes a part per item, or per member of an object under the member's name; unexploded, one + * part of the items joined, an array among them by `nested`; `deepObject` a part per member, + * named `name[key]`. */ +function $styleParts(v: unknown, name: string, e: FlowapiPart): [string, string][] { + const style = e.style ?? "form"; + const explode = e.explode ?? style === "form"; + const out: [string, string][] = []; + if (Array.isArray(v)) { + const nest = e.nested?.map($joins); + const raw = (s: string): string => s; + const items = v.filter((x) => x !== null && x !== undefined).map((x) => (nest !== undefined && Array.isArray(x) ? $nest(x, nest, 0, raw) : $str(x))); + if (explode && style === "form") for (const s of items) out.push([name, s]); + else if (items.length > 0) out.push([name, items.join($joins(style))]); + } else if (typeof v === "object" && v !== null) { + const keys = Object.keys(v).filter((k) => (v as Record)[k] != null); + const at = (k: string) => $str((v as Record)[k]); + if (style === "deepObject") for (const k of keys) out.push([`${name}[${k}]`, at(k)]); + else if (explode && style === "form") for (const k of keys) out.push([k, at(k)]); + else if (keys.length > 0) out.push([name, keys.map((k) => k + $joins(style) + at(k)).join($joins(style))]); + } else if (v !== undefined && v !== null) { + out.push([name, $str(v)]); + } + return out; +} + /** A file to send as a part of a `multipart/form-data` body: its bytes, the name its part's * `filename` is written from and the `Content-Type` it is sent as. Made by `flowapiFile` or * `flowapiBlob`. */ @@ -379,51 +472,90 @@ export async function flowapiBlob(blob: $Blob, name?: string, type?: string): Pr return new FlowapiFile(bytes, name ?? blob.name, type ?? (blob.type === "" ? undefined : blob.type)); } -/** Per part's name, what the description's Encoding Object says of it: the `Content-Type` its - * value is sent as, and the headers its part carries (`Content-Type` among them is ignored, as - * the spec says). An array's items each take their property's. */ -export type FlowapiEncoding = { - readonly [name: string]: { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; +/** One Encoding Object as it applies to a value: the `Content-Type` it is sent as (a list or a + * range needs a file's own type to pick one), the headers of its part (`Content-Type` among them + * ignored, as the spec says; values written as they are), the style it is serialized by in a form + * (`style`, `explode`, `allowReserved`: any written, and `contentType` is not used), `nested` + * the styles that join the arrays inside an array value, outermost first (Swagger 2.0's Items + * Objects), and for a part that is itself `multipart`, the Encoding Objects of its own parts + * (3.2's nesting). */ +export type FlowapiPart = { + readonly contentType?: string; + readonly headers?: { readonly [name: string]: string }; + readonly style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject" | "tabDelimited"; + readonly explode?: boolean; + readonly allowReserved?: boolean; + readonly nested?: readonly ("form" | "spaceDelimited" | "pipeDelimited" | "tabDelimited")[]; + readonly encoding?: FlowapiEncoding; + readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; + readonly itemEncoding?: FlowapiPart; }; +/** Per property's name, its Encoding Object (a form's, or a `multipart/form-data` part's). An + * array's items each take their property's. */ +export type FlowapiEncoding = { readonly [name: string]: FlowapiPart | undefined }; + /** A `multipart/form-data` value as `Request` takes it: a string member may also be a file * (the types cannot tell `format: binary` from text), an array member's items one part each. */ type $Upload = T extends string ? T | Uint8Array | FlowapiFile : T; type $Member = T extends readonly (infer U)[] ? readonly $Upload[] : $Upload; type $Fields = T extends object ? { [K in keyof T]: $Member } : T; export type $Form = T extends readonly (infer U)[] ? readonly $Fields[] : $Fields; +/** Another `multipart` type's value: an array, an item a part each, in order (3.2, "Encoding By + * Position"); its parts' types cannot tell a file from text either. */ +export type $Mixed = unknown extends T ? readonly unknown[] : T extends readonly (infer U)[] ? readonly $Upload[] : never; -/** A request body as the input gives it. */ -type $Given = { readonly contentType: string; readonly value: unknown; readonly encoding?: FlowapiEncoding }; +/** A request body as the input gives it, with the Encoding Objects of its media type: by name + * (`encoding`) or by position (`prefixEncoding`, then `itemEncoding`). */ +type $Given = { readonly contentType: string; readonly value: unknown } & $Layout; +type $Layout = { readonly encoding?: FlowapiEncoding; readonly prefixEncoding?: readonly (FlowapiPart | undefined)[]; readonly itemEncoding?: FlowapiPart }; + +/** How deep `multipart` parts nest: 3.2 asks one level, and more are written up to this. */ +const $nesting = 8; /** The body set on a request with its `Content-Type`: a `multipart/form-data` object (or 3.2's - * array of objects, its parts in order) written as parts, any other value by `$body`. */ + * array of objects, its parts in order) and any `multipart` array written as parts, any other + * value by `$body`. */ function $put(request: $Request, body: $Given): void { const v = body.value; - if ($bare(body.contentType) === "multipart/form-data" && typeof v === "object" && v !== null && !ArrayBuffer.isView(v)) { - const parts: $Part[] = []; - for (const one of Array.isArray(v) ? v : [v]) { - if (one === undefined) continue; - if (one === null) throw new FlowapiRequestError("body", null, "null"); - if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { - throw new FlowapiRequestError("body", null, "unnamed-part"); - } - for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], body.encoding?.[name]); - } - const [type, bytes] = $multipart(body.contentType, parts); + const kind = $bare(body.contentType); + if (kind.startsWith("multipart/") && typeof v === "object" && v !== null && !ArrayBuffer.isView(v) && (kind === "multipart/form-data" || Array.isArray(v))) { + const [type, bytes] = $multipart(body.contentType, $parts(kind, v, body, 0)); request.headers["content-type"] = type; request.body = bytes; return; } request.headers["content-type"] = body.contentType; - request.body = $body(body.contentType, v); + request.body = $body(body.contentType, v, body.encoding); +} + +/** A `multipart` value's parts: `multipart/form-data`'s by its members' names (an array's items + * each an object of them), any other type's an item each, unnamed. An item at position `i` takes + * `prefixEncoding[i]`, else `itemEncoding`; a member without one takes its name's `encoding`. */ +function $parts(kind: string, v: object, layout: $Layout, depth: number): $Part[] { + const parts: $Part[] = []; + const named = kind === "multipart/form-data"; + const list: unknown[] = Array.isArray(v) ? v : [v]; + for (let i = 0; i < list.length; i++) { + const one = list[i]; + if (one === undefined) continue; + if (one === null) throw new FlowapiRequestError("body", null, "null"); + const at = Array.isArray(v) ? (layout.prefixEncoding?.[i] ?? layout.itemEncoding) : undefined; + if (!named) { + $part(parts, undefined, one, at, depth); + continue; + } + if (typeof one !== "object" || Array.isArray(one) || ArrayBuffer.isView(one) || one instanceof FlowapiFile || $unread(one)) { + throw new FlowapiRequestError("body", null, "unnamed-part"); + } + for (const name of Object.keys(one)) $member(parts, name, (one as Record)[name], at ?? layout.encoding?.[name], depth); + } + return parts; } /** One part: its head (`Content-Disposition` and the other headers, each line ended) and data. */ type $Part = { head: string; data: Uint8Array }; -type $One = { readonly contentType?: string; readonly headers?: { readonly [name: string]: string } } | undefined; - let $encoder: { encode(text: string): Uint8Array } | undefined; /** Text as UTF-8 bytes. */ @@ -439,7 +571,7 @@ const $token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; /** `s` refused when it holds a CR, LF or NUL (it would end its header line), and where it goes * between quotes, a `"` or `\`: RFC 7578 and WHATWG's FormData escape them differently, so a * receiver could read another name. */ -function $safe(s: string, part: string, quoted: boolean): string { +function $safe(s: string, part: string | null, quoted: boolean): string { if ($breaks.test(s)) throw new FlowapiRequestError("body", part, "control-character"); if (quoted && $quotes.test(s)) throw new FlowapiRequestError("body", part, "quote"); return s; @@ -455,53 +587,67 @@ function $filename(name: string, part: string): string { return $safe(base, part, true); } -/** A member's parts: an array's items one part each in order, `undefined` none. */ -function $member(parts: $Part[], name: string, v: unknown, e: $One): void { +/** A member's parts: by its Encoding Object's style where it has one (`$styleParts`), else an + * array's items one part each in order; `undefined` none. */ +function $member(parts: $Part[], name: string, v: unknown, e: FlowapiPart | undefined, depth: number): void { if (v === undefined) return; $safe(name, name, true); - if (!Array.isArray(v)) return $part(parts, name, v, e); - for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e); + if (e !== undefined && $styled(e) && v !== null && !$unread(v) && !(v instanceof FlowapiFile) && !ArrayBuffer.isView(v)) { + if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + for (const [n, s] of $styleParts(v, name, e)) { + $safe(n, name, true); + parts.push({ head: `Content-Disposition: form-data; name="${n}"\r\n`, data: $bytes(s) }); + } + return; + } + if (!Array.isArray(v)) return $part(parts, name, v, e, depth); + for (let i = 0; i < v.length; i++) if (v[i] !== undefined) $part(parts, name, v[i], e, depth); } /** One part, by the Encoding Object's defaults for the value: bytes and files as files (WHATWG's * `blob` for a name not given, `application/octet-stream` for a type not given), strings, * numbers and booleans as text (`text/plain`, the part's default, so not written), objects and - * arrays as JSON. `encoding.contentType` replaces the default; a file's own type replaces it. */ -function $part(parts: $Part[], name: string, v: unknown, e: $One): void { - if (v === null) throw new FlowapiRequestError("body", name, "null"); + * arrays as JSON. `e.contentType` replaces the default; a file's own type replaces it. A part of + * a `multipart` type is written as its own body, by `e`'s nested Encoding Objects. A part with no + * `name` (not `multipart/form-data`) has no `Content-Disposition`. */ +function $part(parts: $Part[], name: string | undefined, v: unknown, e: FlowapiPart | undefined, depth: number): void { + const at = name ?? null; + if (v === null) throw new FlowapiRequestError("body", at, "null"); // Bytes in any other view are the same bytes. if (v instanceof ArrayBuffer) v = new Uint8Array(v); else if (ArrayBuffer.isView(v) && !(v instanceof Uint8Array)) v = new Uint8Array(v.buffer, v.byteOffset, v.byteLength); - let head = `Content-Disposition: form-data; name="${name}"`; + const lines: string[] = name === undefined ? [] : [`Content-Disposition: form-data; name="${name}"`]; let type = e?.contentType; let data: Uint8Array; if (v instanceof FlowapiFile || v instanceof Uint8Array) { const file = v instanceof FlowapiFile ? v : undefined; - head += `; filename="${$filename(file?.name ?? "blob", name)}"`; + if (name !== undefined) lines[0] += `; filename="${$filename(file?.name ?? "blob", name)}"`; type = file?.type ?? type ?? "application/octet-stream"; data = file?.data ?? (v as Uint8Array); } else if ($unread(v)) { - throw new FlowapiRequestError("body", name, "unread-blob"); + throw new FlowapiRequestError("body", at, "unread-blob"); + } else if (type !== undefined && $bare(type).startsWith("multipart/") && typeof v === "object" && depth < $nesting) { + [type, data] = $multipart(type, $parts($bare(type), v as object, e ?? {}, depth + 1)); } else { - if ($bad(v)) throw new FlowapiRequestError("body", name, "non-finite"); + if ($bad(v)) throw new FlowapiRequestError("body", at, "non-finite"); type ??= typeof v === "object" ? "application/json" : undefined; // An object in its type (JSON, or a form), a scalar as its text unless the type is JSON. - const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v) : $str(v); + const s = typeof v === "object" || (type !== undefined && $json(type)) ? $body(type ?? "application/json", v, e?.encoding) : $str(v); data = typeof s === "string" ? $bytes(s) : s; } if (type !== undefined) { - if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", name, "media-range"); - head += `\r\nContent-Type: ${$safe(type, name, false)}`; + if (type.indexOf(",") >= 0 || $bare(type).indexOf("*") >= 0) throw new FlowapiRequestError("body", at, "media-range"); + lines.push(`Content-Type: ${$safe(type, at, false)}`); } const headers = e?.headers ?? {}; for (const key of Object.keys(headers)) { const value = headers[key]; const lower = key.toLowerCase(); if (value === undefined || lower === "content-type") continue; - if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", name, "header-name"); - head += `\r\n${key}: ${$safe(value, name, false)}`; + if (!$token.test(key) || lower === "content-disposition") throw new FlowapiRequestError("body", at, "header-name"); + lines.push(`${key}: ${$safe(value, at, false)}`); } - parts.push({ head: head + "\r\n", data }); + parts.push({ head: lines.map((l) => l + "\r\n").join(""), data }); } /** A `Blob`, a `File` or a `Response` given unread: its bytes come only by waiting @@ -674,9 +820,13 @@ export function listPetsRequest(input: NonNullable): $Re query = $add(query, $x(input.query?.["multi"], "multi", "", "&", true, "=", true, ",", $enc, "query", "multi"), "&"); query = $add(query, $x(input.query?.["ssv"], "ssv", "", "&", true, "=", false, "%20", $enc, "query", "ssv"), "&"); query = $add(query, $x(input.query?.["pipes"], "pipes", "", "&", true, "=", false, "%7C", $enc, "query", "pipes"), "&"); - query = $add(query, $x(input.query?.["tsv"], "tsv", "", "&", true, "=", false, ",", $enc, "query", "tsv"), "&"); + query = $add(query, $x(input.query?.["tsv"], "tsv", "", "&", true, "=", false, "%09", $enc, "query", "tsv"), "&"); + query = $add(query, $x(input.query?.["grid"], "grid", "", "&", true, "=", true, ",", $enc, "query", "grid", ["%7C", ","]), "&"); $set(headers, "X-Ids", $x(input.header?.["X-Ids"], "X-Ids", "", ",", false, "", false, ",", $raw, "header", "X-Ids")); - const request: $Request = { method: "GET", path: "/pets/" + $seg(($x(input.path?.["ids"], "ids", "", ",", false, "", false, ",", $enc, "path", "ids") ?? ""), "ids", false), query, headers }; + $set(headers, "X-Words", $x(input.header?.["X-Words"], "X-Words", "", ",", false, "", false, " ", $raw, "header", "X-Words")); + $set(headers, "X-Tabs", $x(input.header?.["X-Tabs"], "X-Tabs", "", ",", false, "", false, "\t", $raw, "header", "X-Tabs")); + $set(headers, "X-Many", $x(input.header?.["X-Many"], "X-Many", "", ",", false, "", false, ",", $raw, "header", "X-Many")); + const request: $Request = { method: "GET", path: "/pets/" + $seg(($x(input.path?.["ids"], "ids", "", ",", false, "", false, "%7C", $enc, "path", "ids") ?? ""), "ids", false), query, headers }; return request; } @@ -691,7 +841,7 @@ export function listPetsResponse( return $read($listPetsResponse, status, headers, body) as ReturnType; } -export function addPetRequest(input: NonNullable & { body: { contentType: "application/x-www-form-urlencoded" | `application/x-www-form-urlencoded;${string}`; value: NonNullable["application/x-www-form-urlencoded"] } }): $Request { +export function addPetRequest(input: NonNullable & { body: { contentType: "application/x-www-form-urlencoded" | `application/x-www-form-urlencoded;${string}`; value: NonNullable["application/x-www-form-urlencoded"]; encoding?: FlowapiEncoding } }): $Request { const headers: Record = {}; const request: $Request = { method: "POST", path: "/pets/" + $seg(($x(input.path?.["ids"], "ids", "", ",", false, "", false, ",", $enc, "path", "ids") ?? ""), "ids", false), query: "", headers }; if (input.body !== undefined) $put(request, input.body); @@ -708,4 +858,4 @@ export function addPetResponse( | { response: null; status: number; mediaType: string | null; body: string | Uint8Array } { return $read($addPetResponse, status, headers, body) as ReturnType; } -// warning[swagger.collectionFormat]: `collectionFormat` tsv has no 3.x style in `query`: written as `csv` +// warning[swagger.collectionFormat]: `collectionFormat` multi is not one a parameter in `header` takes: written as `csv` diff --git a/crates/flowapi-wasm/src/repo.rs b/crates/flowapi-wasm/src/repo.rs index 494f7a3..cbea83c 100644 --- a/crates/flowapi-wasm/src/repo.rs +++ b/crates/flowapi-wasm/src/repo.rs @@ -189,7 +189,8 @@ fn generate(r: RepoRequest<'_>, text: &mut String) -> Result<(Repo, Option } let target = flowapi_ts::TypeScript::new("src/api.ts").with_sdk(); let (program, diags) = flowapi::program(&docs, &target); - for d in diags.all().iter().filter(|d| d.severity == Severity::Error) { + // The core's warnings too, as the command prints them. + for d in diags.all() { let _ = writeln!(text, "{}", line(&found(&sources, d))); } let uri = sources.first().map_or("", |s| s.uri.as_ref()); diff --git a/crates/flowapi/src/graph.rs b/crates/flowapi/src/graph.rs index 4dbcc73..fd1f62a 100644 --- a/crates/flowapi/src/graph.rs +++ b/crates/flowapi/src/graph.rs @@ -82,7 +82,7 @@ pub struct Type<'t> { impl Type<'_> { /// A type with only a shape. #[must_use] - pub fn of(kind: Kind<'_>) -> Type<'_> { + pub const fn of(kind: Kind<'_>) -> Type<'_> { Type { kind, origin: None, @@ -170,13 +170,4 @@ impl<'t> Graph<'t> { } } -static ANY: Type<'static> = Type { - kind: Kind::Any, - origin: None, - title: None, - description: None, - lossy: Vec::new(), - deprecated: false, - read_only: false, - write_only: false, -}; +static ANY: Type<'static> = Type::of(Kind::Any); diff --git a/crates/flowapi/src/graph/branches.rs b/crates/flowapi/src/graph/branches.rs index eec2c85..25977a4 100644 --- a/crates/flowapi/src/graph/branches.rs +++ b/crates/flowapi/src/graph/branches.rs @@ -72,6 +72,28 @@ pub struct Lit<'t> { pub norm: Cow<'t, str>, } +impl Lit<'_> { + /// Whether it is an integer: a number with a zero fractional part, `1.0` among them. + pub(crate) fn is_integer(&self) -> bool { + self.raw + .parse::() + .is_ok_and(|v| v.is_finite() && v.fract() == 0.0) + } + + /// The values both lists allow, in `a`'s order; `None` allows every value. + pub(crate) fn common(a: Option>, b: Option<&[Self]>) -> Option> { + match (a, b) { + (Some(x), Some(y)) => Some( + x.into_iter() + .filter(|l| y.iter().any(|e| e.norm == l.norm)) + .collect(), + ), + (x, None) => x, + (None, y) => y.map(<[Self]>::to_vec), + } + } +} + /// Which booleans a type allows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Bools { diff --git a/crates/flowapi/src/graph/build.rs b/crates/flowapi/src/graph/build.rs index a36b840..f2f5d61 100644 --- a/crates/flowapi/src/graph/build.rs +++ b/crates/flowapi/src/graph/build.rs @@ -107,12 +107,7 @@ impl<'d, 't> Builder<'d, 't> { /// The type of a schema under `parent`, read with the same base and dialect. pub(super) fn sub(&mut self, parent: &Resource, node: NodeId) -> TypeId { - self.type_of(&Resource { - doc: parent.doc, - node, - base: std::sync::Arc::clone(&parent.base), - dialect: parent.dialect, - }) + self.type_of(&parent.at(node)) } /// A type the graph makes, with no schema of its own. @@ -148,8 +143,7 @@ impl<'d, 't> Builder<'d, 't> { return ty; } } - let at = self.scoped(at); - let mut at = at; + let mut at = self.scoped(at); match self.vocabularies(&at) { Meaning::All => {} Meaning::NoValidation => at.dialect = Dialect::Draft2020Annotations, diff --git a/crates/flowapi/src/graph/local.rs b/crates/flowapi/src/graph/local.rs index 25926dd..f80d790 100644 --- a/crates/flowapi/src/graph/local.rs +++ b/crates/flowapi/src/graph/local.rs @@ -50,11 +50,7 @@ impl<'t> Builder<'_, 't> { if !matches!(tree.value(node), Value::Object(_) | Value::Bool(_)) { return None; } - let schema = Resource { - node, - base: std::sync::Arc::clone(&at.base), - ..*at - }; + let schema = at.at(node); let (read, own) = self.read(&schema); let plain = read.reference.is_none() && read.parts.is_empty() diff --git a/crates/flowapi/src/graph/narrow.rs b/crates/flowapi/src/graph/narrow.rs index d2bafda..b11473a 100644 --- a/crates/flowapi/src/graph/narrow.rs +++ b/crates/flowapi/src/graph/narrow.rs @@ -41,13 +41,11 @@ pub(super) fn restrict<'t>(b: &mut Branches<'t>, tree: &Tree<'t>, values: &[Node } fn narrow_numbers<'t>(n: &Numbers<'t>, values: Vec>) -> Option> { - let mut lits: Vec> = values + let values = values .into_iter() - .filter(|l| !n.integer || is_integer(l.raw)) + .filter(|l| !n.integer || l.is_integer()) .collect(); - if let Some(existing) = &n.lits { - lits.retain(|l| existing.iter().any(|e| e.norm == l.norm)); - } + let mut lits = Lit::common(Some(values), n.lits.as_deref()).unwrap_or_default(); dedupe(&mut lits); (!lits.is_empty()).then_some(Numbers { integer: n.integer, @@ -56,10 +54,7 @@ fn narrow_numbers<'t>(n: &Numbers<'t>, values: Vec>) -> Option(s: Strings<'t>, values: Vec>) -> Option> { - let mut lits = values; - if let Some(existing) = &s.lits { - lits.retain(|l| existing.iter().any(|e| e.norm == l.norm)); - } + let mut lits = Lit::common(Some(values), s.lits.as_deref()).unwrap_or_default(); dedupe(&mut lits); (!lits.is_empty()).then_some(Strings { format: s.format, @@ -78,11 +73,6 @@ fn dedupe(lits: &mut Vec>) { }); } -fn is_integer(raw: &str) -> bool { - raw.parse::() - .is_ok_and(|v| v.is_finite() && v.fract() == 0.0) -} - pub(super) fn number_lit(raw: &str) -> Lit<'_> { let norm = raw.parse::().map_or_else( |_| raw.to_owned(), diff --git a/crates/flowapi/src/graph/ops.rs b/crates/flowapi/src/graph/ops.rs index 672d66b..b2192de 100644 --- a/crates/flowapi/src/graph/ops.rs +++ b/crates/flowapi/src/graph/ops.rs @@ -58,19 +58,16 @@ impl<'t> Builder<'_, 't> { Location::Header, Location::Cookie, ] { - let params: Vec<_> = op + let props: Vec<_> = op .params .iter() .filter(|p| p.location == location) + .map(|p| (p.name.clone(), self.param(p), p.required)) .collect(); - if params.is_empty() { + if props.is_empty() { continue; } - let required = params.iter().any(|p| p.required); - let props = params - .iter() - .map(|p| (p.name.clone(), self.param(p), p.required)) - .collect(); + let required = props.iter().any(|p| p.2); let ty = self.closed(props); locations.push((location.name().to_owned(), ty, required)); } diff --git a/crates/flowapi/src/graph/unevaluated.rs b/crates/flowapi/src/graph/unevaluated.rs index 1f00ccf..2df7d75 100644 --- a/crates/flowapi/src/graph/unevaluated.rs +++ b/crates/flowapi/src/graph/unevaluated.rs @@ -106,36 +106,18 @@ impl<'t> Builder<'_, 't> { fn applied(tree: &crate::json::Tree<'_>, r: &Resource, stack: &mut Vec<(Resource, bool)>) { for key in ["allOf", "anyOf", "oneOf"] { for &n in tree.get(r.node, key).map_or(&[][..], |a| tree.items(a)) { - stack.push(( - Resource { - node: n, - ..r.clone() - }, - false, - )); + stack.push((r.at(n), false)); } } for key in ["if", "then", "else"] { if let Some(n) = tree.get(r.node, key) { - stack.push(( - Resource { - node: n, - ..r.clone() - }, - false, - )); + stack.push((r.at(n), false)); } } for m in tree .get(r.node, "dependentSchemas") .map_or(&[][..], |n| tree.members(n)) { - stack.push(( - Resource { - node: m.value, - ..r.clone() - }, - false, - )); + stack.push((r.at(m.value), false)); } } diff --git a/crates/flowapi/src/json/parse.rs b/crates/flowapi/src/json/parse.rs index efda785..3633abf 100644 --- a/crates/flowapi/src/json/parse.rs +++ b/crates/flowapi/src/json/parse.rs @@ -95,6 +95,9 @@ impl Reader<'_> { fn value(&mut self, parent: Option, depth: u32) -> Result { let id = self.node(parent)?; let value = match self.peek() { + Some(b'{' | b'[') if depth >= MAX_DEPTH => { + return Err(self.error("nesting deeper than 512 levels")); + } Some(b'{') => self.object(id, depth)?, Some(b'[') => self.array(id, depth)?, Some(b'"') => Value::String(self.string()?), @@ -118,9 +121,6 @@ impl Reader<'_> { } fn array(&mut self, id: NodeId, depth: u32) -> Result { - if depth >= MAX_DEPTH { - return Err(self.error("nesting deeper than 512 levels")); - } self.at += 1; let mark = self.scratch_items.len(); self.space(); @@ -151,9 +151,6 @@ impl Reader<'_> { } fn object(&mut self, id: NodeId, depth: u32) -> Result { - if depth >= MAX_DEPTH { - return Err(self.error("nesting deeper than 512 levels")); - } self.at += 1; let mark = self.scratch_members.len(); self.space(); diff --git a/crates/flowapi/src/lower/merge/branch.rs b/crates/flowapi/src/lower/merge/branch.rs index 71e33b1..e72cca4 100644 --- a/crates/flowapi/src/lower/merge/branch.rs +++ b/crates/flowapi/src/lower/merge/branch.rs @@ -103,15 +103,10 @@ pub(super) fn narrows(b: &Branches<'_>, allowed: Kinds) -> bool { fn numbers<'t>(a: Numbers<'t>, b: &Numbers<'t>) -> Option> { let integer = a.integer || b.integer; - let lits = match (a.lits, &b.lits) { - (Some(x), Some(y)) => Some(common(x, y)), - (Some(x), None) => Some(x), - (None, Some(y)) => Some(y.clone()), - (None, None) => None, - }; + let lits = Lit::common(a.lits, b.lits.as_deref()); let lits = lits.map(|l| { if integer { - l.into_iter().filter(|v| is_integer(v.raw)).collect() + l.into_iter().filter(Lit::is_integer).collect() } else { l } @@ -123,12 +118,7 @@ fn numbers<'t>(a: Numbers<'t>, b: &Numbers<'t>) -> Option> { } fn strings<'t>(a: Strings<'t>, b: &Strings<'t>) -> Option> { - let lits = match (a.lits, &b.lits) { - (Some(x), Some(y)) => Some(common(x, y)), - (Some(x), None) => Some(x), - (None, Some(y)) => Some(y.clone()), - (None, None) => None, - }; + let lits = Lit::common(a.lits, b.lits.as_deref()); match &lits { Some(l) if l.is_empty() => None, Some(_) | None => Some(Strings { @@ -137,14 +127,3 @@ fn strings<'t>(a: Strings<'t>, b: &Strings<'t>) -> Option> { }), } } - -fn common<'t>(a: Vec>, b: &[Lit<'t>]) -> Vec> { - a.into_iter() - .filter(|x| b.iter().any(|y| y.norm == x.norm)) - .collect() -} - -fn is_integer(raw: &str) -> bool { - raw.parse::() - .is_ok_and(|v| v.is_finite() && v.fract() == 0.0) -} diff --git a/crates/flowapi/src/schema/index.rs b/crates/flowapi/src/schema/index.rs index eaff355..953b523 100644 --- a/crates/flowapi/src/schema/index.rs +++ b/crates/flowapi/src/schema/index.rs @@ -24,6 +24,17 @@ pub struct Resource { pub dialect: Dialect, } +impl Resource { + /// The schema at `node` of the same document, read in the same base and dialect. + pub(crate) fn at(&self, node: NodeId) -> Self { + Self { + node, + base: Arc::clone(&self.base), + ..*self + } + } +} + /// What a reference resolved to. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Target { @@ -89,12 +100,7 @@ impl Index { .seen .insert((at.doc, at.node), (Arc::clone(&at.base), at.dialect)); for (_, node) in subschemas(tree, at.node, dialect).into_iter().rev() { - stack.push(Resource { - doc: at.doc, - node, - base: Arc::clone(&base), - dialect, - }); + stack.push(scoped.at(node)); } } index diff --git a/crates/flowapi/src/spec/operations.rs b/crates/flowapi/src/spec/operations.rs index 1467d75..3d327cd 100644 --- a/crates/flowapi/src/spec/operations.rs +++ b/crates/flowapi/src/spec/operations.rs @@ -48,7 +48,8 @@ impl Location { } /// How a parameter's value is written (3.2, "Style Values"): RFC 6570's operators and the three -/// query styles it has no operator for, and 3.2's `cookie`. +/// query styles it has no operator for, 3.2's `cookie`, and Swagger 2.0's `tsv`. In 2.0 the +/// delimited styles go in a path and a header too: a `collectionFormat` is allowed in each. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Style { /// `;name=value` (RFC 6570 `{;x}`), in a path. @@ -63,6 +64,8 @@ pub enum Style { SpaceDelimited, /// Values joined by `|`, in a query (2.0's `pipes`). PipeDelimited, + /// Values joined by a tab: 2.0's `tsv`, which no 3.x style is. + TabDelimited, /// `name[key]=value` for each member of an object, in a query. DeepObject, /// `name=value; name=value` with no percent-encoding, in a cookie (3.2). @@ -80,6 +83,7 @@ impl Style { Self::Form => "form", Self::SpaceDelimited => "spaceDelimited", Self::PipeDelimited => "pipeDelimited", + Self::TabDelimited => "tabDelimited", Self::DeepObject => "deepObject", Self::Cookie => "cookie", } @@ -100,6 +104,11 @@ pub struct Serialization { pub allow_reserved: bool, /// The media type of `content`, when the value is serialized by it rather than by style. pub media_type: Option, + /// Swagger 2.0: how the arrays inside an array value are joined, one style per level of + /// `items` that is an array, outermost first (an Items Object's `collectionFormat`): + /// `Simple` for `csv` (`,`), else a delimited style. Empty in 3.x, where an array inside a + /// value is its JSON text. + pub nested: Vec