From c963bd2c1f4188cf4c9592980632735f29420161 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 27 Aug 2026 13:24:06 +0530 Subject: [PATCH 1/4] feat: generate additive OpenAPI v3 document Convert the finalized Swagger 2 artifact to a deterministic OpenAPI 3.0.3 document with strict parity validation and additive CI coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .gitattributes | 1 + .github/dependabot.yaml | 9 + .github/workflows/review.yaml | 18 +- .gitignore | 1 + Makefile | 5 +- README.md | 13 +- docs/openapiv3/apidocs.openapi.json | 5146 +++++++++++++++++++++++++++ package-lock.json | 493 +++ package.json | 10 + scripts/generate_openapiv3.js | 478 +++ 10 files changed, 6170 insertions(+), 4 deletions(-) create mode 100644 docs/openapiv3/apidocs.openapi.json create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 scripts/generate_openapiv3.js diff --git a/.gitattributes b/.gitattributes index 5fb64c41..d6884cd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ /docs/openapiv2/apidocs.swagger.json linguist-generated=true +/docs/openapiv3/apidocs.openapi.json linguist-generated=true *.pb.go linguist-generated=true *.pb.*.go linguist-generated=true go.sum linguist-generated=true diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index c3ad2246..b203fcee 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -11,6 +11,15 @@ updates: patterns: - "*" + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + groups: + dependencies: + patterns: + - "*" + - package-ecosystem: "github-actions" directory: "/" schedule: diff --git a/.github/workflows/review.yaml b/.github/workflows/review.yaml index fda1df2f..9a7fbd95 100644 --- a/.github/workflows/review.yaml +++ b/.github/workflows/review.yaml @@ -30,10 +30,15 @@ jobs: with: fetch-depth: 0 - uses: bufbuild/buf-setup-action@a47c93e0b1648d5651a065437926377d060baa99 # v1.50.0 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + cache: npm + - run: npm ci - name: "Generate OpenAPI & Diff" run: | make all - git diff --text --exit-code docs/openapiv2/apidocs.swagger.json proto/**/*.go + git diff --text --exit-code docs/openapiv2/apidocs.swagger.json docs/openapiv3/apidocs.openapi.json proto/**/*.go validate-openapi: runs-on: ubuntu-latest @@ -45,3 +50,14 @@ jobs: with: definition-file: './docs/openapiv2/apidocs.swagger.json' fails-on: 1 + + validate-openapiv3: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + fetch-depth: 0 + - uses: swaggerexpert/apidom-validate@f839307deab4db59c7814834a2076d309e23b535 # v1 + with: + definition-file: './docs/openapiv3/apidocs.openapi.json' + fails-on: 1 diff --git a/.gitignore b/.gitignore index 22ac7755..976b6c52 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ .DS_Store .env +node_modules/ diff --git a/Makefile b/Makefile index c70c06cc..ec08b14c 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -all: patch-swagger-doc format +all: openapi-v3 format buf-gen: init-git-hooks ./buf.gen.yaml @@ -6,6 +6,9 @@ buf-gen: init-git-hooks patch-swagger-doc: buf-gen ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json +openapi-v3: patch-swagger-doc + npm run --silent generate:openapiv3 + format: buf-gen buf format -w diff --git a/README.md b/README.md index dd887f03..33858c85 100644 --- a/README.md +++ b/README.md @@ -55,21 +55,30 @@ may be overly strict. In those cases you can bypass it with `commit --no-verify` ``` ### Generating OpenAPI Documentation -To generate the OpenAPI documentation from the protobuf sources you can run the following commands: +Generation produces both the finalized Swagger 2.0 document at +`docs/openapiv2/apidocs.swagger.json` and an additive OpenAPI 3.0.3 document at +`docs/openapiv3/apidocs.openapi.json`. -> **Note**: You must have [jq](https://jqlang.github.io/jq/download/) installed to run the `format` step below +> **Note**: You must have [jq](https://jqlang.github.io/jq/download/), Node.js, and npm installed. ```bash +npm ci ./buf.gen.yaml ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json +npm run generate:openapiv3 buf format -w ``` Or you can just use ```bash +npm ci make ``` +The OpenAPI 3 document is deterministically converted from the finalized Swagger 2 document. +Existing SDK generation remains compatible with, and must continue to use, +`docs/openapiv2/apidocs.swagger.json`. + See [CONTRIBUTING](https://github.com/openfga/.github/blob/main/CONTRIBUTING.md). ## Author diff --git a/docs/openapiv3/apidocs.openapi.json b/docs/openapiv3/apidocs.openapi.json new file mode 100644 index 00000000..0c07a51c --- /dev/null +++ b/docs/openapiv3/apidocs.openapi.json @@ -0,0 +1,5146 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "OpenFGA", + "description": "A high performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar.", + "version": "1.x", + "contact": { + "name": "OpenFGA", + "url": "https://openfga.dev", + "email": "community@openfga.dev" + }, + "license": { + "name": "Apache-2.0", + "url": "https://github.com/openfga/openfga/blob/main/LICENSE" + } + }, + "tags": [ + { + "name": "AuthZenService" + }, + { + "name": "OpenFGAService" + } + ], + "paths": { + "/.well-known/authzen-configuration/{store_id}": { + "get": { + "summary": "[Experimental] Get AuthZEN PDP configuration and capabilities", + "description": "[Experimental] The GetConfiguration API returns metadata about the Policy Decision Point (PDP) including its name, version, supported endpoints, and capabilities. This endpoint follows the AuthZEN specification for PDP discovery.\n\nFollowing the AuthZEN spec's multi-tenant pattern, OpenFGA provides a per-store discovery endpoint at `/.well-known/authzen-configuration/{store_id}`. This returns absolute endpoint URLs specific to that store.\n\n## Example Response\n```json\n{\n \"policy_decision_point\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV\",\n \"access_evaluation_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/evaluation\",\n \"access_evaluations_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/evaluations\",\n \"search_subject_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/subject\",\n \"search_resource_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/resource\",\n \"search_action_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/action\"\n}\n```\n", + "operationId": "GetConfiguration", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetConfigurationResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "description": "The store ID for which to retrieve configuration.\nFollowing the AuthZEN spec's multi-tenant pattern, each store has its own discovery endpoint.", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "AuthZenService" + ] + } + }, + "/stores": { + "get": { + "summary": "List all stores", + "description": "Returns a paginated list of OpenFGA stores and a continuation token to get additional stores.\nThe continuation token will be empty if there are no more stores.\n", + "operationId": "ListStores", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListStoresResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "continuation_token", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "name", + "description": "The name parameter instructs the API to only include results that match that name.Multiple results may be returned. Only exact matches will be returned; substring matches and regexes will not be evaluated", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Stores" + ] + }, + "post": { + "summary": "Create a store", + "description": "Create a unique OpenFGA store which will be used to store authorization models and relationship tuples.", + "operationId": "CreateStore", + "responses": { + "201": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateStoreResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateStoreRequest" + } + } + }, + "required": true + }, + "tags": [ + "Stores" + ] + } + }, + "/stores/{store_id}": { + "get": { + "summary": "Get a store", + "description": "Returns an OpenFGA store by its identifier", + "operationId": "GetStore", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetStoreResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Stores" + ] + }, + "delete": { + "summary": "Delete a store", + "description": "Delete an OpenFGA store. This does not delete the data associated with the store, like tuples or authorization models.", + "operationId": "DeleteStore", + "responses": { + "204": { + "description": "A successful response." + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Stores" + ] + } + }, + "/stores/{store_id}/access/v1/evaluation": { + "post": { + "summary": "[Experimental] Evaluate whether a subject can perform an action on a resource", + "description": "[Experimental] The Evaluation API determines whether a subject is authorized to perform an action on a resource. This endpoint implements the AuthZEN Access Evaluation API specification.\n\n## Request Structure\nThe request requires three components:\n- **subject**: The entity requesting access (e.g., a user or service)\n- **action**: The operation being performed (maps to a relation in the authorization model)\n- **resource**: The object being accessed\n\nEach component has a `type` and `id` field, and may include optional `properties` for ABAC (Attribute-Based Access Control) conditions.\n\n## Response\nThe response contains a `decision` field (boolean) indicating whether access is permitted, and an optional `context` object with additional information such as the evaluation ID or error details.\n\n## ABAC Support\nProperties on subject, action, and resource are automatically merged into the evaluation context with prefixes:\n- Subject properties: `subject_`\n- Resource properties: `resource_`\n- Action properties: `action_`\n\nThese merged properties can be used in conditions defined in your authorization model.\n\n## Examples\n### Basic authorization check\nCheck if user Anne can read a document:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"}\n}\n```\nResponse when authorized:\n```json\n{\n \"decision\": true\n}\n```\n### Using properties for ABAC\nCheck access with subject and resource attributes:\n```json\n{\n \"subject\": {\n \"type\": \"user\",\n \"id\": \"anne\",\n \"properties\": {\"department\": \"engineering\", \"clearance_level\": 3}\n },\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\n \"type\": \"document\",\n \"id\": \"secret-project\",\n \"properties\": {\"classification\": \"confidential\", \"required_clearance\": 2}\n }\n}\n```\n### Using request context\nProvide additional context for time-based or environmental conditions:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"action\": {\"name\": \"can_access\"},\n \"resource\": {\"type\": \"system\", \"id\": \"production\"},\n \"context\": {\n \"current_time\": \"2024-01-15T14:30:00Z\",\n \"ip_address\": \"192.168.1.100\",\n \"is_vpn_connected\": true\n }\n}\n```\n### Specifying authorization model\nPin the evaluation to a specific authorization model version using the `Openfga-Authorization-Model-Id` header:\n```\nPOST /stores/{store_id}/access/v1/evaluation\nOpenfga-Authorization-Model-Id: 01G50QVV17PECNVAHX1GG4Y5NC\n\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_write\"},\n \"resource\": {\"type\": \"document\", \"id\": \"budget-2024\"}\n}\n```\n", + "operationId": "Evaluation", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationBody" + } + } + }, + "required": true + }, + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/access/v1/evaluations": { + "post": { + "summary": "[Experimental] Check whether one or more users are authorized to access resources", + "description": "[Experimental] The Evaluations API allows batch authorization checks in a single request. It supports request-level defaults for subject, action, resource, and context that can be overridden per evaluation item.\n\n## Evaluation Semantics\nThe `options.evaluations_semantic` field controls how evaluations are processed:\n- `execute_all` (default): Execute all evaluations and return all results\n- `deny_on_first_deny`: Stop processing on first deny decision\n- `permit_on_first_permit`: Stop processing on first permit decision\n\nWhen using `deny_on_first_deny` or `permit_on_first_permit`, the response may include fewer items than the request because processing short-circuits when the condition is met.\n\n## Authorization Model Selection\nTo pin evaluations to a specific authorization model version, send the `Openfga-Authorization-Model-Id` header. If the header is not provided, the latest model is used.\n\n## Examples\n### Basic batch evaluation\nCheck if a user can perform multiple actions on a document:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"evaluations\": [\n {\"action\": {\"name\": \"can_read\"}},\n {\"action\": {\"name\": \"can_write\"}},\n {\"action\": {\"name\": \"can_delete\"}}\n ]\n}\n```\n### Using evaluation semantics\nStop on first permitted action (useful for finding any valid permission):\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"evaluations\": [\n {\"action\": {\"name\": \"can_read\"}},\n {\"action\": {\"name\": \"can_write\"}}\n ],\n \"options\": {\n \"evaluations_semantic\": \"permit_on_first_permit\"\n }\n}\n```\n### Overriding defaults per evaluation\nCheck permissions across multiple resources:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"evaluations\": [\n {\"resource\": {\"type\": \"document\", \"id\": \"doc1\"}},\n {\"resource\": {\"type\": \"document\", \"id\": \"doc2\"}},\n {\"resource\": {\"type\": \"folder\", \"id\": \"folder1\"}}\n ]\n}\n```\n", + "operationId": "Evaluations", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationsResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationsBody" + } + } + }, + "required": true + }, + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/access/v1/search/action": { + "post": { + "summary": "[Experimental] Search for actions a subject can perform on a resource", + "description": "[Experimental] The ActionSearch API returns all actions (relations) that a subject can perform on a specific resource. This is useful for answering questions like \"What can Anne do with this document?\" or building dynamic UIs that show only the actions a user is permitted to perform.\n\n## Examples\n### Find all actions a user can perform on a document\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"name\": \"can_read\"},\n {\"name\": \"can_write\"},\n {\"name\": \"can_share\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Search with ABAC context for time-based permissions\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"resource\": {\"type\": \"report\", \"id\": \"quarterly-financials\"},\n \"context\": {\n \"current_time\": \"2024-01-15T14:30:00Z\",\n \"user_department\": \"finance\"\n }\n}\n```\n### Paginated action search\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"admin\"},\n \"resource\": {\"type\": \"system\", \"id\": \"production\"},\n \"page\": {\"limit\": 50}\n}\n```\n", + "operationId": "ActionSearch", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActionSearchResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActionSearchBody" + } + } + }, + "required": true + }, + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/access/v1/search/resource": { + "post": { + "summary": "[Experimental] Search for resources a subject has access to", + "description": "[Experimental] The ResourceSearch API returns all resources of a given type that a subject has a specific action (relation) on. This is useful for answering questions like \"What documents can Anne read?\" or \"What folders can Bob administer?\"\n\nThe resource type filter is required. Results support pagination for large result sets.\n\n## Examples\n### Find all documents a user can read\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"type\": \"document\", \"id\": \"roadmap\"},\n {\"type\": \"document\", \"id\": \"budget-2024\"},\n {\"type\": \"document\", \"id\": \"team-roster\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Find folders a user can administer with pagination\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"action\": {\"name\": \"can_admin\"},\n \"resource\": {\"type\": \"folder\"},\n \"page\": {\"limit\": 25}\n}\n```\n### Search with ABAC context\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\"},\n \"context\": {\n \"current_time\": \"2024-01-15T10:00:00Z\",\n \"ip_address\": \"192.168.1.100\"\n }\n}\n```\n", + "operationId": "ResourceSearch", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResourceSearchResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResourceSearchBody" + } + } + }, + "required": true + }, + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/access/v1/search/subject": { + "post": { + "summary": "[Experimental] Search for subjects with access to a resource", + "description": "[Experimental] The SubjectSearch API returns all subjects that have a specific action (relation) on a given resource. This is useful for answering questions like \"Who can read this document?\" or \"Who can administer this folder?\"\n\nResults can be filtered by subject type and support pagination for large result sets.\n\n## Examples\n### Find all users who can read a document\n```json\n{\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"action\": {\"name\": \"can_read\"},\n \"subject\": {\"type\": \"user\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"type\": \"user\", \"id\": \"anne\"},\n {\"type\": \"user\", \"id\": \"bob\"},\n {\"type\": \"user\", \"id\": \"charlie\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Paginated search with limit\n```json\n{\n \"resource\": {\"type\": \"folder\", \"id\": \"engineering\"},\n \"action\": {\"name\": \"can_view\"},\n \"subject\": {\"type\": \"user\"},\n \"page\": {\"limit\": 10}\n}\n```\n### Continue from previous page\n```json\n{\n \"resource\": {\"type\": \"folder\", \"id\": \"engineering\"},\n \"action\": {\"name\": \"can_view\"},\n \"subject\": {\"type\": \"user\"},\n \"page\": {\"token\": \"eyJsYXN0X2lkIjoiMTAwIn0=\", \"limit\": 10}\n}\n```\n", + "operationId": "SubjectSearch", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSearchResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSearchBody" + } + } + }, + "required": true + }, + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/assertions/{authorization_model_id}": { + "get": { + "summary": "Read assertions for an authorization model ID", + "description": "The ReadAssertions API will return, for a given authorization model id, all the assertions stored for it. ", + "operationId": "ReadAssertions", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAssertionsResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "authorization_model_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Assertions" + ] + }, + "put": { + "summary": "Upsert assertions for an authorization model ID", + "description": "The WriteAssertions API will upsert new assertions for an authorization model id, or overwrite the existing ones. An assertion is an object that contains a tuple key, the expectation of whether a call to the Check API of that tuple key will return true or false, and optionally a list of contextual tuples.", + "operationId": "WriteAssertions", + "responses": { + "204": { + "description": "A successful response." + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "authorization_model_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAssertionsBody" + } + } + }, + "required": true + }, + "tags": [ + "Assertions" + ] + } + }, + "/stores/{store_id}/authorization-models": { + "get": { + "summary": "Return all the authorization models for a particular store", + "description": "The ReadAuthorizationModels API will return all the authorization models for a certain store.\nOpenFGA's response will contain an array of all authorization models, sorted in descending order of creation.\n\n## Example\nAssume that a store's authorization model has been configured twice. To get all the authorization models that have been created in this store, call GET authorization-models. The API will return a response that looks like:\n```json\n{\n \"authorization_models\": [\n {\n \"id\": \"01G50QVV17PECNVAHX1GG4Y5NC\",\n \"type_definitions\": [...]\n },\n {\n \"id\": \"01G4ZW8F4A07AKQ8RHSVG9RW04\",\n \"type_definitions\": [...]\n },\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nIf there are no more authorization models available, the `continuation_token` field will be empty\n```json\n{\n \"authorization_models\": [\n {\n \"id\": \"01G50QVV17PECNVAHX1GG4Y5NC\",\n \"type_definitions\": [...]\n },\n {\n \"id\": \"01G4ZW8F4A07AKQ8RHSVG9RW04\",\n \"type_definitions\": [...]\n },\n ],\n \"continuation_token\": \"\"\n}\n```\n", + "operationId": "ReadAuthorizationModels", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAuthorizationModelsResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "continuation_token", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Authorization Models" + ] + }, + "post": { + "summary": "Create a new authorization model", + "description": "The WriteAuthorizationModel API will add a new authorization model to a store.\nEach item in the `type_definitions` array is a type definition as specified in the field `type_definition`.\nThe response will return the authorization model's ID in the `id` field.\n\n## Example\nTo add an authorization model with `user` and `document` type definitions, call POST authorization-models API with the body: \n```json\n{\n \"type_definitions\":[\n {\n \"type\":\"user\"\n },\n {\n \"type\":\"document\",\n \"relations\":{\n \"reader\":{\n \"union\":{\n \"child\":[\n {\n \"this\":{}\n },\n {\n \"computedUserset\":{\n \"object\":\"\",\n \"relation\":\"writer\"\n }\n }\n ]\n }\n },\n \"writer\":{\n \"this\":{}\n }\n }\n }\n ]\n}\n```\nOpenFGA's response will include the version id for this authorization model, which will look like \n```\n{\"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"}\n```\n", + "operationId": "WriteAuthorizationModel", + "responses": { + "201": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAuthorizationModelResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAuthorizationModelBody" + } + } + }, + "required": true + }, + "tags": [ + "Authorization Models" + ] + } + }, + "/stores/{store_id}/authorization-models/{id}": { + "get": { + "summary": "Return a particular version of an authorization model", + "description": "The ReadAuthorizationModel API returns an authorization model by its identifier.\nThe response will return the authorization model for the particular version.\n\n## Example\nTo retrieve the authorization model with ID `01G5JAVJ41T49E9TT3SKVS7X1J` for the store, call the GET authorization-models by ID API with `01G5JAVJ41T49E9TT3SKVS7X1J` as the `id` path parameter. The API will return:\n```json\n{\n \"authorization_model\":{\n \"id\":\"01G5JAVJ41T49E9TT3SKVS7X1J\",\n \"type_definitions\":[\n {\n \"type\":\"user\"\n },\n {\n \"type\":\"document\",\n \"relations\":{\n \"reader\":{\n \"union\":{\n \"child\":[\n {\n \"this\":{}\n },\n {\n \"computedUserset\":{\n \"object\":\"\",\n \"relation\":\"writer\"\n }\n }\n ]\n }\n },\n \"writer\":{\n \"this\":{}\n }\n }\n }\n ]\n }\n}\n```\nIn the above example, there are 2 types (`user` and `document`). The `document` type has 2 relations (`writer` and `reader`).", + "operationId": "ReadAuthorizationModel", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAuthorizationModelResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "tags": [ + "Authorization Models" + ] + } + }, + "/stores/{store_id}/batch-check": { + "post": { + "summary": "Send a list of `check` operations in a single request", + "description": "The `BatchCheck` API functions nearly identically to `Check`, but instead of checking a single user-object relationship BatchCheck accepts a list of relationships to check and returns a map containing `BatchCheckItem` response for each check it received.\n\nAn associated `correlation_id` is required for each check in the batch. This ID is used to correlate a check to the appropriate response. It is a string consisting of only alphanumeric characters or hyphens with a maximum length of 36 characters. This `correlation_id` is used to map the result of each check to the item which was checked, so it must be unique for each item in the batch. We recommend using a UUID or ULID as the `correlation_id`, but you can use whatever unique identifier you need as long as it matches this regex pattern: `^[\\w\\d-]{1,36}$`\n\nNOTE: The maximum number of checks that can be passed in the `BatchCheck` API is configurable via the [OPENFGA_MAX_CHECKS_PER_BATCH_CHECK](https://openfga.dev/docs/getting-started/setup-openfga/configuration#OPENFGA_MAX_CHECKS_PER_BATCH_CHECK) environment variable. If `BatchCheck` is called using the SDK, the SDK can split the batch check requests for you.\n\nFor more details on how `Check` functions, see the docs for `/check`.\n\n### Examples\n#### A BatchCheckRequest\n```json\n{\n \"checks\": [\n {\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n \"relation\": \"reader\",\n \"user\": \"user:anne\",\n },\n \"contextual_tuples\": {...}\n \"context\": {}\n \"correlation_id\": \"01JA8PM3QM7VBPGB8KMPK8SBD5\"\n },\n {\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n \"relation\": \"reader\",\n \"user\": \"user:bob\",\n },\n \"contextual_tuples\": {...}\n \"context\": {}\n \"correlation_id\": \"01JA8PMM6A90NV5ET0F28CYSZQ\"\n }\n ]\n}\n```\n\nBelow is a possible response to the above request. Note that the result map's keys are the `correlation_id` values from the checked items in the request:\n```json\n{\n \"result\": {\n \"01JA8PMM6A90NV5ET0F28CYSZQ\": {\n \"allowed\": false, \n \"error\": {\"message\": \"\"} \n },\n \"01JA8PM3QM7VBPGB8KMPK8SBD5\": {\n \"allowed\": true, \n \"error\": {\"message\": \"\"} \n }\n}\n```\n", + "operationId": "BatchCheck", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchCheckResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchCheckBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Queries" + ] + } + }, + "/stores/{store_id}/changes": { + "get": { + "summary": "Return a list of all the tuple changes", + "description": "The ReadChanges API will return a paginated list of tuple changes (additions and deletions) that occurred in a given store, sorted by ascending time. The response will include a continuation token that is used to get the next set of changes. If there are no changes after the provided continuation token, the same token will be returned in order for it to be used when new changes are recorded. If the store never had any tuples added or removed, this token will be empty.\nYou can use the `type` parameter to only get the list of tuple changes that affect objects of that type.\nWhen reading a write tuple change, if it was conditioned, the condition will be returned.\nWhen reading a delete tuple change, the condition will NOT be returned regardless of whether it was originally conditioned or not.\n", + "operationId": "ReadChanges", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadChangesResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "type", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "page_size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "format": "int32" + } + }, + { + "name": "continuation_token", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "start_time", + "description": "Start date and time of changes to read.\nFormat: ISO 8601 timestamp (e.g., 2022-01-01T00:00:00Z)\nIf a continuation_token is provided along side start_time, the continuation_token will take precedence over start_time.", + "in": "query", + "required": false, + "schema": { + "type": "string", + "format": "date-time" + } + } + ], + "tags": [ + "Relationship Tuples" + ] + } + }, + "/stores/{store_id}/check": { + "post": { + "summary": "Check whether a user is authorized to access an object", + "description": "The Check API returns whether a given user has a relationship with a given object in a given store.\nThe `user` field of the request can be a specific target, such as `user:anne`, or a userset (set of users) such as `group:marketing#member` or a type-bound public access `user:*`.\nTo arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nA `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`.\nYou may also provide an `authorization_model_id` in the body. This will be used to assert that the input `tuple_key` is valid for the model specified. If not specified, the assertion will be made against the latest authorization model ID. It is strongly recommended to specify authorization model id for better performance.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nBy default, the Check API caches results for a short time to optimize performance. You may specify a value of `HIGHER_CONSISTENCY` for the optional `consistency` parameter in the body to inform the server that higher conisistency is preferred at the expense of increased latency. Consideration should be given to the increased latency if requesting higher consistency.\nThe response will return whether the relationship exists in the field `allowed`.\n\nSome exceptions apply, but in general, if a Check API responds with `{allowed: true}`, then you can expect the equivalent ListObjects query to return the object, and viceversa. \nFor example, if `Check(user:anne, reader, document:2021-budget)` responds with `{allowed: true}`, then `ListObjects(user:anne, reader, document)` may include `document:2021-budget` in the response.\n## Examples\n### Querying with contextual tuples\nIn order to check if user `user:anne` of type `user` has a `reader` relationship with object `document:2021-budget` given the following contextual tuple\n```json\n{\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"time_slot:office_hours\"\n}\n```\nthe Check API can be used with the following request body:\n```json\n{\n \"tuple_key\": {\n \"user\": \"user:anne\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"time_slot:office_hours\"\n }\n ]\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\n### Querying usersets\nSome Checks will always return `true`, even without any tuples. For example, for the following authorization model\n```python\nmodel\n schema 1.1\ntype user\ntype document\n relations\n define reader: [user]\n```\nthe following query\n```json\n{\n \"tuple_key\": {\n \"user\": \"document:2021-budget#reader\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n }\n}\n```\nwill always return `{ \"allowed\": true }`. This is because usersets are self-defining: the userset `document:2021-budget#reader` will always have the `reader` relation with `document:2021-budget`.\n### Querying usersets with difference in the model\nA Check for a userset can yield results that must be treated carefully if the model involves difference. For example, for the following authorization model\n```python\nmodel\n schema 1.1\ntype user\ntype group\n relations\n define member: [user]\ntype document\n relations\n define blocked: [user]\n define reader: [group#member] but not blocked\n```\nthe following query\n```json\n{\n \"tuple_key\": {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"group:finance\"\n },\n {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n {\n \"user\": \"user:anne\",\n \"relation\": \"blocked\",\n \"object\": \"document:2021-budget\"\n }\n ]\n },\n}\n```\nwill return `{ \"allowed\": true }`, even though a specific user of the userset `group:finance#member` does not have the `reader` relationship with the given object.\n### Requesting higher consistency\nBy default, the Check API caches results for a short time to optimize performance. You may request higher consistency to inform the server that higher consistency should be preferred at the expense of increased latency. Care should be taken when requesting higher consistency due to the increased latency.\n```json\n{\n \"tuple_key\": {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"consistency\": \"HIGHER_CONSISTENCY\"\n}\n```\n", + "operationId": "Check", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Queries" + ] + } + }, + "/stores/{store_id}/expand": { + "post": { + "summary": "Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship", + "description": "The Expand API will return all users and usersets that have certain relationship with an object in a certain store.\nThis is different from the `/stores/{store_id}/read` API in that both users and computed usersets are returned.\nBody parameters `tuple_key.object` and `tuple_key.relation` are all required.\nA `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`.\nThe response will return a tree whose leaves are the specific users and usersets. Union, intersection and difference operator are located in the intermediate nodes.\n\n## Example\nTo expand all users that have the `reader` relationship with object `document:2021-budget`, use the Expand API with the following request body\n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\",\n \"relation\": \"reader\"\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\nOpenFGA's response will be a userset tree of the users and usersets that have read access to the document.\n```json\n{\n \"tree\":{\n \"root\":{\n \"type\":\"document:2021-budget#reader\",\n \"union\":{\n \"nodes\":[\n {\n \"type\":\"document:2021-budget#reader\",\n \"leaf\":{\n \"users\":{\n \"users\":[\n \"user:bob\"\n ]\n }\n }\n },\n {\n \"type\":\"document:2021-budget#reader\",\n \"leaf\":{\n \"computed\":{\n \"userset\":\"document:2021-budget#writer\"\n }\n }\n }\n ]\n }\n }\n }\n}\n```\nThe caller can then call expand API for the `writer` relationship for the `document:2021-budget`.\n### Expand Request with Contextual Tuples\n\nGiven the model\n```python\nmodel\n schema 1.1\n\ntype user\n\ntype folder\n relations\n define owner: [user]\n\ntype document\n relations\n define parent: [folder]\n define viewer: [user] or writer\n define writer: [user] or owner from parent\n```\nand the initial tuples\n```json\n[{\n \"user\": \"user:bob\",\n \"relation\": \"owner\",\n \"object\": \"folder:1\"\n}]\n```\n\nTo expand all `writers` of `document:1` when `document:1` is put in `folder:1`, the first call could be\n\n```json\n{\n \"tuple_key\": {\n \"object\": \"document:1\",\n \"relation\": \"writer\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"folder:1\",\n \"relation\": \"parent\",\n \"object\": \"document:1\"\n }\n ]\n }\n}\n```\nthis returns:\n```json\n{\n \"tree\": {\n \"root\": {\n \"name\": \"document:1#writer\",\n \"union\": {\n \"nodes\": [\n {\n \"name\": \"document:1#writer\",\n \"leaf\": {\n \"users\": {\n \"users\": []\n }\n }\n },\n {\n \"name\": \"document:1#writer\",\n \"leaf\": {\n \"tupleToUserset\": {\n \"tupleset\": \"document:1#parent\",\n \"computed\": [\n {\n \"userset\": \"folder:1#owner\"\n }\n ]\n }\n }\n }\n ]\n }\n }\n }\n}\n```\nThis tells us that the `owner` of `folder:1` may also be a writer. So our next call could be to find the `owners` of `folder:1`\n```json\n{\n \"tuple_key\": {\n \"object\": \"folder:1\",\n \"relation\": \"owner\"\n }\n}\n```\nwhich gives\n```json\n{\n \"tree\": {\n \"root\": {\n \"name\": \"folder:1#owner\",\n \"leaf\": {\n \"users\": {\n \"users\": [\n \"user:bob\"\n ]\n }\n }\n }\n }\n}\n```\n", + "operationId": "Expand", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExpandResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExpandBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Queries" + ] + } + }, + "/stores/{store_id}/list-objects": { + "post": { + "summary": "List all objects of the given type that the user has a relation with", + "description": "The ListObjects API returns a list of all the objects of the given type that the user has a relation with.\n To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nAn `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance.\nYou may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nBy default, the Check API caches results for a short time to optimize performance. You may specify a value of `HIGHER_CONSISTENCY` for the optional `consistency` parameter in the body to inform the server that higher conisistency is preferred at the expense of increased latency. Consideration should be given to the increased latency if requesting higher consistency.\nThe response will contain the related objects in an array in the \"objects\" field of the response and they will be strings in the object format `:` (e.g. \"document:roadmap\").\nThe number of objects in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first.\nThe objects given will not be sorted, and therefore two identical calls can give a given different set of objects.", + "operationId": "ListObjects", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListObjectsResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListObjectsBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Queries" + ] + } + }, + "/stores/{store_id}/list-users": { + "post": { + "summary": "List the users matching the provided filter who have a certain relation to a particular type.", + "description": "The ListUsers API returns a list of all the users of a specific type that have a relation to a given object.\n To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nAn `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance.\nYou may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nThe response will contain the related users in an array in the \"users\" field of the response. These results may include specific objects, usersets \nor type-bound public access. Each of these types of results is encoded in its own type and not represented as a string.In cases where a type-bound public access result is returned (e.g. `user:*`), it cannot be inferred that all subjects\nof that type have a relation to the object; it is possible that negations exist and checks should still be queried\non individual subjects to ensure access to that document.The number of users in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_USERS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_USERS_MAX_RESULTS, whichever is hit first.\nThe returned users will not be sorted, and therefore two identical calls may yield different sets of users.", + "operationId": "ListUsers", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListUsersResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListUsersBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Queries" + ] + } + }, + "/stores/{store_id}/read": { + "post": { + "summary": "Get tuples from the store that matches a query, without following userset rewrite rules", + "description": "The Read API will return the tuples for a certain store that match a query filter specified in the body of the request. \nThe API doesn't guarantee order by any field. \nIt is different from the `/stores/{store_id}/expand` API in that it only returns relationship tuples that are stored in the system and satisfy the query. \nIn the body:\n1. `tuple_key` is optional. If not specified, it will return all tuples in the store.\n2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can be a full object (e.g., `type:object_id`) or type only (e.g., `type:`).\n3. `tuple_key.user` is mandatory if tuple_key is specified in the case the `tuple_key.object` is a type only. If tuple_key.user is specified, it needs to be a full object (e.g., `type:user_id`).\n## Examples\n### Query for all objects in a type definition\nTo query for all objects that `user:bob` has `reader` relationship in the `document` type definition, call read API with body of\n```json\n{\n \"tuple_key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:\"\n }\n}\n```\nThe API will return tuples and a continuation token, something like\n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `user:bob` has a `reader` relationship with 1 document `document:2021-budget`. Note that this API, unlike the List Objects API, does not evaluate the tuples in the store.\nThe continuation token will be empty if there are no more tuples to query.\n### Query for all stored relationship tuples that have a particular relation and object\nTo query for all users that have `reader` relationship with `document:2021-budget`, call read API with body of \n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\",\n \"relation\": \"reader\"\n }\n}\n```\nThe API will return something like \n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `document:2021-budget` has 1 `reader` (`user:bob`). Note that, even if the model said that all `writers` are also `readers`, the API will not return writers such as `user:anne` because it only returns tuples and does not evaluate them.\n### Query for all users with all relationships for a particular document\nTo query for all users that have any relationship with `document:2021-budget`, call read API with body of \n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n }\n}\n```\nThe API will return something like \n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:anne\",\n \"relation\": \"writer\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-05T13:42:12.356Z\"\n },\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1 `writer` (`user:anne`).\n", + "operationId": "Read", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Tuples" + ] + } + }, + "/stores/{store_id}/streamed-list-objects": { + "post": { + "summary": "Stream all objects of the given type that the user has a relation with", + "description": "The Streamed ListObjects API is very similar to the the ListObjects API, with two differences: \n1. Instead of collecting all objects before returning a response, it streams them to the client as they are collected. \n2. The number of results returned is only limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE. \n", + "operationId": "StreamedListObjects", + "responses": { + "200": { + "description": "A successful response.(streaming responses)", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/components/schemas/StreamedListObjectsResponse" + }, + "error": { + "$ref": "#/components/schemas/Status" + } + }, + "title": "Stream result of StreamedListObjectsResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StreamedListObjectsBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Queries" + ] + } + }, + "/stores/{store_id}/write": { + "post": { + "summary": "Add or delete tuples from the store", + "description": "The Write API will transactionally update the tuples for a certain store. Tuples and type definitions allow OpenFGA to determine whether a relationship exists between an object and an user.\nIn the body, `writes` adds new tuples and `deletes` removes existing tuples. When deleting a tuple, any `condition` specified with it is ignored.\nThe API is not idempotent by default: if, later on, you try to add the same tuple key (even if the `condition` is different), or if you try to delete a non-existing tuple, it will throw an error.\nTo allow writes when an identical tuple already exists in the database, set `\"on_duplicate\": \"ignore\"` on the `writes` object.\nTo allow deletes when a tuple was already removed from the database, set `\"on_missing\": \"ignore\"` on the `deletes` object.\nIf a Write request contains both idempotent (ignore) and non-idempotent (error) operations, the most restrictive action (error) will take precedence. If a condition fails for a sub-request with an error flag, the entire transaction will be rolled back. This gives developers explicit control over the atomicity of the requests.\nThe API will not allow you to write tuples such as `document:2021-budget#viewer@document:2021-budget#viewer`, because they are implicit.\nAn `authorization_model_id` may be specified in the body. If it is, it will be used to assert that each written tuple (not deleted) is valid for the model specified. If it is not specified, the latest authorization model ID will be used.\n## Example\n### Adding relationships\nTo add `user:anne` as a `writer` for `document:2021-budget`, call write API with the following \n```json\n{\n \"writes\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"writer\",\n \"object\": \"document:2021-budget\"\n }\n ],\n \"on_duplicate\": \"ignore\"\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\n### Removing relationships\nTo remove `user:bob` as a `reader` for `document:2021-budget`, call write API with the following \n```json\n{\n \"deletes\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n }\n ],\n \"on_missing\": \"ignore\"\n }\n}\n```\n", + "operationId": "Write", + "responses": { + "200": { + "description": "A successful response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResponse" + } + } + } + }, + "400": { + "description": "Request failed due to invalid input.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + } + }, + "401": { + "description": "Not authenticated.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + } + }, + "403": { + "description": "Forbidden.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + } + }, + "404": { + "description": "Request failed due to incorrect path.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + } + }, + "409": { + "description": "Request was aborted due a transaction conflict.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + } + }, + "422": { + "description": "Request timed out due to excessive request throttling.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + } + }, + "500": { + "description": "Request failed due to internal server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + } + } + }, + "parameters": [ + { + "name": "store_id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteBody" + } + } + }, + "required": true + }, + "tags": [ + "Relationship Tuples" + ] + } + } + }, + "components": { + "schemas": { + "AbortedMessageResponse": { + "type": "object", + "example": { + "code": "10", + "message": "transaction conflict" + }, + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + } + } + }, + "Action": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "can_read" + }, + "properties": { + "type": "object" + } + }, + "required": [ + "name" + ] + }, + "ActionSearchBody": { + "type": "object", + "properties": { + "subject": { + "$ref": "#/components/schemas/Subject" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "context": { + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageRequest" + } + }, + "title": "ActionSearch request", + "required": [ + "subject", + "resource" + ] + }, + "ActionSearchResponse": { + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Action" + }, + { + "type": "object" + } + ] + } + }, + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" + } + ] + } + } + }, + "Any": { + "type": "object", + "properties": { + "@type": { + "type": "string" + } + }, + "additionalProperties": {} + }, + "Assertion": { + "type": "object", + "properties": { + "tuple_key": { + "$ref": "#/components/schemas/AssertionTupleKey" + }, + "expectation": { + "type": "boolean" + }, + "contextual_tuples": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "maxItems": 20 + }, + "context": { + "type": "object", + "example": { + "view_count": 100 + }, + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + } + }, + "required": [ + "tuple_key", + "expectation" + ] + }, + "AssertionTupleKey": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "document:2021-budget", + "maxLength": 256 + }, + "relation": { + "type": "string", + "example": "reader", + "maxLength": 50 + }, + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512 + } + }, + "required": [ + "object", + "relation", + "user" + ] + }, + "AuthErrorCode": { + "type": "string", + "enum": [ + "no_auth_error", + "auth_failed_invalid_subject", + "auth_failed_invalid_audience", + "auth_failed_invalid_issuer", + "invalid_claims", + "auth_failed_invalid_bearer_token", + "bearer_token_missing", + "unauthenticated", + "forbidden" + ], + "default": "no_auth_error" + }, + "AuthorizationModel": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "schema_version": { + "type": "string" + }, + "type_definitions": { + "type": "array", + "example": [ + { + "type": "user" + }, + { + "type": "document", + "relations": { + "reader": { + "union": { + "child": [ + { + "this": {} + }, + { + "computedUserset": { + "object": "", + "relation": "writer" + } + } + ] + } + }, + "writer": { + "this": {} + } + }, + "metadata": { + "relations": { + "reader": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "writer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + } + } + ], + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TypeDefinition" + }, + { + "type": "object" + } + ] + } + }, + "conditions": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Condition" + } + } + }, + "required": [ + "id", + "schema_version", + "type_definitions" + ] + }, + "BatchCheckBody": { + "type": "object", + "properties": { + "checks": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/BatchCheckItem" + }, + { + "type": "object" + } + ] + }, + "minItems": 1 + }, + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "consistency": { + "$ref": "#/components/schemas/ConsistencyPreference" + } + }, + "required": [ + "checks" + ] + }, + "BatchCheckItem": { + "type": "object", + "properties": { + "tuple_key": { + "$ref": "#/components/schemas/CheckRequestTupleKey" + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + }, + "context": { + "type": "object" + }, + "correlation_id": { + "type": "string", + "example": "1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc", + "description": "correlation_id must be a string containing only letters, numbers, or hyphens, with length ≤ 36 characters." + } + }, + "required": [ + "tuple_key", + "correlation_id" + ] + }, + "BatchCheckResponse": { + "type": "object", + "properties": { + "result": { + "type": "object", + "example": { + "1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc": { + "allowed": true, + "error": { + "message": "" + } + } + }, + "additionalProperties": { + "$ref": "#/components/schemas/BatchCheckSingleResult" + }, + "description": "map keys are the correlation_id values from the BatchCheckItems in the request" + } + } + }, + "BatchCheckSingleResult": { + "type": "object", + "properties": { + "allowed": { + "type": "boolean" + }, + "error": { + "$ref": "#/components/schemas/CheckError" + } + } + }, + "CheckBody": { + "type": "object", + "properties": { + "tuple_key": { + "$ref": "#/components/schemas/CheckRequestTupleKey" + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + }, + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "trace": { + "type": "boolean", + "example": false, + "description": "Defaults to false. Making it true has performance implications.", + "readOnly": true + }, + "context": { + "type": "object", + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + }, + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + } + ] + } + }, + "required": [ + "tuple_key" + ] + }, + "CheckError": { + "type": "object", + "properties": { + "input_error": { + "$ref": "#/components/schemas/ErrorCode" + }, + "internal_error": { + "$ref": "#/components/schemas/InternalErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "CheckRequestTupleKey": { + "type": "object", + "properties": { + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512 + }, + "relation": { + "type": "string", + "example": "reader", + "maxLength": 50 + }, + "object": { + "type": "string", + "example": "document:2021-budget", + "maxLength": 256 + } + }, + "required": [ + "user", + "relation", + "object" + ] + }, + "CheckResponse": { + "type": "object", + "properties": { + "allowed": { + "type": "boolean", + "example": true + }, + "resolution": { + "type": "string", + "description": "For internal use only." + } + } + }, + "Computed": { + "type": "object", + "properties": { + "userset": { + "type": "string" + } + }, + "required": [ + "userset" + ] + }, + "Condition": { + "type": "object", + "properties": { + "name": { + "type": "string", + "title": "A unique name for the condition" + }, + "expression": { + "type": "string", + "description": "A Google CEL expression, expressed as a string." + }, + "parameters": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ConditionParamTypeRef" + }, + "description": "A map of parameter names to the parameter's defined type reference." + }, + "metadata": { + "$ref": "#/components/schemas/ConditionMetadata" + } + }, + "required": [ + "name", + "expression" + ] + }, + "ConditionMetadata": { + "type": "object", + "properties": { + "module": { + "type": "string" + }, + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + } + }, + "ConditionParamTypeRef": { + "type": "object", + "properties": { + "type_name": { + "$ref": "#/components/schemas/TypeName" + }, + "generic_types": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/ConditionParamTypeRef" + }, + { + "type": "object" + } + ] + } + } + }, + "required": [ + "type_name" + ] + }, + "ConsistencyPreference": { + "type": "string", + "enum": [ + "UNSPECIFIED", + "MINIMIZE_LATENCY", + "HIGHER_CONSISTENCY" + ], + "default": "UNSPECIFIED", + "description": "Controls the consistency preferences when calling the query APIs.\n\n - UNSPECIFIED: Default if not set. Behavior will be the same as MINIMIZE_LATENCY.\n - MINIMIZE_LATENCY: Minimize latency at the potential expense of lower consistency.\n - HIGHER_CONSISTENCY: Prefer higher consistency, at the potential expense of increased latency.", + "example": "MINIMIZE_LATENCY" + }, + "ContextualTupleKeys": { + "type": "object", + "properties": { + "tuple_keys": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "maxItems": 100 + } + }, + "required": [ + "tuple_keys" + ] + }, + "CreateStoreRequest": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "my-store-name" + } + }, + "required": [ + "name" + ] + }, + "CreateStoreResponse": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "01YCP46JKYM8FJCQ37NMBYHE5X" + }, + "name": { + "type": "string" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "created_at", + "updated_at" + ] + }, + "DeleteStoreResponse": { + "type": "object" + }, + "DirectUserset": { + "type": "object", + "description": "A DirectUserset is a sentinel message for referencing\nthe direct members specified by an object/relation mapping." + }, + "ErrorCode": { + "type": "string", + "enum": [ + "no_error", + "validation_error", + "authorization_model_not_found", + "authorization_model_resolution_too_complex", + "invalid_write_input", + "cannot_allow_duplicate_tuples_in_one_request", + "cannot_allow_duplicate_types_in_one_request", + "cannot_allow_multiple_references_to_one_relation", + "invalid_continuation_token", + "invalid_tuple_set", + "invalid_check_input", + "invalid_expand_input", + "unsupported_user_set", + "invalid_object_format", + "write_failed_due_to_invalid_input", + "authorization_model_assertions_not_found", + "latest_authorization_model_not_found", + "type_not_found", + "relation_not_found", + "empty_relation_definition", + "invalid_user", + "invalid_tuple", + "unknown_relation", + "store_id_invalid_length", + "assertions_too_many_items", + "id_too_long", + "authorization_model_id_too_long", + "tuple_key_value_not_specified", + "tuple_keys_too_many_or_too_few_items", + "page_size_invalid", + "param_missing_value", + "difference_base_missing_value", + "subtract_base_missing_value", + "object_too_long", + "relation_too_long", + "type_definitions_too_few_items", + "type_invalid_length", + "type_invalid_pattern", + "relations_too_few_items", + "relations_too_long", + "relations_invalid_pattern", + "object_invalid_pattern", + "query_string_type_continuation_token_mismatch", + "exceeded_entity_limit", + "invalid_contextual_tuple", + "duplicate_contextual_tuple", + "invalid_authorization_model", + "unsupported_schema_version", + "cancelled", + "invalid_start_time" + ], + "default": "no_error" + }, + "EvaluationBody": { + "type": "object", + "properties": { + "subject": { + "$ref": "#/components/schemas/Subject" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "action": { + "$ref": "#/components/schemas/Action" + }, + "context": { + "type": "object" + } + }, + "required": [ + "subject", + "resource", + "action" + ] + }, + "EvaluationResponse": { + "type": "object", + "properties": { + "decision": { + "type": "boolean" + }, + "context": { + "type": "object" + } + } + }, + "EvaluationsBody": { + "type": "object", + "properties": { + "subject": { + "$ref": "#/components/schemas/Subject" + }, + "action": { + "$ref": "#/components/schemas/Action" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "context": { + "type": "object" + }, + "evaluations": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsItemRequest" + }, + { + "type": "object" + } + ] + }, + "description": "Optional. If omitted or empty, behaves like a single Access Evaluation request." + }, + "options": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsOptions" + }, + { + "title": "Options for batch evaluation semantics" + } + ] + } + } + }, + "EvaluationsItemRequest": { + "type": "object", + "properties": { + "subject": { + "$ref": "#/components/schemas/Subject" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "action": { + "$ref": "#/components/schemas/Action" + }, + "context": { + "type": "object" + } + } + }, + "EvaluationsOptions": { + "type": "object", + "properties": { + "evaluations_semantic": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsSemantic" + }, + { + "title": "Controls how batch evaluations are processed" + } + ] + } + }, + "title": "Options for batch evaluations" + }, + "EvaluationsResponse": { + "type": "object", + "properties": { + "evaluations": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationResponse" + }, + { + "type": "object" + } + ] + } + } + } + }, + "EvaluationsSemantic": { + "type": "string", + "enum": [ + "execute_all", + "deny_on_first_deny", + "permit_on_first_permit" + ], + "default": "execute_all", + "description": "- execute_all: Execute all evaluations (default behavior)\n - deny_on_first_deny: Stop on first deny decision\n - permit_on_first_permit: Stop on first permit decision", + "title": "Enum for evaluation semantics" + }, + "ExpandBody": { + "type": "object", + "properties": { + "tuple_key": { + "$ref": "#/components/schemas/ExpandRequestTupleKey" + }, + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + } + ] + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + } + }, + "required": [ + "tuple_key" + ] + }, + "ExpandRequestTupleKey": { + "type": "object", + "properties": { + "relation": { + "type": "string", + "example": "reader", + "maxLength": 50 + }, + "object": { + "type": "string", + "example": "document:2021-budget", + "maxLength": 256 + } + }, + "required": [ + "relation", + "object" + ] + }, + "ExpandResponse": { + "type": "object", + "properties": { + "tree": { + "$ref": "#/components/schemas/UsersetTree" + } + } + }, + "ForbiddenResponse": { + "type": "object", + "example": { + "code": "forbidden", + "message": "the principal is not authorized to perform the action" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/AuthErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "GetConfigurationResponse": { + "type": "object", + "properties": { + "policy_decision_point": { + "type": "string", + "description": "REQUIRED. The PDP identifier URL (HTTPS, no query or fragment)." + }, + "access_evaluation_endpoint": { + "type": "string", + "description": "REQUIRED. The access evaluation endpoint URL." + }, + "access_evaluations_endpoint": { + "type": "string", + "description": "OPTIONAL. The batch evaluations endpoint URL." + }, + "search_subject_endpoint": { + "type": "string", + "description": "OPTIONAL. The subject search endpoint URL." + }, + "search_resource_endpoint": { + "type": "string", + "description": "OPTIONAL. The resource search endpoint URL." + }, + "search_action_endpoint": { + "type": "string", + "description": "OPTIONAL. The action search endpoint URL." + }, + "capabilities": { + "type": "array", + "items": { + "type": "string" + }, + "description": "OPTIONAL. Supported capabilities as URN strings." + }, + "signed_metadata": { + "type": "string", + "description": "OPTIONAL. Signed metadata JWT per AuthZEN metadata specification." + } + }, + "title": "GetConfiguration response - PDP metadata per AuthZEN spec", + "required": [ + "policy_decision_point", + "access_evaluation_endpoint" + ] + }, + "GetStoreResponse": { + "type": "object", + "properties": { + "id": { + "type": "string", + "example": "01YCP46JKYM8FJCQ37NMBYHE5X" + }, + "name": { + "type": "string" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "deleted_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "created_at", + "updated_at" + ] + }, + "InternalErrorCode": { + "type": "string", + "enum": [ + "no_internal_error", + "internal_error", + "deadline_exceeded", + "already_exists", + "resource_exhausted", + "failed_precondition", + "aborted", + "out_of_range", + "unavailable", + "data_loss" + ], + "default": "no_internal_error" + }, + "InternalErrorMessageResponse": { + "type": "object", + "example": { + "code": "internal_error", + "message": "Internal Server Error" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/InternalErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "Leaf": { + "type": "object", + "properties": { + "users": { + "$ref": "#/components/schemas/Users" + }, + "computed": { + "$ref": "#/components/schemas/Computed" + }, + "tupleToUserset": { + "$ref": "#/components/schemas/UsersetTree.TupleToUserset" + } + }, + "description": "A leaf node contains either\n- a set of users (which may be individual users, or usersets\n referencing other relations)\n- a computed node, which is the result of a computed userset\n value in the authorization model\n- a tupleToUserset nodes, containing the result of expanding\n a tupleToUserset value in a authorization model." + }, + "ListObjectsBody": { + "type": "object", + "properties": { + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "type": { + "type": "string", + "example": "document" + }, + "relation": { + "type": "string", + "example": "reader" + }, + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512, + "minLength": 1 + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + }, + "context": { + "type": "object", + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + }, + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + } + ] + } + }, + "required": [ + "type", + "relation", + "user" + ] + }, + "ListObjectsResponse": { + "type": "object", + "properties": { + "objects": { + "type": "array", + "example": [ + "document:roadmap", + "document:planning" + ], + "items": { + "type": "string" + } + } + }, + "required": [ + "objects" + ] + }, + "ListStoresResponse": { + "type": "object", + "properties": { + "stores": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Store" + }, + { + "type": "object" + } + ] + } + }, + "continuation_token": { + "type": "string", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "description": "The continuation token will be empty if there are no more stores." + } + }, + "required": [ + "stores", + "continuation_token" + ] + }, + "ListUsersBody": { + "type": "object", + "properties": { + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "object": { + "allOf": [ + { + "$ref": "#/components/schemas/Object" + }, + { + "example": "document:example" + } + ] + }, + "relation": { + "type": "string", + "example": "reader" + }, + "user_filters": { + "type": "array", + "example": [ + { + "type": "user" + }, + { + "type": "group", + "relation": "member" + } + ], + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/UserTypeFilter" + }, + { + "type": "object" + } + ] + }, + "description": "The type of results returned. Only accepts exactly one value.", + "maxItems": 1, + "minItems": 1 + }, + "contextual_tuples": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "maxItems": 100 + }, + "context": { + "type": "object", + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + }, + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + } + ] + } + }, + "required": [ + "object", + "relation", + "user_filters" + ] + }, + "ListUsersResponse": { + "type": "object", + "properties": { + "users": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/User" + }, + { + "type": "object" + } + ] + } + } + }, + "required": [ + "users" + ] + }, + "Metadata": { + "type": "object", + "properties": { + "relations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/RelationMetadata" + } + }, + "module": { + "type": "string" + }, + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + } + }, + "Node": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "leaf": { + "$ref": "#/components/schemas/Leaf" + }, + "difference": { + "$ref": "#/components/schemas/UsersetTree.Difference" + }, + "union": { + "$ref": "#/components/schemas/Nodes" + }, + "intersection": { + "$ref": "#/components/schemas/Nodes" + } + }, + "required": [ + "name" + ] + }, + "Nodes": { + "type": "object", + "properties": { + "nodes": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Node" + }, + { + "type": "object" + } + ] + } + } + }, + "required": [ + "nodes" + ] + }, + "NotFoundErrorCode": { + "type": "string", + "enum": [ + "no_not_found_error", + "undefined_endpoint", + "store_id_not_found", + "unimplemented" + ], + "default": "no_not_found_error" + }, + "NullValue": { + "type": "string", + "enum": [ + "NULL_VALUE" + ], + "default": "NULL_VALUE", + "description": "`NullValue` is a singleton enumeration to represent the null value for the\n`Value` type union.\n\nThe JSON representation for `NullValue` is JSON `null`.\n\n - NULL_VALUE: Null value." + }, + "Object": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "document" + }, + "id": { + "type": "string", + "example": "0bcdf6fa-a6aa-4730-a8eb-9cf172ff16d9" + } + }, + "description": "Object represents an OpenFGA Object.\n\nAn Object is composed of a type and identifier (e.g. 'document:1')\n\nSee https://openfga.dev/docs/concepts#what-is-an-object", + "required": [ + "type", + "id" + ] + }, + "ObjectRelation": { + "type": "object", + "properties": { + "object": { + "type": "string" + }, + "relation": { + "type": "string" + } + } + }, + "PageRequest": { + "type": "object", + "properties": { + "token": { + "type": "string", + "title": "Continuation token from previous response" + }, + "limit": { + "type": "integer", + "format": "int64", + "title": "Maximum number of results to return (default: 50, max: 1000)" + } + }, + "title": "Pagination request parameters for search operations" + }, + "PageResponse": { + "type": "object", + "properties": { + "next_token": { + "type": "string", + "title": "Token to retrieve next page (empty if no more results)" + }, + "count": { + "type": "integer", + "format": "int64", + "title": "Number of results in this page" + }, + "total": { + "type": "integer", + "format": "int64", + "title": "Total number of results (if known, otherwise 0)" + } + }, + "title": "Pagination response parameters" + }, + "PathUnknownErrorMessageResponse": { + "type": "object", + "example": { + "code": "undefined_endpoint", + "message": "Endpoint not enabled" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/NotFoundErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "ReadAssertionsResponse": { + "type": "object", + "properties": { + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "assertions": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Assertion" + }, + { + "type": "object" + } + ] + } + } + }, + "required": [ + "authorization_model_id" + ] + }, + "ReadAuthorizationModelResponse": { + "type": "object", + "properties": { + "authorization_model": { + "$ref": "#/components/schemas/AuthorizationModel" + } + } + }, + "ReadAuthorizationModelsResponse": { + "type": "object", + "properties": { + "authorization_models": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/AuthorizationModel" + }, + { + "type": "object" + } + ] + } + }, + "continuation_token": { + "type": "string", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "description": "The continuation token will be empty if there are no more models." + } + }, + "required": [ + "authorization_models" + ] + }, + "ReadBody": { + "type": "object", + "properties": { + "tuple_key": { + "$ref": "#/components/schemas/ReadRequestTupleKey" + }, + "page_size": { + "type": "integer", + "format": "int32", + "example": 50, + "maximum": 100, + "minimum": 1 + }, + "continuation_token": { + "type": "string", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" + }, + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + } + ] + } + } + }, + "ReadChangesResponse": { + "type": "object", + "properties": { + "changes": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleChange" + }, + { + "type": "object" + } + ] + } + }, + "continuation_token": { + "type": "string", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "description": "The continuation token will be identical if there are no new changes." + } + }, + "required": [ + "changes" + ] + }, + "ReadRequestTupleKey": { + "type": "object", + "properties": { + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512 + }, + "relation": { + "type": "string", + "example": "reader", + "maxLength": 50 + }, + "object": { + "type": "string", + "example": "document:2021-budget", + "maxLength": 256 + } + } + }, + "ReadResponse": { + "type": "object", + "properties": { + "tuples": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Tuple" + }, + { + "type": "object" + } + ] + } + }, + "continuation_token": { + "type": "string", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "description": "The continuation token will be empty if there are no more tuples." + } + }, + "required": [ + "tuples", + "continuation_token" + ] + }, + "RelationMetadata": { + "type": "object", + "properties": { + "directly_related_user_types": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/RelationReference" + }, + { + "type": "object" + } + ] + } + }, + "module": { + "type": "string" + }, + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + } + }, + "RelationReference": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "group" + }, + "relation": { + "type": "string", + "example": "member" + }, + "wildcard": { + "$ref": "#/components/schemas/Wildcard" + }, + "condition": { + "type": "string", + "description": "The name of a condition that is enforced over the allowed relation." + } + }, + "description": "RelationReference represents a relation of a particular object type (e.g. 'document#viewer').", + "required": [ + "type" + ] + }, + "RelationshipCondition": { + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "condition1", + "description": "A reference (by name) of the relationship condition defined in the authorization model.", + "maxLength": 256 + }, + "context": { + "type": "object", + "description": "Additional context/data to persist along with the condition.\nThe keys must match the parameters defined by the condition, and the value types must\nmatch the parameter type definitions." + } + }, + "required": [ + "name" + ] + }, + "Resource": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "document" + }, + "id": { + "type": "string", + "example": "roadmap" + }, + "properties": { + "type": "object" + } + }, + "required": [ + "type", + "id" + ] + }, + "ResourceFilter": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "document" + }, + "id": { + "type": "string", + "description": "Optional resource id. If present in Resource Search, it is ignored per AuthZEN spec." + }, + "properties": { + "type": "object" + } + }, + "title": "ResourceFilter is used for search operations where only type is required", + "required": [ + "type" + ] + }, + "ResourceSearchBody": { + "type": "object", + "properties": { + "subject": { + "$ref": "#/components/schemas/Subject" + }, + "action": { + "$ref": "#/components/schemas/Action" + }, + "resource": { + "allOf": [ + { + "$ref": "#/components/schemas/ResourceFilter" + }, + { + "title": "Filter by resource type" + } + ] + }, + "context": { + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageRequest" + } + }, + "title": "ResourceSearch request", + "required": [ + "subject", + "action", + "resource" + ] + }, + "ResourceSearchResponse": { + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Resource" + }, + { + "type": "object" + } + ] + } + }, + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" + } + ] + } + } + }, + "SourceInfo": { + "type": "object", + "properties": { + "file": { + "type": "string" + } + } + }, + "Status": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + }, + "details": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Any" + }, + { + "type": "object" + } + ] + } + } + } + }, + "Store": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "deleted_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "created_at", + "updated_at" + ] + }, + "StreamedListObjectsBody": { + "type": "object", + "properties": { + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + }, + "type": { + "type": "string", + "example": "document" + }, + "relation": { + "type": "string", + "example": "reader" + }, + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512, + "minLength": 1 + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + }, + "context": { + "type": "object", + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + }, + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + } + ] + } + }, + "required": [ + "type", + "relation", + "user" + ] + }, + "StreamedListObjectsResponse": { + "type": "object", + "properties": { + "object": { + "type": "string", + "example": "document:roadmap" + } + }, + "description": "The response for a StreamedListObjects RPC.", + "required": [ + "object" + ] + }, + "Subject": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "user" + }, + "id": { + "type": "string", + "example": "anne" + }, + "properties": { + "type": "object" + } + }, + "required": [ + "type", + "id" + ] + }, + "SubjectFilter": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "user" + }, + "id": { + "type": "string", + "description": "Optional subject id. If present in Subject Search, it is ignored per AuthZEN spec." + }, + "properties": { + "type": "object" + } + }, + "title": "SubjectFilter is used for search operations where only type is required", + "required": [ + "type" + ] + }, + "SubjectSearchBody": { + "type": "object", + "properties": { + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "action": { + "$ref": "#/components/schemas/Action" + }, + "subject": { + "allOf": [ + { + "$ref": "#/components/schemas/SubjectFilter" + }, + { + "description": "REQUIRED by AuthZEN Subject Search. Subject `id` may be provided but is ignored." + } + ] + }, + "context": { + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageRequest" + } + }, + "title": "SubjectSearch request", + "required": [ + "resource", + "action", + "subject" + ] + }, + "SubjectSearchResponse": { + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Subject" + }, + { + "type": "object" + } + ] + } + }, + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" + } + ] + } + } + }, + "Tuple": { + "type": "object", + "properties": { + "key": { + "$ref": "#/components/schemas/TupleKey" + }, + "timestamp": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "key", + "timestamp" + ] + }, + "TupleChange": { + "type": "object", + "properties": { + "tuple_key": { + "$ref": "#/components/schemas/TupleKey" + }, + "operation": { + "$ref": "#/components/schemas/TupleOperation" + }, + "timestamp": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "tuple_key", + "operation", + "timestamp" + ] + }, + "TupleKey": { + "type": "object", + "properties": { + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512 + }, + "relation": { + "type": "string", + "example": "reader", + "maxLength": 50 + }, + "object": { + "type": "string", + "example": "document:2021-budget", + "maxLength": 256 + }, + "condition": { + "$ref": "#/components/schemas/RelationshipCondition" + } + }, + "required": [ + "user", + "relation", + "object" + ] + }, + "TupleKeyWithoutCondition": { + "type": "object", + "properties": { + "user": { + "type": "string", + "example": "user:anne", + "maxLength": 512 + }, + "relation": { + "type": "string", + "example": "reader", + "maxLength": 50 + }, + "object": { + "type": "string", + "example": "document:2021-budget", + "maxLength": 256 + } + }, + "required": [ + "user", + "relation", + "object" + ] + }, + "TupleOperation": { + "type": "string", + "enum": [ + "TUPLE_OPERATION_WRITE", + "TUPLE_OPERATION_DELETE" + ], + "default": "TUPLE_OPERATION_WRITE", + "title": "buf:lint:ignore ENUM_ZERO_VALUE_SUFFIX" + }, + "TypeDefinition": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "document" + }, + "relations": { + "type": "object", + "example": { + "reader": { + "union": { + "child": [ + { + "this": {} + }, + { + "computedUserset": { + "object": "", + "relation": "writer" + } + } + ] + } + }, + "writer": { + "this": {} + } + }, + "additionalProperties": { + "$ref": "#/components/schemas/Userset" + } + }, + "metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/Metadata" + }, + { + "description": "A map whose keys are the name of the relation and whose value is the Metadata for that relation.\nIt also holds information around the module name and source file if this model was constructed\nfrom a modular model." + } + ] + } + }, + "required": [ + "type" + ] + }, + "TypeName": { + "type": "string", + "enum": [ + "TYPE_NAME_UNSPECIFIED", + "TYPE_NAME_ANY", + "TYPE_NAME_BOOL", + "TYPE_NAME_STRING", + "TYPE_NAME_INT", + "TYPE_NAME_UINT", + "TYPE_NAME_DOUBLE", + "TYPE_NAME_DURATION", + "TYPE_NAME_TIMESTAMP", + "TYPE_NAME_MAP", + "TYPE_NAME_LIST", + "TYPE_NAME_IPADDRESS" + ], + "default": "TYPE_NAME_UNSPECIFIED" + }, + "TypedWildcard": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "employee" + } + }, + "description": "Type bound public access.\n\nNormally represented using the `:*` syntax\n\n`employee:*` represents every object of type `employee`, including those not currently present in the system\n\nSee https://openfga.dev/docs/concepts#what-is-type-bound-public-access", + "required": [ + "type" + ] + }, + "UnauthenticatedResponse": { + "type": "object", + "example": { + "code": "unauthenticated", + "message": "unauthenticated" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/ErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "UnprocessableContentErrorCode": { + "type": "string", + "enum": [ + "no_throttled_error_code", + "throttled_timeout_error" + ], + "default": "no_throttled_error_code" + }, + "UnprocessableContentMessageResponse": { + "type": "object", + "example": { + "code": "throttled_timeout_error", + "message": "timeout due to throttling on complex request" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/UnprocessableContentErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "User": { + "type": "object", + "properties": { + "object": { + "$ref": "#/components/schemas/Object" + }, + "userset": { + "$ref": "#/components/schemas/UsersetUser" + }, + "wildcard": { + "$ref": "#/components/schemas/TypedWildcard" + } + }, + "description": "User.\n\nRepresents any possible value for a user (subject or principal). Can be a:\n- Specific user object e.g.: 'user:will', 'folder:marketing', 'org:contoso', ...)\n- Specific userset (e.g. 'group:engineering#member')\n- Public-typed wildcard (e.g. 'user:*')\n\nSee https://openfga.dev/docs/concepts#what-is-a-user" + }, + "UserTypeFilter": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "group" + }, + "relation": { + "type": "string", + "example": "member" + } + }, + "required": [ + "type" + ] + }, + "Users": { + "type": "object", + "properties": { + "users": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "users" + ] + }, + "Userset": { + "type": "object", + "properties": { + "this": { + "$ref": "#/components/schemas/DirectUserset" + }, + "computedUserset": { + "$ref": "#/components/schemas/ObjectRelation" + }, + "tupleToUserset": { + "$ref": "#/components/schemas/v1.TupleToUserset" + }, + "union": { + "$ref": "#/components/schemas/Usersets" + }, + "intersection": { + "$ref": "#/components/schemas/Usersets" + }, + "difference": { + "$ref": "#/components/schemas/v1.Difference" + } + } + }, + "UsersetTree": { + "type": "object", + "properties": { + "root": { + "$ref": "#/components/schemas/Node" + } + }, + "description": "A UsersetTree contains the result of an Expansion." + }, + "UsersetTree.Difference": { + "type": "object", + "properties": { + "base": { + "$ref": "#/components/schemas/Node" + }, + "subtract": { + "$ref": "#/components/schemas/Node" + } + }, + "required": [ + "base", + "subtract" + ] + }, + "UsersetTree.TupleToUserset": { + "type": "object", + "properties": { + "tupleset": { + "type": "string" + }, + "computed": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Computed" + }, + { + "type": "object" + } + ] + } + } + }, + "required": [ + "tupleset", + "computed" + ] + }, + "UsersetUser": { + "type": "object", + "properties": { + "type": { + "type": "string", + "example": "group" + }, + "id": { + "type": "string", + "example": "fga" + }, + "relation": { + "type": "string", + "example": "member" + } + }, + "description": "Userset.\n\nA set or group of users, represented in the `:#` format\n\n`group:fga#member` represents all members of group FGA, not to be confused by `group:fga` which represents the group itself as a specific object.\n\nSee: https://openfga.dev/docs/modeling/building-blocks/usersets#what-is-a-userset", + "required": [ + "type", + "id", + "relation" + ] + }, + "Usersets": { + "type": "object", + "properties": { + "child": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Userset" + }, + { + "type": "object" + } + ] + } + } + }, + "required": [ + "child" + ] + }, + "ValidationErrorMessageResponse": { + "type": "object", + "example": { + "code": "validation_error", + "message": "Generic validation error" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/ErrorCode" + }, + "message": { + "type": "string" + } + } + }, + "Wildcard": { + "type": "object" + }, + "WriteAssertionsBody": { + "type": "object", + "properties": { + "assertions": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Assertion" + }, + { + "type": "object" + } + ] + }, + "maxItems": 100 + } + }, + "required": [ + "assertions" + ] + }, + "WriteAssertionsResponse": { + "type": "object" + }, + "WriteAuthorizationModelBody": { + "type": "object", + "properties": { + "type_definitions": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TypeDefinition" + }, + { + "type": "object" + } + ] + }, + "minItems": 1 + }, + "schema_version": { + "type": "string" + }, + "conditions": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Condition" + } + } + }, + "required": [ + "type_definitions", + "schema_version" + ] + }, + "WriteAuthorizationModelResponse": { + "type": "object", + "properties": { + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + } + }, + "required": [ + "authorization_model_id" + ] + }, + "WriteBody": { + "type": "object", + "properties": { + "writes": { + "$ref": "#/components/schemas/WriteRequestWrites" + }, + "deletes": { + "$ref": "#/components/schemas/WriteRequestDeletes" + }, + "authorization_model_id": { + "type": "string", + "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + } + } + }, + "WriteRequestDeletes": { + "type": "object", + "properties": { + "tuple_keys": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKeyWithoutCondition" + }, + { + "type": "object" + } + ] + }, + "minItems": 1 + }, + "on_missing": { + "type": "string", + "example": "ignore", + "enum": [ + "error", + "ignore" + ], + "default": "error", + "description": "On 'error', the API returns an error when deleting a tuple that does not exist. On 'ignore', deletes of non-existent tuples are treated as no-ops." + } + }, + "required": [ + "tuple_keys" + ] + }, + "WriteRequestWrites": { + "type": "object", + "properties": { + "tuple_keys": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "minItems": 1 + }, + "on_duplicate": { + "type": "string", + "example": "ignore", + "enum": [ + "error", + "ignore" + ], + "default": "error", + "description": "On 'error' ( or unspecified ), the API returns an error if an identical tuple already exists. On 'ignore', identical writes are treated as no-ops (matching on user, relation, object, and RelationshipCondition)." + } + }, + "required": [ + "tuple_keys" + ] + }, + "WriteResponse": { + "type": "object" + }, + "v1.Difference": { + "type": "object", + "properties": { + "base": { + "$ref": "#/components/schemas/Userset" + }, + "subtract": { + "$ref": "#/components/schemas/Userset" + } + }, + "required": [ + "base", + "subtract" + ] + }, + "v1.TupleToUserset": { + "type": "object", + "properties": { + "tupleset": { + "allOf": [ + { + "$ref": "#/components/schemas/ObjectRelation" + }, + { + "title": "The target object/relation" + } + ] + }, + "computedUserset": { + "$ref": "#/components/schemas/ObjectRelation" + } + }, + "required": [ + "tupleset", + "computedUserset" + ] + } + } + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..f94da267 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,493 @@ +{ + "name": "@openfga/api", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@openfga/api", + "devDependencies": { + "swagger2openapi": "7.0.8" + } + }, + "node_modules/@exodus/schemasafe": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz", + "integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==", + "dev": true, + "license": "MIT" + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/call-me-maybe": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", + "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/es6-promise": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", + "integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/http2-client": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz", + "integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch-h2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz", + "integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==", + "dev": true, + "license": "MIT", + "dependencies": { + "http2-client": "^1.2.5" + }, + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/node-readfiles": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz", + "integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es6-promise": "^3.2.1" + } + }, + "node_modules/oas-kit-common": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz", + "integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "fast-safe-stringify": "^2.0.7" + } + }, + "node_modules/oas-linter": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz", + "integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@exodus/schemasafe": "^1.0.0-rc.2", + "should": "^13.2.1", + "yaml": "^1.10.0" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-resolver": { + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz", + "integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "node-fetch-h2": "^2.3.0", + "oas-kit-common": "^1.0.8", + "reftools": "^1.1.9", + "yaml": "^1.10.0", + "yargs": "^17.0.1" + }, + "bin": { + "resolve": "resolve.js" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-schema-walker": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz", + "integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==", + "dev": true, + "license": "BSD-3-Clause", + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-validator": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz", + "integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "call-me-maybe": "^1.0.1", + "oas-kit-common": "^1.0.8", + "oas-linter": "^3.2.2", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "reftools": "^1.1.9", + "should": "^13.2.1", + "yaml": "^1.10.0" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/reftools": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz", + "integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==", + "dev": true, + "license": "BSD-3-Clause", + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/should": { + "version": "13.2.3", + "resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz", + "integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "should-equal": "^2.0.0", + "should-format": "^3.0.3", + "should-type": "^1.4.0", + "should-type-adaptors": "^1.0.1", + "should-util": "^1.0.0" + } + }, + "node_modules/should-equal": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz", + "integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "should-type": "^1.4.0" + } + }, + "node_modules/should-format": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz", + "integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "should-type": "^1.3.0", + "should-type-adaptors": "^1.0.1" + } + }, + "node_modules/should-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz", + "integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/should-type-adaptors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz", + "integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "should-type": "^1.3.0", + "should-util": "^1.0.0" + } + }, + "node_modules/should-util": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz", + "integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/swagger2openapi": { + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz", + "integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "call-me-maybe": "^1.0.1", + "node-fetch": "^2.6.1", + "node-fetch-h2": "^2.3.0", + "node-readfiles": "^0.2.0", + "oas-kit-common": "^1.0.8", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "oas-validator": "^5.0.8", + "reftools": "^1.1.9", + "yaml": "^1.10.0", + "yargs": "^17.0.1" + }, + "bin": { + "boast": "boast.js", + "oas-validate": "oas-validate.js", + "swagger2openapi": "swagger2openapi.js" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true, + "license": "MIT" + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..e9eb112b --- /dev/null +++ b/package.json @@ -0,0 +1,10 @@ +{ + "name": "@openfga/api", + "private": true, + "scripts": { + "generate:openapiv3": "node scripts/generate_openapiv3.js" + }, + "devDependencies": { + "swagger2openapi": "7.0.8" + } +} diff --git a/scripts/generate_openapiv3.js b/scripts/generate_openapiv3.js new file mode 100644 index 00000000..19b54ad5 --- /dev/null +++ b/scripts/generate_openapiv3.js @@ -0,0 +1,478 @@ +#!/usr/bin/env node + +"use strict"; + +const crypto = require("crypto"); +const fs = require("fs/promises"); +const path = require("path"); +const converter = require("swagger2openapi"); +const converterPackage = require("swagger2openapi/package.json"); + +const HTTP_METHODS = new Set([ + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "trace", +]); +const REQUIRED_CONVERTER_VERSION = "7.0.8"; +const ROOT = path.resolve(__dirname, ".."); +const OPENAPI_V2_PATH = path.join( + ROOT, + "docs", + "openapiv2", + "apidocs.swagger.json", +); +const OPENAPI_V3_PATH = path.join( + ROOT, + "docs", + "openapiv3", + "apidocs.openapi.json", +); + +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +function isObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function requireObject(value, label) { + invariant(isObject(value), `${label} must be an object`); +} + +function hasOwn(value, key) { + return Object.prototype.hasOwnProperty.call(value, key); +} + +function hash(value) { + return crypto.createHash("sha256").update(value).digest("hex"); +} + +function canonicalJson(value) { + if (Array.isArray(value)) { + return `[${value.map(canonicalJson).join(",")}]`; + } + if (isObject(value)) { + return `{${Object.keys(value) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`) + .join(",")}}`; + } + return JSON.stringify(value); +} + +function walk(value, visit, location = "#") { + if (Array.isArray(value)) { + value.forEach((item, index) => walk(item, visit, `${location}/${index}`)); + return; + } + if (!isObject(value)) { + return; + } + + visit(value, location); + for (const [key, child] of Object.entries(value)) { + const escapedKey = key.replaceAll("~", "~0").replaceAll("/", "~1"); + walk(child, visit, `${location}/${escapedKey}`); + } +} + +function validateRootShapeV2(document) { + requireObject(document, "OpenAPI v2 document"); + invariant(document.swagger === "2.0", 'OpenAPI v2 root "swagger" must be "2.0"'); + invariant(!hasOwn(document, "openapi"), 'OpenAPI v2 root must not contain "openapi"'); + requireObject(document.info, "OpenAPI v2 info"); + requireObject(document.paths, "OpenAPI v2 paths"); + requireObject(document.definitions, "OpenAPI v2 definitions"); + invariant(Array.isArray(document.tags), "OpenAPI v2 tags must be an array"); +} + +function validateRootShapeV3(document) { + requireObject(document, "OpenAPI v3 document"); + invariant(document.openapi === "3.0.3", 'OpenAPI v3 root "openapi" must be "3.0.3"'); + requireObject(document.info, "OpenAPI v3 info"); + requireObject(document.paths, "OpenAPI v3 paths"); + requireObject(document.components, "OpenAPI v3 components"); + requireObject(document.components.schemas, "OpenAPI v3 component schemas"); + invariant(Array.isArray(document.tags), "OpenAPI v3 tags must be an array"); + + for (const key of [ + "swagger", + "definitions", + "parameters", + "responses", + "securityDefinitions", + "schemes", + "consumes", + "produces", + ]) { + invariant(!hasOwn(document, key), `OpenAPI v3 root contains Swagger-only key "${key}"`); + } +} + +function collectParameters(pathItem, operation) { + return [...(pathItem.parameters || []), ...(operation.parameters || [])]; +} + +function collectOperations(document, version) { + const operations = new Map(); + const operationIds = new Map(); + + for (const [apiPath, pathItem] of Object.entries(document.paths)) { + invariant(apiPath.startsWith("/"), `${version} path "${apiPath}" must start with "/"`); + requireObject(pathItem, `${version} path item ${apiPath}`); + + for (const [method, operation] of Object.entries(pathItem)) { + if (!HTTP_METHODS.has(method)) { + continue; + } + + requireObject(operation, `${version} operation ${method.toUpperCase()} ${apiPath}`); + invariant( + typeof operation.operationId === "string" && operation.operationId.length > 0, + `${version} operation ${method.toUpperCase()} ${apiPath} must have an operationId`, + ); + invariant( + !operationIds.has(operation.operationId), + `${version} operationId "${operation.operationId}" is duplicated`, + ); + operationIds.set(operation.operationId, `${method.toUpperCase()} ${apiPath}`); + requireObject( + operation.responses, + `${version} responses for ${method.toUpperCase()} ${apiPath}`, + ); + + const responseCodes = Object.keys(operation.responses) + .filter((code) => !code.startsWith("x-")) + .sort(); + invariant( + responseCodes.length > 0, + `${version} operation ${method.toUpperCase()} ${apiPath} must define responses`, + ); + + operations.set(`${apiPath}\t${method}`, { + apiPath, + method, + operation, + pathItem, + responseCodes, + }); + } + } + + return operations; +} + +function validateInternalRefs(document, version) { + let count = 0; + + walk(document, (value, location) => { + if (!hasOwn(value, "$ref")) { + return; + } + + count += 1; + const ref = value.$ref; + invariant(typeof ref === "string", `${version} $ref at ${location} must be a string`); + invariant( + ref === "#" || ref.startsWith("#/"), + `${version} $ref at ${location} must be internal: ${ref}`, + ); + + let target = document; + if (ref !== "#") { + const tokens = ref + .slice(2) + .split("/") + .map((token) => + decodeURIComponent(token).replaceAll("~1", "/").replaceAll("~0", "~"), + ); + for (const token of tokens) { + invariant( + isObject(target) || Array.isArray(target), + `${version} $ref at ${location} does not resolve: ${ref}`, + ); + invariant( + hasOwn(target, token), + `${version} $ref at ${location} does not resolve: ${ref}`, + ); + target = target[token]; + } + } + }); + + return count; +} + +function collectExamples(document) { + const examples = new Map(); + + walk(document, (value) => { + if (!hasOwn(value, "example")) { + return; + } + const example = canonicalJson(value.example); + examples.set(example, (examples.get(example) || 0) + 1); + }); + + return examples; +} + +function validateServiceCoverage(document, operations, version) { + const rootTagNames = new Set(document.tags.map((tag) => tag.name)); + invariant(rootTagNames.has("OpenFGAService"), `${version} is missing OpenFGAService tag`); + invariant(rootTagNames.has("AuthZenService"), `${version} is missing AuthZenService tag`); + + let authZenOperations = 0; + let openFgaOperations = 0; + for (const { operation } of operations.values()) { + invariant( + Array.isArray(operation.tags), + `${version} ${operation.operationId} tags must be an array`, + ); + if (operation.tags.includes("AuthZenService")) { + authZenOperations += 1; + } else { + openFgaOperations += 1; + } + invariant( + !operation.operationId.includes("UpdateStore"), + `${version} must not expose the unimplemented UpdateStore operation`, + ); + } + + invariant(authZenOperations > 0, `${version} must contain AuthZen operations`); + invariant(openFgaOperations > 0, `${version} must contain OpenFGA operations`); +} + +function validateContentFree204(operations, version) { + for (const { apiPath, method, operation } of operations.values()) { + const response = operation.responses["204"]; + if (!response) { + continue; + } + requireObject( + response, + `${version} 204 response for ${method.toUpperCase()} ${apiPath}`, + ); + if (version === "OpenAPI v2") { + invariant( + !hasOwn(response, "schema"), + `${version} 204 response for ${method.toUpperCase()} ${apiPath} must not have a schema`, + ); + } else { + invariant( + !hasOwn(response, "content"), + `${version} 204 response for ${method.toUpperCase()} ${apiPath} must not have content`, + ); + } + } +} + +function validateNoSwaggerOnlyV3(document, operations) { + for (const { apiPath, method, operation, pathItem } of operations.values()) { + for (const key of ["consumes", "produces", "schemes"]) { + invariant( + !hasOwn(operation, key), + `OpenAPI v3 operation ${method.toUpperCase()} ${apiPath} contains Swagger-only key "${key}"`, + ); + } + + for (const parameter of collectParameters(pathItem, operation)) { + requireObject( + parameter, + `OpenAPI v3 parameter for ${method.toUpperCase()} ${apiPath}`, + ); + invariant( + parameter.in !== "body" && parameter.in !== "formData", + `OpenAPI v3 operation ${method.toUpperCase()} ${apiPath} contains a Swagger-only ${parameter.in} parameter`, + ); + for (const key of ["type", "format", "items", "collectionFormat"]) { + invariant( + !hasOwn(parameter, key), + `OpenAPI v3 parameter for ${method.toUpperCase()} ${apiPath} contains Swagger-only key "${key}"`, + ); + } + } + + for (const [code, response] of Object.entries(operation.responses)) { + if (code.startsWith("x-")) { + continue; + } + requireObject( + response, + `OpenAPI v3 response ${code} for ${method.toUpperCase()} ${apiPath}`, + ); + for (const key of ["schema", "examples"]) { + invariant( + !hasOwn(response, key), + `OpenAPI v3 response ${code} for ${method.toUpperCase()} ${apiPath} contains Swagger-only key "${key}"`, + ); + } + } + } + + walk(document, (value, location) => { + for (const key of Object.keys(value)) { + invariant( + !key.toLowerCase().startsWith("x-mintlify"), + `OpenAPI v3 contains Mintlify-specific extension "${key}" at ${location}`, + ); + } + if (hasOwn(value, "$ref")) { + invariant( + !value.$ref.startsWith("#/definitions/"), + `OpenAPI v3 contains a Swagger-only definition reference at ${location}`, + ); + } + }); +} + +function validateParity(v2, v3, v2Operations, v3Operations) { + invariant( + canonicalJson(Object.keys(v2.paths).sort()) === + canonicalJson(Object.keys(v3.paths).sort()), + "API paths changed during OpenAPI v3 conversion", + ); + invariant( + v2Operations.size === v3Operations.size, + `operation count changed from ${v2Operations.size} to ${v3Operations.size}`, + ); + + for (const [key, v2Entry] of v2Operations) { + const v3Entry = v3Operations.get(key); + invariant( + v3Entry, + `OpenAPI v3 is missing ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, + ); + + for (const property of ["operationId", "summary", "description", "tags"]) { + invariant( + canonicalJson(v2Entry.operation[property]) === + canonicalJson(v3Entry.operation[property]), + `${property} changed for ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, + ); + } + invariant( + canonicalJson(v2Entry.responseCodes) === canonicalJson(v3Entry.responseCodes), + `response codes changed for ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, + ); + for (const code of v2Entry.responseCodes) { + invariant( + v2Entry.operation.responses[code].description === + v3Entry.operation.responses[code].description, + `response ${code} description changed for ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, + ); + } + } + + const v2Schemas = Object.keys(v2.definitions).sort(); + const v3Schemas = Object.keys(v3.components.schemas).sort(); + invariant( + canonicalJson(v2Schemas) === canonicalJson(v3Schemas), + "component schema names changed during OpenAPI v3 conversion", + ); + invariant( + canonicalJson(v2.tags) === canonicalJson(v3.tags), + "root tags changed during conversion", + ); + + const v2Examples = collectExamples(v2); + const v3Examples = collectExamples(v3); + invariant( + canonicalJson(Object.fromEntries(v2Examples)) === + canonicalJson(Object.fromEntries(v3Examples)), + "examples changed during OpenAPI v3 conversion", + ); + + if (!hasOwn(v2, "host") && !hasOwn(v2, "basePath")) { + invariant(!hasOwn(v3, "servers"), "OpenAPI v3 conversion invented servers"); + } + if (!hasOwn(v2, "securityDefinitions")) { + invariant( + !hasOwn(v3.components, "securitySchemes"), + "OpenAPI v3 conversion invented security schemes", + ); + } + if (!hasOwn(v2, "security")) { + invariant(!hasOwn(v3, "security"), "OpenAPI v3 conversion invented root security policy"); + } +} + +async function writeAtomically(filename, contents) { + await fs.mkdir(path.dirname(filename), { recursive: true }); + const temporaryFilename = path.join( + path.dirname(filename), + `.${path.basename(filename)}.${process.pid}.tmp`, + ); + + try { + await fs.writeFile(temporaryFilename, contents, { flag: "wx" }); + await fs.rename(temporaryFilename, filename); + } finally { + await fs.rm(temporaryFilename, { force: true }); + } +} + +async function main() { + invariant( + converterPackage.version === REQUIRED_CONVERTER_VERSION, + `swagger2openapi ${REQUIRED_CONVERTER_VERSION} is required; found ${converterPackage.version}`, + ); + + const sourceBytes = await fs.readFile(OPENAPI_V2_PATH); + const sourceHash = hash(sourceBytes); + const openapiV2 = JSON.parse(sourceBytes.toString("utf8")); + validateRootShapeV2(openapiV2); + const v2Operations = collectOperations(openapiV2, "OpenAPI v2"); + validateServiceCoverage(openapiV2, v2Operations, "OpenAPI v2"); + validateContentFree204(v2Operations, "OpenAPI v2"); + validateInternalRefs(openapiV2, "OpenAPI v2"); + + const conversion = await converter.convertObj(openapiV2, { + refSiblings: "allOf", + targetVersion: "3.0.3", + }); + invariant(conversion.patches === 0, "swagger2openapi unexpectedly patched the v2 input"); + invariant( + !conversion.warnings || conversion.warnings.length === 0, + "swagger2openapi produced conversion warnings", + ); + + const openapiV3 = conversion.openapi; + validateRootShapeV3(openapiV3); + const v3Operations = collectOperations(openapiV3, "OpenAPI v3"); + validateNoSwaggerOnlyV3(openapiV3, v3Operations); + validateServiceCoverage(openapiV3, v3Operations, "OpenAPI v3"); + validateContentFree204(v3Operations, "OpenAPI v3"); + validateInternalRefs(openapiV3, "OpenAPI v3"); + validateParity(openapiV2, openapiV3, v2Operations, v3Operations); + + const sourceBytesAfterConversion = await fs.readFile(OPENAPI_V2_PATH); + invariant( + sourceHash === hash(sourceBytesAfterConversion) && + sourceBytes.equals(sourceBytesAfterConversion), + "OpenAPI v2 artifact changed during OpenAPI v3 conversion", + ); + + await writeAtomically(OPENAPI_V3_PATH, `${JSON.stringify(openapiV3, null, 2)}\n`); + + console.log( + `Generated OpenAPI 3.0.3: ${Object.keys(openapiV3.paths).length} paths, ` + + `${v3Operations.size} operations, ${Object.keys(openapiV3.components.schemas).length} schemas, ` + + `${[...collectExamples(openapiV3).values()].reduce((sum, count) => sum + count, 0)} examples`, + ); + console.log(`OpenAPI v2 SHA-256 unchanged: ${sourceHash}`); +} + +main().catch((error) => { + console.error(error.stack || error.message); + process.exitCode = 1; +}); From 65fa0e1b8f373c1ab3171aed216c9286555c024f Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 3 Sep 2026 15:53:52 +0530 Subject: [PATCH 2/4] refactor: generate OpenAPI v3 with Go Replace the Node conversion toolchain with a dedicated kin-openapi module while preserving the finalized Swagger 2 source and full OpenAPI 3 semantic parity. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/dependabot.yaml | 4 +- .github/workflows/review.yaml | 8 +- .gitignore | 1 - Makefile | 5 +- README.md | 9 +- docs/openapiv3/apidocs.openapi.json | 9064 +++++++++++++-------------- package-lock.json | 493 -- package.json | 10 - scripts/generate_openapiv3.js | 478 -- tools/openapiv3/go.mod | 17 + tools/openapiv3/go.sum | 36 + tools/openapiv3/main.go | 1301 ++++ tools/openapiv3/main_test.go | 349 ++ 13 files changed, 6249 insertions(+), 5526 deletions(-) delete mode 100644 package-lock.json delete mode 100644 package.json delete mode 100644 scripts/generate_openapiv3.js create mode 100644 tools/openapiv3/go.mod create mode 100644 tools/openapiv3/go.sum create mode 100644 tools/openapiv3/main.go create mode 100644 tools/openapiv3/main_test.go diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index b203fcee..52d35fdc 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -11,8 +11,8 @@ updates: patterns: - "*" - - package-ecosystem: "npm" - directory: "/" + - package-ecosystem: "gomod" + directory: "/tools/openapiv3" schedule: interval: "weekly" groups: diff --git a/.github/workflows/review.yaml b/.github/workflows/review.yaml index 9a7fbd95..4367d27c 100644 --- a/.github/workflows/review.yaml +++ b/.github/workflows/review.yaml @@ -30,11 +30,11 @@ jobs: with: fetch-depth: 0 - uses: bufbuild/buf-setup-action@a47c93e0b1648d5651a065437926377d060baa99 # v1.50.0 - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - node-version: 24 - cache: npm - - run: npm ci + go-version: 1.26.6 + cache-dependency-path: tools/openapiv3/go.sum + - run: make test-openapi-v3 - name: "Generate OpenAPI & Diff" run: | make all diff --git a/.gitignore b/.gitignore index 976b6c52..22ac7755 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,3 @@ .DS_Store .env -node_modules/ diff --git a/Makefile b/Makefile index ec08b14c..787065ea 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,10 @@ patch-swagger-doc: buf-gen ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json openapi-v3: patch-swagger-doc - npm run --silent generate:openapiv3 + cd tools/openapiv3 && go run . + +test-openapi-v3: + cd tools/openapiv3 && go test ./... format: buf-gen buf format -w diff --git a/README.md b/README.md index 33858c85..327943f9 100644 --- a/README.md +++ b/README.md @@ -59,23 +59,22 @@ Generation produces both the finalized Swagger 2.0 document at `docs/openapiv2/apidocs.swagger.json` and an additive OpenAPI 3.0.3 document at `docs/openapiv3/apidocs.openapi.json`. -> **Note**: You must have [jq](https://jqlang.github.io/jq/download/), Node.js, and npm installed. +> **Note**: You must have [jq](https://jqlang.github.io/jq/download/) and Go installed. ```bash -npm ci ./buf.gen.yaml ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json -npm run generate:openapiv3 +(cd tools/openapiv3 && go run .) buf format -w ``` Or you can just use ```bash -npm ci make ``` -The OpenAPI 3 document is deterministically converted from the finalized Swagger 2 document. +The OpenAPI 3 document is deterministically converted from the finalized Swagger 2 document +using the Go tool in `tools/openapiv3`. Existing SDK generation remains compatible with, and must continue to use, `docs/openapiv2/apidocs.swagger.json`. diff --git a/docs/openapiv3/apidocs.openapi.json b/docs/openapiv3/apidocs.openapi.json index 0c07a51c..7b837bab 100644 --- a/docs/openapiv3/apidocs.openapi.json +++ b/docs/openapiv3/apidocs.openapi.json @@ -1,5146 +1,5146 @@ { - "openapi": "3.0.3", - "info": { - "title": "OpenFGA", - "description": "A high performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar.", - "version": "1.x", - "contact": { - "name": "OpenFGA", - "url": "https://openfga.dev", - "email": "community@openfga.dev" - }, - "license": { - "name": "Apache-2.0", - "url": "https://github.com/openfga/openfga/blob/main/LICENSE" - } - }, - "tags": [ - { - "name": "AuthZenService" - }, - { - "name": "OpenFGAService" - } - ], - "paths": { - "/.well-known/authzen-configuration/{store_id}": { - "get": { - "summary": "[Experimental] Get AuthZEN PDP configuration and capabilities", - "description": "[Experimental] The GetConfiguration API returns metadata about the Policy Decision Point (PDP) including its name, version, supported endpoints, and capabilities. This endpoint follows the AuthZEN specification for PDP discovery.\n\nFollowing the AuthZEN spec's multi-tenant pattern, OpenFGA provides a per-store discovery endpoint at `/.well-known/authzen-configuration/{store_id}`. This returns absolute endpoint URLs specific to that store.\n\n## Example Response\n```json\n{\n \"policy_decision_point\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV\",\n \"access_evaluation_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/evaluation\",\n \"access_evaluations_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/evaluations\",\n \"search_subject_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/subject\",\n \"search_resource_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/resource\",\n \"search_action_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/action\"\n}\n```\n", - "operationId": "GetConfiguration", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GetConfigurationResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "components": { + "schemas": { + "AbortedMessageResponse": { + "example": { + "code": "10", + "message": "transaction conflict" + }, + "properties": { + "code": { + "type": "string" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "message": { + "type": "string" + } + }, + "type": "object" + }, + "Action": { + "properties": { + "name": { + "example": "can_read", + "type": "string" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "properties": { + "type": "object" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "ActionSearchBody": { + "properties": { + "context": { + "type": "object" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "page": { + "$ref": "#/components/schemas/PageRequest" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "resource": { + "$ref": "#/components/schemas/Resource" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } + "subject": { + "$ref": "#/components/schemas/Subject" + } + }, + "required": [ + "subject", + "resource" + ], + "title": "ActionSearch request", + "type": "object" + }, + "ActionSearchResponse": { + "properties": { + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" } - } + ] }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" + "results": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Action" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" } }, - "parameters": [ - { - "name": "store_id", - "description": "The store ID for which to retrieve configuration.\nFollowing the AuthZEN spec's multi-tenant pattern, each store has its own discovery endpoint.", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "type": "object" + }, + "Any": { + "additionalProperties": {}, + "properties": { + "@type": { + "type": "string" } - ], - "tags": [ - "AuthZenService" - ] - } - }, - "/stores": { - "get": { - "summary": "List all stores", - "description": "Returns a paginated list of OpenFGA stores and a continuation token to get additional stores.\nThe continuation token will be empty if there are no more stores.\n", - "operationId": "ListStores", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ListStoresResponse" - } - } - } + }, + "type": "object" + }, + "Assertion": { + "properties": { + "context": { + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation.", + "example": { + "view_count": 100 + }, + "type": "object" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + "contextual_tuples": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" } - } - } + ] + }, + "maxItems": 20, + "type": "array" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "expectation": { + "type": "boolean" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "tuple_key": { + "$ref": "#/components/schemas/AssertionTupleKey" + } + }, + "required": [ + "tuple_key", + "expectation" + ], + "type": "object" + }, + "AssertionTupleKey": { + "properties": { + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "user": { + "example": "user:anne", + "maxLength": 512, + "type": "string" + } + }, + "required": [ + "object", + "relation", + "user" + ], + "type": "object" + }, + "AuthErrorCode": { + "default": "no_auth_error", + "enum": [ + "no_auth_error", + "auth_failed_invalid_subject", + "auth_failed_invalid_audience", + "auth_failed_invalid_issuer", + "invalid_claims", + "auth_failed_invalid_bearer_token", + "bearer_token_missing", + "unauthenticated", + "forbidden" + ], + "type": "string" + }, + "AuthorizationModel": { + "properties": { + "conditions": { + "additionalProperties": { + "$ref": "#/components/schemas/Condition" + }, + "type": "object" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } + "schema_version": { + "type": "string" + }, + "type_definitions": { + "example": [ + { + "type": "user" + }, + { + "metadata": { + "relations": { + "reader": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + }, + "writer": { + "directly_related_user_types": [ + { + "type": "user" + } + ] + } + } + }, + "relations": { + "reader": { + "union": { + "child": [ + { + "this": {} + }, + { + "computedUserset": { + "object": "", + "relation": "writer" + } + } + ] + } + }, + "writer": { + "this": {} + } + }, + "type": "document" } - } + ], + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TypeDefinition" + }, + { + "type": "object" + } + ] + }, + "type": "array" } }, - "parameters": [ - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "format": "int32" - } + "required": [ + "id", + "schema_version", + "type_definitions" + ], + "type": "object" + }, + "BatchCheckBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - { - "name": "continuation_token", - "in": "query", - "required": false, - "schema": { - "type": "string" - } + "checks": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/BatchCheckItem" + }, + { + "type": "object" + } + ] + }, + "minItems": 1, + "type": "array" }, - { - "name": "name", - "description": "The name parameter instructs the API to only include results that match that name.Multiple results may be returned. Only exact matches will be returned; substring matches and regexes will not be evaluated", - "in": "query", - "required": false, - "schema": { - "type": "string" - } + "consistency": { + "$ref": "#/components/schemas/ConsistencyPreference" } + }, + "required": [ + "checks" ], - "tags": [ - "Stores" - ] + "type": "object" }, - "post": { - "summary": "Create a store", - "description": "Create a unique OpenFGA store which will be used to store authorization models and relationship tuples.", - "operationId": "CreateStore", - "responses": { - "201": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateStoreResponse" - } - } - } + "BatchCheckItem": { + "properties": { + "context": { + "type": "object" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "correlation_id": { + "description": "correlation_id must be a string containing only letters, numbers, or hyphens, with length ≤ 36 characters.", + "example": "1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc", + "type": "string" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" + "tuple_key": { + "$ref": "#/components/schemas/CheckRequestTupleKey" + } + }, + "required": [ + "tuple_key", + "correlation_id" + ], + "type": "object" + }, + "BatchCheckResponse": { + "properties": { + "result": { + "additionalProperties": { + "$ref": "#/components/schemas/BatchCheckSingleResult" + }, + "description": "map keys are the correlation_id values from the BatchCheckItems in the request", + "example": { + "1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc": { + "allowed": true, + "error": { + "message": "" } } - } + }, + "type": "object" + } + }, + "type": "object" + }, + "BatchCheckSingleResult": { + "properties": { + "allowed": { + "type": "boolean" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } - }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } - }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "error": { + "$ref": "#/components/schemas/CheckError" } }, - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateStoreRequest" - } - } - }, - "required": true - }, - "tags": [ - "Stores" - ] - } - }, - "/stores/{store_id}": { - "get": { - "summary": "Get a store", - "description": "Returns an OpenFGA store by its identifier", - "operationId": "GetStore", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GetStoreResponse" - } - } - } + "type": "object" + }, + "CheckBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." } - } + ] }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "context": { + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation.", + "type": "object" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "trace": { + "description": "Defaults to false. Making it true has performance implications.", + "example": false, + "readOnly": true, + "type": "boolean" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "tuple_key": { + "$ref": "#/components/schemas/CheckRequestTupleKey" + } + }, + "required": [ + "tuple_key" + ], + "type": "object" + }, + "CheckError": { + "properties": { + "input_error": { + "$ref": "#/components/schemas/ErrorCode" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "internal_error": { + "$ref": "#/components/schemas/InternalErrorCode" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "message": { + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "type": "object" + }, + "CheckRequestTupleKey": { + "properties": { + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" + }, + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" + }, + "user": { + "example": "user:anne", + "maxLength": 512, + "type": "string" } + }, + "required": [ + "user", + "relation", + "object" ], - "tags": [ - "Stores" - ] + "type": "object" }, - "delete": { - "summary": "Delete a store", - "description": "Delete an OpenFGA store. This does not delete the data associated with the store, like tuples or authorization models.", - "operationId": "DeleteStore", - "responses": { - "204": { - "description": "A successful response." + "CheckResponse": { + "properties": { + "allowed": { + "example": true, + "type": "boolean" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "resolution": { + "description": "For internal use only.", + "type": "string" + } + }, + "type": "object" + }, + "Computed": { + "properties": { + "userset": { + "type": "string" + } + }, + "required": [ + "userset" + ], + "type": "object" + }, + "Condition": { + "properties": { + "expression": { + "description": "A Google CEL expression, expressed as a string.", + "type": "string" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "metadata": { + "$ref": "#/components/schemas/ConditionMetadata" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "name": { + "title": "A unique name for the condition", + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } - }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } - }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "parameters": { + "additionalProperties": { + "$ref": "#/components/schemas/ConditionParamTypeRef" + }, + "description": "A map of parameter names to the parameter's defined type reference.", + "type": "object" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } + "required": [ + "name", + "expression" ], - "tags": [ - "Stores" - ] - } - }, - "/stores/{store_id}/access/v1/evaluation": { - "post": { - "summary": "[Experimental] Evaluate whether a subject can perform an action on a resource", - "description": "[Experimental] The Evaluation API determines whether a subject is authorized to perform an action on a resource. This endpoint implements the AuthZEN Access Evaluation API specification.\n\n## Request Structure\nThe request requires three components:\n- **subject**: The entity requesting access (e.g., a user or service)\n- **action**: The operation being performed (maps to a relation in the authorization model)\n- **resource**: The object being accessed\n\nEach component has a `type` and `id` field, and may include optional `properties` for ABAC (Attribute-Based Access Control) conditions.\n\n## Response\nThe response contains a `decision` field (boolean) indicating whether access is permitted, and an optional `context` object with additional information such as the evaluation ID or error details.\n\n## ABAC Support\nProperties on subject, action, and resource are automatically merged into the evaluation context with prefixes:\n- Subject properties: `subject_`\n- Resource properties: `resource_`\n- Action properties: `action_`\n\nThese merged properties can be used in conditions defined in your authorization model.\n\n## Examples\n### Basic authorization check\nCheck if user Anne can read a document:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"}\n}\n```\nResponse when authorized:\n```json\n{\n \"decision\": true\n}\n```\n### Using properties for ABAC\nCheck access with subject and resource attributes:\n```json\n{\n \"subject\": {\n \"type\": \"user\",\n \"id\": \"anne\",\n \"properties\": {\"department\": \"engineering\", \"clearance_level\": 3}\n },\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\n \"type\": \"document\",\n \"id\": \"secret-project\",\n \"properties\": {\"classification\": \"confidential\", \"required_clearance\": 2}\n }\n}\n```\n### Using request context\nProvide additional context for time-based or environmental conditions:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"action\": {\"name\": \"can_access\"},\n \"resource\": {\"type\": \"system\", \"id\": \"production\"},\n \"context\": {\n \"current_time\": \"2024-01-15T14:30:00Z\",\n \"ip_address\": \"192.168.1.100\",\n \"is_vpn_connected\": true\n }\n}\n```\n### Specifying authorization model\nPin the evaluation to a specific authorization model version using the `Openfga-Authorization-Model-Id` header:\n```\nPOST /stores/{store_id}/access/v1/evaluation\nOpenfga-Authorization-Model-Id: 01G50QVV17PECNVAHX1GG4Y5NC\n\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_write\"},\n \"resource\": {\"type\": \"document\", \"id\": \"budget-2024\"}\n}\n```\n", - "operationId": "Evaluation", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EvaluationResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } - }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } - }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } - }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "type": "object" + }, + "ConditionMetadata": { + "properties": { + "module": { + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + }, + "type": "object" + }, + "ConditionParamTypeRef": { + "properties": { + "generic_types": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/ConditionParamTypeRef" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "type_name": { + "$ref": "#/components/schemas/TypeName" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "required": [ + "type_name" + ], + "type": "object" + }, + "ConsistencyPreference": { + "default": "UNSPECIFIED", + "description": "Controls the consistency preferences when calling the query APIs.\n\n - UNSPECIFIED: Default if not set. Behavior will be the same as MINIMIZE_LATENCY.\n - MINIMIZE_LATENCY: Minimize latency at the potential expense of lower consistency.\n - HIGHER_CONSISTENCY: Prefer higher consistency, at the potential expense of increased latency.", + "enum": [ + "UNSPECIFIED", + "MINIMIZE_LATENCY", + "HIGHER_CONSISTENCY" + ], + "example": "MINIMIZE_LATENCY", + "type": "string" + }, + "ContextualTupleKeys": { + "properties": { + "tuple_keys": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "maxItems": 100, + "type": "array" } + }, + "required": [ + "tuple_keys" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EvaluationBody" - } - } - }, - "required": true + "type": "object" + }, + "CreateStoreRequest": { + "properties": { + "name": { + "example": "my-store-name", + "type": "string" + } }, - "tags": [ - "AuthZenService" - ] - } - }, - "/stores/{store_id}/access/v1/evaluations": { - "post": { - "summary": "[Experimental] Check whether one or more users are authorized to access resources", - "description": "[Experimental] The Evaluations API allows batch authorization checks in a single request. It supports request-level defaults for subject, action, resource, and context that can be overridden per evaluation item.\n\n## Evaluation Semantics\nThe `options.evaluations_semantic` field controls how evaluations are processed:\n- `execute_all` (default): Execute all evaluations and return all results\n- `deny_on_first_deny`: Stop processing on first deny decision\n- `permit_on_first_permit`: Stop processing on first permit decision\n\nWhen using `deny_on_first_deny` or `permit_on_first_permit`, the response may include fewer items than the request because processing short-circuits when the condition is met.\n\n## Authorization Model Selection\nTo pin evaluations to a specific authorization model version, send the `Openfga-Authorization-Model-Id` header. If the header is not provided, the latest model is used.\n\n## Examples\n### Basic batch evaluation\nCheck if a user can perform multiple actions on a document:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"evaluations\": [\n {\"action\": {\"name\": \"can_read\"}},\n {\"action\": {\"name\": \"can_write\"}},\n {\"action\": {\"name\": \"can_delete\"}}\n ]\n}\n```\n### Using evaluation semantics\nStop on first permitted action (useful for finding any valid permission):\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"evaluations\": [\n {\"action\": {\"name\": \"can_read\"}},\n {\"action\": {\"name\": \"can_write\"}}\n ],\n \"options\": {\n \"evaluations_semantic\": \"permit_on_first_permit\"\n }\n}\n```\n### Overriding defaults per evaluation\nCheck permissions across multiple resources:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"evaluations\": [\n {\"resource\": {\"type\": \"document\", \"id\": \"doc1\"}},\n {\"resource\": {\"type\": \"document\", \"id\": \"doc2\"}},\n {\"resource\": {\"type\": \"folder\", \"id\": \"folder1\"}}\n ]\n}\n```\n", - "operationId": "Evaluations", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EvaluationsResponse" - } - } - } + "required": [ + "name" + ], + "type": "object" + }, + "CreateStoreResponse": { + "properties": { + "created_at": { + "format": "date-time", + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "id": { + "example": "01YCP46JKYM8FJCQ37NMBYHE5X", + "type": "string" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "name": { + "type": "string" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } - }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } - }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } - }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } - } - }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EvaluationsBody" - } - } - }, - "required": true - }, - "tags": [ - "AuthZenService" - ] - } - }, - "/stores/{store_id}/access/v1/search/action": { - "post": { - "summary": "[Experimental] Search for actions a subject can perform on a resource", - "description": "[Experimental] The ActionSearch API returns all actions (relations) that a subject can perform on a specific resource. This is useful for answering questions like \"What can Anne do with this document?\" or building dynamic UIs that show only the actions a user is permitted to perform.\n\n## Examples\n### Find all actions a user can perform on a document\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"name\": \"can_read\"},\n {\"name\": \"can_write\"},\n {\"name\": \"can_share\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Search with ABAC context for time-based permissions\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"resource\": {\"type\": \"report\", \"id\": \"quarterly-financials\"},\n \"context\": {\n \"current_time\": \"2024-01-15T14:30:00Z\",\n \"user_department\": \"finance\"\n }\n}\n```\n### Paginated action search\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"admin\"},\n \"resource\": {\"type\": \"system\", \"id\": \"production\"},\n \"page\": {\"limit\": 50}\n}\n```\n", - "operationId": "ActionSearch", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ActionSearchResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } - }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } - }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } - }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } - }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } - }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "updated_at": { + "format": "date-time", + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } + "required": [ + "id", + "name", + "created_at", + "updated_at" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ActionSearchBody" - } - } - }, - "required": true - }, - "tags": [ - "AuthZenService" - ] - } - }, - "/stores/{store_id}/access/v1/search/resource": { - "post": { - "summary": "[Experimental] Search for resources a subject has access to", - "description": "[Experimental] The ResourceSearch API returns all resources of a given type that a subject has a specific action (relation) on. This is useful for answering questions like \"What documents can Anne read?\" or \"What folders can Bob administer?\"\n\nThe resource type filter is required. Results support pagination for large result sets.\n\n## Examples\n### Find all documents a user can read\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"type\": \"document\", \"id\": \"roadmap\"},\n {\"type\": \"document\", \"id\": \"budget-2024\"},\n {\"type\": \"document\", \"id\": \"team-roster\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Find folders a user can administer with pagination\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"action\": {\"name\": \"can_admin\"},\n \"resource\": {\"type\": \"folder\"},\n \"page\": {\"limit\": 25}\n}\n```\n### Search with ABAC context\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\"},\n \"context\": {\n \"current_time\": \"2024-01-15T10:00:00Z\",\n \"ip_address\": \"192.168.1.100\"\n }\n}\n```\n", - "operationId": "ResourceSearch", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ResourceSearchResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } - }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } - }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } - }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } - }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } - }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } - } - }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } + "type": "object" + }, + "DeleteStoreResponse": { + "type": "object" + }, + "DirectUserset": { + "description": "A DirectUserset is a sentinel message for referencing\nthe direct members specified by an object/relation mapping.", + "type": "object" + }, + "ErrorCode": { + "default": "no_error", + "enum": [ + "no_error", + "validation_error", + "authorization_model_not_found", + "authorization_model_resolution_too_complex", + "invalid_write_input", + "cannot_allow_duplicate_tuples_in_one_request", + "cannot_allow_duplicate_types_in_one_request", + "cannot_allow_multiple_references_to_one_relation", + "invalid_continuation_token", + "invalid_tuple_set", + "invalid_check_input", + "invalid_expand_input", + "unsupported_user_set", + "invalid_object_format", + "write_failed_due_to_invalid_input", + "authorization_model_assertions_not_found", + "latest_authorization_model_not_found", + "type_not_found", + "relation_not_found", + "empty_relation_definition", + "invalid_user", + "invalid_tuple", + "unknown_relation", + "store_id_invalid_length", + "assertions_too_many_items", + "id_too_long", + "authorization_model_id_too_long", + "tuple_key_value_not_specified", + "tuple_keys_too_many_or_too_few_items", + "page_size_invalid", + "param_missing_value", + "difference_base_missing_value", + "subtract_base_missing_value", + "object_too_long", + "relation_too_long", + "type_definitions_too_few_items", + "type_invalid_length", + "type_invalid_pattern", + "relations_too_few_items", + "relations_too_long", + "relations_invalid_pattern", + "object_invalid_pattern", + "query_string_type_continuation_token_mismatch", + "exceeded_entity_limit", + "invalid_contextual_tuple", + "duplicate_contextual_tuple", + "invalid_authorization_model", + "unsupported_schema_version", + "cancelled", + "invalid_start_time" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ResourceSearchBody" - } - } - }, - "required": true - }, - "tags": [ - "AuthZenService" - ] - } - }, - "/stores/{store_id}/access/v1/search/subject": { - "post": { - "summary": "[Experimental] Search for subjects with access to a resource", - "description": "[Experimental] The SubjectSearch API returns all subjects that have a specific action (relation) on a given resource. This is useful for answering questions like \"Who can read this document?\" or \"Who can administer this folder?\"\n\nResults can be filtered by subject type and support pagination for large result sets.\n\n## Examples\n### Find all users who can read a document\n```json\n{\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"action\": {\"name\": \"can_read\"},\n \"subject\": {\"type\": \"user\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"type\": \"user\", \"id\": \"anne\"},\n {\"type\": \"user\", \"id\": \"bob\"},\n {\"type\": \"user\", \"id\": \"charlie\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Paginated search with limit\n```json\n{\n \"resource\": {\"type\": \"folder\", \"id\": \"engineering\"},\n \"action\": {\"name\": \"can_view\"},\n \"subject\": {\"type\": \"user\"},\n \"page\": {\"limit\": 10}\n}\n```\n### Continue from previous page\n```json\n{\n \"resource\": {\"type\": \"folder\", \"id\": \"engineering\"},\n \"action\": {\"name\": \"can_view\"},\n \"subject\": {\"type\": \"user\"},\n \"page\": {\"token\": \"eyJsYXN0X2lkIjoiMTAwIn0=\", \"limit\": 10}\n}\n```\n", - "operationId": "SubjectSearch", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SubjectSearchResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } - }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } - }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } - }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } - }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "type": "string" + }, + "EvaluationBody": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "context": { + "type": "object" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "subject": { + "$ref": "#/components/schemas/Subject" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } + "required": [ + "subject", + "resource", + "action" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SubjectSearchBody" - } - } + "type": "object" + }, + "EvaluationResponse": { + "properties": { + "context": { + "type": "object" }, - "required": true + "decision": { + "type": "boolean" + } }, - "tags": [ - "AuthZenService" - ] - } - }, - "/stores/{store_id}/assertions/{authorization_model_id}": { - "get": { - "summary": "Read assertions for an authorization model ID", - "description": "The ReadAssertions API will return, for a given authorization model id, all the assertions stored for it. ", - "operationId": "ReadAssertions", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReadAssertionsResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } - }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "type": "object" + }, + "EvaluationsBody": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "context": { + "type": "object" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + "evaluations": { + "description": "Optional. If omitted or empty, behaves like a single Access Evaluation request.", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsItemRequest" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } + "options": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsOptions" + }, + { + "title": "Options for batch evaluation semantics" } - } + ] }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "resource": { + "$ref": "#/components/schemas/Resource" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "subject": { + "$ref": "#/components/schemas/Subject" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "authorization_model_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "tags": [ - "Assertions" - ] + "type": "object" }, - "put": { - "summary": "Upsert assertions for an authorization model ID", - "description": "The WriteAssertions API will upsert new assertions for an authorization model id, or overwrite the existing ones. An assertion is an object that contains a tuple key, the expectation of whether a call to the Check API of that tuple key will return true or false, and optionally a list of contextual tuples.", - "operationId": "WriteAssertions", - "responses": { - "204": { - "description": "A successful response." + "EvaluationsItemRequest": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "context": { + "type": "object" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "resource": { + "$ref": "#/components/schemas/Resource" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } + "subject": { + "$ref": "#/components/schemas/Subject" + } + }, + "type": "object" + }, + "EvaluationsOptions": { + "properties": { + "evaluations_semantic": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsSemantic" + }, + { + "title": "Controls how batch evaluations are processed" } - } - }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + ] + } + }, + "title": "Options for batch evaluations", + "type": "object" + }, + "EvaluationsResponse": { + "properties": { + "evaluations": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationResponse" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" + } + }, + "type": "object" + }, + "EvaluationsSemantic": { + "default": "execute_all", + "description": "- execute_all: Execute all evaluations (default behavior)\n - deny_on_first_deny: Stop on first deny decision\n - permit_on_first_permit: Stop on first permit decision", + "enum": [ + "execute_all", + "deny_on_first_deny", + "permit_on_first_permit" + ], + "title": "Enum for evaluation semantics", + "type": "string" + }, + "ExpandBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." } - } + ] }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "tuple_key": { + "$ref": "#/components/schemas/ExpandRequestTupleKey" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "required": [ + "tuple_key" + ], + "type": "object" + }, + "ExpandRequestTupleKey": { + "properties": { + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" }, - { - "name": "authorization_model_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" } + }, + "required": [ + "relation", + "object" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/WriteAssertionsBody" - } - } + "type": "object" + }, + "ExpandResponse": { + "properties": { + "tree": { + "$ref": "#/components/schemas/UsersetTree" + } + }, + "type": "object" + }, + "ForbiddenResponse": { + "example": { + "code": "forbidden", + "message": "the principal is not authorized to perform the action" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/AuthErrorCode" }, - "required": true + "message": { + "type": "string" + } }, - "tags": [ - "Assertions" - ] - } - }, - "/stores/{store_id}/authorization-models": { - "get": { - "summary": "Return all the authorization models for a particular store", - "description": "The ReadAuthorizationModels API will return all the authorization models for a certain store.\nOpenFGA's response will contain an array of all authorization models, sorted in descending order of creation.\n\n## Example\nAssume that a store's authorization model has been configured twice. To get all the authorization models that have been created in this store, call GET authorization-models. The API will return a response that looks like:\n```json\n{\n \"authorization_models\": [\n {\n \"id\": \"01G50QVV17PECNVAHX1GG4Y5NC\",\n \"type_definitions\": [...]\n },\n {\n \"id\": \"01G4ZW8F4A07AKQ8RHSVG9RW04\",\n \"type_definitions\": [...]\n },\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nIf there are no more authorization models available, the `continuation_token` field will be empty\n```json\n{\n \"authorization_models\": [\n {\n \"id\": \"01G50QVV17PECNVAHX1GG4Y5NC\",\n \"type_definitions\": [...]\n },\n {\n \"id\": \"01G4ZW8F4A07AKQ8RHSVG9RW04\",\n \"type_definitions\": [...]\n },\n ],\n \"continuation_token\": \"\"\n}\n```\n", - "operationId": "ReadAuthorizationModels", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReadAuthorizationModelsResponse" - } - } - } + "type": "object" + }, + "GetConfigurationResponse": { + "properties": { + "access_evaluation_endpoint": { + "description": "REQUIRED. The access evaluation endpoint URL.", + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "access_evaluations_endpoint": { + "description": "OPTIONAL. The batch evaluations endpoint URL.", + "type": "string" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "capabilities": { + "description": "OPTIONAL. Supported capabilities as URN strings.", + "items": { + "type": "string" + }, + "type": "array" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "policy_decision_point": { + "description": "REQUIRED. The PDP identifier URL (HTTPS, no query or fragment).", + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "search_action_endpoint": { + "description": "OPTIONAL. The action search endpoint URL.", + "type": "string" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "search_resource_endpoint": { + "description": "OPTIONAL. The resource search endpoint URL.", + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "search_subject_endpoint": { + "description": "OPTIONAL. The subject search endpoint URL.", + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "signed_metadata": { + "description": "OPTIONAL. Signed metadata JWT per AuthZEN metadata specification.", + "type": "string" + } + }, + "required": [ + "policy_decision_point", + "access_evaluation_endpoint" + ], + "title": "GetConfiguration response - PDP metadata per AuthZEN spec", + "type": "object" + }, + "GetStoreResponse": { + "properties": { + "created_at": { + "format": "date-time", + "type": "string" + }, + "deleted_at": { + "format": "date-time", + "type": "string" + }, + "id": { + "example": "01YCP46JKYM8FJCQ37NMBYHE5X", + "type": "string" + }, + "name": { + "type": "string" + }, + "updated_at": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "id", + "name", + "created_at", + "updated_at" + ], + "type": "object" + }, + "InternalErrorCode": { + "default": "no_internal_error", + "enum": [ + "no_internal_error", + "internal_error", + "deadline_exceeded", + "already_exists", + "resource_exhausted", + "failed_precondition", + "aborted", + "out_of_range", + "unavailable", + "data_loss" + ], + "type": "string" + }, + "InternalErrorMessageResponse": { + "example": { + "code": "internal_error", + "message": "Internal Server Error" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/InternalErrorCode" + }, + "message": { + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "type": "object" + }, + "Leaf": { + "description": "A leaf node contains either\n- a set of users (which may be individual users, or usersets\n referencing other relations)\n- a computed node, which is the result of a computed userset\n value in the authorization model\n- a tupleToUserset nodes, containing the result of expanding\n a tupleToUserset value in a authorization model.", + "properties": { + "computed": { + "$ref": "#/components/schemas/Computed" }, - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "format": "int32" - } + "tupleToUserset": { + "$ref": "#/components/schemas/UsersetTree.TupleToUserset" }, - { - "name": "continuation_token", - "in": "query", - "required": false, - "schema": { - "type": "string" - } + "users": { + "$ref": "#/components/schemas/Users" } - ], - "tags": [ - "Authorization Models" - ] + }, + "type": "object" }, - "post": { - "summary": "Create a new authorization model", - "description": "The WriteAuthorizationModel API will add a new authorization model to a store.\nEach item in the `type_definitions` array is a type definition as specified in the field `type_definition`.\nThe response will return the authorization model's ID in the `id` field.\n\n## Example\nTo add an authorization model with `user` and `document` type definitions, call POST authorization-models API with the body: \n```json\n{\n \"type_definitions\":[\n {\n \"type\":\"user\"\n },\n {\n \"type\":\"document\",\n \"relations\":{\n \"reader\":{\n \"union\":{\n \"child\":[\n {\n \"this\":{}\n },\n {\n \"computedUserset\":{\n \"object\":\"\",\n \"relation\":\"writer\"\n }\n }\n ]\n }\n },\n \"writer\":{\n \"this\":{}\n }\n }\n }\n ]\n}\n```\nOpenFGA's response will include the version id for this authorization model, which will look like \n```\n{\"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"}\n```\n", - "operationId": "WriteAuthorizationModel", - "responses": { - "201": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/WriteAuthorizationModelResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "ListObjectsBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." } - } + ] }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "context": { + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation.", + "type": "object" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "relation": { + "example": "reader", + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "type": { + "example": "document", + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "user": { + "example": "user:anne", + "maxLength": 512, + "minLength": 1, + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { + "required": [ + "type", + "relation", + "user" + ], + "type": "object" + }, + "ListObjectsResponse": { + "properties": { + "objects": { + "example": [ + "document:roadmap", + "document:planning" + ], + "items": { "type": "string" - } + }, + "type": "array" } + }, + "required": [ + "objects" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/WriteAuthorizationModelBody" - } - } + "type": "object" + }, + "ListStoresResponse": { + "properties": { + "continuation_token": { + "description": "The continuation token will be empty if there are no more stores.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" }, - "required": true - }, - "tags": [ - "Authorization Models" - ] - } - }, - "/stores/{store_id}/authorization-models/{id}": { - "get": { - "summary": "Return a particular version of an authorization model", - "description": "The ReadAuthorizationModel API returns an authorization model by its identifier.\nThe response will return the authorization model for the particular version.\n\n## Example\nTo retrieve the authorization model with ID `01G5JAVJ41T49E9TT3SKVS7X1J` for the store, call the GET authorization-models by ID API with `01G5JAVJ41T49E9TT3SKVS7X1J` as the `id` path parameter. The API will return:\n```json\n{\n \"authorization_model\":{\n \"id\":\"01G5JAVJ41T49E9TT3SKVS7X1J\",\n \"type_definitions\":[\n {\n \"type\":\"user\"\n },\n {\n \"type\":\"document\",\n \"relations\":{\n \"reader\":{\n \"union\":{\n \"child\":[\n {\n \"this\":{}\n },\n {\n \"computedUserset\":{\n \"object\":\"\",\n \"relation\":\"writer\"\n }\n }\n ]\n }\n },\n \"writer\":{\n \"this\":{}\n }\n }\n }\n ]\n }\n}\n```\nIn the above example, there are 2 types (`user` and `document`). The `document` type has 2 relations (`writer` and `reader`).", - "operationId": "ReadAuthorizationModel", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReadAuthorizationModelResponse" + "stores": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Store" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" + } + }, + "required": [ + "stores", + "continuation_token" + ], + "type": "object" + }, + "ListUsersBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." } - } + ] }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "context": { + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation.", + "type": "object" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" + "contextual_tuples": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" } - } - } + ] + }, + "maxItems": 100, + "type": "array" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } + "object": { + "allOf": [ + { + "$ref": "#/components/schemas/Object" + }, + { + "example": "document:example" } - } + ] }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "relation": { + "example": "reader", + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } + "user_filters": { + "description": "The type of results returned. Only accepts exactly one value.", + "example": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "group" } - } - }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" + ], + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/UserTypeFilter" + }, + { + "type": "object" } - } - } + ] + }, + "maxItems": 1, + "minItems": 1, + "type": "array" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } + "required": [ + "object", + "relation", + "user_filters" ], - "tags": [ - "Authorization Models" - ] - } - }, - "/stores/{store_id}/batch-check": { - "post": { - "summary": "Send a list of `check` operations in a single request", - "description": "The `BatchCheck` API functions nearly identically to `Check`, but instead of checking a single user-object relationship BatchCheck accepts a list of relationships to check and returns a map containing `BatchCheckItem` response for each check it received.\n\nAn associated `correlation_id` is required for each check in the batch. This ID is used to correlate a check to the appropriate response. It is a string consisting of only alphanumeric characters or hyphens with a maximum length of 36 characters. This `correlation_id` is used to map the result of each check to the item which was checked, so it must be unique for each item in the batch. We recommend using a UUID or ULID as the `correlation_id`, but you can use whatever unique identifier you need as long as it matches this regex pattern: `^[\\w\\d-]{1,36}$`\n\nNOTE: The maximum number of checks that can be passed in the `BatchCheck` API is configurable via the [OPENFGA_MAX_CHECKS_PER_BATCH_CHECK](https://openfga.dev/docs/getting-started/setup-openfga/configuration#OPENFGA_MAX_CHECKS_PER_BATCH_CHECK) environment variable. If `BatchCheck` is called using the SDK, the SDK can split the batch check requests for you.\n\nFor more details on how `Check` functions, see the docs for `/check`.\n\n### Examples\n#### A BatchCheckRequest\n```json\n{\n \"checks\": [\n {\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n \"relation\": \"reader\",\n \"user\": \"user:anne\",\n },\n \"contextual_tuples\": {...}\n \"context\": {}\n \"correlation_id\": \"01JA8PM3QM7VBPGB8KMPK8SBD5\"\n },\n {\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n \"relation\": \"reader\",\n \"user\": \"user:bob\",\n },\n \"contextual_tuples\": {...}\n \"context\": {}\n \"correlation_id\": \"01JA8PMM6A90NV5ET0F28CYSZQ\"\n }\n ]\n}\n```\n\nBelow is a possible response to the above request. Note that the result map's keys are the `correlation_id` values from the checked items in the request:\n```json\n{\n \"result\": {\n \"01JA8PMM6A90NV5ET0F28CYSZQ\": {\n \"allowed\": false, \n \"error\": {\"message\": \"\"} \n },\n \"01JA8PM3QM7VBPGB8KMPK8SBD5\": {\n \"allowed\": true, \n \"error\": {\"message\": \"\"} \n }\n}\n```\n", - "operationId": "BatchCheck", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BatchCheckResponse" + "type": "object" + }, + "ListUsersResponse": { + "properties": { + "users": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/User" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" + } + }, + "required": [ + "users" + ], + "type": "object" + }, + "Metadata": { + "properties": { + "module": { + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "relations": { + "additionalProperties": { + "$ref": "#/components/schemas/RelationMetadata" + }, + "type": "object" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + }, + "type": "object" + }, + "Node": { + "properties": { + "difference": { + "$ref": "#/components/schemas/UsersetTree.Difference" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "intersection": { + "$ref": "#/components/schemas/Nodes" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "leaf": { + "$ref": "#/components/schemas/Leaf" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "name": { + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + "union": { + "$ref": "#/components/schemas/Nodes" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "Nodes": { + "properties": { + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Node" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" + } + }, + "required": [ + "nodes" + ], + "type": "object" + }, + "NotFoundErrorCode": { + "default": "no_not_found_error", + "enum": [ + "no_not_found_error", + "undefined_endpoint", + "store_id_not_found", + "unimplemented" + ], + "type": "string" + }, + "NullValue": { + "default": "NULL_VALUE", + "description": "`NullValue` is a singleton enumeration to represent the null value for the\n`Value` type union.\n\nThe JSON representation for `NullValue` is JSON `null`.\n\n - NULL_VALUE: Null value.", + "enum": [ + "NULL_VALUE" + ], + "type": "string" + }, + "Object": { + "description": "Object represents an OpenFGA Object.\n\nAn Object is composed of a type and identifier (e.g. 'document:1')\n\nSee https://openfga.dev/docs/concepts#what-is-an-object", + "properties": { + "id": { + "example": "0bcdf6fa-a6aa-4730-a8eb-9cf172ff16d9", + "type": "string" + }, + "type": { + "example": "document", + "type": "string" + } + }, + "required": [ + "type", + "id" + ], + "type": "object" + }, + "ObjectRelation": { + "properties": { + "object": { + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "relation": { + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "type": "object" + }, + "PageRequest": { + "properties": { + "limit": { + "format": "int64", + "title": "Maximum number of results to return (default: 50, max: 1000)", + "type": "integer" + }, + "token": { + "title": "Continuation token from previous response", + "type": "string" } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BatchCheckBody" - } - } + }, + "title": "Pagination request parameters for search operations", + "type": "object" + }, + "PageResponse": { + "properties": { + "count": { + "format": "int64", + "title": "Number of results in this page", + "type": "integer" }, - "required": true + "next_token": { + "title": "Token to retrieve next page (empty if no more results)", + "type": "string" + }, + "total": { + "format": "int64", + "title": "Total number of results (if known, otherwise 0)", + "type": "integer" + } }, - "tags": [ - "Relationship Queries" - ] - } - }, - "/stores/{store_id}/changes": { - "get": { - "summary": "Return a list of all the tuple changes", - "description": "The ReadChanges API will return a paginated list of tuple changes (additions and deletions) that occurred in a given store, sorted by ascending time. The response will include a continuation token that is used to get the next set of changes. If there are no changes after the provided continuation token, the same token will be returned in order for it to be used when new changes are recorded. If the store never had any tuples added or removed, this token will be empty.\nYou can use the `type` parameter to only get the list of tuple changes that affect objects of that type.\nWhen reading a write tuple change, if it was conditioned, the condition will be returned.\nWhen reading a delete tuple change, the condition will NOT be returned regardless of whether it was originally conditioned or not.\n", - "operationId": "ReadChanges", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReadChangesResponse" - } - } - } + "title": "Pagination response parameters", + "type": "object" + }, + "PathUnknownErrorMessageResponse": { + "example": { + "code": "undefined_endpoint", + "message": "Endpoint not enabled" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/NotFoundErrorCode" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + "message": { + "type": "string" + } + }, + "type": "object" + }, + "ReadAssertionsResponse": { + "properties": { + "assertions": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Assertion" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + } + }, + "required": [ + "authorization_model_id" + ], + "type": "object" + }, + "ReadAuthorizationModelResponse": { + "properties": { + "authorization_model": { + "$ref": "#/components/schemas/AuthorizationModel" + } + }, + "type": "object" + }, + "ReadAuthorizationModelsResponse": { + "properties": { + "authorization_models": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/AuthorizationModel" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } + "continuation_token": { + "description": "The continuation token will be empty if there are no more models.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" + } + }, + "required": [ + "authorization_models" + ], + "type": "object" + }, + "ReadBody": { + "properties": { + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." } - } + ] }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "continuation_token": { + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "page_size": { + "example": 50, + "format": "int32", + "maximum": 100, + "minimum": 1, + "type": "integer" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + "tuple_key": { + "$ref": "#/components/schemas/ReadRequestTupleKey" + } + }, + "type": "object" + }, + "ReadChangesResponse": { + "properties": { + "changes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleChange" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "continuation_token": { + "description": "The continuation token will be identical if there are no new changes.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "type", - "in": "query", - "required": false, - "schema": { - "type": "string" - } - }, - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "format": "int32" - } + "required": [ + "changes" + ], + "type": "object" + }, + "ReadRequestTupleKey": { + "properties": { + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" }, - { - "name": "continuation_token", - "in": "query", - "required": false, - "schema": { - "type": "string" - } + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" }, - { - "name": "start_time", - "description": "Start date and time of changes to read.\nFormat: ISO 8601 timestamp (e.g., 2022-01-01T00:00:00Z)\nIf a continuation_token is provided along side start_time, the continuation_token will take precedence over start_time.", - "in": "query", - "required": false, - "schema": { - "type": "string", - "format": "date-time" - } + "user": { + "example": "user:anne", + "maxLength": 512, + "type": "string" } - ], - "tags": [ - "Relationship Tuples" - ] - } - }, - "/stores/{store_id}/check": { - "post": { - "summary": "Check whether a user is authorized to access an object", - "description": "The Check API returns whether a given user has a relationship with a given object in a given store.\nThe `user` field of the request can be a specific target, such as `user:anne`, or a userset (set of users) such as `group:marketing#member` or a type-bound public access `user:*`.\nTo arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nA `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`.\nYou may also provide an `authorization_model_id` in the body. This will be used to assert that the input `tuple_key` is valid for the model specified. If not specified, the assertion will be made against the latest authorization model ID. It is strongly recommended to specify authorization model id for better performance.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nBy default, the Check API caches results for a short time to optimize performance. You may specify a value of `HIGHER_CONSISTENCY` for the optional `consistency` parameter in the body to inform the server that higher conisistency is preferred at the expense of increased latency. Consideration should be given to the increased latency if requesting higher consistency.\nThe response will return whether the relationship exists in the field `allowed`.\n\nSome exceptions apply, but in general, if a Check API responds with `{allowed: true}`, then you can expect the equivalent ListObjects query to return the object, and viceversa. \nFor example, if `Check(user:anne, reader, document:2021-budget)` responds with `{allowed: true}`, then `ListObjects(user:anne, reader, document)` may include `document:2021-budget` in the response.\n## Examples\n### Querying with contextual tuples\nIn order to check if user `user:anne` of type `user` has a `reader` relationship with object `document:2021-budget` given the following contextual tuple\n```json\n{\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"time_slot:office_hours\"\n}\n```\nthe Check API can be used with the following request body:\n```json\n{\n \"tuple_key\": {\n \"user\": \"user:anne\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"time_slot:office_hours\"\n }\n ]\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\n### Querying usersets\nSome Checks will always return `true`, even without any tuples. For example, for the following authorization model\n```python\nmodel\n schema 1.1\ntype user\ntype document\n relations\n define reader: [user]\n```\nthe following query\n```json\n{\n \"tuple_key\": {\n \"user\": \"document:2021-budget#reader\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n }\n}\n```\nwill always return `{ \"allowed\": true }`. This is because usersets are self-defining: the userset `document:2021-budget#reader` will always have the `reader` relation with `document:2021-budget`.\n### Querying usersets with difference in the model\nA Check for a userset can yield results that must be treated carefully if the model involves difference. For example, for the following authorization model\n```python\nmodel\n schema 1.1\ntype user\ntype group\n relations\n define member: [user]\ntype document\n relations\n define blocked: [user]\n define reader: [group#member] but not blocked\n```\nthe following query\n```json\n{\n \"tuple_key\": {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"group:finance\"\n },\n {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n {\n \"user\": \"user:anne\",\n \"relation\": \"blocked\",\n \"object\": \"document:2021-budget\"\n }\n ]\n },\n}\n```\nwill return `{ \"allowed\": true }`, even though a specific user of the userset `group:finance#member` does not have the `reader` relationship with the given object.\n### Requesting higher consistency\nBy default, the Check API caches results for a short time to optimize performance. You may request higher consistency to inform the server that higher consistency should be preferred at the expense of increased latency. Care should be taken when requesting higher consistency due to the increased latency.\n```json\n{\n \"tuple_key\": {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"consistency\": \"HIGHER_CONSISTENCY\"\n}\n```\n", - "operationId": "Check", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CheckResponse" - } - } - } + }, + "type": "object" + }, + "ReadResponse": { + "properties": { + "continuation_token": { + "description": "The continuation token will be empty if there are no more tuples.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + "tuples": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Tuple" + }, + { + "type": "object" } - } - } - }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" + ] + }, + "type": "array" + } + }, + "required": [ + "tuples", + "continuation_token" + ], + "type": "object" + }, + "RelationMetadata": { + "properties": { + "directly_related_user_types": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/RelationReference" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "module": { + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + }, + "type": "object" + }, + "RelationReference": { + "description": "RelationReference represents a relation of a particular object type (e.g. 'document#viewer').", + "properties": { + "condition": { + "description": "The name of a condition that is enforced over the allowed relation.", + "type": "string" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "relation": { + "example": "member", + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "type": { + "example": "group", + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "wildcard": { + "$ref": "#/components/schemas/Wildcard" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "required": [ + "type" + ], + "type": "object" + }, + "RelationshipCondition": { + "properties": { + "context": { + "description": "Additional context/data to persist along with the condition.\nThe keys must match the parameters defined by the condition, and the value types must\nmatch the parameter type definitions.", + "type": "object" + }, + "name": { + "description": "A reference (by name) of the relationship condition defined in the authorization model.", + "example": "condition1", + "maxLength": 256, + "type": "string" } + }, + "required": [ + "name" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CheckBody" - } - } + "type": "object" + }, + "Resource": { + "properties": { + "id": { + "example": "roadmap", + "type": "string" }, - "required": true + "properties": { + "type": "object" + }, + "type": { + "example": "document", + "type": "string" + } }, - "tags": [ - "Relationship Queries" - ] - } - }, - "/stores/{store_id}/expand": { - "post": { - "summary": "Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship", - "description": "The Expand API will return all users and usersets that have certain relationship with an object in a certain store.\nThis is different from the `/stores/{store_id}/read` API in that both users and computed usersets are returned.\nBody parameters `tuple_key.object` and `tuple_key.relation` are all required.\nA `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`.\nThe response will return a tree whose leaves are the specific users and usersets. Union, intersection and difference operator are located in the intermediate nodes.\n\n## Example\nTo expand all users that have the `reader` relationship with object `document:2021-budget`, use the Expand API with the following request body\n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\",\n \"relation\": \"reader\"\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\nOpenFGA's response will be a userset tree of the users and usersets that have read access to the document.\n```json\n{\n \"tree\":{\n \"root\":{\n \"type\":\"document:2021-budget#reader\",\n \"union\":{\n \"nodes\":[\n {\n \"type\":\"document:2021-budget#reader\",\n \"leaf\":{\n \"users\":{\n \"users\":[\n \"user:bob\"\n ]\n }\n }\n },\n {\n \"type\":\"document:2021-budget#reader\",\n \"leaf\":{\n \"computed\":{\n \"userset\":\"document:2021-budget#writer\"\n }\n }\n }\n ]\n }\n }\n }\n}\n```\nThe caller can then call expand API for the `writer` relationship for the `document:2021-budget`.\n### Expand Request with Contextual Tuples\n\nGiven the model\n```python\nmodel\n schema 1.1\n\ntype user\n\ntype folder\n relations\n define owner: [user]\n\ntype document\n relations\n define parent: [folder]\n define viewer: [user] or writer\n define writer: [user] or owner from parent\n```\nand the initial tuples\n```json\n[{\n \"user\": \"user:bob\",\n \"relation\": \"owner\",\n \"object\": \"folder:1\"\n}]\n```\n\nTo expand all `writers` of `document:1` when `document:1` is put in `folder:1`, the first call could be\n\n```json\n{\n \"tuple_key\": {\n \"object\": \"document:1\",\n \"relation\": \"writer\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"folder:1\",\n \"relation\": \"parent\",\n \"object\": \"document:1\"\n }\n ]\n }\n}\n```\nthis returns:\n```json\n{\n \"tree\": {\n \"root\": {\n \"name\": \"document:1#writer\",\n \"union\": {\n \"nodes\": [\n {\n \"name\": \"document:1#writer\",\n \"leaf\": {\n \"users\": {\n \"users\": []\n }\n }\n },\n {\n \"name\": \"document:1#writer\",\n \"leaf\": {\n \"tupleToUserset\": {\n \"tupleset\": \"document:1#parent\",\n \"computed\": [\n {\n \"userset\": \"folder:1#owner\"\n }\n ]\n }\n }\n }\n ]\n }\n }\n }\n}\n```\nThis tells us that the `owner` of `folder:1` may also be a writer. So our next call could be to find the `owners` of `folder:1`\n```json\n{\n \"tuple_key\": {\n \"object\": \"folder:1\",\n \"relation\": \"owner\"\n }\n}\n```\nwhich gives\n```json\n{\n \"tree\": {\n \"root\": {\n \"name\": \"folder:1#owner\",\n \"leaf\": {\n \"users\": {\n \"users\": [\n \"user:bob\"\n ]\n }\n }\n }\n }\n}\n```\n", - "operationId": "Expand", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ExpandResponse" - } - } - } + "required": [ + "type", + "id" + ], + "type": "object" + }, + "ResourceFilter": { + "properties": { + "id": { + "description": "Optional resource id. If present in Resource Search, it is ignored per AuthZEN spec.", + "type": "string" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "properties": { + "type": "object" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "type": { + "example": "document", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "ResourceFilter is used for search operations where only type is required", + "type": "object" + }, + "ResourceSearchBody": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "context": { + "type": "object" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "page": { + "$ref": "#/components/schemas/PageRequest" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } + "resource": { + "allOf": [ + { + "$ref": "#/components/schemas/ResourceFilter" + }, + { + "title": "Filter by resource type" } - } + ] }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } + "subject": { + "$ref": "#/components/schemas/Subject" + } + }, + "required": [ + "subject", + "action", + "resource" + ], + "title": "ResourceSearch request", + "type": "object" + }, + "ResourceSearchResponse": { + "properties": { + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" } - } + ] }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" + "results": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Resource" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "type": "object" + }, + "SourceInfo": { + "properties": { + "file": { + "type": "string" } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ExpandBody" - } - } - }, - "required": true }, - "tags": [ - "Relationship Queries" - ] - } - }, - "/stores/{store_id}/list-objects": { - "post": { - "summary": "List all objects of the given type that the user has a relation with", - "description": "The ListObjects API returns a list of all the objects of the given type that the user has a relation with.\n To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nAn `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance.\nYou may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nBy default, the Check API caches results for a short time to optimize performance. You may specify a value of `HIGHER_CONSISTENCY` for the optional `consistency` parameter in the body to inform the server that higher conisistency is preferred at the expense of increased latency. Consideration should be given to the increased latency if requesting higher consistency.\nThe response will contain the related objects in an array in the \"objects\" field of the response and they will be strings in the object format `:` (e.g. \"document:roadmap\").\nThe number of objects in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first.\nThe objects given will not be sorted, and therefore two identical calls can give a given different set of objects.", - "operationId": "ListObjects", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ListObjectsResponse" - } - } - } + "type": "object" + }, + "Status": { + "properties": { + "code": { + "format": "int32", + "type": "integer" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + "details": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Any" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "message": { + "type": "string" + } + }, + "type": "object" + }, + "Store": { + "properties": { + "created_at": { + "format": "date-time", + "type": "string" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "deleted_at": { + "format": "date-time", + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "id": { + "type": "string" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "name": { + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "updated_at": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "id", + "name", + "created_at", + "updated_at" + ], + "type": "object" + }, + "StreamedListObjectsBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } + "consistency": { + "allOf": [ + { + "$ref": "#/components/schemas/ConsistencyPreference" + }, + { + "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." } - } + ] + }, + "context": { + "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation.", + "type": "object" + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + }, + "relation": { + "example": "reader", + "type": "string" + }, + "type": { + "example": "document", + "type": "string" + }, + "user": { + "example": "user:anne", + "maxLength": 512, + "minLength": 1, + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "required": [ + "type", + "relation", + "user" + ], + "type": "object" + }, + "StreamedListObjectsResponse": { + "description": "The response for a StreamedListObjects RPC.", + "properties": { + "object": { + "example": "document:roadmap", + "type": "string" } + }, + "required": [ + "object" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ListObjectsBody" - } - } + "type": "object" + }, + "Subject": { + "properties": { + "id": { + "example": "anne", + "type": "string" }, - "required": true - }, - "tags": [ - "Relationship Queries" - ] - } - }, - "/stores/{store_id}/list-users": { - "post": { - "summary": "List the users matching the provided filter who have a certain relation to a particular type.", - "description": "The ListUsers API returns a list of all the users of a specific type that have a relation to a given object.\n To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nAn `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance.\nYou may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nThe response will contain the related users in an array in the \"users\" field of the response. These results may include specific objects, usersets \nor type-bound public access. Each of these types of results is encoded in its own type and not represented as a string.In cases where a type-bound public access result is returned (e.g. `user:*`), it cannot be inferred that all subjects\nof that type have a relation to the object; it is possible that negations exist and checks should still be queried\non individual subjects to ensure access to that document.The number of users in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_USERS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_USERS_MAX_RESULTS, whichever is hit first.\nThe returned users will not be sorted, and therefore two identical calls may yield different sets of users.", - "operationId": "ListUsers", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ListUsersResponse" - } - } - } + "properties": { + "type": "object" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" - } - } - } + "type": { + "example": "user", + "type": "string" + } + }, + "required": [ + "type", + "id" + ], + "type": "object" + }, + "SubjectFilter": { + "properties": { + "id": { + "description": "Optional subject id. If present in Subject Search, it is ignored per AuthZEN spec.", + "type": "string" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "properties": { + "type": "object" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "type": { + "example": "user", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "SubjectFilter is used for search operations where only type is required", + "type": "object" + }, + "SubjectSearchBody": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "context": { + "type": "object" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "page": { + "$ref": "#/components/schemas/PageRequest" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "resource": { + "$ref": "#/components/schemas/Resource" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } + "subject": { + "allOf": [ + { + "$ref": "#/components/schemas/SubjectFilter" + }, + { + "description": "REQUIRED by AuthZEN Subject Search. Subject `id` may be provided but is ignored." } - } + ] } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } + "required": [ + "resource", + "action", + "subject" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ListUsersBody" - } - } - }, - "required": true - }, - "tags": [ - "Relationship Queries" - ] - } - }, - "/stores/{store_id}/read": { - "post": { - "summary": "Get tuples from the store that matches a query, without following userset rewrite rules", - "description": "The Read API will return the tuples for a certain store that match a query filter specified in the body of the request. \nThe API doesn't guarantee order by any field. \nIt is different from the `/stores/{store_id}/expand` API in that it only returns relationship tuples that are stored in the system and satisfy the query. \nIn the body:\n1. `tuple_key` is optional. If not specified, it will return all tuples in the store.\n2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can be a full object (e.g., `type:object_id`) or type only (e.g., `type:`).\n3. `tuple_key.user` is mandatory if tuple_key is specified in the case the `tuple_key.object` is a type only. If tuple_key.user is specified, it needs to be a full object (e.g., `type:user_id`).\n## Examples\n### Query for all objects in a type definition\nTo query for all objects that `user:bob` has `reader` relationship in the `document` type definition, call read API with body of\n```json\n{\n \"tuple_key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:\"\n }\n}\n```\nThe API will return tuples and a continuation token, something like\n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `user:bob` has a `reader` relationship with 1 document `document:2021-budget`. Note that this API, unlike the List Objects API, does not evaluate the tuples in the store.\nThe continuation token will be empty if there are no more tuples to query.\n### Query for all stored relationship tuples that have a particular relation and object\nTo query for all users that have `reader` relationship with `document:2021-budget`, call read API with body of \n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\",\n \"relation\": \"reader\"\n }\n}\n```\nThe API will return something like \n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `document:2021-budget` has 1 `reader` (`user:bob`). Note that, even if the model said that all `writers` are also `readers`, the API will not return writers such as `user:anne` because it only returns tuples and does not evaluate them.\n### Query for all users with all relationships for a particular document\nTo query for all users that have any relationship with `document:2021-budget`, call read API with body of \n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n }\n}\n```\nThe API will return something like \n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:anne\",\n \"relation\": \"writer\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-05T13:42:12.356Z\"\n },\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1 `writer` (`user:anne`).\n", - "operationId": "Read", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReadResponse" - } + "title": "SubjectSearch request", + "type": "object" + }, + "SubjectSearchResponse": { + "properties": { + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" } - } + ] }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + "results": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Subject" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" + } + }, + "type": "object" + }, + "Tuple": { + "properties": { + "key": { + "$ref": "#/components/schemas/TupleKey" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "timestamp": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "key", + "timestamp" + ], + "type": "object" + }, + "TupleChange": { + "properties": { + "operation": { + "$ref": "#/components/schemas/TupleOperation" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "timestamp": { + "format": "date-time", + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "tuple_key": { + "$ref": "#/components/schemas/TupleKey" + } + }, + "required": [ + "tuple_key", + "operation", + "timestamp" + ], + "type": "object" + }, + "TupleKey": { + "properties": { + "condition": { + "$ref": "#/components/schemas/RelationshipCondition" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "user": { + "example": "user:anne", + "maxLength": 512, + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "required": [ + "user", + "relation", + "object" + ], + "type": "object" + }, + "TupleKeyWithoutCondition": { + "properties": { + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" + }, + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" + }, + "user": { + "example": "user:anne", + "maxLength": 512, + "type": "string" } + }, + "required": [ + "user", + "relation", + "object" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReadBody" + "type": "object" + }, + "TupleOperation": { + "default": "TUPLE_OPERATION_WRITE", + "enum": [ + "TUPLE_OPERATION_WRITE", + "TUPLE_OPERATION_DELETE" + ], + "title": "buf:lint:ignore ENUM_ZERO_VALUE_SUFFIX", + "type": "string" + }, + "TypeDefinition": { + "properties": { + "metadata": { + "allOf": [ + { + "$ref": "#/components/schemas/Metadata" + }, + { + "description": "A map whose keys are the name of the relation and whose value is the Metadata for that relation.\nIt also holds information around the module name and source file if this model was constructed\nfrom a modular model." } - } + ] }, - "required": true - }, - "tags": [ - "Relationship Tuples" - ] - } - }, - "/stores/{store_id}/streamed-list-objects": { - "post": { - "summary": "Stream all objects of the given type that the user has a relation with", - "description": "The Streamed ListObjects API is very similar to the the ListObjects API, with two differences: \n1. Instead of collecting all objects before returning a response, it streams them to the client as they are collected. \n2. The number of results returned is only limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE. \n", - "operationId": "StreamedListObjects", - "responses": { - "200": { - "description": "A successful response.(streaming responses)", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "result": { - "$ref": "#/components/schemas/StreamedListObjectsResponse" + "relations": { + "additionalProperties": { + "$ref": "#/components/schemas/Userset" + }, + "example": { + "reader": { + "union": { + "child": [ + { + "this": {} }, - "error": { - "$ref": "#/components/schemas/Status" + { + "computedUserset": { + "object": "", + "relation": "writer" + } } - }, - "title": "Stream result of StreamedListObjectsResponse" - } - } - } - }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + ] } + }, + "writer": { + "this": {} } - } + }, + "type": "object" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "type": { + "example": "document", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "TypeName": { + "default": "TYPE_NAME_UNSPECIFIED", + "enum": [ + "TYPE_NAME_UNSPECIFIED", + "TYPE_NAME_ANY", + "TYPE_NAME_BOOL", + "TYPE_NAME_STRING", + "TYPE_NAME_INT", + "TYPE_NAME_UINT", + "TYPE_NAME_DOUBLE", + "TYPE_NAME_DURATION", + "TYPE_NAME_TIMESTAMP", + "TYPE_NAME_MAP", + "TYPE_NAME_LIST", + "TYPE_NAME_IPADDRESS" + ], + "type": "string" + }, + "TypedWildcard": { + "description": "Type bound public access.\n\nNormally represented using the `:*` syntax\n\n`employee:*` represents every object of type `employee`, including those not currently present in the system\n\nSee https://openfga.dev/docs/concepts#what-is-type-bound-public-access", + "properties": { + "type": { + "example": "employee", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "UnauthenticatedResponse": { + "example": { + "code": "unauthenticated", + "message": "unauthenticated" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/ErrorCode" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "message": { + "type": "string" + } + }, + "type": "object" + }, + "UnprocessableContentErrorCode": { + "default": "no_throttled_error_code", + "enum": [ + "no_throttled_error_code", + "throttled_timeout_error" + ], + "type": "string" + }, + "UnprocessableContentMessageResponse": { + "example": { + "code": "throttled_timeout_error", + "message": "timeout due to throttling on complex request" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/UnprocessableContentErrorCode" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" - } - } - } + "message": { + "type": "string" + } + }, + "type": "object" + }, + "User": { + "description": "User.\n\nRepresents any possible value for a user (subject or principal). Can be a:\n- Specific user object e.g.: 'user:will', 'folder:marketing', 'org:contoso', ...)\n- Specific userset (e.g. 'group:engineering#member')\n- Public-typed wildcard (e.g. 'user:*')\n\nSee https://openfga.dev/docs/concepts#what-is-a-user", + "properties": { + "object": { + "$ref": "#/components/schemas/Object" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" - } - } - } + "userset": { + "$ref": "#/components/schemas/UsersetUser" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "wildcard": { + "$ref": "#/components/schemas/TypedWildcard" + } + }, + "type": "object" + }, + "UserTypeFilter": { + "properties": { + "relation": { + "example": "member", + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" - } - } - } + "type": { + "example": "group", + "type": "string" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { + "required": [ + "type" + ], + "type": "object" + }, + "Users": { + "properties": { + "users": { + "items": { "type": "string" - } + }, + "type": "array" } + }, + "required": [ + "users" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/StreamedListObjectsBody" - } - } + "type": "object" + }, + "Userset": { + "properties": { + "computedUserset": { + "$ref": "#/components/schemas/ObjectRelation" }, - "required": true + "difference": { + "$ref": "#/components/schemas/v1.Difference" + }, + "intersection": { + "$ref": "#/components/schemas/Usersets" + }, + "this": { + "$ref": "#/components/schemas/DirectUserset" + }, + "tupleToUserset": { + "$ref": "#/components/schemas/v1.TupleToUserset" + }, + "union": { + "$ref": "#/components/schemas/Usersets" + } }, - "tags": [ - "Relationship Queries" - ] - } - }, - "/stores/{store_id}/write": { - "post": { - "summary": "Add or delete tuples from the store", - "description": "The Write API will transactionally update the tuples for a certain store. Tuples and type definitions allow OpenFGA to determine whether a relationship exists between an object and an user.\nIn the body, `writes` adds new tuples and `deletes` removes existing tuples. When deleting a tuple, any `condition` specified with it is ignored.\nThe API is not idempotent by default: if, later on, you try to add the same tuple key (even if the `condition` is different), or if you try to delete a non-existing tuple, it will throw an error.\nTo allow writes when an identical tuple already exists in the database, set `\"on_duplicate\": \"ignore\"` on the `writes` object.\nTo allow deletes when a tuple was already removed from the database, set `\"on_missing\": \"ignore\"` on the `deletes` object.\nIf a Write request contains both idempotent (ignore) and non-idempotent (error) operations, the most restrictive action (error) will take precedence. If a condition fails for a sub-request with an error flag, the entire transaction will be rolled back. This gives developers explicit control over the atomicity of the requests.\nThe API will not allow you to write tuples such as `document:2021-budget#viewer@document:2021-budget#viewer`, because they are implicit.\nAn `authorization_model_id` may be specified in the body. If it is, it will be used to assert that each written tuple (not deleted) is valid for the model specified. If it is not specified, the latest authorization model ID will be used.\n## Example\n### Adding relationships\nTo add `user:anne` as a `writer` for `document:2021-budget`, call write API with the following \n```json\n{\n \"writes\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"writer\",\n \"object\": \"document:2021-budget\"\n }\n ],\n \"on_duplicate\": \"ignore\"\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\n### Removing relationships\nTo remove `user:bob` as a `reader` for `document:2021-budget`, call write API with the following \n```json\n{\n \"deletes\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n }\n ],\n \"on_missing\": \"ignore\"\n }\n}\n```\n", - "operationId": "Write", - "responses": { - "200": { - "description": "A successful response.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/WriteResponse" - } - } - } + "type": "object" + }, + "UsersetTree": { + "description": "A UsersetTree contains the result of an Expansion.", + "properties": { + "root": { + "$ref": "#/components/schemas/Node" + } + }, + "type": "object" + }, + "UsersetTree.Difference": { + "properties": { + "base": { + "$ref": "#/components/schemas/Node" }, - "400": { - "description": "Request failed due to invalid input.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ValidationErrorMessageResponse" + "subtract": { + "$ref": "#/components/schemas/Node" + } + }, + "required": [ + "base", + "subtract" + ], + "type": "object" + }, + "UsersetTree.TupleToUserset": { + "properties": { + "computed": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Computed" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" }, - "401": { - "description": "Not authenticated.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnauthenticatedResponse" - } - } - } + "tupleset": { + "type": "string" + } + }, + "required": [ + "tupleset", + "computed" + ], + "type": "object" + }, + "UsersetUser": { + "description": "Userset.\n\nA set or group of users, represented in the `:#` format\n\n`group:fga#member` represents all members of group FGA, not to be confused by `group:fga` which represents the group itself as a specific object.\n\nSee: https://openfga.dev/docs/modeling/building-blocks/usersets#what-is-a-userset", + "properties": { + "id": { + "example": "fga", + "type": "string" }, - "403": { - "description": "Forbidden.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForbiddenResponse" - } - } - } + "relation": { + "example": "member", + "type": "string" }, - "404": { - "description": "Request failed due to incorrect path.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + "type": { + "example": "group", + "type": "string" + } + }, + "required": [ + "type", + "id", + "relation" + ], + "type": "object" + }, + "Usersets": { + "properties": { + "child": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Userset" + }, + { + "type": "object" } - } - } + ] + }, + "type": "array" + } + }, + "required": [ + "child" + ], + "type": "object" + }, + "ValidationErrorMessageResponse": { + "example": { + "code": "validation_error", + "message": "Generic validation error" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/ErrorCode" }, - "409": { - "description": "Request was aborted due a transaction conflict.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AbortedMessageResponse" + "message": { + "type": "string" + } + }, + "type": "object" + }, + "Wildcard": { + "type": "object" + }, + "WriteAssertionsBody": { + "properties": { + "assertions": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Assertion" + }, + { + "type": "object" } - } - } + ] + }, + "maxItems": 100, + "type": "array" + } + }, + "required": [ + "assertions" + ], + "type": "object" + }, + "WriteAssertionsResponse": { + "type": "object" + }, + "WriteAuthorizationModelBody": { + "properties": { + "conditions": { + "additionalProperties": { + "$ref": "#/components/schemas/Condition" + }, + "type": "object" }, - "422": { - "description": "Request timed out due to excessive request throttling.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UnprocessableContentMessageResponse" - } - } - } + "schema_version": { + "type": "string" }, - "500": { - "description": "Request failed due to internal server error.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InternalErrorMessageResponse" + "type_definitions": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TypeDefinition" + }, + { + "type": "object" } - } - } + ] + }, + "minItems": 1, + "type": "array" } }, - "parameters": [ - { - "name": "store_id", - "in": "path", - "required": true, - "schema": { - "type": "string" - } + "required": [ + "type_definitions", + "schema_version" + ], + "type": "object" + }, + "WriteAuthorizationModelResponse": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" } + }, + "required": [ + "authorization_model_id" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/WriteBody" - } - } + "type": "object" + }, + "WriteBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" }, - "required": true - }, - "tags": [ - "Relationship Tuples" - ] - } - } - }, - "components": { - "schemas": { - "AbortedMessageResponse": { - "type": "object", - "example": { - "code": "10", - "message": "transaction conflict" + "deletes": { + "$ref": "#/components/schemas/WriteRequestDeletes" + }, + "writes": { + "$ref": "#/components/schemas/WriteRequestWrites" + } }, + "type": "object" + }, + "WriteRequestDeletes": { "properties": { - "code": { + "on_missing": { + "default": "error", + "description": "On 'error', the API returns an error when deleting a tuple that does not exist. On 'ignore', deletes of non-existent tuples are treated as no-ops.", + "enum": [ + "error", + "ignore" + ], + "example": "ignore", "type": "string" }, - "message": { + "tuple_keys": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKeyWithoutCondition" + }, + { + "type": "object" + } + ] + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "tuple_keys" + ], + "type": "object" + }, + "WriteRequestWrites": { + "properties": { + "on_duplicate": { + "default": "error", + "description": "On 'error' ( or unspecified ), the API returns an error if an identical tuple already exists. On 'ignore', identical writes are treated as no-ops (matching on user, relation, object, and RelationshipCondition).", + "enum": [ + "error", + "ignore" + ], + "example": "ignore", "type": "string" + }, + "tuple_keys": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "minItems": 1, + "type": "array" } - } + }, + "required": [ + "tuple_keys" + ], + "type": "object" }, - "Action": { - "type": "object", + "WriteResponse": { + "type": "object" + }, + "v1.Difference": { "properties": { - "name": { - "type": "string", - "example": "can_read" + "base": { + "$ref": "#/components/schemas/Userset" }, - "properties": { - "type": "object" + "subtract": { + "$ref": "#/components/schemas/Userset" } }, "required": [ - "name" - ] + "base", + "subtract" + ], + "type": "object" }, - "ActionSearchBody": { - "type": "object", + "v1.TupleToUserset": { "properties": { - "subject": { - "$ref": "#/components/schemas/Subject" + "computedUserset": { + "$ref": "#/components/schemas/ObjectRelation" + }, + "tupleset": { + "allOf": [ + { + "$ref": "#/components/schemas/ObjectRelation" + }, + { + "title": "The target object/relation" + } + ] + } + }, + "required": [ + "tupleset", + "computedUserset" + ], + "type": "object" + } + } + }, + "info": { + "contact": { + "email": "community@openfga.dev", + "name": "OpenFGA", + "url": "https://openfga.dev" + }, + "description": "A high performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar.", + "license": { + "name": "Apache-2.0", + "url": "https://github.com/openfga/openfga/blob/main/LICENSE" + }, + "title": "OpenFGA", + "version": "1.x" + }, + "openapi": "3.0.3", + "paths": { + "/.well-known/authzen-configuration/{store_id}": { + "get": { + "description": "[Experimental] The GetConfiguration API returns metadata about the Policy Decision Point (PDP) including its name, version, supported endpoints, and capabilities. This endpoint follows the AuthZEN specification for PDP discovery.\n\nFollowing the AuthZEN spec's multi-tenant pattern, OpenFGA provides a per-store discovery endpoint at `/.well-known/authzen-configuration/{store_id}`. This returns absolute endpoint URLs specific to that store.\n\n## Example Response\n```json\n{\n \"policy_decision_point\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV\",\n \"access_evaluation_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/evaluation\",\n \"access_evaluations_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/evaluations\",\n \"search_subject_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/subject\",\n \"search_resource_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/resource\",\n \"search_action_endpoint\": \"https://example.com/stores/01ARZ3NDEKTSV4RRFFQ69G5FAV/access/v1/search/action\"\n}\n```\n", + "operationId": "GetConfiguration", + "parameters": [ + { + "description": "The store ID for which to retrieve configuration.\nFollowing the AuthZEN spec's multi-tenant pattern, each store has its own discovery endpoint.", + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetConfigurationResponse" + } + } + }, + "description": "A successful response." }, - "resource": { - "$ref": "#/components/schemas/Resource" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "context": { - "type": "object" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "page": { - "$ref": "#/components/schemas/PageRequest" - } - }, - "title": "ActionSearch request", - "required": [ - "subject", - "resource" - ] - }, - "ActionSearchResponse": { - "type": "object", - "properties": { - "results": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Action" - }, - { - "type": "object" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" } - ] - } + } + }, + "description": "Forbidden." }, - "page": { - "allOf": [ - { - "$ref": "#/components/schemas/PageResponse" - }, - { - "title": "Optional per AuthZEN spec - omit if pagination not supported" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } } - ] - } - } - }, - "Any": { - "type": "object", - "properties": { - "@type": { - "type": "string" - } - }, - "additionalProperties": {} - }, - "Assertion": { - "type": "object", - "properties": { - "tuple_key": { - "$ref": "#/components/schemas/AssertionTupleKey" + }, + "description": "Request failed due to incorrect path." }, - "expectation": { - "type": "boolean" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "contextual_tuples": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TupleKey" - }, - { - "type": "object" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" } - ] + } }, - "maxItems": 20 + "description": "Request timed out due to excessive request throttling." }, - "context": { - "type": "object", - "example": { - "view_count": 100 + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } }, - "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + "description": "Request failed due to internal server error." } }, - "required": [ - "tuple_key", - "expectation" + "summary": "[Experimental] Get AuthZEN PDP configuration and capabilities", + "tags": [ + "AuthZenService" ] - }, - "AssertionTupleKey": { - "type": "object", - "properties": { - "object": { - "type": "string", - "example": "document:2021-budget", - "maxLength": 256 + } + }, + "/stores": { + "get": { + "description": "Returns a paginated list of OpenFGA stores and a continuation token to get additional stores.\nThe continuation token will be empty if there are no more stores.\n", + "operationId": "ListStores", + "parameters": [ + { + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "format": "int32", + "type": "integer" + } }, - "relation": { - "type": "string", - "example": "reader", - "maxLength": 50 + { + "in": "query", + "name": "continuation_token", + "required": false, + "schema": { + "type": "string" + } }, - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512 + { + "description": "The name parameter instructs the API to only include results that match that name.Multiple results may be returned. Only exact matches will be returned; substring matches and regexes will not be evaluated", + "in": "query", + "name": "name", + "required": false, + "schema": { + "type": "string" + } } - }, - "required": [ - "object", - "relation", - "user" - ] - }, - "AuthErrorCode": { - "type": "string", - "enum": [ - "no_auth_error", - "auth_failed_invalid_subject", - "auth_failed_invalid_audience", - "auth_failed_invalid_issuer", - "invalid_claims", - "auth_failed_invalid_bearer_token", - "bearer_token_missing", - "unauthenticated", - "forbidden" ], - "default": "no_auth_error" - }, - "AuthorizationModel": { - "type": "object", - "properties": { - "id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListStoresResponse" + } + } + }, + "description": "A successful response." }, - "schema_version": { - "type": "string" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "type_definitions": { - "type": "array", - "example": [ - { - "type": "user" - }, - { - "type": "document", - "relations": { - "reader": { - "union": { - "child": [ - { - "this": {} - }, - { - "computedUserset": { - "object": "", - "relation": "writer" - } - } - ] - } - }, - "writer": { - "this": {} - } - }, - "metadata": { - "relations": { - "reader": { - "directly_related_user_types": [ - { - "type": "user" - } - ] - }, - "writer": { - "directly_related_user_types": [ - { - "type": "user" - } - ] - } - } + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" } } - ], - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TypeDefinition" - }, - { - "type": "object" + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" } - ] - } + } + }, + "description": "Request failed due to incorrect path." }, - "conditions": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/Condition" - } - } - }, - "required": [ - "id", - "schema_version", - "type_definitions" - ] - }, - "BatchCheckBody": { - "type": "object", - "properties": { - "checks": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/BatchCheckItem" - }, - { - "type": "object" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" } - ] + } }, - "minItems": 1 + "description": "Request was aborted due a transaction conflict." }, - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "consistency": { - "$ref": "#/components/schemas/ConsistencyPreference" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "checks" + "summary": "List all stores", + "tags": [ + "Stores" ] }, - "BatchCheckItem": { - "type": "object", - "properties": { - "tuple_key": { - "$ref": "#/components/schemas/CheckRequestTupleKey" + "post": { + "description": "Create a unique OpenFGA store which will be used to store authorization models and relationship tuples.", + "operationId": "CreateStore", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateStoreRequest" + } + } }, - "contextual_tuples": { - "$ref": "#/components/schemas/ContextualTupleKeys" + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateStoreResponse" + } + } + }, + "description": "A successful response." }, - "context": { - "type": "object" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "correlation_id": { - "type": "string", - "example": "1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc", - "description": "correlation_id must be a string containing only letters, numbers, or hyphens, with length ≤ 36 characters." + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "tuple_key", - "correlation_id" + "summary": "Create a store", + "tags": [ + "Stores" ] - }, - "BatchCheckResponse": { - "type": "object", - "properties": { - "result": { - "type": "object", - "example": { - "1cd93d8c-8e45-43c6-9a15-cbb3c7f394bc": { - "allowed": true, - "error": { - "message": "" + } + }, + "/stores/{store_id}": { + "delete": { + "description": "Delete an OpenFGA store. This does not delete the data associated with the store, like tuples or authorization models.", + "operationId": "DeleteStore", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "A successful response." + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" } } }, - "additionalProperties": { - "$ref": "#/components/schemas/BatchCheckSingleResult" - }, - "description": "map keys are the correlation_id values from the BatchCheckItems in the request" - } - } - }, - "BatchCheckSingleResult": { - "type": "object", - "properties": { - "allowed": { - "type": "boolean" + "description": "Request failed due to invalid input." }, - "error": { - "$ref": "#/components/schemas/CheckError" - } - } - }, - "CheckBody": { - "type": "object", - "properties": { - "tuple_key": { - "$ref": "#/components/schemas/CheckRequestTupleKey" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "contextual_tuples": { - "$ref": "#/components/schemas/ContextualTupleKeys" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "trace": { - "type": "boolean", - "example": false, - "description": "Defaults to false. Making it true has performance implications.", - "readOnly": true + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "context": { - "type": "object", - "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "consistency": { - "allOf": [ - { - "$ref": "#/components/schemas/ConsistencyPreference" - }, - { - "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } } - ] + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "tuple_key" + "summary": "Delete a store", + "tags": [ + "Stores" ] }, - "CheckError": { - "type": "object", - "properties": { - "input_error": { - "$ref": "#/components/schemas/ErrorCode" - }, - "internal_error": { - "$ref": "#/components/schemas/InternalErrorCode" - }, - "message": { - "type": "string" + "get": { + "description": "Returns an OpenFGA store by its identifier", + "operationId": "GetStore", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } - } - }, - "CheckRequestTupleKey": { - "type": "object", - "properties": { - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512 - }, - "relation": { - "type": "string", - "example": "reader", - "maxLength": 50 + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetStoreResponse" + } + } + }, + "description": "A successful response." }, - "object": { - "type": "string", - "example": "document:2021-budget", - "maxLength": 256 - } - }, - "required": [ - "user", - "relation", - "object" - ] - }, - "CheckResponse": { - "type": "object", - "properties": { - "allowed": { - "type": "boolean", - "example": true + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "resolution": { - "type": "string", - "description": "For internal use only." - } - } - }, - "Computed": { - "type": "object", - "properties": { - "userset": { - "type": "string" - } - }, - "required": [ - "userset" - ] - }, - "Condition": { - "type": "object", - "properties": { - "name": { - "type": "string", - "title": "A unique name for the condition" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "expression": { - "type": "string", - "description": "A Google CEL expression, expressed as a string." + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "parameters": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/ConditionParamTypeRef" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } }, - "description": "A map of parameter names to the parameter's defined type reference." + "description": "Request failed due to incorrect path." }, - "metadata": { - "$ref": "#/components/schemas/ConditionMetadata" - } - }, - "required": [ - "name", - "expression" - ] - }, - "ConditionMetadata": { - "type": "object", - "properties": { - "module": { - "type": "string" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "source_info": { - "$ref": "#/components/schemas/SourceInfo" - } - } - }, - "ConditionParamTypeRef": { - "type": "object", - "properties": { - "type_name": { - "$ref": "#/components/schemas/TypeName" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "generic_types": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/ConditionParamTypeRef" - }, - { - "type": "object" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" } - ] - } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "type_name" + "summary": "Get a store", + "tags": [ + "Stores" ] - }, - "ConsistencyPreference": { - "type": "string", - "enum": [ - "UNSPECIFIED", - "MINIMIZE_LATENCY", - "HIGHER_CONSISTENCY" + } + }, + "/stores/{store_id}/access/v1/evaluation": { + "post": { + "description": "[Experimental] The Evaluation API determines whether a subject is authorized to perform an action on a resource. This endpoint implements the AuthZEN Access Evaluation API specification.\n\n## Request Structure\nThe request requires three components:\n- **subject**: The entity requesting access (e.g., a user or service)\n- **action**: The operation being performed (maps to a relation in the authorization model)\n- **resource**: The object being accessed\n\nEach component has a `type` and `id` field, and may include optional `properties` for ABAC (Attribute-Based Access Control) conditions.\n\n## Response\nThe response contains a `decision` field (boolean) indicating whether access is permitted, and an optional `context` object with additional information such as the evaluation ID or error details.\n\n## ABAC Support\nProperties on subject, action, and resource are automatically merged into the evaluation context with prefixes:\n- Subject properties: `subject_`\n- Resource properties: `resource_`\n- Action properties: `action_`\n\nThese merged properties can be used in conditions defined in your authorization model.\n\n## Examples\n### Basic authorization check\nCheck if user Anne can read a document:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"}\n}\n```\nResponse when authorized:\n```json\n{\n \"decision\": true\n}\n```\n### Using properties for ABAC\nCheck access with subject and resource attributes:\n```json\n{\n \"subject\": {\n \"type\": \"user\",\n \"id\": \"anne\",\n \"properties\": {\"department\": \"engineering\", \"clearance_level\": 3}\n },\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\n \"type\": \"document\",\n \"id\": \"secret-project\",\n \"properties\": {\"classification\": \"confidential\", \"required_clearance\": 2}\n }\n}\n```\n### Using request context\nProvide additional context for time-based or environmental conditions:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"action\": {\"name\": \"can_access\"},\n \"resource\": {\"type\": \"system\", \"id\": \"production\"},\n \"context\": {\n \"current_time\": \"2024-01-15T14:30:00Z\",\n \"ip_address\": \"192.168.1.100\",\n \"is_vpn_connected\": true\n }\n}\n```\n### Specifying authorization model\nPin the evaluation to a specific authorization model version using the `Openfga-Authorization-Model-Id` header:\n```\nPOST /stores/{store_id}/access/v1/evaluation\nOpenfga-Authorization-Model-Id: 01G50QVV17PECNVAHX1GG4Y5NC\n\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_write\"},\n \"resource\": {\"type\": \"document\", \"id\": \"budget-2024\"}\n}\n```\n", + "operationId": "Evaluation", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } ], - "default": "UNSPECIFIED", - "description": "Controls the consistency preferences when calling the query APIs.\n\n - UNSPECIFIED: Default if not set. Behavior will be the same as MINIMIZE_LATENCY.\n - MINIMIZE_LATENCY: Minimize latency at the potential expense of lower consistency.\n - HIGHER_CONSISTENCY: Prefer higher consistency, at the potential expense of increased latency.", - "example": "MINIMIZE_LATENCY" - }, - "ContextualTupleKeys": { - "type": "object", - "properties": { - "tuple_keys": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TupleKey" - }, - { - "type": "object" + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationResponse" + } + } + }, + "description": "A successful response." + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" } - ] + } }, - "maxItems": 100 - } - }, - "required": [ - "tuple_keys" - ] - }, - "CreateStoreRequest": { - "type": "object", - "properties": { - "name": { - "type": "string", - "example": "my-store-name" - } - }, - "required": [ - "name" - ] - }, - "CreateStoreResponse": { - "type": "object", - "properties": { - "id": { - "type": "string", - "example": "01YCP46JKYM8FJCQ37NMBYHE5X" + "description": "Request failed due to invalid input." }, - "name": { - "type": "string" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "created_at": { - "type": "string", - "format": "date-time" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "updated_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "name", - "created_at", - "updated_at" - ] - }, - "DeleteStoreResponse": { - "type": "object" - }, - "DirectUserset": { - "type": "object", - "description": "A DirectUserset is a sentinel message for referencing\nthe direct members specified by an object/relation mapping." - }, - "ErrorCode": { - "type": "string", - "enum": [ - "no_error", - "validation_error", - "authorization_model_not_found", - "authorization_model_resolution_too_complex", - "invalid_write_input", - "cannot_allow_duplicate_tuples_in_one_request", - "cannot_allow_duplicate_types_in_one_request", - "cannot_allow_multiple_references_to_one_relation", - "invalid_continuation_token", - "invalid_tuple_set", - "invalid_check_input", - "invalid_expand_input", - "unsupported_user_set", - "invalid_object_format", - "write_failed_due_to_invalid_input", - "authorization_model_assertions_not_found", - "latest_authorization_model_not_found", - "type_not_found", - "relation_not_found", - "empty_relation_definition", - "invalid_user", - "invalid_tuple", - "unknown_relation", - "store_id_invalid_length", - "assertions_too_many_items", - "id_too_long", - "authorization_model_id_too_long", - "tuple_key_value_not_specified", - "tuple_keys_too_many_or_too_few_items", - "page_size_invalid", - "param_missing_value", - "difference_base_missing_value", - "subtract_base_missing_value", - "object_too_long", - "relation_too_long", - "type_definitions_too_few_items", - "type_invalid_length", - "type_invalid_pattern", - "relations_too_few_items", - "relations_too_long", - "relations_invalid_pattern", - "object_invalid_pattern", - "query_string_type_continuation_token_mismatch", - "exceeded_entity_limit", - "invalid_contextual_tuple", - "duplicate_contextual_tuple", - "invalid_authorization_model", - "unsupported_schema_version", - "cancelled", - "invalid_start_time" - ], - "default": "no_error" - }, - "EvaluationBody": { - "type": "object", - "properties": { - "subject": { - "$ref": "#/components/schemas/Subject" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "resource": { - "$ref": "#/components/schemas/Resource" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "action": { - "$ref": "#/components/schemas/Action" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "context": { - "type": "object" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "subject", - "resource", - "action" + "summary": "[Experimental] Evaluate whether a subject can perform an action on a resource", + "tags": [ + "AuthZenService" ] - }, - "EvaluationResponse": { - "type": "object", - "properties": { - "decision": { - "type": "boolean" - }, - "context": { - "type": "object" + } + }, + "/stores/{store_id}/access/v1/evaluations": { + "post": { + "description": "[Experimental] The Evaluations API allows batch authorization checks in a single request. It supports request-level defaults for subject, action, resource, and context that can be overridden per evaluation item.\n\n## Evaluation Semantics\nThe `options.evaluations_semantic` field controls how evaluations are processed:\n- `execute_all` (default): Execute all evaluations and return all results\n- `deny_on_first_deny`: Stop processing on first deny decision\n- `permit_on_first_permit`: Stop processing on first permit decision\n\nWhen using `deny_on_first_deny` or `permit_on_first_permit`, the response may include fewer items than the request because processing short-circuits when the condition is met.\n\n## Authorization Model Selection\nTo pin evaluations to a specific authorization model version, send the `Openfga-Authorization-Model-Id` header. If the header is not provided, the latest model is used.\n\n## Examples\n### Basic batch evaluation\nCheck if a user can perform multiple actions on a document:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"evaluations\": [\n {\"action\": {\"name\": \"can_read\"}},\n {\"action\": {\"name\": \"can_write\"}},\n {\"action\": {\"name\": \"can_delete\"}}\n ]\n}\n```\n### Using evaluation semantics\nStop on first permitted action (useful for finding any valid permission):\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"evaluations\": [\n {\"action\": {\"name\": \"can_read\"}},\n {\"action\": {\"name\": \"can_write\"}}\n ],\n \"options\": {\n \"evaluations_semantic\": \"permit_on_first_permit\"\n }\n}\n```\n### Overriding defaults per evaluation\nCheck permissions across multiple resources:\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"evaluations\": [\n {\"resource\": {\"type\": \"document\", \"id\": \"doc1\"}},\n {\"resource\": {\"type\": \"document\", \"id\": \"doc2\"}},\n {\"resource\": {\"type\": \"folder\", \"id\": \"folder1\"}}\n ]\n}\n```\n", + "operationId": "Evaluations", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } - } - }, - "EvaluationsBody": { - "type": "object", - "properties": { - "subject": { - "$ref": "#/components/schemas/Subject" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationsBody" + } + } }, - "action": { - "$ref": "#/components/schemas/Action" + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationsResponse" + } + } + }, + "description": "A successful response." }, - "resource": { - "$ref": "#/components/schemas/Resource" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "context": { - "type": "object" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "evaluations": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/EvaluationsItemRequest" - }, - { - "type": "object" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" } - ] + } + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } }, - "description": "Optional. If omitted or empty, behaves like a single Access Evaluation request." + "description": "Request failed due to incorrect path." }, - "options": { - "allOf": [ - { - "$ref": "#/components/schemas/EvaluationsOptions" - }, - { - "title": "Options for batch evaluation semantics" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } } - ] - } - } - }, - "EvaluationsItemRequest": { - "type": "object", - "properties": { - "subject": { - "$ref": "#/components/schemas/Subject" - }, - "resource": { - "$ref": "#/components/schemas/Resource" + }, + "description": "Request was aborted due a transaction conflict." }, - "action": { - "$ref": "#/components/schemas/Action" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "context": { - "type": "object" - } - } - }, - "EvaluationsOptions": { - "type": "object", - "properties": { - "evaluations_semantic": { - "allOf": [ - { - "$ref": "#/components/schemas/EvaluationsSemantic" - }, - { - "title": "Controls how batch evaluations are processed" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } } - ] + }, + "description": "Request failed due to internal server error." } }, - "title": "Options for batch evaluations" - }, - "EvaluationsResponse": { - "type": "object", - "properties": { - "evaluations": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/EvaluationResponse" - }, - { - "type": "object" - } - ] + "summary": "[Experimental] Check whether one or more users are authorized to access resources", + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/access/v1/search/action": { + "post": { + "description": "[Experimental] The ActionSearch API returns all actions (relations) that a subject can perform on a specific resource. This is useful for answering questions like \"What can Anne do with this document?\" or building dynamic UIs that show only the actions a user is permitted to perform.\n\n## Examples\n### Find all actions a user can perform on a document\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"name\": \"can_read\"},\n {\"name\": \"can_write\"},\n {\"name\": \"can_share\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Search with ABAC context for time-based permissions\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"resource\": {\"type\": \"report\", \"id\": \"quarterly-financials\"},\n \"context\": {\n \"current_time\": \"2024-01-15T14:30:00Z\",\n \"user_department\": \"finance\"\n }\n}\n```\n### Paginated action search\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"admin\"},\n \"resource\": {\"type\": \"system\", \"id\": \"production\"},\n \"page\": {\"limit\": 50}\n}\n```\n", + "operationId": "ActionSearch", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" } } - } - }, - "EvaluationsSemantic": { - "type": "string", - "enum": [ - "execute_all", - "deny_on_first_deny", - "permit_on_first_permit" ], - "default": "execute_all", - "description": "- execute_all: Execute all evaluations (default behavior)\n - deny_on_first_deny: Stop on first deny decision\n - permit_on_first_permit: Stop on first permit decision", - "title": "Enum for evaluation semantics" - }, - "ExpandBody": { - "type": "object", - "properties": { - "tuple_key": { - "$ref": "#/components/schemas/ExpandRequestTupleKey" + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActionSearchBody" + } + } }, - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActionSearchResponse" + } + } + }, + "description": "A successful response." }, - "consistency": { - "allOf": [ - { - "$ref": "#/components/schemas/ConsistencyPreference" - }, - { - "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } } - ] + }, + "description": "Request failed due to invalid input." }, - "contextual_tuples": { - "$ref": "#/components/schemas/ContextualTupleKeys" - } - }, - "required": [ - "tuple_key" - ] - }, - "ExpandRequestTupleKey": { - "type": "object", - "properties": { - "relation": { - "type": "string", - "example": "reader", - "maxLength": 50 + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "object": { - "type": "string", - "example": "document:2021-budget", - "maxLength": 256 - } - }, - "required": [ - "relation", - "object" - ] - }, - "ExpandResponse": { - "type": "object", - "properties": { - "tree": { - "$ref": "#/components/schemas/UsersetTree" - } - } - }, - "ForbiddenResponse": { - "type": "object", - "example": { - "code": "forbidden", - "message": "the principal is not authorized to perform the action" - }, - "properties": { - "code": { - "$ref": "#/components/schemas/AuthErrorCode" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "message": { - "type": "string" - } - } - }, - "GetConfigurationResponse": { - "type": "object", - "properties": { - "policy_decision_point": { - "type": "string", - "description": "REQUIRED. The PDP identifier URL (HTTPS, no query or fragment)." + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "access_evaluation_endpoint": { - "type": "string", - "description": "REQUIRED. The access evaluation endpoint URL." + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "access_evaluations_endpoint": { - "type": "string", - "description": "OPTIONAL. The batch evaluations endpoint URL." + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "search_subject_endpoint": { - "type": "string", - "description": "OPTIONAL. The subject search endpoint URL." + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." + } + }, + "summary": "[Experimental] Search for actions a subject can perform on a resource", + "tags": [ + "AuthZenService" + ] + } + }, + "/stores/{store_id}/access/v1/search/resource": { + "post": { + "description": "[Experimental] The ResourceSearch API returns all resources of a given type that a subject has a specific action (relation) on. This is useful for answering questions like \"What documents can Anne read?\" or \"What folders can Bob administer?\"\n\nThe resource type filter is required. Results support pagination for large result sets.\n\n## Examples\n### Find all documents a user can read\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"type\": \"document\", \"id\": \"roadmap\"},\n {\"type\": \"document\", \"id\": \"budget-2024\"},\n {\"type\": \"document\", \"id\": \"team-roster\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Find folders a user can administer with pagination\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"bob\"},\n \"action\": {\"name\": \"can_admin\"},\n \"resource\": {\"type\": \"folder\"},\n \"page\": {\"limit\": 25}\n}\n```\n### Search with ABAC context\n```json\n{\n \"subject\": {\"type\": \"user\", \"id\": \"anne\"},\n \"action\": {\"name\": \"can_read\"},\n \"resource\": {\"type\": \"document\"},\n \"context\": {\n \"current_time\": \"2024-01-15T10:00:00Z\",\n \"ip_address\": \"192.168.1.100\"\n }\n}\n```\n", + "operationId": "ResourceSearch", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResourceSearchBody" + } + } }, - "search_resource_endpoint": { - "type": "string", - "description": "OPTIONAL. The resource search endpoint URL." + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResourceSearchResponse" + } + } + }, + "description": "A successful response." }, - "search_action_endpoint": { - "type": "string", - "description": "OPTIONAL. The action search endpoint URL." + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "capabilities": { - "type": "array", - "items": { - "type": "string" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } }, - "description": "OPTIONAL. Supported capabilities as URN strings." + "description": "Not authenticated." }, - "signed_metadata": { - "type": "string", - "description": "OPTIONAL. Signed metadata JWT per AuthZEN metadata specification." - } - }, - "title": "GetConfiguration response - PDP metadata per AuthZEN spec", - "required": [ - "policy_decision_point", - "access_evaluation_endpoint" - ] - }, - "GetStoreResponse": { - "type": "object", - "properties": { - "id": { - "type": "string", - "example": "01YCP46JKYM8FJCQ37NMBYHE5X" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "name": { - "type": "string" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "created_at": { - "type": "string", - "format": "date-time" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "updated_at": { - "type": "string", - "format": "date-time" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "deleted_at": { - "type": "string", - "format": "date-time" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "id", - "name", - "created_at", - "updated_at" + "summary": "[Experimental] Search for resources a subject has access to", + "tags": [ + "AuthZenService" ] - }, - "InternalErrorCode": { - "type": "string", - "enum": [ - "no_internal_error", - "internal_error", - "deadline_exceeded", - "already_exists", - "resource_exhausted", - "failed_precondition", - "aborted", - "out_of_range", - "unavailable", - "data_loss" - ], - "default": "no_internal_error" - }, - "InternalErrorMessageResponse": { - "type": "object", - "example": { - "code": "internal_error", - "message": "Internal Server Error" - }, - "properties": { - "code": { - "$ref": "#/components/schemas/InternalErrorCode" - }, - "message": { - "type": "string" + } + }, + "/stores/{store_id}/access/v1/search/subject": { + "post": { + "description": "[Experimental] The SubjectSearch API returns all subjects that have a specific action (relation) on a given resource. This is useful for answering questions like \"Who can read this document?\" or \"Who can administer this folder?\"\n\nResults can be filtered by subject type and support pagination for large result sets.\n\n## Examples\n### Find all users who can read a document\n```json\n{\n \"resource\": {\"type\": \"document\", \"id\": \"roadmap\"},\n \"action\": {\"name\": \"can_read\"},\n \"subject\": {\"type\": \"user\"}\n}\n```\nResponse:\n```json\n{\n \"results\": [\n {\"type\": \"user\", \"id\": \"anne\"},\n {\"type\": \"user\", \"id\": \"bob\"},\n {\"type\": \"user\", \"id\": \"charlie\"}\n ],\n \"page\": {\"count\": 3}\n}\n```\n### Paginated search with limit\n```json\n{\n \"resource\": {\"type\": \"folder\", \"id\": \"engineering\"},\n \"action\": {\"name\": \"can_view\"},\n \"subject\": {\"type\": \"user\"},\n \"page\": {\"limit\": 10}\n}\n```\n### Continue from previous page\n```json\n{\n \"resource\": {\"type\": \"folder\", \"id\": \"engineering\"},\n \"action\": {\"name\": \"can_view\"},\n \"subject\": {\"type\": \"user\"},\n \"page\": {\"token\": \"eyJsYXN0X2lkIjoiMTAwIn0=\", \"limit\": 10}\n}\n```\n", + "operationId": "SubjectSearch", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } - } - }, - "Leaf": { - "type": "object", - "properties": { - "users": { - "$ref": "#/components/schemas/Users" - }, - "computed": { - "$ref": "#/components/schemas/Computed" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSearchBody" + } + } }, - "tupleToUserset": { - "$ref": "#/components/schemas/UsersetTree.TupleToUserset" - } + "required": true }, - "description": "A leaf node contains either\n- a set of users (which may be individual users, or usersets\n referencing other relations)\n- a computed node, which is the result of a computed userset\n value in the authorization model\n- a tupleToUserset nodes, containing the result of expanding\n a tupleToUserset value in a authorization model." - }, - "ListObjectsBody": { - "type": "object", - "properties": { - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSearchResponse" + } + } + }, + "description": "A successful response." }, - "type": { - "type": "string", - "example": "document" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "relation": { - "type": "string", - "example": "reader" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512, - "minLength": 1 + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "contextual_tuples": { - "$ref": "#/components/schemas/ContextualTupleKeys" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "context": { - "type": "object", - "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "consistency": { - "allOf": [ - { - "$ref": "#/components/schemas/ConsistencyPreference" - }, - { - "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } } - ] - } - }, - "required": [ - "type", - "relation", - "user" - ] - }, - "ListObjectsResponse": { - "type": "object", - "properties": { - "objects": { - "type": "array", - "example": [ - "document:roadmap", - "document:planning" - ], - "items": { - "type": "string" - } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "objects" + "summary": "[Experimental] Search for subjects with access to a resource", + "tags": [ + "AuthZenService" ] - }, - "ListStoresResponse": { - "type": "object", - "properties": { - "stores": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Store" - }, - { - "type": "object" - } - ] + } + }, + "/stores/{store_id}/assertions/{authorization_model_id}": { + "get": { + "description": "The ReadAssertions API will return, for a given authorization model id, all the assertions stored for it. ", + "operationId": "ReadAssertions", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" } }, - "continuation_token": { - "type": "string", - "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", - "description": "The continuation token will be empty if there are no more stores." + { + "in": "path", + "name": "authorization_model_id", + "required": true, + "schema": { + "type": "string" + } } - }, - "required": [ - "stores", - "continuation_token" - ] - }, - "ListUsersBody": { - "type": "object", - "properties": { - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAssertionsResponse" + } + } + }, + "description": "A successful response." }, - "object": { - "allOf": [ - { - "$ref": "#/components/schemas/Object" - }, - { - "example": "document:example" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } } - ] + }, + "description": "Request failed due to invalid input." }, - "relation": { - "type": "string", - "example": "reader" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "user_filters": { - "type": "array", - "example": [ - { - "type": "user" - }, - { - "type": "group", - "relation": "member" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } } - ], - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/UserTypeFilter" - }, - { - "type": "object" + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" } - ] + } }, - "description": "The type of results returned. Only accepts exactly one value.", - "maxItems": 1, - "minItems": 1 + "description": "Request failed due to incorrect path." }, - "contextual_tuples": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TupleKey" - }, - { - "type": "object" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" } - ] + } }, - "maxItems": 100 + "description": "Request was aborted due a transaction conflict." }, - "context": { - "type": "object", - "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "consistency": { - "allOf": [ - { - "$ref": "#/components/schemas/ConsistencyPreference" - }, - { - "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } } - ] + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "object", - "relation", - "user_filters" + "summary": "Read assertions for an authorization model ID", + "tags": [ + "Assertions" ] }, - "ListUsersResponse": { - "type": "object", - "properties": { - "users": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/User" - }, - { - "type": "object" - } - ] + "put": { + "description": "The WriteAssertions API will upsert new assertions for an authorization model id, or overwrite the existing ones. An assertion is an object that contains a tuple key, the expectation of whether a call to the Check API of that tuple key will return true or false, and optionally a list of contextual tuples.", + "operationId": "WriteAssertions", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "authorization_model_id", + "required": true, + "schema": { + "type": "string" } } - }, - "required": [ - "users" - ] - }, - "Metadata": { - "type": "object", - "properties": { - "relations": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/RelationMetadata" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAssertionsBody" + } } }, - "module": { - "type": "string" + "required": true + }, + "responses": { + "204": { + "description": "A successful response." }, - "source_info": { - "$ref": "#/components/schemas/SourceInfo" - } - } - }, - "Node": { - "type": "object", - "properties": { - "name": { - "type": "string" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "leaf": { - "$ref": "#/components/schemas/Leaf" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "difference": { - "$ref": "#/components/schemas/UsersetTree.Difference" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "union": { - "$ref": "#/components/schemas/Nodes" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "intersection": { - "$ref": "#/components/schemas/Nodes" - } - }, - "required": [ - "name" - ] - }, - "Nodes": { - "type": "object", - "properties": { - "nodes": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Node" - }, - { - "type": "object" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" } - ] - } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "nodes" + "summary": "Upsert assertions for an authorization model ID", + "tags": [ + "Assertions" ] - }, - "NotFoundErrorCode": { - "type": "string", - "enum": [ - "no_not_found_error", - "undefined_endpoint", - "store_id_not_found", - "unimplemented" - ], - "default": "no_not_found_error" - }, - "NullValue": { - "type": "string", - "enum": [ - "NULL_VALUE" - ], - "default": "NULL_VALUE", - "description": "`NullValue` is a singleton enumeration to represent the null value for the\n`Value` type union.\n\nThe JSON representation for `NullValue` is JSON `null`.\n\n - NULL_VALUE: Null value." - }, - "Object": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "document" + } + }, + "/stores/{store_id}/authorization-models": { + "get": { + "description": "The ReadAuthorizationModels API will return all the authorization models for a certain store.\nOpenFGA's response will contain an array of all authorization models, sorted in descending order of creation.\n\n## Example\nAssume that a store's authorization model has been configured twice. To get all the authorization models that have been created in this store, call GET authorization-models. The API will return a response that looks like:\n```json\n{\n \"authorization_models\": [\n {\n \"id\": \"01G50QVV17PECNVAHX1GG4Y5NC\",\n \"type_definitions\": [...]\n },\n {\n \"id\": \"01G4ZW8F4A07AKQ8RHSVG9RW04\",\n \"type_definitions\": [...]\n },\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nIf there are no more authorization models available, the `continuation_token` field will be empty\n```json\n{\n \"authorization_models\": [\n {\n \"id\": \"01G50QVV17PECNVAHX1GG4Y5NC\",\n \"type_definitions\": [...]\n },\n {\n \"id\": \"01G4ZW8F4A07AKQ8RHSVG9RW04\",\n \"type_definitions\": [...]\n },\n ],\n \"continuation_token\": \"\"\n}\n```\n", + "operationId": "ReadAuthorizationModels", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } }, - "id": { - "type": "string", - "example": "0bcdf6fa-a6aa-4730-a8eb-9cf172ff16d9" - } - }, - "description": "Object represents an OpenFGA Object.\n\nAn Object is composed of a type and identifier (e.g. 'document:1')\n\nSee https://openfga.dev/docs/concepts#what-is-an-object", - "required": [ - "type", - "id" - ] - }, - "ObjectRelation": { - "type": "object", - "properties": { - "object": { - "type": "string" + { + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "format": "int32", + "type": "integer" + } }, - "relation": { - "type": "string" + { + "in": "query", + "name": "continuation_token", + "required": false, + "schema": { + "type": "string" + } } - } - }, - "PageRequest": { - "type": "object", - "properties": { - "token": { - "type": "string", - "title": "Continuation token from previous response" + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAuthorizationModelsResponse" + } + } + }, + "description": "A successful response." }, - "limit": { - "type": "integer", - "format": "int64", - "title": "Maximum number of results to return (default: 50, max: 1000)" - } - }, - "title": "Pagination request parameters for search operations" - }, - "PageResponse": { - "type": "object", - "properties": { - "next_token": { - "type": "string", - "title": "Token to retrieve next page (empty if no more results)" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "count": { - "type": "integer", - "format": "int64", - "title": "Number of results in this page" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "total": { - "type": "integer", - "format": "int64", - "title": "Total number of results (if known, otherwise 0)" - } - }, - "title": "Pagination response parameters" - }, - "PathUnknownErrorMessageResponse": { - "type": "object", - "example": { - "code": "undefined_endpoint", - "message": "Endpoint not enabled" - }, - "properties": { - "code": { - "$ref": "#/components/schemas/NotFoundErrorCode" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "message": { - "type": "string" - } - } - }, - "ReadAssertionsResponse": { - "type": "object", - "properties": { - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "assertions": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Assertion" - }, - { - "type": "object" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" } - ] - } - } - }, - "required": [ - "authorization_model_id" - ] - }, - "ReadAuthorizationModelResponse": { - "type": "object", - "properties": { - "authorization_model": { - "$ref": "#/components/schemas/AuthorizationModel" - } - } - }, - "ReadAuthorizationModelsResponse": { - "type": "object", - "properties": { - "authorization_models": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/AuthorizationModel" - }, - { - "type": "object" + } + }, + "description": "Request was aborted due a transaction conflict." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" } - ] - } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "continuation_token": { - "type": "string", - "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", - "description": "The continuation token will be empty if there are no more models." + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "authorization_models" + "summary": "Return all the authorization models for a particular store", + "tags": [ + "Authorization Models" ] }, - "ReadBody": { - "type": "object", - "properties": { - "tuple_key": { - "$ref": "#/components/schemas/ReadRequestTupleKey" + "post": { + "description": "The WriteAuthorizationModel API will add a new authorization model to a store.\nEach item in the `type_definitions` array is a type definition as specified in the field `type_definition`.\nThe response will return the authorization model's ID in the `id` field.\n\n## Example\nTo add an authorization model with `user` and `document` type definitions, call POST authorization-models API with the body: \n```json\n{\n \"type_definitions\":[\n {\n \"type\":\"user\"\n },\n {\n \"type\":\"document\",\n \"relations\":{\n \"reader\":{\n \"union\":{\n \"child\":[\n {\n \"this\":{}\n },\n {\n \"computedUserset\":{\n \"object\":\"\",\n \"relation\":\"writer\"\n }\n }\n ]\n }\n },\n \"writer\":{\n \"this\":{}\n }\n }\n }\n ]\n}\n```\nOpenFGA's response will include the version id for this authorization model, which will look like \n```\n{\"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"}\n```\n", + "operationId": "WriteAuthorizationModel", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAuthorizationModelBody" + } + } }, - "page_size": { - "type": "integer", - "format": "int32", - "example": 50, - "maximum": 100, - "minimum": 1 + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAuthorizationModelResponse" + } + } + }, + "description": "A successful response." }, - "continuation_token": { - "type": "string", - "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "consistency": { - "allOf": [ - { - "$ref": "#/components/schemas/ConsistencyPreference" - }, - { - "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } } - ] - } - } - }, - "ReadChangesResponse": { - "type": "object", - "properties": { - "changes": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TupleChange" - }, - { - "type": "object" + }, + "description": "Not authenticated." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" } - ] - } + } + }, + "description": "Forbidden." }, - "continuation_token": { - "type": "string", - "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", - "description": "The continuation token will be identical if there are no new changes." - } - }, - "required": [ - "changes" - ] - }, - "ReadRequestTupleKey": { - "type": "object", - "properties": { - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512 + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "relation": { - "type": "string", - "example": "reader", - "maxLength": 50 + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "object": { - "type": "string", - "example": "document:2021-budget", - "maxLength": 256 - } - } - }, - "ReadResponse": { - "type": "object", - "properties": { - "tuples": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Tuple" - }, - { - "type": "object" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" } - ] - } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "continuation_token": { - "type": "string", - "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", - "description": "The continuation token will be empty if there are no more tuples." + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "tuples", - "continuation_token" + "summary": "Create a new authorization model", + "tags": [ + "Authorization Models" ] - }, - "RelationMetadata": { - "type": "object", - "properties": { - "directly_related_user_types": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/RelationReference" - }, - { - "type": "object" - } - ] + } + }, + "/stores/{store_id}/authorization-models/{id}": { + "get": { + "description": "The ReadAuthorizationModel API returns an authorization model by its identifier.\nThe response will return the authorization model for the particular version.\n\n## Example\nTo retrieve the authorization model with ID `01G5JAVJ41T49E9TT3SKVS7X1J` for the store, call the GET authorization-models by ID API with `01G5JAVJ41T49E9TT3SKVS7X1J` as the `id` path parameter. The API will return:\n```json\n{\n \"authorization_model\":{\n \"id\":\"01G5JAVJ41T49E9TT3SKVS7X1J\",\n \"type_definitions\":[\n {\n \"type\":\"user\"\n },\n {\n \"type\":\"document\",\n \"relations\":{\n \"reader\":{\n \"union\":{\n \"child\":[\n {\n \"this\":{}\n },\n {\n \"computedUserset\":{\n \"object\":\"\",\n \"relation\":\"writer\"\n }\n }\n ]\n }\n },\n \"writer\":{\n \"this\":{}\n }\n }\n }\n ]\n }\n}\n```\nIn the above example, there are 2 types (`user` and `document`). The `document` type has 2 relations (`writer` and `reader`).", + "operationId": "ReadAuthorizationModel", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" } }, - "module": { - "type": "string" - }, - "source_info": { - "$ref": "#/components/schemas/SourceInfo" + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } } - } - }, - "RelationReference": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "group" + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAuthorizationModelResponse" + } + } + }, + "description": "A successful response." }, - "relation": { - "type": "string", - "example": "member" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "wildcard": { - "$ref": "#/components/schemas/Wildcard" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "condition": { - "type": "string", - "description": "The name of a condition that is enforced over the allowed relation." + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "description": "RelationReference represents a relation of a particular object type (e.g. 'document#viewer').", - "required": [ - "type" + "summary": "Return a particular version of an authorization model", + "tags": [ + "Authorization Models" ] - }, - "RelationshipCondition": { - "type": "object", - "properties": { - "name": { - "type": "string", - "example": "condition1", - "description": "A reference (by name) of the relationship condition defined in the authorization model.", - "maxLength": 256 - }, - "context": { - "type": "object", - "description": "Additional context/data to persist along with the condition.\nThe keys must match the parameters defined by the condition, and the value types must\nmatch the parameter type definitions." + } + }, + "/stores/{store_id}/batch-check": { + "post": { + "description": "The `BatchCheck` API functions nearly identically to `Check`, but instead of checking a single user-object relationship BatchCheck accepts a list of relationships to check and returns a map containing `BatchCheckItem` response for each check it received.\n\nAn associated `correlation_id` is required for each check in the batch. This ID is used to correlate a check to the appropriate response. It is a string consisting of only alphanumeric characters or hyphens with a maximum length of 36 characters. This `correlation_id` is used to map the result of each check to the item which was checked, so it must be unique for each item in the batch. We recommend using a UUID or ULID as the `correlation_id`, but you can use whatever unique identifier you need as long as it matches this regex pattern: `^[\\w\\d-]{1,36}$`\n\nNOTE: The maximum number of checks that can be passed in the `BatchCheck` API is configurable via the [OPENFGA_MAX_CHECKS_PER_BATCH_CHECK](https://openfga.dev/docs/getting-started/setup-openfga/configuration#OPENFGA_MAX_CHECKS_PER_BATCH_CHECK) environment variable. If `BatchCheck` is called using the SDK, the SDK can split the batch check requests for you.\n\nFor more details on how `Check` functions, see the docs for `/check`.\n\n### Examples\n#### A BatchCheckRequest\n```json\n{\n \"checks\": [\n {\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n \"relation\": \"reader\",\n \"user\": \"user:anne\",\n },\n \"contextual_tuples\": {...}\n \"context\": {}\n \"correlation_id\": \"01JA8PM3QM7VBPGB8KMPK8SBD5\"\n },\n {\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n \"relation\": \"reader\",\n \"user\": \"user:bob\",\n },\n \"contextual_tuples\": {...}\n \"context\": {}\n \"correlation_id\": \"01JA8PMM6A90NV5ET0F28CYSZQ\"\n }\n ]\n}\n```\n\nBelow is a possible response to the above request. Note that the result map's keys are the `correlation_id` values from the checked items in the request:\n```json\n{\n \"result\": {\n \"01JA8PMM6A90NV5ET0F28CYSZQ\": {\n \"allowed\": false, \n \"error\": {\"message\": \"\"} \n },\n \"01JA8PM3QM7VBPGB8KMPK8SBD5\": {\n \"allowed\": true, \n \"error\": {\"message\": \"\"} \n }\n}\n```\n", + "operationId": "BatchCheck", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchCheckBody" + } + } + }, + "required": true }, - "required": [ - "name" - ] - }, - "Resource": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "document" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchCheckResponse" + } + } + }, + "description": "A successful response." }, - "id": { - "type": "string", - "example": "roadmap" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "properties": { - "type": "object" - } - }, - "required": [ - "type", - "id" - ] - }, - "ResourceFilter": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "document" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "id": { - "type": "string", - "description": "Optional resource id. If present in Resource Search, it is ignored per AuthZEN spec." + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "properties": { - "type": "object" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "title": "ResourceFilter is used for search operations where only type is required", - "required": [ - "type" + "summary": "Send a list of `check` operations in a single request", + "tags": [ + "Relationship Queries" ] - }, - "ResourceSearchBody": { - "type": "object", - "properties": { - "subject": { - "$ref": "#/components/schemas/Subject" + } + }, + "/stores/{store_id}/changes": { + "get": { + "description": "The ReadChanges API will return a paginated list of tuple changes (additions and deletions) that occurred in a given store, sorted by ascending time. The response will include a continuation token that is used to get the next set of changes. If there are no changes after the provided continuation token, the same token will be returned in order for it to be used when new changes are recorded. If the store never had any tuples added or removed, this token will be empty.\nYou can use the `type` parameter to only get the list of tuple changes that affect objects of that type.\nWhen reading a write tuple change, if it was conditioned, the condition will be returned.\nWhen reading a delete tuple change, the condition will NOT be returned regardless of whether it was originally conditioned or not.\n", + "operationId": "ReadChanges", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } }, - "action": { - "$ref": "#/components/schemas/Action" + { + "in": "query", + "name": "type", + "required": false, + "schema": { + "type": "string" + } }, - "resource": { - "allOf": [ - { - "$ref": "#/components/schemas/ResourceFilter" - }, - { - "title": "Filter by resource type" - } - ] + { + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "format": "int32", + "type": "integer" + } }, - "context": { - "type": "object" + { + "in": "query", + "name": "continuation_token", + "required": false, + "schema": { + "type": "string" + } }, - "page": { - "$ref": "#/components/schemas/PageRequest" + { + "description": "Start date and time of changes to read.\nFormat: ISO 8601 timestamp (e.g., 2022-01-01T00:00:00Z)\nIf a continuation_token is provided along side start_time, the continuation_token will take precedence over start_time.", + "in": "query", + "name": "start_time", + "required": false, + "schema": { + "format": "date-time", + "type": "string" + } } - }, - "title": "ResourceSearch request", - "required": [ - "subject", - "action", - "resource" - ] - }, - "ResourceSearchResponse": { - "type": "object", - "properties": { - "results": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Resource" - }, - { - "type": "object" + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadChangesResponse" } - ] - } + } + }, + "description": "A successful response." }, - "page": { - "allOf": [ - { - "$ref": "#/components/schemas/PageResponse" - }, - { - "title": "Optional per AuthZEN spec - omit if pagination not supported" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } } - ] - } - } - }, - "SourceInfo": { - "type": "object", - "properties": { - "file": { - "type": "string" - } - } - }, - "Status": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" + }, + "description": "Request failed due to invalid input." }, - "message": { - "type": "string" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "details": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Any" - }, - { - "type": "object" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" } - ] - } - } - } - }, - "Store": { - "type": "object", - "properties": { - "id": { - "type": "string" + } + }, + "description": "Forbidden." }, - "name": { - "type": "string" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "created_at": { - "type": "string", - "format": "date-time" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "updated_at": { - "type": "string", - "format": "date-time" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "deleted_at": { - "type": "string", - "format": "date-time" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "id", - "name", - "created_at", - "updated_at" + "summary": "Return a list of all the tuple changes", + "tags": [ + "Relationship Tuples" ] - }, - "StreamedListObjectsBody": { - "type": "object", - "properties": { - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + } + }, + "/stores/{store_id}/check": { + "post": { + "description": "The Check API returns whether a given user has a relationship with a given object in a given store.\nThe `user` field of the request can be a specific target, such as `user:anne`, or a userset (set of users) such as `group:marketing#member` or a type-bound public access `user:*`.\nTo arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nA `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`.\nYou may also provide an `authorization_model_id` in the body. This will be used to assert that the input `tuple_key` is valid for the model specified. If not specified, the assertion will be made against the latest authorization model ID. It is strongly recommended to specify authorization model id for better performance.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nBy default, the Check API caches results for a short time to optimize performance. You may specify a value of `HIGHER_CONSISTENCY` for the optional `consistency` parameter in the body to inform the server that higher conisistency is preferred at the expense of increased latency. Consideration should be given to the increased latency if requesting higher consistency.\nThe response will return whether the relationship exists in the field `allowed`.\n\nSome exceptions apply, but in general, if a Check API responds with `{allowed: true}`, then you can expect the equivalent ListObjects query to return the object, and viceversa. \nFor example, if `Check(user:anne, reader, document:2021-budget)` responds with `{allowed: true}`, then `ListObjects(user:anne, reader, document)` may include `document:2021-budget` in the response.\n## Examples\n### Querying with contextual tuples\nIn order to check if user `user:anne` of type `user` has a `reader` relationship with object `document:2021-budget` given the following contextual tuple\n```json\n{\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"time_slot:office_hours\"\n}\n```\nthe Check API can be used with the following request body:\n```json\n{\n \"tuple_key\": {\n \"user\": \"user:anne\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"time_slot:office_hours\"\n }\n ]\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\n### Querying usersets\nSome Checks will always return `true`, even without any tuples. For example, for the following authorization model\n```python\nmodel\n schema 1.1\ntype user\ntype document\n relations\n define reader: [user]\n```\nthe following query\n```json\n{\n \"tuple_key\": {\n \"user\": \"document:2021-budget#reader\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n }\n}\n```\nwill always return `{ \"allowed\": true }`. This is because usersets are self-defining: the userset `document:2021-budget#reader` will always have the `reader` relation with `document:2021-budget`.\n### Querying usersets with difference in the model\nA Check for a userset can yield results that must be treated carefully if the model involves difference. For example, for the following authorization model\n```python\nmodel\n schema 1.1\ntype user\ntype group\n relations\n define member: [user]\ntype document\n relations\n define blocked: [user]\n define reader: [group#member] but not blocked\n```\nthe following query\n```json\n{\n \"tuple_key\": {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"member\",\n \"object\": \"group:finance\"\n },\n {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n {\n \"user\": \"user:anne\",\n \"relation\": \"blocked\",\n \"object\": \"document:2021-budget\"\n }\n ]\n },\n}\n```\nwill return `{ \"allowed\": true }`, even though a specific user of the userset `group:finance#member` does not have the `reader` relationship with the given object.\n### Requesting higher consistency\nBy default, the Check API caches results for a short time to optimize performance. You may request higher consistency to inform the server that higher consistency should be preferred at the expense of increased latency. Care should be taken when requesting higher consistency due to the increased latency.\n```json\n{\n \"tuple_key\": {\n \"user\": \"group:finance#member\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"consistency\": \"HIGHER_CONSISTENCY\"\n}\n```\n", + "operationId": "Check", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckBody" + } + } }, - "type": { - "type": "string", - "example": "document" + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckResponse" + } + } + }, + "description": "A successful response." }, - "relation": { - "type": "string", - "example": "reader" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512, - "minLength": 1 + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "contextual_tuples": { - "$ref": "#/components/schemas/ContextualTupleKeys" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "context": { - "type": "object", - "description": "Additional request context that will be used to evaluate any ABAC conditions encountered\nin the query evaluation." + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "consistency": { - "allOf": [ - { - "$ref": "#/components/schemas/ConsistencyPreference" - }, - { - "description": "Controls the consistency preference for this request. Default value is UNSPECIFIED, which will have the same behavior as MINIMIZE_LATENCY." + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } } - ] - } - }, - "required": [ - "type", - "relation", - "user" - ] - }, - "StreamedListObjectsResponse": { - "type": "object", - "properties": { - "object": { - "type": "string", - "example": "document:roadmap" + }, + "description": "Request was aborted due a transaction conflict." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "description": "The response for a StreamedListObjects RPC.", - "required": [ - "object" + "summary": "Check whether a user is authorized to access an object", + "tags": [ + "Relationship Queries" ] - }, - "Subject": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "user" - }, - "id": { - "type": "string", - "example": "anne" - }, - "properties": { - "type": "object" + } + }, + "/stores/{store_id}/expand": { + "post": { + "description": "The Expand API will return all users and usersets that have certain relationship with an object in a certain store.\nThis is different from the `/stores/{store_id}/read` API in that both users and computed usersets are returned.\nBody parameters `tuple_key.object` and `tuple_key.relation` are all required.\nA `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`.\nThe response will return a tree whose leaves are the specific users and usersets. Union, intersection and difference operator are located in the intermediate nodes.\n\n## Example\nTo expand all users that have the `reader` relationship with object `document:2021-budget`, use the Expand API with the following request body\n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\",\n \"relation\": \"reader\"\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\nOpenFGA's response will be a userset tree of the users and usersets that have read access to the document.\n```json\n{\n \"tree\":{\n \"root\":{\n \"type\":\"document:2021-budget#reader\",\n \"union\":{\n \"nodes\":[\n {\n \"type\":\"document:2021-budget#reader\",\n \"leaf\":{\n \"users\":{\n \"users\":[\n \"user:bob\"\n ]\n }\n }\n },\n {\n \"type\":\"document:2021-budget#reader\",\n \"leaf\":{\n \"computed\":{\n \"userset\":\"document:2021-budget#writer\"\n }\n }\n }\n ]\n }\n }\n }\n}\n```\nThe caller can then call expand API for the `writer` relationship for the `document:2021-budget`.\n### Expand Request with Contextual Tuples\n\nGiven the model\n```python\nmodel\n schema 1.1\n\ntype user\n\ntype folder\n relations\n define owner: [user]\n\ntype document\n relations\n define parent: [folder]\n define viewer: [user] or writer\n define writer: [user] or owner from parent\n```\nand the initial tuples\n```json\n[{\n \"user\": \"user:bob\",\n \"relation\": \"owner\",\n \"object\": \"folder:1\"\n}]\n```\n\nTo expand all `writers` of `document:1` when `document:1` is put in `folder:1`, the first call could be\n\n```json\n{\n \"tuple_key\": {\n \"object\": \"document:1\",\n \"relation\": \"writer\"\n },\n \"contextual_tuples\": {\n \"tuple_keys\": [\n {\n \"user\": \"folder:1\",\n \"relation\": \"parent\",\n \"object\": \"document:1\"\n }\n ]\n }\n}\n```\nthis returns:\n```json\n{\n \"tree\": {\n \"root\": {\n \"name\": \"document:1#writer\",\n \"union\": {\n \"nodes\": [\n {\n \"name\": \"document:1#writer\",\n \"leaf\": {\n \"users\": {\n \"users\": []\n }\n }\n },\n {\n \"name\": \"document:1#writer\",\n \"leaf\": {\n \"tupleToUserset\": {\n \"tupleset\": \"document:1#parent\",\n \"computed\": [\n {\n \"userset\": \"folder:1#owner\"\n }\n ]\n }\n }\n }\n ]\n }\n }\n }\n}\n```\nThis tells us that the `owner` of `folder:1` may also be a writer. So our next call could be to find the `owners` of `folder:1`\n```json\n{\n \"tuple_key\": {\n \"object\": \"folder:1\",\n \"relation\": \"owner\"\n }\n}\n```\nwhich gives\n```json\n{\n \"tree\": {\n \"root\": {\n \"name\": \"folder:1#owner\",\n \"leaf\": {\n \"users\": {\n \"users\": [\n \"user:bob\"\n ]\n }\n }\n }\n }\n}\n```\n", + "operationId": "Expand", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExpandBody" + } + } + }, + "required": true }, - "required": [ - "type", - "id" - ] - }, - "SubjectFilter": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "user" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExpandResponse" + } + } + }, + "description": "A successful response." }, - "id": { - "type": "string", - "description": "Optional subject id. If present in Subject Search, it is ignored per AuthZEN spec." + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "properties": { - "type": "object" - } - }, - "title": "SubjectFilter is used for search operations where only type is required", - "required": [ - "type" - ] - }, - "SubjectSearchBody": { - "type": "object", - "properties": { - "resource": { - "$ref": "#/components/schemas/Resource" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "action": { - "$ref": "#/components/schemas/Action" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "subject": { - "allOf": [ - { - "$ref": "#/components/schemas/SubjectFilter" - }, - { - "description": "REQUIRED by AuthZEN Subject Search. Subject `id` may be provided but is ignored." + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } } - ] + }, + "description": "Request failed due to incorrect path." }, - "context": { - "type": "object" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "page": { - "$ref": "#/components/schemas/PageRequest" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "title": "SubjectSearch request", - "required": [ - "resource", - "action", - "subject" + "summary": "Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship", + "tags": [ + "Relationship Queries" ] - }, - "SubjectSearchResponse": { - "type": "object", - "properties": { - "results": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Subject" - }, - { - "type": "object" - } - ] + } + }, + "/stores/{store_id}/list-objects": { + "post": { + "description": "The ListObjects API returns a list of all the objects of the given type that the user has a relation with.\n To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nAn `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance.\nYou may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nBy default, the Check API caches results for a short time to optimize performance. You may specify a value of `HIGHER_CONSISTENCY` for the optional `consistency` parameter in the body to inform the server that higher conisistency is preferred at the expense of increased latency. Consideration should be given to the increased latency if requesting higher consistency.\nThe response will contain the related objects in an array in the \"objects\" field of the response and they will be strings in the object format `:` (e.g. \"document:roadmap\").\nThe number of objects in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first.\nThe objects given will not be sorted, and therefore two identical calls can give a given different set of objects.", + "operationId": "ListObjects", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" } - }, - "page": { - "allOf": [ - { - "$ref": "#/components/schemas/PageResponse" - }, - { - "title": "Optional per AuthZEN spec - omit if pagination not supported" - } - ] } - } - }, - "Tuple": { - "type": "object", - "properties": { - "key": { - "$ref": "#/components/schemas/TupleKey" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListObjectsBody" + } + } }, - "timestamp": { - "type": "string", - "format": "date-time" - } + "required": true }, - "required": [ - "key", - "timestamp" - ] - }, - "TupleChange": { - "type": "object", - "properties": { - "tuple_key": { - "$ref": "#/components/schemas/TupleKey" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListObjectsResponse" + } + } + }, + "description": "A successful response." }, - "operation": { - "$ref": "#/components/schemas/TupleOperation" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "timestamp": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "tuple_key", - "operation", - "timestamp" - ] - }, - "TupleKey": { - "type": "object", - "properties": { - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512 + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "relation": { - "type": "string", - "example": "reader", - "maxLength": 50 + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "object": { - "type": "string", - "example": "document:2021-budget", - "maxLength": 256 + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "condition": { - "$ref": "#/components/schemas/RelationshipCondition" - } - }, - "required": [ - "user", - "relation", - "object" - ] - }, - "TupleKeyWithoutCondition": { - "type": "object", - "properties": { - "user": { - "type": "string", - "example": "user:anne", - "maxLength": 512 + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "relation": { - "type": "string", - "example": "reader", - "maxLength": 50 + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "object": { - "type": "string", - "example": "document:2021-budget", - "maxLength": 256 + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "user", - "relation", - "object" + "summary": "List all objects of the given type that the user has a relation with", + "tags": [ + "Relationship Queries" ] - }, - "TupleOperation": { - "type": "string", - "enum": [ - "TUPLE_OPERATION_WRITE", - "TUPLE_OPERATION_DELETE" + } + }, + "/stores/{store_id}/list-users": { + "post": { + "description": "The ListUsers API returns a list of all the users of a specific type that have a relation to a given object.\n To arrive at a result, the API uses: an authorization model, explicit tuples written through the Write API, contextual tuples present in the request, and implicit tuples that exist by virtue of applying set theory (such as `document:2021-budget#viewer@document:2021-budget#viewer`; the set of users who are viewers of `document:2021-budget` are the set of users who are the viewers of `document:2021-budget`).\nAn `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance.\nYou may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`.\nYou may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly.\nThe response will contain the related users in an array in the \"users\" field of the response. These results may include specific objects, usersets \nor type-bound public access. Each of these types of results is encoded in its own type and not represented as a string.In cases where a type-bound public access result is returned (e.g. `user:*`), it cannot be inferred that all subjects\nof that type have a relation to the object; it is possible that negations exist and checks should still be queried\non individual subjects to ensure access to that document.The number of users in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_USERS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_USERS_MAX_RESULTS, whichever is hit first.\nThe returned users will not be sorted, and therefore two identical calls may yield different sets of users.", + "operationId": "ListUsers", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } ], - "default": "TUPLE_OPERATION_WRITE", - "title": "buf:lint:ignore ENUM_ZERO_VALUE_SUFFIX" - }, - "TypeDefinition": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "document" + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListUsersBody" + } + } }, - "relations": { - "type": "object", - "example": { - "reader": { - "union": { - "child": [ - { - "this": {} - }, - { - "computedUserset": { - "object": "", - "relation": "writer" - } - } - ] + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListUsersResponse" } - }, - "writer": { - "this": {} } }, - "additionalProperties": { - "$ref": "#/components/schemas/Userset" - } + "description": "A successful response." }, - "metadata": { - "allOf": [ - { - "$ref": "#/components/schemas/Metadata" - }, - { - "description": "A map whose keys are the name of the relation and whose value is the Metadata for that relation.\nIt also holds information around the module name and source file if this model was constructed\nfrom a modular model." + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } } - ] - } - }, - "required": [ - "type" - ] - }, - "TypeName": { - "type": "string", - "enum": [ - "TYPE_NAME_UNSPECIFIED", - "TYPE_NAME_ANY", - "TYPE_NAME_BOOL", - "TYPE_NAME_STRING", - "TYPE_NAME_INT", - "TYPE_NAME_UINT", - "TYPE_NAME_DOUBLE", - "TYPE_NAME_DURATION", - "TYPE_NAME_TIMESTAMP", - "TYPE_NAME_MAP", - "TYPE_NAME_LIST", - "TYPE_NAME_IPADDRESS" - ], - "default": "TYPE_NAME_UNSPECIFIED" - }, - "TypedWildcard": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "employee" - } - }, - "description": "Type bound public access.\n\nNormally represented using the `:*` syntax\n\n`employee:*` represents every object of type `employee`, including those not currently present in the system\n\nSee https://openfga.dev/docs/concepts#what-is-type-bound-public-access", - "required": [ - "type" - ] - }, - "UnauthenticatedResponse": { - "type": "object", - "example": { - "code": "unauthenticated", - "message": "unauthenticated" - }, - "properties": { - "code": { - "$ref": "#/components/schemas/ErrorCode" + }, + "description": "Request failed due to invalid input." }, - "message": { - "type": "string" - } - } - }, - "UnprocessableContentErrorCode": { - "type": "string", - "enum": [ - "no_throttled_error_code", - "throttled_timeout_error" - ], - "default": "no_throttled_error_code" - }, - "UnprocessableContentMessageResponse": { - "type": "object", - "example": { - "code": "throttled_timeout_error", - "message": "timeout due to throttling on complex request" - }, - "properties": { - "code": { - "$ref": "#/components/schemas/UnprocessableContentErrorCode" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "message": { - "type": "string" - } - } - }, - "User": { - "type": "object", - "properties": { - "object": { - "$ref": "#/components/schemas/Object" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "userset": { - "$ref": "#/components/schemas/UsersetUser" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "wildcard": { - "$ref": "#/components/schemas/TypedWildcard" - } - }, - "description": "User.\n\nRepresents any possible value for a user (subject or principal). Can be a:\n- Specific user object e.g.: 'user:will', 'folder:marketing', 'org:contoso', ...)\n- Specific userset (e.g. 'group:engineering#member')\n- Public-typed wildcard (e.g. 'user:*')\n\nSee https://openfga.dev/docs/concepts#what-is-a-user" - }, - "UserTypeFilter": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "group" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "relation": { - "type": "string", - "example": "member" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "type" + "summary": "List the users matching the provided filter who have a certain relation to a particular type.", + "tags": [ + "Relationship Queries" ] - }, - "Users": { - "type": "object", - "properties": { - "users": { - "type": "array", - "items": { + } + }, + "/stores/{store_id}/read": { + "post": { + "description": "The Read API will return the tuples for a certain store that match a query filter specified in the body of the request. \nThe API doesn't guarantee order by any field. \nIt is different from the `/stores/{store_id}/expand` API in that it only returns relationship tuples that are stored in the system and satisfy the query. \nIn the body:\n1. `tuple_key` is optional. If not specified, it will return all tuples in the store.\n2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can be a full object (e.g., `type:object_id`) or type only (e.g., `type:`).\n3. `tuple_key.user` is mandatory if tuple_key is specified in the case the `tuple_key.object` is a type only. If tuple_key.user is specified, it needs to be a full object (e.g., `type:user_id`).\n## Examples\n### Query for all objects in a type definition\nTo query for all objects that `user:bob` has `reader` relationship in the `document` type definition, call read API with body of\n```json\n{\n \"tuple_key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:\"\n }\n}\n```\nThe API will return tuples and a continuation token, something like\n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `user:bob` has a `reader` relationship with 1 document `document:2021-budget`. Note that this API, unlike the List Objects API, does not evaluate the tuples in the store.\nThe continuation token will be empty if there are no more tuples to query.\n### Query for all stored relationship tuples that have a particular relation and object\nTo query for all users that have `reader` relationship with `document:2021-budget`, call read API with body of \n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\",\n \"relation\": \"reader\"\n }\n}\n```\nThe API will return something like \n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `document:2021-budget` has 1 `reader` (`user:bob`). Note that, even if the model said that all `writers` are also `readers`, the API will not return writers such as `user:anne` because it only returns tuples and does not evaluate them.\n### Query for all users with all relationships for a particular document\nTo query for all users that have any relationship with `document:2021-budget`, call read API with body of \n```json\n{\n \"tuple_key\": {\n \"object\": \"document:2021-budget\"\n }\n}\n```\nThe API will return something like \n```json\n{\n \"tuples\": [\n {\n \"key\": {\n \"user\": \"user:anne\",\n \"relation\": \"writer\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-05T13:42:12.356Z\"\n },\n {\n \"key\": {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n },\n \"timestamp\": \"2021-10-06T15:32:11.128Z\"\n }\n ],\n \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\"\n}\n```\nThis means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1 `writer` (`user:anne`).\n", + "operationId": "Read", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { "type": "string" } - } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadBody" + } + } + }, + "required": true }, - "required": [ - "users" - ] - }, - "Userset": { - "type": "object", - "properties": { - "this": { - "$ref": "#/components/schemas/DirectUserset" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadResponse" + } + } + }, + "description": "A successful response." }, - "computedUserset": { - "$ref": "#/components/schemas/ObjectRelation" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "tupleToUserset": { - "$ref": "#/components/schemas/v1.TupleToUserset" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." }, - "union": { - "$ref": "#/components/schemas/Usersets" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." }, - "intersection": { - "$ref": "#/components/schemas/Usersets" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "difference": { - "$ref": "#/components/schemas/v1.Difference" - } - } - }, - "UsersetTree": { - "type": "object", - "properties": { - "root": { - "$ref": "#/components/schemas/Node" - } - }, - "description": "A UsersetTree contains the result of an Expansion." - }, - "UsersetTree.Difference": { - "type": "object", - "properties": { - "base": { - "$ref": "#/components/schemas/Node" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } + } + }, + "description": "Request was aborted due a transaction conflict." }, - "subtract": { - "$ref": "#/components/schemas/Node" - } - }, - "required": [ - "base", - "subtract" - ] - }, - "UsersetTree.TupleToUserset": { - "type": "object", - "properties": { - "tupleset": { - "type": "string" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "computed": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Computed" - }, - { - "type": "object" + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" } - ] - } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "tupleset", - "computed" + "summary": "Get tuples from the store that matches a query, without following userset rewrite rules", + "tags": [ + "Relationship Tuples" ] - }, - "UsersetUser": { - "type": "object", - "properties": { - "type": { - "type": "string", - "example": "group" - }, - "id": { - "type": "string", - "example": "fga" - }, - "relation": { - "type": "string", - "example": "member" + } + }, + "/stores/{store_id}/streamed-list-objects": { + "post": { + "description": "The Streamed ListObjects API is very similar to the the ListObjects API, with two differences: \n1. Instead of collecting all objects before returning a response, it streams them to the client as they are collected. \n2. The number of results returned is only limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE. \n", + "operationId": "StreamedListObjects", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StreamedListObjectsBody" + } + } + }, + "required": true }, - "description": "Userset.\n\nA set or group of users, represented in the `:#` format\n\n`group:fga#member` represents all members of group FGA, not to be confused by `group:fga` which represents the group itself as a specific object.\n\nSee: https://openfga.dev/docs/modeling/building-blocks/usersets#what-is-a-userset", - "required": [ - "type", - "id", - "relation" - ] - }, - "Usersets": { - "type": "object", - "properties": { - "child": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Userset" - }, - { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "error": { + "$ref": "#/components/schemas/Status" + }, + "result": { + "$ref": "#/components/schemas/StreamedListObjectsResponse" + } + }, + "title": "Stream result of StreamedListObjectsResponse", "type": "object" } - ] - } - } - }, - "required": [ - "child" - ] - }, - "ValidationErrorMessageResponse": { - "type": "object", - "example": { - "code": "validation_error", - "message": "Generic validation error" - }, - "properties": { - "code": { - "$ref": "#/components/schemas/ErrorCode" + } + }, + "description": "A successful response.(streaming responses)" }, - "message": { - "type": "string" - } - } - }, - "Wildcard": { - "type": "object" - }, - "WriteAssertionsBody": { - "type": "object", - "properties": { - "assertions": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/Assertion" - }, - { - "type": "object" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" + } + } + }, + "description": "Not authenticated." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" + } + } + }, + "description": "Forbidden." + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" } - ] + } }, - "maxItems": 100 - } - }, - "required": [ - "assertions" - ] - }, - "WriteAssertionsResponse": { - "type": "object" - }, - "WriteAuthorizationModelBody": { - "type": "object", - "properties": { - "type_definitions": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TypeDefinition" - }, - { - "type": "object" + "description": "Request failed due to incorrect path." + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" } - ] + } }, - "minItems": 1 + "description": "Request was aborted due a transaction conflict." }, - "schema_version": { - "type": "string" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." }, - "conditions": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/Condition" - } + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "type_definitions", - "schema_version" + "summary": "Stream all objects of the given type that the user has a relation with", + "tags": [ + "Relationship Queries" ] - }, - "WriteAuthorizationModelResponse": { - "type": "object", - "properties": { - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" + } + }, + "/stores/{store_id}/write": { + "post": { + "description": "The Write API will transactionally update the tuples for a certain store. Tuples and type definitions allow OpenFGA to determine whether a relationship exists between an object and an user.\nIn the body, `writes` adds new tuples and `deletes` removes existing tuples. When deleting a tuple, any `condition` specified with it is ignored.\nThe API is not idempotent by default: if, later on, you try to add the same tuple key (even if the `condition` is different), or if you try to delete a non-existing tuple, it will throw an error.\nTo allow writes when an identical tuple already exists in the database, set `\"on_duplicate\": \"ignore\"` on the `writes` object.\nTo allow deletes when a tuple was already removed from the database, set `\"on_missing\": \"ignore\"` on the `deletes` object.\nIf a Write request contains both idempotent (ignore) and non-idempotent (error) operations, the most restrictive action (error) will take precedence. If a condition fails for a sub-request with an error flag, the entire transaction will be rolled back. This gives developers explicit control over the atomicity of the requests.\nThe API will not allow you to write tuples such as `document:2021-budget#viewer@document:2021-budget#viewer`, because they are implicit.\nAn `authorization_model_id` may be specified in the body. If it is, it will be used to assert that each written tuple (not deleted) is valid for the model specified. If it is not specified, the latest authorization model ID will be used.\n## Example\n### Adding relationships\nTo add `user:anne` as a `writer` for `document:2021-budget`, call write API with the following \n```json\n{\n \"writes\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:anne\",\n \"relation\": \"writer\",\n \"object\": \"document:2021-budget\"\n }\n ],\n \"on_duplicate\": \"ignore\"\n },\n \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\"\n}\n```\n### Removing relationships\nTo remove `user:bob` as a `reader` for `document:2021-budget`, call write API with the following \n```json\n{\n \"deletes\": {\n \"tuple_keys\": [\n {\n \"user\": \"user:bob\",\n \"relation\": \"reader\",\n \"object\": \"document:2021-budget\"\n }\n ],\n \"on_missing\": \"ignore\"\n }\n}\n```\n", + "operationId": "Write", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteBody" + } + } + }, + "required": true }, - "required": [ - "authorization_model_id" - ] - }, - "WriteBody": { - "type": "object", - "properties": { - "writes": { - "$ref": "#/components/schemas/WriteRequestWrites" + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResponse" + } + } + }, + "description": "A successful response." }, - "deletes": { - "$ref": "#/components/schemas/WriteRequestDeletes" + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorMessageResponse" + } + } + }, + "description": "Request failed due to invalid input." }, - "authorization_model_id": { - "type": "string", - "example": "01G5JAVJ41T49E9TT3SKVS7X1J" - } - } - }, - "WriteRequestDeletes": { - "type": "object", - "properties": { - "tuple_keys": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TupleKeyWithoutCondition" - }, - { - "type": "object" + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthenticatedResponse" } - ] + } }, - "minItems": 1 + "description": "Not authenticated." }, - "on_missing": { - "type": "string", - "example": "ignore", - "enum": [ - "error", - "ignore" - ], - "default": "error", - "description": "On 'error', the API returns an error when deleting a tuple that does not exist. On 'ignore', deletes of non-existent tuples are treated as no-ops." - } - }, - "required": [ - "tuple_keys" - ] - }, - "WriteRequestWrites": { - "type": "object", - "properties": { - "tuple_keys": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/components/schemas/TupleKey" - }, - { - "type": "object" + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForbiddenResponse" } - ] + } }, - "minItems": 1 + "description": "Forbidden." }, - "on_duplicate": { - "type": "string", - "example": "ignore", - "enum": [ - "error", - "ignore" - ], - "default": "error", - "description": "On 'error' ( or unspecified ), the API returns an error if an identical tuple already exists. On 'ignore', identical writes are treated as no-ops (matching on user, relation, object, and RelationshipCondition)." - } - }, - "required": [ - "tuple_keys" - ] - }, - "WriteResponse": { - "type": "object" - }, - "v1.Difference": { - "type": "object", - "properties": { - "base": { - "$ref": "#/components/schemas/Userset" + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PathUnknownErrorMessageResponse" + } + } + }, + "description": "Request failed due to incorrect path." }, - "subtract": { - "$ref": "#/components/schemas/Userset" - } - }, - "required": [ - "base", - "subtract" - ] - }, - "v1.TupleToUserset": { - "type": "object", - "properties": { - "tupleset": { - "allOf": [ - { - "$ref": "#/components/schemas/ObjectRelation" - }, - { - "title": "The target object/relation" + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AbortedMessageResponse" + } } - ] + }, + "description": "Request was aborted due a transaction conflict." }, - "computedUserset": { - "$ref": "#/components/schemas/ObjectRelation" + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnprocessableContentMessageResponse" + } + } + }, + "description": "Request timed out due to excessive request throttling." + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InternalErrorMessageResponse" + } + } + }, + "description": "Request failed due to internal server error." } }, - "required": [ - "tupleset", - "computedUserset" + "summary": "Add or delete tuples from the store", + "tags": [ + "Relationship Tuples" ] } } - } + }, + "tags": [ + { + "name": "AuthZenService" + }, + { + "name": "OpenFGAService" + } + ] } diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index f94da267..00000000 --- a/package-lock.json +++ /dev/null @@ -1,493 +0,0 @@ -{ - "name": "@openfga/api", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@openfga/api", - "devDependencies": { - "swagger2openapi": "7.0.8" - } - }, - "node_modules/@exodus/schemasafe": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz", - "integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==", - "dev": true, - "license": "MIT" - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/call-me-maybe": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", - "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/es6-promise": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", - "integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==", - "dev": true, - "license": "MIT" - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/fast-safe-stringify": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true, - "license": "MIT" - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/http2-client": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz", - "integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==", - "dev": true, - "license": "MIT" - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-fetch-h2": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz", - "integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==", - "dev": true, - "license": "MIT", - "dependencies": { - "http2-client": "^1.2.5" - }, - "engines": { - "node": "4.x || >=6.0.0" - } - }, - "node_modules/node-readfiles": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz", - "integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es6-promise": "^3.2.1" - } - }, - "node_modules/oas-kit-common": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz", - "integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "fast-safe-stringify": "^2.0.7" - } - }, - "node_modules/oas-linter": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz", - "integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@exodus/schemasafe": "^1.0.0-rc.2", - "should": "^13.2.1", - "yaml": "^1.10.0" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-resolver": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz", - "integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "node-fetch-h2": "^2.3.0", - "oas-kit-common": "^1.0.8", - "reftools": "^1.1.9", - "yaml": "^1.10.0", - "yargs": "^17.0.1" - }, - "bin": { - "resolve": "resolve.js" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-schema-walker": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz", - "integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==", - "dev": true, - "license": "BSD-3-Clause", - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/oas-validator": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz", - "integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "call-me-maybe": "^1.0.1", - "oas-kit-common": "^1.0.8", - "oas-linter": "^3.2.2", - "oas-resolver": "^2.5.6", - "oas-schema-walker": "^1.1.5", - "reftools": "^1.1.9", - "should": "^13.2.1", - "yaml": "^1.10.0" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/reftools": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz", - "integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==", - "dev": true, - "license": "BSD-3-Clause", - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/should": { - "version": "13.2.3", - "resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz", - "integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-equal": "^2.0.0", - "should-format": "^3.0.3", - "should-type": "^1.4.0", - "should-type-adaptors": "^1.0.1", - "should-util": "^1.0.0" - } - }, - "node_modules/should-equal": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz", - "integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-type": "^1.4.0" - } - }, - "node_modules/should-format": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz", - "integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-type": "^1.3.0", - "should-type-adaptors": "^1.0.1" - } - }, - "node_modules/should-type": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz", - "integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/should-type-adaptors": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz", - "integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==", - "dev": true, - "license": "MIT", - "dependencies": { - "should-type": "^1.3.0", - "should-util": "^1.0.0" - } - }, - "node_modules/should-util": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz", - "integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==", - "dev": true, - "license": "MIT" - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/swagger2openapi": { - "version": "7.0.8", - "resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz", - "integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "call-me-maybe": "^1.0.1", - "node-fetch": "^2.6.1", - "node-fetch-h2": "^2.3.0", - "node-readfiles": "^0.2.0", - "oas-kit-common": "^1.0.8", - "oas-resolver": "^2.5.6", - "oas-schema-walker": "^1.1.5", - "oas-validator": "^5.0.8", - "reftools": "^1.1.9", - "yaml": "^1.10.0", - "yargs": "^17.0.1" - }, - "bin": { - "boast": "boast.js", - "oas-validate": "oas-validate.js", - "swagger2openapi": "swagger2openapi.js" - }, - "funding": { - "url": "https://github.com/Mermade/oas-kit?sponsor=1" - } - }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true, - "license": "MIT" - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/yaml": { - "version": "1.10.3", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", - "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, - "node_modules/yargs": { - "version": "17.7.3", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", - "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index e9eb112b..00000000 --- a/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@openfga/api", - "private": true, - "scripts": { - "generate:openapiv3": "node scripts/generate_openapiv3.js" - }, - "devDependencies": { - "swagger2openapi": "7.0.8" - } -} diff --git a/scripts/generate_openapiv3.js b/scripts/generate_openapiv3.js deleted file mode 100644 index 19b54ad5..00000000 --- a/scripts/generate_openapiv3.js +++ /dev/null @@ -1,478 +0,0 @@ -#!/usr/bin/env node - -"use strict"; - -const crypto = require("crypto"); -const fs = require("fs/promises"); -const path = require("path"); -const converter = require("swagger2openapi"); -const converterPackage = require("swagger2openapi/package.json"); - -const HTTP_METHODS = new Set([ - "delete", - "get", - "head", - "options", - "patch", - "post", - "put", - "trace", -]); -const REQUIRED_CONVERTER_VERSION = "7.0.8"; -const ROOT = path.resolve(__dirname, ".."); -const OPENAPI_V2_PATH = path.join( - ROOT, - "docs", - "openapiv2", - "apidocs.swagger.json", -); -const OPENAPI_V3_PATH = path.join( - ROOT, - "docs", - "openapiv3", - "apidocs.openapi.json", -); - -function invariant(condition, message) { - if (!condition) { - throw new Error(message); - } -} - -function isObject(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -function requireObject(value, label) { - invariant(isObject(value), `${label} must be an object`); -} - -function hasOwn(value, key) { - return Object.prototype.hasOwnProperty.call(value, key); -} - -function hash(value) { - return crypto.createHash("sha256").update(value).digest("hex"); -} - -function canonicalJson(value) { - if (Array.isArray(value)) { - return `[${value.map(canonicalJson).join(",")}]`; - } - if (isObject(value)) { - return `{${Object.keys(value) - .sort() - .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`) - .join(",")}}`; - } - return JSON.stringify(value); -} - -function walk(value, visit, location = "#") { - if (Array.isArray(value)) { - value.forEach((item, index) => walk(item, visit, `${location}/${index}`)); - return; - } - if (!isObject(value)) { - return; - } - - visit(value, location); - for (const [key, child] of Object.entries(value)) { - const escapedKey = key.replaceAll("~", "~0").replaceAll("/", "~1"); - walk(child, visit, `${location}/${escapedKey}`); - } -} - -function validateRootShapeV2(document) { - requireObject(document, "OpenAPI v2 document"); - invariant(document.swagger === "2.0", 'OpenAPI v2 root "swagger" must be "2.0"'); - invariant(!hasOwn(document, "openapi"), 'OpenAPI v2 root must not contain "openapi"'); - requireObject(document.info, "OpenAPI v2 info"); - requireObject(document.paths, "OpenAPI v2 paths"); - requireObject(document.definitions, "OpenAPI v2 definitions"); - invariant(Array.isArray(document.tags), "OpenAPI v2 tags must be an array"); -} - -function validateRootShapeV3(document) { - requireObject(document, "OpenAPI v3 document"); - invariant(document.openapi === "3.0.3", 'OpenAPI v3 root "openapi" must be "3.0.3"'); - requireObject(document.info, "OpenAPI v3 info"); - requireObject(document.paths, "OpenAPI v3 paths"); - requireObject(document.components, "OpenAPI v3 components"); - requireObject(document.components.schemas, "OpenAPI v3 component schemas"); - invariant(Array.isArray(document.tags), "OpenAPI v3 tags must be an array"); - - for (const key of [ - "swagger", - "definitions", - "parameters", - "responses", - "securityDefinitions", - "schemes", - "consumes", - "produces", - ]) { - invariant(!hasOwn(document, key), `OpenAPI v3 root contains Swagger-only key "${key}"`); - } -} - -function collectParameters(pathItem, operation) { - return [...(pathItem.parameters || []), ...(operation.parameters || [])]; -} - -function collectOperations(document, version) { - const operations = new Map(); - const operationIds = new Map(); - - for (const [apiPath, pathItem] of Object.entries(document.paths)) { - invariant(apiPath.startsWith("/"), `${version} path "${apiPath}" must start with "/"`); - requireObject(pathItem, `${version} path item ${apiPath}`); - - for (const [method, operation] of Object.entries(pathItem)) { - if (!HTTP_METHODS.has(method)) { - continue; - } - - requireObject(operation, `${version} operation ${method.toUpperCase()} ${apiPath}`); - invariant( - typeof operation.operationId === "string" && operation.operationId.length > 0, - `${version} operation ${method.toUpperCase()} ${apiPath} must have an operationId`, - ); - invariant( - !operationIds.has(operation.operationId), - `${version} operationId "${operation.operationId}" is duplicated`, - ); - operationIds.set(operation.operationId, `${method.toUpperCase()} ${apiPath}`); - requireObject( - operation.responses, - `${version} responses for ${method.toUpperCase()} ${apiPath}`, - ); - - const responseCodes = Object.keys(operation.responses) - .filter((code) => !code.startsWith("x-")) - .sort(); - invariant( - responseCodes.length > 0, - `${version} operation ${method.toUpperCase()} ${apiPath} must define responses`, - ); - - operations.set(`${apiPath}\t${method}`, { - apiPath, - method, - operation, - pathItem, - responseCodes, - }); - } - } - - return operations; -} - -function validateInternalRefs(document, version) { - let count = 0; - - walk(document, (value, location) => { - if (!hasOwn(value, "$ref")) { - return; - } - - count += 1; - const ref = value.$ref; - invariant(typeof ref === "string", `${version} $ref at ${location} must be a string`); - invariant( - ref === "#" || ref.startsWith("#/"), - `${version} $ref at ${location} must be internal: ${ref}`, - ); - - let target = document; - if (ref !== "#") { - const tokens = ref - .slice(2) - .split("/") - .map((token) => - decodeURIComponent(token).replaceAll("~1", "/").replaceAll("~0", "~"), - ); - for (const token of tokens) { - invariant( - isObject(target) || Array.isArray(target), - `${version} $ref at ${location} does not resolve: ${ref}`, - ); - invariant( - hasOwn(target, token), - `${version} $ref at ${location} does not resolve: ${ref}`, - ); - target = target[token]; - } - } - }); - - return count; -} - -function collectExamples(document) { - const examples = new Map(); - - walk(document, (value) => { - if (!hasOwn(value, "example")) { - return; - } - const example = canonicalJson(value.example); - examples.set(example, (examples.get(example) || 0) + 1); - }); - - return examples; -} - -function validateServiceCoverage(document, operations, version) { - const rootTagNames = new Set(document.tags.map((tag) => tag.name)); - invariant(rootTagNames.has("OpenFGAService"), `${version} is missing OpenFGAService tag`); - invariant(rootTagNames.has("AuthZenService"), `${version} is missing AuthZenService tag`); - - let authZenOperations = 0; - let openFgaOperations = 0; - for (const { operation } of operations.values()) { - invariant( - Array.isArray(operation.tags), - `${version} ${operation.operationId} tags must be an array`, - ); - if (operation.tags.includes("AuthZenService")) { - authZenOperations += 1; - } else { - openFgaOperations += 1; - } - invariant( - !operation.operationId.includes("UpdateStore"), - `${version} must not expose the unimplemented UpdateStore operation`, - ); - } - - invariant(authZenOperations > 0, `${version} must contain AuthZen operations`); - invariant(openFgaOperations > 0, `${version} must contain OpenFGA operations`); -} - -function validateContentFree204(operations, version) { - for (const { apiPath, method, operation } of operations.values()) { - const response = operation.responses["204"]; - if (!response) { - continue; - } - requireObject( - response, - `${version} 204 response for ${method.toUpperCase()} ${apiPath}`, - ); - if (version === "OpenAPI v2") { - invariant( - !hasOwn(response, "schema"), - `${version} 204 response for ${method.toUpperCase()} ${apiPath} must not have a schema`, - ); - } else { - invariant( - !hasOwn(response, "content"), - `${version} 204 response for ${method.toUpperCase()} ${apiPath} must not have content`, - ); - } - } -} - -function validateNoSwaggerOnlyV3(document, operations) { - for (const { apiPath, method, operation, pathItem } of operations.values()) { - for (const key of ["consumes", "produces", "schemes"]) { - invariant( - !hasOwn(operation, key), - `OpenAPI v3 operation ${method.toUpperCase()} ${apiPath} contains Swagger-only key "${key}"`, - ); - } - - for (const parameter of collectParameters(pathItem, operation)) { - requireObject( - parameter, - `OpenAPI v3 parameter for ${method.toUpperCase()} ${apiPath}`, - ); - invariant( - parameter.in !== "body" && parameter.in !== "formData", - `OpenAPI v3 operation ${method.toUpperCase()} ${apiPath} contains a Swagger-only ${parameter.in} parameter`, - ); - for (const key of ["type", "format", "items", "collectionFormat"]) { - invariant( - !hasOwn(parameter, key), - `OpenAPI v3 parameter for ${method.toUpperCase()} ${apiPath} contains Swagger-only key "${key}"`, - ); - } - } - - for (const [code, response] of Object.entries(operation.responses)) { - if (code.startsWith("x-")) { - continue; - } - requireObject( - response, - `OpenAPI v3 response ${code} for ${method.toUpperCase()} ${apiPath}`, - ); - for (const key of ["schema", "examples"]) { - invariant( - !hasOwn(response, key), - `OpenAPI v3 response ${code} for ${method.toUpperCase()} ${apiPath} contains Swagger-only key "${key}"`, - ); - } - } - } - - walk(document, (value, location) => { - for (const key of Object.keys(value)) { - invariant( - !key.toLowerCase().startsWith("x-mintlify"), - `OpenAPI v3 contains Mintlify-specific extension "${key}" at ${location}`, - ); - } - if (hasOwn(value, "$ref")) { - invariant( - !value.$ref.startsWith("#/definitions/"), - `OpenAPI v3 contains a Swagger-only definition reference at ${location}`, - ); - } - }); -} - -function validateParity(v2, v3, v2Operations, v3Operations) { - invariant( - canonicalJson(Object.keys(v2.paths).sort()) === - canonicalJson(Object.keys(v3.paths).sort()), - "API paths changed during OpenAPI v3 conversion", - ); - invariant( - v2Operations.size === v3Operations.size, - `operation count changed from ${v2Operations.size} to ${v3Operations.size}`, - ); - - for (const [key, v2Entry] of v2Operations) { - const v3Entry = v3Operations.get(key); - invariant( - v3Entry, - `OpenAPI v3 is missing ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, - ); - - for (const property of ["operationId", "summary", "description", "tags"]) { - invariant( - canonicalJson(v2Entry.operation[property]) === - canonicalJson(v3Entry.operation[property]), - `${property} changed for ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, - ); - } - invariant( - canonicalJson(v2Entry.responseCodes) === canonicalJson(v3Entry.responseCodes), - `response codes changed for ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, - ); - for (const code of v2Entry.responseCodes) { - invariant( - v2Entry.operation.responses[code].description === - v3Entry.operation.responses[code].description, - `response ${code} description changed for ${v2Entry.method.toUpperCase()} ${v2Entry.apiPath}`, - ); - } - } - - const v2Schemas = Object.keys(v2.definitions).sort(); - const v3Schemas = Object.keys(v3.components.schemas).sort(); - invariant( - canonicalJson(v2Schemas) === canonicalJson(v3Schemas), - "component schema names changed during OpenAPI v3 conversion", - ); - invariant( - canonicalJson(v2.tags) === canonicalJson(v3.tags), - "root tags changed during conversion", - ); - - const v2Examples = collectExamples(v2); - const v3Examples = collectExamples(v3); - invariant( - canonicalJson(Object.fromEntries(v2Examples)) === - canonicalJson(Object.fromEntries(v3Examples)), - "examples changed during OpenAPI v3 conversion", - ); - - if (!hasOwn(v2, "host") && !hasOwn(v2, "basePath")) { - invariant(!hasOwn(v3, "servers"), "OpenAPI v3 conversion invented servers"); - } - if (!hasOwn(v2, "securityDefinitions")) { - invariant( - !hasOwn(v3.components, "securitySchemes"), - "OpenAPI v3 conversion invented security schemes", - ); - } - if (!hasOwn(v2, "security")) { - invariant(!hasOwn(v3, "security"), "OpenAPI v3 conversion invented root security policy"); - } -} - -async function writeAtomically(filename, contents) { - await fs.mkdir(path.dirname(filename), { recursive: true }); - const temporaryFilename = path.join( - path.dirname(filename), - `.${path.basename(filename)}.${process.pid}.tmp`, - ); - - try { - await fs.writeFile(temporaryFilename, contents, { flag: "wx" }); - await fs.rename(temporaryFilename, filename); - } finally { - await fs.rm(temporaryFilename, { force: true }); - } -} - -async function main() { - invariant( - converterPackage.version === REQUIRED_CONVERTER_VERSION, - `swagger2openapi ${REQUIRED_CONVERTER_VERSION} is required; found ${converterPackage.version}`, - ); - - const sourceBytes = await fs.readFile(OPENAPI_V2_PATH); - const sourceHash = hash(sourceBytes); - const openapiV2 = JSON.parse(sourceBytes.toString("utf8")); - validateRootShapeV2(openapiV2); - const v2Operations = collectOperations(openapiV2, "OpenAPI v2"); - validateServiceCoverage(openapiV2, v2Operations, "OpenAPI v2"); - validateContentFree204(v2Operations, "OpenAPI v2"); - validateInternalRefs(openapiV2, "OpenAPI v2"); - - const conversion = await converter.convertObj(openapiV2, { - refSiblings: "allOf", - targetVersion: "3.0.3", - }); - invariant(conversion.patches === 0, "swagger2openapi unexpectedly patched the v2 input"); - invariant( - !conversion.warnings || conversion.warnings.length === 0, - "swagger2openapi produced conversion warnings", - ); - - const openapiV3 = conversion.openapi; - validateRootShapeV3(openapiV3); - const v3Operations = collectOperations(openapiV3, "OpenAPI v3"); - validateNoSwaggerOnlyV3(openapiV3, v3Operations); - validateServiceCoverage(openapiV3, v3Operations, "OpenAPI v3"); - validateContentFree204(v3Operations, "OpenAPI v3"); - validateInternalRefs(openapiV3, "OpenAPI v3"); - validateParity(openapiV2, openapiV3, v2Operations, v3Operations); - - const sourceBytesAfterConversion = await fs.readFile(OPENAPI_V2_PATH); - invariant( - sourceHash === hash(sourceBytesAfterConversion) && - sourceBytes.equals(sourceBytesAfterConversion), - "OpenAPI v2 artifact changed during OpenAPI v3 conversion", - ); - - await writeAtomically(OPENAPI_V3_PATH, `${JSON.stringify(openapiV3, null, 2)}\n`); - - console.log( - `Generated OpenAPI 3.0.3: ${Object.keys(openapiV3.paths).length} paths, ` + - `${v3Operations.size} operations, ${Object.keys(openapiV3.components.schemas).length} schemas, ` + - `${[...collectExamples(openapiV3).values()].reduce((sum, count) => sum + count, 0)} examples`, - ); - console.log(`OpenAPI v2 SHA-256 unchanged: ${sourceHash}`); -} - -main().catch((error) => { - console.error(error.stack || error.message); - process.exitCode = 1; -}); diff --git a/tools/openapiv3/go.mod b/tools/openapiv3/go.mod new file mode 100644 index 00000000..c732842d --- /dev/null +++ b/tools/openapiv3/go.mod @@ -0,0 +1,17 @@ +module github.com/openfga/api/tools/openapiv3 + +go 1.25.0 + +toolchain go1.26.6 + +require github.com/getkin/kin-openapi v0.149.0 + +require ( + github.com/go-openapi/jsonpointer v0.22.5 // indirect + github.com/go-openapi/swag/jsonname v0.25.5 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/oasdiff/yaml v0.1.1 // indirect + github.com/oasdiff/yaml3 v0.0.14 // indirect + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect + golang.org/x/text v0.39.0 // indirect +) diff --git a/tools/openapiv3/go.sum b/tools/openapiv3/go.sum new file mode 100644 index 00000000..92db867b --- /dev/null +++ b/tools/openapiv3/go.sum @@ -0,0 +1,36 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/getkin/kin-openapi v0.149.0 h1:ZbhmVJ4yq5RZDUsyP8lcBcGMsjsaTqXEFt6isdtMDfA= +github.com/getkin/kin-openapi v0.149.0/go.mod h1:1+BHDzstro+P5CKtPy1X4PfofnFgmRe6uvMy9+r9fKY= +github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA= +github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0= +github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo= +github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU= +github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM= +github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY= +github.com/oasdiff/yaml v0.1.1/go.mod h1:EYJNoyktvWMJ0Hmhx+6qTaqMOsalUaRGT8Sj1hNcegU= +github.com/oasdiff/yaml3 v0.0.14 h1:aLJee3hxBK2H5wdXd9iPcIXb93Nty1Ge0pT171eHtkw= +github.com/oasdiff/yaml3 v0.0.14/go.mod h1:csto2xfDjYccdUn/yw/bPjj/cYTdp6HtFA0J4TWG+gg= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus= +golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/tools/openapiv3/main.go b/tools/openapiv3/main.go new file mode 100644 index 00000000..d1366800 --- /dev/null +++ b/tools/openapiv3/main.go @@ -0,0 +1,1301 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/getkin/kin-openapi/openapi2" + "github.com/getkin/kin-openapi/openapi2conv" +) + +const ( + expectedInternalRefs = 330 + expectedRefSiblings = 43 + openAPIV2DefaultPath = "../../docs/openapiv2/apidocs.swagger.json" + openAPIV3DefaultPath = "../../docs/openapiv3/apidocs.openapi.json" + openAPIV3TargetVersion = "3.0.3" +) + +var httpMethods = map[string]struct{}{ + "delete": {}, + "get": {}, + "head": {}, + "options": {}, + "patch": {}, + "post": {}, + "put": {}, + "trace": {}, +} + +type object = map[string]any + +type operationInfo struct { + apiPath string + method string + operation object + pathItem object + responseCodes []string +} + +type normalizationStats struct { + removedOriginalParamNames int + restoredRequiredFalse int +} + +type generationSummary struct { + examples int + operations int + paths int + refs int + requestBodies int + schemas int +} + +func main() { + sourcePath := flag.String("source", openAPIV2DefaultPath, "path to the finalized Swagger 2 document") + outputPath := flag.String("output", openAPIV3DefaultPath, "path for the generated OpenAPI 3 document") + flag.Parse() + + summary, sourceHash, err := run(*sourcePath, *outputPath) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + + fmt.Printf( + "Generated OpenAPI %s: %d paths, %d operations, %d schemas, %d examples, %d internal refs\n", + openAPIV3TargetVersion, + summary.paths, + summary.operations, + summary.schemas, + summary.examples, + summary.refs, + ) + fmt.Printf("OpenAPI v2 SHA-256 unchanged: %s\n", sourceHash) +} + +func run(sourcePath, outputPath string) (generationSummary, string, error) { + sourceBytes, err := os.ReadFile(sourcePath) + if err != nil { + return generationSummary{}, "", fmt.Errorf("read OpenAPI v2 source: %w", err) + } + sourceHash := hash(sourceBytes) + + output, summary, err := generate(sourceBytes) + if err != nil { + return generationSummary{}, "", err + } + + sourceBytesAfterConversion, err := os.ReadFile(sourcePath) + if err != nil { + return generationSummary{}, "", fmt.Errorf("re-read OpenAPI v2 source: %w", err) + } + if sourceHash != hash(sourceBytesAfterConversion) || !bytes.Equal(sourceBytes, sourceBytesAfterConversion) { + return generationSummary{}, "", errors.New("OpenAPI v2 artifact changed during OpenAPI v3 conversion") + } + + if err := writeAtomically(outputPath, output); err != nil { + return generationSummary{}, "", err + } + return summary, sourceHash, nil +} + +func generate(sourceBytes []byte) ([]byte, generationSummary, error) { + openAPIV2, err := decodeObject(sourceBytes) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("decode OpenAPI v2 source: %w", err) + } + v2Operations, err := validateOpenAPIV2(openAPIV2) + if err != nil { + return nil, generationSummary{}, err + } + expectedRequestBodies := countBodyParameters(v2Operations) + expectedRequiredFalse := countOptionalParameters(v2Operations) + + normalizedV2, err := decodeObject(sourceBytes) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("decode OpenAPI v2 source for normalization: %w", err) + } + normalizedValue, refSiblingCount, err := normalizeRefSiblings(normalizedV2) + if err != nil { + return nil, generationSummary{}, err + } + if refSiblingCount != expectedRefSiblings { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v2 ref sibling count changed from %d to %d", + expectedRefSiblings, + refSiblingCount, + ) + } + normalizedV2 = normalizedValue.(object) + if countRefSiblings(normalizedV2) != 0 { + return nil, generationSummary{}, errors.New("OpenAPI v2 ref sibling normalization was incomplete") + } + + normalizedBytes, err := marshalJSON(normalizedV2, false) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("encode normalized OpenAPI v2 source: %w", err) + } + var typedV2 openapi2.T + if err := json.Unmarshal(normalizedBytes, &typedV2); err != nil { + return nil, generationSummary{}, fmt.Errorf("decode normalized OpenAPI v2 source: %w", err) + } + + typedV3, err := openapi2conv.ToV3(&typedV2) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("convert OpenAPI v2 to v3: %w", err) + } + convertedBytes, err := json.Marshal(typedV3) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("encode converted OpenAPI v3 document: %w", err) + } + openAPIV3, err := decodeObject(convertedBytes) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("decode converted OpenAPI v3 document: %w", err) + } + + normalization, err := normalizeOutput(openAPIV3) + if err != nil { + return nil, generationSummary{}, err + } + if normalization.removedOriginalParamNames != expectedRequestBodies { + return nil, generationSummary{}, fmt.Errorf( + "converter-only request body extension count changed from %d to %d", + expectedRequestBodies, + normalization.removedOriginalParamNames, + ) + } + if normalization.restoredRequiredFalse != expectedRequiredFalse { + return nil, generationSummary{}, fmt.Errorf( + "optional parameter normalization count changed from %d to %d", + expectedRequiredFalse, + normalization.restoredRequiredFalse, + ) + } + + summary, err := validateConverted(openAPIV2, normalizedV2, openAPIV3, v2Operations) + if err != nil { + return nil, generationSummary{}, err + } + + output, err := marshalJSON(openAPIV3, true) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("encode final OpenAPI v3 document: %w", err) + } + return output, summary, nil +} + +func validateConverted( + originalV2 object, + normalizedV2 object, + openAPIV3 object, + v2Operations map[string]operationInfo, +) (generationSummary, error) { + v3Operations, summary, err := validateOpenAPIV3(openAPIV3) + if err != nil { + return generationSummary{}, err + } + if err := validateParity(originalV2, normalizedV2, openAPIV3, v2Operations, v3Operations); err != nil { + return generationSummary{}, err + } + return summary, nil +} + +func validateOpenAPIV2(document object) (map[string]operationInfo, error) { + if document["swagger"] != "2.0" { + return nil, errors.New(`OpenAPI v2 root "swagger" must be "2.0"`) + } + if _, exists := document["openapi"]; exists { + return nil, errors.New(`OpenAPI v2 root must not contain "openapi"`) + } + if _, err := requiredObject(document, "info", "OpenAPI v2"); err != nil { + return nil, err + } + paths, err := requiredObject(document, "paths", "OpenAPI v2") + if err != nil { + return nil, err + } + definitions, err := requiredObject(document, "definitions", "OpenAPI v2") + if err != nil { + return nil, err + } + if _, err := requiredArray(document, "tags", "OpenAPI v2"); err != nil { + return nil, err + } + operations, err := collectOperations(document, "OpenAPI v2") + if err != nil { + return nil, err + } + if err := validateServiceCoverage(document, operations, "OpenAPI v2"); err != nil { + return nil, err + } + if err := validateContentFree204(operations, "OpenAPI v2"); err != nil { + return nil, err + } + refCount, err := validateInternalRefs(document, "OpenAPI v2") + if err != nil { + return nil, err + } + if refCount != expectedInternalRefs { + return nil, fmt.Errorf( + "OpenAPI v2 internal ref count changed from %d to %d", + expectedInternalRefs, + refCount, + ) + } + _, exampleCount, err := collectExamples(document) + if err != nil { + return nil, err + } + if len(paths) == 0 || len(definitions) == 0 || len(operations) == 0 || exampleCount == 0 { + return nil, errors.New("OpenAPI v2 document must contain paths, operations, schemas, and examples") + } + return operations, nil +} + +func validateOpenAPIV3(document object) (map[string]operationInfo, generationSummary, error) { + if document["openapi"] != openAPIV3TargetVersion { + return nil, generationSummary{}, fmt.Errorf( + `OpenAPI v3 root "openapi" must be %q`, + openAPIV3TargetVersion, + ) + } + if _, err := requiredObject(document, "info", "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + paths, err := requiredObject(document, "paths", "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + components, err := requiredObject(document, "components", "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + schemas, err := requiredObject(components, "schemas", "OpenAPI v3 components") + if err != nil { + return nil, generationSummary{}, err + } + if _, err := requiredArray(document, "tags", "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + for _, key := range []string{ + "swagger", + "definitions", + "parameters", + "responses", + "securityDefinitions", + "schemes", + "consumes", + "produces", + } { + if _, exists := document[key]; exists { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v3 root contains Swagger-only key %q", + key, + ) + } + } + operations, err := collectOperations(document, "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + if err := validateNoSwaggerOnlyV3(document, operations); err != nil { + return nil, generationSummary{}, err + } + if err := validateServiceCoverage(document, operations, "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + if err := validateContentFree204(operations, "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + refCount, err := validateInternalRefs(document, "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + if refCount != expectedInternalRefs { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v3 internal ref count changed from %d to %d", + expectedInternalRefs, + refCount, + ) + } + if siblingCount := countRefSiblings(document); siblingCount != 0 { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v3 contains %d ref objects with siblings", + siblingCount, + ) + } + _, exampleCount, err := collectExamples(document) + if err != nil { + return nil, generationSummary{}, err + } + requestBodyCount := 0 + for _, operation := range operations { + if _, exists := operation.operation["requestBody"]; exists { + requestBodyCount++ + } + } + return operations, generationSummary{ + examples: exampleCount, + operations: len(operations), + paths: len(paths), + refs: refCount, + requestBodies: requestBodyCount, + schemas: len(schemas), + }, nil +} + +func validateParity( + originalV2 object, + normalizedV2 object, + openAPIV3 object, + v2Operations map[string]operationInfo, + v3Operations map[string]operationInfo, +) error { + v2Paths := sortedKeys(originalV2["paths"].(object)) + v3Paths := sortedKeys(openAPIV3["paths"].(object)) + if !equalJSON(v2Paths, v3Paths) { + return errors.New("API paths changed during OpenAPI v3 conversion") + } + if len(v2Operations) != len(v3Operations) { + return fmt.Errorf( + "operation count changed from %d to %d", + len(v2Operations), + len(v3Operations), + ) + } + if len(originalV2["paths"].(object)) != len(openAPIV3["paths"].(object)) { + return errors.New("path count changed during OpenAPI v3 conversion") + } + + normalizedOperations, err := collectOperations(normalizedV2, "normalized OpenAPI v2") + if err != nil { + return err + } + rootConsumes := stringArray(normalizedV2["consumes"]) + rootProduces := stringArray(normalizedV2["produces"]) + for key, v2Entry := range v2Operations { + v3Entry, exists := v3Operations[key] + if !exists { + return fmt.Errorf( + "OpenAPI v3 is missing %s %s", + strings.ToUpper(v2Entry.method), + v2Entry.apiPath, + ) + } + for _, property := range []string{"operationId", "summary", "description", "tags"} { + if !equalJSON(v2Entry.operation[property], v3Entry.operation[property]) { + return fmt.Errorf( + "%s changed for %s %s", + property, + strings.ToUpper(v2Entry.method), + v2Entry.apiPath, + ) + } + } + if !equalJSON(v2Entry.responseCodes, v3Entry.responseCodes) { + return fmt.Errorf( + "response codes changed for %s %s", + strings.ToUpper(v2Entry.method), + v2Entry.apiPath, + ) + } + + normalizedEntry := normalizedOperations[key] + if err := validateParameterParity(normalizedEntry, v3Entry); err != nil { + return err + } + if err := validateRequestBodyParity(normalizedEntry, v3Entry, rootConsumes); err != nil { + return err + } + if err := validateResponseParity(normalizedEntry, v3Entry, rootProduces); err != nil { + return err + } + } + + v2Examples, _, err := collectExamples(originalV2) + if err != nil { + return err + } + v3Examples, _, err := collectExamples(openAPIV3) + if err != nil { + return err + } + if !equalJSON(v2Examples, v3Examples) { + return errors.New("examples changed during OpenAPI v3 conversion") + } + + v2Definitions := normalizedV2["definitions"].(object) + v3Components := openAPIV3["components"].(object) + v3Schemas := v3Components["schemas"].(object) + expectedSchemas := rewriteSchemaRefs(v2Definitions) + if !equalJSON(expectedSchemas, v3Schemas) { + return errors.New("component schemas changed during OpenAPI v3 conversion") + } + if len(v2Definitions) != len(v3Schemas) { + return errors.New("component schema count changed during OpenAPI v3 conversion") + } + if !equalJSON(originalV2["tags"], openAPIV3["tags"]) { + return errors.New("root tags changed during OpenAPI v3 conversion") + } + if !equalJSON(originalV2["info"], openAPIV3["info"]) { + return errors.New("API information changed during OpenAPI v3 conversion") + } + + if !hasAnyKey(originalV2, "host", "basePath") { + if _, exists := openAPIV3["servers"]; exists { + return errors.New("OpenAPI v3 conversion invented servers") + } + } + if _, exists := originalV2["securityDefinitions"]; !exists { + if _, exists := v3Components["securitySchemes"]; exists { + return errors.New("OpenAPI v3 conversion invented security schemes") + } + } + if _, exists := originalV2["security"]; !exists { + if _, exists := openAPIV3["security"]; exists { + return errors.New("OpenAPI v3 conversion invented root security policy") + } + } + return nil +} + +func validateParameterParity(v2Entry, v3Entry operationInfo) error { + for _, pair := range []struct { + label string + v2 object + v3 object + }{ + {label: "path", v2: v2Entry.pathItem, v3: v3Entry.pathItem}, + {label: "operation", v2: v2Entry.operation, v3: v3Entry.operation}, + } { + expected, err := expectedParameters(pair.v2) + if err != nil { + return fmt.Errorf("%s parameters for %s: %w", pair.label, operationLabel(v2Entry), err) + } + + actual := any([]any{}) + if value, exists := pair.v3["parameters"]; exists { + actual = value + } + if !equalJSON(expected, actual) { + return fmt.Errorf("%s parameters changed for %s", pair.label, operationLabel(v2Entry)) + } + } + return nil +} + +func countBodyParameters(operations map[string]operationInfo) int { + count := 0 + for _, entry := range operations { + for _, container := range []object{entry.pathItem, entry.operation} { + values, _ := container["parameters"].([]any) + for _, value := range values { + parameter, ok := value.(object) + if ok && parameter["in"] == "body" { + count++ + } + } + } + } + return count +} + +func countOptionalParameters(operations map[string]operationInfo) int { + count := 0 + for _, entry := range operations { + for _, container := range []object{entry.pathItem, entry.operation} { + values, _ := container["parameters"].([]any) + for _, value := range values { + parameter, ok := value.(object) + if !ok || parameter["in"] == "body" || parameter["in"] == "path" { + continue + } + if required, _ := parameter["required"].(bool); !required { + count++ + } + } + } + } + return count +} + +func expectedParameters(container object) ([]any, error) { + parameters, exists := container["parameters"] + if !exists { + return []any{}, nil + } + values, ok := parameters.([]any) + if !ok { + return nil, errors.New("parameters must be an array") + } + + expected := make([]any, 0, len(values)) + for _, value := range values { + parameter, ok := value.(object) + if !ok { + return nil, errors.New("parameter must be an object") + } + if parameter["in"] == "body" { + continue + } + result := object{} + for _, key := range []string{"name", "in", "description", "required"} { + if field, exists := parameter[key]; exists { + result[key] = cloneJSON(field) + } + } + schema := object{} + for _, key := range []string{ + "type", + "format", + "enum", + "default", + "items", + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "minLength", + "maxLength", + "pattern", + "minItems", + "maxItems", + "uniqueItems", + "multipleOf", + } { + if field, exists := parameter[key]; exists { + schema[key] = rewriteSchemaRefs(field) + } + } + result["schema"] = schema + expected = append(expected, result) + } + return expected, nil +} + +func validateRequestBodyParity(v2Entry, v3Entry operationInfo, rootConsumes []string) error { + bodyParameters := make([]object, 0, 1) + for _, container := range []object{v2Entry.pathItem, v2Entry.operation} { + values, _ := container["parameters"].([]any) + for _, value := range values { + parameter, ok := value.(object) + if ok && parameter["in"] == "body" { + bodyParameters = append(bodyParameters, parameter) + } + } + } + if len(bodyParameters) > 1 { + return fmt.Errorf("multiple body parameters found for %s", operationLabel(v2Entry)) + } + + actual, hasActual := v3Entry.operation["requestBody"] + if len(bodyParameters) == 0 { + if hasActual { + return fmt.Errorf("OpenAPI v3 invented a request body for %s", operationLabel(v2Entry)) + } + return nil + } + if !hasActual { + return fmt.Errorf("OpenAPI v3 is missing the request body for %s", operationLabel(v2Entry)) + } + + body := bodyParameters[0] + expected := object{} + if description, ok := body["description"].(string); ok && description != "" { + expected["description"] = description + } + if required, _ := body["required"].(bool); required { + expected["required"] = true + } + schema, exists := body["schema"] + if !exists { + return fmt.Errorf("OpenAPI v2 body parameter lacks a schema for %s", operationLabel(v2Entry)) + } + consumes := stringArray(v2Entry.operation["consumes"]) + if len(consumes) == 0 { + consumes = rootConsumes + } + content := object{} + for _, mediaType := range consumes { + content[mediaType] = object{"schema": rewriteSchemaRefs(schema)} + } + expected["content"] = content + + if !equalJSON(expected, actual) { + return fmt.Errorf("request body changed for %s", operationLabel(v2Entry)) + } + return nil +} + +func validateResponseParity(v2Entry, v3Entry operationInfo, rootProduces []string) error { + v2Responses := v2Entry.operation["responses"].(object) + v3Responses := v3Entry.operation["responses"].(object) + produces := stringArray(v2Entry.operation["produces"]) + if len(produces) == 0 { + produces = rootProduces + } + if len(produces) == 0 { + produces = []string{"application/json"} + } + + for code, value := range v2Responses { + v2Response, ok := value.(object) + if !ok { + return fmt.Errorf("OpenAPI v2 response %s for %s must be an object", code, operationLabel(v2Entry)) + } + actual, exists := v3Responses[code] + if !exists { + return fmt.Errorf("OpenAPI v3 response %s is missing for %s", code, operationLabel(v2Entry)) + } + expected := object{} + if ref, exists := v2Response["$ref"]; exists { + expected["$ref"] = rewriteRef(ref) + } else { + expected["description"] = v2Response["description"] + if schema, exists := v2Response["schema"]; exists { + content := object{} + for _, mediaType := range produces { + content[mediaType] = object{"schema": rewriteSchemaRefs(schema)} + } + expected["content"] = content + } + } + if !equalJSON(expected, actual) { + return fmt.Errorf("response %s changed for %s", code, operationLabel(v2Entry)) + } + } + return nil +} + +func validateNoSwaggerOnlyV3(document object, operations map[string]operationInfo) error { + for _, entry := range operations { + for _, key := range []string{"consumes", "produces", "schemes"} { + if _, exists := entry.operation[key]; exists { + return fmt.Errorf( + "OpenAPI v3 operation %s contains Swagger-only key %q", + operationLabel(entry), + key, + ) + } + } + for _, container := range []object{entry.pathItem, entry.operation} { + parameters, _ := container["parameters"].([]any) + for _, value := range parameters { + parameter, ok := value.(object) + if !ok { + return fmt.Errorf("OpenAPI v3 parameter for %s must be an object", operationLabel(entry)) + } + if parameter["in"] == "body" || parameter["in"] == "formData" { + return fmt.Errorf( + "OpenAPI v3 operation %s contains a Swagger-only %s parameter", + operationLabel(entry), + parameter["in"], + ) + } + for _, key := range []string{"type", "format", "items", "collectionFormat"} { + if _, exists := parameter[key]; exists { + return fmt.Errorf( + "OpenAPI v3 parameter for %s contains Swagger-only key %q", + operationLabel(entry), + key, + ) + } + } + } + } + responses := entry.operation["responses"].(object) + for code, value := range responses { + if strings.HasPrefix(code, "x-") { + continue + } + response, ok := value.(object) + if !ok { + return fmt.Errorf( + "OpenAPI v3 response %s for %s must be an object", + code, + operationLabel(entry), + ) + } + for _, key := range []string{"schema", "examples"} { + if _, exists := response[key]; exists { + return fmt.Errorf( + "OpenAPI v3 response %s for %s contains Swagger-only key %q", + code, + operationLabel(entry), + key, + ) + } + } + } + } + + return walk(document, "#", func(value object, location string) error { + for key := range value { + if strings.HasPrefix(strings.ToLower(key), "x-mintlify") { + return fmt.Errorf( + "OpenAPI v3 contains Mintlify-specific extension %q at %s", + key, + location, + ) + } + } + if ref, ok := value["$ref"].(string); ok && strings.HasPrefix(ref, "#/definitions/") { + return fmt.Errorf("OpenAPI v3 contains a Swagger-only definition reference at %s", location) + } + if _, exists := value["x-originalParamName"]; exists { + return fmt.Errorf("OpenAPI v3 contains converter-only extension at %s", location) + } + return nil + }) +} + +func collectOperations(document object, version string) (map[string]operationInfo, error) { + paths, err := requiredObject(document, "paths", version) + if err != nil { + return nil, err + } + operations := make(map[string]operationInfo) + operationIDs := make(map[string]string) + + for _, apiPath := range sortedKeys(paths) { + if !strings.HasPrefix(apiPath, "/") { + return nil, fmt.Errorf("%s path %q must start with \"/\"", version, apiPath) + } + pathItem, ok := paths[apiPath].(object) + if !ok { + return nil, fmt.Errorf("%s path item %s must be an object", version, apiPath) + } + for _, method := range sortedKeys(pathItem) { + if _, isMethod := httpMethods[method]; !isMethod { + continue + } + operation, ok := pathItem[method].(object) + if !ok { + return nil, fmt.Errorf( + "%s operation %s %s must be an object", + version, + strings.ToUpper(method), + apiPath, + ) + } + operationID, ok := operation["operationId"].(string) + if !ok || operationID == "" { + return nil, fmt.Errorf( + "%s operation %s %s must have an operationId", + version, + strings.ToUpper(method), + apiPath, + ) + } + if previous, duplicated := operationIDs[operationID]; duplicated { + return nil, fmt.Errorf( + "%s operationId %q is duplicated by %s and %s %s", + version, + operationID, + previous, + strings.ToUpper(method), + apiPath, + ) + } + operationIDs[operationID] = strings.ToUpper(method) + " " + apiPath + + responses, err := requiredObject(operation, "responses", version+" operation "+operationID) + if err != nil { + return nil, err + } + responseCodes := make([]string, 0, len(responses)) + for code := range responses { + if !strings.HasPrefix(code, "x-") { + responseCodes = append(responseCodes, code) + } + } + sort.Strings(responseCodes) + if len(responseCodes) == 0 { + return nil, fmt.Errorf("%s operation %s must define responses", version, operationID) + } + + operations[apiPath+"\t"+method] = operationInfo{ + apiPath: apiPath, + method: method, + operation: operation, + pathItem: pathItem, + responseCodes: responseCodes, + } + } + } + return operations, nil +} + +func validateInternalRefs(document object, version string) (int, error) { + count := 0 + err := walk(document, "#", func(value object, location string) error { + refValue, exists := value["$ref"] + if !exists { + return nil + } + count++ + ref, ok := refValue.(string) + if !ok { + return fmt.Errorf("%s $ref at %s must be a string", version, location) + } + if ref != "#" && !strings.HasPrefix(ref, "#/") { + return fmt.Errorf("%s $ref at %s must be internal: %s", version, location, ref) + } + if _, err := resolveJSONPointer(document, ref); err != nil { + return fmt.Errorf("%s $ref at %s does not resolve: %s: %w", version, location, ref, err) + } + return nil + }) + return count, err +} + +func validateServiceCoverage(document object, operations map[string]operationInfo, version string) error { + tags, err := requiredArray(document, "tags", version) + if err != nil { + return err + } + rootTags := make(map[string]struct{}) + for _, value := range tags { + tag, ok := value.(object) + if !ok { + return fmt.Errorf("%s root tag must be an object", version) + } + name, _ := tag["name"].(string) + rootTags[name] = struct{}{} + } + for _, required := range []string{"OpenFGAService", "AuthZenService"} { + if _, exists := rootTags[required]; !exists { + return fmt.Errorf("%s is missing %s tag", version, required) + } + } + + authZenOperations := 0 + openFGAOperations := 0 + for _, entry := range operations { + operationID := entry.operation["operationId"].(string) + if strings.Contains(operationID, "UpdateStore") { + return fmt.Errorf("%s must not expose the unimplemented UpdateStore operation", version) + } + tags, ok := entry.operation["tags"].([]any) + if !ok { + return fmt.Errorf("%s %s tags must be an array", version, operationID) + } + isAuthZen := false + for _, tag := range tags { + if tag == "AuthZenService" { + isAuthZen = true + break + } + } + if isAuthZen { + authZenOperations++ + } else { + openFGAOperations++ + } + } + if authZenOperations == 0 { + return fmt.Errorf("%s must contain AuthZen operations", version) + } + if openFGAOperations == 0 { + return fmt.Errorf("%s must contain OpenFGA operations", version) + } + return nil +} + +func validateContentFree204(operations map[string]operationInfo, version string) error { + for _, entry := range operations { + responses := entry.operation["responses"].(object) + value, exists := responses["204"] + if !exists { + continue + } + response, ok := value.(object) + if !ok { + return fmt.Errorf("%s 204 response for %s must be an object", version, operationLabel(entry)) + } + forbiddenKey := "content" + if version == "OpenAPI v2" { + forbiddenKey = "schema" + } + if _, exists := response[forbiddenKey]; exists { + return fmt.Errorf( + "%s 204 response for %s must not have %s", + version, + operationLabel(entry), + forbiddenKey, + ) + } + } + return nil +} + +func normalizeRefSiblings(value any) (any, int, error) { + switch value := value.(type) { + case []any: + count := 0 + for index, item := range value { + normalized, itemCount, err := normalizeRefSiblings(item) + if err != nil { + return nil, 0, err + } + value[index] = normalized + count += itemCount + } + return value, count, nil + case object: + count := 0 + for key, item := range value { + normalized, itemCount, err := normalizeRefSiblings(item) + if err != nil { + return nil, 0, err + } + value[key] = normalized + count += itemCount + } + ref, hasRef := value["$ref"] + if hasRef && len(value) > 1 { + if _, ok := ref.(string); !ok { + return nil, 0, errors.New("$ref value must be a string") + } + siblings := make(object, len(value)-1) + for key, item := range value { + if key != "$ref" { + siblings[key] = item + } + } + return object{ + "allOf": []any{ + object{"$ref": ref}, + siblings, + }, + }, count + 1, nil + } + return value, count, nil + default: + return value, 0, nil + } +} + +func normalizeOutput(value any) (normalizationStats, error) { + stats := normalizationStats{} + err := walk(value, "#", func(current object, location string) error { + if originalName, exists := current["x-originalParamName"]; exists { + if originalName != "body" { + return fmt.Errorf( + "unexpected x-originalParamName value at %s: %v", + location, + originalName, + ) + } + delete(current, "x-originalParamName") + stats.removedOriginalParamNames++ + } + in, hasIn := current["in"].(string) + _, hasName := current["name"].(string) + if hasIn && hasName && in != "path" { + if _, hasRequired := current["required"]; !hasRequired { + current["required"] = false + stats.restoredRequiredFalse++ + } + } + return nil + }) + return stats, err +} + +func countRefSiblings(value any) int { + count := 0 + _ = walk(value, "#", func(current object, _ string) error { + if _, hasRef := current["$ref"]; hasRef && len(current) > 1 { + count++ + } + return nil + }) + return count +} + +func collectExamples(value any) (map[string]int, int, error) { + examples := make(map[string]int) + total := 0 + err := walk(value, "#", func(current object, _ string) error { + example, exists := current["example"] + if !exists { + return nil + } + encoded, err := json.Marshal(example) + if err != nil { + return err + } + examples[string(encoded)]++ + total++ + return nil + }) + return examples, total, err +} + +func rewriteSchemaRefs(value any) any { + switch value := value.(type) { + case []any: + result := make([]any, len(value)) + for index, item := range value { + result[index] = rewriteSchemaRefs(item) + } + return result + case object: + result := make(object, len(value)) + for key, item := range value { + if key == "$ref" { + result[key] = rewriteRef(item) + } else { + result[key] = rewriteSchemaRefs(item) + } + } + return result + default: + return value + } +} + +func rewriteRef(value any) any { + ref, ok := value.(string) + if !ok { + return value + } + replacements := []struct { + from string + to string + }{ + {from: "#/definitions/", to: "#/components/schemas/"}, + {from: "#/parameters/", to: "#/components/parameters/"}, + {from: "#/responses/", to: "#/components/responses/"}, + } + for _, replacement := range replacements { + if strings.HasPrefix(ref, replacement.from) { + return strings.Replace(ref, replacement.from, replacement.to, 1) + } + } + return ref +} + +func walk(value any, location string, visit func(object, string) error) error { + switch value := value.(type) { + case []any: + for index, item := range value { + if err := walk(item, fmt.Sprintf("%s/%d", location, index), visit); err != nil { + return err + } + } + case object: + if err := visit(value, location); err != nil { + return err + } + for _, key := range sortedKeys(value) { + if err := walk(value[key], location+"/"+escapeJSONPointer(key), visit); err != nil { + return err + } + } + } + return nil +} + +func resolveJSONPointer(document any, ref string) (any, error) { + if ref == "#" { + return document, nil + } + current := document + for _, token := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") { + decoded, err := url.PathUnescape(token) + if err != nil { + return nil, err + } + decoded = strings.ReplaceAll(strings.ReplaceAll(decoded, "~1", "/"), "~0", "~") + switch value := current.(type) { + case object: + next, exists := value[decoded] + if !exists { + return nil, fmt.Errorf("missing object key %q", decoded) + } + current = next + case []any: + var index int + if _, err := fmt.Sscanf(decoded, "%d", &index); err != nil || index < 0 || index >= len(value) { + return nil, fmt.Errorf("invalid array index %q", decoded) + } + current = value[index] + default: + return nil, fmt.Errorf("cannot traverse %q", decoded) + } + } + return current, nil +} + +func requiredObject(container object, key, label string) (object, error) { + value, exists := container[key] + if !exists { + return nil, fmt.Errorf("%s %s must be an object", label, key) + } + result, ok := value.(object) + if !ok { + return nil, fmt.Errorf("%s %s must be an object", label, key) + } + return result, nil +} + +func requiredArray(container object, key, label string) ([]any, error) { + value, exists := container[key] + if !exists { + return nil, fmt.Errorf("%s %s must be an array", label, key) + } + result, ok := value.([]any) + if !ok { + return nil, fmt.Errorf("%s %s must be an array", label, key) + } + return result, nil +} + +func decodeObject(data []byte) (object, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return nil, err + } + var trailing any + if err := decoder.Decode(&trailing); err == nil { + return nil, errors.New("unexpected data after JSON document") + } else if !errors.Is(err, io.EOF) { + return nil, fmt.Errorf("decode trailing JSON data: %w", err) + } + result, ok := value.(object) + if !ok { + return nil, errors.New("document root must be an object") + } + return result, nil +} + +func marshalJSON(value any, indent bool) ([]byte, error) { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + encoder.SetEscapeHTML(false) + if indent { + encoder.SetIndent("", " ") + } + if err := encoder.Encode(value); err != nil { + return nil, err + } + return buffer.Bytes(), nil +} + +func writeAtomically(filename string, contents []byte) error { + if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil { + return fmt.Errorf("create OpenAPI v3 directory: %w", err) + } + temporary, err := os.CreateTemp(filepath.Dir(filename), "."+filepath.Base(filename)+".*.tmp") + if err != nil { + return fmt.Errorf("create temporary OpenAPI v3 document: %w", err) + } + temporaryName := temporary.Name() + defer os.Remove(temporaryName) + + if err := temporary.Chmod(0o644); err != nil { + temporary.Close() + return fmt.Errorf("set temporary OpenAPI v3 permissions: %w", err) + } + if _, err := temporary.Write(contents); err != nil { + temporary.Close() + return fmt.Errorf("write temporary OpenAPI v3 document: %w", err) + } + if err := temporary.Sync(); err != nil { + temporary.Close() + return fmt.Errorf("sync temporary OpenAPI v3 document: %w", err) + } + if err := temporary.Close(); err != nil { + return fmt.Errorf("close temporary OpenAPI v3 document: %w", err) + } + if err := os.Rename(temporaryName, filename); err != nil { + return fmt.Errorf("replace OpenAPI v3 document: %w", err) + } + return nil +} + +func cloneJSON(value any) any { + switch value := value.(type) { + case []any: + result := make([]any, len(value)) + for index, item := range value { + result[index] = cloneJSON(item) + } + return result + case object: + result := make(object, len(value)) + for key, item := range value { + result[key] = cloneJSON(item) + } + return result + default: + return value + } +} + +func equalJSON(left, right any) bool { + leftJSON, leftErr := json.Marshal(left) + rightJSON, rightErr := json.Marshal(right) + return leftErr == nil && rightErr == nil && bytes.Equal(leftJSON, rightJSON) +} + +func sortedKeys(value object) []string { + keys := make([]string, 0, len(value)) + for key := range value { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} + +func stringArray(value any) []string { + values, ok := value.([]any) + if !ok { + return nil + } + result := make([]string, 0, len(values)) + for _, value := range values { + if text, ok := value.(string); ok { + result = append(result, text) + } + } + return result +} + +func operationLabel(entry operationInfo) string { + return strings.ToUpper(entry.method) + " " + entry.apiPath +} + +func escapeJSONPointer(value string) string { + return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1") +} + +func hasAnyKey(value object, keys ...string) bool { + for _, key := range keys { + if _, exists := value[key]; exists { + return true + } + } + return false +} + +func hash(value []byte) string { + sum := sha256.Sum256(value) + return hex.EncodeToString(sum[:]) +} diff --git a/tools/openapiv3/main_test.go b/tools/openapiv3/main_test.go new file mode 100644 index 00000000..b93d7ab7 --- /dev/null +++ b/tools/openapiv3/main_test.go @@ -0,0 +1,349 @@ +package main + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/getkin/kin-openapi/openapi2" + "github.com/getkin/kin-openapi/openapi2conv" +) + +const ( + fixtureExpectedExamples = 83 + fixtureExpectedOperations = 24 + fixtureExpectedPaths = 20 + fixtureExpectedRequestBodies = 16 + fixtureExpectedSchemas = 114 +) + +func TestGenerateMatchesCommittedArtifactSemantics(t *testing.T) { + source := readFixture(t, openAPIV2DefaultPath) + generated, summary, err := generate(source) + if err != nil { + t.Fatalf("generate: %v", err) + } + + expected := readFixture(t, openAPIV3DefaultPath) + generatedDocument, err := decodeObject(generated) + if err != nil { + t.Fatalf("decode generated document: %v", err) + } + expectedDocument, err := decodeObject(expected) + if err != nil { + t.Fatalf("decode committed document: %v", err) + } + if !equalJSON(expectedDocument, generatedDocument) { + t.Fatal("generated document is not semantically identical to the committed artifact") + } + if summary != (generationSummary{ + examples: fixtureExpectedExamples, + operations: fixtureExpectedOperations, + paths: fixtureExpectedPaths, + refs: expectedInternalRefs, + requestBodies: fixtureExpectedRequestBodies, + schemas: fixtureExpectedSchemas, + }) { + t.Fatalf("unexpected generation summary: %+v", summary) + } +} + +func TestGenerateIsDeterministic(t *testing.T) { + source := readFixture(t, openAPIV2DefaultPath) + first, _, err := generate(source) + if err != nil { + t.Fatalf("first generation: %v", err) + } + second, _, err := generate(source) + if err != nil { + t.Fatalf("second generation: %v", err) + } + if !bytes.Equal(first, second) { + t.Fatal("generation is not byte deterministic") + } +} + +func TestRunPreservesSourceAndWritesAtomically(t *testing.T) { + directory := t.TempDir() + sourcePath := filepath.Join(directory, "source.json") + outputPath := filepath.Join(directory, "output.json") + source := readFixture(t, openAPIV2DefaultPath) + if err := os.WriteFile(sourcePath, source, 0o644); err != nil { + t.Fatalf("write source: %v", err) + } + + if _, _, err := run(sourcePath, outputPath); err != nil { + t.Fatalf("run: %v", err) + } + sourceAfter, err := os.ReadFile(sourcePath) + if err != nil { + t.Fatalf("read source after run: %v", err) + } + if !bytes.Equal(source, sourceAfter) { + t.Fatal("source changed during conversion") + } + if matches, err := filepath.Glob(filepath.Join(directory, ".output.json.*.tmp")); err != nil { + t.Fatalf("glob temporary output: %v", err) + } else if len(matches) != 0 { + t.Fatalf("temporary output remains after atomic write: %v", matches) + } + info, err := os.Stat(outputPath) + if err != nil { + t.Fatalf("stat output: %v", err) + } + if info.Mode().Perm() != 0o644 { + t.Fatalf("unexpected output permissions: %o", info.Mode().Perm()) + } +} + +func TestSourceMutationGuards(t *testing.T) { + tests := []struct { + name string + wantError string + mutate func(object) + }{ + { + name: "root shape", + wantError: `root "swagger"`, + mutate: func(document object) { + document["swagger"] = "1.0" + }, + }, + { + name: "duplicate operation ID", + wantError: "is duplicated", + mutate: func(document object) { + operation(document, "/stores", "post")["operationId"] = "ListStores" + }, + }, + { + name: "external ref", + wantError: "must be internal", + mutate: func(document object) { + schema(document, "ListUsersBody")["properties"].(object)["object"].(object)["$ref"] = + "https://example.com/schema.json" + }, + }, + { + name: "UpdateStore exposure", + wantError: "must not expose the unimplemented UpdateStore", + mutate: func(document object) { + operation(document, "/stores/{store_id}", "get")["operationId"] = "UpdateStore" + }, + }, + { + name: "contentful v2 204", + wantError: "must not have schema", + mutate: func(document object) { + operation(document, "/stores/{store_id}", "delete")["responses"].(object)["204"].(object)["schema"] = + object{"type": "object"} + }, + }, + { + name: "ref sibling loss", + wantError: "ref sibling count changed", + mutate: func(document object) { + delete( + schema(document, "ActionSearchResponse")["properties"].(object)["page"].(object), + "title", + ) + }, + }, + } + + source := readFixture(t, openAPIV2DefaultPath) + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + document, err := decodeObject(source) + if err != nil { + t.Fatalf("decode source: %v", err) + } + test.mutate(document) + mutated, err := marshalJSON(document, true) + if err != nil { + t.Fatalf("encode mutation: %v", err) + } + _, _, err = generate(mutated) + assertErrorContains(t, err, test.wantError) + }) + } +} + +func TestConvertedMutationGuards(t *testing.T) { + source := readFixture(t, openAPIV2DefaultPath) + originalV2, normalizedV2, v2Operations := prepareSource(t, source) + generated, _, err := generate(source) + if err != nil { + t.Fatalf("generate: %v", err) + } + + tests := []struct { + name string + wantError string + mutate func(object) + }{ + { + name: "invented server", + wantError: "invented servers", + mutate: func(document object) { + document["servers"] = []any{object{"url": "https://example.com"}} + }, + }, + { + name: "invented security scheme", + wantError: "invented security schemes", + mutate: func(document object) { + document["components"].(object)["securitySchemes"] = object{ + "bearer": object{"type": "http", "scheme": "bearer"}, + } + }, + }, + { + name: "Swagger definition ref", + wantError: "Swagger-only definition reference", + mutate: func(document object) { + schema(document, "ListUsersBody")["properties"].(object)["object"].(object)["allOf"].([]any)[0].(object)["$ref"] = "#/definitions/Object" + }, + }, + { + name: "contentful v3 204", + wantError: "must not have content", + mutate: func(document object) { + operation(document, "/stores/{store_id}", "delete")["responses"].(object)["204"].(object)["content"] = + object{"application/json": object{}} + }, + }, + { + name: "request body drift", + wantError: "request body changed", + mutate: func(document object) { + operation(document, "/stores", "post")["requestBody"].(object)["required"] = false + }, + }, + { + name: "response drift", + wantError: "response 200 changed", + mutate: func(document object) { + operation(document, "/stores", "get")["responses"].(object)["200"].(object)["description"] = "changed" + }, + }, + { + name: "example drift", + wantError: "examples changed", + mutate: func(document object) { + delete(schema(document, "ConsistencyPreference"), "example") + }, + }, + { + name: "converter extension", + wantError: "converter-only extension", + mutate: func(document object) { + operation(document, "/stores", "post")["requestBody"].(object)["x-originalParamName"] = "body" + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + document, err := decodeObject(generated) + if err != nil { + t.Fatalf("decode generated document: %v", err) + } + test.mutate(document) + _, err = validateConverted(originalV2, normalizedV2, document, v2Operations) + assertErrorContains(t, err, test.wantError) + }) + } +} + +func TestRawKinConversionCannotBypassRefSiblingGuard(t *testing.T) { + source := readFixture(t, openAPIV2DefaultPath) + originalV2, err := decodeObject(source) + if err != nil { + t.Fatalf("decode source: %v", err) + } + v2Operations, err := validateOpenAPIV2(originalV2) + if err != nil { + t.Fatalf("validate source: %v", err) + } + + var typedV2 openapi2.T + if err := json.Unmarshal(source, &typedV2); err != nil { + t.Fatalf("decode typed source: %v", err) + } + typedV3, err := openapi2conv.ToV3(&typedV2) + if err != nil { + t.Fatalf("raw conversion: %v", err) + } + rawOutput, err := json.Marshal(typedV3) + if err != nil { + t.Fatalf("encode raw conversion: %v", err) + } + rawV3, err := decodeObject(rawOutput) + if err != nil { + t.Fatalf("decode raw conversion: %v", err) + } + if _, err := normalizeOutput(rawV3); err != nil { + t.Fatalf("normalize raw output: %v", err) + } + _, err = validateConverted(originalV2, originalV2, rawV3, v2Operations) + assertErrorContains(t, err, "examples changed") +} + +func prepareSource(t *testing.T, source []byte) (object, object, map[string]operationInfo) { + t.Helper() + original, err := decodeObject(source) + if err != nil { + t.Fatalf("decode original source: %v", err) + } + + operations, err := validateOpenAPIV2(original) + if err != nil { + t.Fatalf("validate original source: %v", err) + } + normalized, err := decodeObject(source) + if err != nil { + t.Fatalf("decode normalized source: %v", err) + } + value, count, err := normalizeRefSiblings(normalized) + if err != nil { + t.Fatalf("normalize ref siblings: %v", err) + } + if count != expectedRefSiblings { + t.Fatalf("unexpected ref sibling count: %d", count) + } + return original, value.(object), operations +} + +func readFixture(t *testing.T, filename string) []byte { + t.Helper() + value, err := os.ReadFile(filename) + if err != nil { + t.Fatalf("read %s: %v", filename, err) + } + return value +} + +func assertErrorContains(t *testing.T, err error, expected string) { + t.Helper() + if err == nil { + t.Fatalf("expected error containing %q", expected) + } + if !strings.Contains(err.Error(), expected) { + t.Fatalf("expected error containing %q, got %q", expected, err) + } +} + +func operation(document object, apiPath, method string) object { + return document["paths"].(object)[apiPath].(object)[method].(object) +} + +func schema(document object, name string) object { + if definitions, exists := document["definitions"].(object); exists { + return definitions[name].(object) + } + return document["components"].(object)["schemas"].(object)[name].(object) +} From 1fe4f5c5ff58a47f1fe9e71735c3bb8ff3104265 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 3 Sep 2026 17:19:27 +0530 Subject: [PATCH 3/4] refactor: split OpenAPI v3 converter Organize conversion, normalization, validation, operation parity, JSON helpers, and atomic output into focused files without changing generated output. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 1 + tools/openapiv3/generate.go | 141 ++++ tools/openapiv3/json.go | 210 ++++++ tools/openapiv3/main.go | 1271 --------------------------------- tools/openapiv3/normalize.go | 143 ++++ tools/openapiv3/operations.go | 316 ++++++++ tools/openapiv3/validate.go | 467 ++++++++++++ tools/openapiv3/write.go | 40 ++ 8 files changed, 1318 insertions(+), 1271 deletions(-) create mode 100644 tools/openapiv3/generate.go create mode 100644 tools/openapiv3/json.go create mode 100644 tools/openapiv3/normalize.go create mode 100644 tools/openapiv3/operations.go create mode 100644 tools/openapiv3/validate.go create mode 100644 tools/openapiv3/write.go diff --git a/README.md b/README.md index 327943f9..d65d1ce2 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ make The OpenAPI 3 document is deterministically converted from the finalized Swagger 2 document using the Go tool in `tools/openapiv3`. +Run `make test-openapi-v3` to exercise its conversion and parity guards. Existing SDK generation remains compatible with, and must continue to use, `docs/openapiv2/apidocs.swagger.json`. diff --git a/tools/openapiv3/generate.go b/tools/openapiv3/generate.go new file mode 100644 index 00000000..80e2d250 --- /dev/null +++ b/tools/openapiv3/generate.go @@ -0,0 +1,141 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + + "github.com/getkin/kin-openapi/openapi2" + "github.com/getkin/kin-openapi/openapi2conv" +) + +const ( + // These counts are reviewed-change sentinels: legitimate generator changes must update them deliberately. + expectedInternalRefs = 330 + expectedRefSiblings = 43 + openAPIV2DefaultPath = "../../docs/openapiv2/apidocs.swagger.json" + openAPIV3DefaultPath = "../../docs/openapiv3/apidocs.openapi.json" + openAPIV3TargetVersion = "3.0.3" +) + +type generationSummary struct { + examples int + operations int + paths int + refs int + requestBodies int + schemas int +} + +func run(sourcePath, outputPath string) (generationSummary, string, error) { + sourceBytes, err := os.ReadFile(sourcePath) + if err != nil { + return generationSummary{}, "", fmt.Errorf("read OpenAPI v2 source: %w", err) + } + sourceHash := hash(sourceBytes) + + output, summary, err := generate(sourceBytes) + if err != nil { + return generationSummary{}, "", err + } + + sourceBytesAfterConversion, err := os.ReadFile(sourcePath) + if err != nil { + return generationSummary{}, "", fmt.Errorf("re-read OpenAPI v2 source: %w", err) + } + if sourceHash != hash(sourceBytesAfterConversion) || !bytes.Equal(sourceBytes, sourceBytesAfterConversion) { + return generationSummary{}, "", errors.New("OpenAPI v2 artifact changed during OpenAPI v3 conversion") + } + + if err := writeAtomically(outputPath, output); err != nil { + return generationSummary{}, "", err + } + return summary, sourceHash, nil +} + +func generate(sourceBytes []byte) ([]byte, generationSummary, error) { + openAPIV2, err := decodeObject(sourceBytes) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("decode OpenAPI v2 source: %w", err) + } + v2Operations, err := validateOpenAPIV2(openAPIV2) + if err != nil { + return nil, generationSummary{}, err + } + expectedRequestBodies := countBodyParameters(v2Operations) + expectedRequiredFalse := countOptionalParameters(v2Operations) + + normalizedV2, err := decodeObject(sourceBytes) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("decode OpenAPI v2 source for normalization: %w", err) + } + normalizedValue, refSiblingCount, err := normalizeRefSiblings(normalizedV2) + if err != nil { + return nil, generationSummary{}, err + } + if refSiblingCount != expectedRefSiblings { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v2 ref sibling count changed from %d to %d", + expectedRefSiblings, + refSiblingCount, + ) + } + normalizedV2 = normalizedValue.(object) + if countRefSiblings(normalizedV2) != 0 { + return nil, generationSummary{}, errors.New("OpenAPI v2 ref sibling normalization was incomplete") + } + + normalizedBytes, err := marshalJSON(normalizedV2, false) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("encode normalized OpenAPI v2 source: %w", err) + } + var typedV2 openapi2.T + if err := json.Unmarshal(normalizedBytes, &typedV2); err != nil { + return nil, generationSummary{}, fmt.Errorf("decode normalized OpenAPI v2 source: %w", err) + } + + typedV3, err := openapi2conv.ToV3(&typedV2) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("convert OpenAPI v2 to v3: %w", err) + } + convertedBytes, err := json.Marshal(typedV3) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("encode converted OpenAPI v3 document: %w", err) + } + openAPIV3, err := decodeObject(convertedBytes) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("decode converted OpenAPI v3 document: %w", err) + } + + normalization, err := normalizeOutput(openAPIV3) + if err != nil { + return nil, generationSummary{}, err + } + if normalization.removedOriginalParamNames != expectedRequestBodies { + return nil, generationSummary{}, fmt.Errorf( + "converter-only request body extension count changed from %d to %d", + expectedRequestBodies, + normalization.removedOriginalParamNames, + ) + } + if normalization.restoredRequiredFalse != expectedRequiredFalse { + return nil, generationSummary{}, fmt.Errorf( + "optional parameter normalization count changed from %d to %d", + expectedRequiredFalse, + normalization.restoredRequiredFalse, + ) + } + + summary, err := validateConverted(openAPIV2, normalizedV2, openAPIV3, v2Operations) + if err != nil { + return nil, generationSummary{}, err + } + + output, err := marshalJSON(openAPIV3, true) + if err != nil { + return nil, generationSummary{}, fmt.Errorf("encode final OpenAPI v3 document: %w", err) + } + return output, summary, nil +} diff --git a/tools/openapiv3/json.go b/tools/openapiv3/json.go new file mode 100644 index 00000000..c8e32b4b --- /dev/null +++ b/tools/openapiv3/json.go @@ -0,0 +1,210 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/url" + "sort" + "strings" +) + +type object = map[string]any + +func collectExamples(value any) (map[string]int, int, error) { + examples := make(map[string]int) + total := 0 + err := walk(value, "#", func(current object, _ string) error { + example, exists := current["example"] + if !exists { + return nil + } + encoded, err := json.Marshal(example) + if err != nil { + return err + } + examples[string(encoded)]++ + total++ + return nil + }) + return examples, total, err +} + +func walk(value any, location string, visit func(object, string) error) error { + switch value := value.(type) { + case []any: + for index, item := range value { + if err := walk(item, fmt.Sprintf("%s/%d", location, index), visit); err != nil { + return err + } + } + case object: + if err := visit(value, location); err != nil { + return err + } + for _, key := range sortedKeys(value) { + if err := walk(value[key], location+"/"+escapeJSONPointer(key), visit); err != nil { + return err + } + } + } + return nil +} + +func resolveJSONPointer(document any, ref string) (any, error) { + if ref == "#" { + return document, nil + } + current := document + for _, token := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") { + decoded, err := url.PathUnescape(token) + if err != nil { + return nil, err + } + decoded = strings.ReplaceAll(strings.ReplaceAll(decoded, "~1", "/"), "~0", "~") + switch value := current.(type) { + case object: + next, exists := value[decoded] + if !exists { + return nil, fmt.Errorf("missing object key %q", decoded) + } + current = next + case []any: + var index int + if _, err := fmt.Sscanf(decoded, "%d", &index); err != nil || index < 0 || index >= len(value) { + return nil, fmt.Errorf("invalid array index %q", decoded) + } + current = value[index] + default: + return nil, fmt.Errorf("cannot traverse %q", decoded) + } + } + return current, nil +} + +func requiredObject(container object, key, label string) (object, error) { + value, exists := container[key] + if !exists { + return nil, fmt.Errorf("%s %s must be an object", label, key) + } + result, ok := value.(object) + if !ok { + return nil, fmt.Errorf("%s %s must be an object", label, key) + } + return result, nil +} + +func requiredArray(container object, key, label string) ([]any, error) { + value, exists := container[key] + if !exists { + return nil, fmt.Errorf("%s %s must be an array", label, key) + } + result, ok := value.([]any) + if !ok { + return nil, fmt.Errorf("%s %s must be an array", label, key) + } + return result, nil +} + +func decodeObject(data []byte) (object, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return nil, err + } + var trailing any + if err := decoder.Decode(&trailing); err == nil { + return nil, errors.New("unexpected data after JSON document") + } else if !errors.Is(err, io.EOF) { + return nil, fmt.Errorf("decode trailing JSON data: %w", err) + } + result, ok := value.(object) + if !ok { + return nil, errors.New("document root must be an object") + } + return result, nil +} + +func marshalJSON(value any, indent bool) ([]byte, error) { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + encoder.SetEscapeHTML(false) + if indent { + encoder.SetIndent("", " ") + } + if err := encoder.Encode(value); err != nil { + return nil, err + } + return buffer.Bytes(), nil +} + +func cloneJSON(value any) any { + switch value := value.(type) { + case []any: + result := make([]any, len(value)) + for index, item := range value { + result[index] = cloneJSON(item) + } + return result + case object: + result := make(object, len(value)) + for key, item := range value { + result[key] = cloneJSON(item) + } + return result + default: + return value + } +} + +func equalJSON(left, right any) bool { + leftJSON, leftErr := json.Marshal(left) + rightJSON, rightErr := json.Marshal(right) + return leftErr == nil && rightErr == nil && bytes.Equal(leftJSON, rightJSON) +} + +func sortedKeys(value object) []string { + keys := make([]string, 0, len(value)) + for key := range value { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} + +func stringArray(value any) []string { + values, ok := value.([]any) + if !ok { + return nil + } + result := make([]string, 0, len(values)) + for _, value := range values { + if text, ok := value.(string); ok { + result = append(result, text) + } + } + return result +} + +func escapeJSONPointer(value string) string { + return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1") +} + +func hasAnyKey(value object, keys ...string) bool { + for _, key := range keys { + if _, exists := value[key]; exists { + return true + } + } + return false +} + +func hash(value []byte) string { + sum := sha256.Sum256(value) + return hex.EncodeToString(sum[:]) +} diff --git a/tools/openapiv3/main.go b/tools/openapiv3/main.go index d1366800..13dda2cb 100644 --- a/tools/openapiv3/main.go +++ b/tools/openapiv3/main.go @@ -1,67 +1,11 @@ package main import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" "flag" "fmt" - "io" - "net/url" "os" - "path/filepath" - "sort" - "strings" - - "github.com/getkin/kin-openapi/openapi2" - "github.com/getkin/kin-openapi/openapi2conv" -) - -const ( - expectedInternalRefs = 330 - expectedRefSiblings = 43 - openAPIV2DefaultPath = "../../docs/openapiv2/apidocs.swagger.json" - openAPIV3DefaultPath = "../../docs/openapiv3/apidocs.openapi.json" - openAPIV3TargetVersion = "3.0.3" ) -var httpMethods = map[string]struct{}{ - "delete": {}, - "get": {}, - "head": {}, - "options": {}, - "patch": {}, - "post": {}, - "put": {}, - "trace": {}, -} - -type object = map[string]any - -type operationInfo struct { - apiPath string - method string - operation object - pathItem object - responseCodes []string -} - -type normalizationStats struct { - removedOriginalParamNames int - restoredRequiredFalse int -} - -type generationSummary struct { - examples int - operations int - paths int - refs int - requestBodies int - schemas int -} - func main() { sourcePath := flag.String("source", openAPIV2DefaultPath, "path to the finalized Swagger 2 document") outputPath := flag.String("output", openAPIV3DefaultPath, "path for the generated OpenAPI 3 document") @@ -84,1218 +28,3 @@ func main() { ) fmt.Printf("OpenAPI v2 SHA-256 unchanged: %s\n", sourceHash) } - -func run(sourcePath, outputPath string) (generationSummary, string, error) { - sourceBytes, err := os.ReadFile(sourcePath) - if err != nil { - return generationSummary{}, "", fmt.Errorf("read OpenAPI v2 source: %w", err) - } - sourceHash := hash(sourceBytes) - - output, summary, err := generate(sourceBytes) - if err != nil { - return generationSummary{}, "", err - } - - sourceBytesAfterConversion, err := os.ReadFile(sourcePath) - if err != nil { - return generationSummary{}, "", fmt.Errorf("re-read OpenAPI v2 source: %w", err) - } - if sourceHash != hash(sourceBytesAfterConversion) || !bytes.Equal(sourceBytes, sourceBytesAfterConversion) { - return generationSummary{}, "", errors.New("OpenAPI v2 artifact changed during OpenAPI v3 conversion") - } - - if err := writeAtomically(outputPath, output); err != nil { - return generationSummary{}, "", err - } - return summary, sourceHash, nil -} - -func generate(sourceBytes []byte) ([]byte, generationSummary, error) { - openAPIV2, err := decodeObject(sourceBytes) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("decode OpenAPI v2 source: %w", err) - } - v2Operations, err := validateOpenAPIV2(openAPIV2) - if err != nil { - return nil, generationSummary{}, err - } - expectedRequestBodies := countBodyParameters(v2Operations) - expectedRequiredFalse := countOptionalParameters(v2Operations) - - normalizedV2, err := decodeObject(sourceBytes) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("decode OpenAPI v2 source for normalization: %w", err) - } - normalizedValue, refSiblingCount, err := normalizeRefSiblings(normalizedV2) - if err != nil { - return nil, generationSummary{}, err - } - if refSiblingCount != expectedRefSiblings { - return nil, generationSummary{}, fmt.Errorf( - "OpenAPI v2 ref sibling count changed from %d to %d", - expectedRefSiblings, - refSiblingCount, - ) - } - normalizedV2 = normalizedValue.(object) - if countRefSiblings(normalizedV2) != 0 { - return nil, generationSummary{}, errors.New("OpenAPI v2 ref sibling normalization was incomplete") - } - - normalizedBytes, err := marshalJSON(normalizedV2, false) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("encode normalized OpenAPI v2 source: %w", err) - } - var typedV2 openapi2.T - if err := json.Unmarshal(normalizedBytes, &typedV2); err != nil { - return nil, generationSummary{}, fmt.Errorf("decode normalized OpenAPI v2 source: %w", err) - } - - typedV3, err := openapi2conv.ToV3(&typedV2) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("convert OpenAPI v2 to v3: %w", err) - } - convertedBytes, err := json.Marshal(typedV3) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("encode converted OpenAPI v3 document: %w", err) - } - openAPIV3, err := decodeObject(convertedBytes) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("decode converted OpenAPI v3 document: %w", err) - } - - normalization, err := normalizeOutput(openAPIV3) - if err != nil { - return nil, generationSummary{}, err - } - if normalization.removedOriginalParamNames != expectedRequestBodies { - return nil, generationSummary{}, fmt.Errorf( - "converter-only request body extension count changed from %d to %d", - expectedRequestBodies, - normalization.removedOriginalParamNames, - ) - } - if normalization.restoredRequiredFalse != expectedRequiredFalse { - return nil, generationSummary{}, fmt.Errorf( - "optional parameter normalization count changed from %d to %d", - expectedRequiredFalse, - normalization.restoredRequiredFalse, - ) - } - - summary, err := validateConverted(openAPIV2, normalizedV2, openAPIV3, v2Operations) - if err != nil { - return nil, generationSummary{}, err - } - - output, err := marshalJSON(openAPIV3, true) - if err != nil { - return nil, generationSummary{}, fmt.Errorf("encode final OpenAPI v3 document: %w", err) - } - return output, summary, nil -} - -func validateConverted( - originalV2 object, - normalizedV2 object, - openAPIV3 object, - v2Operations map[string]operationInfo, -) (generationSummary, error) { - v3Operations, summary, err := validateOpenAPIV3(openAPIV3) - if err != nil { - return generationSummary{}, err - } - if err := validateParity(originalV2, normalizedV2, openAPIV3, v2Operations, v3Operations); err != nil { - return generationSummary{}, err - } - return summary, nil -} - -func validateOpenAPIV2(document object) (map[string]operationInfo, error) { - if document["swagger"] != "2.0" { - return nil, errors.New(`OpenAPI v2 root "swagger" must be "2.0"`) - } - if _, exists := document["openapi"]; exists { - return nil, errors.New(`OpenAPI v2 root must not contain "openapi"`) - } - if _, err := requiredObject(document, "info", "OpenAPI v2"); err != nil { - return nil, err - } - paths, err := requiredObject(document, "paths", "OpenAPI v2") - if err != nil { - return nil, err - } - definitions, err := requiredObject(document, "definitions", "OpenAPI v2") - if err != nil { - return nil, err - } - if _, err := requiredArray(document, "tags", "OpenAPI v2"); err != nil { - return nil, err - } - operations, err := collectOperations(document, "OpenAPI v2") - if err != nil { - return nil, err - } - if err := validateServiceCoverage(document, operations, "OpenAPI v2"); err != nil { - return nil, err - } - if err := validateContentFree204(operations, "OpenAPI v2"); err != nil { - return nil, err - } - refCount, err := validateInternalRefs(document, "OpenAPI v2") - if err != nil { - return nil, err - } - if refCount != expectedInternalRefs { - return nil, fmt.Errorf( - "OpenAPI v2 internal ref count changed from %d to %d", - expectedInternalRefs, - refCount, - ) - } - _, exampleCount, err := collectExamples(document) - if err != nil { - return nil, err - } - if len(paths) == 0 || len(definitions) == 0 || len(operations) == 0 || exampleCount == 0 { - return nil, errors.New("OpenAPI v2 document must contain paths, operations, schemas, and examples") - } - return operations, nil -} - -func validateOpenAPIV3(document object) (map[string]operationInfo, generationSummary, error) { - if document["openapi"] != openAPIV3TargetVersion { - return nil, generationSummary{}, fmt.Errorf( - `OpenAPI v3 root "openapi" must be %q`, - openAPIV3TargetVersion, - ) - } - if _, err := requiredObject(document, "info", "OpenAPI v3"); err != nil { - return nil, generationSummary{}, err - } - paths, err := requiredObject(document, "paths", "OpenAPI v3") - if err != nil { - return nil, generationSummary{}, err - } - components, err := requiredObject(document, "components", "OpenAPI v3") - if err != nil { - return nil, generationSummary{}, err - } - schemas, err := requiredObject(components, "schemas", "OpenAPI v3 components") - if err != nil { - return nil, generationSummary{}, err - } - if _, err := requiredArray(document, "tags", "OpenAPI v3"); err != nil { - return nil, generationSummary{}, err - } - for _, key := range []string{ - "swagger", - "definitions", - "parameters", - "responses", - "securityDefinitions", - "schemes", - "consumes", - "produces", - } { - if _, exists := document[key]; exists { - return nil, generationSummary{}, fmt.Errorf( - "OpenAPI v3 root contains Swagger-only key %q", - key, - ) - } - } - operations, err := collectOperations(document, "OpenAPI v3") - if err != nil { - return nil, generationSummary{}, err - } - if err := validateNoSwaggerOnlyV3(document, operations); err != nil { - return nil, generationSummary{}, err - } - if err := validateServiceCoverage(document, operations, "OpenAPI v3"); err != nil { - return nil, generationSummary{}, err - } - if err := validateContentFree204(operations, "OpenAPI v3"); err != nil { - return nil, generationSummary{}, err - } - refCount, err := validateInternalRefs(document, "OpenAPI v3") - if err != nil { - return nil, generationSummary{}, err - } - if refCount != expectedInternalRefs { - return nil, generationSummary{}, fmt.Errorf( - "OpenAPI v3 internal ref count changed from %d to %d", - expectedInternalRefs, - refCount, - ) - } - if siblingCount := countRefSiblings(document); siblingCount != 0 { - return nil, generationSummary{}, fmt.Errorf( - "OpenAPI v3 contains %d ref objects with siblings", - siblingCount, - ) - } - _, exampleCount, err := collectExamples(document) - if err != nil { - return nil, generationSummary{}, err - } - requestBodyCount := 0 - for _, operation := range operations { - if _, exists := operation.operation["requestBody"]; exists { - requestBodyCount++ - } - } - return operations, generationSummary{ - examples: exampleCount, - operations: len(operations), - paths: len(paths), - refs: refCount, - requestBodies: requestBodyCount, - schemas: len(schemas), - }, nil -} - -func validateParity( - originalV2 object, - normalizedV2 object, - openAPIV3 object, - v2Operations map[string]operationInfo, - v3Operations map[string]operationInfo, -) error { - v2Paths := sortedKeys(originalV2["paths"].(object)) - v3Paths := sortedKeys(openAPIV3["paths"].(object)) - if !equalJSON(v2Paths, v3Paths) { - return errors.New("API paths changed during OpenAPI v3 conversion") - } - if len(v2Operations) != len(v3Operations) { - return fmt.Errorf( - "operation count changed from %d to %d", - len(v2Operations), - len(v3Operations), - ) - } - if len(originalV2["paths"].(object)) != len(openAPIV3["paths"].(object)) { - return errors.New("path count changed during OpenAPI v3 conversion") - } - - normalizedOperations, err := collectOperations(normalizedV2, "normalized OpenAPI v2") - if err != nil { - return err - } - rootConsumes := stringArray(normalizedV2["consumes"]) - rootProduces := stringArray(normalizedV2["produces"]) - for key, v2Entry := range v2Operations { - v3Entry, exists := v3Operations[key] - if !exists { - return fmt.Errorf( - "OpenAPI v3 is missing %s %s", - strings.ToUpper(v2Entry.method), - v2Entry.apiPath, - ) - } - for _, property := range []string{"operationId", "summary", "description", "tags"} { - if !equalJSON(v2Entry.operation[property], v3Entry.operation[property]) { - return fmt.Errorf( - "%s changed for %s %s", - property, - strings.ToUpper(v2Entry.method), - v2Entry.apiPath, - ) - } - } - if !equalJSON(v2Entry.responseCodes, v3Entry.responseCodes) { - return fmt.Errorf( - "response codes changed for %s %s", - strings.ToUpper(v2Entry.method), - v2Entry.apiPath, - ) - } - - normalizedEntry := normalizedOperations[key] - if err := validateParameterParity(normalizedEntry, v3Entry); err != nil { - return err - } - if err := validateRequestBodyParity(normalizedEntry, v3Entry, rootConsumes); err != nil { - return err - } - if err := validateResponseParity(normalizedEntry, v3Entry, rootProduces); err != nil { - return err - } - } - - v2Examples, _, err := collectExamples(originalV2) - if err != nil { - return err - } - v3Examples, _, err := collectExamples(openAPIV3) - if err != nil { - return err - } - if !equalJSON(v2Examples, v3Examples) { - return errors.New("examples changed during OpenAPI v3 conversion") - } - - v2Definitions := normalizedV2["definitions"].(object) - v3Components := openAPIV3["components"].(object) - v3Schemas := v3Components["schemas"].(object) - expectedSchemas := rewriteSchemaRefs(v2Definitions) - if !equalJSON(expectedSchemas, v3Schemas) { - return errors.New("component schemas changed during OpenAPI v3 conversion") - } - if len(v2Definitions) != len(v3Schemas) { - return errors.New("component schema count changed during OpenAPI v3 conversion") - } - if !equalJSON(originalV2["tags"], openAPIV3["tags"]) { - return errors.New("root tags changed during OpenAPI v3 conversion") - } - if !equalJSON(originalV2["info"], openAPIV3["info"]) { - return errors.New("API information changed during OpenAPI v3 conversion") - } - - if !hasAnyKey(originalV2, "host", "basePath") { - if _, exists := openAPIV3["servers"]; exists { - return errors.New("OpenAPI v3 conversion invented servers") - } - } - if _, exists := originalV2["securityDefinitions"]; !exists { - if _, exists := v3Components["securitySchemes"]; exists { - return errors.New("OpenAPI v3 conversion invented security schemes") - } - } - if _, exists := originalV2["security"]; !exists { - if _, exists := openAPIV3["security"]; exists { - return errors.New("OpenAPI v3 conversion invented root security policy") - } - } - return nil -} - -func validateParameterParity(v2Entry, v3Entry operationInfo) error { - for _, pair := range []struct { - label string - v2 object - v3 object - }{ - {label: "path", v2: v2Entry.pathItem, v3: v3Entry.pathItem}, - {label: "operation", v2: v2Entry.operation, v3: v3Entry.operation}, - } { - expected, err := expectedParameters(pair.v2) - if err != nil { - return fmt.Errorf("%s parameters for %s: %w", pair.label, operationLabel(v2Entry), err) - } - - actual := any([]any{}) - if value, exists := pair.v3["parameters"]; exists { - actual = value - } - if !equalJSON(expected, actual) { - return fmt.Errorf("%s parameters changed for %s", pair.label, operationLabel(v2Entry)) - } - } - return nil -} - -func countBodyParameters(operations map[string]operationInfo) int { - count := 0 - for _, entry := range operations { - for _, container := range []object{entry.pathItem, entry.operation} { - values, _ := container["parameters"].([]any) - for _, value := range values { - parameter, ok := value.(object) - if ok && parameter["in"] == "body" { - count++ - } - } - } - } - return count -} - -func countOptionalParameters(operations map[string]operationInfo) int { - count := 0 - for _, entry := range operations { - for _, container := range []object{entry.pathItem, entry.operation} { - values, _ := container["parameters"].([]any) - for _, value := range values { - parameter, ok := value.(object) - if !ok || parameter["in"] == "body" || parameter["in"] == "path" { - continue - } - if required, _ := parameter["required"].(bool); !required { - count++ - } - } - } - } - return count -} - -func expectedParameters(container object) ([]any, error) { - parameters, exists := container["parameters"] - if !exists { - return []any{}, nil - } - values, ok := parameters.([]any) - if !ok { - return nil, errors.New("parameters must be an array") - } - - expected := make([]any, 0, len(values)) - for _, value := range values { - parameter, ok := value.(object) - if !ok { - return nil, errors.New("parameter must be an object") - } - if parameter["in"] == "body" { - continue - } - result := object{} - for _, key := range []string{"name", "in", "description", "required"} { - if field, exists := parameter[key]; exists { - result[key] = cloneJSON(field) - } - } - schema := object{} - for _, key := range []string{ - "type", - "format", - "enum", - "default", - "items", - "minimum", - "maximum", - "exclusiveMinimum", - "exclusiveMaximum", - "minLength", - "maxLength", - "pattern", - "minItems", - "maxItems", - "uniqueItems", - "multipleOf", - } { - if field, exists := parameter[key]; exists { - schema[key] = rewriteSchemaRefs(field) - } - } - result["schema"] = schema - expected = append(expected, result) - } - return expected, nil -} - -func validateRequestBodyParity(v2Entry, v3Entry operationInfo, rootConsumes []string) error { - bodyParameters := make([]object, 0, 1) - for _, container := range []object{v2Entry.pathItem, v2Entry.operation} { - values, _ := container["parameters"].([]any) - for _, value := range values { - parameter, ok := value.(object) - if ok && parameter["in"] == "body" { - bodyParameters = append(bodyParameters, parameter) - } - } - } - if len(bodyParameters) > 1 { - return fmt.Errorf("multiple body parameters found for %s", operationLabel(v2Entry)) - } - - actual, hasActual := v3Entry.operation["requestBody"] - if len(bodyParameters) == 0 { - if hasActual { - return fmt.Errorf("OpenAPI v3 invented a request body for %s", operationLabel(v2Entry)) - } - return nil - } - if !hasActual { - return fmt.Errorf("OpenAPI v3 is missing the request body for %s", operationLabel(v2Entry)) - } - - body := bodyParameters[0] - expected := object{} - if description, ok := body["description"].(string); ok && description != "" { - expected["description"] = description - } - if required, _ := body["required"].(bool); required { - expected["required"] = true - } - schema, exists := body["schema"] - if !exists { - return fmt.Errorf("OpenAPI v2 body parameter lacks a schema for %s", operationLabel(v2Entry)) - } - consumes := stringArray(v2Entry.operation["consumes"]) - if len(consumes) == 0 { - consumes = rootConsumes - } - content := object{} - for _, mediaType := range consumes { - content[mediaType] = object{"schema": rewriteSchemaRefs(schema)} - } - expected["content"] = content - - if !equalJSON(expected, actual) { - return fmt.Errorf("request body changed for %s", operationLabel(v2Entry)) - } - return nil -} - -func validateResponseParity(v2Entry, v3Entry operationInfo, rootProduces []string) error { - v2Responses := v2Entry.operation["responses"].(object) - v3Responses := v3Entry.operation["responses"].(object) - produces := stringArray(v2Entry.operation["produces"]) - if len(produces) == 0 { - produces = rootProduces - } - if len(produces) == 0 { - produces = []string{"application/json"} - } - - for code, value := range v2Responses { - v2Response, ok := value.(object) - if !ok { - return fmt.Errorf("OpenAPI v2 response %s for %s must be an object", code, operationLabel(v2Entry)) - } - actual, exists := v3Responses[code] - if !exists { - return fmt.Errorf("OpenAPI v3 response %s is missing for %s", code, operationLabel(v2Entry)) - } - expected := object{} - if ref, exists := v2Response["$ref"]; exists { - expected["$ref"] = rewriteRef(ref) - } else { - expected["description"] = v2Response["description"] - if schema, exists := v2Response["schema"]; exists { - content := object{} - for _, mediaType := range produces { - content[mediaType] = object{"schema": rewriteSchemaRefs(schema)} - } - expected["content"] = content - } - } - if !equalJSON(expected, actual) { - return fmt.Errorf("response %s changed for %s", code, operationLabel(v2Entry)) - } - } - return nil -} - -func validateNoSwaggerOnlyV3(document object, operations map[string]operationInfo) error { - for _, entry := range operations { - for _, key := range []string{"consumes", "produces", "schemes"} { - if _, exists := entry.operation[key]; exists { - return fmt.Errorf( - "OpenAPI v3 operation %s contains Swagger-only key %q", - operationLabel(entry), - key, - ) - } - } - for _, container := range []object{entry.pathItem, entry.operation} { - parameters, _ := container["parameters"].([]any) - for _, value := range parameters { - parameter, ok := value.(object) - if !ok { - return fmt.Errorf("OpenAPI v3 parameter for %s must be an object", operationLabel(entry)) - } - if parameter["in"] == "body" || parameter["in"] == "formData" { - return fmt.Errorf( - "OpenAPI v3 operation %s contains a Swagger-only %s parameter", - operationLabel(entry), - parameter["in"], - ) - } - for _, key := range []string{"type", "format", "items", "collectionFormat"} { - if _, exists := parameter[key]; exists { - return fmt.Errorf( - "OpenAPI v3 parameter for %s contains Swagger-only key %q", - operationLabel(entry), - key, - ) - } - } - } - } - responses := entry.operation["responses"].(object) - for code, value := range responses { - if strings.HasPrefix(code, "x-") { - continue - } - response, ok := value.(object) - if !ok { - return fmt.Errorf( - "OpenAPI v3 response %s for %s must be an object", - code, - operationLabel(entry), - ) - } - for _, key := range []string{"schema", "examples"} { - if _, exists := response[key]; exists { - return fmt.Errorf( - "OpenAPI v3 response %s for %s contains Swagger-only key %q", - code, - operationLabel(entry), - key, - ) - } - } - } - } - - return walk(document, "#", func(value object, location string) error { - for key := range value { - if strings.HasPrefix(strings.ToLower(key), "x-mintlify") { - return fmt.Errorf( - "OpenAPI v3 contains Mintlify-specific extension %q at %s", - key, - location, - ) - } - } - if ref, ok := value["$ref"].(string); ok && strings.HasPrefix(ref, "#/definitions/") { - return fmt.Errorf("OpenAPI v3 contains a Swagger-only definition reference at %s", location) - } - if _, exists := value["x-originalParamName"]; exists { - return fmt.Errorf("OpenAPI v3 contains converter-only extension at %s", location) - } - return nil - }) -} - -func collectOperations(document object, version string) (map[string]operationInfo, error) { - paths, err := requiredObject(document, "paths", version) - if err != nil { - return nil, err - } - operations := make(map[string]operationInfo) - operationIDs := make(map[string]string) - - for _, apiPath := range sortedKeys(paths) { - if !strings.HasPrefix(apiPath, "/") { - return nil, fmt.Errorf("%s path %q must start with \"/\"", version, apiPath) - } - pathItem, ok := paths[apiPath].(object) - if !ok { - return nil, fmt.Errorf("%s path item %s must be an object", version, apiPath) - } - for _, method := range sortedKeys(pathItem) { - if _, isMethod := httpMethods[method]; !isMethod { - continue - } - operation, ok := pathItem[method].(object) - if !ok { - return nil, fmt.Errorf( - "%s operation %s %s must be an object", - version, - strings.ToUpper(method), - apiPath, - ) - } - operationID, ok := operation["operationId"].(string) - if !ok || operationID == "" { - return nil, fmt.Errorf( - "%s operation %s %s must have an operationId", - version, - strings.ToUpper(method), - apiPath, - ) - } - if previous, duplicated := operationIDs[operationID]; duplicated { - return nil, fmt.Errorf( - "%s operationId %q is duplicated by %s and %s %s", - version, - operationID, - previous, - strings.ToUpper(method), - apiPath, - ) - } - operationIDs[operationID] = strings.ToUpper(method) + " " + apiPath - - responses, err := requiredObject(operation, "responses", version+" operation "+operationID) - if err != nil { - return nil, err - } - responseCodes := make([]string, 0, len(responses)) - for code := range responses { - if !strings.HasPrefix(code, "x-") { - responseCodes = append(responseCodes, code) - } - } - sort.Strings(responseCodes) - if len(responseCodes) == 0 { - return nil, fmt.Errorf("%s operation %s must define responses", version, operationID) - } - - operations[apiPath+"\t"+method] = operationInfo{ - apiPath: apiPath, - method: method, - operation: operation, - pathItem: pathItem, - responseCodes: responseCodes, - } - } - } - return operations, nil -} - -func validateInternalRefs(document object, version string) (int, error) { - count := 0 - err := walk(document, "#", func(value object, location string) error { - refValue, exists := value["$ref"] - if !exists { - return nil - } - count++ - ref, ok := refValue.(string) - if !ok { - return fmt.Errorf("%s $ref at %s must be a string", version, location) - } - if ref != "#" && !strings.HasPrefix(ref, "#/") { - return fmt.Errorf("%s $ref at %s must be internal: %s", version, location, ref) - } - if _, err := resolveJSONPointer(document, ref); err != nil { - return fmt.Errorf("%s $ref at %s does not resolve: %s: %w", version, location, ref, err) - } - return nil - }) - return count, err -} - -func validateServiceCoverage(document object, operations map[string]operationInfo, version string) error { - tags, err := requiredArray(document, "tags", version) - if err != nil { - return err - } - rootTags := make(map[string]struct{}) - for _, value := range tags { - tag, ok := value.(object) - if !ok { - return fmt.Errorf("%s root tag must be an object", version) - } - name, _ := tag["name"].(string) - rootTags[name] = struct{}{} - } - for _, required := range []string{"OpenFGAService", "AuthZenService"} { - if _, exists := rootTags[required]; !exists { - return fmt.Errorf("%s is missing %s tag", version, required) - } - } - - authZenOperations := 0 - openFGAOperations := 0 - for _, entry := range operations { - operationID := entry.operation["operationId"].(string) - if strings.Contains(operationID, "UpdateStore") { - return fmt.Errorf("%s must not expose the unimplemented UpdateStore operation", version) - } - tags, ok := entry.operation["tags"].([]any) - if !ok { - return fmt.Errorf("%s %s tags must be an array", version, operationID) - } - isAuthZen := false - for _, tag := range tags { - if tag == "AuthZenService" { - isAuthZen = true - break - } - } - if isAuthZen { - authZenOperations++ - } else { - openFGAOperations++ - } - } - if authZenOperations == 0 { - return fmt.Errorf("%s must contain AuthZen operations", version) - } - if openFGAOperations == 0 { - return fmt.Errorf("%s must contain OpenFGA operations", version) - } - return nil -} - -func validateContentFree204(operations map[string]operationInfo, version string) error { - for _, entry := range operations { - responses := entry.operation["responses"].(object) - value, exists := responses["204"] - if !exists { - continue - } - response, ok := value.(object) - if !ok { - return fmt.Errorf("%s 204 response for %s must be an object", version, operationLabel(entry)) - } - forbiddenKey := "content" - if version == "OpenAPI v2" { - forbiddenKey = "schema" - } - if _, exists := response[forbiddenKey]; exists { - return fmt.Errorf( - "%s 204 response for %s must not have %s", - version, - operationLabel(entry), - forbiddenKey, - ) - } - } - return nil -} - -func normalizeRefSiblings(value any) (any, int, error) { - switch value := value.(type) { - case []any: - count := 0 - for index, item := range value { - normalized, itemCount, err := normalizeRefSiblings(item) - if err != nil { - return nil, 0, err - } - value[index] = normalized - count += itemCount - } - return value, count, nil - case object: - count := 0 - for key, item := range value { - normalized, itemCount, err := normalizeRefSiblings(item) - if err != nil { - return nil, 0, err - } - value[key] = normalized - count += itemCount - } - ref, hasRef := value["$ref"] - if hasRef && len(value) > 1 { - if _, ok := ref.(string); !ok { - return nil, 0, errors.New("$ref value must be a string") - } - siblings := make(object, len(value)-1) - for key, item := range value { - if key != "$ref" { - siblings[key] = item - } - } - return object{ - "allOf": []any{ - object{"$ref": ref}, - siblings, - }, - }, count + 1, nil - } - return value, count, nil - default: - return value, 0, nil - } -} - -func normalizeOutput(value any) (normalizationStats, error) { - stats := normalizationStats{} - err := walk(value, "#", func(current object, location string) error { - if originalName, exists := current["x-originalParamName"]; exists { - if originalName != "body" { - return fmt.Errorf( - "unexpected x-originalParamName value at %s: %v", - location, - originalName, - ) - } - delete(current, "x-originalParamName") - stats.removedOriginalParamNames++ - } - in, hasIn := current["in"].(string) - _, hasName := current["name"].(string) - if hasIn && hasName && in != "path" { - if _, hasRequired := current["required"]; !hasRequired { - current["required"] = false - stats.restoredRequiredFalse++ - } - } - return nil - }) - return stats, err -} - -func countRefSiblings(value any) int { - count := 0 - _ = walk(value, "#", func(current object, _ string) error { - if _, hasRef := current["$ref"]; hasRef && len(current) > 1 { - count++ - } - return nil - }) - return count -} - -func collectExamples(value any) (map[string]int, int, error) { - examples := make(map[string]int) - total := 0 - err := walk(value, "#", func(current object, _ string) error { - example, exists := current["example"] - if !exists { - return nil - } - encoded, err := json.Marshal(example) - if err != nil { - return err - } - examples[string(encoded)]++ - total++ - return nil - }) - return examples, total, err -} - -func rewriteSchemaRefs(value any) any { - switch value := value.(type) { - case []any: - result := make([]any, len(value)) - for index, item := range value { - result[index] = rewriteSchemaRefs(item) - } - return result - case object: - result := make(object, len(value)) - for key, item := range value { - if key == "$ref" { - result[key] = rewriteRef(item) - } else { - result[key] = rewriteSchemaRefs(item) - } - } - return result - default: - return value - } -} - -func rewriteRef(value any) any { - ref, ok := value.(string) - if !ok { - return value - } - replacements := []struct { - from string - to string - }{ - {from: "#/definitions/", to: "#/components/schemas/"}, - {from: "#/parameters/", to: "#/components/parameters/"}, - {from: "#/responses/", to: "#/components/responses/"}, - } - for _, replacement := range replacements { - if strings.HasPrefix(ref, replacement.from) { - return strings.Replace(ref, replacement.from, replacement.to, 1) - } - } - return ref -} - -func walk(value any, location string, visit func(object, string) error) error { - switch value := value.(type) { - case []any: - for index, item := range value { - if err := walk(item, fmt.Sprintf("%s/%d", location, index), visit); err != nil { - return err - } - } - case object: - if err := visit(value, location); err != nil { - return err - } - for _, key := range sortedKeys(value) { - if err := walk(value[key], location+"/"+escapeJSONPointer(key), visit); err != nil { - return err - } - } - } - return nil -} - -func resolveJSONPointer(document any, ref string) (any, error) { - if ref == "#" { - return document, nil - } - current := document - for _, token := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") { - decoded, err := url.PathUnescape(token) - if err != nil { - return nil, err - } - decoded = strings.ReplaceAll(strings.ReplaceAll(decoded, "~1", "/"), "~0", "~") - switch value := current.(type) { - case object: - next, exists := value[decoded] - if !exists { - return nil, fmt.Errorf("missing object key %q", decoded) - } - current = next - case []any: - var index int - if _, err := fmt.Sscanf(decoded, "%d", &index); err != nil || index < 0 || index >= len(value) { - return nil, fmt.Errorf("invalid array index %q", decoded) - } - current = value[index] - default: - return nil, fmt.Errorf("cannot traverse %q", decoded) - } - } - return current, nil -} - -func requiredObject(container object, key, label string) (object, error) { - value, exists := container[key] - if !exists { - return nil, fmt.Errorf("%s %s must be an object", label, key) - } - result, ok := value.(object) - if !ok { - return nil, fmt.Errorf("%s %s must be an object", label, key) - } - return result, nil -} - -func requiredArray(container object, key, label string) ([]any, error) { - value, exists := container[key] - if !exists { - return nil, fmt.Errorf("%s %s must be an array", label, key) - } - result, ok := value.([]any) - if !ok { - return nil, fmt.Errorf("%s %s must be an array", label, key) - } - return result, nil -} - -func decodeObject(data []byte) (object, error) { - decoder := json.NewDecoder(bytes.NewReader(data)) - decoder.UseNumber() - var value any - if err := decoder.Decode(&value); err != nil { - return nil, err - } - var trailing any - if err := decoder.Decode(&trailing); err == nil { - return nil, errors.New("unexpected data after JSON document") - } else if !errors.Is(err, io.EOF) { - return nil, fmt.Errorf("decode trailing JSON data: %w", err) - } - result, ok := value.(object) - if !ok { - return nil, errors.New("document root must be an object") - } - return result, nil -} - -func marshalJSON(value any, indent bool) ([]byte, error) { - var buffer bytes.Buffer - encoder := json.NewEncoder(&buffer) - encoder.SetEscapeHTML(false) - if indent { - encoder.SetIndent("", " ") - } - if err := encoder.Encode(value); err != nil { - return nil, err - } - return buffer.Bytes(), nil -} - -func writeAtomically(filename string, contents []byte) error { - if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil { - return fmt.Errorf("create OpenAPI v3 directory: %w", err) - } - temporary, err := os.CreateTemp(filepath.Dir(filename), "."+filepath.Base(filename)+".*.tmp") - if err != nil { - return fmt.Errorf("create temporary OpenAPI v3 document: %w", err) - } - temporaryName := temporary.Name() - defer os.Remove(temporaryName) - - if err := temporary.Chmod(0o644); err != nil { - temporary.Close() - return fmt.Errorf("set temporary OpenAPI v3 permissions: %w", err) - } - if _, err := temporary.Write(contents); err != nil { - temporary.Close() - return fmt.Errorf("write temporary OpenAPI v3 document: %w", err) - } - if err := temporary.Sync(); err != nil { - temporary.Close() - return fmt.Errorf("sync temporary OpenAPI v3 document: %w", err) - } - if err := temporary.Close(); err != nil { - return fmt.Errorf("close temporary OpenAPI v3 document: %w", err) - } - if err := os.Rename(temporaryName, filename); err != nil { - return fmt.Errorf("replace OpenAPI v3 document: %w", err) - } - return nil -} - -func cloneJSON(value any) any { - switch value := value.(type) { - case []any: - result := make([]any, len(value)) - for index, item := range value { - result[index] = cloneJSON(item) - } - return result - case object: - result := make(object, len(value)) - for key, item := range value { - result[key] = cloneJSON(item) - } - return result - default: - return value - } -} - -func equalJSON(left, right any) bool { - leftJSON, leftErr := json.Marshal(left) - rightJSON, rightErr := json.Marshal(right) - return leftErr == nil && rightErr == nil && bytes.Equal(leftJSON, rightJSON) -} - -func sortedKeys(value object) []string { - keys := make([]string, 0, len(value)) - for key := range value { - keys = append(keys, key) - } - sort.Strings(keys) - return keys -} - -func stringArray(value any) []string { - values, ok := value.([]any) - if !ok { - return nil - } - result := make([]string, 0, len(values)) - for _, value := range values { - if text, ok := value.(string); ok { - result = append(result, text) - } - } - return result -} - -func operationLabel(entry operationInfo) string { - return strings.ToUpper(entry.method) + " " + entry.apiPath -} - -func escapeJSONPointer(value string) string { - return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1") -} - -func hasAnyKey(value object, keys ...string) bool { - for _, key := range keys { - if _, exists := value[key]; exists { - return true - } - } - return false -} - -func hash(value []byte) string { - sum := sha256.Sum256(value) - return hex.EncodeToString(sum[:]) -} diff --git a/tools/openapiv3/normalize.go b/tools/openapiv3/normalize.go new file mode 100644 index 00000000..42914fd8 --- /dev/null +++ b/tools/openapiv3/normalize.go @@ -0,0 +1,143 @@ +package main + +import ( + "errors" + "fmt" + "strings" +) + +type normalizationStats struct { + removedOriginalParamNames int + restoredRequiredFalse int +} + +// Swagger permits $ref siblings, but OpenAPI 3.0 ignores them; allOf preserves both meanings. +func normalizeRefSiblings(value any) (any, int, error) { + switch value := value.(type) { + case []any: + count := 0 + for index, item := range value { + normalized, itemCount, err := normalizeRefSiblings(item) + if err != nil { + return nil, 0, err + } + value[index] = normalized + count += itemCount + } + return value, count, nil + case object: + count := 0 + for key, item := range value { + normalized, itemCount, err := normalizeRefSiblings(item) + if err != nil { + return nil, 0, err + } + value[key] = normalized + count += itemCount + } + ref, hasRef := value["$ref"] + if hasRef && len(value) > 1 { + if _, ok := ref.(string); !ok { + return nil, 0, errors.New("$ref value must be a string") + } + siblings := make(object, len(value)-1) + for key, item := range value { + if key != "$ref" { + siblings[key] = item + } + } + return object{ + "allOf": []any{ + object{"$ref": ref}, + siblings, + }, + }, count + 1, nil + } + return value, count, nil + default: + return value, 0, nil + } +} + +func normalizeOutput(value any) (normalizationStats, error) { + stats := normalizationStats{} + err := walk(value, "#", func(current object, location string) error { + // kin-openapi adds this compatibility extension and omits explicit false values. + if originalName, exists := current["x-originalParamName"]; exists { + if originalName != "body" { + return fmt.Errorf( + "unexpected x-originalParamName value at %s: %v", + location, + originalName, + ) + } + delete(current, "x-originalParamName") + stats.removedOriginalParamNames++ + } + in, hasIn := current["in"].(string) + _, hasName := current["name"].(string) + if hasIn && hasName && in != "path" { + if _, hasRequired := current["required"]; !hasRequired { + current["required"] = false + stats.restoredRequiredFalse++ + } + } + return nil + }) + return stats, err +} + +func countRefSiblings(value any) int { + count := 0 + _ = walk(value, "#", func(current object, _ string) error { + if _, hasRef := current["$ref"]; hasRef && len(current) > 1 { + count++ + } + return nil + }) + return count +} + +func rewriteSchemaRefs(value any) any { + switch value := value.(type) { + case []any: + result := make([]any, len(value)) + for index, item := range value { + result[index] = rewriteSchemaRefs(item) + } + return result + case object: + result := make(object, len(value)) + for key, item := range value { + if key == "$ref" { + result[key] = rewriteRef(item) + } else { + result[key] = rewriteSchemaRefs(item) + } + } + return result + default: + return value + } +} + +func rewriteRef(value any) any { + ref, ok := value.(string) + if !ok { + return value + } + replacements := []struct { + from string + to string + }{ + {from: "#/definitions/", to: "#/components/schemas/"}, + {from: "#/parameters/", to: "#/components/parameters/"}, + {from: "#/responses/", to: "#/components/responses/"}, + } + for _, replacement := range replacements { + if strings.HasPrefix(ref, replacement.from) { + return strings.Replace(ref, replacement.from, replacement.to, 1) + } + } + return ref +} diff --git a/tools/openapiv3/operations.go b/tools/openapiv3/operations.go new file mode 100644 index 00000000..5ed42a2c --- /dev/null +++ b/tools/openapiv3/operations.go @@ -0,0 +1,316 @@ +package main + +import ( + "errors" + "fmt" + "sort" + "strings" +) + +var httpMethods = map[string]struct{}{ + "delete": {}, + "get": {}, + "head": {}, + "options": {}, + "patch": {}, + "post": {}, + "put": {}, + "trace": {}, +} + +type operationInfo struct { + apiPath string + method string + operation object + pathItem object + responseCodes []string +} + +func validateParameterParity(v2Entry, v3Entry operationInfo) error { + for _, pair := range []struct { + label string + v2 object + v3 object + }{ + {label: "path", v2: v2Entry.pathItem, v3: v3Entry.pathItem}, + {label: "operation", v2: v2Entry.operation, v3: v3Entry.operation}, + } { + expected, err := expectedParameters(pair.v2) + if err != nil { + return fmt.Errorf("%s parameters for %s: %w", pair.label, operationLabel(v2Entry), err) + } + + actual := any([]any{}) + if value, exists := pair.v3["parameters"]; exists { + actual = value + } + if !equalJSON(expected, actual) { + return fmt.Errorf("%s parameters changed for %s", pair.label, operationLabel(v2Entry)) + } + } + return nil +} + +func countBodyParameters(operations map[string]operationInfo) int { + count := 0 + for _, entry := range operations { + for _, container := range []object{entry.pathItem, entry.operation} { + values, _ := container["parameters"].([]any) + for _, value := range values { + parameter, ok := value.(object) + if ok && parameter["in"] == "body" { + count++ + } + } + } + } + return count +} + +func countOptionalParameters(operations map[string]operationInfo) int { + count := 0 + for _, entry := range operations { + for _, container := range []object{entry.pathItem, entry.operation} { + values, _ := container["parameters"].([]any) + for _, value := range values { + parameter, ok := value.(object) + if !ok || parameter["in"] == "body" || parameter["in"] == "path" { + continue + } + if required, _ := parameter["required"].(bool); !required { + count++ + } + } + } + } + return count +} + +func expectedParameters(container object) ([]any, error) { + parameters, exists := container["parameters"] + if !exists { + return []any{}, nil + } + values, ok := parameters.([]any) + if !ok { + return nil, errors.New("parameters must be an array") + } + + expected := make([]any, 0, len(values)) + for _, value := range values { + parameter, ok := value.(object) + if !ok { + return nil, errors.New("parameter must be an object") + } + if parameter["in"] == "body" { + continue + } + result := object{} + for _, key := range []string{"name", "in", "description", "required"} { + if field, exists := parameter[key]; exists { + result[key] = cloneJSON(field) + } + } + schema := object{} + for _, key := range []string{ + "type", + "format", + "enum", + "default", + "items", + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "minLength", + "maxLength", + "pattern", + "minItems", + "maxItems", + "uniqueItems", + "multipleOf", + } { + if field, exists := parameter[key]; exists { + schema[key] = rewriteSchemaRefs(field) + } + } + result["schema"] = schema + expected = append(expected, result) + } + return expected, nil +} + +func validateRequestBodyParity(v2Entry, v3Entry operationInfo, rootConsumes []string) error { + bodyParameters := make([]object, 0, 1) + for _, container := range []object{v2Entry.pathItem, v2Entry.operation} { + values, _ := container["parameters"].([]any) + for _, value := range values { + parameter, ok := value.(object) + if ok && parameter["in"] == "body" { + bodyParameters = append(bodyParameters, parameter) + } + } + } + if len(bodyParameters) > 1 { + return fmt.Errorf("multiple body parameters found for %s", operationLabel(v2Entry)) + } + + actual, hasActual := v3Entry.operation["requestBody"] + if len(bodyParameters) == 0 { + if hasActual { + return fmt.Errorf("OpenAPI v3 invented a request body for %s", operationLabel(v2Entry)) + } + return nil + } + if !hasActual { + return fmt.Errorf("OpenAPI v3 is missing the request body for %s", operationLabel(v2Entry)) + } + + body := bodyParameters[0] + expected := object{} + if description, ok := body["description"].(string); ok && description != "" { + expected["description"] = description + } + if required, _ := body["required"].(bool); required { + expected["required"] = true + } + schema, exists := body["schema"] + if !exists { + return fmt.Errorf("OpenAPI v2 body parameter lacks a schema for %s", operationLabel(v2Entry)) + } + consumes := stringArray(v2Entry.operation["consumes"]) + if len(consumes) == 0 { + consumes = rootConsumes + } + content := object{} + for _, mediaType := range consumes { + content[mediaType] = object{"schema": rewriteSchemaRefs(schema)} + } + expected["content"] = content + + if !equalJSON(expected, actual) { + return fmt.Errorf("request body changed for %s", operationLabel(v2Entry)) + } + return nil +} + +func validateResponseParity(v2Entry, v3Entry operationInfo, rootProduces []string) error { + v2Responses := v2Entry.operation["responses"].(object) + v3Responses := v3Entry.operation["responses"].(object) + produces := stringArray(v2Entry.operation["produces"]) + if len(produces) == 0 { + produces = rootProduces + } + if len(produces) == 0 { + produces = []string{"application/json"} + } + + for code, value := range v2Responses { + v2Response, ok := value.(object) + if !ok { + return fmt.Errorf("OpenAPI v2 response %s for %s must be an object", code, operationLabel(v2Entry)) + } + actual, exists := v3Responses[code] + if !exists { + return fmt.Errorf("OpenAPI v3 response %s is missing for %s", code, operationLabel(v2Entry)) + } + expected := object{} + if ref, exists := v2Response["$ref"]; exists { + expected["$ref"] = rewriteRef(ref) + } else { + expected["description"] = v2Response["description"] + if schema, exists := v2Response["schema"]; exists { + content := object{} + for _, mediaType := range produces { + content[mediaType] = object{"schema": rewriteSchemaRefs(schema)} + } + expected["content"] = content + } + } + if !equalJSON(expected, actual) { + return fmt.Errorf("response %s changed for %s", code, operationLabel(v2Entry)) + } + } + return nil +} + +func collectOperations(document object, version string) (map[string]operationInfo, error) { + paths, err := requiredObject(document, "paths", version) + if err != nil { + return nil, err + } + operations := make(map[string]operationInfo) + operationIDs := make(map[string]string) + + for _, apiPath := range sortedKeys(paths) { + if !strings.HasPrefix(apiPath, "/") { + return nil, fmt.Errorf("%s path %q must start with \"/\"", version, apiPath) + } + pathItem, ok := paths[apiPath].(object) + if !ok { + return nil, fmt.Errorf("%s path item %s must be an object", version, apiPath) + } + for _, method := range sortedKeys(pathItem) { + if _, isMethod := httpMethods[method]; !isMethod { + continue + } + operation, ok := pathItem[method].(object) + if !ok { + return nil, fmt.Errorf( + "%s operation %s %s must be an object", + version, + strings.ToUpper(method), + apiPath, + ) + } + operationID, ok := operation["operationId"].(string) + if !ok || operationID == "" { + return nil, fmt.Errorf( + "%s operation %s %s must have an operationId", + version, + strings.ToUpper(method), + apiPath, + ) + } + if previous, duplicated := operationIDs[operationID]; duplicated { + return nil, fmt.Errorf( + "%s operationId %q is duplicated by %s and %s %s", + version, + operationID, + previous, + strings.ToUpper(method), + apiPath, + ) + } + operationIDs[operationID] = strings.ToUpper(method) + " " + apiPath + + responses, err := requiredObject(operation, "responses", version+" operation "+operationID) + if err != nil { + return nil, err + } + responseCodes := make([]string, 0, len(responses)) + for code := range responses { + if !strings.HasPrefix(code, "x-") { + responseCodes = append(responseCodes, code) + } + } + sort.Strings(responseCodes) + if len(responseCodes) == 0 { + return nil, fmt.Errorf("%s operation %s must define responses", version, operationID) + } + + operations[apiPath+"\t"+method] = operationInfo{ + apiPath: apiPath, + method: method, + operation: operation, + pathItem: pathItem, + responseCodes: responseCodes, + } + } + } + return operations, nil +} + +func operationLabel(entry operationInfo) string { + return strings.ToUpper(entry.method) + " " + entry.apiPath +} diff --git a/tools/openapiv3/validate.go b/tools/openapiv3/validate.go new file mode 100644 index 00000000..999849fe --- /dev/null +++ b/tools/openapiv3/validate.go @@ -0,0 +1,467 @@ +package main + +import ( + "errors" + "fmt" + "strings" +) + +func validateConverted( + originalV2 object, + normalizedV2 object, + openAPIV3 object, + v2Operations map[string]operationInfo, +) (generationSummary, error) { + v3Operations, summary, err := validateOpenAPIV3(openAPIV3) + if err != nil { + return generationSummary{}, err + } + if err := validateParity(originalV2, normalizedV2, openAPIV3, v2Operations, v3Operations); err != nil { + return generationSummary{}, err + } + return summary, nil +} + +func validateOpenAPIV2(document object) (map[string]operationInfo, error) { + if document["swagger"] != "2.0" { + return nil, errors.New(`OpenAPI v2 root "swagger" must be "2.0"`) + } + if _, exists := document["openapi"]; exists { + return nil, errors.New(`OpenAPI v2 root must not contain "openapi"`) + } + if _, err := requiredObject(document, "info", "OpenAPI v2"); err != nil { + return nil, err + } + paths, err := requiredObject(document, "paths", "OpenAPI v2") + if err != nil { + return nil, err + } + definitions, err := requiredObject(document, "definitions", "OpenAPI v2") + if err != nil { + return nil, err + } + if _, err := requiredArray(document, "tags", "OpenAPI v2"); err != nil { + return nil, err + } + operations, err := collectOperations(document, "OpenAPI v2") + if err != nil { + return nil, err + } + if err := validateServiceCoverage(document, operations, "OpenAPI v2"); err != nil { + return nil, err + } + if err := validateContentFree204(operations, "OpenAPI v2"); err != nil { + return nil, err + } + refCount, err := validateInternalRefs(document, "OpenAPI v2") + if err != nil { + return nil, err + } + if refCount != expectedInternalRefs { + return nil, fmt.Errorf( + "OpenAPI v2 internal ref count changed from %d to %d", + expectedInternalRefs, + refCount, + ) + } + _, exampleCount, err := collectExamples(document) + if err != nil { + return nil, err + } + if len(paths) == 0 || len(definitions) == 0 || len(operations) == 0 || exampleCount == 0 { + return nil, errors.New("OpenAPI v2 document must contain paths, operations, schemas, and examples") + } + return operations, nil +} + +func validateOpenAPIV3(document object) (map[string]operationInfo, generationSummary, error) { + if document["openapi"] != openAPIV3TargetVersion { + return nil, generationSummary{}, fmt.Errorf( + `OpenAPI v3 root "openapi" must be %q`, + openAPIV3TargetVersion, + ) + } + if _, err := requiredObject(document, "info", "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + paths, err := requiredObject(document, "paths", "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + components, err := requiredObject(document, "components", "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + schemas, err := requiredObject(components, "schemas", "OpenAPI v3 components") + if err != nil { + return nil, generationSummary{}, err + } + if _, err := requiredArray(document, "tags", "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + for _, key := range []string{ + "swagger", + "definitions", + "parameters", + "responses", + "securityDefinitions", + "schemes", + "consumes", + "produces", + } { + if _, exists := document[key]; exists { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v3 root contains Swagger-only key %q", + key, + ) + } + } + operations, err := collectOperations(document, "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + if err := validateNoSwaggerOnlyV3(document, operations); err != nil { + return nil, generationSummary{}, err + } + if err := validateServiceCoverage(document, operations, "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + if err := validateContentFree204(operations, "OpenAPI v3"); err != nil { + return nil, generationSummary{}, err + } + refCount, err := validateInternalRefs(document, "OpenAPI v3") + if err != nil { + return nil, generationSummary{}, err + } + if refCount != expectedInternalRefs { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v3 internal ref count changed from %d to %d", + expectedInternalRefs, + refCount, + ) + } + if siblingCount := countRefSiblings(document); siblingCount != 0 { + return nil, generationSummary{}, fmt.Errorf( + "OpenAPI v3 contains %d ref objects with siblings", + siblingCount, + ) + } + _, exampleCount, err := collectExamples(document) + if err != nil { + return nil, generationSummary{}, err + } + requestBodyCount := 0 + for _, operation := range operations { + if _, exists := operation.operation["requestBody"]; exists { + requestBodyCount++ + } + } + return operations, generationSummary{ + examples: exampleCount, + operations: len(operations), + paths: len(paths), + refs: refCount, + requestBodies: requestBodyCount, + schemas: len(schemas), + }, nil +} + +func validateParity( + originalV2 object, + normalizedV2 object, + openAPIV3 object, + v2Operations map[string]operationInfo, + v3Operations map[string]operationInfo, +) error { + v2Paths := sortedKeys(originalV2["paths"].(object)) + v3Paths := sortedKeys(openAPIV3["paths"].(object)) + if !equalJSON(v2Paths, v3Paths) { + return errors.New("API paths changed during OpenAPI v3 conversion") + } + if len(v2Operations) != len(v3Operations) { + return fmt.Errorf( + "operation count changed from %d to %d", + len(v2Operations), + len(v3Operations), + ) + } + if len(originalV2["paths"].(object)) != len(openAPIV3["paths"].(object)) { + return errors.New("path count changed during OpenAPI v3 conversion") + } + + normalizedOperations, err := collectOperations(normalizedV2, "normalized OpenAPI v2") + if err != nil { + return err + } + rootConsumes := stringArray(normalizedV2["consumes"]) + rootProduces := stringArray(normalizedV2["produces"]) + for key, v2Entry := range v2Operations { + v3Entry, exists := v3Operations[key] + if !exists { + return fmt.Errorf( + "OpenAPI v3 is missing %s %s", + strings.ToUpper(v2Entry.method), + v2Entry.apiPath, + ) + } + for _, property := range []string{"operationId", "summary", "description", "tags"} { + if !equalJSON(v2Entry.operation[property], v3Entry.operation[property]) { + return fmt.Errorf( + "%s changed for %s %s", + property, + strings.ToUpper(v2Entry.method), + v2Entry.apiPath, + ) + } + } + if !equalJSON(v2Entry.responseCodes, v3Entry.responseCodes) { + return fmt.Errorf( + "response codes changed for %s %s", + strings.ToUpper(v2Entry.method), + v2Entry.apiPath, + ) + } + + normalizedEntry := normalizedOperations[key] + if err := validateParameterParity(normalizedEntry, v3Entry); err != nil { + return err + } + if err := validateRequestBodyParity(normalizedEntry, v3Entry, rootConsumes); err != nil { + return err + } + if err := validateResponseParity(normalizedEntry, v3Entry, rootProduces); err != nil { + return err + } + } + + v2Examples, _, err := collectExamples(originalV2) + if err != nil { + return err + } + v3Examples, _, err := collectExamples(openAPIV3) + if err != nil { + return err + } + if !equalJSON(v2Examples, v3Examples) { + return errors.New("examples changed during OpenAPI v3 conversion") + } + + v2Definitions := normalizedV2["definitions"].(object) + v3Components := openAPIV3["components"].(object) + v3Schemas := v3Components["schemas"].(object) + expectedSchemas := rewriteSchemaRefs(v2Definitions) + if !equalJSON(expectedSchemas, v3Schemas) { + return errors.New("component schemas changed during OpenAPI v3 conversion") + } + if len(v2Definitions) != len(v3Schemas) { + return errors.New("component schema count changed during OpenAPI v3 conversion") + } + if !equalJSON(originalV2["tags"], openAPIV3["tags"]) { + return errors.New("root tags changed during OpenAPI v3 conversion") + } + if !equalJSON(originalV2["info"], openAPIV3["info"]) { + return errors.New("API information changed during OpenAPI v3 conversion") + } + + if !hasAnyKey(originalV2, "host", "basePath") { + if _, exists := openAPIV3["servers"]; exists { + return errors.New("OpenAPI v3 conversion invented servers") + } + } + if _, exists := originalV2["securityDefinitions"]; !exists { + if _, exists := v3Components["securitySchemes"]; exists { + return errors.New("OpenAPI v3 conversion invented security schemes") + } + } + if _, exists := originalV2["security"]; !exists { + if _, exists := openAPIV3["security"]; exists { + return errors.New("OpenAPI v3 conversion invented root security policy") + } + } + return nil +} + +func validateNoSwaggerOnlyV3(document object, operations map[string]operationInfo) error { + for _, entry := range operations { + for _, key := range []string{"consumes", "produces", "schemes"} { + if _, exists := entry.operation[key]; exists { + return fmt.Errorf( + "OpenAPI v3 operation %s contains Swagger-only key %q", + operationLabel(entry), + key, + ) + } + } + for _, container := range []object{entry.pathItem, entry.operation} { + parameters, _ := container["parameters"].([]any) + for _, value := range parameters { + parameter, ok := value.(object) + if !ok { + return fmt.Errorf("OpenAPI v3 parameter for %s must be an object", operationLabel(entry)) + } + if parameter["in"] == "body" || parameter["in"] == "formData" { + return fmt.Errorf( + "OpenAPI v3 operation %s contains a Swagger-only %s parameter", + operationLabel(entry), + parameter["in"], + ) + } + for _, key := range []string{"type", "format", "items", "collectionFormat"} { + if _, exists := parameter[key]; exists { + return fmt.Errorf( + "OpenAPI v3 parameter for %s contains Swagger-only key %q", + operationLabel(entry), + key, + ) + } + } + } + } + responses := entry.operation["responses"].(object) + for code, value := range responses { + if strings.HasPrefix(code, "x-") { + continue + } + response, ok := value.(object) + if !ok { + return fmt.Errorf( + "OpenAPI v3 response %s for %s must be an object", + code, + operationLabel(entry), + ) + } + for _, key := range []string{"schema", "examples"} { + if _, exists := response[key]; exists { + return fmt.Errorf( + "OpenAPI v3 response %s for %s contains Swagger-only key %q", + code, + operationLabel(entry), + key, + ) + } + } + } + } + + return walk(document, "#", func(value object, location string) error { + for key := range value { + if strings.HasPrefix(strings.ToLower(key), "x-mintlify") { + return fmt.Errorf( + "OpenAPI v3 contains Mintlify-specific extension %q at %s", + key, + location, + ) + } + } + if ref, ok := value["$ref"].(string); ok && strings.HasPrefix(ref, "#/definitions/") { + return fmt.Errorf("OpenAPI v3 contains a Swagger-only definition reference at %s", location) + } + if _, exists := value["x-originalParamName"]; exists { + return fmt.Errorf("OpenAPI v3 contains converter-only extension at %s", location) + } + return nil + }) +} + +func validateInternalRefs(document object, version string) (int, error) { + count := 0 + err := walk(document, "#", func(value object, location string) error { + refValue, exists := value["$ref"] + if !exists { + return nil + } + count++ + ref, ok := refValue.(string) + if !ok { + return fmt.Errorf("%s $ref at %s must be a string", version, location) + } + if ref != "#" && !strings.HasPrefix(ref, "#/") { + return fmt.Errorf("%s $ref at %s must be internal: %s", version, location, ref) + } + if _, err := resolveJSONPointer(document, ref); err != nil { + return fmt.Errorf("%s $ref at %s does not resolve: %s: %w", version, location, ref, err) + } + return nil + }) + return count, err +} + +func validateServiceCoverage(document object, operations map[string]operationInfo, version string) error { + tags, err := requiredArray(document, "tags", version) + if err != nil { + return err + } + rootTags := make(map[string]struct{}) + for _, value := range tags { + tag, ok := value.(object) + if !ok { + return fmt.Errorf("%s root tag must be an object", version) + } + name, _ := tag["name"].(string) + rootTags[name] = struct{}{} + } + for _, required := range []string{"OpenFGAService", "AuthZenService"} { + if _, exists := rootTags[required]; !exists { + return fmt.Errorf("%s is missing %s tag", version, required) + } + } + + authZenOperations := 0 + openFGAOperations := 0 + for _, entry := range operations { + operationID := entry.operation["operationId"].(string) + if strings.Contains(operationID, "UpdateStore") { + return fmt.Errorf("%s must not expose the unimplemented UpdateStore operation", version) + } + tags, ok := entry.operation["tags"].([]any) + if !ok { + return fmt.Errorf("%s %s tags must be an array", version, operationID) + } + isAuthZen := false + for _, tag := range tags { + if tag == "AuthZenService" { + isAuthZen = true + break + } + } + if isAuthZen { + authZenOperations++ + } else { + openFGAOperations++ + } + } + if authZenOperations == 0 { + return fmt.Errorf("%s must contain AuthZen operations", version) + } + if openFGAOperations == 0 { + return fmt.Errorf("%s must contain OpenFGA operations", version) + } + return nil +} + +func validateContentFree204(operations map[string]operationInfo, version string) error { + for _, entry := range operations { + responses := entry.operation["responses"].(object) + value, exists := responses["204"] + if !exists { + continue + } + response, ok := value.(object) + if !ok { + return fmt.Errorf("%s 204 response for %s must be an object", version, operationLabel(entry)) + } + forbiddenKey := "content" + if version == "OpenAPI v2" { + forbiddenKey = "schema" + } + if _, exists := response[forbiddenKey]; exists { + return fmt.Errorf( + "%s 204 response for %s must not have %s", + version, + operationLabel(entry), + forbiddenKey, + ) + } + } + return nil +} diff --git a/tools/openapiv3/write.go b/tools/openapiv3/write.go new file mode 100644 index 00000000..2ae182bc --- /dev/null +++ b/tools/openapiv3/write.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" +) + +func writeAtomically(filename string, contents []byte) error { + // Same-directory rename prevents readers from observing a partially written generated artifact. + if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil { + return fmt.Errorf("create OpenAPI v3 directory: %w", err) + } + temporary, err := os.CreateTemp(filepath.Dir(filename), "."+filepath.Base(filename)+".*.tmp") + if err != nil { + return fmt.Errorf("create temporary OpenAPI v3 document: %w", err) + } + temporaryName := temporary.Name() + defer os.Remove(temporaryName) + + if err := temporary.Chmod(0o644); err != nil { + temporary.Close() + return fmt.Errorf("set temporary OpenAPI v3 permissions: %w", err) + } + if _, err := temporary.Write(contents); err != nil { + temporary.Close() + return fmt.Errorf("write temporary OpenAPI v3 document: %w", err) + } + if err := temporary.Sync(); err != nil { + temporary.Close() + return fmt.Errorf("sync temporary OpenAPI v3 document: %w", err) + } + if err := temporary.Close(); err != nil { + return fmt.Errorf("close temporary OpenAPI v3 document: %w", err) + } + if err := os.Rename(temporaryName, filename); err != nil { + return fmt.Errorf("replace OpenAPI v3 document: %w", err) + } + return nil +} From 4e62637ff72720517b3f478a9f6aeb461b286ee3 Mon Sep 17 00:00:00 2001 From: Siddhant Khare Date: Thu, 3 Sep 2026 18:40:08 +0530 Subject: [PATCH 4/4] fix: isolate OpenAPI v3 generation Keep the additive converter independent from protobuf generation and enforce strict JSON Pointer array indices. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/review.yaml | 4 +++ Makefile | 7 ++-- tools/openapiv3/json.go | 34 ++++++++++++++++++-- tools/openapiv3/json_test.go | 60 +++++++++++++++++++++++++++++++++++ 4 files changed, 100 insertions(+), 5 deletions(-) create mode 100644 tools/openapiv3/json_test.go diff --git a/.github/workflows/review.yaml b/.github/workflows/review.yaml index 4367d27c..e7af4ee6 100644 --- a/.github/workflows/review.yaml +++ b/.github/workflows/review.yaml @@ -35,6 +35,10 @@ jobs: go-version: 1.26.6 cache-dependency-path: tools/openapiv3/go.sum - run: make test-openapi-v3 + - name: "Verify Standalone OpenAPI v3 Generation" + run: | + make openapi-v3 + git diff --text --exit-code -- docs/openapiv2 proto - name: "Generate OpenAPI & Diff" run: | make all diff --git a/Makefile b/Makefile index 787065ea..0c01cd50 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ -all: openapi-v3 format +all: + $(MAKE) patch-swagger-doc + buf format -w + $(MAKE) openapi-v3 buf-gen: init-git-hooks ./buf.gen.yaml @@ -6,7 +9,7 @@ buf-gen: init-git-hooks patch-swagger-doc: buf-gen ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json -openapi-v3: patch-swagger-doc +openapi-v3: cd tools/openapiv3 && go run . test-openapi-v3: diff --git a/tools/openapiv3/json.go b/tools/openapiv3/json.go index c8e32b4b..f0d18303 100644 --- a/tools/openapiv3/json.go +++ b/tools/openapiv3/json.go @@ -10,6 +10,7 @@ import ( "io" "net/url" "sort" + "strconv" "strings" ) @@ -74,9 +75,9 @@ func resolveJSONPointer(document any, ref string) (any, error) { } current = next case []any: - var index int - if _, err := fmt.Sscanf(decoded, "%d", &index); err != nil || index < 0 || index >= len(value) { - return nil, fmt.Errorf("invalid array index %q", decoded) + index, err := parseArrayIndex(decoded, len(value)) + if err != nil { + return nil, err } current = value[index] default: @@ -86,6 +87,33 @@ func resolveJSONPointer(document any, ref string) (any, error) { return current, nil } +func parseArrayIndex(token string, length int) (int, error) { + if token == "0" { + if length == 0 { + return 0, fmt.Errorf("array index %q is out of range", token) + } + return 0, nil + } + if token == "" || token[0] < '1' || token[0] > '9' { + return 0, fmt.Errorf("invalid array index %q", token) + } + for index := 1; index < len(token); index++ { + if token[index] < '0' || token[index] > '9' { + return 0, fmt.Errorf("invalid array index %q", token) + } + } + + parsed, err := strconv.ParseInt(token, 10, strconv.IntSize) + if err != nil { + return 0, fmt.Errorf("invalid array index %q: %w", token, err) + } + index := int(parsed) + if index >= length { + return 0, fmt.Errorf("array index %q is out of range", token) + } + return index, nil +} + func requiredObject(container object, key, label string) (object, error) { value, exists := container[key] if !exists { diff --git a/tools/openapiv3/json_test.go b/tools/openapiv3/json_test.go new file mode 100644 index 00000000..4de75578 --- /dev/null +++ b/tools/openapiv3/json_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "strconv" + "strings" + "testing" +) + +func TestParseArrayIndex(t *testing.T) { + for _, test := range []struct { + token string + length int + want int + }{ + {token: "0", length: 1, want: 0}, + {token: "1", length: 2, want: 1}, + {token: "10", length: 11, want: 10}, + } { + t.Run(test.token, func(t *testing.T) { + got, err := parseArrayIndex(test.token, test.length) + if err != nil { + t.Fatalf("parseArrayIndex(%q, %d): %v", test.token, test.length, err) + } + if got != test.want { + t.Fatalf("parseArrayIndex(%q, %d) = %d, want %d", test.token, test.length, got, test.want) + } + }) + } +} + +func TestParseArrayIndexRejectsMalformedTokens(t *testing.T) { + for _, test := range []struct { + name string + token string + length int + }{ + {name: "empty", token: "", length: 2}, + {name: "leading zero", token: "01", length: 2}, + {name: "multiple zeroes", token: "00", length: 2}, + {name: "positive sign", token: "+1", length: 2}, + {name: "negative sign", token: "-1", length: 2}, + {name: "partial numeric prefix", token: "1junk", length: 2}, + {name: "leading whitespace", token: " 1", length: 2}, + {name: "trailing whitespace", token: "1 ", length: 2}, + { + name: "int overflow", + token: strconv.FormatUint(uint64(^uint(0)>>1)+1, 10), + length: 2, + }, + {name: "overflow", token: strings.Repeat("9", 100), length: 2}, + {name: "out of range", token: "2", length: 2}, + {name: "zero in empty array", token: "0", length: 0}, + } { + t.Run(test.name, func(t *testing.T) { + if _, err := parseArrayIndex(test.token, test.length); err == nil { + t.Fatalf("parseArrayIndex(%q, %d) succeeded", test.token, test.length) + } + }) + } +}