From 078bfd8e941cb9dba1e03f4f078f99ee86e14a6f Mon Sep 17 00:00:00 2001 From: LucaCappelletti94 Date: Thu, 19 Nov 2026 14:16:01 +0100 Subject: [PATCH] Add openfga-model generated from authzmodel.proto --- .github/workflows/ci.yml | 66 + .gitignore | 1 + .gitmodules | 3 + Cargo.lock | 558 ++++ Cargo.toml | 23 + README.md | 13 + codecov.yml | 3 + codegen/Cargo.toml | 19 + codegen/proto/google/api/field_behavior.proto | 104 + codegen/proto/openfga/v1/authzmodel.proto | 265 ++ .../options/annotations.proto | 51 + .../options/openapiv2.proto | 762 ++++++ codegen/proto/validate/validate.proto | 862 +++++++ codegen/src/main.rs | 123 + conformance/openfga-language | 1 + crates/openfga-model/Cargo.toml | 23 + crates/openfga-model/README.md | 40 + .../openfga-model/src/generated/openfga.v1.rs | 254 ++ .../src/generated/openfga.v1.serde.rs | 2249 +++++++++++++++++ crates/openfga-model/src/lib.rs | 20 + crates/openfga-model/tests/conformance.rs | 98 + 21 files changed, 5538 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 codecov.yml create mode 100644 codegen/Cargo.toml create mode 100644 codegen/proto/google/api/field_behavior.proto create mode 100644 codegen/proto/openfga/v1/authzmodel.proto create mode 100644 codegen/proto/protoc-gen-openapiv2/options/annotations.proto create mode 100644 codegen/proto/protoc-gen-openapiv2/options/openapiv2.proto create mode 100644 codegen/proto/validate/validate.proto create mode 100644 codegen/src/main.rs create mode 160000 conformance/openfga-language create mode 100644 crates/openfga-model/Cargo.toml create mode 100644 crates/openfga-model/README.md create mode 100644 crates/openfga-model/src/generated/openfga.v1.rs create mode 100644 crates/openfga-model/src/generated/openfga.v1.serde.rs create mode 100644 crates/openfga-model/src/lib.rs create mode 100644 crates/openfga-model/tests/conformance.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6624ef2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,66 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + RUSTFLAGS: -D warnings + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + - run: rustup toolchain install stable --profile minimal --component rustfmt,clippy --target thumbv7em-none-eabihf && rustup default stable + - run: cargo fmt --all --check + - run: cargo run -p codegen --locked -- --check + - run: cargo clippy --workspace --all-targets --all-features --locked + - run: cargo build -p openfga-model --target thumbv7em-none-eabihf --locked + - run: cargo doc --no-deps --all-features --locked + env: + RUSTDOCFLAGS: -D warnings + - run: cargo test --workspace --all-features --locked + + msrv: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: rustup toolchain install 1.88 --profile minimal && rustup default 1.88 + - run: cargo check -p openfga-model --lib --locked + + coverage: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + RUSTFLAGS: "" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + submodules: true + - run: rustup toolchain install nightly --profile minimal --component llvm-tools-preview && rustup default nightly + - uses: taiki-e/install-action@b80e2bb2635f28eb98b9fce1e2f0887e1535c6b2 # v2.90.0 + with: + tool: cargo-llvm-cov + - run: mkdir -p target/coverage + - run: cargo llvm-cov -p openfga-model --all-targets --all-features --locked --no-report + - run: cargo llvm-cov -p openfga-model --doc --all-features --locked --no-clean --lcov --output-path target/coverage/coverage.lcov + - uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + if: github.actor != 'dependabot[bot]' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) + with: + files: target/coverage/coverage.lcov + fail_ci_if_error: true + use_oidc: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..6b2a6a1 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "conformance/openfga-language"] + path = conformance/openfga-language + url = https://github.com/openfga/language diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..cab037e --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,558 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "codegen" +version = "0.0.0" +dependencies = [ + "anyhow", + "pbjson-build", + "prost", + "prost-build", + "protox", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "logos" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-codegen" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970" +dependencies = [ + "fnv", + "proc-macro2", + "quote", + "regex-automata", + "regex-syntax", + "syn 2.0.119", +] + +[[package]] +name = "logos-derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31" +dependencies = [ + "logos-codegen", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openfga-model" +version = "0.1.0" +dependencies = [ + "prost", + "serde", + "serde_json", +] + +[[package]] +name = "pbjson-build" +version = "0.9.0" +source = "git+https://github.com/LucaCappelletti94/pbjson?rev=d489b9731af2fbee9b881dfa8dcd507dc8339788#d489b9731af2fbee9b881dfa8dcd507dc8339788" +dependencies = [ + "heck", + "itertools 0.14.0", + "prost", + "prost-types", +] + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6e4d69d0fa3e7f6f9cf6b53a0e83e4fc99ba3586f65ce166cff30bd13bb4ad2" +dependencies = [ + "heck", + "itertools 0.15.0", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 3.0.10", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools 0.15.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-reflect" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1" +dependencies = [ + "logos", + "miette", + "prost", + "prost-types", +] + +[[package]] +name = "prost-types" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f29a7c4c7a84cef41a53d338a2d10d4f1b043ea5c3dde26db22ee2c9c1b1c75b" +dependencies = [ + "prost", +] + +[[package]] +name = "protox" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f43240d7f22cf77d1625885e547acf874dd63cd2790f29f4a38e86256f41996f" +dependencies = [ + "bytes", + "miette", + "prost", + "prost-reflect", + "prost-types", + "protox-parse", + "thiserror", +] + +[[package]] +name = "protox-parse" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34efee6fad0cf6d71642d20a66bfe0c281919c9577e7c66d20360dfcb7549272" +dependencies = [ + "logos", + "miette", + "prost-types", + "thiserror", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f5e4e78 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,23 @@ +[workspace] +resolver = "3" +members = ["codegen", "crates/openfga-model"] + +[workspace.package] +edition = "2024" +rust-version = "1.88" +license = "Apache-2.0" +repository = "https://github.com/LucaCappelletti94/openfga-rs" +authors = ["Luca Cappelletti "] + +[workspace.lints.rust] +missing_docs = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } +unreachable_pub = "warn" +unsafe_code = "forbid" +unused_qualifications = "warn" + +[workspace.lints.clippy] +all = { level = "deny", priority = -1 } +pedantic = { level = "warn", priority = -1 } +allow_attributes = "deny" +allow_attributes_without_reason = "deny" diff --git a/README.md b/README.md new file mode 100644 index 0000000..7152ee8 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# openfga-rs + +[![CI](https://github.com/LucaCappelletti94/openfga-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/LucaCappelletti94/openfga-rs/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/LucaCappelletti94/openfga-rs/graph/badge.svg)](https://codecov.io/gh/LucaCappelletti94/openfga-rs) +[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/LucaCappelletti94/openfga-rs/blob/main/LICENSE) + +[OpenFGA](https://openfga.dev) authorization models in Rust, `no_std`. + +| Crate | What it holds | +|---|---| +| [`openfga-model`](crates/openfga-model) | The model types generated from `authzmodel.proto`, with protobuf binary and JSON encodings | + +Conformance tests read the pinned [openfga/language](https://github.com/openfga/language) corpus, so clone with `--recurse-submodules`. diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..7f8ff1f --- /dev/null +++ b/codecov.yml @@ -0,0 +1,3 @@ +ignore: + - crates/openfga-model/src/generated + - codegen diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml new file mode 100644 index 0000000..7845a46 --- /dev/null +++ b/codegen/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "codegen" +version = "0.0.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish = false +description = "Generates openfga-model's src/generated modules from the vendored OpenFGA protos" + +[dependencies] +anyhow = "1" +# The branch of influxdata/pbjson#163, which makes the generated serde code compile under no_std. +pbjson-build = { git = "https://github.com/LucaCappelletti94/pbjson", rev = "d489b9731af2fbee9b881dfa8dcd507dc8339788" } +prost = "0.14.1" +prost-build = "0.14.1" +protox = "0.10.0" + +[lints] +workspace = true diff --git a/codegen/proto/google/api/field_behavior.proto b/codegen/proto/google/api/field_behavior.proto new file mode 100644 index 0000000..861f825 --- /dev/null +++ b/codegen/proto/google/api/field_behavior.proto @@ -0,0 +1,104 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "FieldBehaviorProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.FieldOptions { + // A designation of a specific field behavior (required, output only, etc.) + // in protobuf messages. + // + // Examples: + // + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; + repeated google.api.FieldBehavior field_behavior = 1052 [packed = false]; +} + +// An indicator of the behavior of a given field (for example, that a field +// is required in requests, or given as output but ignored as input). +// This **does not** change the behavior in protocol buffers itself; it only +// denotes the behavior and may affect how API tooling handles the field. +// +// Note: This enum **may** receive new values in the future. +enum FieldBehavior { + // Conventional default for enums. Do not use this. + FIELD_BEHAVIOR_UNSPECIFIED = 0; + + // Specifically denotes a field as optional. + // While all fields in protocol buffers are optional, this may be specified + // for emphasis if appropriate. + OPTIONAL = 1; + + // Denotes a field as required. + // This indicates that the field **must** be provided as part of the request, + // and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + REQUIRED = 2; + + // Denotes a field as output only. + // This indicates that the field is provided in responses, but including the + // field in a request does nothing (the server *must* ignore it and + // *must not* throw an error as a result of the field's presence). + OUTPUT_ONLY = 3; + + // Denotes a field as input only. + // This indicates that the field is provided in requests, and the + // corresponding field is not included in output. + INPUT_ONLY = 4; + + // Denotes a field as immutable. + // This indicates that the field may be set once in a request to create a + // resource, but may not be changed thereafter. + IMMUTABLE = 5; + + // Denotes that a (repeated) field is an unordered list. + // This indicates that the service may provide the elements of the list + // in any arbitrary order, rather than the order the user originally + // provided. Additionally, the list's order may or may not be stable. + UNORDERED_LIST = 6; + + // Denotes that this field returns a non-empty default value if not set. + // This indicates that if the user provides the empty value in a request, + // a non-empty value will be returned. The user will not be aware of what + // non-empty value to expect. + NON_EMPTY_DEFAULT = 7; + + // Denotes that the field in a resource (a message annotated with + // google.api.resource) is used in the resource name to uniquely identify the + // resource. For AIP-compliant APIs, this should only be applied to the + // `name` field on the resource. + // + // This behavior should not be applied to references to other resources within + // the message. + // + // The identifier field of resources often have different field behavior + // depending on the request it is embedded in (e.g. for Create methods name + // is optional and unused, while for Update methods it is required). Instead + // of method-specific annotations, only `IDENTIFIER` is required. + IDENTIFIER = 8; +} diff --git a/codegen/proto/openfga/v1/authzmodel.proto b/codegen/proto/openfga/v1/authzmodel.proto new file mode 100644 index 0000000..67fcf45 --- /dev/null +++ b/codegen/proto/openfga/v1/authzmodel.proto @@ -0,0 +1,265 @@ +syntax = "proto3"; + +package openfga.v1; + +import "google/api/field_behavior.proto"; +import "protoc-gen-openapiv2/options/annotations.proto"; +import "validate/validate.proto"; + +message AuthorizationModel { + string id = 1 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).string = { + pattern: "^[ABCDEFGHJKMNPQRSTVWXYZ0-9]{26}$" + ignore_empty: false + }, + (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {example: "\"01G5JAVJ41T49E9TT3SKVS7X1J\""} + ]; + + string schema_version = 2 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).string = { + pattern: "^[1-9].[1-9]$" + ignore_empty: false + }, + json_name = "schema_version" + ]; + + repeated TypeDefinition type_definitions = 3 [ + json_name = "type_definitions", + (google.api.field_behavior) = REQUIRED, + (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {example: "[{\"type\": \"user\"}, {\"type\":\"document\",\"relations\":{\"reader\":{\"union\":{\"child\":[{\"this\":{}},{\"computedUserset\":{\"object\":\"\",\"relation\":\"writer\"}}]}},\"writer\":{\"this\":{}}},\"metadata\":{\"relations\":{\"reader\":{\"directly_related_user_types\":[{\"type\":\"user\"}]},\"writer\":{\"directly_related_user_types\":[{\"type\":\"user\"}]}}}}]"} + ]; + + map conditions = 4 [ + json_name = "conditions", + (validate.rules).map.max_pairs = 25, + (validate.rules).map.keys.string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: false + } + ]; +} + +message TypeDefinition { + string type = 1 [ + (validate.rules).string = { + pattern: "^[^:#@\\s]{1,254}$" + ignore_empty: false + }, + (google.api.field_behavior) = REQUIRED, + (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {example: "\"document\""} + ]; + + map relations = 2 [ + (validate.rules).map.keys.string = {pattern: "^[^:#@\\s]{1,50}$"}, + (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {example: "{\"reader\":{\"union\":{\"child\":[{\"this\":{}},{\"computedUserset\":{\"object\":\"\",\"relation\":\"writer\"}}]}},\"writer\":{\"this\":{}}}"} + ]; + + // A map whose keys are the name of the relation and whose value is the Metadata for that relation. + // It also holds information around the module name and source file if this model was constructed + // from a modular model. + Metadata metadata = 3; +} + +message Relation { + string name = 1 [(validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: false + }]; + + Userset rewrite = 2 [ + (validate.rules).message.required = true, + (google.api.field_behavior) = REQUIRED + ]; + + RelationTypeInfo type_info = 3; +} + +message RelationTypeInfo { + repeated RelationReference directly_related_user_types = 1 [json_name = "directly_related_user_types"]; +} + +message Metadata { + map relations = 1; + + string module = 2 [(validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: true + }]; + + SourceInfo source_info = 3 [json_name = "source_info"]; +} + +message SourceInfo { + string file = 1 [(validate.rules).string = { + pattern: "^[a-zA-Z0-9_\\-\\/]{1,100}\\.fga$" + ignore_empty: true + }]; +} + +message RelationMetadata { + repeated RelationReference directly_related_user_types = 1 [json_name = "directly_related_user_types"]; + + string module = 2 [(validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: true + }]; + + SourceInfo source_info = 3 [json_name = "source_info"]; +} + +// RelationReference represents a relation of a particular object type (e.g. 'document#viewer'). +message RelationReference { + string type = 1 [ + (validate.rules).string = { + pattern: "^[^:#@\\s]{1,254}$" + ignore_empty: false + }, + (google.api.field_behavior) = REQUIRED, + (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {example: "\"group\""} + ]; + + oneof relation_or_wildcard { + string relation = 2 [ + (validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: true + }, + (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {example: "\"member\""} + ]; + + Wildcard wildcard = 3; + } + + // The name of a condition that is enforced over the allowed relation. + string condition = 4 [(validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: true + }]; +} + +message Wildcard {} + +message Usersets { + repeated Userset child = 1 [(google.api.field_behavior) = REQUIRED]; +} + +message Difference { + Userset base = 1 [ + (validate.rules).message.required = true, + (google.api.field_behavior) = REQUIRED + ]; + + Userset subtract = 2 [ + (validate.rules).message.required = true, + (google.api.field_behavior) = REQUIRED + ]; +} + +message Userset { + oneof userset { + DirectUserset this = 1; + ObjectRelation computed_userset = 2; + TupleToUserset tuple_to_userset = 3; + Usersets union = 4; + Usersets intersection = 5; + Difference difference = 6; + } +} + +// A DirectUserset is a sentinel message for referencing +// the direct members specified by an object/relation mapping. +message DirectUserset {} + +message ObjectRelation { + string object = 1 [(validate.rules).string = {max_bytes: 256}]; + string relation = 2 [(validate.rules).string = {max_bytes: 50}]; +} + +message ComputedUserset { + string relation = 1 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).string = { + max_bytes: 50 + ignore_empty: false + } + ]; +} + +message TupleToUserset { + // The target object/relation + ObjectRelation tupleset = 1 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).message.required = true + ]; + ObjectRelation computed_userset = 2 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).message.required = true + ]; +} + +message Condition { + // A unique name for the condition + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: false + } + ]; + + // A Google CEL expression, expressed as a string. + string expression = 2 [ + (google.api.field_behavior) = REQUIRED, + (validate.rules).string = { + max_bytes: 512 + ignore_empty: false + } + ]; + + // A map of parameter names to the parameter's defined type reference. + map parameters = 3 [ + (validate.rules).map.max_pairs = 25, + (validate.rules).map.keys.string = {pattern: "^[^:#@\\s]{1,50}$"} + ]; + + ConditionMetadata metadata = 4; +} + +message ConditionMetadata { + string module = 1 [(validate.rules).string = { + pattern: "^[^:#@\\s]{1,50}$" + ignore_empty: true + }]; + + SourceInfo source_info = 2 [json_name = "source_info"]; +} + +message ConditionParamTypeRef { + enum TypeName { + TYPE_NAME_UNSPECIFIED = 0; + TYPE_NAME_ANY = 1; + TYPE_NAME_BOOL = 2; + TYPE_NAME_STRING = 3; + TYPE_NAME_INT = 4; + TYPE_NAME_UINT = 5; + TYPE_NAME_DOUBLE = 6; + TYPE_NAME_DURATION = 7; + TYPE_NAME_TIMESTAMP = 8; + TYPE_NAME_MAP = 9; + TYPE_NAME_LIST = 10; + TYPE_NAME_IPADDRESS = 11; + } + + TypeName type_name = 1 [ + json_name = "type_name", + (google.api.field_behavior) = REQUIRED, + (validate.rules).enum.defined_only = true + ]; + + repeated ConditionParamTypeRef generic_types = 2 [ + json_name = "generic_types", + (validate.rules).repeated.max_items = 5 + ]; +} diff --git a/codegen/proto/protoc-gen-openapiv2/options/annotations.proto b/codegen/proto/protoc-gen-openapiv2/options/annotations.proto new file mode 100644 index 0000000..aecc5e7 --- /dev/null +++ b/codegen/proto/protoc-gen-openapiv2/options/annotations.proto @@ -0,0 +1,51 @@ +syntax = "proto3"; + +package grpc.gateway.protoc_gen_openapiv2.options; + +import "google/protobuf/descriptor.proto"; +import "protoc-gen-openapiv2/options/openapiv2.proto"; + +option go_package = "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options"; + +extend google.protobuf.FileOptions { + // ID assigned by protobuf-global-extension-registry@google.com for gRPC-Gateway project. + // + // All IDs are the same, as assigned. It is okay that they are the same, as they extend + // different descriptor messages. + Swagger openapiv2_swagger = 1042; +} +extend google.protobuf.MethodOptions { + // ID assigned by protobuf-global-extension-registry@google.com for gRPC-Gateway project. + // + // All IDs are the same, as assigned. It is okay that they are the same, as they extend + // different descriptor messages. + Operation openapiv2_operation = 1042; +} +extend google.protobuf.MessageOptions { + // ID assigned by protobuf-global-extension-registry@google.com for gRPC-Gateway project. + // + // All IDs are the same, as assigned. It is okay that they are the same, as they extend + // different descriptor messages. + Schema openapiv2_schema = 1042; +} +extend google.protobuf.EnumOptions { + // ID assigned by protobuf-global-extension-registry@google.com for gRPC-Gateway project. + // + // All IDs are the same, as assigned. It is okay that they are the same, as they extend + // different descriptor messages. + EnumSchema openapiv2_enum = 1042; +} +extend google.protobuf.ServiceOptions { + // ID assigned by protobuf-global-extension-registry@google.com for gRPC-Gateway project. + // + // All IDs are the same, as assigned. It is okay that they are the same, as they extend + // different descriptor messages. + Tag openapiv2_tag = 1042; +} +extend google.protobuf.FieldOptions { + // ID assigned by protobuf-global-extension-registry@google.com for gRPC-Gateway project. + // + // All IDs are the same, as assigned. It is okay that they are the same, as they extend + // different descriptor messages. + JSONSchema openapiv2_field = 1042; +} diff --git a/codegen/proto/protoc-gen-openapiv2/options/openapiv2.proto b/codegen/proto/protoc-gen-openapiv2/options/openapiv2.proto new file mode 100644 index 0000000..444a568 --- /dev/null +++ b/codegen/proto/protoc-gen-openapiv2/options/openapiv2.proto @@ -0,0 +1,762 @@ +syntax = "proto3"; + +package grpc.gateway.protoc_gen_openapiv2.options; + +import "google/protobuf/struct.proto"; + +option go_package = "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options"; + +// Scheme describes the schemes supported by the OpenAPI Swagger +// and Operation objects. +enum Scheme { + UNKNOWN = 0; + HTTP = 1; + HTTPS = 2; + WS = 3; + WSS = 4; +} + +// `Swagger` is a representation of OpenAPI v2 specification's Swagger object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#swaggerObject +// +// Example: +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { +// info: { +// title: "Echo API"; +// version: "1.0"; +// description: ""; +// contact: { +// name: "gRPC-Gateway project"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway"; +// email: "none@example.com"; +// }; +// license: { +// name: "BSD 3-Clause License"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/main/LICENSE"; +// }; +// }; +// schemes: HTTPS; +// consumes: "application/json"; +// produces: "application/json"; +// }; +// +message Swagger { + // Specifies the OpenAPI Specification version being used. It can be + // used by the OpenAPI UI and other clients to interpret the API listing. The + // value MUST be "2.0". + string swagger = 1; + // Provides metadata about the API. The metadata can be used by the + // clients if needed. + Info info = 2; + // The host (name or ip) serving the API. This MUST be the host only and does + // not include the scheme nor sub-paths. It MAY include a port. If the host is + // not included, the host serving the documentation is to be used (including + // the port). The host does not support path templating. + string host = 3; + // The base path on which the API is served, which is relative to the host. If + // it is not included, the API is served directly under the host. The value + // MUST start with a leading slash (/). The basePath does not support path + // templating. + // Note that using `base_path` does not change the endpoint paths that are + // generated in the resulting OpenAPI file. If you wish to use `base_path` + // with relatively generated OpenAPI paths, the `base_path` prefix must be + // manually removed from your `google.api.http` paths and your code changed to + // serve the API from the `base_path`. + string base_path = 4; + // The transfer protocol of the API. Values MUST be from the list: "http", + // "https", "ws", "wss". If the schemes is not included, the default scheme to + // be used is the one used to access the OpenAPI definition itself. + repeated Scheme schemes = 5; + // A list of MIME types the APIs can consume. This is global to all APIs but + // can be overridden on specific API calls. Value MUST be as described under + // Mime Types. + repeated string consumes = 6; + // A list of MIME types the APIs can produce. This is global to all APIs but + // can be overridden on specific API calls. Value MUST be as described under + // Mime Types. + repeated string produces = 7; + // field 8 is reserved for 'paths'. + reserved 8; + // field 9 is reserved for 'definitions', which at this time are already + // exposed as and customizable as proto messages. + reserved 9; + // An object to hold responses that can be used across operations. This + // property does not define global responses for all operations. + map responses = 10; + // Security scheme definitions that can be used across the specification. + SecurityDefinitions security_definitions = 11; + // A declaration of which security schemes are applied for the API as a whole. + // The list of values describes alternative security schemes that can be used + // (that is, there is a logical OR between the security requirements). + // Individual operations can override this definition. + repeated SecurityRequirement security = 12; + // A list of tags for API documentation control. Tags can be used for logical + // grouping of operations by resources or any other qualifier. + repeated Tag tags = 13; + // Additional external documentation. + ExternalDocumentation external_docs = 14; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 15; +} + +// `Operation` is a representation of OpenAPI v2 specification's Operation object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#operationObject +// +// Example: +// +// service EchoService { +// rpc Echo(SimpleMessage) returns (SimpleMessage) { +// option (google.api.http) = { +// get: "/v1/example/echo/{id}" +// }; +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = { +// summary: "Get a message."; +// operation_id: "getMessage"; +// tags: "echo"; +// responses: { +// key: "200" +// value: { +// description: "OK"; +// } +// } +// }; +// } +// } +message Operation { + // A list of tags for API documentation control. Tags can be used for logical + // grouping of operations by resources or any other qualifier. + repeated string tags = 1; + // A short summary of what the operation does. For maximum readability in the + // swagger-ui, this field SHOULD be less than 120 characters. + string summary = 2; + // A verbose explanation of the operation behavior. GFM syntax can be used for + // rich text representation. + string description = 3; + // Additional external documentation for this operation. + ExternalDocumentation external_docs = 4; + // Unique string used to identify the operation. The id MUST be unique among + // all operations described in the API. Tools and libraries MAY use the + // operationId to uniquely identify an operation, therefore, it is recommended + // to follow common programming naming conventions. + string operation_id = 5; + // A list of MIME types the operation can consume. This overrides the consumes + // definition at the OpenAPI Object. An empty value MAY be used to clear the + // global definition. Value MUST be as described under Mime Types. + repeated string consumes = 6; + // A list of MIME types the operation can produce. This overrides the produces + // definition at the OpenAPI Object. An empty value MAY be used to clear the + // global definition. Value MUST be as described under Mime Types. + repeated string produces = 7; + // field 8 is reserved for 'parameters'. + reserved 8; + // The list of possible responses as they are returned from executing this + // operation. + map responses = 9; + // The transfer protocol for the operation. Values MUST be from the list: + // "http", "https", "ws", "wss". The value overrides the OpenAPI Object + // schemes definition. + repeated Scheme schemes = 10; + // Declares this operation to be deprecated. Usage of the declared operation + // should be refrained. Default value is false. + bool deprecated = 11; + // A declaration of which security schemes are applied for this operation. The + // list of values describes alternative security schemes that can be used + // (that is, there is a logical OR between the security requirements). This + // definition overrides any declared top-level security. To remove a top-level + // security declaration, an empty array can be used. + repeated SecurityRequirement security = 12; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 13; + // Custom parameters such as HTTP request headers. + // See: https://swagger.io/docs/specification/2-0/describing-parameters/ + // and https://swagger.io/specification/v2/#parameter-object. + Parameters parameters = 14; +} + +// `Parameters` is a representation of OpenAPI v2 specification's parameters object. +// Note: This technically breaks compatibility with the OpenAPI 2 definition structure as we only +// allow header parameters to be set here since we do not want users specifying custom non-header +// parameters beyond those inferred from the Protobuf schema. +// See: https://swagger.io/specification/v2/#parameter-object +message Parameters { + // `Headers` is one or more HTTP header parameter. + // See: https://swagger.io/docs/specification/2-0/describing-parameters/#header-parameters + repeated HeaderParameter headers = 1; +} + +// `HeaderParameter` a HTTP header parameter. +// See: https://swagger.io/specification/v2/#parameter-object +message HeaderParameter { + // `Type` is a supported HTTP header type. + // See https://swagger.io/specification/v2/#parameterType. + enum Type { + UNKNOWN = 0; + STRING = 1; + NUMBER = 2; + INTEGER = 3; + BOOLEAN = 4; + } + + // `Name` is the header name. + string name = 1; + // `Description` is a short description of the header. + string description = 2; + // `Type` is the type of the object. The value MUST be one of "string", "number", "integer", or "boolean". The "array" type is not supported. + // See: https://swagger.io/specification/v2/#parameterType. + Type type = 3; + // `Format` The extending format for the previously mentioned type. + string format = 4; + // `Required` indicates if the header is optional + bool required = 5; + // field 6 is reserved for 'items', but in OpenAPI-specific way. + reserved 6; + // field 7 is reserved `Collection Format`. Determines the format of the array if type array is used. + reserved 7; +} + +// `Header` is a representation of OpenAPI v2 specification's Header object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#headerObject +// +message Header { + // `Description` is a short description of the header. + string description = 1; + // The type of the object. The value MUST be one of "string", "number", "integer", or "boolean". The "array" type is not supported. + string type = 2; + // `Format` The extending format for the previously mentioned type. + string format = 3; + // field 4 is reserved for 'items', but in OpenAPI-specific way. + reserved 4; + // field 5 is reserved `Collection Format` Determines the format of the array if type array is used. + reserved 5; + // `Default` Declares the value of the header that the server will use if none is provided. + // See: https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. + // Unlike JSON Schema this value MUST conform to the defined type for the header. + string default = 6; + // field 7 is reserved for 'maximum'. + reserved 7; + // field 8 is reserved for 'exclusiveMaximum'. + reserved 8; + // field 9 is reserved for 'minimum'. + reserved 9; + // field 10 is reserved for 'exclusiveMinimum'. + reserved 10; + // field 11 is reserved for 'maxLength'. + reserved 11; + // field 12 is reserved for 'minLength'. + reserved 12; + // 'Pattern' See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. + string pattern = 13; + // field 14 is reserved for 'maxItems'. + reserved 14; + // field 15 is reserved for 'minItems'. + reserved 15; + // field 16 is reserved for 'uniqueItems'. + reserved 16; + // field 17 is reserved for 'enum'. + reserved 17; + // field 18 is reserved for 'multipleOf'. + reserved 18; +} + +// `Response` is a representation of OpenAPI v2 specification's Response object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#responseObject +// +message Response { + // `Description` is a short description of the response. + // GFM syntax can be used for rich text representation. + string description = 1; + // `Schema` optionally defines the structure of the response. + // If `Schema` is not provided, it means there is no content to the response. + Schema schema = 2; + // `Headers` A list of headers that are sent with the response. + // `Header` name is expected to be a string in the canonical format of the MIME header key + // See: https://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey + map headers = 3; + // `Examples` gives per-mimetype response examples. + // See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#example-object + map examples = 4; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 5; +} + +// `Info` is a representation of OpenAPI v2 specification's Info object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#infoObject +// +// Example: +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { +// info: { +// title: "Echo API"; +// version: "1.0"; +// description: ""; +// contact: { +// name: "gRPC-Gateway project"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway"; +// email: "none@example.com"; +// }; +// license: { +// name: "BSD 3-Clause License"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/main/LICENSE"; +// }; +// }; +// ... +// }; +// +message Info { + // The title of the application. + string title = 1; + // A short description of the application. GFM syntax can be used for rich + // text representation. + string description = 2; + // The Terms of Service for the API. + string terms_of_service = 3; + // The contact information for the exposed API. + Contact contact = 4; + // The license information for the exposed API. + License license = 5; + // Provides the version of the application API (not to be confused + // with the specification version). + string version = 6; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 7; +} + +// `Contact` is a representation of OpenAPI v2 specification's Contact object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#contactObject +// +// Example: +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { +// info: { +// ... +// contact: { +// name: "gRPC-Gateway project"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway"; +// email: "none@example.com"; +// }; +// ... +// }; +// ... +// }; +// +message Contact { + // The identifying name of the contact person/organization. + string name = 1; + // The URL pointing to the contact information. MUST be in the format of a + // URL. + string url = 2; + // The email address of the contact person/organization. MUST be in the format + // of an email address. + string email = 3; +} + +// `License` is a representation of OpenAPI v2 specification's License object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#licenseObject +// +// Example: +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { +// info: { +// ... +// license: { +// name: "BSD 3-Clause License"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/main/LICENSE"; +// }; +// ... +// }; +// ... +// }; +// +message License { + // The license name used for the API. + string name = 1; + // A URL to the license used for the API. MUST be in the format of a URL. + string url = 2; +} + +// `ExternalDocumentation` is a representation of OpenAPI v2 specification's +// ExternalDocumentation object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#externalDocumentationObject +// +// Example: +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { +// ... +// external_docs: { +// description: "More about gRPC-Gateway"; +// url: "https://github.com/grpc-ecosystem/grpc-gateway"; +// } +// ... +// }; +// +message ExternalDocumentation { + // A short description of the target documentation. GFM syntax can be used for + // rich text representation. + string description = 1; + // The URL for the target documentation. Value MUST be in the format + // of a URL. + string url = 2; +} + +// `Schema` is a representation of OpenAPI v2 specification's Schema object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject +// +message Schema { + JSONSchema json_schema = 1; + // Adds support for polymorphism. The discriminator is the schema property + // name that is used to differentiate between other schema that inherit this + // schema. The property name used MUST be defined at this schema and it MUST + // be in the required property list. When used, the value MUST be the name of + // this schema or any schema that inherits it. + string discriminator = 2; + // Relevant only for Schema "properties" definitions. Declares the property as + // "read only". This means that it MAY be sent as part of a response but MUST + // NOT be sent as part of the request. Properties marked as readOnly being + // true SHOULD NOT be in the required list of the defined schema. Default + // value is false. + bool read_only = 3; + // field 4 is reserved for 'xml'. + reserved 4; + // Additional external documentation for this schema. + ExternalDocumentation external_docs = 5; + // A free-form property to include an example of an instance for this schema in JSON. + // This is copied verbatim to the output. + string example = 6; +} + +// `EnumSchema` is subset of fields from the OpenAPI v2 specification's Schema object. +// Only fields that are applicable to Enums are included +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject +// +// Example: +// +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_enum) = { +// ... +// title: "MyEnum"; +// description:"This is my nice enum"; +// example: "ZERO"; +// required: true; +// ... +// }; +// +message EnumSchema { + // A short description of the schema. + string description = 1; + string default = 2; + // The title of the schema. + string title = 3; + bool required = 4; + bool read_only = 5; + // Additional external documentation for this schema. + ExternalDocumentation external_docs = 6; + string example = 7; + // Ref is used to define an external reference to include in the message. + // This could be a fully qualified proto message reference, and that type must + // be imported into the protofile. If no message is identified, the Ref will + // be used verbatim in the output. + // For example: + // `ref: ".google.protobuf.Timestamp"`. + string ref = 8; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 9; +} + +// `JSONSchema` represents properties from JSON Schema taken, and as used, in +// the OpenAPI v2 spec. +// +// This includes changes made by OpenAPI v2. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject +// +// See also: https://cswr.github.io/JsonSchema/spec/basic_types/, +// https://github.com/json-schema-org/json-schema-spec/blob/master/schema.json +// +// Example: +// +// message SimpleMessage { +// option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_schema) = { +// json_schema: { +// title: "SimpleMessage" +// description: "A simple message." +// required: ["id"] +// } +// }; +// +// // Id represents the message identifier. +// string id = 1; [ +// (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = { +// description: "The unique identifier of the simple message." +// }]; +// } +// +message JSONSchema { + // field 1 is reserved for '$id', omitted from OpenAPI v2. + reserved 1; + // field 2 is reserved for '$schema', omitted from OpenAPI v2. + reserved 2; + // Ref is used to define an external reference to include in the message. + // This could be a fully qualified proto message reference, and that type must + // be imported into the protofile. If no message is identified, the Ref will + // be used verbatim in the output. + // For example: + // `ref: ".google.protobuf.Timestamp"`. + string ref = 3; + // field 4 is reserved for '$comment', omitted from OpenAPI v2. + reserved 4; + // The title of the schema. + string title = 5; + // A short description of the schema. + string description = 6; + string default = 7; + bool read_only = 8; + // A free-form property to include a JSON example of this field. This is copied + // verbatim to the output swagger.json. Quotes must be escaped. + // This property is the same for 2.0 and 3.0.0 https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/3.0.0.md#schemaObject https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject + string example = 9; + double multiple_of = 10; + // Maximum represents an inclusive upper limit for a numeric instance. The + // value of MUST be a number, + double maximum = 11; + bool exclusive_maximum = 12; + // minimum represents an inclusive lower limit for a numeric instance. The + // value of MUST be a number, + double minimum = 13; + bool exclusive_minimum = 14; + uint64 max_length = 15; + uint64 min_length = 16; + string pattern = 17; + // field 18 is reserved for 'additionalItems', omitted from OpenAPI v2. + reserved 18; + // field 19 is reserved for 'items', but in OpenAPI-specific way. + // TODO(ivucica): add 'items'? + reserved 19; + uint64 max_items = 20; + uint64 min_items = 21; + bool unique_items = 22; + // field 23 is reserved for 'contains', omitted from OpenAPI v2. + reserved 23; + uint64 max_properties = 24; + uint64 min_properties = 25; + repeated string required = 26; + // field 27 is reserved for 'additionalProperties', but in OpenAPI-specific + // way. TODO(ivucica): add 'additionalProperties'? + reserved 27; + // field 28 is reserved for 'definitions', omitted from OpenAPI v2. + reserved 28; + // field 29 is reserved for 'properties', but in OpenAPI-specific way. + // TODO(ivucica): add 'additionalProperties'? + reserved 29; + // following fields are reserved, as the properties have been omitted from + // OpenAPI v2: + // patternProperties, dependencies, propertyNames, const + reserved 30 to 33; + // Items in 'array' must be unique. + repeated string array = 34; + + enum JSONSchemaSimpleTypes { + UNKNOWN = 0; + ARRAY = 1; + BOOLEAN = 2; + INTEGER = 3; + NULL = 4; + NUMBER = 5; + OBJECT = 6; + STRING = 7; + } + + repeated JSONSchemaSimpleTypes type = 35; + // `Format` + string format = 36; + // following fields are reserved, as the properties have been omitted from + // OpenAPI v2: contentMediaType, contentEncoding, if, then, else + reserved 37 to 41; + // field 42 is reserved for 'allOf', but in OpenAPI-specific way. + // TODO(ivucica): add 'allOf'? + reserved 42; + // following fields are reserved, as the properties have been omitted from + // OpenAPI v2: + // anyOf, oneOf, not + reserved 43 to 45; + // Items in `enum` must be unique https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 + repeated string enum = 46; + + // Additional field level properties used when generating the OpenAPI v2 file. + FieldConfiguration field_configuration = 1001; + + // 'FieldConfiguration' provides additional field level properties used when generating the OpenAPI v2 file. + // These properties are not defined by OpenAPIv2, but they are used to control the generation. + message FieldConfiguration { + // Alternative parameter name when used as path parameter. If set, this will + // be used as the complete parameter name when this field is used as a path + // parameter. Use this to avoid having auto generated path parameter names + // for overlapping paths. + string path_param_name = 47; + // Declares this field to be deprecated. Allows for the generated OpenAPI + // parameter to be marked as deprecated without affecting the proto field. + bool deprecated = 49; + } + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 48; +} + +// `Tag` is a representation of OpenAPI v2 specification's Tag object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#tagObject +// +message Tag { + // The name of the tag. Use it to allow override of the name of a + // global Tag object, then use that name to reference the tag throughout the + // OpenAPI file. + string name = 1; + // A short description for the tag. GFM syntax can be used for rich text + // representation. + string description = 2; + // Additional external documentation for this tag. + ExternalDocumentation external_docs = 3; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 4; +} + +// `SecurityDefinitions` is a representation of OpenAPI v2 specification's +// Security Definitions object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityDefinitionsObject +// +// A declaration of the security schemes available to be used in the +// specification. This does not enforce the security schemes on the operations +// and only serves to provide the relevant details for each scheme. +message SecurityDefinitions { + // A single security scheme definition, mapping a "name" to the scheme it + // defines. + map security = 1; +} + +// `SecurityScheme` is a representation of OpenAPI v2 specification's +// Security Scheme object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securitySchemeObject +// +// Allows the definition of a security scheme that can be used by the +// operations. Supported schemes are basic authentication, an API key (either as +// a header or as a query parameter) and OAuth2's common flows (implicit, +// password, application and access code). +message SecurityScheme { + // The type of the security scheme. Valid values are "basic", + // "apiKey" or "oauth2". + enum Type { + TYPE_INVALID = 0; + TYPE_BASIC = 1; + TYPE_API_KEY = 2; + TYPE_OAUTH2 = 3; + } + + // The location of the API key. Valid values are "query" or "header". + enum In { + IN_INVALID = 0; + IN_QUERY = 1; + IN_HEADER = 2; + } + + // The flow used by the OAuth2 security scheme. Valid values are + // "implicit", "password", "application" or "accessCode". + enum Flow { + FLOW_INVALID = 0; + FLOW_IMPLICIT = 1; + FLOW_PASSWORD = 2; + FLOW_APPLICATION = 3; + FLOW_ACCESS_CODE = 4; + } + + // The type of the security scheme. Valid values are "basic", + // "apiKey" or "oauth2". + Type type = 1; + // A short description for security scheme. + string description = 2; + // The name of the header or query parameter to be used. + // Valid for apiKey. + string name = 3; + // The location of the API key. Valid values are "query" or + // "header". + // Valid for apiKey. + In in = 4; + // The flow used by the OAuth2 security scheme. Valid values are + // "implicit", "password", "application" or "accessCode". + // Valid for oauth2. + Flow flow = 5; + // The authorization URL to be used for this flow. This SHOULD be in + // the form of a URL. + // Valid for oauth2/implicit and oauth2/accessCode. + string authorization_url = 6; + // The token URL to be used for this flow. This SHOULD be in the + // form of a URL. + // Valid for oauth2/password, oauth2/application and oauth2/accessCode. + string token_url = 7; + // The available scopes for the OAuth2 security scheme. + // Valid for oauth2. + Scopes scopes = 8; + // Custom properties that start with "x-" such as "x-foo" used to describe + // extra functionality that is not covered by the standard OpenAPI Specification. + // See: https://swagger.io/docs/specification/2-0/swagger-extensions/ + map extensions = 9; +} + +// `SecurityRequirement` is a representation of OpenAPI v2 specification's +// Security Requirement object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityRequirementObject +// +// Lists the required security schemes to execute this operation. The object can +// have multiple security schemes declared in it which are all required (that +// is, there is a logical AND between the schemes). +// +// The name used for each property MUST correspond to a security scheme +// declared in the Security Definitions. +message SecurityRequirement { + // If the security scheme is of type "oauth2", then the value is a list of + // scope names required for the execution. For other security scheme types, + // the array MUST be empty. + message SecurityRequirementValue { + repeated string scope = 1; + } + // Each name must correspond to a security scheme which is declared in + // the Security Definitions. If the security scheme is of type "oauth2", + // then the value is a list of scope names required for the execution. + // For other security scheme types, the array MUST be empty. + map security_requirement = 1; +} + +// `Scopes` is a representation of OpenAPI v2 specification's Scopes object. +// +// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#scopesObject +// +// Lists the available scopes for an OAuth2 security scheme. +message Scopes { + // Maps between a name of a scope to a short description of it (as the value + // of the property). + map scope = 1; +} diff --git a/codegen/proto/validate/validate.proto b/codegen/proto/validate/validate.proto new file mode 100644 index 0000000..5aa9653 --- /dev/null +++ b/codegen/proto/validate/validate.proto @@ -0,0 +1,862 @@ +syntax = "proto2"; +package validate; + +option go_package = "github.com/envoyproxy/protoc-gen-validate/validate"; +option java_package = "io.envoyproxy.pgv.validate"; + +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +// Validation rules applied at the message level +extend google.protobuf.MessageOptions { + // Disabled nullifies any validation rules for this message, including any + // message fields associated with it that do support validation. + optional bool disabled = 1071; + // Ignore skips generation of validation methods for this message. + optional bool ignored = 1072; +} + +// Validation rules applied at the oneof level +extend google.protobuf.OneofOptions { + // Required ensures that exactly one the field options in a oneof is set; + // validation fails if no fields in the oneof are set. + optional bool required = 1071; +} + +// Validation rules applied at the field level +extend google.protobuf.FieldOptions { + // Rules specify the validations to be performed on this field. By default, + // no validation is performed against a field. + optional FieldRules rules = 1071; +} + +// FieldRules encapsulates the rules for each type of field. Depending on the +// field, the correct set should be used to ensure proper validations. +message FieldRules { + optional MessageRules message = 17; + oneof type { + // Scalar Field Types + FloatRules float = 1; + DoubleRules double = 2; + Int32Rules int32 = 3; + Int64Rules int64 = 4; + UInt32Rules uint32 = 5; + UInt64Rules uint64 = 6; + SInt32Rules sint32 = 7; + SInt64Rules sint64 = 8; + Fixed32Rules fixed32 = 9; + Fixed64Rules fixed64 = 10; + SFixed32Rules sfixed32 = 11; + SFixed64Rules sfixed64 = 12; + BoolRules bool = 13; + StringRules string = 14; + BytesRules bytes = 15; + + // Complex Field Types + EnumRules enum = 16; + RepeatedRules repeated = 18; + MapRules map = 19; + + // Well-Known Field Types + AnyRules any = 20; + DurationRules duration = 21; + TimestampRules timestamp = 22; + } +} + +// FloatRules describes the constraints applied to `float` values +message FloatRules { + // Const specifies that this field must be exactly the specified value + optional float const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional float lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional float lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional float gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional float gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated float in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated float not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// DoubleRules describes the constraints applied to `double` values +message DoubleRules { + // Const specifies that this field must be exactly the specified value + optional double const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional double lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional double lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional double gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional double gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated double in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated double not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// Int32Rules describes the constraints applied to `int32` values +message Int32Rules { + // Const specifies that this field must be exactly the specified value + optional int32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional int32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional int32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional int32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional int32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated int32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated int32 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// Int64Rules describes the constraints applied to `int64` values +message Int64Rules { + // Const specifies that this field must be exactly the specified value + optional int64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional int64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional int64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional int64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional int64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated int64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated int64 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// UInt32Rules describes the constraints applied to `uint32` values +message UInt32Rules { + // Const specifies that this field must be exactly the specified value + optional uint32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional uint32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional uint32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional uint32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional uint32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated uint32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated uint32 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// UInt64Rules describes the constraints applied to `uint64` values +message UInt64Rules { + // Const specifies that this field must be exactly the specified value + optional uint64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional uint64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional uint64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional uint64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional uint64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated uint64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated uint64 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// SInt32Rules describes the constraints applied to `sint32` values +message SInt32Rules { + // Const specifies that this field must be exactly the specified value + optional sint32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sint32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sint32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sint32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sint32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sint32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sint32 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// SInt64Rules describes the constraints applied to `sint64` values +message SInt64Rules { + // Const specifies that this field must be exactly the specified value + optional sint64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sint64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sint64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sint64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sint64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sint64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sint64 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// Fixed32Rules describes the constraints applied to `fixed32` values +message Fixed32Rules { + // Const specifies that this field must be exactly the specified value + optional fixed32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional fixed32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional fixed32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional fixed32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional fixed32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated fixed32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated fixed32 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// Fixed64Rules describes the constraints applied to `fixed64` values +message Fixed64Rules { + // Const specifies that this field must be exactly the specified value + optional fixed64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional fixed64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional fixed64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional fixed64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional fixed64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated fixed64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated fixed64 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// SFixed32Rules describes the constraints applied to `sfixed32` values +message SFixed32Rules { + // Const specifies that this field must be exactly the specified value + optional sfixed32 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sfixed32 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sfixed32 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sfixed32 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sfixed32 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sfixed32 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sfixed32 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// SFixed64Rules describes the constraints applied to `sfixed64` values +message SFixed64Rules { + // Const specifies that this field must be exactly the specified value + optional sfixed64 const = 1; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional sfixed64 lt = 2; + + // Lte specifies that this field must be less than or equal to the + // specified value, inclusive + optional sfixed64 lte = 3; + + // Gt specifies that this field must be greater than the specified value, + // exclusive. If the value of Gt is larger than a specified Lt or Lte, the + // range is reversed. + optional sfixed64 gt = 4; + + // Gte specifies that this field must be greater than or equal to the + // specified value, inclusive. If the value of Gte is larger than a + // specified Lt or Lte, the range is reversed. + optional sfixed64 gte = 5; + + // In specifies that this field must be equal to one of the specified + // values + repeated sfixed64 in = 6; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated sfixed64 not_in = 7; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 8; +} + +// BoolRules describes the constraints applied to `bool` values +message BoolRules { + // Const specifies that this field must be exactly the specified value + optional bool const = 1; +} + +// StringRules describe the constraints applied to `string` values +message StringRules { + // Const specifies that this field must be exactly the specified value + optional string const = 1; + + // Len specifies that this field must be the specified number of + // characters (Unicode code points). Note that the number of + // characters may differ from the number of bytes in the string. + optional uint64 len = 19; + + // MinLen specifies that this field must be the specified number of + // characters (Unicode code points) at a minimum. Note that the number of + // characters may differ from the number of bytes in the string. + optional uint64 min_len = 2; + + // MaxLen specifies that this field must be the specified number of + // characters (Unicode code points) at a maximum. Note that the number of + // characters may differ from the number of bytes in the string. + optional uint64 max_len = 3; + + // LenBytes specifies that this field must be the specified number of bytes + optional uint64 len_bytes = 20; + + // MinBytes specifies that this field must be the specified number of bytes + // at a minimum + optional uint64 min_bytes = 4; + + // MaxBytes specifies that this field must be the specified number of bytes + // at a maximum + optional uint64 max_bytes = 5; + + // Pattern specifies that this field must match against the specified + // regular expression (RE2 syntax). The included expression should elide + // any delimiters. + optional string pattern = 6; + + // Prefix specifies that this field must have the specified substring at + // the beginning of the string. + optional string prefix = 7; + + // Suffix specifies that this field must have the specified substring at + // the end of the string. + optional string suffix = 8; + + // Contains specifies that this field must have the specified substring + // anywhere in the string. + optional string contains = 9; + + // NotContains specifies that this field cannot have the specified substring + // anywhere in the string. + optional string not_contains = 23; + + // In specifies that this field must be equal to one of the specified + // values + repeated string in = 10; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated string not_in = 11; + + // WellKnown rules provide advanced constraints against common string + // patterns + oneof well_known { + // Email specifies that the field must be a valid email address as + // defined by RFC 5322 + bool email = 12; + + // Hostname specifies that the field must be a valid hostname as + // defined by RFC 1034. This constraint does not support + // internationalized domain names (IDNs). + bool hostname = 13; + + // Ip specifies that the field must be a valid IP (v4 or v6) address. + // Valid IPv6 addresses should not include surrounding square brackets. + bool ip = 14; + + // Ipv4 specifies that the field must be a valid IPv4 address. + bool ipv4 = 15; + + // Ipv6 specifies that the field must be a valid IPv6 address. Valid + // IPv6 addresses should not include surrounding square brackets. + bool ipv6 = 16; + + // Uri specifies that the field must be a valid, absolute URI as defined + // by RFC 3986 + bool uri = 17; + + // UriRef specifies that the field must be a valid URI as defined by RFC + // 3986 and may be relative or absolute. + bool uri_ref = 18; + + // Address specifies that the field must be either a valid hostname as + // defined by RFC 1034 (which does not support internationalized domain + // names or IDNs), or it can be a valid IP (v4 or v6). + bool address = 21; + + // Uuid specifies that the field must be a valid UUID as defined by + // RFC 4122 + bool uuid = 22; + + // WellKnownRegex specifies a common well known pattern defined as a regex. + KnownRegex well_known_regex = 24; + } + + // This applies to regexes HTTP_HEADER_NAME and HTTP_HEADER_VALUE to enable + // strict header validation. + // By default, this is true, and HTTP header validations are RFC-compliant. + // Setting to false will enable a looser validations that only disallows + // \r\n\0 characters, which can be used to bypass header matching rules. + optional bool strict = 25 [default = true]; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 26; +} + +// WellKnownRegex contain some well-known patterns. +enum KnownRegex { + UNKNOWN = 0; + + // HTTP header name as defined by RFC 7230. + HTTP_HEADER_NAME = 1; + + // HTTP header value as defined by RFC 7230. + HTTP_HEADER_VALUE = 2; +} + +// BytesRules describe the constraints applied to `bytes` values +message BytesRules { + // Const specifies that this field must be exactly the specified value + optional bytes const = 1; + + // Len specifies that this field must be the specified number of bytes + optional uint64 len = 13; + + // MinLen specifies that this field must be the specified number of bytes + // at a minimum + optional uint64 min_len = 2; + + // MaxLen specifies that this field must be the specified number of bytes + // at a maximum + optional uint64 max_len = 3; + + // Pattern specifies that this field must match against the specified + // regular expression (RE2 syntax). The included expression should elide + // any delimiters. + optional string pattern = 4; + + // Prefix specifies that this field must have the specified bytes at the + // beginning of the string. + optional bytes prefix = 5; + + // Suffix specifies that this field must have the specified bytes at the + // end of the string. + optional bytes suffix = 6; + + // Contains specifies that this field must have the specified bytes + // anywhere in the string. + optional bytes contains = 7; + + // In specifies that this field must be equal to one of the specified + // values + repeated bytes in = 8; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated bytes not_in = 9; + + // WellKnown rules provide advanced constraints against common byte + // patterns + oneof well_known { + // Ip specifies that the field must be a valid IP (v4 or v6) address in + // byte format + bool ip = 10; + + // Ipv4 specifies that the field must be a valid IPv4 address in byte + // format + bool ipv4 = 11; + + // Ipv6 specifies that the field must be a valid IPv6 address in byte + // format + bool ipv6 = 12; + } + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 14; +} + +// EnumRules describe the constraints applied to enum values +message EnumRules { + // Const specifies that this field must be exactly the specified value + optional int32 const = 1; + + // DefinedOnly specifies that this field must be only one of the defined + // values for this enum, failing on any undefined value. + optional bool defined_only = 2; + + // In specifies that this field must be equal to one of the specified + // values + repeated int32 in = 3; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated int32 not_in = 4; +} + +// MessageRules describe the constraints applied to embedded message values. +// For message-type fields, validation is performed recursively. +message MessageRules { + // Skip specifies that the validation rules of this field should not be + // evaluated + optional bool skip = 1; + + // Required specifies that this field must be set + optional bool required = 2; +} + +// RepeatedRules describe the constraints applied to `repeated` values +message RepeatedRules { + // MinItems specifies that this field must have the specified number of + // items at a minimum + optional uint64 min_items = 1; + + // MaxItems specifies that this field must have the specified number of + // items at a maximum + optional uint64 max_items = 2; + + // Unique specifies that all elements in this field must be unique. This + // constraint is only applicable to scalar and enum types (messages are not + // supported). + optional bool unique = 3; + + // Items specifies the constraints to be applied to each item in the field. + // Repeated message fields will still execute validation against each item + // unless skip is specified here. + optional FieldRules items = 4; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 5; +} + +// MapRules describe the constraints applied to `map` values +message MapRules { + // MinPairs specifies that this field must have the specified number of + // KVs at a minimum + optional uint64 min_pairs = 1; + + // MaxPairs specifies that this field must have the specified number of + // KVs at a maximum + optional uint64 max_pairs = 2; + + // NoSparse specifies values in this field cannot be unset. This only + // applies to map's with message value types. + optional bool no_sparse = 3; + + // Keys specifies the constraints to be applied to each key in the field. + optional FieldRules keys = 4; + + // Values specifies the constraints to be applied to the value of each key + // in the field. Message values will still have their validations evaluated + // unless skip is specified here. + optional FieldRules values = 5; + + // IgnoreEmpty specifies that the validation rules of this field should be + // evaluated only if the field is not empty + optional bool ignore_empty = 6; +} + +// AnyRules describe constraints applied exclusively to the +// `google.protobuf.Any` well-known type +message AnyRules { + // Required specifies that this field must be set + optional bool required = 1; + + // In specifies that this field's `type_url` must be equal to one of the + // specified values. + repeated string in = 2; + + // NotIn specifies that this field's `type_url` must not be equal to any of + // the specified values. + repeated string not_in = 3; +} + +// DurationRules describe the constraints applied exclusively to the +// `google.protobuf.Duration` well-known type +message DurationRules { + // Required specifies that this field must be set + optional bool required = 1; + + // Const specifies that this field must be exactly the specified value + optional google.protobuf.Duration const = 2; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional google.protobuf.Duration lt = 3; + + // Lt specifies that this field must be less than the specified value, + // inclusive + optional google.protobuf.Duration lte = 4; + + // Gt specifies that this field must be greater than the specified value, + // exclusive + optional google.protobuf.Duration gt = 5; + + // Gte specifies that this field must be greater than the specified value, + // inclusive + optional google.protobuf.Duration gte = 6; + + // In specifies that this field must be equal to one of the specified + // values + repeated google.protobuf.Duration in = 7; + + // NotIn specifies that this field cannot be equal to one of the specified + // values + repeated google.protobuf.Duration not_in = 8; +} + +// TimestampRules describe the constraints applied exclusively to the +// `google.protobuf.Timestamp` well-known type +message TimestampRules { + // Required specifies that this field must be set + optional bool required = 1; + + // Const specifies that this field must be exactly the specified value + optional google.protobuf.Timestamp const = 2; + + // Lt specifies that this field must be less than the specified value, + // exclusive + optional google.protobuf.Timestamp lt = 3; + + // Lte specifies that this field must be less than the specified value, + // inclusive + optional google.protobuf.Timestamp lte = 4; + + // Gt specifies that this field must be greater than the specified value, + // exclusive + optional google.protobuf.Timestamp gt = 5; + + // Gte specifies that this field must be greater than the specified value, + // inclusive + optional google.protobuf.Timestamp gte = 6; + + // LtNow specifies that this must be less than the current time. LtNow + // can only be used with the Within rule. + optional bool lt_now = 7; + + // GtNow specifies that this must be greater than the current time. GtNow + // can only be used with the Within rule. + optional bool gt_now = 8; + + // Within specifies that this field must be within this duration of the + // current time. This constraint can be used alone or with the LtNow and + // GtNow rules. + optional google.protobuf.Duration within = 9; +} diff --git a/codegen/src/main.rs b/codegen/src/main.rs new file mode 100644 index 0000000..b18aad6 --- /dev/null +++ b/codegen/src/main.rs @@ -0,0 +1,123 @@ +//! Generates `crates/openfga-model/src/generated` from the protos vendored in `codegen/proto`. +//! +//! `cargo run -p codegen` rewrites the generated modules, and `cargo run -p codegen -- --check` +//! fails when a checked-in module differs from a fresh one. +//! +//! `codegen/proto` is `openfga/v1/authzmodel.proto` with its imports, exported from +//! [openfga/api](https://github.com/openfga/api) by +//! +//! ```sh +//! buf export "https://github.com/openfga/api.git#ref=c0650ce2169bcb39a72d73841fb531c200e32248" \ +//! --path openfga/v1/authzmodel.proto -o codegen/proto +//! ``` + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use anyhow::{Context, bail}; +use prost::Message; +use prost_build::Module; + +/// The proto file whose messages form the authorization model. +const MODEL_PROTO: &str = "openfga/v1/authzmodel.proto"; + +/// The protobuf package of [`MODEL_PROTO`]. +const MODEL_PACKAGE: &str = "openfga.v1"; + +/// What a run does with the freshly generated modules. +enum Mode { + /// Writes them over the checked-in ones. + Write, + /// Fails when a checked-in module differs from a fresh one. + Check, +} + +fn main() -> ExitCode { + let arguments: Vec = std::env::args().skip(1).collect(); + let mode = match arguments.as_slice() { + [] => Mode::Write, + [flag] if flag == "--check" => Mode::Check, + _ => { + eprintln!("usage: codegen [--check]"); + return ExitCode::FAILURE; + } + }; + match run(&mode) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("codegen: {error:#}"); + ExitCode::FAILURE + } + } +} + +/// Generates every module and writes or checks it according to `mode`. +fn run(mode: &Mode) -> anyhow::Result<()> { + let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR")); + let output_dir = manifest_dir.join("../crates/openfga-model/src/generated"); + let modules = generate(&manifest_dir.join("proto"))?; + let mut stale = Vec::new(); + for (file_name, contents) in &modules { + let path = output_dir.join(file_name); + match mode { + Mode::Write => { + fs::create_dir_all(&output_dir) + .with_context(|| format!("creating {}", output_dir.display()))?; + fs::write(&path, contents) + .with_context(|| format!("writing {}", path.display()))?; + } + Mode::Check => { + if fs::read_to_string(&path).ok().as_deref() != Some(contents.as_str()) { + stale.push(path); + } + } + } + } + if !stale.is_empty() { + let names: Vec = stale + .iter() + .map(|path| path.display().to_string()) + .collect(); + bail!("stale, rerun `cargo run -p codegen`: {}", names.join(", ")); + } + Ok(()) +} + +/// Returns each generated module as its file name and contents. +fn generate(proto_root: &Path) -> anyhow::Result> { + let mut compiler = protox::Compiler::new([proto_root])?; + compiler.include_imports(true).include_source_info(true); + compiler.open_file(MODEL_PROTO)?; + let descriptors = compiler.file_descriptor_set(); + + let mut pbjson = pbjson_build::Builder::new(); + pbjson + .register_descriptors(&descriptors.encode_to_vec())? + .btree_map(["."]); + let mut serde = String::from("// This file is @generated by pbjson-build.\n"); + for (_, writer) in pbjson.generate(&[format!(".{MODEL_PACKAGE}")], |_| Ok(Vec::new()))? { + serde.push_str(&String::from_utf8(writer)?); + } + + let model_file = descriptors + .file + .into_iter() + .find(|file| file.name() == MODEL_PROTO) + .with_context(|| format!("{MODEL_PROTO} is missing from the compiled descriptors"))?; + let mut prost_config = prost_build::Config::new(); + prost_config.btree_map(["."]); + let types = prost_config + .generate(vec![( + Module::from_protobuf_package_name(MODEL_PACKAGE), + model_file, + )])? + .into_values() + .next() + .with_context(|| format!("prost-build produced no module for {MODEL_PACKAGE}"))?; + + Ok(vec![ + (PathBuf::from(format!("{MODEL_PACKAGE}.rs")), types), + (PathBuf::from(format!("{MODEL_PACKAGE}.serde.rs")), serde), + ]) +} diff --git a/conformance/openfga-language b/conformance/openfga-language new file mode 160000 index 0000000..da7beed --- /dev/null +++ b/conformance/openfga-language @@ -0,0 +1 @@ +Subproject commit da7beeda519e8cf9fbbe552b72fc9a2a4d7590e0 diff --git a/crates/openfga-model/Cargo.toml b/crates/openfga-model/Cargo.toml new file mode 100644 index 0000000..76af14c --- /dev/null +++ b/crates/openfga-model/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "openfga-model" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +description = "OpenFGA authorization model types with protobuf and JSON encodings, for no_std" +readme = "README.md" +documentation = "https://docs.rs/openfga-model" +keywords = ["openfga", "authorization", "zanzibar", "protobuf", "no-std"] +categories = ["authentication", "encoding", "no-std"] + +[dependencies] +prost = { version = "0.14.1", default-features = false, features = ["derive"] } +serde = { version = "1.0.225", default-features = false, features = ["alloc"] } + +[dev-dependencies] +serde_json = "1.0.110" + +[lints] +workspace = true diff --git a/crates/openfga-model/README.md b/crates/openfga-model/README.md new file mode 100644 index 0000000..a088e71 --- /dev/null +++ b/crates/openfga-model/README.md @@ -0,0 +1,40 @@ +# openfga-model + +[![CI](https://github.com/LucaCappelletti94/openfga-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/LucaCappelletti94/openfga-rs/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/LucaCappelletti94/openfga-rs/graph/badge.svg)](https://codecov.io/gh/LucaCappelletti94/openfga-rs) +[![crates.io](https://img.shields.io/crates/v/openfga-model.svg)](https://crates.io/crates/openfga-model) +[![docs.rs](https://docs.rs/openfga-model/badge.svg)](https://docs.rs/openfga-model) +[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/LucaCappelletti94/openfga-rs/blob/main/LICENSE) + +Not published yet, so the crates.io and docs.rs badges resolve after the first release. + +The [OpenFGA](https://openfga.dev) authorization model as Rust types, generated from [`authzmodel.proto`](https://github.com/openfga/api/blob/main/openfga/v1/authzmodel.proto). Each type reads and writes the protobuf binary of the gRPC API and the JSON of the HTTP API and `fga model transform`. The crate is `no_std` and needs only `alloc`. + +```rust +use openfga_model::{AuthorizationModel, userset::Userset}; +use prost::Message; + +let model: AuthorizationModel = serde_json::from_str( + r#"{ + "schema_version": "1.1", + "type_definitions": [ + { "type": "user" }, + { + "type": "document", + "relations": { "viewer": { "this": {} } }, + "metadata": { + "relations": { + "viewer": { "directly_related_user_types": [{ "type": "user" }] } + } + } + } + ] + }"#, +)?; +let viewer = &model.type_definitions[1].relations["viewer"]; +assert!(matches!(viewer.userset, Some(Userset::This(_)))); + +let bytes = model.encode_to_vec(); +assert_eq!(AuthorizationModel::decode(bytes.as_slice())?, model); +# Ok::<(), Box>(()) +``` diff --git a/crates/openfga-model/src/generated/openfga.v1.rs b/crates/openfga-model/src/generated/openfga.v1.rs new file mode 100644 index 0000000..a4e8f77 --- /dev/null +++ b/crates/openfga-model/src/generated/openfga.v1.rs @@ -0,0 +1,254 @@ +// This file is @generated by prost-build. +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct AuthorizationModel { + #[prost(string, tag = "1")] + pub id: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub schema_version: ::prost::alloc::string::String, + #[prost(message, repeated, tag = "3")] + pub type_definitions: ::prost::alloc::vec::Vec, + #[prost(btree_map = "string, message", tag = "4")] + pub conditions: ::prost::alloc::collections::BTreeMap< + ::prost::alloc::string::String, + Condition, + >, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct TypeDefinition { + #[prost(string, tag = "1")] + pub r#type: ::prost::alloc::string::String, + #[prost(btree_map = "string, message", tag = "2")] + pub relations: ::prost::alloc::collections::BTreeMap< + ::prost::alloc::string::String, + Userset, + >, + /// A map whose keys are the name of the relation and whose value is the Metadata for that relation. + /// It also holds information around the module name and source file if this model was constructed + /// from a modular model. + #[prost(message, optional, tag = "3")] + pub metadata: ::core::option::Option, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Relation { + #[prost(string, tag = "1")] + pub name: ::prost::alloc::string::String, + #[prost(message, optional, tag = "2")] + pub rewrite: ::core::option::Option, + #[prost(message, optional, tag = "3")] + pub type_info: ::core::option::Option, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct RelationTypeInfo { + #[prost(message, repeated, tag = "1")] + pub directly_related_user_types: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Metadata { + #[prost(btree_map = "string, message", tag = "1")] + pub relations: ::prost::alloc::collections::BTreeMap< + ::prost::alloc::string::String, + RelationMetadata, + >, + #[prost(string, tag = "2")] + pub module: ::prost::alloc::string::String, + #[prost(message, optional, tag = "3")] + pub source_info: ::core::option::Option, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct SourceInfo { + #[prost(string, tag = "1")] + pub file: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct RelationMetadata { + #[prost(message, repeated, tag = "1")] + pub directly_related_user_types: ::prost::alloc::vec::Vec, + #[prost(string, tag = "2")] + pub module: ::prost::alloc::string::String, + #[prost(message, optional, tag = "3")] + pub source_info: ::core::option::Option, +} +/// RelationReference represents a relation of a particular object type (e.g. 'document#viewer'). +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct RelationReference { + #[prost(string, tag = "1")] + pub r#type: ::prost::alloc::string::String, + /// The name of a condition that is enforced over the allowed relation. + #[prost(string, tag = "4")] + pub condition: ::prost::alloc::string::String, + #[prost(oneof = "relation_reference::RelationOrWildcard", tags = "2, 3")] + pub relation_or_wildcard: ::core::option::Option< + relation_reference::RelationOrWildcard, + >, +} +/// Nested message and enum types in `RelationReference`. +pub mod relation_reference { + #[derive(Clone, PartialEq, Eq, Hash, ::prost::Oneof)] + pub enum RelationOrWildcard { + #[prost(string, tag = "2")] + Relation(::prost::alloc::string::String), + #[prost(message, tag = "3")] + Wildcard(super::Wildcard), + } +} +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Wildcard {} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Usersets { + #[prost(message, repeated, tag = "1")] + pub child: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Difference { + #[prost(message, optional, boxed, tag = "1")] + pub base: ::core::option::Option<::prost::alloc::boxed::Box>, + #[prost(message, optional, boxed, tag = "2")] + pub subtract: ::core::option::Option<::prost::alloc::boxed::Box>, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Userset { + #[prost(oneof = "userset::Userset", tags = "1, 2, 3, 4, 5, 6")] + pub userset: ::core::option::Option, +} +/// Nested message and enum types in `Userset`. +pub mod userset { + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Userset { + #[prost(message, tag = "1")] + This(super::DirectUserset), + #[prost(message, tag = "2")] + ComputedUserset(super::ObjectRelation), + #[prost(message, tag = "3")] + TupleToUserset(super::TupleToUserset), + #[prost(message, tag = "4")] + Union(super::Usersets), + #[prost(message, tag = "5")] + Intersection(super::Usersets), + #[prost(message, tag = "6")] + Difference(::prost::alloc::boxed::Box), + } +} +/// A DirectUserset is a sentinel message for referencing +/// the direct members specified by an object/relation mapping. +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct DirectUserset {} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ObjectRelation { + #[prost(string, tag = "1")] + pub object: ::prost::alloc::string::String, + #[prost(string, tag = "2")] + pub relation: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ComputedUserset { + #[prost(string, tag = "1")] + pub relation: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct TupleToUserset { + /// The target object/relation + #[prost(message, optional, tag = "1")] + pub tupleset: ::core::option::Option, + #[prost(message, optional, tag = "2")] + pub computed_userset: ::core::option::Option, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Condition { + /// A unique name for the condition + #[prost(string, tag = "1")] + pub name: ::prost::alloc::string::String, + /// A Google CEL expression, expressed as a string. + #[prost(string, tag = "2")] + pub expression: ::prost::alloc::string::String, + /// A map of parameter names to the parameter's defined type reference. + #[prost(btree_map = "string, message", tag = "3")] + pub parameters: ::prost::alloc::collections::BTreeMap< + ::prost::alloc::string::String, + ConditionParamTypeRef, + >, + #[prost(message, optional, tag = "4")] + pub metadata: ::core::option::Option, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ConditionMetadata { + #[prost(string, tag = "1")] + pub module: ::prost::alloc::string::String, + #[prost(message, optional, tag = "2")] + pub source_info: ::core::option::Option, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct ConditionParamTypeRef { + #[prost(enumeration = "condition_param_type_ref::TypeName", tag = "1")] + pub type_name: i32, + #[prost(message, repeated, tag = "2")] + pub generic_types: ::prost::alloc::vec::Vec, +} +/// Nested message and enum types in `ConditionParamTypeRef`. +pub mod condition_param_type_ref { + #[derive( + Clone, + Copy, + Debug, + PartialEq, + Eq, + Hash, + PartialOrd, + Ord, + ::prost::Enumeration + )] + #[repr(i32)] + pub enum TypeName { + Unspecified = 0, + Any = 1, + Bool = 2, + String = 3, + Int = 4, + Uint = 5, + Double = 6, + Duration = 7, + Timestamp = 8, + Map = 9, + List = 10, + Ipaddress = 11, + } + impl TypeName { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Unspecified => "TYPE_NAME_UNSPECIFIED", + Self::Any => "TYPE_NAME_ANY", + Self::Bool => "TYPE_NAME_BOOL", + Self::String => "TYPE_NAME_STRING", + Self::Int => "TYPE_NAME_INT", + Self::Uint => "TYPE_NAME_UINT", + Self::Double => "TYPE_NAME_DOUBLE", + Self::Duration => "TYPE_NAME_DURATION", + Self::Timestamp => "TYPE_NAME_TIMESTAMP", + Self::Map => "TYPE_NAME_MAP", + Self::List => "TYPE_NAME_LIST", + Self::Ipaddress => "TYPE_NAME_IPADDRESS", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "TYPE_NAME_UNSPECIFIED" => Some(Self::Unspecified), + "TYPE_NAME_ANY" => Some(Self::Any), + "TYPE_NAME_BOOL" => Some(Self::Bool), + "TYPE_NAME_STRING" => Some(Self::String), + "TYPE_NAME_INT" => Some(Self::Int), + "TYPE_NAME_UINT" => Some(Self::Uint), + "TYPE_NAME_DOUBLE" => Some(Self::Double), + "TYPE_NAME_DURATION" => Some(Self::Duration), + "TYPE_NAME_TIMESTAMP" => Some(Self::Timestamp), + "TYPE_NAME_MAP" => Some(Self::Map), + "TYPE_NAME_LIST" => Some(Self::List), + "TYPE_NAME_IPADDRESS" => Some(Self::Ipaddress), + _ => None, + } + } + } +} diff --git a/crates/openfga-model/src/generated/openfga.v1.serde.rs b/crates/openfga-model/src/generated/openfga.v1.serde.rs new file mode 100644 index 0000000..5dab697 --- /dev/null +++ b/crates/openfga-model/src/generated/openfga.v1.serde.rs @@ -0,0 +1,2249 @@ +// This file is @generated by pbjson-build. +impl serde::Serialize for AuthorizationModel { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.id.is_empty() { + len += 1; + } + if !self.schema_version.is_empty() { + len += 1; + } + if !self.type_definitions.is_empty() { + len += 1; + } + if !self.conditions.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.AuthorizationModel", len)?; + if !self.id.is_empty() { + struct_ser.serialize_field("id", &self.id)?; + } + if !self.schema_version.is_empty() { + struct_ser.serialize_field("schema_version", &self.schema_version)?; + } + if !self.type_definitions.is_empty() { + struct_ser.serialize_field("type_definitions", &self.type_definitions)?; + } + if !self.conditions.is_empty() { + struct_ser.serialize_field("conditions", &self.conditions)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for AuthorizationModel { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "id", + "schema_version", + "type_definitions", + "conditions", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Id, + SchemaVersion, + TypeDefinitions, + Conditions, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "id" => Ok(GeneratedField::Id), + "schema_version" => Ok(GeneratedField::SchemaVersion), + "type_definitions" => Ok(GeneratedField::TypeDefinitions), + "conditions" => Ok(GeneratedField::Conditions), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = AuthorizationModel; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.AuthorizationModel") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut id__ = None; + let mut schema_version__ = None; + let mut type_definitions__ = None; + let mut conditions__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Id => { + if id__.is_some() { + return Err(serde::de::Error::duplicate_field("id")); + } + id__ = Some(map_.next_value()?); + } + GeneratedField::SchemaVersion => { + if schema_version__.is_some() { + return Err(serde::de::Error::duplicate_field("schema_version")); + } + schema_version__ = Some(map_.next_value()?); + } + GeneratedField::TypeDefinitions => { + if type_definitions__.is_some() { + return Err(serde::de::Error::duplicate_field("type_definitions")); + } + type_definitions__ = Some(map_.next_value()?); + } + GeneratedField::Conditions => { + if conditions__.is_some() { + return Err(serde::de::Error::duplicate_field("conditions")); + } + conditions__ = Some( + map_.next_value::<::prost::alloc::collections::BTreeMap<_, _>>()? + ); + } + } + } + Ok(AuthorizationModel { + id: id__.unwrap_or_default(), + schema_version: schema_version__.unwrap_or_default(), + type_definitions: type_definitions__.unwrap_or_default(), + conditions: conditions__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.AuthorizationModel", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for ComputedUserset { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.relation.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.ComputedUserset", len)?; + if !self.relation.is_empty() { + struct_ser.serialize_field("relation", &self.relation)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for ComputedUserset { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "relation", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Relation, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "relation" => Ok(GeneratedField::Relation), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = ComputedUserset; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.ComputedUserset") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut relation__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Relation => { + if relation__.is_some() { + return Err(serde::de::Error::duplicate_field("relation")); + } + relation__ = Some(map_.next_value()?); + } + } + } + Ok(ComputedUserset { + relation: relation__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.ComputedUserset", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for Condition { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.name.is_empty() { + len += 1; + } + if !self.expression.is_empty() { + len += 1; + } + if !self.parameters.is_empty() { + len += 1; + } + if self.metadata.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.Condition", len)?; + if !self.name.is_empty() { + struct_ser.serialize_field("name", &self.name)?; + } + if !self.expression.is_empty() { + struct_ser.serialize_field("expression", &self.expression)?; + } + if !self.parameters.is_empty() { + struct_ser.serialize_field("parameters", &self.parameters)?; + } + if let Some(v) = self.metadata.as_ref() { + struct_ser.serialize_field("metadata", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Condition { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "name", + "expression", + "parameters", + "metadata", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Name, + Expression, + Parameters, + Metadata, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "name" => Ok(GeneratedField::Name), + "expression" => Ok(GeneratedField::Expression), + "parameters" => Ok(GeneratedField::Parameters), + "metadata" => Ok(GeneratedField::Metadata), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Condition; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Condition") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut name__ = None; + let mut expression__ = None; + let mut parameters__ = None; + let mut metadata__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Name => { + if name__.is_some() { + return Err(serde::de::Error::duplicate_field("name")); + } + name__ = Some(map_.next_value()?); + } + GeneratedField::Expression => { + if expression__.is_some() { + return Err(serde::de::Error::duplicate_field("expression")); + } + expression__ = Some(map_.next_value()?); + } + GeneratedField::Parameters => { + if parameters__.is_some() { + return Err(serde::de::Error::duplicate_field("parameters")); + } + parameters__ = Some( + map_.next_value::<::prost::alloc::collections::BTreeMap<_, _>>()? + ); + } + GeneratedField::Metadata => { + if metadata__.is_some() { + return Err(serde::de::Error::duplicate_field("metadata")); + } + metadata__ = map_.next_value()?; + } + } + } + Ok(Condition { + name: name__.unwrap_or_default(), + expression: expression__.unwrap_or_default(), + parameters: parameters__.unwrap_or_default(), + metadata: metadata__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.Condition", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for ConditionMetadata { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.module.is_empty() { + len += 1; + } + if self.source_info.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.ConditionMetadata", len)?; + if !self.module.is_empty() { + struct_ser.serialize_field("module", &self.module)?; + } + if let Some(v) = self.source_info.as_ref() { + struct_ser.serialize_field("source_info", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for ConditionMetadata { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "module", + "source_info", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Module, + SourceInfo, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "module" => Ok(GeneratedField::Module), + "source_info" => Ok(GeneratedField::SourceInfo), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = ConditionMetadata; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.ConditionMetadata") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut module__ = None; + let mut source_info__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Module => { + if module__.is_some() { + return Err(serde::de::Error::duplicate_field("module")); + } + module__ = Some(map_.next_value()?); + } + GeneratedField::SourceInfo => { + if source_info__.is_some() { + return Err(serde::de::Error::duplicate_field("source_info")); + } + source_info__ = map_.next_value()?; + } + } + } + Ok(ConditionMetadata { + module: module__.unwrap_or_default(), + source_info: source_info__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.ConditionMetadata", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for ConditionParamTypeRef { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.type_name != 0 { + len += 1; + } + if !self.generic_types.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.ConditionParamTypeRef", len)?; + if self.type_name != 0 { + let v = condition_param_type_ref::TypeName::try_from(self.type_name) + .map_err(|_| serde::ser::Error::custom(::core::format_args!("Invalid variant {}", self.type_name)))?; + struct_ser.serialize_field("type_name", &v)?; + } + if !self.generic_types.is_empty() { + struct_ser.serialize_field("generic_types", &self.generic_types)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for ConditionParamTypeRef { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "type_name", + "generic_types", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + TypeName, + GenericTypes, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "type_name" => Ok(GeneratedField::TypeName), + "generic_types" => Ok(GeneratedField::GenericTypes), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = ConditionParamTypeRef; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.ConditionParamTypeRef") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut type_name__ = None; + let mut generic_types__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::TypeName => { + if type_name__.is_some() { + return Err(serde::de::Error::duplicate_field("type_name")); + } + type_name__ = Some(map_.next_value::()? as i32); + } + GeneratedField::GenericTypes => { + if generic_types__.is_some() { + return Err(serde::de::Error::duplicate_field("generic_types")); + } + generic_types__ = Some(map_.next_value()?); + } + } + } + Ok(ConditionParamTypeRef { + type_name: type_name__.unwrap_or_default(), + generic_types: generic_types__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.ConditionParamTypeRef", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for condition_param_type_ref::TypeName { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + let variant = match self { + Self::Unspecified => "TYPE_NAME_UNSPECIFIED", + Self::Any => "TYPE_NAME_ANY", + Self::Bool => "TYPE_NAME_BOOL", + Self::String => "TYPE_NAME_STRING", + Self::Int => "TYPE_NAME_INT", + Self::Uint => "TYPE_NAME_UINT", + Self::Double => "TYPE_NAME_DOUBLE", + Self::Duration => "TYPE_NAME_DURATION", + Self::Timestamp => "TYPE_NAME_TIMESTAMP", + Self::Map => "TYPE_NAME_MAP", + Self::List => "TYPE_NAME_LIST", + Self::Ipaddress => "TYPE_NAME_IPADDRESS", + }; + serializer.serialize_str(variant) + } +} +impl<'de> serde::Deserialize<'de> for condition_param_type_ref::TypeName { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "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", + ]; + + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = condition_param_type_ref::TypeName; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + fn visit_i64(self, v: i64) -> ::core::result::Result + where + E: serde::de::Error, + { + i32::try_from(v) + .ok() + .and_then(|x| x.try_into().ok()) + .ok_or_else(|| { + serde::de::Error::invalid_value(serde::de::Unexpected::Signed(v), &self) + }) + } + + fn visit_u64(self, v: u64) -> ::core::result::Result + where + E: serde::de::Error, + { + i32::try_from(v) + .ok() + .and_then(|x| x.try_into().ok()) + .ok_or_else(|| { + serde::de::Error::invalid_value(serde::de::Unexpected::Unsigned(v), &self) + }) + } + + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "TYPE_NAME_UNSPECIFIED" => Ok(condition_param_type_ref::TypeName::Unspecified), + "TYPE_NAME_ANY" => Ok(condition_param_type_ref::TypeName::Any), + "TYPE_NAME_BOOL" => Ok(condition_param_type_ref::TypeName::Bool), + "TYPE_NAME_STRING" => Ok(condition_param_type_ref::TypeName::String), + "TYPE_NAME_INT" => Ok(condition_param_type_ref::TypeName::Int), + "TYPE_NAME_UINT" => Ok(condition_param_type_ref::TypeName::Uint), + "TYPE_NAME_DOUBLE" => Ok(condition_param_type_ref::TypeName::Double), + "TYPE_NAME_DURATION" => Ok(condition_param_type_ref::TypeName::Duration), + "TYPE_NAME_TIMESTAMP" => Ok(condition_param_type_ref::TypeName::Timestamp), + "TYPE_NAME_MAP" => Ok(condition_param_type_ref::TypeName::Map), + "TYPE_NAME_LIST" => Ok(condition_param_type_ref::TypeName::List), + "TYPE_NAME_IPADDRESS" => Ok(condition_param_type_ref::TypeName::Ipaddress), + _ => Err(serde::de::Error::unknown_variant(value, FIELDS)), + } + } + } + deserializer.deserialize_any(GeneratedVisitor) + } +} +impl serde::Serialize for Difference { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.base.is_some() { + len += 1; + } + if self.subtract.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.Difference", len)?; + if let Some(v) = self.base.as_ref() { + struct_ser.serialize_field("base", v)?; + } + if let Some(v) = self.subtract.as_ref() { + struct_ser.serialize_field("subtract", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Difference { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "base", + "subtract", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Base, + Subtract, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "base" => Ok(GeneratedField::Base), + "subtract" => Ok(GeneratedField::Subtract), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Difference; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Difference") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut base__ = None; + let mut subtract__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Base => { + if base__.is_some() { + return Err(serde::de::Error::duplicate_field("base")); + } + base__ = map_.next_value()?; + } + GeneratedField::Subtract => { + if subtract__.is_some() { + return Err(serde::de::Error::duplicate_field("subtract")); + } + subtract__ = map_.next_value()?; + } + } + } + Ok(Difference { + base: base__, + subtract: subtract__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.Difference", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for DirectUserset { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let len = 0; + let struct_ser = serializer.serialize_struct("openfga.v1.DirectUserset", len)?; + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for DirectUserset { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + Err(serde::de::Error::unknown_field(value, FIELDS)) + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = DirectUserset; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.DirectUserset") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + while map_.next_key::()?.is_some() { + let _ = map_.next_value::()?; + } + Ok(DirectUserset { + }) + } + } + deserializer.deserialize_struct("openfga.v1.DirectUserset", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for Metadata { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.relations.is_empty() { + len += 1; + } + if !self.module.is_empty() { + len += 1; + } + if self.source_info.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.Metadata", len)?; + if !self.relations.is_empty() { + struct_ser.serialize_field("relations", &self.relations)?; + } + if !self.module.is_empty() { + struct_ser.serialize_field("module", &self.module)?; + } + if let Some(v) = self.source_info.as_ref() { + struct_ser.serialize_field("source_info", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Metadata { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "relations", + "module", + "source_info", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Relations, + Module, + SourceInfo, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "relations" => Ok(GeneratedField::Relations), + "module" => Ok(GeneratedField::Module), + "source_info" => Ok(GeneratedField::SourceInfo), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Metadata; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Metadata") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut relations__ = None; + let mut module__ = None; + let mut source_info__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Relations => { + if relations__.is_some() { + return Err(serde::de::Error::duplicate_field("relations")); + } + relations__ = Some( + map_.next_value::<::prost::alloc::collections::BTreeMap<_, _>>()? + ); + } + GeneratedField::Module => { + if module__.is_some() { + return Err(serde::de::Error::duplicate_field("module")); + } + module__ = Some(map_.next_value()?); + } + GeneratedField::SourceInfo => { + if source_info__.is_some() { + return Err(serde::de::Error::duplicate_field("source_info")); + } + source_info__ = map_.next_value()?; + } + } + } + Ok(Metadata { + relations: relations__.unwrap_or_default(), + module: module__.unwrap_or_default(), + source_info: source_info__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.Metadata", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for ObjectRelation { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.object.is_empty() { + len += 1; + } + if !self.relation.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.ObjectRelation", len)?; + if !self.object.is_empty() { + struct_ser.serialize_field("object", &self.object)?; + } + if !self.relation.is_empty() { + struct_ser.serialize_field("relation", &self.relation)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for ObjectRelation { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "object", + "relation", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Object, + Relation, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "object" => Ok(GeneratedField::Object), + "relation" => Ok(GeneratedField::Relation), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = ObjectRelation; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.ObjectRelation") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut object__ = None; + let mut relation__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Object => { + if object__.is_some() { + return Err(serde::de::Error::duplicate_field("object")); + } + object__ = Some(map_.next_value()?); + } + GeneratedField::Relation => { + if relation__.is_some() { + return Err(serde::de::Error::duplicate_field("relation")); + } + relation__ = Some(map_.next_value()?); + } + } + } + Ok(ObjectRelation { + object: object__.unwrap_or_default(), + relation: relation__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.ObjectRelation", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for Relation { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.name.is_empty() { + len += 1; + } + if self.rewrite.is_some() { + len += 1; + } + if self.type_info.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.Relation", len)?; + if !self.name.is_empty() { + struct_ser.serialize_field("name", &self.name)?; + } + if let Some(v) = self.rewrite.as_ref() { + struct_ser.serialize_field("rewrite", v)?; + } + if let Some(v) = self.type_info.as_ref() { + struct_ser.serialize_field("typeInfo", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Relation { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "name", + "rewrite", + "type_info", + "typeInfo", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Name, + Rewrite, + TypeInfo, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "name" => Ok(GeneratedField::Name), + "rewrite" => Ok(GeneratedField::Rewrite), + "typeInfo" | "type_info" => Ok(GeneratedField::TypeInfo), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Relation; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Relation") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut name__ = None; + let mut rewrite__ = None; + let mut type_info__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Name => { + if name__.is_some() { + return Err(serde::de::Error::duplicate_field("name")); + } + name__ = Some(map_.next_value()?); + } + GeneratedField::Rewrite => { + if rewrite__.is_some() { + return Err(serde::de::Error::duplicate_field("rewrite")); + } + rewrite__ = map_.next_value()?; + } + GeneratedField::TypeInfo => { + if type_info__.is_some() { + return Err(serde::de::Error::duplicate_field("typeInfo")); + } + type_info__ = map_.next_value()?; + } + } + } + Ok(Relation { + name: name__.unwrap_or_default(), + rewrite: rewrite__, + type_info: type_info__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.Relation", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for RelationMetadata { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.directly_related_user_types.is_empty() { + len += 1; + } + if !self.module.is_empty() { + len += 1; + } + if self.source_info.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.RelationMetadata", len)?; + if !self.directly_related_user_types.is_empty() { + struct_ser.serialize_field("directly_related_user_types", &self.directly_related_user_types)?; + } + if !self.module.is_empty() { + struct_ser.serialize_field("module", &self.module)?; + } + if let Some(v) = self.source_info.as_ref() { + struct_ser.serialize_field("source_info", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for RelationMetadata { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "directly_related_user_types", + "module", + "source_info", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + DirectlyRelatedUserTypes, + Module, + SourceInfo, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "directly_related_user_types" => Ok(GeneratedField::DirectlyRelatedUserTypes), + "module" => Ok(GeneratedField::Module), + "source_info" => Ok(GeneratedField::SourceInfo), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = RelationMetadata; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.RelationMetadata") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut directly_related_user_types__ = None; + let mut module__ = None; + let mut source_info__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::DirectlyRelatedUserTypes => { + if directly_related_user_types__.is_some() { + return Err(serde::de::Error::duplicate_field("directly_related_user_types")); + } + directly_related_user_types__ = Some(map_.next_value()?); + } + GeneratedField::Module => { + if module__.is_some() { + return Err(serde::de::Error::duplicate_field("module")); + } + module__ = Some(map_.next_value()?); + } + GeneratedField::SourceInfo => { + if source_info__.is_some() { + return Err(serde::de::Error::duplicate_field("source_info")); + } + source_info__ = map_.next_value()?; + } + } + } + Ok(RelationMetadata { + directly_related_user_types: directly_related_user_types__.unwrap_or_default(), + module: module__.unwrap_or_default(), + source_info: source_info__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.RelationMetadata", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for RelationReference { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.r#type.is_empty() { + len += 1; + } + if !self.condition.is_empty() { + len += 1; + } + if self.relation_or_wildcard.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.RelationReference", len)?; + if !self.r#type.is_empty() { + struct_ser.serialize_field("type", &self.r#type)?; + } + if !self.condition.is_empty() { + struct_ser.serialize_field("condition", &self.condition)?; + } + if let Some(v) = self.relation_or_wildcard.as_ref() { + match v { + relation_reference::RelationOrWildcard::Relation(v) => { + struct_ser.serialize_field("relation", v)?; + } + relation_reference::RelationOrWildcard::Wildcard(v) => { + struct_ser.serialize_field("wildcard", v)?; + } + } + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for RelationReference { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "type", + "condition", + "relation", + "wildcard", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Type, + Condition, + Relation, + Wildcard, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "type" => Ok(GeneratedField::Type), + "condition" => Ok(GeneratedField::Condition), + "relation" => Ok(GeneratedField::Relation), + "wildcard" => Ok(GeneratedField::Wildcard), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = RelationReference; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.RelationReference") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut r#type__ = None; + let mut condition__ = None; + let mut relation_or_wildcard__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Type => { + if r#type__.is_some() { + return Err(serde::de::Error::duplicate_field("type")); + } + r#type__ = Some(map_.next_value()?); + } + GeneratedField::Condition => { + if condition__.is_some() { + return Err(serde::de::Error::duplicate_field("condition")); + } + condition__ = Some(map_.next_value()?); + } + GeneratedField::Relation => { + if relation_or_wildcard__.is_some() { + return Err(serde::de::Error::duplicate_field("relation")); + } + relation_or_wildcard__ = map_.next_value::<::core::option::Option<_>>()?.map(relation_reference::RelationOrWildcard::Relation); + } + GeneratedField::Wildcard => { + if relation_or_wildcard__.is_some() { + return Err(serde::de::Error::duplicate_field("wildcard")); + } + relation_or_wildcard__ = map_.next_value::<::core::option::Option<_>>()?.map(relation_reference::RelationOrWildcard::Wildcard) +; + } + } + } + Ok(RelationReference { + r#type: r#type__.unwrap_or_default(), + condition: condition__.unwrap_or_default(), + relation_or_wildcard: relation_or_wildcard__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.RelationReference", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for RelationTypeInfo { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.directly_related_user_types.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.RelationTypeInfo", len)?; + if !self.directly_related_user_types.is_empty() { + struct_ser.serialize_field("directly_related_user_types", &self.directly_related_user_types)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for RelationTypeInfo { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "directly_related_user_types", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + DirectlyRelatedUserTypes, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "directly_related_user_types" => Ok(GeneratedField::DirectlyRelatedUserTypes), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = RelationTypeInfo; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.RelationTypeInfo") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut directly_related_user_types__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::DirectlyRelatedUserTypes => { + if directly_related_user_types__.is_some() { + return Err(serde::de::Error::duplicate_field("directly_related_user_types")); + } + directly_related_user_types__ = Some(map_.next_value()?); + } + } + } + Ok(RelationTypeInfo { + directly_related_user_types: directly_related_user_types__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.RelationTypeInfo", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for SourceInfo { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.file.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.SourceInfo", len)?; + if !self.file.is_empty() { + struct_ser.serialize_field("file", &self.file)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for SourceInfo { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "file", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + File, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "file" => Ok(GeneratedField::File), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = SourceInfo; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.SourceInfo") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut file__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::File => { + if file__.is_some() { + return Err(serde::de::Error::duplicate_field("file")); + } + file__ = Some(map_.next_value()?); + } + } + } + Ok(SourceInfo { + file: file__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.SourceInfo", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for TupleToUserset { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.tupleset.is_some() { + len += 1; + } + if self.computed_userset.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.TupleToUserset", len)?; + if let Some(v) = self.tupleset.as_ref() { + struct_ser.serialize_field("tupleset", v)?; + } + if let Some(v) = self.computed_userset.as_ref() { + struct_ser.serialize_field("computedUserset", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for TupleToUserset { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "tupleset", + "computed_userset", + "computedUserset", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Tupleset, + ComputedUserset, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "tupleset" => Ok(GeneratedField::Tupleset), + "computedUserset" | "computed_userset" => Ok(GeneratedField::ComputedUserset), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = TupleToUserset; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.TupleToUserset") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut tupleset__ = None; + let mut computed_userset__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Tupleset => { + if tupleset__.is_some() { + return Err(serde::de::Error::duplicate_field("tupleset")); + } + tupleset__ = map_.next_value()?; + } + GeneratedField::ComputedUserset => { + if computed_userset__.is_some() { + return Err(serde::de::Error::duplicate_field("computedUserset")); + } + computed_userset__ = map_.next_value()?; + } + } + } + Ok(TupleToUserset { + tupleset: tupleset__, + computed_userset: computed_userset__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.TupleToUserset", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for TypeDefinition { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.r#type.is_empty() { + len += 1; + } + if !self.relations.is_empty() { + len += 1; + } + if self.metadata.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.TypeDefinition", len)?; + if !self.r#type.is_empty() { + struct_ser.serialize_field("type", &self.r#type)?; + } + if !self.relations.is_empty() { + struct_ser.serialize_field("relations", &self.relations)?; + } + if let Some(v) = self.metadata.as_ref() { + struct_ser.serialize_field("metadata", v)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for TypeDefinition { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "type", + "relations", + "metadata", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Type, + Relations, + Metadata, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "type" => Ok(GeneratedField::Type), + "relations" => Ok(GeneratedField::Relations), + "metadata" => Ok(GeneratedField::Metadata), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = TypeDefinition; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.TypeDefinition") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut r#type__ = None; + let mut relations__ = None; + let mut metadata__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Type => { + if r#type__.is_some() { + return Err(serde::de::Error::duplicate_field("type")); + } + r#type__ = Some(map_.next_value()?); + } + GeneratedField::Relations => { + if relations__.is_some() { + return Err(serde::de::Error::duplicate_field("relations")); + } + relations__ = Some( + map_.next_value::<::prost::alloc::collections::BTreeMap<_, _>>()? + ); + } + GeneratedField::Metadata => { + if metadata__.is_some() { + return Err(serde::de::Error::duplicate_field("metadata")); + } + metadata__ = map_.next_value()?; + } + } + } + Ok(TypeDefinition { + r#type: r#type__.unwrap_or_default(), + relations: relations__.unwrap_or_default(), + metadata: metadata__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.TypeDefinition", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for Userset { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if self.userset.is_some() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.Userset", len)?; + if let Some(v) = self.userset.as_ref() { + match v { + userset::Userset::This(v) => { + struct_ser.serialize_field("this", v)?; + } + userset::Userset::ComputedUserset(v) => { + struct_ser.serialize_field("computedUserset", v)?; + } + userset::Userset::TupleToUserset(v) => { + struct_ser.serialize_field("tupleToUserset", v)?; + } + userset::Userset::Union(v) => { + struct_ser.serialize_field("union", v)?; + } + userset::Userset::Intersection(v) => { + struct_ser.serialize_field("intersection", v)?; + } + userset::Userset::Difference(v) => { + struct_ser.serialize_field("difference", v)?; + } + } + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Userset { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "this", + "computed_userset", + "computedUserset", + "tuple_to_userset", + "tupleToUserset", + "union", + "intersection", + "difference", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + This, + ComputedUserset, + TupleToUserset, + Union, + Intersection, + Difference, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "this" => Ok(GeneratedField::This), + "computedUserset" | "computed_userset" => Ok(GeneratedField::ComputedUserset), + "tupleToUserset" | "tuple_to_userset" => Ok(GeneratedField::TupleToUserset), + "union" => Ok(GeneratedField::Union), + "intersection" => Ok(GeneratedField::Intersection), + "difference" => Ok(GeneratedField::Difference), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Userset; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Userset") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut userset__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::This => { + if userset__.is_some() { + return Err(serde::de::Error::duplicate_field("this")); + } + userset__ = map_.next_value::<::core::option::Option<_>>()?.map(userset::Userset::This) +; + } + GeneratedField::ComputedUserset => { + if userset__.is_some() { + return Err(serde::de::Error::duplicate_field("computedUserset")); + } + userset__ = map_.next_value::<::core::option::Option<_>>()?.map(userset::Userset::ComputedUserset) +; + } + GeneratedField::TupleToUserset => { + if userset__.is_some() { + return Err(serde::de::Error::duplicate_field("tupleToUserset")); + } + userset__ = map_.next_value::<::core::option::Option<_>>()?.map(userset::Userset::TupleToUserset) +; + } + GeneratedField::Union => { + if userset__.is_some() { + return Err(serde::de::Error::duplicate_field("union")); + } + userset__ = map_.next_value::<::core::option::Option<_>>()?.map(userset::Userset::Union) +; + } + GeneratedField::Intersection => { + if userset__.is_some() { + return Err(serde::de::Error::duplicate_field("intersection")); + } + userset__ = map_.next_value::<::core::option::Option<_>>()?.map(userset::Userset::Intersection) +; + } + GeneratedField::Difference => { + if userset__.is_some() { + return Err(serde::de::Error::duplicate_field("difference")); + } + userset__ = map_.next_value::<::core::option::Option<_>>()?.map(userset::Userset::Difference) +; + } + } + } + Ok(Userset { + userset: userset__, + }) + } + } + deserializer.deserialize_struct("openfga.v1.Userset", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for Usersets { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let mut len = 0; + if !self.child.is_empty() { + len += 1; + } + let mut struct_ser = serializer.serialize_struct("openfga.v1.Usersets", len)?; + if !self.child.is_empty() { + struct_ser.serialize_field("child", &self.child)?; + } + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Usersets { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + "child", + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + Child, + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + match value { + "child" => Ok(GeneratedField::Child), + _ => Err(serde::de::Error::unknown_field(value, FIELDS)), + } + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Usersets; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Usersets") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + let mut child__ = None; + while let Some(k) = map_.next_key()? { + match k { + GeneratedField::Child => { + if child__.is_some() { + return Err(serde::de::Error::duplicate_field("child")); + } + child__ = Some(map_.next_value()?); + } + } + } + Ok(Usersets { + child: child__.unwrap_or_default(), + }) + } + } + deserializer.deserialize_struct("openfga.v1.Usersets", FIELDS, GeneratedVisitor) + } +} +impl serde::Serialize for Wildcard { + #[allow(deprecated)] + fn serialize(&self, serializer: S) -> ::core::result::Result + where + S: serde::Serializer, + { + use serde::ser::SerializeStruct; + let len = 0; + let struct_ser = serializer.serialize_struct("openfga.v1.Wildcard", len)?; + struct_ser.end() + } +} +impl<'de> serde::Deserialize<'de> for Wildcard { + #[allow(deprecated)] + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + const FIELDS: &[&str] = &[ + ]; + + #[allow(clippy::enum_variant_names)] + enum GeneratedField { + } + impl<'de> serde::Deserialize<'de> for GeneratedField { + fn deserialize(deserializer: D) -> ::core::result::Result + where + D: serde::Deserializer<'de>, + { + struct GeneratedVisitor; + + impl serde::de::Visitor<'_> for GeneratedVisitor { + type Value = GeneratedField; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + write!(formatter, "expected one of: {:?}", FIELDS) + } + + #[allow(unused_variables)] + fn visit_str(self, value: &str) -> ::core::result::Result + where + E: serde::de::Error, + { + Err(serde::de::Error::unknown_field(value, FIELDS)) + } + } + deserializer.deserialize_identifier(GeneratedVisitor) + } + } + struct GeneratedVisitor; + impl<'de> serde::de::Visitor<'de> for GeneratedVisitor { + type Value = Wildcard; + + fn expecting(&self, formatter: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + formatter.write_str("struct openfga.v1.Wildcard") + } + + fn visit_map(self, mut map_: V) -> ::core::result::Result + where + V: serde::de::MapAccess<'de>, + { + while map_.next_key::()?.is_some() { + let _ = map_.next_value::()?; + } + Ok(Wildcard { + }) + } + } + deserializer.deserialize_struct("openfga.v1.Wildcard", FIELDS, GeneratedVisitor) + } +} diff --git a/crates/openfga-model/src/lib.rs b/crates/openfga-model/src/lib.rs new file mode 100644 index 0000000..9e4608a --- /dev/null +++ b/crates/openfga-model/src/lib.rs @@ -0,0 +1,20 @@ +#![doc = include_str!("../README.md")] +#![no_std] + +/// The `openfga.v1` messages of `authzmodel.proto`, generated by `cargo run -p codegen`. +#[expect( + missing_docs, + reason = "the docs are the comments of authzmodel.proto, which leaves most items undocumented" +)] +#[expect( + clippy::allow_attributes, + clippy::allow_attributes_without_reason, + clippy::pedantic, + reason = "prost-build and pbjson-build write this code, with their own allow attributes" +)] +mod generated { + include!("generated/openfga.v1.rs"); + include!("generated/openfga.v1.serde.rs"); +} + +pub use generated::*; diff --git a/crates/openfga-model/tests/conformance.rs b/crates/openfga-model/tests/conformance.rs new file mode 100644 index 0000000..4f454f9 --- /dev/null +++ b/crates/openfga-model/tests/conformance.rs @@ -0,0 +1,98 @@ +//! Every authorization model JSON in the pinned openfga/language corpus reads into the model +//! types and survives both the JSON and the protobuf binary encodings. + +use std::fs; +use std::path::{Path, PathBuf}; + +use openfga_model::AuthorizationModel; +use prost::Message; +use serde_json::Value; + +/// JSON names of the map fields in `authzmodel.proto`, whose empty object is the default value. +const MAP_FIELDS: [&str; 3] = ["conditions", "parameters", "relations"]; + +/// Returns every `authorization-model.json` under the corpus suites holding whole models. +fn corpus_models() -> Vec { + let data = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../conformance/openfga-language/tests/data"); + let mut models = Vec::new(); + for suite in ["transformer", "transformer-module"] { + let suite_dir = data.join(suite); + let cases = fs::read_dir(&suite_dir).unwrap_or_else(|error| { + panic!( + "reading {}, run `git submodule update --init`: {error}", + suite_dir.display() + ) + }); + for case in cases { + let model = case + .expect("a corpus directory entry") + .path() + .join("authorization-model.json"); + if model.is_file() { + models.push(model); + } + } + } + models.sort(); + models +} + +/// Removes every member holding its field's proto3 default, which the JSON mapping may omit. +fn without_defaults(value: Value) -> Value { + match value { + Value::Object(members) => Value::Object( + members + .into_iter() + .filter(|(key, member)| !is_default(key, member)) + .map(|(key, member)| (key, without_defaults(member))) + .collect(), + ), + Value::Array(items) => Value::Array(items.into_iter().map(without_defaults).collect()), + scalar => scalar, + } +} + +/// Whether `member`, stored under `key`, is the proto3 default for its field. +fn is_default(key: &str, member: &Value) -> bool { + match member { + Value::Null => true, + Value::Bool(flag) => !flag, + Value::Number(number) => number.as_f64() == Some(0.0), + Value::String(text) => text.is_empty(), + Value::Array(items) => items.is_empty(), + Value::Object(members) => members.is_empty() && MAP_FIELDS.contains(&key), + } +} + +#[test] +fn corpus_models_round_trip() { + let models = corpus_models(); + assert!( + !models.is_empty(), + "the corpus holds no authorization-model.json" + ); + for path in models { + let text = fs::read_to_string(&path).expect("a readable corpus model"); + let input: Value = serde_json::from_str(&text).expect("corpus JSON"); + let model: AuthorizationModel = serde_json::from_str(&text) + .unwrap_or_else(|error| panic!("{} does not read: {error}", path.display())); + + let written = serde_json::to_value(&model).expect("a model writes as JSON"); + assert_eq!( + written, + without_defaults(input), + "{} writes different JSON", + path.display() + ); + + let decoded = AuthorizationModel::decode(model.encode_to_vec().as_slice()) + .unwrap_or_else(|error| panic!("{} does not decode: {error}", path.display())); + assert_eq!( + decoded, + model, + "{} changes through protobuf", + path.display() + ); + } +}