├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ ├── automatic-api-update.yaml │ ├── build.yaml │ ├── cla.yaml │ ├── manual-api-update.yaml │ └── publish.yaml ├── .gitignore ├── CODE-OF-CONDUCT.md ├── CODEOWNERS ├── CONTRIBUTING.md ├── DCO ├── LICENSE ├── README.md ├── build.gradle ├── examples └── v1 │ └── App.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── intTest └── java │ ├── TestClient.java │ └── V1ClientTest.java └── main └── java └── com └── authzed └── grpcutil └── BearerToken.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # These are explicitly windows files and should use crlf 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | *.bat text eol=crlf 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gradle" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | groups: 8 | gradle: 9 | patterns: ["*"] 10 | - package-ecosystem: "github-actions" 11 | directory: "/" 12 | schedule: 13 | interval: "monthly" 14 | groups: 15 | github-actions: 16 | patterns: ["*"] 17 | -------------------------------------------------------------------------------- /.github/workflows/automatic-api-update.yaml: -------------------------------------------------------------------------------- 1 | name: "Called update for API change" 2 | on: 3 | repository_dispatch: 4 | types: ["api_update"] 5 | jobs: 6 | test: 7 | name: "Create PR for API update" 8 | timeout-minutes: 10 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - uses: actions/setup-node@v4 13 | - name: "Update Buf Script" 14 | id: buf-update 15 | uses: authzed/actions/buf-api-update@main 16 | with: 17 | api-commit: "${{ github.event.client_payload.BUFTAG }}" 18 | spec-path: build.gradle 19 | file-format: gradle 20 | - name: "Output update status" 21 | env: 22 | UPDATED_STATUS: ${{ steps.buf-update.outputs.updated }} 23 | run: | 24 | echo "Update status: $UPDATED_STATUS" 25 | - name: "Update README package version" 26 | uses: authzed/actions/semver-update@main 27 | if: steps.buf-update.outputs.updated == 'true' 28 | with: 29 | sourcefile-path: README.md 30 | version-regex: 'authzed<\/artifactId>\s+(.+)<\/version>' 31 | version-change: minor 32 | - name: Create Pull Request 33 | uses: peter-evans/create-pull-request@v7.0.8 34 | if: steps.buf-update.outputs.updated == 'true' 35 | with: 36 | delete-branch: "true" 37 | title: "Update API to ${{ github.event.client_payload.BUFTAG }}" 38 | branch: "api-change/${{ github.event.client_payload.BUFTAG }}" 39 | token: ${{ secrets.GITHUB_TOKEN }} 40 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: "build" 2 | on: 3 | push: 4 | branches: 5 | - "!dependabot/*" 6 | - "*" 7 | pull_request: 8 | branches: 9 | - "*" 10 | types: 11 | # NOTE: these are the defaults 12 | - opened 13 | - synchronize 14 | - reopened 15 | # NOTE: we add this to let the conversion from draft trigger the workflows 16 | - ready_for_review 17 | merge_group: 18 | types: 19 | - "checks_requested" 20 | jobs: 21 | build: 22 | runs-on: "ubuntu-latest" 23 | strategy: 24 | matrix: 25 | java: 26 | - 8 # Oldest 27 | - 21 # LTS 28 | - 24 # Latest 29 | name: "Java ${{ matrix.java }} Build" 30 | steps: 31 | - uses: "actions/checkout@v4" 32 | - uses: "actions/setup-java@v4" 33 | with: 34 | distribution: "adopt" 35 | java-package: "jdk" 36 | java-version: "${{ matrix.java }}" 37 | - uses: "bufbuild/buf-setup-action@v1" 38 | with: 39 | version: "1.18.0" 40 | github_token: ${{ github.token }} 41 | - uses: "gradle/wrapper-validation-action@v3" 42 | - name: "Gradle Build" 43 | run: "./gradlew build" 44 | test: 45 | runs-on: "ubuntu-latest" 46 | strategy: 47 | matrix: 48 | java: 49 | - 8 # Oldest 50 | - 21 # LTS 51 | - 24 # Latest 52 | name: "Java ${{ matrix.java }} Test" 53 | steps: 54 | - uses: "actions/checkout@v4" 55 | - uses: "actions/setup-java@v4" 56 | with: 57 | distribution: "adopt" 58 | java-package: "jdk" 59 | java-version: "${{ matrix.java }}" 60 | - uses: "bufbuild/buf-setup-action@v1" 61 | with: 62 | version: "1.18.0" 63 | github_token: ${{ github.token }} 64 | - uses: "authzed/action-spicedb@v1" 65 | with: 66 | version: "latest" 67 | - uses: "gradle/wrapper-validation-action@v3" 68 | - name: "Gradle integrationTest" 69 | run: "./gradlew integrationTest --info" 70 | -------------------------------------------------------------------------------- /.github/workflows/cla.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: "CLA" 3 | on: # yamllint disable-line rule:truthy 4 | issue_comment: 5 | types: 6 | - "created" 7 | pull_request_target: 8 | types: 9 | - "opened" 10 | - "closed" 11 | - "synchronize" 12 | merge_group: 13 | types: 14 | - "checks_requested" 15 | jobs: 16 | cla: 17 | name: "Check Signature" 18 | runs-on: "ubuntu-latest" 19 | steps: 20 | - uses: "authzed/actions/cla-check@main" 21 | with: 22 | github_token: "${{ secrets.GITHUB_TOKEN }}" 23 | cla_assistant_token: "${{ secrets.CLA_ASSISTANT_ACCESS_TOKEN }}" 24 | -------------------------------------------------------------------------------- /.github/workflows/manual-api-update.yaml: -------------------------------------------------------------------------------- 1 | name: Update for API change 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | buftag: 6 | description: Tag or commit from https://buf.build/authzed/api/tags/main 7 | required: true 8 | type: string 9 | jobs: 10 | test: 11 | name: "Create PR for API update" 12 | timeout-minutes: 10 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-node@v4 17 | - name: "Update Buf Script" 18 | id: buf-update 19 | uses: authzed/actions/buf-api-update@main 20 | with: 21 | api-commit: ${{ inputs.buftag }} 22 | spec-path: build.gradle 23 | file-format: gradle 24 | - name: "Output update status" 25 | env: 26 | UPDATED_STATUS: ${{ steps.buf-update.outputs.updated }} 27 | run: | 28 | echo "Update status: $UPDATED_STATUS" 29 | - name: "Update README package version" 30 | uses: authzed/actions/semver-update@main 31 | if: steps.buf-update.outputs.updated == 'true' 32 | with: 33 | sourcefile-path: README.md 34 | version-regex: 'authzed<\/artifactId>\s+(.+)<\/version>' 35 | version-change: minor 36 | - name: Create Pull Request 37 | uses: peter-evans/create-pull-request@v7.0.8 38 | if: steps.buf-update.outputs.updated == 'true' 39 | with: 40 | delete-branch: "true" 41 | title: Update API to ${{ inputs.buftag }} 42 | branch: api-change/${{ inputs.buftag }} 43 | token: ${{ secrets.GITHUB_TOKEN }} 44 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Publish to Maven" 3 | on: # yamllint disable-line rule:truthy 4 | release: 5 | types: 6 | - "published" 7 | jobs: 8 | publish: 9 | name: "Publish to Maven" 10 | runs-on: "ubuntu-latest" 11 | steps: 12 | - uses: "actions/checkout@v4" 13 | - uses: "actions/setup-java@v4" 14 | with: 15 | distribution: "adopt" 16 | java-package: "jdk" 17 | java-version: "17" # LTS 18 | - uses: "bufbuild/buf-setup-action@v1" 19 | with: 20 | version: "1.18.0" 21 | github_token: ${{ github.token }} 22 | # Store the version, stripping any v-prefix 23 | # This lets us use v-prefixed releases 24 | - name: Write release version 25 | run: | 26 | VERSION=${GITHUB_REF_NAME#v} 27 | echo Version: $VERSION 28 | echo "VERSION=$VERSION" >> $GITHUB_ENV 29 | - name: "Publish to Sonatype" 30 | env: 31 | ORG_GRADLE_PROJECT_signingKey: "${{ secrets.SIGNING_KEY_ARMORED }}" 32 | ORG_GRADLE_PROJECT_signingPassword: "${{ secrets.SIGNING_PASSWORD }}" 33 | ORG_GRADLE_PROJECT_sonatypeUsername: "${{ secrets.SONATYPE_USERNAME }}" 34 | ORG_GRADLE_PROJECT_sonatypePassword: "${{ secrets.SONATYPE_PASSWORD }}" 35 | run: | 36 | export ORG_GRADLE_PROJECT_release=${VERSION} 37 | ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository 38 | - name: Publish JavaDoc 39 | uses: MathieuSoysal/Javadoc-publisher.yml@v3.0.2 40 | with: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | javadoc-branch: javadoc 43 | java-version: 17 44 | project: gradle 45 | target-folder: docs 46 | custom-command: gradle javadoc -Prelease=${VERSION} 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | bin 5 | gradle/wrapper 6 | !gradle/wrapper/gradle-wrapper.jar 7 | !gradle/wrapper/gradle-wrapper.properties 8 | -------------------------------------------------------------------------------- /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 2 | 3 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. 4 | 5 | Examples of unacceptable behavior by participants include: 6 | 7 | - The use of sexualized language or imagery 8 | - Personal attacks 9 | - Trolling or insulting/derogatory comments 10 | - Public or private harassment 11 | - Publishing other’s private information, such as physical or electronic addresses, without explicit permission 12 | - Other unethical or unprofessional conduct 13 | 14 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. 15 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. 16 | Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. 17 | 18 | This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 19 | 20 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 21 | 22 | This Code of Conduct is adapted from the Contributor Covenant, version 1.2.0, available at https://www.contributor-covenant.org/version/1/2/0/code-of-conduct.html 23 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @authzed/spicedb-maintainers 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ## Communication 4 | 5 | - Issues: [GitHub](https://github.com/authzed/authzed-java/issues) 6 | - Email: [Google Groups](https://groups.google.com/g/authzed-oss) 7 | - Discord: [Zanzibar Discord](https://discord.gg/jTysUaxXzM) 8 | 9 | All communication must follow our [Code of Conduct]. 10 | 11 | [Code of Conduct]: CODE-OF-CONDUCT.md 12 | 13 | ## Creating issues 14 | 15 | If any part of the project has a bug or documentation mistakes, please let us know by opening an issue. 16 | All bugs and mistakes are considered very seriously, regardless of complexity. 17 | 18 | Before creating an issue, please check that an issue reporting the same problem does not already exist. 19 | To make the issue accurate and easy to understand, please try to create issues that are: 20 | 21 | - Unique -- do not duplicate existing bug report. 22 | Deuplicate bug reports will be closed. 23 | - Specific -- include as much details as possible: which version, what environment, what configuration, etc. 24 | - Reproducible -- include the steps to reproduce the problem. 25 | Some issues might be hard to reproduce, so please do your best to include the steps that might lead to the problem. 26 | - Isolated -- try to isolate and reproduce the bug with minimum dependencies. 27 | It would significantly slow down the speed to fix a bug if too many dependencies are involved in a bug report. 28 | Debugging external systems that rely on this project is out of scope, but guidance or help using the project itself is fine. 29 | - Scoped -- one bug per report. 30 | Do not follow up with another bug inside one report. 31 | 32 | It may be worthwhile to read [Elika Etemad’s article on filing good bug reports][filing-good-bugs] before creating a bug report. 33 | 34 | Maintainers might ask for further information to resolve an issue. 35 | 36 | [filing-good-bugs]: http://fantasai.inkedblade.net/style/talks/filing-good-bugs/ 37 | 38 | ## Contribution flow 39 | 40 | This is a rough outline of what a contributor's workflow looks like: 41 | 42 | - Create an issue 43 | - Fork the project 44 | - Create a branch from where to base the contribution -- this is almost always `main` 45 | - Push changes into a branch of your fork 46 | - Submit a pull request 47 | - Respond to feedback from project maintainers 48 | 49 | Creating new issues is one of the best ways to contribute. 50 | You have no obligation to offer a solution or code to fix an issue that you open. 51 | If you do decide to try and contribute something, please submit an issue first so that a discussion can occur to avoid any wasted efforts. 52 | 53 | ## Legal requirements 54 | 55 | In order to protect both you and ourselves, all commits will require an explicit sign-off that acknowledges the [DCO]. 56 | 57 | Sign-off commits end with the following line: 58 | 59 | ``` 60 | Signed-off-by: Random J Developer 61 | ``` 62 | 63 | This can be done by using the `--signoff` (or `-s` for short) git flag to append this automatically to your commit message. 64 | If you have already authored a commit that is missing the signed-off, you can amend or rebase your commits and force push them to GitHub. 65 | 66 | [DCO]: /DCO 67 | 68 | ## Common tasks 69 | 70 | ### Testing and building jars 71 | 72 | In order to build this library yourself it requires the following: 73 | 74 | - The latest or an LTS version of [Java] (8, 11, 16) 75 | - [buf] in order to download Protobuf definitions 76 | 77 | Building is the typical [Gradle wrapper] workflow: 78 | 79 | ```sh 80 | ./gradlew build 81 | ``` 82 | 83 | After a successful build, compiled, source, and javadoc jars are located in `build/libs/`. 84 | 85 | [Gradle wrapper]: https://docs.gradle.org/current/userguide/gradle_wrapper.html 86 | [Java]: https://adoptopenjdk.net 87 | [buf]: https://docs.buf.build/installation 88 | -------------------------------------------------------------------------------- /DCO: -------------------------------------------------------------------------------- 1 | Developer Certificate of Origin 2 | Version 1.1 3 | 4 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 5 | 1 Letterman Drive 6 | Suite D4700 7 | San Francisco, CA, 94129 8 | 9 | Everyone is permitted to copy and distribute verbatim copies of this 10 | license document, but changing it is not allowed. 11 | 12 | 13 | Developer's Certificate of Origin 1.1 14 | 15 | By making a contribution to this project, I certify that: 16 | 17 | (a) The contribution was created in whole or in part by me and I 18 | have the right to submit it under the open source license 19 | indicated in the file; or 20 | 21 | (b) The contribution is based upon previous work that, to the best 22 | of my knowledge, is covered under an appropriate open source 23 | license and I have the right under that license to submit that 24 | work with modifications, whether created in whole or in part 25 | by me, under the same open source license (unless I am 26 | permitted to submit under a different license), as indicated 27 | in the file; or 28 | 29 | (c) The contribution was provided directly to me by some other 30 | person who certified (a), (b) or (c) and I have not modified 31 | it. 32 | 33 | (d) I understand and agree that this project and the contribution 34 | are public and that a record of the contribution (including all 35 | personal information I submit with it, including my sign-off) is 36 | maintained indefinitely and may be redistributed consistent with 37 | this project or the open source license(s) involved. 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Authzed Java Client 2 | 3 | [![Maven Metadata](https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Frepo1.maven.org%2Fmaven2%2Fcom%2Fauthzed%2Fapi%2Fauthzed%2Fmaven-metadata.xml)](https://search.maven.org/artifact/com.authzed.api/authzed) 4 | [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) 5 | [![Build Status](https://github.com/authzed/authzed-java/workflows/build/badge.svg)](https://github.com/authzed/authzed-java/actions) 6 | [![Discord Server](https://img.shields.io/discord/844600078504951838?color=7289da&logo=discord "Discord Server")](https://discord.gg/jTysUaxXzM) 7 | [![Twitter](https://img.shields.io/twitter/follow/authzed?color=%23179CF0&logo=twitter&style=flat-square)](https://twitter.com/authzed) 8 | 9 | This repository houses the Java client library for [SpiceDB]. 10 | 11 | [SpiceDB] is a database and service that stores, computes, and validates your application's permissions. 12 | 13 | Developers create a schema that models their permissions requirements and use a client library, such as this one, to apply the schema to the database, insert data into the database, and query the data to efficiently check permissions in their applications. 14 | 15 | Supported client API versions: 16 | - [v1](https://authzed.com/docs/reference/api#authzedapiv1) 17 | 18 | You can find more info on each API on the [SpiceDB API reference documentation]. 19 | Additionally, Protobuf API documentation can be found on the [Buf Registry SpiceDB API repository]. 20 | Documentation for the latest Java client release is available as [Javadoc]. 21 | 22 | See [CONTRIBUTING.md] for instructions on contributing and performing common tasks like building the project and running tests. 23 | 24 | [Authzed]: https://authzed.com 25 | [SpiceDB]: https://github.com/authzed/spicedb 26 | [SpiceDB API Reference documentation]: https://authzed.com/docs/reference/api 27 | [Buf Registry SpiceDB API repository]: https://buf.build/authzed/api/docs/main 28 | [CONTRIBUTING.md]: CONTRIBUTING.md 29 | [Javadoc]: https://authzed.github.io/authzed-java/index.html 30 | 31 | ## Getting Started 32 | 33 | We highly recommend following the **[Protecting Your First App]** guide to learn the latest best practice to integrate an application with SpiceDB. 34 | 35 | If you're interested in examples for a specific API version, they can be found in their respective folders in the [examples directory]. 36 | 37 | [Protecting Your First App]: https://authzed.com/docs/guides/first-app 38 | [examples directory]: /examples 39 | 40 | ## Basic Usage 41 | 42 | ### Installation 43 | 44 | This project is packaged as the artifact `authzed` under the `com.authzed.api` group on [Maven Central]. 45 | You can find the commands for installing the jar for various JVM toolchains on the [Maven Central Artifact Page]. 46 | 47 | Most commonly, if you are using [Maven] you can add the following to your pom.xml: 48 | 49 | ```xml 50 | 51 | 52 | com.authzed.api 53 | authzed 54 | 1.3.0 55 | 56 | 57 | io.grpc 58 | grpc-api 59 | 1.72.0 60 | 61 | 62 | io.grpc 63 | grpc-stub 64 | 1.72.0 65 | 66 | 67 | ``` 68 | 69 | If you are using [Gradle] then add the following to your `build.gradle` file: 70 | 71 | ```groovy 72 | dependencies { 73 | implementation "com.authzed.api:authzed:v1.0.0" 74 | implementation 'io.grpc:grpc-api:1.72.0' 75 | implementation 'io.grpc:grpc-stub:1.72.0' 76 | } 77 | ``` 78 | 79 | [Maven Central]: https://maven.apache.org/repository/index.html 80 | [Maven Central Artifact Page]: https://search.maven.org/artifact/com.authzed.api/authzed 81 | [Maven]: https://maven.apache.org 82 | [Gradle]: https://gradle.org/ 83 | 84 | ### Initializing a client 85 | 86 | Because of how [grpc-java] is designed, there is little in terms of abstraction over the gRPC APIs underpinning Authzed. 87 | A `ManagedChannel` will establish a connection to Authzed that can be shared with _stubs_ for each gRPC service. 88 | To successfully authenticate with the API, you will have to provide a [Bearer Token] with your own API Token 89 | from the [Authzed dashboard] or your local SpiceDB instance in place of `t_your_token_here_1234567deadbeef` as 90 | `CallCredentials` for each stub: 91 | 92 | ```java 93 | package org.example; 94 | 95 | import com.authzed.api.v1.PermissionsServiceGrpc; 96 | import com.authzed.grpcutil.BearerToken; 97 | import io.grpc.ManagedChannel; 98 | import io.grpc.ManagedChannelBuilder; 99 | 100 | public class PermissionServiceExample { 101 | public static void main(String[] args) { 102 | ManagedChannel channel = ManagedChannelBuilder 103 | .forTarget("grpc.authzed.com:443") 104 | .useTransportSecurity() 105 | .build(); 106 | 107 | BearerToken bearerToken = new BearerToken("t_your_token_here_1234567deadbeef"); 108 | PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService = PermissionsServiceGrpc 109 | .newBlockingStub(channel) 110 | .withCallCredentials(bearerToken); 111 | } 112 | } 113 | ``` 114 | 115 | In case of a local development instance of SpiceDB without TLS, configure your `ManagedChannel` as follows: 116 | 117 | ```java 118 | ManagedChannel channel = ManagedChannelBuilder 119 | .forTarget("localhost:50051") 120 | .usePlaintext() 121 | .build(); 122 | ``` 123 | 124 | [grpc-java]: https://github.com/grpc/grpc-java 125 | [Bearer Token]: https://authzed.com/docs/reference/api#authentication 126 | [Authzed dashboard]: https://app.authzed.com/ 127 | 128 | ### Performing an API call 129 | 130 | Request and Response types are located in their respective gRPC Service packages and common types can be found in the Core package. 131 | Referring to the [Authzed ProtoBuf Documentation] is useful for discovering these APIs. 132 | 133 | Because of the verbosity of these types, we recommend writing your own functions/methods to create these types from your existing application's models. 134 | 135 | The following example initializes a permission client, performs a `CheckPermission` call and prints the result 136 | 137 | [Authzed Protobuf Documentation]: https://buf.build/authzed/api/docs/main 138 | 139 | ```java 140 | package org.example; 141 | 142 | import com.authzed.api.v1.*; 143 | import com.authzed.grpcutil.BearerToken; 144 | import io.grpc.ManagedChannel; 145 | import io.grpc.ManagedChannelBuilder; 146 | 147 | public class ClientExample { 148 | public static void main(String[] args) { 149 | ManagedChannel channel = ManagedChannelBuilder 150 | .forTarget("localhost:50051") 151 | .usePlaintext() 152 | .build(); 153 | 154 | BearerToken bearerToken = new BearerToken("t_your_token_here_1234567deadbeef"); 155 | PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService = PermissionsServiceGrpc 156 | .newBlockingStub(channel) 157 | .withCallCredentials(bearerToken); 158 | 159 | 160 | CheckPermissionRequest request = CheckPermissionRequest.newBuilder() 161 | .setConsistency( 162 | Consistency.newBuilder() 163 | .setMinimizeLatency(true) 164 | .build()) 165 | .setResource( 166 | ObjectReference.newBuilder() 167 | .setObjectType("blog/post") 168 | .setObjectId("1") 169 | .build()) 170 | .setSubject( 171 | SubjectReference.newBuilder() 172 | .setObject( 173 | ObjectReference.newBuilder() 174 | .setObjectType("blog/user") 175 | .setObjectId("emilia") 176 | .build()) 177 | .build()) 178 | .setPermission("read") 179 | .build(); 180 | 181 | // Is Emilia in the set of users that can read post #1? 182 | try { 183 | CheckPermissionResponse response = permissionsService.checkPermission(request); 184 | System.out.println("result: " + response.getPermissionship().getValueDescriptor().getName()); 185 | } catch (Exception e) { 186 | System.out.println("Failed to check permission: " + e.getMessage()); 187 | } 188 | } 189 | } 190 | ``` 191 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "java-library" 3 | id "maven-publish" 4 | id "signing" 5 | 6 | id "io.github.gradle-nexus.publish-plugin" version "2.0.0" 7 | id "com.google.protobuf" version "0.9.5" 8 | } 9 | 10 | repositories { 11 | // The Google mirror is less flaky than mavenCentral() 12 | maven { url "https://maven-central.storage-download.googleapis.com/maven2/" } 13 | mavenCentral() 14 | mavenLocal() 15 | } 16 | 17 | group = "com.authzed.api" 18 | version = findProperty("release") ?: "0.0.0-SNAPSHOT" 19 | 20 | nexusPublishing { repositories { sonatype { 21 | // If registered in Sonatype after 24 Feb 2021, you must explicitly configure these: 22 | nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) 23 | snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) 24 | }}} 25 | 26 | publishing { 27 | publications { authzed(MavenPublication) { 28 | from components.java 29 | pom { 30 | name = "authzed" 31 | description = "Authzed client library for Java" 32 | url = "https://github.com/authzed/authzed-java" 33 | licenses { license { 34 | name = "The Apache License, Version 2.0" 35 | url = "http://www.apache.org/licenses/LICENSE-2.0.txt" 36 | }} 37 | developers { developer { 38 | id = "jzelinskie" 39 | name = "Jimmy Zelinskie" 40 | email = "jimmy@authzed.com" 41 | }} 42 | scm { 43 | connection = "scm:git:git://github.com/authzed/authzed-java.git" 44 | developerConnection = "scm:git:ssh://github.com:authzed/authzed-java.git" 45 | url = "https://github.com/authzed/authzed-java/tree/master" 46 | } 47 | } 48 | }} 49 | 50 | repositories { maven { 51 | def releasesRepoUrl = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/" 52 | def snapshotsRepoUrl = "https://s01.oss.sonatype.org/content/repositories/snapshots/" 53 | def ossrhUsername = findProperty("sonatypeUsername") 54 | def ossrhPassword = findProperty("sonatypePassword") 55 | 56 | name = "authzed" 57 | url = project.hasProperty("release") ? releasesRepoUrl : snapshotsRepoUrl 58 | }} 59 | } 60 | 61 | signing { 62 | def signingKey = findProperty("signingKey") 63 | def signingPassword = findProperty("signingPassword") 64 | useInMemoryPgpKeys(signingKey, signingPassword) 65 | 66 | sign publishing.publications.authzed 67 | } 68 | 69 | 70 | java { 71 | withJavadocJar() 72 | withSourcesJar() 73 | sourceCompatibility = JavaVersion.VERSION_1_8 74 | targetCompatibility = JavaVersion.VERSION_1_8 75 | } 76 | 77 | tasks.sourcesJar { 78 | // This is necessary to keep gradle from barking at you 79 | // about an implicit dependency between these two tasks. 80 | dependsOn tasks.compileJava 81 | } 82 | 83 | // All it does is complain about generated code. 84 | javadoc { options.addStringOption('Xdoclint:none', '-quiet') } 85 | 86 | def grpcVersion = "1.73.0" 87 | def protocVersion = "4.31.1" 88 | def authzedProtoCommit = "v1.41.0" 89 | def bufDir = "${buildDir}/buf" 90 | def protocPlatformTag = project.findProperty('protoc_platform') ? ":${protoc_platform}" : "" 91 | 92 | sourceSets { main { 93 | proto { srcDir bufDir } 94 | java { srcDir "$buildDir/generated" } 95 | java { srcDir "$buildDir/src" } 96 | }} 97 | 98 | dependencies { 99 | implementation("io.grpc:grpc-protobuf:${grpcVersion}") { 100 | exclude group: 'com.google.protobuf', module: 'protobuf-java' 101 | } 102 | api "com.google.protobuf:protobuf-java:${protocVersion}" 103 | implementation "io.grpc:grpc-stub:${grpcVersion}" 104 | runtimeOnly "io.grpc:grpc-netty-shaded:${grpcVersion}" 105 | compileOnly "org.apache.tomcat:annotations-api:6.0.53" 106 | } 107 | 108 | task validateProtos(type: Exec) { 109 | mkdir bufDir 110 | commandLine("buf", "export", "--exclude-imports", "buf.build/envoyproxy/protoc-gen-validate", "-o", bufDir) 111 | } 112 | 113 | task gatewayProtos(type: Exec) { 114 | mkdir bufDir 115 | commandLine("buf", "export", "--exclude-imports", "buf.build/grpc-ecosystem/grpc-gateway", "-o", bufDir) 116 | } 117 | 118 | task authzedProtos(type: Exec) { 119 | dependsOn validateProtos 120 | dependsOn gatewayProtos 121 | commandLine("buf", "export", "--exclude-imports", "buf.build/authzed/api:${authzedProtoCommit}", "-o", bufDir) 122 | } 123 | 124 | protobuf { 125 | protoc { artifact = "com.google.protobuf:protoc:${protocVersion}${protocPlatformTag}" } 126 | plugins { grpc { artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}${protocPlatformTag}" } } 127 | 128 | generateProtoTasks { 129 | ofSourceSet("main").each { task -> task.dependsOn authzedProtos } 130 | all()*.plugins { grpc {} } 131 | } 132 | } 133 | 134 | tasks.named("jar") { manifest { 135 | attributes("Implementation-Title": project.name, 136 | "Implementation-Version": project.version) 137 | }} 138 | 139 | sourceSets { 140 | intTest { 141 | compileClasspath += sourceSets.main.output 142 | runtimeClasspath += sourceSets.main.output 143 | } 144 | } 145 | 146 | configurations { 147 | intTestImplementation.extendsFrom implementation 148 | intTestRuntimeOnly.extendsFrom runtimeOnly 149 | } 150 | 151 | // Test things 152 | dependencies { 153 | intTestImplementation "junit:junit:4.13.2" 154 | intTestImplementation "org.assertj:assertj-core:3.27.3" 155 | } 156 | 157 | tasks.register('integrationTest', Test) { 158 | useJUnit() 159 | 160 | description = 'Runs integration tests.' 161 | group = 'verification' 162 | 163 | testClassesDirs = sourceSets.intTest.output.classesDirs 164 | classpath = sourceSets.intTest.runtimeClasspath 165 | shouldRunAfter test 166 | } 167 | -------------------------------------------------------------------------------- /examples/v1/App.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Authzed API examples 3 | */ 4 | package v1; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | 10 | import com.authzed.api.v1.CheckPermissionRequest; 11 | import com.authzed.api.v1.CheckPermissionResponse; 12 | import com.authzed.api.v1.CheckPermissionResponse.Permissionship; 13 | import com.authzed.api.v1.Consistency; 14 | import com.authzed.api.v1.ObjectReference; 15 | import com.authzed.api.v1.PermissionsServiceGrpc; 16 | import com.authzed.api.v1.ReadSchemaRequest; 17 | import com.authzed.api.v1.ReadSchemaResponse; 18 | import com.authzed.api.v1.Relationship; 19 | import com.authzed.api.v1.RelationshipUpdate; 20 | import com.authzed.api.v1.SchemaServiceGrpc; 21 | import com.authzed.api.v1.SubjectReference; 22 | import com.authzed.api.v1.WriteRelationshipsRequest; 23 | import com.authzed.api.v1.WriteRelationshipsResponse; 24 | import com.authzed.api.v1.WriteSchemaRequest; 25 | import com.authzed.api.v1.WriteSchemaResponse; 26 | import com.authzed.api.v1.ZedToken; 27 | import com.authzed.grpcutil.BearerToken; 28 | import io.grpc.Channel; 29 | import io.grpc.ManagedChannel; 30 | import io.grpc.ManagedChannelBuilder; 31 | 32 | // Installation 33 | // https://search.maven.org/artifact/com.authzed.api/authzed 34 | 35 | public class App { 36 | private static final Logger logger = Logger.getLogger(App.class.getName()); 37 | private static final String target = "grpc.authzed.com:443"; 38 | private static final String token = "tc_test_def_token"; 39 | 40 | private final SchemaServiceGrpc.SchemaServiceBlockingStub schemaService; 41 | private final PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService; 42 | 43 | public App(Channel channel) { 44 | BearerToken bearerToken = new BearerToken(token); 45 | schemaService = SchemaServiceGrpc.newBlockingStub(channel) 46 | .withCallCredentials(bearerToken); 47 | permissionsService = PermissionsServiceGrpc.newBlockingStub(channel) 48 | .withCallCredentials(new BearerToken(token)); 49 | } 50 | 51 | public static void main(String[] args) { 52 | ManagedChannel channel = ManagedChannelBuilder 53 | .forTarget(target) 54 | .useTransportSecurity() // if not using TLS, replace with .usePlaintext() 55 | .build(); 56 | try { 57 | App client = new App(channel); 58 | 59 | client.writeSchema(); 60 | 61 | client.readSchema(); 62 | 63 | String tokenVal = client.writeRelationship(); 64 | 65 | Permissionship result = client.check( 66 | ZedToken.newBuilder() 67 | .setToken(tokenVal) 68 | .build()); 69 | logger.log(Level.INFO, "Check result: {0}", result); 70 | } finally { 71 | try { 72 | channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); 73 | } catch (InterruptedException e) { 74 | // Uh oh! 75 | } 76 | } 77 | } 78 | 79 | public String writeSchema() { 80 | logger.info("Writing schema..."); 81 | String schema = """ 82 | definition thelargeapp/article { 83 | relation author: thelargeapp/user 84 | relation commenter: thelargeapp/user 85 | 86 | permission can_comment = commenter + author 87 | } 88 | 89 | definition thelargeapp/user {} 90 | """; 91 | 92 | WriteSchemaRequest request = WriteSchemaRequest 93 | .newBuilder() 94 | .setSchema(schema) 95 | .build(); 96 | 97 | WriteSchemaResponse response; 98 | try { 99 | response = schemaService.writeSchema(request); 100 | } catch (Exception e) { 101 | logger.log(Level.WARNING, "RPC failed: {0}", e.getMessage()); 102 | return ""; 103 | } 104 | logger.info("Response: " + response.toString()); 105 | return response.toString(); 106 | } 107 | 108 | public String readSchema() { 109 | logger.info("Reading schema..."); 110 | ReadSchemaRequest request = ReadSchemaRequest 111 | .newBuilder() 112 | .build(); 113 | 114 | ReadSchemaResponse response; 115 | try { 116 | response = schemaService.readSchema(request); 117 | } catch (Exception e) { 118 | logger.log(Level.WARNING, "RPC failed: {0}", e.getMessage()); 119 | return ""; 120 | } 121 | logger.info(response.toString()); 122 | return response.toString(); 123 | } 124 | 125 | public String writeRelationship() { 126 | logger.info("Write relationship..."); 127 | 128 | WriteRelationshipsRequest request = WriteRelationshipsRequest.newBuilder() 129 | .addUpdates( 130 | RelationshipUpdate.newBuilder() 131 | .setOperation(RelationshipUpdate.Operation.OPERATION_CREATE) 132 | .setRelationship( 133 | Relationship.newBuilder() 134 | .setResource( 135 | ObjectReference.newBuilder() 136 | .setObjectType("thelargeapp/article") 137 | .setObjectId("java_test") 138 | .build()) 139 | .setRelation("author") 140 | .setSubject( 141 | SubjectReference.newBuilder() 142 | .setObject( 143 | ObjectReference.newBuilder() 144 | .setObjectType("thelargeapp/user") 145 | .setObjectId("george") 146 | .build()) 147 | .build()) 148 | .build()) 149 | .build()) 150 | .build(); 151 | 152 | WriteRelationshipsResponse response; 153 | try { 154 | response = permissionsService.writeRelationships(request); 155 | } catch (Exception e) { 156 | logger.log(Level.WARNING, "RPC failed: {0}", e.getMessage()); 157 | return ""; 158 | } 159 | logger.info("Response: " + response.toString()); 160 | return response.getWrittenAt().getToken(); 161 | } 162 | 163 | public Permissionship check(ZedToken zedToken) { 164 | logger.info("Checking..."); 165 | 166 | CheckPermissionRequest request = CheckPermissionRequest.newBuilder() 167 | .setConsistency( 168 | Consistency.newBuilder() 169 | .setAtLeastAsFresh(zedToken) 170 | .build()) 171 | .setResource( 172 | ObjectReference.newBuilder() 173 | .setObjectType("thelargeapp/article") 174 | .setObjectId("java_test") 175 | .build()) 176 | .setSubject( 177 | SubjectReference.newBuilder() 178 | .setObject( 179 | ObjectReference.newBuilder() 180 | .setObjectType("thelargeapp/user") 181 | .setObjectId("george") 182 | .build()) 183 | .build()) 184 | .setPermission("can_comment") 185 | .build(); 186 | 187 | CheckPermissionResponse response; 188 | try { 189 | response = permissionsService.checkPermission(request); 190 | } catch (Exception e) { 191 | logger.log(Level.WARNING, "RPC failed: {0}", e.getMessage()); 192 | return null; 193 | } 194 | logger.info("Response: " + response.toString()); 195 | return response.getPermissionship(); 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/authzed/authzed-java/7fb204394df2f7c4e31b5f3529cff57052b243e7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-rc-1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH="\\\"\\\"" 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = "authzed" 2 | -------------------------------------------------------------------------------- /src/intTest/java/TestClient.java: -------------------------------------------------------------------------------- 1 | import com.authzed.api.v1.ExperimentalServiceGrpc; 2 | import com.authzed.api.v1.PermissionsServiceGrpc; 3 | import com.authzed.api.v1.SchemaServiceGrpc; 4 | import com.authzed.grpcutil.BearerToken; 5 | import io.grpc.ManagedChannel; 6 | import io.grpc.ManagedChannelBuilder; 7 | 8 | import java.util.Random; 9 | 10 | public class TestClient { 11 | private static final String tokenPrefix = "tc_test_token"; 12 | 13 | public SchemaServiceGrpc.SchemaServiceBlockingStub schemaService; 14 | public PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService; 15 | public PermissionsServiceGrpc.PermissionsServiceStub asyncPermissionsService; 16 | public ExperimentalServiceGrpc.ExperimentalServiceBlockingStub experimentalService; 17 | public TestClient() { 18 | ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:50051").usePlaintext().build(); 19 | String token = generateToken(); 20 | schemaService = SchemaServiceGrpc.newBlockingStub(channel) 21 | .withCallCredentials(new BearerToken(token)); 22 | permissionsService = PermissionsServiceGrpc.newBlockingStub(channel) 23 | .withCallCredentials(new BearerToken(token)); 24 | asyncPermissionsService = PermissionsServiceGrpc.newStub(channel) 25 | .withCallCredentials(new BearerToken(token)); 26 | experimentalService = ExperimentalServiceGrpc.newBlockingStub(channel) 27 | .withCallCredentials(new BearerToken(token)); 28 | } 29 | public String generateToken() { 30 | Random random = new Random(); 31 | return tokenPrefix + random.nextInt(1000); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/intTest/java/V1ClientTest.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Iterator; 3 | import java.util.concurrent.CountDownLatch; 4 | 5 | import com.google.protobuf.Struct; 6 | import com.google.protobuf.Value; 7 | 8 | import com.authzed.api.v1.*; 9 | 10 | import io.grpc.stub.StreamObserver; 11 | import org.junit.Test; 12 | 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | 15 | /* 16 | NOTE: this file has some un-ergonomic code because we test against Java 8 17 | and therefore need to conform to Java 8 syntax. When we get to where we can 18 | drop support, we can update this code. 19 | */ 20 | public class V1ClientTest { 21 | private static final Consistency fullyConsistent = Consistency.newBuilder().setFullyConsistent(true).build(); 22 | 23 | @Test 24 | public void testBasicSchema() { 25 | // Initialize services 26 | TestClient client = new TestClient(); 27 | String schema = "definition document {\n" 28 | + "relation reader: user\n" 29 | + "}\n" 30 | + "definition user {}"; 31 | // Write schema 32 | writeSchema(client, schema); 33 | 34 | // Read schema 35 | ReadSchemaRequest readRequest = ReadSchemaRequest.newBuilder().build(); 36 | ReadSchemaResponse readResponse = client.schemaService.readSchema(readRequest); 37 | assertThat(readResponse.getSchemaText()).contains("definition document"); 38 | assertThat(readResponse.getSchemaText()).contains("definition user"); 39 | } 40 | 41 | @Test 42 | public void testSchemaWithCaveats() { 43 | TestClient client = new TestClient(); 44 | writeTestSchema(client); 45 | } 46 | 47 | // For an example with flow control, see 48 | // https://github.com/grpc/grpc-java/blob/9071c1ad7c842f4e73b6ae95b71f11c517b177a4/examples/src/main/java/io/grpc/examples/manualflowcontrol/ManualFlowControlClient.java 49 | @Test 50 | public void testCheck() { 51 | TestClient client = new TestClient(); 52 | writeTestSchema(client); 53 | TestTuples testTuples = writeTestTuples(client); 54 | 55 | CheckPermissionResponse firstResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 56 | .setConsistency(fullyConsistent) 57 | .setResource(testTuples.postOne) 58 | .setSubject(testTuples.emilia) 59 | .setPermission("view") 60 | .build()); 61 | assertThat(firstResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_HAS_PERMISSION); 62 | 63 | CheckPermissionResponse secondResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 64 | .setConsistency(fullyConsistent) 65 | .setResource(testTuples.postOne) 66 | .setSubject(testTuples.emilia) 67 | .setPermission("write") 68 | .build()); 69 | assertThat(secondResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_HAS_PERMISSION); 70 | 71 | CheckPermissionResponse thirdResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 72 | .setConsistency(fullyConsistent) 73 | .setResource(testTuples.postOne) 74 | .setSubject(testTuples.beatrice) 75 | .setPermission("view") 76 | .build()); 77 | assertThat(thirdResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_HAS_PERMISSION); 78 | 79 | CheckPermissionResponse fourthResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 80 | .setConsistency(fullyConsistent) 81 | .setResource(testTuples.postOne) 82 | .setSubject(testTuples.beatrice) 83 | .setPermission("write") 84 | .build()); 85 | assertThat(fourthResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_NO_PERMISSION); 86 | } 87 | 88 | @Test 89 | public void testCaveatedCheck() { 90 | TestClient client = new TestClient(); 91 | writeTestSchema(client); 92 | TestTuples testTuples = writeTestTuples(client); 93 | 94 | // Likes Harry Potter 95 | Struct likesContext = Struct.newBuilder().putFields("likes", Value.newBuilder().setBoolValue(true).build()).build(); 96 | CheckPermissionResponse firstResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 97 | .setConsistency(fullyConsistent) 98 | .setResource(testTuples.postOne) 99 | .setSubject(testTuples.beatrice) 100 | .setPermission("view_as_fan") 101 | .setContext(likesContext) 102 | .build()); 103 | assertThat(firstResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_HAS_PERMISSION); 104 | 105 | // No longer likes Harry Potter 106 | Struct dislikesContext = Struct.newBuilder().putFields("likes", Value.newBuilder().setBoolValue(false).build()).build(); 107 | CheckPermissionResponse secondResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 108 | .setConsistency(fullyConsistent) 109 | .setResource(testTuples.postOne) 110 | .setSubject(testTuples.beatrice) 111 | .setPermission("view_as_fan") 112 | .setContext(dislikesContext) 113 | .build()); 114 | assertThat(secondResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_NO_PERMISSION); 115 | 116 | // No longer likes Harry Potter 117 | CheckPermissionResponse thirdResponse = client.permissionsService.checkPermission(CheckPermissionRequest.newBuilder() 118 | .setConsistency(fullyConsistent) 119 | .setResource(testTuples.postOne) 120 | .setSubject(testTuples.beatrice) 121 | .setPermission("view_as_fan") 122 | .build()); 123 | assertThat(thirdResponse.getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_CONDITIONAL_PERMISSION); 124 | assertThat(thirdResponse.getPartialCaveatInfo().getMissingRequiredContextList()).contains("likes"); 125 | } 126 | 127 | @Test 128 | public void testLookupResources() { 129 | TestClient client = new TestClient(); 130 | writeTestSchema(client); 131 | TestTuples testTuples = writeTestTuples(client); 132 | 133 | LookupResourcesRequest lookupResourcesRequest = LookupResourcesRequest.newBuilder() 134 | .setConsistency(fullyConsistent) 135 | .setResourceObjectType("post") 136 | .setSubject(testTuples.emilia) 137 | .setPermission("write") 138 | .build(); 139 | 140 | Iterator resp = client.permissionsService.lookupResources(lookupResourcesRequest); 141 | HashSet resources = new HashSet(); 142 | resp.forEachRemaining(lookupResourcesResponse -> resources.add(lookupResourcesResponse.getResourceObjectId())); 143 | 144 | assertThat(resources).contains(testTuples.postOne.getObjectId()); 145 | assertThat(resources).contains(testTuples.postTwo.getObjectId()); 146 | assertThat(resources).hasSize(2); 147 | } 148 | 149 | @Test 150 | public void testLookupSubjects() { 151 | TestClient client = new TestClient(); 152 | writeTestSchema(client); 153 | TestTuples testTuples = writeTestTuples(client); 154 | 155 | LookupSubjectsRequest lookupSubjectsRequest = LookupSubjectsRequest.newBuilder() 156 | .setConsistency(fullyConsistent) 157 | .setSubjectObjectType("user") 158 | .setResource(testTuples.postOne) 159 | .setPermission("view") 160 | .build(); 161 | 162 | Iterator resp = client.permissionsService.lookupSubjects(lookupSubjectsRequest); 163 | HashSet users = new HashSet(); 164 | resp.forEachRemaining(response -> 165 | users.add(response.getSubject().getSubjectObjectId())); 166 | 167 | assertThat(users).contains(testTuples.emilia.getObject().getObjectId()); 168 | assertThat(users).contains(testTuples.beatrice.getObject().getObjectId()); 169 | assertThat(users).hasSize(2); 170 | } 171 | 172 | @Test 173 | public void testCheckBulkPermissions() { 174 | TestClient client = new TestClient(); 175 | writeTestSchema(client); 176 | TestTuples testTuples = writeTestTuples(client); 177 | 178 | CheckBulkPermissionsRequest checkBulkPermissionsRequest = CheckBulkPermissionsRequest.newBuilder() 179 | .setConsistency(fullyConsistent) 180 | .addItems(CheckBulkPermissionsRequestItem.newBuilder() 181 | .setResource(testTuples.postOne) 182 | .setPermission("view") 183 | .setSubject(testTuples.emilia)) 184 | .addItems(CheckBulkPermissionsRequestItem.newBuilder() 185 | .setResource(testTuples.postOne) 186 | .setPermission("write") 187 | .setSubject(testTuples.emilia)) 188 | .build(); 189 | 190 | CheckBulkPermissionsResponse response = client.permissionsService.checkBulkPermissions(checkBulkPermissionsRequest); 191 | assertThat(response.getPairsList()).hasSize(2); 192 | assertThat(response.getPairs(0).getItem().getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_HAS_PERMISSION); 193 | assertThat(response.getPairs(1).getItem().getPermissionship()).isEqualTo(CheckPermissionResponse.Permissionship.PERMISSIONSHIP_HAS_PERMISSION); 194 | } 195 | 196 | @Test 197 | public void testBulkImport() throws InterruptedException { 198 | TestClient client = new TestClient(); 199 | writeTestSchema(client); 200 | writeTestTuples(client); 201 | 202 | // Validate export 203 | Iterator exportCall = client.permissionsService.exportBulkRelationships(ExportBulkRelationshipsRequest.newBuilder() 204 | .setConsistency(fullyConsistent) 205 | .build()); 206 | 207 | HashSet relations = new HashSet(); 208 | exportCall.forEachRemaining(response -> 209 | relations.addAll(response.getRelationshipsList())); 210 | 211 | assertThat(relations).hasSize(4); 212 | 213 | // Note that this has a different preshared key 214 | // Validate import 215 | TestClient emptyClient = new TestClient(); 216 | writeTestSchema(emptyClient); 217 | 218 | final CountDownLatch done = new CountDownLatch(1); 219 | 220 | class ImportBulkObserver implements StreamObserver { 221 | private long loaded; 222 | 223 | @Override 224 | public void onNext(ImportBulkRelationshipsResponse resp) { 225 | loaded += resp.getNumLoaded(); 226 | } 227 | 228 | @Override 229 | public void onError(Throwable throwable) { 230 | // TODO need to capture error so that blocking callsite is able to access it 231 | System.out.println("onError"); 232 | done.countDown(); 233 | } 234 | 235 | @Override 236 | public void onCompleted() { 237 | System.out.println("onCompleted"); 238 | done.countDown(); 239 | } 240 | } 241 | 242 | // Do the import 243 | ImportBulkObserver importObserver = new ImportBulkObserver(); 244 | StreamObserver wrappedObserver = client.asyncPermissionsService.importBulkRelationships(importObserver); 245 | wrappedObserver.onNext(ImportBulkRelationshipsRequest.newBuilder() 246 | .addAllRelationships(relations).build()); 247 | wrappedObserver.onCompleted(); 248 | 249 | done.await(); 250 | 251 | // Validate that everything was loaded 252 | Iterator postImportExportCall = client.permissionsService.exportBulkRelationships(ExportBulkRelationshipsRequest.newBuilder() 253 | .setConsistency(fullyConsistent) 254 | .build()); 255 | 256 | HashSet importedRelations = new HashSet(); 257 | postImportExportCall.forEachRemaining(response -> 258 | importedRelations.addAll(response.getRelationshipsList())); 259 | 260 | assertThat(importedRelations).hasSize(4); 261 | } 262 | 263 | 264 | 265 | 266 | private TestTuples writeTestTuples(TestClient client) { 267 | SubjectReference emilia = SubjectReference.newBuilder().setObject(ObjectReference.newBuilder().setObjectId("emilia").setObjectType("user").build()).build(); 268 | SubjectReference beatrice = SubjectReference.newBuilder().setObject(ObjectReference.newBuilder().setObjectId("beatrice").setObjectType("user").build()).build(); 269 | ObjectReference postOne = ObjectReference.newBuilder().setObjectId("post-one").setObjectType("post").build(); 270 | ObjectReference postTwo = ObjectReference.newBuilder().setObjectId("post-two").setObjectType("post").build(); 271 | WriteRelationshipsRequest.Builder builder = WriteRelationshipsRequest.newBuilder() 272 | .addUpdates( 273 | RelationshipUpdate.newBuilder() 274 | .setOperation(RelationshipUpdate.Operation.OPERATION_CREATE) 275 | .setRelationship(Relationship.newBuilder() 276 | .setRelation("writer") 277 | .setResource(postOne) 278 | .setSubject(emilia) 279 | )) 280 | .addUpdates( 281 | RelationshipUpdate.newBuilder() 282 | .setOperation(RelationshipUpdate.Operation.OPERATION_CREATE) 283 | .setRelationship(Relationship.newBuilder() 284 | .setRelation("writer") 285 | .setResource(postTwo) 286 | .setSubject(emilia) 287 | )) 288 | .addUpdates( 289 | RelationshipUpdate.newBuilder() 290 | .setOperation(RelationshipUpdate.Operation.OPERATION_CREATE) 291 | .setRelationship(Relationship.newBuilder() 292 | .setRelation("reader") 293 | .setResource(postOne) 294 | .setSubject(beatrice) 295 | ) 296 | ) 297 | .addUpdates( 298 | RelationshipUpdate.newBuilder() 299 | .setOperation(RelationshipUpdate.Operation.OPERATION_CREATE) 300 | .setRelationship(Relationship.newBuilder() 301 | .setRelation("caveated_reader") 302 | .setResource(postOne) 303 | .setSubject(beatrice) 304 | .setOptionalCaveat(ContextualizedCaveat.newBuilder() 305 | .setCaveatName("likes_harry_potter")) 306 | ) 307 | ); 308 | client.permissionsService.writeRelationships(builder.build()); 309 | return new TestTuples(emilia, beatrice, postOne, postTwo); 310 | } 311 | 312 | private void writeTestSchema(TestClient client) { 313 | String schema = "caveat likes_harry_potter(likes bool) {\n" 314 | + "likes == true\n" 315 | + "}\n" 316 | + "definition post {\n" 317 | + "relation writer: user\n" 318 | + "relation reader: user\n" 319 | + "relation caveated_reader: user with likes_harry_potter\n" 320 | + "permission write = writer\n" 321 | + "permission view = reader + writer\n" 322 | + "permission view_as_fan = caveated_reader + writer\n" 323 | + "}\n" 324 | + "definition user {}"; 325 | writeSchema(client, schema); 326 | } 327 | 328 | private void writeSchema(TestClient client, String schema) { 329 | WriteSchemaRequest writeRequest = WriteSchemaRequest 330 | .newBuilder() 331 | .setSchema(schema) 332 | .build(); 333 | client.schemaService.writeSchema(writeRequest); 334 | } 335 | } 336 | 337 | class TestTuples { 338 | public SubjectReference emilia; 339 | public SubjectReference beatrice; 340 | public ObjectReference postOne; 341 | public ObjectReference postTwo; 342 | 343 | public TestTuples(SubjectReference one, SubjectReference two, ObjectReference three, ObjectReference four) { 344 | emilia = one; 345 | beatrice = two; 346 | postOne = three; 347 | postTwo = four; 348 | } 349 | } 350 | -------------------------------------------------------------------------------- /src/main/java/com/authzed/grpcutil/BearerToken.java: -------------------------------------------------------------------------------- 1 | package com.authzed.grpcutil; 2 | 3 | import io.grpc.*; 4 | 5 | import java.util.concurrent.Executor; 6 | 7 | /** 8 | * Bearer token implementation that can be used with GRPC stubs. 9 | */ 10 | public class BearerToken extends CallCredentials { 11 | public static final String AUTHORIZATION = "authorization"; 12 | private static final Metadata.Key META_DATA_KEY = 13 | Metadata.Key.of(AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER); 14 | 15 | private final String token; 16 | private final String header; 17 | 18 | public BearerToken(String value) { 19 | this.token = value; 20 | this.header = "Bearer " + token; 21 | } 22 | 23 | @Override 24 | public void applyRequestMetadata(RequestInfo requestInfo, Executor executor, MetadataApplier applier) { 25 | executor.execute(() -> { 26 | try { 27 | Metadata headers = new Metadata(); 28 | headers.put(META_DATA_KEY, header); 29 | applier.apply(headers); 30 | } catch (Throwable e) { 31 | applier.fail(Status.UNAUTHENTICATED.withCause(e)); 32 | } 33 | }); 34 | } 35 | } 36 | --------------------------------------------------------------------------------