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..52d35fdc 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -11,6 +11,15 @@ updates: patterns: - "*" + - package-ecosystem: "gomod" + directory: "/tools/openapiv3" + 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..e7af4ee6 100644 --- a/.github/workflows/review.yaml +++ b/.github/workflows/review.yaml @@ -30,10 +30,19 @@ jobs: with: fetch-depth: 0 - uses: bufbuild/buf-setup-action@a47c93e0b1648d5651a065437926377d060baa99 # v1.50.0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + 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 - 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 +54,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/Makefile b/Makefile index c70c06cc..0c01cd50 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ -all: patch-swagger-doc format +all: + $(MAKE) patch-swagger-doc + buf format -w + $(MAKE) openapi-v3 buf-gen: init-git-hooks ./buf.gen.yaml @@ -6,6 +9,12 @@ buf-gen: init-git-hooks patch-swagger-doc: buf-gen ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json +openapi-v3: + 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 dd887f03..d65d1ce2 100644 --- a/README.md +++ b/README.md @@ -55,13 +55,16 @@ 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/) and Go installed. ```bash ./buf.gen.yaml ./scripts/update_swagger.sh docs/openapiv2/apidocs.swagger.json +(cd tools/openapiv3 && go run .) buf format -w ``` @@ -70,6 +73,12 @@ Or you can just use 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`. + 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..7b837bab --- /dev/null +++ b/docs/openapiv3/apidocs.openapi.json @@ -0,0 +1,5146 @@ +{ + "components": { + "schemas": { + "AbortedMessageResponse": { + "example": { + "code": "10", + "message": "transaction conflict" + }, + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "type": "object" + }, + "Action": { + "properties": { + "name": { + "example": "can_read", + "type": "string" + }, + "properties": { + "type": "object" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "ActionSearchBody": { + "properties": { + "context": { + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageRequest" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "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" + } + ] + }, + "results": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Action" + }, + { + "type": "object" + } + ] + }, + "type": "array" + } + }, + "type": "object" + }, + "Any": { + "additionalProperties": {}, + "properties": { + "@type": { + "type": "string" + } + }, + "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" + }, + "contextual_tuples": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "maxItems": 20, + "type": "array" + }, + "expectation": { + "type": "boolean" + }, + "tuple_key": { + "$ref": "#/components/schemas/AssertionTupleKey" + } + }, + "required": [ + "tuple_key", + "expectation" + ], + "type": "object" + }, + "AssertionTupleKey": { + "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": [ + "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" + }, + "id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + }, + "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" + } + }, + "required": [ + "id", + "schema_version", + "type_definitions" + ], + "type": "object" + }, + "BatchCheckBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + }, + "checks": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/BatchCheckItem" + }, + { + "type": "object" + } + ] + }, + "minItems": 1, + "type": "array" + }, + "consistency": { + "$ref": "#/components/schemas/ConsistencyPreference" + } + }, + "required": [ + "checks" + ], + "type": "object" + }, + "BatchCheckItem": { + "properties": { + "context": { + "type": "object" + }, + "contextual_tuples": { + "$ref": "#/components/schemas/ContextualTupleKeys" + }, + "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" + }, + "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" + }, + "error": { + "$ref": "#/components/schemas/CheckError" + } + }, + "type": "object" + }, + "CheckBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + }, + "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" + }, + "trace": { + "description": "Defaults to false. Making it true has performance implications.", + "example": false, + "readOnly": true, + "type": "boolean" + }, + "tuple_key": { + "$ref": "#/components/schemas/CheckRequestTupleKey" + } + }, + "required": [ + "tuple_key" + ], + "type": "object" + }, + "CheckError": { + "properties": { + "input_error": { + "$ref": "#/components/schemas/ErrorCode" + }, + "internal_error": { + "$ref": "#/components/schemas/InternalErrorCode" + }, + "message": { + "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" + ], + "type": "object" + }, + "CheckResponse": { + "properties": { + "allowed": { + "example": true, + "type": "boolean" + }, + "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" + }, + "metadata": { + "$ref": "#/components/schemas/ConditionMetadata" + }, + "name": { + "title": "A unique name for the condition", + "type": "string" + }, + "parameters": { + "additionalProperties": { + "$ref": "#/components/schemas/ConditionParamTypeRef" + }, + "description": "A map of parameter names to the parameter's defined type reference.", + "type": "object" + } + }, + "required": [ + "name", + "expression" + ], + "type": "object" + }, + "ConditionMetadata": { + "properties": { + "module": { + "type": "string" + }, + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + }, + "type": "object" + }, + "ConditionParamTypeRef": { + "properties": { + "generic_types": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/ConditionParamTypeRef" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "type_name": { + "$ref": "#/components/schemas/TypeName" + } + }, + "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" + ], + "type": "object" + }, + "CreateStoreRequest": { + "properties": { + "name": { + "example": "my-store-name", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "CreateStoreResponse": { + "properties": { + "created_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" + }, + "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" + ], + "type": "string" + }, + "EvaluationBody": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" + }, + "context": { + "type": "object" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "subject": { + "$ref": "#/components/schemas/Subject" + } + }, + "required": [ + "subject", + "resource", + "action" + ], + "type": "object" + }, + "EvaluationResponse": { + "properties": { + "context": { + "type": "object" + }, + "decision": { + "type": "boolean" + } + }, + "type": "object" + }, + "EvaluationsBody": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" + }, + "context": { + "type": "object" + }, + "evaluations": { + "description": "Optional. If omitted or empty, behaves like a single Access Evaluation request.", + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsItemRequest" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "options": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsOptions" + }, + { + "title": "Options for batch evaluation semantics" + } + ] + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "subject": { + "$ref": "#/components/schemas/Subject" + } + }, + "type": "object" + }, + "EvaluationsItemRequest": { + "properties": { + "action": { + "$ref": "#/components/schemas/Action" + }, + "context": { + "type": "object" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "subject": { + "$ref": "#/components/schemas/Subject" + } + }, + "type": "object" + }, + "EvaluationsOptions": { + "properties": { + "evaluations_semantic": { + "allOf": [ + { + "$ref": "#/components/schemas/EvaluationsSemantic" + }, + { + "title": "Controls how batch evaluations are processed" + } + ] + } + }, + "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" + }, + "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" + }, + "tuple_key": { + "$ref": "#/components/schemas/ExpandRequestTupleKey" + } + }, + "required": [ + "tuple_key" + ], + "type": "object" + }, + "ExpandRequestTupleKey": { + "properties": { + "object": { + "example": "document:2021-budget", + "maxLength": 256, + "type": "string" + }, + "relation": { + "example": "reader", + "maxLength": 50, + "type": "string" + } + }, + "required": [ + "relation", + "object" + ], + "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" + }, + "message": { + "type": "string" + } + }, + "type": "object" + }, + "GetConfigurationResponse": { + "properties": { + "access_evaluation_endpoint": { + "description": "REQUIRED. The access evaluation endpoint URL.", + "type": "string" + }, + "access_evaluations_endpoint": { + "description": "OPTIONAL. The batch evaluations endpoint URL.", + "type": "string" + }, + "capabilities": { + "description": "OPTIONAL. Supported capabilities as URN strings.", + "items": { + "type": "string" + }, + "type": "array" + }, + "policy_decision_point": { + "description": "REQUIRED. The PDP identifier URL (HTTPS, no query or fragment).", + "type": "string" + }, + "search_action_endpoint": { + "description": "OPTIONAL. The action search endpoint URL.", + "type": "string" + }, + "search_resource_endpoint": { + "description": "OPTIONAL. The resource search endpoint URL.", + "type": "string" + }, + "search_subject_endpoint": { + "description": "OPTIONAL. The subject search endpoint URL.", + "type": "string" + }, + "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" + } + }, + "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" + }, + "tupleToUserset": { + "$ref": "#/components/schemas/UsersetTree.TupleToUserset" + }, + "users": { + "$ref": "#/components/schemas/Users" + } + }, + "type": "object" + }, + "ListObjectsBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + }, + "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" + } + }, + "required": [ + "type", + "relation", + "user" + ], + "type": "object" + }, + "ListObjectsResponse": { + "properties": { + "objects": { + "example": [ + "document:roadmap", + "document:planning" + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "objects" + ], + "type": "object" + }, + "ListStoresResponse": { + "properties": { + "continuation_token": { + "description": "The continuation token will be empty if there are no more stores.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" + }, + "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" + }, + "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": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleKey" + }, + { + "type": "object" + } + ] + }, + "maxItems": 100, + "type": "array" + }, + "object": { + "allOf": [ + { + "$ref": "#/components/schemas/Object" + }, + { + "example": "document:example" + } + ] + }, + "relation": { + "example": "reader", + "type": "string" + }, + "user_filters": { + "description": "The type of results returned. Only accepts exactly one value.", + "example": [ + { + "type": "user" + }, + { + "relation": "member", + "type": "group" + } + ], + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/UserTypeFilter" + }, + { + "type": "object" + } + ] + }, + "maxItems": 1, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "object", + "relation", + "user_filters" + ], + "type": "object" + }, + "ListUsersResponse": { + "properties": { + "users": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/User" + }, + { + "type": "object" + } + ] + }, + "type": "array" + } + }, + "required": [ + "users" + ], + "type": "object" + }, + "Metadata": { + "properties": { + "module": { + "type": "string" + }, + "relations": { + "additionalProperties": { + "$ref": "#/components/schemas/RelationMetadata" + }, + "type": "object" + }, + "source_info": { + "$ref": "#/components/schemas/SourceInfo" + } + }, + "type": "object" + }, + "Node": { + "properties": { + "difference": { + "$ref": "#/components/schemas/UsersetTree.Difference" + }, + "intersection": { + "$ref": "#/components/schemas/Nodes" + }, + "leaf": { + "$ref": "#/components/schemas/Leaf" + }, + "name": { + "type": "string" + }, + "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" + }, + "relation": { + "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" + } + }, + "title": "Pagination request parameters for search operations", + "type": "object" + }, + "PageResponse": { + "properties": { + "count": { + "format": "int64", + "title": "Number of results in this page", + "type": "integer" + }, + "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" + } + }, + "title": "Pagination response parameters", + "type": "object" + }, + "PathUnknownErrorMessageResponse": { + "example": { + "code": "undefined_endpoint", + "message": "Endpoint not enabled" + }, + "properties": { + "code": { + "$ref": "#/components/schemas/NotFoundErrorCode" + }, + "message": { + "type": "string" + } + }, + "type": "object" + }, + "ReadAssertionsResponse": { + "properties": { + "assertions": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Assertion" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "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" + }, + "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." + } + ] + }, + "continuation_token": { + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" + }, + "page_size": { + "example": 50, + "format": "int32", + "maximum": 100, + "minimum": 1, + "type": "integer" + }, + "tuple_key": { + "$ref": "#/components/schemas/ReadRequestTupleKey" + } + }, + "type": "object" + }, + "ReadChangesResponse": { + "properties": { + "changes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TupleChange" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "continuation_token": { + "description": "The continuation token will be identical if there are no new changes.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" + } + }, + "required": [ + "changes" + ], + "type": "object" + }, + "ReadRequestTupleKey": { + "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" + } + }, + "type": "object" + }, + "ReadResponse": { + "properties": { + "continuation_token": { + "description": "The continuation token will be empty if there are no more tuples.", + "example": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", + "type": "string" + }, + "tuples": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Tuple" + }, + { + "type": "object" + } + ] + }, + "type": "array" + } + }, + "required": [ + "tuples", + "continuation_token" + ], + "type": "object" + }, + "RelationMetadata": { + "properties": { + "directly_related_user_types": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/RelationReference" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "module": { + "type": "string" + }, + "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" + }, + "relation": { + "example": "member", + "type": "string" + }, + "type": { + "example": "group", + "type": "string" + }, + "wildcard": { + "$ref": "#/components/schemas/Wildcard" + } + }, + "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" + ], + "type": "object" + }, + "Resource": { + "properties": { + "id": { + "example": "roadmap", + "type": "string" + }, + "properties": { + "type": "object" + }, + "type": { + "example": "document", + "type": "string" + } + }, + "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" + }, + "properties": { + "type": "object" + }, + "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" + }, + "context": { + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageRequest" + }, + "resource": { + "allOf": [ + { + "$ref": "#/components/schemas/ResourceFilter" + }, + { + "title": "Filter by resource type" + } + ] + }, + "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" + } + ] + }, + "results": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Resource" + }, + { + "type": "object" + } + ] + }, + "type": "array" + } + }, + "type": "object" + }, + "SourceInfo": { + "properties": { + "file": { + "type": "string" + } + }, + "type": "object" + }, + "Status": { + "properties": { + "code": { + "format": "int32", + "type": "integer" + }, + "details": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Any" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "message": { + "type": "string" + } + }, + "type": "object" + }, + "Store": { + "properties": { + "created_at": { + "format": "date-time", + "type": "string" + }, + "deleted_at": { + "format": "date-time", + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "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" + }, + "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" + } + }, + "required": [ + "type", + "relation", + "user" + ], + "type": "object" + }, + "StreamedListObjectsResponse": { + "description": "The response for a StreamedListObjects RPC.", + "properties": { + "object": { + "example": "document:roadmap", + "type": "string" + } + }, + "required": [ + "object" + ], + "type": "object" + }, + "Subject": { + "properties": { + "id": { + "example": "anne", + "type": "string" + }, + "properties": { + "type": "object" + }, + "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" + }, + "properties": { + "type": "object" + }, + "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" + }, + "context": { + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageRequest" + }, + "resource": { + "$ref": "#/components/schemas/Resource" + }, + "subject": { + "allOf": [ + { + "$ref": "#/components/schemas/SubjectFilter" + }, + { + "description": "REQUIRED by AuthZEN Subject Search. Subject `id` may be provided but is ignored." + } + ] + } + }, + "required": [ + "resource", + "action", + "subject" + ], + "title": "SubjectSearch request", + "type": "object" + }, + "SubjectSearchResponse": { + "properties": { + "page": { + "allOf": [ + { + "$ref": "#/components/schemas/PageResponse" + }, + { + "title": "Optional per AuthZEN spec - omit if pagination not supported" + } + ] + }, + "results": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Subject" + }, + { + "type": "object" + } + ] + }, + "type": "array" + } + }, + "type": "object" + }, + "Tuple": { + "properties": { + "key": { + "$ref": "#/components/schemas/TupleKey" + }, + "timestamp": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "key", + "timestamp" + ], + "type": "object" + }, + "TupleChange": { + "properties": { + "operation": { + "$ref": "#/components/schemas/TupleOperation" + }, + "timestamp": { + "format": "date-time", + "type": "string" + }, + "tuple_key": { + "$ref": "#/components/schemas/TupleKey" + } + }, + "required": [ + "tuple_key", + "operation", + "timestamp" + ], + "type": "object" + }, + "TupleKey": { + "properties": { + "condition": { + "$ref": "#/components/schemas/RelationshipCondition" + }, + "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" + ], + "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" + ], + "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." + } + ] + }, + "relations": { + "additionalProperties": { + "$ref": "#/components/schemas/Userset" + }, + "example": { + "reader": { + "union": { + "child": [ + { + "this": {} + }, + { + "computedUserset": { + "object": "", + "relation": "writer" + } + } + ] + } + }, + "writer": { + "this": {} + } + }, + "type": "object" + }, + "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" + }, + "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" + }, + "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" + }, + "userset": { + "$ref": "#/components/schemas/UsersetUser" + }, + "wildcard": { + "$ref": "#/components/schemas/TypedWildcard" + } + }, + "type": "object" + }, + "UserTypeFilter": { + "properties": { + "relation": { + "example": "member", + "type": "string" + }, + "type": { + "example": "group", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "Users": { + "properties": { + "users": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "users" + ], + "type": "object" + }, + "Userset": { + "properties": { + "computedUserset": { + "$ref": "#/components/schemas/ObjectRelation" + }, + "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" + } + }, + "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" + }, + "subtract": { + "$ref": "#/components/schemas/Node" + } + }, + "required": [ + "base", + "subtract" + ], + "type": "object" + }, + "UsersetTree.TupleToUserset": { + "properties": { + "computed": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Computed" + }, + { + "type": "object" + } + ] + }, + "type": "array" + }, + "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" + }, + "relation": { + "example": "member", + "type": "string" + }, + "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" + }, + "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" + }, + "schema_version": { + "type": "string" + }, + "type_definitions": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/TypeDefinition" + }, + { + "type": "object" + } + ] + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "type_definitions", + "schema_version" + ], + "type": "object" + }, + "WriteAuthorizationModelResponse": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + } + }, + "required": [ + "authorization_model_id" + ], + "type": "object" + }, + "WriteBody": { + "properties": { + "authorization_model_id": { + "example": "01G5JAVJ41T49E9TT3SKVS7X1J", + "type": "string" + }, + "deletes": { + "$ref": "#/components/schemas/WriteRequestDeletes" + }, + "writes": { + "$ref": "#/components/schemas/WriteRequestWrites" + } + }, + "type": "object" + }, + "WriteRequestDeletes": { + "properties": { + "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" + }, + "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" + }, + "WriteResponse": { + "type": "object" + }, + "v1.Difference": { + "properties": { + "base": { + "$ref": "#/components/schemas/Userset" + }, + "subtract": { + "$ref": "#/components/schemas/Userset" + } + }, + "required": [ + "base", + "subtract" + ], + "type": "object" + }, + "v1.TupleToUserset": { + "properties": { + "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." + }, + "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." + }, + "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." + } + }, + "summary": "[Experimental] Get AuthZEN PDP configuration and capabilities", + "tags": [ + "AuthZenService" + ] + } + }, + "/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" + } + }, + { + "in": "query", + "name": "continuation_token", + "required": false, + "schema": { + "type": "string" + } + }, + { + "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" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListStoresResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "List all stores", + "tags": [ + "Stores" + ] + }, + "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" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateStoreResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Create a store", + "tags": [ + "Stores" + ] + } + }, + "/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" + } + } + }, + "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." + }, + "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." + } + }, + "summary": "Delete a store", + "tags": [ + "Stores" + ] + }, + "get": { + "description": "Returns an OpenFGA store by its identifier", + "operationId": "GetStore", + "parameters": [ + { + "in": "path", + "name": "store_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetStoreResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Get a store", + "tags": [ + "Stores" + ] + } + }, + "/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" + } + } + ], + "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" + } + } + }, + "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." + }, + "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." + } + }, + "summary": "[Experimental] Evaluate whether a subject can perform an action on a resource", + "tags": [ + "AuthZenService" + ] + } + }, + "/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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationsBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EvaluationsResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActionSearchBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActionSearchResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "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" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResourceSearchResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "[Experimental] Search for resources a subject has access to", + "tags": [ + "AuthZenService" + ] + } + }, + "/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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSearchBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSearchResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "[Experimental] Search for subjects with access to a resource", + "tags": [ + "AuthZenService" + ] + } + }, + "/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" + } + }, + { + "in": "path", + "name": "authorization_model_id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAssertionsResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Read assertions for an authorization model ID", + "tags": [ + "Assertions" + ] + }, + "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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAssertionsBody" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Upsert assertions for an authorization model ID", + "tags": [ + "Assertions" + ] + } + }, + "/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" + } + }, + { + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "format": "int32", + "type": "integer" + } + }, + { + "in": "query", + "name": "continuation_token", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAuthorizationModelsResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Return all the authorization models for a particular store", + "tags": [ + "Authorization Models" + ] + }, + "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" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteAuthorizationModelResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Create a new authorization model", + "tags": [ + "Authorization Models" + ] + } + }, + "/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" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadAuthorizationModelResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Return a particular version of an authorization model", + "tags": [ + "Authorization Models" + ] + } + }, + "/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 + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchCheckResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Send a list of `check` operations in a single request", + "tags": [ + "Relationship Queries" + ] + } + }, + "/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" + } + }, + { + "in": "query", + "name": "type", + "required": false, + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "format": "int32", + "type": "integer" + } + }, + { + "in": "query", + "name": "continuation_token", + "required": false, + "schema": { + "type": "string" + } + }, + { + "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" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadChangesResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Return a list of all the tuple changes", + "tags": [ + "Relationship Tuples" + ] + } + }, + "/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" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Check whether a user is authorized to access an object", + "tags": [ + "Relationship Queries" + ] + } + }, + "/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 + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExpandResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "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" + ] + } + }, + "/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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListObjectsBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListObjectsResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "List all objects of the given type that the user has a relation with", + "tags": [ + "Relationship Queries" + ] + } + }, + "/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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListUsersBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListUsersResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "List the users matching the provided filter who have a certain relation to a particular type.", + "tags": [ + "Relationship Queries" + ] + } + }, + "/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 + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Get tuples from the store that matches a query, without following userset rewrite rules", + "tags": [ + "Relationship Tuples" + ] + } + }, + "/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 + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "properties": { + "error": { + "$ref": "#/components/schemas/Status" + }, + "result": { + "$ref": "#/components/schemas/StreamedListObjectsResponse" + } + }, + "title": "Stream result of StreamedListObjectsResponse", + "type": "object" + } + } + }, + "description": "A successful response.(streaming responses)" + }, + "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." + }, + "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." + } + }, + "summary": "Stream all objects of the given type that the user has a relation with", + "tags": [ + "Relationship Queries" + ] + } + }, + "/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 + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResponse" + } + } + }, + "description": "A successful response." + }, + "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." + }, + "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." + } + }, + "summary": "Add or delete tuples from the store", + "tags": [ + "Relationship Tuples" + ] + } + } + }, + "tags": [ + { + "name": "AuthZenService" + }, + { + "name": "OpenFGAService" + } + ] +} 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/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/json.go b/tools/openapiv3/json.go new file mode 100644 index 00000000..f0d18303 --- /dev/null +++ b/tools/openapiv3/json.go @@ -0,0 +1,238 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/url" + "sort" + "strconv" + "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: + index, err := parseArrayIndex(decoded, len(value)) + if err != nil { + return nil, err + } + current = value[index] + default: + return nil, fmt.Errorf("cannot traverse %q", decoded) + } + } + 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 { + 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/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) + } + }) + } +} diff --git a/tools/openapiv3/main.go b/tools/openapiv3/main.go new file mode 100644 index 00000000..13dda2cb --- /dev/null +++ b/tools/openapiv3/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "flag" + "fmt" + "os" +) + +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) +} 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) +} 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 +}