├── .github ├── CODEOWNERS ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── github_release.yml │ ├── main.yml │ └── maven_release.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── graphql-authorization-java.png ├── lombok.config ├── pom.xml └── src ├── main └── java │ └── com │ └── intuit │ └── graphql │ └── authorization │ ├── config │ ├── AuthzClient.java │ └── AuthzClientConfiguration.java │ ├── enforcement │ ├── AuthorizationHolder.java │ ├── AuthzInstrumentation.java │ ├── AuthzListener.java │ ├── IntrospectionRedactingDataFetcher.java │ ├── PermissionVerifier.java │ ├── RedactingVisitor.java │ ├── RedactionContext.java │ ├── SimpleAuthZListener.java │ └── TypeFieldPermissionVerifier.java │ ├── extension │ ├── AuthorizationExtension.java │ ├── AuthorizationExtensionProvider.java │ ├── DefaultAuthorizationExtension.java │ ├── DefaultAuthorizationExtensionProvider.java │ ├── FieldAuthorizationEnvironment.java │ └── FieldAuthorizationResult.java │ ├── rules │ ├── AuthorizationHolderFactory.java │ ├── InvalidFieldsCollector.java │ ├── QueryRuleParser.java │ ├── RuleParser.java │ └── RuleParserListener.java │ └── util │ ├── FieldCoordinatesFormattingUtil.java │ ├── GraphQLUtil.java │ └── ScopeProvider.java └── test ├── groovy └── com │ └── intuit │ └── graphql │ └── authorization │ └── enforcement │ └── AuthorizationSpec.groovy ├── java └── com │ └── intuit │ └── graphql │ └── authorization │ ├── context │ └── ExecutionScopeFetcherTest.java │ ├── enforcement │ ├── AuthZListenerTest.java │ ├── HelperAuthzClientConfiguration.java │ ├── HelperBuildTestSchema.java │ ├── HelperGraphQLDataFetchers.java │ ├── HelperScopeProvider.java │ ├── HelperUtils.java │ ├── IntrospectionRedactingDataFetcherTest.java │ ├── RedactingVisitorTest.java │ ├── TypeAndFieldAuthorizationHolderTest.java │ └── TypeFieldPermissionVerifierTest.java │ ├── rules │ ├── AuthorizationHolderFactoryTest.java │ ├── InvalidFieldsCollectorTest.java │ └── QueryRuleParserTest.java │ └── util │ ├── FieldCoordinatesFormattingUtilTest.java │ ├── GraphQLUtilTest.java │ └── TestStaticResources.java └── resources ├── mocks.graphqlauthz └── client │ ├── client1-permissions-mutation.graphql │ ├── client1-permissions.graphql │ ├── client1.yml │ ├── client2-permissions-mutation.graphql │ ├── client2-permissions-query.graphql │ ├── client2.yml │ ├── client3-permissions-query.graphql │ ├── client3.yml │ ├── client4-permissions-mutation1.graphql │ ├── client4-permissions-mutation2.graphql │ ├── client4-permissions-query.graphql │ ├── client4.yml │ ├── client5-pa.yml │ ├── client5-permissions-mutation1.graphql │ ├── client5-permissions-mutation2.graphql │ ├── client5-permissions-query.graphql │ ├── client6-permissions-query.graphql │ └── client6.yml ├── queries ├── mutationQuery.graphql ├── mutationQueryWithFragments.graphql ├── requestAllBooks.graphql ├── requestAllFields.graphql ├── requestAllFieldsWithIntrospection.graphql ├── requestWithAllowedFields.graphql ├── requestWithFragments.graphql ├── requestWithInvalidFields.graphql └── requestWithInvalidFragment.graphql ├── test_rule_query.graphql └── testschema.graphqls /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | @ashpak-shaikh 2 | @CNAChino 3 | @scanbns 4 | @hplewis 5 | @lt-schmidt-jr 6 | @akulkarni01 7 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | * Please create a bug report or feature request on the issue section. 4 | * Discuss your issue and get the high level design approved from one of the code owners. 5 | * Please read the [Code of Conduct](/CODE_OF_CONDUCT.md) before contributing to this project. 6 | * Please link your issues to corresponding Pull Requests, especially for larger changes. 7 | * All code changes should have a new/edited test! 8 | 9 | ## Formatting 10 | Please import and use either the provided [Eclipse Java style guide](./documents/style-guide-eclipse.xml) or 11 | the [IntelliJ Java style guide](./documents/style-guide-intellij.xml) into your project. 12 | 13 | * (IntelliJ) Preferences -> Code Style -> Click gear -> Import 14 | * (Eclipse) Preferences -> Java -> Code Style -> Formatter -> Import -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | --- 8 | 9 | **Describe the bug** 10 | 11 | 12 | 13 | **To Reproduce** 14 | 15 | 16 | 17 | **Expected behavior** 18 | 19 | 20 | 21 | **Additional context** 22 | 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | 12 | 13 | 14 | **Describe the solution you'd like** 15 | 16 | 17 | 18 | **Describe alternatives you've considered** 19 | 20 | 21 | 22 | **Additional context** 23 | 24 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # What Changed 2 | 3 | # Why 4 | 5 | Todo: 6 | 7 | - [ ] Add tests 8 | - [ ] Add docs -------------------------------------------------------------------------------- /.github/workflows/github_release.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | # Sequence of patterns matched against refs/tags 4 | tags: 5 | - 'v[0-9]+.[0-9]+.[0-9]+' # Push events to matching v*, i.e. v1.0, v20.15.10 6 | 7 | name: Create Github Release 8 | 9 | jobs: 10 | build: 11 | name: Create Release 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v3 16 | 17 | - name: "✏️ Generate full changelog" 18 | id: generate-changelog 19 | uses: heinrichreimer/github-changelog-generator-action@v2.3 20 | with: 21 | token: ${{ secrets.GITHUB_TOKEN }} 22 | headerLabel: "# 📑 Changelog" 23 | 24 | breakingLabel: '### 💥 Breaking' 25 | breakingLabels: breaking 26 | 27 | enhancementLabel: '### 🚀 Enhancements' 28 | enhancementLabels: enhancement 29 | 30 | bugsLabel: '### 🐛 Bug fixes' 31 | bugLabels: bug 32 | 33 | securityLabel: '### 🛡️ Security' 34 | securityLabels: security 35 | 36 | issuesLabel: '### 📁 Other issues' 37 | prLabel: '### 📁 Other pull requests' 38 | issues: true 39 | issuesWoLabels: true 40 | pullRequests: true 41 | prWoLabels: true 42 | author: true 43 | unreleased: true 44 | compareLink: true 45 | stripGeneratorNotice: true 46 | verbose: true 47 | onlyLastTag: true 48 | stripHeaders: true 49 | 50 | - name: Print changelog 51 | run: | 52 | echo ${{ steps.generate-changelog.outputs.changelog }} 53 | 54 | - name: Calculate release version 55 | id: calculate_version 56 | run: | 57 | VERSION=${GITHUB_REF_NAME#v} 58 | echo Version: $VERSION 59 | echo "version=$VERSION" >> $GITHUB_OUTPUT 60 | 61 | # - name: Auto Dry run 62 | # uses: auto-it/setup-auto@v1 63 | # 64 | # - name: Auto Release 65 | # run: auto release -d 66 | 67 | - name: Create Release 68 | id: create_release 69 | uses: actions/create-release@v1 70 | env: 71 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token 72 | with: 73 | tag_name: ${{ github.ref }} 74 | release_name: ${{ github.ref }} 75 | body: | 76 | ### Usage in pom.xml file 77 | ``` 78 | 79 | com.intuit.graphql 80 | graphql-authorization-java 81 | ${{ steps.calculate_version.outputs.version }} 82 | 83 | 84 | ${{ steps.generate-changelog.outputs.changelog }} 85 | ``` 86 | draft: false 87 | prerelease: false -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a package using Maven and then publish it to GitHub packages when a release is created 2 | # For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path 3 | 4 | name: GraphQL Authorization Java Maven Action 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | permissions: 16 | contents: read 17 | packages: write 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: Set up JDK 11 22 | uses: actions/setup-java@v3 23 | with: 24 | java-version: '11' 25 | distribution: 'corretto' 26 | server-id: ossrh 27 | server-username: MAVEN_USERNAME 28 | server-password: MAVEN_PASSWORD 29 | 30 | - name: Build with Maven 31 | if: ${{ github.ref != 'refs/heads/master' }} 32 | run: mvn -B package --file pom.xml 33 | 34 | - name: Publish Snapshot to OSS Maven Repository 35 | if: ${{ github.ref == 'refs/heads/master' }} 36 | run: mvn -B install --file pom.xml 37 | env: 38 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 39 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 40 | -------------------------------------------------------------------------------- /.github/workflows/maven_release.yml: -------------------------------------------------------------------------------- 1 | name: release-to-maven-central 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | releaseversion: 6 | description: 'Release version' 7 | required: false 8 | default: '2.4.0' 9 | jobs: 10 | publish: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - run: echo "Will release to central maven" 14 | 15 | - uses: actions/checkout@v2 16 | 17 | - name: Set up Maven Central Repository 18 | uses: actions/setup-java@v3 19 | with: 20 | java-version: 11 21 | distribution: corretto 22 | server-id: ossrh 23 | server-username: MAVEN_USERNAME 24 | server-password: MAVEN_PASSWORD 25 | gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} 26 | gpg-passphrase: MAVEN_GPG_PASSPHRASE 27 | 28 | - name: Configure Git User 29 | run: | 30 | git config user.email "actions@github.com" 31 | git config user.name "GitHub Actions" 32 | 33 | # - name: Set projects Maven version to GitHub Action GUI set version 34 | # run: mvn versions:set "-DnewVersion=${{ github.event.inputs.releaseversion }}" 35 | 36 | - name: Publish package 37 | run: mvn --batch-mode release:prepare release:perform -P release -DskipTests=true 38 | env: 39 | MAVEN_USERNAME: ${{ secrets.OSS_SONATYPE_USERNAME }} 40 | MAVEN_PASSWORD: ${{ secrets.OSS_SONATYPE_PASSWORD }} 41 | MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | /target/ 26 | /test-output/ 27 | /screenshots/ 28 | interview-service-tests/responses 29 | .idea 30 | *.iml 31 | .classpath 32 | .project 33 | .DS_Store 34 | .settings/ 35 | logs/ 36 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | ### Added 9 | - Initial release. 10 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | Open source projects are “living.” Contributions in the form of issues and pull requests are welcomed and encouraged. When you contribute, you explicitly say you are part of the community and abide by its Code of Conduct. 2 | 3 | # The Code 4 | 5 | At Intuit, we foster a kind, respectful, harassment-free cooperative community. Our open source community works to: 6 | 7 | - Be kind and respectful; 8 | - Act as a global community; 9 | - Conduct ourselves professionally. 10 | 11 | As members of this community, we will not tolerate behaviors including, but not limited to: 12 | 13 | - Violent threats or language; 14 | - Discriminatory or derogatory jokes or language; 15 | - Public or private harassment of any kind; 16 | - Other conduct considered inappropriate in a professional setting. 17 | 18 | ## Reporting Concerns 19 | 20 | If you see someone violating the Code of Conduct please email TechOpenSource@intuit.com 21 | 22 | ## Scope 23 | 24 | This code of conduct applies to: 25 | 26 | All repos and communities for Intuit-managed projects, whether or not the text is included in a Intuit-managed project’s repository; 27 | 28 | Individuals or teams representing projects in official capacity, such as via official social media channels or at in-person meetups. 29 | 30 | ## Attribution 31 | 32 | This Code of Conduct is partly inspired by and based on those of Amazon, CocoaPods, GitHub, Microsoft, thoughtbot, and on the Contributor Covenant version 1.4.1. -------------------------------------------------------------------------------- /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 |
2 | 3 | ![graphql-authorization-java](./graphql-authorization-java.png) 4 | 5 |
6 | 7 |
A powerful library for securing a GraphQL service using attribute level access control.
8 | 9 | ----- 10 | 11 | ![Master Build](https://github.com/graph-quilt/graphql-authorization-java/actions/workflows/main.yml/badge.svg) 12 | 13 | 14 | ## Introduction 15 | 16 | This library enforces access control on GraphQL queries by checking for allowed types and fields. A GraphQL query that 17 | has access to some of the requested fields/types will return: 18 | * Requested fields it has access to 19 | * Authorization Error message for the fields it does not have access to. You can customize the error message by over-riding the 20 | `getErrorMessage` method in the `ScopeProvider` interface. 21 | 22 | ```json lines 23 | "errors": [ 24 | { 25 | "message": "403 - Not authorized to access field=accountId of type=AccountType", 26 | ... 27 | }, 28 | ``` 29 | 30 | ## Getting Started 31 | 32 | #### Maven coordinates: 33 | 34 | ```xml 35 | 36 | com.intuit.graphql 37 | graphql-authorization-java 38 | ${latest.version} 39 | 40 | ``` 41 | 42 | ### Usage 43 | 44 | * Implement the AuthzClientConfiguration interface and provide the configuration for initialization. The configuration contains 45 | mappings of scopes represented by `id` to the `list of Queries` allowed by that `id`. The id can also represent clientids, 46 | userids, scopes or roles. 47 | 48 | * Add the AuthzInstrumentation defined in the library as an instrumentation when you create your GraphQL Instance. More on 49 | [graphql-java instrumentation](https://www.graphql-java.com/documentation/instrumentation/) 50 | 51 | If dgs framework is used, add the AuthzInstrumentation as a bean in the configuration class. 52 | 53 | * The library provides a default implementation of the ScopeProvider interface. The default implementation uses the request-context 54 | to fetch the list of scopes associated with the request. The default implementation can be over-ridden by providing a custom 55 | implementation of the ScopeProvider interface. 56 | * Get scopes should be customized by overriding the `getScopes` method in the ScopeProvider interface. 57 | * Request-context information would be available at execution time. Request-context would have headers and that could be used 58 | to fetch the list of scopes associated with the request. 59 | * Error Message could be customized by overriding the `getErrorMessage` method in the ScopeProvider interface. 60 | 61 | * AuthZlistener is an optional interface that can be implemented to listen to the authorization events. The listener can be used 62 | to log the authorization events or to send the events to a monitoring system. The listener can be added to the instrumentation 63 | by providing an implementation of the AuthzListener interface. 64 | 65 | * AuthorizationExtensionProvider is an optional interface that can be implemented to provide custom authorization extensions. 66 | The extensions can be used to add custom authorization logic. The extensions can be added to the instrumentation by providing 67 | an implementation of the AuthorizationExtensionProvider interface. 68 | 69 | ```java 70 | GraphQL.newGraphQL(schema) 71 | .instrumentation(new AuthzInstrumentation(authzClientConfiguration, schema, scopeProvider,authzListener, authorizationExtensionProvider)) 72 | .build(); 73 | ``` 74 | ### Example Implementation 75 | 76 | Please refer to the [example service](https://github.com/graph-quilt/example-subgraphs/tree/main/name-service) where this library was used to 77 | implement user permissions with userids. 78 | 79 | ### Contributing 80 | 81 | Read the [Contribution guide](./.github/CONTRIBUTING.md) 82 | -------------------------------------------------------------------------------- /graphql-authorization-java.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/graph-quilt/graphql-authorization-java/dedf92c3b0d69aec16fb9404272edbda96848e78/graphql-authorization-java.png -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | config.stopBubbling = true 2 | lombok.addLombokGeneratedAnnotation = true 3 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | com.intuit.graphql 6 | graphql-authorization-java 7 | 2.0.17-SNAPSHOT 8 | jar 9 | 10 | graphql-authorization-java 11 | GraphQL Authorization provides attributes based access control(ABAC) defined using GraphQL queries 12 | 13 | https://github.com/intuit/graphql-authorization-java 14 | 15 | 16 | 17 | Apache 2.0 18 | https://www.apache.org/licenses/LICENSE-2.0.txt 19 | 20 | 21 | 22 | 23 | 24 | Ashpak Shaikh 25 | Shaikh 26 | Intuit, Inc. 27 | https://www.intuit.com 28 | 29 | 30 | 31 | 32 | scm:git:https://github.com/intuit/graphql-authorization-java 33 | https://github.com/intuit/graphql-authorization-java 34 | HEAD 35 | 36 | 37 | 38 | 5.5.0 39 | 1.18.30 40 | 20.4 41 | true 42 | 0.8.4 43 | 3.0.1 44 | 2.13.5 45 | 1.3-groovy-2.5 46 | 2.5.14 47 | 48 | 49 | 50 | 51 | release 52 | 53 | 54 | 55 | org.apache.maven.plugins 56 | maven-release-plugin 57 | 3.0.0-M7 58 | 59 | v@{project.version} 60 | 61 | 62 | 63 | maven-gpg-plugin 64 | ${maven-gpg-plugin.version} 65 | 66 | 67 | sign-artifacts 68 | verify 69 | 70 | sign 71 | 72 | 73 | 74 | 75 | --pinentry-mode 76 | loopback 77 | 78 | 79 | 80 | 81 | 82 | 83 | org.apache.maven.plugins 84 | maven-deploy-plugin 85 | 86 | true 87 | 88 | 89 | 90 | org.sonatype.plugins 91 | nexus-staging-maven-plugin 92 | 1.6.13 93 | 94 | 95 | default-deploy 96 | deploy 97 | 98 | deploy 99 | 100 | 101 | 102 | 103 | ossrh 104 | https://oss.sonatype.org 105 | true 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | org.apache.maven.plugins 117 | maven-compiler-plugin 118 | 3.8.1 119 | 120 | 11 121 | 11 122 | 123 | 124 | 125 | org.apache.maven.plugins 126 | maven-source-plugin 127 | 3.2.0 128 | 129 | 130 | attach-sources 131 | verify 132 | 133 | jar-no-fork 134 | 135 | 136 | 137 | 138 | 139 | org.apache.maven.plugins 140 | maven-javadoc-plugin 141 | 3.3.1 142 | 143 | 144 | attach-javadocs 145 | 146 | jar 147 | 148 | 149 | 150 | 151 | 152 | org.jacoco 153 | jacoco-maven-plugin 154 | ${jacoco.version} 155 | 156 |
2018 Intuit, Inc. Generated ${maven.build.timestamp}
157 | 158 | **/Immutable*.* 159 | 160 |
161 | 162 | 163 | default-prepare-agent 164 | 165 | prepare-agent 166 | 167 | 168 | 169 | default-report 170 | prepare-package 171 | 172 | report 173 | 174 | 175 | 176 | default-check 177 | 178 | check 179 | 180 | 181 | 182 | 183 | 184 | 185 |
186 | 187 | org.apache.maven.plugins 188 | maven-surefire-plugin 189 | 2.22.0 190 | 191 | 192 | ${project.build.directory}/coverage.exec 193 | 194 | 195 | **/*Test.class 196 | **/*Spec.class 197 | 198 | 199 | 200 | 201 | org.codehaus.gmavenplus 202 | gmavenplus-plugin 203 | 1.12.1 204 | 205 | 206 | 207 | compile 208 | compileTests 209 | 210 | 211 | 212 | 213 |
214 |
215 | 216 | 217 | com.graphql-java 218 | graphql-java 219 | ${graphql-java.version} 220 | provided 221 | 222 | 223 | org.apache.commons 224 | commons-collections4 225 | 4.3 226 | 227 | 228 | org.apache.commons 229 | commons-lang3 230 | 3.12.0 231 | 232 | 233 | com.google.guava 234 | guava 235 | 32.0.0-jre 236 | test 237 | 238 | 239 | org.projectlombok 240 | lombok 241 | ${lombok.version} 242 | provided 243 | 244 | 245 | com.fasterxml.jackson.dataformat 246 | jackson-dataformat-yaml 247 | ${jackson.version} 248 | test 249 | 250 | 251 | com.fasterxml.jackson.datatype 252 | jackson-datatype-jsr310 253 | ${jackson.version} 254 | test 255 | 256 | 257 | junit 258 | junit 259 | 4.13.1 260 | test 261 | 262 | 263 | org.assertj 264 | assertj-core 265 | 266 | 3.11.1 267 | test 268 | 269 | 270 | org.mockito 271 | mockito-core 272 | 2.23.0 273 | test 274 | 275 | 276 | com.google.code.gson 277 | gson 278 | 2.9.1 279 | test 280 | 281 | 282 | com.fasterxml.jackson.core 283 | jackson-databind 284 | ${jackson.version} 285 | compile 286 | 287 | 288 | org.spockframework 289 | spock-core 290 | ${spock-core.version} 291 | test 292 | 293 | 294 | org.codehaus.groovy 295 | groovy-all 296 | 2.5.14 297 | pom 298 | test 299 | 300 | 301 | org.awaitility 302 | awaitility-groovy 303 | 3.0.0 304 | test 305 | 306 | 307 | 308 | 309 | 310 | 311 | ossrh 312 | https://oss.sonatype.org/content/repositories/snapshots 313 | 314 | 315 | ossrh 316 | https://oss.sonatype.org/service/local/staging/deploy/maven2 317 | 318 | 319 | 320 | 321 | 322 | ossrh 323 | Sonatype Repository 324 | https://oss.sonatype.org/content/repositories/releases 325 | 326 | 327 | 328 | 329 | 330 | ossrh 331 | Sonatype Repository 332 | https://oss.sonatype.org/content/repositories/releases 333 | 334 | 335 | 336 |
337 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/config/AuthzClient.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.config; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * This class represents the client calling your GraphQL API. You can extend this class 7 | * to add more attributes for your client. 8 | */ 9 | @Data 10 | public class AuthzClient { 11 | /* 12 | The scopeid or clientid or appid of your client. 13 | */ 14 | private String id; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/config/AuthzClientConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.config; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * This client represents the configuration that is needed to initialize the 8 | * {@link com.intuit.graphql.authorization.enforcement.AuthzInstrumentation} class. It represnts a map of your client 9 | * against the list of queries that defines the access control. 10 | */ 11 | public interface AuthzClientConfiguration { 12 | 13 | /** 14 | * Provide the access control map 15 | * @return Queries by Client 16 | */ 17 | Map> getQueriesByClient(); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/AuthorizationHolder.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import graphql.schema.GraphQLSchema; 4 | import java.util.Collections; 5 | import java.util.Map; 6 | import java.util.Map.Entry; 7 | import java.util.Objects; 8 | import java.util.Set; 9 | import java.util.stream.Collectors; 10 | import org.apache.commons.collections4.SetUtils; 11 | 12 | 13 | public class AuthorizationHolder { 14 | 15 | private final Map>> scopeToTypeMap; 16 | 17 | public AuthorizationHolder(Map>> scopeToType) { 18 | this.scopeToTypeMap = Collections.unmodifiableMap(scopeToType); 19 | } 20 | 21 | public TypeFieldPermissionVerifier getPermissionsVerifier(Set scopes, GraphQLSchema schema) { 22 | return new TypeFieldPermissionVerifier(schema, 23 | Collections.unmodifiableMap( 24 | scopes.stream() 25 | .map(scopeToTypeMap::get) 26 | .filter(Objects::nonNull) 27 | .flatMap(map -> map.entrySet().stream()) 28 | .collect(Collectors.toMap(Entry::getKey, Entry::getValue, 29 | (oldSet, newSet) -> SetUtils.union(oldSet, newSet) 30 | )))); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/AuthzInstrumentation.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; 4 | 5 | import com.intuit.graphql.authorization.config.AuthzClientConfiguration; 6 | import com.intuit.graphql.authorization.extension.AuthorizationExtension; 7 | import com.intuit.graphql.authorization.extension.AuthorizationExtensionProvider; 8 | import com.intuit.graphql.authorization.extension.DefaultAuthorizationExtensionProvider; 9 | import com.intuit.graphql.authorization.rules.AuthorizationHolderFactory; 10 | import com.intuit.graphql.authorization.rules.QueryRuleParser; 11 | import com.intuit.graphql.authorization.util.GraphQLUtil; 12 | import com.intuit.graphql.authorization.util.ScopeProvider; 13 | import graphql.ExecutionResult; 14 | import graphql.ExecutionResultImpl; 15 | import graphql.GraphQLError; 16 | import graphql.analysis.QueryTransformer; 17 | import graphql.execution.ExecutionContext; 18 | import graphql.execution.instrumentation.InstrumentationState; 19 | import graphql.execution.instrumentation.SimpleInstrumentation; 20 | import graphql.execution.instrumentation.parameters.InstrumentationCreateStateParameters; 21 | import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters; 22 | import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters; 23 | import graphql.language.FragmentDefinition; 24 | import graphql.language.SelectionSet; 25 | import graphql.schema.DataFetcher; 26 | import graphql.schema.GraphQLObjectType; 27 | import graphql.schema.GraphQLSchema; 28 | import java.util.LinkedList; 29 | import java.util.List; 30 | import java.util.Map; 31 | import java.util.Set; 32 | import java.util.concurrent.CompletableFuture; 33 | import java.util.function.Function; 34 | import java.util.stream.Collectors; 35 | import java.util.stream.Stream; 36 | import lombok.Builder; 37 | import lombok.Builder.Default; 38 | import lombok.Data; 39 | import lombok.NonNull; 40 | import lombok.RequiredArgsConstructor; 41 | import lombok.extern.slf4j.Slf4j; 42 | import org.apache.commons.collections4.CollectionUtils; 43 | 44 | @Slf4j 45 | public class AuthzInstrumentation extends SimpleInstrumentation { 46 | 47 | private static final AuthzListener DEFAULT_AUTHZ_LISTENER = new SimpleAuthZListener(); 48 | private static final AuthorizationExtensionProvider DEFAULT_AUTH_EXTENSION_PROVIDER = new DefaultAuthorizationExtensionProvider(); 49 | private final AuthorizationHolder authorizationHolder; 50 | private final ScopeProvider scopeProvider; 51 | 52 | @Default 53 | private AuthzListener authzListener = DEFAULT_AUTHZ_LISTENER; 54 | @Default 55 | private AuthorizationExtensionProvider authorizationExtensionProvider = DEFAULT_AUTH_EXTENSION_PROVIDER; 56 | 57 | @Builder 58 | public AuthzInstrumentation( 59 | @NonNull AuthzClientConfiguration configuration, 60 | @NonNull GraphQLSchema schema, 61 | @NonNull ScopeProvider scopeProvider, 62 | AuthzListener authzListener, 63 | AuthorizationExtensionProvider authorizationExtensionProvider) { 64 | 65 | if (configuration.getQueriesByClient().isEmpty()) { 66 | throw new IllegalArgumentException("Clients missing from AuthZClientConfiguration"); 67 | } 68 | 69 | this.authorizationHolder = new AuthorizationHolder( 70 | getAuthorizationFactory(schema).parse(configuration.getQueriesByClient())); 71 | this.scopeProvider = scopeProvider; 72 | this.authzListener = defaultIfNull(authzListener, DEFAULT_AUTHZ_LISTENER); 73 | this.authorizationExtensionProvider = defaultIfNull(authorizationExtensionProvider, DEFAULT_AUTH_EXTENSION_PROVIDER); 74 | } 75 | 76 | static AuthorizationHolderFactory getAuthorizationFactory(GraphQLSchema graphQLSchema) { 77 | QueryRuleParser queryRuleParser = new QueryRuleParser(graphQLSchema); 78 | return new AuthorizationHolderFactory(queryRuleParser); 79 | } 80 | 81 | @Override 82 | public AuthzInstrumentationState createState(InstrumentationCreateStateParameters parameters) { 83 | // 84 | // instrumentation state is passed during each invocation of an Instrumentation method 85 | // and allows you to put stateful data away and reference it during the query execution 86 | // 87 | Set scopes = scopeProvider.getScopes(parameters.getExecutionInput().getContext()); 88 | 89 | authzListener.onCreatingState(parameters.getSchema(), parameters.getExecutionInput()); 90 | return new AuthzInstrumentationState(authorizationHolder.getPermissionsVerifier(scopes, parameters.getSchema()), 91 | parameters.getSchema(), scopes); 92 | } 93 | 94 | 95 | @Override 96 | public ExecutionContext instrumentExecutionContext(ExecutionContext executionContext, 97 | InstrumentationExecutionParameters parameters) { 98 | AuthzInstrumentationState state = parameters.getInstrumentationState(); 99 | AuthorizationExtension authorizationExtension = this.authorizationExtensionProvider.getAuthorizationExtension( 100 | executionContext, parameters); 101 | ExecutionContext enforcedExecutionContext = getAuthzExecutionContext(executionContext, state, 102 | authorizationExtension); 103 | authzListener.onEnforcement(executionContext, enforcedExecutionContext); 104 | return enforcedExecutionContext; 105 | } 106 | 107 | private ExecutionContext getAuthzExecutionContext(ExecutionContext executionContext, 108 | AuthzInstrumentationState state, AuthorizationExtension authorizationExtension) { 109 | log.info("Authorization is enabled"); 110 | ExecutionContext restrictedContext = executionContext 111 | .transform(executionContextBuilder -> executionContextBuilder 112 | .operationDefinition(executionContext.getOperationDefinition() 113 | .transform(operationDefinitionBuilder -> 114 | operationDefinitionBuilder 115 | .selectionSet(redactSelectionSet(executionContext, state, authorizationExtension)))) 116 | .fragmentsByName(redactFragments(executionContext, state, authorizationExtension)) 117 | ); 118 | log.info("Restricted executionContext created"); 119 | return restrictedContext; 120 | } 121 | 122 | 123 | @Override 124 | public CompletableFuture instrumentExecutionResult(ExecutionResult executionResult, 125 | InstrumentationExecutionParameters parameters) { 126 | AuthzInstrumentationState instrumentationState = parameters.getInstrumentationState(); 127 | List graphQLErrors = executionResult.getErrors(); 128 | if (CollectionUtils.isNotEmpty(instrumentationState.getAuthzErrors())) { 129 | graphQLErrors = Stream.concat(graphQLErrors.stream(), instrumentationState.getAuthzErrors().stream()) 130 | .collect(Collectors.toList()); 131 | } 132 | if (executionResult.getData() == null) { 133 | return CompletableFuture.completedFuture(new ExecutionResultImpl(graphQLErrors)); 134 | } 135 | return CompletableFuture.completedFuture( 136 | new ExecutionResultImpl(executionResult.getData(), graphQLErrors, executionResult.getExtensions())); 137 | } 138 | 139 | 140 | private QueryTransformer.Builder initQueryTransformerBuilder(ExecutionContext executionContext) { 141 | return QueryTransformer.newQueryTransformer() 142 | .schema(executionContext.getGraphQLSchema()) 143 | .variables(executionContext.getVariables()) 144 | .fragmentsByName(executionContext.getFragmentsByName()); 145 | } 146 | 147 | Map redactFragments(ExecutionContext executionContext, AuthzInstrumentationState state, 148 | AuthorizationExtension authorizationExtension) { 149 | //treat each fragment as root and redact based on configuration 150 | return executionContext.getFragmentsByName().values().stream().map(entry -> 151 | redactFragment(entry, executionContext, state, authorizationExtension)) 152 | .collect(Collectors.toMap(FragmentDefinition::getName, Function.identity())); 153 | } 154 | 155 | FragmentDefinition redactFragment(FragmentDefinition fragmentDefinition, ExecutionContext executionContext, 156 | AuthzInstrumentationState state, AuthorizationExtension authorizationExtension) { 157 | fragmentDefinition.getTypeCondition(); 158 | QueryTransformer queryTransformer = initQueryTransformerBuilder(executionContext) 159 | .root(fragmentDefinition) 160 | .rootParentType(executionContext.getGraphQLSchema().getQueryType()) 161 | .build(); 162 | 163 | return (FragmentDefinition) 164 | queryTransformer.transform(new RedactingVisitor(state, executionContext, authzListener, 165 | authorizationExtension, scopeProvider)); 166 | } 167 | 168 | 169 | SelectionSet redactSelectionSet(ExecutionContext executionContext, AuthzInstrumentationState state, 170 | AuthorizationExtension authorizationExtension) { 171 | GraphQLObjectType rootType = GraphQLUtil.getRootTypeFromOperation(executionContext.getOperationDefinition(), 172 | executionContext.getGraphQLSchema()); 173 | 174 | QueryTransformer transformer = initQueryTransformerBuilder(executionContext) 175 | .rootParentType(rootType) 176 | .root(executionContext.getOperationDefinition().getSelectionSet()) 177 | .build(); 178 | 179 | return (SelectionSet) transformer.transform(new RedactingVisitor(state, executionContext, authzListener, 180 | authorizationExtension, scopeProvider)); 181 | } 182 | 183 | 184 | @Override 185 | public DataFetcher instrumentDataFetcher(DataFetcher dataFetcher, 186 | InstrumentationFieldFetchParameters parameters) { 187 | AuthzInstrumentationState state = parameters.getInstrumentationState(); 188 | return new IntrospectionRedactingDataFetcher(dataFetcher, state); 189 | } 190 | 191 | @Data 192 | @RequiredArgsConstructor 193 | static class AuthzInstrumentationState implements InstrumentationState { 194 | 195 | private final TypeFieldPermissionVerifier typeFieldPermissionVerifier; 196 | private final GraphQLSchema graphQLSchema; 197 | private final Set scopes; 198 | private List authzErrors = new LinkedList<>(); 199 | } 200 | 201 | } 202 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/AuthzListener.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import graphql.ExecutionInput; 4 | import graphql.analysis.QueryVisitorFieldEnvironment; 5 | import graphql.execution.ExecutionContext; 6 | import graphql.schema.GraphQLSchema; 7 | 8 | /** 9 | * This interface provides a customizable way to listen to various execution steps of query authorization. 10 | */ 11 | public interface AuthzListener { 12 | 13 | /** 14 | * This will be called just before a query field is redacted for unauthorized access. It gives the execution context 15 | * and queryVisitorFieldEnvironment as metadata of the field being redacted. 16 | * 17 | * @param executionContext ExecutionContext 18 | * @param queryVisitorFieldEnvironment Environment 19 | * 20 | */ 21 | void onFieldRedaction(final ExecutionContext executionContext, 22 | final QueryVisitorFieldEnvironment queryVisitorFieldEnvironment); 23 | 24 | /** 25 | * This will be called just before creating authz instrumentation state. 26 | * 27 | * @param schema the graphql schema. 28 | * @param executionInput the execution input. 29 | */ 30 | void onCreatingState( final GraphQLSchema schema, final ExecutionInput executionInput); 31 | 32 | /** 33 | * This will be called after enforcing authz policy on the execution input if applicable. 34 | * 35 | * @param originalExecutionContext execution context before authz policy is enforced. 36 | * @param enforcedExecutionContext execution context after authz policy is enforced. 37 | */ 38 | void onEnforcement(final ExecutionContext originalExecutionContext, 39 | final ExecutionContext enforcedExecutionContext); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/IntrospectionRedactingDataFetcher.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static graphql.introspection.Introspection.__Type; 4 | 5 | import com.intuit.graphql.authorization.util.GraphQLUtil; 6 | import graphql.schema.DataFetcher; 7 | import graphql.schema.DataFetchingEnvironment; 8 | import graphql.schema.GraphQLFieldDefinition; 9 | import graphql.schema.GraphQLFieldsContainer; 10 | import graphql.schema.GraphQLNamedType; 11 | import graphql.schema.GraphQLType; 12 | import java.util.List; 13 | import java.util.stream.Collectors; 14 | 15 | class IntrospectionRedactingDataFetcher implements DataFetcher { 16 | 17 | private final DataFetcher delegate; 18 | private final AuthzInstrumentation.AuthzInstrumentationState state; 19 | 20 | public IntrospectionRedactingDataFetcher(DataFetcher delegate, AuthzInstrumentation.AuthzInstrumentationState state) { 21 | this.state = state; 22 | this.delegate = delegate; 23 | } 24 | 25 | @Override 26 | public Object get(DataFetchingEnvironment environment) throws Exception { 27 | Object delegatedGetResult = delegate.get(environment); 28 | if (delegatedGetResult != null) { 29 | if (GraphQLUtil.isListOfIntrospection__Type(environment.getFieldType())) { 30 | //would be nice if there were no type erasure for generics 31 | return redactTypeList((List) delegatedGetResult); 32 | } 33 | 34 | //used for introspection of fields 35 | //Note: Since fieldsDatafetcher is now private, we are getting it from codeRegistry 36 | if (delegate == fieldsDataFetcher(environment)) { 37 | Object type = environment.getSource(); 38 | return redactFields( 39 | (List) delegatedGetResult, 40 | (GraphQLFieldsContainer) type); 41 | } 42 | } 43 | return delegatedGetResult; 44 | } 45 | 46 | private DataFetcher fieldsDataFetcher(DataFetchingEnvironment environment) { 47 | return environment.getGraphQLSchema().getCodeRegistry().getDataFetcher(__Type, 48 | __Type.getFieldDefinition("fields")); 49 | } 50 | 51 | private List redactFields(List fields, 52 | GraphQLFieldsContainer fieldsContainer) { 53 | return fields.stream().filter(fieldDefinition -> 54 | state.getTypeFieldPermissionVerifier().isPermitted(fieldsContainer, fieldDefinition)) 55 | .collect(Collectors.toList()); 56 | } 57 | 58 | private List redactTypeList(List fields) { 59 | return fields.stream() 60 | .filter(type -> state.getTypeFieldPermissionVerifier().isPermitted(type)) 61 | .collect(Collectors.toList()); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/PermissionVerifier.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import graphql.schema.GraphQLFieldDefinition; 4 | import graphql.schema.GraphQLNamedType; 5 | 6 | 7 | public interface PermissionVerifier { 8 | 9 | default boolean isPermitted(GraphQLNamedType graphQLType) { 10 | return false; 11 | } 12 | 13 | default boolean isPermitted(GraphQLNamedType graphQLType, GraphQLFieldDefinition fieldDefinition) { 14 | return false; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/RedactingVisitor.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static graphql.ErrorType.DataFetchingException; 4 | import static graphql.schema.GraphQLTypeUtil.unwrapAll; 5 | 6 | import com.intuit.graphql.authorization.extension.AuthorizationExtension; 7 | import com.intuit.graphql.authorization.extension.FieldAuthorizationEnvironment; 8 | import com.intuit.graphql.authorization.extension.FieldAuthorizationResult; 9 | import com.intuit.graphql.authorization.util.ScopeProvider; 10 | import graphql.GraphQLError; 11 | import graphql.GraphqlErrorBuilder; 12 | import graphql.analysis.QueryVisitorFieldEnvironment; 13 | import graphql.analysis.QueryVisitorStub; 14 | import graphql.execution.ExecutionContext; 15 | import graphql.language.Field; 16 | import graphql.schema.FieldCoordinates; 17 | import graphql.schema.GraphQLFieldDefinition; 18 | import graphql.schema.GraphQLUnmodifiedType; 19 | import graphql.util.TreeTransformerUtil; 20 | import lombok.extern.slf4j.Slf4j; 21 | 22 | @Slf4j 23 | public class RedactingVisitor extends QueryVisitorStub { 24 | 25 | private final AuthzInstrumentation.AuthzInstrumentationState instrumentationState; 26 | private final TypeFieldPermissionVerifier typeFieldPermissionVerifier; 27 | private final ExecutionContext executionContext; 28 | private final AuthzListener authzListener; 29 | private final AuthorizationExtension authorizationExtension; 30 | 31 | private final ScopeProvider scopeProvider; 32 | 33 | 34 | public RedactingVisitor(AuthzInstrumentation.AuthzInstrumentationState state, 35 | ExecutionContext executionContext, AuthzListener authzListener, 36 | AuthorizationExtension authorizationExtension, ScopeProvider scopeProvider) { 37 | this.instrumentationState = state; 38 | this.executionContext = executionContext; 39 | this.authzListener = authzListener; 40 | this.authorizationExtension = authorizationExtension; 41 | this.typeFieldPermissionVerifier = instrumentationState.getTypeFieldPermissionVerifier(); 42 | this.scopeProvider = scopeProvider; 43 | } 44 | 45 | @Override 46 | public void visitField(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) { 47 | final GraphQLUnmodifiedType graphQLUnmodifiedParentType = unwrapAll(queryVisitorFieldEnvironment.getParentType()); 48 | GraphQLFieldDefinition requestedFieldDefinition = queryVisitorFieldEnvironment.getFieldDefinition(); 49 | 50 | boolean permitted = typeFieldPermissionVerifier.isPermitted(graphQLUnmodifiedParentType, requestedFieldDefinition); 51 | 52 | if (!permitted) { 53 | //record an error 54 | String parentName = graphQLUnmodifiedParentType.getName(); 55 | authzListener.onFieldRedaction(executionContext, queryVisitorFieldEnvironment); 56 | Field field = queryVisitorFieldEnvironment.getField(); 57 | 58 | String errorMessage = scopeProvider.getErrorMessage(RedactionContext.builder() 59 | .fieldCoordinates(FieldCoordinates.coordinates(parentName, field.getName())) 60 | .field(field) 61 | .build()); 62 | 63 | GraphQLError error = GraphqlErrorBuilder.newError() 64 | .errorType(DataFetchingException) 65 | .message(errorMessage) 66 | .location(field.getSourceLocation()) 67 | .build(); 68 | instrumentationState.getAuthzErrors().add(error); 69 | 70 | TreeTransformerUtil.deleteNode(queryVisitorFieldEnvironment.getTraverserContext()); 71 | } else { 72 | FieldAuthorizationEnvironment fieldAuthorizationEnvironment = createFieldAuthorizationEnvironment(queryVisitorFieldEnvironment); 73 | FieldAuthorizationResult fieldAuthorizationResult = authorizationExtension.authorize(fieldAuthorizationEnvironment); 74 | if (!fieldAuthorizationResult.isAllowed()) { 75 | authzListener.onFieldRedaction(executionContext, queryVisitorFieldEnvironment); 76 | instrumentationState.getAuthzErrors().add(fieldAuthorizationResult.getGraphqlErrorException()); 77 | TreeTransformerUtil.deleteNode(queryVisitorFieldEnvironment.getTraverserContext()); 78 | } 79 | } 80 | } 81 | 82 | private FieldAuthorizationEnvironment createFieldAuthorizationEnvironment( 83 | QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) { 84 | 85 | GraphQLUnmodifiedType parentType = unwrapAll(queryVisitorFieldEnvironment.getParentType()); 86 | Field field = queryVisitorFieldEnvironment.getField(); 87 | 88 | FieldCoordinates fieldCoordinates = FieldCoordinates 89 | .coordinates(parentType.getName(), field.getName()); 90 | 91 | return FieldAuthorizationEnvironment.builder() 92 | .field(field) 93 | .arguments(queryVisitorFieldEnvironment.getArguments()) 94 | .fieldCoordinates(fieldCoordinates) 95 | .fieldDefinition(queryVisitorFieldEnvironment.getFieldDefinition()) 96 | .parentType(queryVisitorFieldEnvironment.getParentType()) 97 | .graphQLSchema(queryVisitorFieldEnvironment.getSchema()) 98 | .build(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/RedactionContext.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import graphql.language.Field; 4 | import graphql.schema.FieldCoordinates; 5 | import lombok.Builder; 6 | import lombok.Getter; 7 | 8 | @Builder 9 | @Getter 10 | public class RedactionContext { 11 | Field field; 12 | FieldCoordinates fieldCoordinates; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/SimpleAuthZListener.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import graphql.ExecutionInput; 4 | import graphql.analysis.QueryVisitorFieldEnvironment; 5 | import graphql.execution.ExecutionContext; 6 | import graphql.schema.GraphQLSchema; 7 | 8 | public class SimpleAuthZListener implements AuthzListener { 9 | 10 | @Override 11 | public void onFieldRedaction(ExecutionContext executionContext, 12 | QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) { 13 | //do nothing 14 | } 15 | 16 | @Override 17 | public void onCreatingState(GraphQLSchema schema, ExecutionInput executionInput) { 18 | //do nothing 19 | } 20 | 21 | @Override 22 | public void onEnforcement(ExecutionContext originalExecutionContext, 23 | ExecutionContext enforcedExecutionContext) { 24 | //do nothing 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/enforcement/TypeFieldPermissionVerifier.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static graphql.schema.GraphQLTypeUtil.unwrapAll; 4 | 5 | import com.intuit.graphql.authorization.util.GraphQLUtil; 6 | import graphql.introspection.Introspection; 7 | import graphql.schema.GraphQLFieldDefinition; 8 | import graphql.schema.GraphQLNamedType; 9 | import graphql.schema.GraphQLSchema; 10 | import graphql.schema.GraphQLTypeUtil; 11 | import java.util.Map; 12 | import java.util.Set; 13 | import lombok.Getter; 14 | import org.apache.commons.collections4.CollectionUtils; 15 | import org.apache.commons.collections4.SetUtils; 16 | 17 | public class TypeFieldPermissionVerifier implements PermissionVerifier { 18 | 19 | @Getter 20 | private final Map> typeToFieldsMap; 21 | private final GraphQLSchema schema; 22 | 23 | TypeFieldPermissionVerifier(GraphQLSchema schema, Map> typeToFieldsMap) { 24 | this.typeToFieldsMap = typeToFieldsMap; 25 | this.schema = schema; 26 | } 27 | 28 | @Override 29 | public boolean isPermitted(GraphQLNamedType graphQLType) { 30 | return isTypeSpecial(graphQLType) || typeToFieldsMap.containsKey(graphQLType.getName()); 31 | } 32 | 33 | @Override 34 | public boolean isPermitted(GraphQLNamedType parentType, GraphQLFieldDefinition fieldDefinition) { 35 | if (isTypeSpecial(parentType)) { 36 | return true; 37 | } 38 | final GraphQLNamedType type = unwrapAll(fieldDefinition.getType()); 39 | if (parentType == schema.getQueryType() && type == Introspection.__Schema) { 40 | return true; 41 | } 42 | Set fields = typeToFieldsMap.getOrDefault(parentType.getName(), SetUtils.emptySet()); 43 | //allow __typename, if at least one field is allowed. 44 | if (fieldDefinition == Introspection.TypeNameMetaFieldDef) { 45 | return CollectionUtils.isNotEmpty(fields); 46 | } 47 | return fields.contains(fieldDefinition.getName()); 48 | } 49 | 50 | private boolean isTypeSpecial(GraphQLNamedType parentType) { 51 | //input types are permitted 52 | //schema types are permitted 53 | return GraphQLUtil.isReservedSchemaType(parentType) || GraphQLTypeUtil.isInput(parentType); 54 | } 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/extension/AuthorizationExtension.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.extension; 2 | 3 | import com.intuit.graphql.authorization.enforcement.TypeFieldPermissionVerifier; 4 | 5 | /** 6 | * The class allows creating authorization logic in addition to 7 | * {@link TypeFieldPermissionVerifier}. 8 | * 9 | * To create an instance of AuthorizationExtension instance, {@link AuthorizationExtensionProvider}. 10 | */ 11 | public interface AuthorizationExtension { 12 | 13 | FieldAuthorizationResult authorize(FieldAuthorizationEnvironment fieldAuthorizationEnvironment); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/extension/AuthorizationExtensionProvider.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.extension; 2 | 3 | import com.intuit.graphql.authorization.enforcement.AuthzInstrumentation; 4 | import graphql.execution.ExecutionContext; 5 | import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters; 6 | 7 | /** 8 | * This class provides capability to customize the creation of {@link AuthorizationExtension} during 9 | * {@link AuthzInstrumentation#instrumentExecutionContext(ExecutionContext, 10 | * InstrumentationExecutionParameters)}. This is useful if the authorization extension logic 11 | * requires data such as from HTTP headers, parameters, etc. which can be extracted from 12 | * instrumentationExecutionContext method parameters if properly setup. 13 | */ 14 | public interface AuthorizationExtensionProvider { 15 | 16 | AuthorizationExtension getAuthorizationExtension(ExecutionContext executionContext, 17 | InstrumentationExecutionParameters parameters); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/extension/DefaultAuthorizationExtension.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.extension; 2 | 3 | public class DefaultAuthorizationExtension implements AuthorizationExtension { 4 | 5 | @Override 6 | public FieldAuthorizationResult authorize( 7 | FieldAuthorizationEnvironment fieldAuthorizationEnvironment) { 8 | return FieldAuthorizationResult.ALLOWED_FIELD_AUTH_RESULT; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/extension/DefaultAuthorizationExtensionProvider.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.extension; 2 | 3 | import graphql.execution.ExecutionContext; 4 | import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters; 5 | 6 | public class DefaultAuthorizationExtensionProvider implements 7 | AuthorizationExtensionProvider { 8 | 9 | private static final AuthorizationExtension DEFAULT_AUTH_EXTENSION = new DefaultAuthorizationExtension(); 10 | 11 | @Override 12 | public AuthorizationExtension getAuthorizationExtension(ExecutionContext executionContext, 13 | InstrumentationExecutionParameters parameters) { 14 | return DEFAULT_AUTH_EXTENSION; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/extension/FieldAuthorizationEnvironment.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.extension; 2 | 3 | import graphql.language.Field; 4 | import graphql.schema.FieldCoordinates; 5 | import graphql.schema.GraphQLFieldDefinition; 6 | import graphql.schema.GraphQLOutputType; 7 | import graphql.schema.GraphQLSchema; 8 | import java.util.Map; 9 | import lombok.Builder; 10 | import lombok.EqualsAndHashCode; 11 | import lombok.Getter; 12 | import lombok.NonNull; 13 | 14 | @Builder 15 | @Getter 16 | @EqualsAndHashCode 17 | public class FieldAuthorizationEnvironment { 18 | 19 | @NonNull 20 | @EqualsAndHashCode.Include 21 | private FieldCoordinates fieldCoordinates; 22 | @NonNull 23 | @EqualsAndHashCode.Exclude 24 | private Field field; 25 | @NonNull 26 | @EqualsAndHashCode.Exclude 27 | private Map arguments; 28 | @NonNull 29 | @EqualsAndHashCode.Exclude 30 | private GraphQLFieldDefinition fieldDefinition; 31 | @NonNull 32 | @EqualsAndHashCode.Exclude 33 | private GraphQLOutputType parentType; 34 | @NonNull 35 | @EqualsAndHashCode.Exclude 36 | private GraphQLSchema graphQLSchema; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/extension/FieldAuthorizationResult.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.extension; 2 | 3 | import graphql.GraphqlErrorException; 4 | import java.util.Objects; 5 | import lombok.Getter; 6 | 7 | public class FieldAuthorizationResult { 8 | 9 | public static final FieldAuthorizationResult ALLOWED_FIELD_AUTH_RESULT = 10 | new FieldAuthorizationResult(true, null); 11 | 12 | @Getter private final boolean isAllowed; 13 | @Getter private final GraphqlErrorException graphqlErrorException; 14 | 15 | private FieldAuthorizationResult(boolean isAllowed, GraphqlErrorException graphqlErrorException) { 16 | this.isAllowed = isAllowed; 17 | this.graphqlErrorException = graphqlErrorException; 18 | } 19 | 20 | public static FieldAuthorizationResult createDeniedResult(GraphqlErrorException graphqlErrorException) { 21 | Objects.requireNonNull(graphqlErrorException, "an instance of GraphqlErrorException is " 22 | + "required to create a denied FieldAuthorizationResult"); 23 | return new FieldAuthorizationResult(false, graphqlErrorException); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/rules/AuthorizationHolderFactory.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import com.intuit.graphql.authorization.config.AuthzClient; 4 | import com.intuit.graphql.authorization.util.FieldCoordinatesFormattingUtil; 5 | import graphql.schema.FieldCoordinates; 6 | import java.util.Collections; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.Map.Entry; 11 | import java.util.Objects; 12 | import java.util.Set; 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | 16 | @Slf4j 17 | public class AuthorizationHolderFactory { 18 | 19 | private final RuleParser ruleParser; 20 | 21 | public AuthorizationHolderFactory(RuleParser ruleParser) { 22 | this.ruleParser = Objects.requireNonNull(ruleParser); 23 | } 24 | 25 | public Map>> parse( 26 | Map> graphqlRulesByClient 27 | ) { 28 | Map>> scopeToTypeMap = new HashMap<>(); 29 | 30 | for (Entry> entry : graphqlRulesByClient.entrySet()) { 31 | AuthzClient authzClient = entry.getKey(); 32 | List queries = entry.getValue(); 33 | String id = authzClient.getId(); 34 | 35 | Map> intermediateResults = new HashMap<>(); 36 | 37 | InvalidFieldsCollector invalidFieldsCollector = new InvalidFieldsCollector(); 38 | 39 | for (final String query : queries) { 40 | try { 41 | Map> ruleSetMap = ruleParser.parseRule(query, invalidFieldsCollector); 42 | ruleSetMap.forEach((type, fields) -> intermediateResults.merge(type, fields, (oldSet, newSet) -> { 43 | oldSet.addAll(newSet); 44 | return oldSet; 45 | })); 46 | } catch (Exception e) { 47 | log.error("Failed to parse rule for scope " + id, e); 48 | } 49 | } 50 | 51 | if (invalidFieldsCollector.hasInvalidFields()) { 52 | log.error(String.format("Invalid fields found in query rule. clientId=%s, invalidFields=%s", 53 | id, invalidFieldsCollector.getInvalidFieldsAsString())); 54 | } 55 | 56 | if (!intermediateResults.isEmpty()) { 57 | scopeToTypeMap.put(id, intermediateResults); 58 | } 59 | } 60 | 61 | log.info("Parsed rules for scopes " + scopeToTypeMap.keySet()); 62 | return Collections.unmodifiableMap(scopeToTypeMap); 63 | } 64 | 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/rules/InvalidFieldsCollector.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import com.intuit.graphql.authorization.util.FieldCoordinatesFormattingUtil; 4 | import graphql.language.Field; 5 | import graphql.schema.FieldCoordinates; 6 | import graphql.schema.GraphQLFieldsContainer; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | import org.apache.commons.collections4.CollectionUtils; 10 | 11 | public class InvalidFieldsCollector implements RuleParserListener { 12 | 13 | private final Set invalidFields = new HashSet<>(); 14 | 15 | @Override 16 | public void onQueryParsingError(GraphQLFieldsContainer parentType, Field field) { 17 | invalidFields.add(FieldCoordinates.coordinates(parentType.getName(), field.getName())); 18 | } 19 | 20 | public boolean hasInvalidFields() { 21 | return CollectionUtils.isNotEmpty(invalidFields); 22 | } 23 | 24 | public Set getInvalidFields() { 25 | return this.invalidFields; 26 | } 27 | 28 | public String getInvalidFieldsAsString() { 29 | return FieldCoordinatesFormattingUtil.toString(this.invalidFields); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/rules/QueryRuleParser.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import static com.intuit.graphql.authorization.util.GraphQLUtil.getFieldDefinition; 4 | import static com.intuit.graphql.authorization.util.GraphQLUtil.isNotEmpty; 5 | 6 | import com.intuit.graphql.authorization.util.GraphQLUtil; 7 | import graphql.language.Document; 8 | import graphql.language.Field; 9 | import graphql.language.OperationDefinition; 10 | import graphql.language.SelectionSet; 11 | import graphql.parser.Parser; 12 | import graphql.schema.GraphQLFieldDefinition; 13 | import graphql.schema.GraphQLFieldsContainer; 14 | import graphql.schema.GraphQLOutputType; 15 | import graphql.schema.GraphQLSchema; 16 | import graphql.schema.GraphQLType; 17 | import graphql.schema.GraphQLTypeUtil; 18 | import java.util.HashMap; 19 | import java.util.HashSet; 20 | import java.util.Map; 21 | import java.util.Objects; 22 | import java.util.Set; 23 | import lombok.extern.slf4j.Slf4j; 24 | 25 | @Slf4j 26 | public class QueryRuleParser implements RuleParser { 27 | 28 | private static final String ERR_MSG = "Unknown field '%s'"; 29 | 30 | private final GraphQLSchema schema; 31 | 32 | public QueryRuleParser(GraphQLSchema schema) { 33 | this.schema = Objects.requireNonNull(schema); 34 | } 35 | 36 | private void preOrder(GraphQLType graphQLOutputType, SelectionSet selectionSet, 37 | Map> typeToFieldMap, RuleParserListener ruleParserListener) { 38 | if (graphQLOutputType instanceof GraphQLFieldsContainer && isNotEmpty(selectionSet)) { 39 | GraphQLFieldsContainer parentType = (GraphQLFieldsContainer) graphQLOutputType; 40 | selectionSet.getSelections() 41 | .forEach(node -> { 42 | if (node instanceof Field) { 43 | Field field = (Field) node; 44 | final GraphQLFieldDefinition fieldDefinition = getFieldDefinition(parentType, 45 | field.getName()); 46 | if (fieldDefinition == null) { 47 | ruleParserListener.onQueryParsingError(parentType, field); 48 | } else { 49 | Set fields = typeToFieldMap 50 | .computeIfAbsent(parentType.getName(), k -> new HashSet<>()); 51 | fields.add(fieldDefinition.getName()); 52 | preOrder(GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()), 53 | field.getSelectionSet(), typeToFieldMap, ruleParserListener); 54 | } 55 | } 56 | }); 57 | } 58 | } 59 | 60 | @Override 61 | public Map> parseRule(final String query, RuleParserListener ruleParserListener) { 62 | Map> typeToFieldMap = new HashMap<>(); 63 | Document document = new Parser().parseDocument(query); 64 | document.getDefinitions() 65 | .forEach(definition -> { 66 | if (definition instanceof OperationDefinition) { 67 | OperationDefinition operationDefinition = (OperationDefinition) definition; 68 | GraphQLOutputType operationType = GraphQLUtil.getRootTypeFromOperation(operationDefinition, schema); 69 | preOrder(operationType, operationDefinition.getSelectionSet(), typeToFieldMap, ruleParserListener); 70 | } 71 | }); 72 | return typeToFieldMap; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/rules/RuleParser.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | public interface RuleParser { 8 | 9 | Map> parseRule(String rule, RuleParserListener ruleParserListener); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/rules/RuleParserListener.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import graphql.language.Field; 4 | import graphql.schema.GraphQLFieldsContainer; 5 | 6 | public interface RuleParserListener { 7 | 8 | void onQueryParsingError(GraphQLFieldsContainer parentType, 9 | Field field); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/util/FieldCoordinatesFormattingUtil.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.util; 2 | 3 | import graphql.schema.FieldCoordinates; 4 | import java.util.Set; 5 | import java.util.StringJoiner; 6 | import org.apache.commons.collections4.CollectionUtils; 7 | import org.apache.commons.lang3.StringUtils; 8 | 9 | public class FieldCoordinatesFormattingUtil { 10 | 11 | private static final String DELIMITER_COMMA = ","; 12 | 13 | private FieldCoordinatesFormattingUtil() { 14 | } 15 | 16 | public static String toString(Set invalidFields) { 17 | if (CollectionUtils.isEmpty(invalidFields)) { 18 | return ""; 19 | } 20 | return StringUtils.join(invalidFields.iterator(), DELIMITER_COMMA); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/util/GraphQLUtil.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.util; 2 | 3 | import static graphql.Assert.assertNotNull; 4 | import static graphql.Assert.assertShouldNeverHappen; 5 | 6 | import graphql.introspection.Introspection; 7 | import graphql.language.OperationDefinition; 8 | import graphql.language.SelectionSet; 9 | import graphql.schema.GraphQLFieldDefinition; 10 | import graphql.schema.GraphQLFieldsContainer; 11 | import graphql.schema.GraphQLObjectType; 12 | import graphql.schema.GraphQLSchema; 13 | import graphql.schema.GraphQLType; 14 | import graphql.schema.GraphQLTypeUtil; 15 | import graphql.schema.GraphQLUnmodifiedType; 16 | import org.apache.commons.collections4.CollectionUtils; 17 | 18 | public class GraphQLUtil { 19 | 20 | //hides public constructor 21 | private GraphQLUtil() { 22 | } 23 | 24 | public static GraphQLObjectType getRootTypeFromOperation(OperationDefinition operationDefinition, 25 | GraphQLSchema schema) { 26 | switch (operationDefinition.getOperation()) { 27 | case MUTATION: 28 | return assertNotNull(schema.getMutationType()); 29 | case QUERY: 30 | return assertNotNull(schema.getQueryType()); 31 | case SUBSCRIPTION: 32 | return assertNotNull(schema.getSubscriptionType()); 33 | default: 34 | return assertShouldNeverHappen(); 35 | } 36 | } 37 | 38 | public static boolean isOperationType(GraphQLType type, GraphQLSchema schema) { 39 | return type == schema.getQueryType() || type == schema.getMutationType() || type == schema.getSubscriptionType(); 40 | } 41 | 42 | public static boolean isReservedSchemaType(GraphQLType type) { 43 | GraphQLUnmodifiedType unwrapped = GraphQLTypeUtil.unwrapAll(type); 44 | return unwrapped.getName().startsWith("__"); 45 | } 46 | 47 | public static GraphQLFieldDefinition getFieldDefinition(GraphQLFieldsContainer graphQLFieldsContainer, 48 | String fieldName) { 49 | if (Introspection.TypeNameMetaFieldDef.getName().equals(fieldName)) { 50 | return Introspection.TypeNameMetaFieldDef; 51 | } 52 | return graphQLFieldsContainer.getFieldDefinition(fieldName); 53 | } 54 | 55 | public static boolean isIntrospection__Type(GraphQLType type) { 56 | GraphQLType unwrappedType = GraphQLTypeUtil.unwrapAll(type); 57 | return unwrappedType == Introspection.__Type; 58 | } 59 | 60 | public static boolean isNotEmpty(SelectionSet selectionSet) { 61 | return selectionSet != null && CollectionUtils.isNotEmpty(selectionSet.getSelections()); 62 | } 63 | 64 | public static boolean isListOfIntrospection__Type(GraphQLType type) { 65 | if (GraphQLTypeUtil.isNonNull(type)) { 66 | return isListOfIntrospection__Type(GraphQLTypeUtil.unwrapOne(type)); 67 | } 68 | if (GraphQLTypeUtil.isList(type)) { 69 | return isIntrospection__Type(type); 70 | } 71 | return false; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/intuit/graphql/authorization/util/ScopeProvider.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.util; 2 | 3 | import com.intuit.graphql.authorization.enforcement.RedactionContext; 4 | 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | public interface ScopeProvider { 9 | 10 | String DEFAULT_ERROR_MESSAGE = "403 - Not authorized to access field=%s of type=%s"; 11 | 12 | // This method needs to return a set of strings if the scopes are passed and an empty set if not passed 13 | default Set getScopes(Object o) { 14 | return new HashSet<>(); 15 | } 16 | 17 | default String getErrorMessage(RedactionContext redactionContext) { 18 | return String.format(DEFAULT_ERROR_MESSAGE, 19 | redactionContext.getField().getName(), redactionContext.getFieldCoordinates().getTypeName()); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/test/groovy/com/intuit/graphql/authorization/enforcement/AuthorizationSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement 2 | 3 | import com.google.gson.Gson 4 | import com.google.gson.GsonBuilder 5 | import com.google.gson.JsonArray 6 | import com.google.gson.JsonElement 7 | import com.google.gson.JsonObject 8 | import com.intuit.graphql.authorization.config.AuthzClient 9 | import com.intuit.graphql.authorization.config.AuthzClientConfiguration 10 | import com.intuit.graphql.authorization.util.ScopeProvider 11 | import com.intuit.graphql.authorization.util.TestStaticResources 12 | import graphql.ExecutionInput 13 | import graphql.GraphQL 14 | import graphql.introspection.IntrospectionQuery 15 | import graphql.schema.GraphQLSchema 16 | import java.util.stream.Collectors 17 | import org.junit.Before 18 | import org.junit.Test 19 | import spock.lang.Specification 20 | 21 | class AuthorizationSpec extends Specification{ 22 | 23 | AuthzInstrumentation authzInstrumentation 24 | AuthzClientConfiguration authzClientConfiguration = new HelperAuthzClientConfiguration() 25 | ScopeProvider scopeProvider = new HelperScopeProvider() 26 | GraphQLSchema schema 27 | def graphql 28 | String mutationQuery 29 | String fragmentsInMutationQuery 30 | 31 | void setup() { 32 | 33 | mutationQuery = ''' 34 | mutation { 35 | createNewBookRecord(input: { 36 | id: "Book-7", 37 | name: "New World", 38 | pageCount: 1001, 39 | author:{ 40 | id: "Author-7" 41 | firstName: "Mickey", 42 | lastName: "Mouse" 43 | } 44 | }) { 45 | id 46 | name 47 | pageCount 48 | author{ 49 | firstName 50 | lastName 51 | } 52 | } 53 | updateBookRecord(input: { 54 | id: "book-3", 55 | name: "test updates", 56 | pageCount: 100 57 | }) { 58 | id 59 | } 60 | removeBookRecord(input: { 61 | id: "book-1" 62 | }) { 63 | id 64 | } 65 | } 66 | ''' 67 | fragmentsInMutationQuery = ''' 68 | mutation { 69 | createNewBookRecord(input: { 70 | id: "Book-7", 71 | name: "New World", 72 | pageCount: 1001, 73 | author:{ 74 | id: "Author-7" 75 | firstName: "Mickey", 76 | lastName: "Mouse" 77 | } 78 | }) { 79 | id 80 | name 81 | pageCount 82 | author{ 83 | ...nameFragment 84 | } 85 | } 86 | updateBookRecord(input: { 87 | id: "book-3", 88 | name: "test updates", 89 | pageCount: 100 90 | 91 | }) { 92 | id 93 | } 94 | removeBookRecord(input: { 95 | id: "book-1" 96 | }) { 97 | id 98 | } 99 | } 100 | fragment nameFragment on Author { 101 | firstName 102 | lastName 103 | } 104 | ''' 105 | 106 | String sdl = TestStaticResources.TEST_SCHEMA 107 | schema = HelperBuildTestSchema.buildSchema(sdl) 108 | 109 | authzInstrumentation = AuthzInstrumentation.builder() 110 | .configuration(authzClientConfiguration) 111 | .schema(schema) 112 | .scopeProvider(scopeProvider) 113 | .authzListener(null) 114 | .build() 115 | 116 | GraphQL.Builder builder = GraphQL.newGraphQL(schema) 117 | builder.instrumentation(authzInstrumentation) 118 | graphql = builder.build() 119 | } 120 | 121 | def "test authorization with some redactions with list"() { 122 | 123 | given: 124 | String sdl = TestStaticResources.TEST_SCHEMA 125 | def schema = HelperBuildTestSchema.buildSchema(sdl) 126 | def authzClientConfiguration = new HelperAuthzClientConfiguration() 127 | def scopeProvider = new HelperScopeProvider() 128 | 129 | def authzInstrumentation = AuthzInstrumentation.builder() 130 | .configuration(authzClientConfiguration) 131 | .schema(schema) 132 | .scopeProvider(scopeProvider) 133 | .authzListener(null) 134 | .build() 135 | 136 | GraphQL.Builder builder = GraphQL.newGraphQL(schema) 137 | builder.instrumentation(authzInstrumentation) 138 | def graphql = builder.build() 139 | def requestAllBooks = ''' 140 | { 141 | allBooks { 142 | id 143 | name 144 | pageCount 145 | author { 146 | firstName 147 | lastName 148 | } 149 | rating { 150 | comments 151 | stars 152 | } 153 | } 154 | } 155 | ''' 156 | def executionInput = ExecutionInput.newExecutionInput().query(requestAllBooks).context("Test.client6").build() 157 | 158 | when: 159 | def result = graphql.execute(executionInput) 160 | 161 | then: 162 | def errors = result.getErrors().collect { it.getMessage() } 163 | def data = result.getData().toString() 164 | 165 | expect: 166 | errors.contains("403 - Not authorized to access field=lastName of type=Author") 167 | errors.contains("403 - Not authorized to access field=pageCount of type=Book") 168 | errors.contains("403 - Not authorized to access field=rating of type=Book") 169 | 170 | data.contains("[id:book-1, name:Harry Potter and the Philosopher's Stone, author:[firstName:Joanne]]") 171 | data.contains("[id:book-2, name:Moby Dick, author:[firstName:Herman]]") 172 | data.contains("[id:book-3, name:Interview with the vampire, author:[firstName:Anne]]") 173 | } 174 | 175 | def "test authz with no client configuration"() { 176 | given: 177 | final AuthzClientConfiguration authzClientConfiguration = new AuthzClientConfiguration() { 178 | @Override 179 | Map> getQueriesByClient() { 180 | return [:] 181 | } 182 | } 183 | when: 184 | AuthzInstrumentation.builder() 185 | .configuration(authzClientConfiguration) 186 | .schema(schema) 187 | .scopeProvider(new HelperScopeProvider()) 188 | .build() 189 | 190 | then: 191 | def exception = thrown(IllegalArgumentException) 192 | exception.message == "Clients missing from AuthZClientConfiguration" 193 | } 194 | 195 | 196 | void "test authz Introspection With Some Redactions"() { 197 | given: 198 | def requestAllFieldsWithIntrospection = ''' 199 | { 200 | bookById(id: "book-2") { 201 | __typename 202 | id 203 | name 204 | pageCount 205 | author { 206 | __typename 207 | firstName 208 | lastName 209 | } 210 | rating { 211 | __typename 212 | comments 213 | stars 214 | } 215 | } 216 | } 217 | ''' 218 | def executionInput = ExecutionInput.newExecutionInput() 219 | .query(requestAllFieldsWithIntrospection) 220 | .context("Test.client2") 221 | .build() 222 | 223 | and: 224 | def result = graphql.execute(executionInput) 225 | def errors = result.errors 226 | def dataString = result.data.toString() 227 | 228 | expect: 229 | errors[0].message.contains("403 - Not authorized to access field=lastName of type=Author") 230 | errors[1].message.contains("403 - Not authorized to access field=rating of type=Book") 231 | dataString == "[bookById:[__typename:Book, id:book-2, name:Moby Dick, pageCount:635, author:[__typename:Author, firstName:Herman]]]" 232 | } 233 | 234 | 235 | void "test authz happy case"() { 236 | given: 237 | def requestWithAllowedFields = ''' 238 | { 239 | bookById(id: "book-2") { 240 | id 241 | name 242 | pageCount 243 | author { 244 | firstName 245 | } 246 | } 247 | } 248 | ''' 249 | def executionInput = ExecutionInput.newExecutionInput() 250 | .query(requestWithAllowedFields) 251 | .context("Test.client2") 252 | .build(); 253 | 254 | and: 255 | def result = graphql.execute(executionInput) 256 | def dataString = result.data.toString() 257 | 258 | expect: 259 | result.errors.size() == 0 260 | dataString == "[bookById:[id:book-2, name:Moby Dick, pageCount:635, author:[firstName:Herman]]]" 261 | } 262 | 263 | 264 | void "test authz happy case all fields"() { 265 | given: 266 | def requestAllFields = ''' 267 | { 268 | bookById(id: "book-2") { 269 | __typename 270 | id 271 | name 272 | pageCount 273 | author { 274 | __typename 275 | firstName 276 | lastName 277 | } 278 | rating { 279 | __typename 280 | comments 281 | stars 282 | } 283 | } 284 | } 285 | ''' 286 | def executionInput = ExecutionInput.newExecutionInput() 287 | .query(requestAllFields) 288 | .context("Test.client1") 289 | .build() 290 | 291 | and: 292 | def result = graphql.execute(executionInput) 293 | def dataString = result.data.toString() 294 | 295 | expect: 296 | result.errors.size() == 0 297 | dataString == "[bookById:[__typename:Book, id:book-2, name:Moby Dick, pageCount:635, author:[__typename:Author, firstName:Herman, lastName:Melville], rating:[__typename:Rating, comments:Excellent, stars:5]]]" 298 | } 299 | 300 | 301 | void "test authz happy case all fields with fragments"() { 302 | given: 303 | def requestWithFragments = ''' 304 | { 305 | bookById(id: "book-3") { 306 | id 307 | name 308 | pageCount 309 | author { 310 | ...nameFragment 311 | } 312 | rating { 313 | comments 314 | stars 315 | } 316 | } 317 | } 318 | fragment nameFragment on Author { 319 | firstName 320 | lastName 321 | } 322 | ''' 323 | def executionInput = ExecutionInput.newExecutionInput() 324 | .query(requestWithFragments) 325 | .context("Test.client1") 326 | .build() 327 | 328 | and: 329 | def result = graphql.execute(executionInput) 330 | def dataString = result.data.toString() 331 | 332 | expect: 333 | result.errors.size() == 0 334 | dataString == "[bookById:[id:book-3, name:Interview with the vampire, pageCount:371, author:[firstName:Anne, lastName:Rice], rating:[comments:OK, stars:3]]]" 335 | 336 | } 337 | 338 | 339 | void "test no Authz"() { 340 | given: 341 | def requestAllFields = ''' 342 | { 343 | bookById(id: "book-2") { 344 | __typename 345 | id 346 | name 347 | pageCount 348 | author { 349 | __typename 350 | firstName 351 | lastName 352 | } 353 | rating { 354 | __typename 355 | comments 356 | stars 357 | } 358 | } 359 | } 360 | ''' 361 | def executionInput = ExecutionInput.newExecutionInput() 362 | .query(requestAllFields) 363 | .context("") 364 | .build() 365 | 366 | and: 367 | def result = graphql.execute(executionInput) 368 | def errors = result.errors 369 | 370 | expect: 371 | errors.size() == 1 372 | errors[0].getMessage() == "403 - Not authorized to access field=bookById of type=Query" 373 | } 374 | 375 | 376 | void "test authz with invalid scope"() { 377 | given: 378 | def requestAllFields = ''' 379 | { 380 | bookById(id: "book-2") { 381 | __typename 382 | id 383 | name 384 | pageCount 385 | author { 386 | __typename 387 | firstName 388 | lastName 389 | } 390 | rating { 391 | __typename 392 | comments 393 | stars 394 | } 395 | } 396 | } 397 | ''' 398 | def executionInput = ExecutionInput.newExecutionInput() 399 | .query(requestAllFields) 400 | .context("INV001") 401 | .build() 402 | 403 | and: 404 | def result = graphql.execute(executionInput) 405 | def errors = result.errors 406 | 407 | expect: 408 | errors.size() == 1 409 | errors[0].getMessage() == "403 - Not authorized to access field=bookById of type=Query" 410 | } 411 | 412 | 413 | void "test authz multi scopes"() { 414 | given: 415 | def requestAllFields = ''' 416 | { 417 | bookById(id: "book-2") { 418 | __typename 419 | id 420 | name 421 | pageCount 422 | author { 423 | __typename 424 | firstName 425 | lastName 426 | } 427 | rating { 428 | __typename 429 | comments 430 | stars 431 | } 432 | } 433 | } 434 | ''' 435 | def executionInput = ExecutionInput.newExecutionInput() 436 | .query(requestAllFields) 437 | .context("Test.client3,Test.client2") 438 | .build() 439 | 440 | and: 441 | def result = graphql.execute(executionInput) 442 | def errors = result.errors 443 | def dataString = result.data.toString() 444 | 445 | expect: 446 | errors[0].getMessage().contains("403 - Not authorized to access field=lastName of type=Author") 447 | dataString == "[bookById:[__typename:Book, id:book-2, name:Moby Dick, pageCount:635, author:[__typename:Author, firstName:Herman], rating:[__typename:Rating, comments:Excellent, stars:5]]]" 448 | } 449 | 450 | 451 | void "test authz with invalid field"() { 452 | given: 453 | def requestWithInvalidFields = ''' 454 | { 455 | bookById(id: "book-2") { 456 | id 457 | userName 458 | pageCount 459 | author { 460 | firstName 461 | } 462 | } 463 | } 464 | ''' 465 | def executionInput = ExecutionInput.newExecutionInput() 466 | .query(requestWithInvalidFields) 467 | .context("Test.client2") 468 | .build() 469 | 470 | and: 471 | def result = graphql.execute(executionInput) 472 | def errors = result.errors 473 | 474 | expect: 475 | errors.size() == 1 476 | result.data == null 477 | errors[0].getMessage().contains("Validation error (FieldUndefined@[bookById/userName]) : Field 'userName' in type 'Book' is undefined") 478 | } 479 | 480 | 481 | void "test authz with mutation"() { 482 | given: 483 | def executionInput = ExecutionInput.newExecutionInput() 484 | .query(mutationQuery) 485 | .context("Test.client4") 486 | .build() 487 | 488 | and: 489 | def result = graphql.execute(executionInput) 490 | def errors = result.errors 491 | 492 | expect: 493 | errors.size() == 3 494 | errors[0].getMessage().contains("403 - Not authorized to access field=pageCount of type=Book") 495 | errors[1].getMessage().contains("403 - Not authorized to access field=lastName of type=Author") 496 | errors[2].getMessage().contains("403 - Not authorized to access field=updateBookRecord of type=Mutation") 497 | result.data.toString() == "[createNewBookRecord:[id:Book-7, name:New World, author:[firstName:Mickey]], removeBookRecord:[id:book-1]]" 498 | } 499 | 500 | 501 | void "test authz with mutation multi scopes"() { 502 | given: 503 | def executionInput = ExecutionInput.newExecutionInput() 504 | .query(mutationQuery) 505 | .context("Test.client4,Test.client2") 506 | .build() 507 | 508 | and: 509 | def result = graphql.execute(executionInput) 510 | def errors = result.errors 511 | 512 | expect: 513 | result.data.toString() == "[createNewBookRecord:[id:Book-7, name:New World, pageCount:1001, author:[firstName:Mickey]], updateBookRecord:[id:book-3], removeBookRecord:[id:book-1]]" 514 | errors.size() == 1 515 | errors[0].getMessage().contains("403 - Not authorized to access field=lastName of type=Author") 516 | } 517 | 518 | 519 | public void "test authz with mutation multi scopes2"() { 520 | given: 521 | def executionInput = ExecutionInput.newExecutionInput() 522 | .query(mutationQuery) 523 | .context("CCC03,Test.client2") 524 | .build() 525 | 526 | and: 527 | def result = graphql.execute(executionInput) 528 | def errors = result.errors 529 | 530 | expect: 531 | result.data.toString() == "[updateBookRecord:[id:book-3]]" 532 | errors.size() == 2 533 | errors[0].getMessage().contains("403 - Not authorized to access field=createNewBookRecord of type=Mutation") 534 | errors[1].getMessage().contains("403 - Not authorized to access field=removeBookRecord of type=Mutation") 535 | } 536 | 537 | def "test authz with mutation no access"() { 538 | given: 539 | def executionInput = ExecutionInput.newExecutionInput() 540 | .query(mutationQuery) 541 | .context("CCC03") 542 | .build() 543 | 544 | and: 545 | def result = graphql.execute(executionInput) 546 | def errors = result.errors 547 | 548 | expect: 549 | errors[0].message .contains("403 - Not authorized to access field=createNewBookRecord of type=Mutation") 550 | errors[1].message.contains("403 - Not authorized to access field=updateBookRecord of type=Mutation") 551 | errors[2].message.contains("403 - Not authorized to access field=removeBookRecord of type=Mutation") 552 | result.data.toString() == "[:]" 553 | } 554 | 555 | def "test authz with mutation no scope"() { 556 | given: 557 | def executionInput = ExecutionInput.newExecutionInput() 558 | .query(mutationQuery) 559 | .context("") 560 | .build() 561 | 562 | and: 563 | def result = graphql.execute(executionInput) 564 | def errors = result.errors 565 | 566 | expect: 567 | errors[0].message.contains("403 - Not authorized to access field=createNewBookRecord of type=Mutation") 568 | errors[1].message.contains("403 - Not authorized to access field=updateBookRecord of type=Mutation") 569 | errors[2].message.contains("403 - Not authorized to access field=removeBookRecord of type=Mutation") 570 | result.data.toString() == "[:]" 571 | } 572 | 573 | def "test authz with mutation and fragments"() { 574 | given: 575 | def executionInput = ExecutionInput.newExecutionInput() 576 | .query(fragmentsInMutationQuery) 577 | .context("Test.client4") 578 | .build() 579 | 580 | and: 581 | def result = graphql.execute(executionInput) 582 | def errors = result.errors 583 | 584 | expect: 585 | errors.size() == 3 586 | errors[1].message.contains("403 - Not authorized to access field=updateBookRecord of type=Mutation") 587 | errors[0].message.contains("403 - Not authorized to access field=pageCount of type=Book") 588 | errors[2].message.contains("403 - Not authorized to access field=lastName of type=Author") 589 | result.data.toString() == "[createNewBookRecord:[id:Book-7, name:New World, author:[firstName:Mickey]], removeBookRecord:[id:book-1]]" 590 | } 591 | 592 | def "test authz with mutation non oauth2"() { 593 | given: 594 | def executionInput = ExecutionInput.newExecutionInput() 595 | .query(fragmentsInMutationQuery) 596 | .context("Test.client5") 597 | .build() 598 | 599 | and: 600 | def result = graphql.execute(executionInput) 601 | def errors = result.errors 602 | 603 | expect: 604 | errors.size() == 3 605 | errors[1].message.contains("403 - Not authorized to access field=updateBookRecord of type=Mutation") 606 | errors[0].message.contains("403 - Not authorized to access field=pageCount of type=Book") 607 | errors[2].message.contains("403 - Not authorized to access field=lastName of type=Author") 608 | result.data.toString() == "[createNewBookRecord:[id:Book-7, name:New World, author:[firstName:Mickey]], removeBookRecord:[id:book-1]]" 609 | } 610 | 611 | def "test introspection with test client2"() { 612 | given: 613 | def executionInput = ExecutionInput.newExecutionInput() 614 | .query(IntrospectionQuery.INTROSPECTION_QUERY) 615 | .context("Test.client2") 616 | .build() 617 | 618 | and: 619 | def result = graphql.execute(executionInput) 620 | def errors = result.errors 621 | GsonBuilder builder = new GsonBuilder() 622 | Gson gson = builder.create() 623 | JsonElement res = gson.toJsonTree(result.toSpecification()) 624 | JsonObject jsonres = res.getAsJsonObject().get("data").getAsJsonObject().get("__schema").getAsJsonObject() 625 | JsonArray types = jsonres.get("types").getAsJsonArray() 626 | 627 | expect: 628 | errors.size() == 0 629 | jsonres.size() == 4 630 | jsonres.get("queryType").toString() == "{\"name\":\"Query\"}" 631 | jsonres.get("mutationType").toString() =="{\"name\":\"Mutation\"}" 632 | types.size() == 19 633 | 634 | hasValue(types, "kind", "OBJECT", "name", "Author").booleanValue() 635 | hasValue(types, "kind", "OBJECT", "name", "Book").booleanValue() 636 | hasValue(types, "kind", "OBJECT", "name", "Query").booleanValue() 637 | hasValue(types, "kind", "OBJECT", "name", "Mutation").booleanValue() 638 | hasValue(types, "kind", "INPUT_OBJECT", "name", "BookID").booleanValue() 639 | hasValue(types, "kind", "INPUT_OBJECT", "name", "BookInput").booleanValue() 640 | hasValue(types, "kind", "INPUT_OBJECT", "name", "AuthorInput").booleanValue() 641 | 642 | getFields(types, "Query") == ["bookById"] 643 | getFields(types, "Author") == ["firstName"] 644 | getFields(types, "Book") == ["id", "name", "pageCount", "author"] 645 | getFields(types, "Mutation") == ["updateBookRecord"] 646 | } 647 | 648 | def "test introspection without scope"() { 649 | given: 650 | def executionInput = ExecutionInput.newExecutionInput() 651 | .query(IntrospectionQuery.INTROSPECTION_QUERY) 652 | .context("") 653 | .build() 654 | 655 | and: 656 | def result = graphql.execute(executionInput) 657 | GsonBuilder builder = new GsonBuilder() 658 | Gson gson = builder.create() 659 | JsonElement res = gson.toJsonTree(result.toSpecification()) 660 | JsonObject jsonres = res.getAsJsonObject().get("data").getAsJsonObject().get("__schema").getAsJsonObject() 661 | JsonArray types = jsonres.get("types").getAsJsonArray() 662 | 663 | expect: 664 | result.errors.size() == 0 665 | jsonres.size() == 4 666 | jsonres.get("queryType").toString() == "{\"name\":\"Query\"}" 667 | jsonres.get("mutationType").toString() == "{\"name\":\"Mutation\"}" 668 | types.size() == 15 669 | ! hasValue(types, "kind", "OBJECT", "name", "Author").booleanValue() 670 | ! hasValue(types, "kind", "OBJECT", "name", "Book").booleanValue() 671 | ! hasValue(types, "kind", "OBJECT", "name", "Query").booleanValue() 672 | ! hasValue(types, "kind", "OBJECT", "name", "Mutation").booleanValue() 673 | ! hasValue(types, "kind", "OBJECT", "name", "Rating").booleanValue() 674 | hasValue(types, "kind", "INPUT_OBJECT", "name", "BookID").booleanValue() 675 | hasValue(types, "kind", "INPUT_OBJECT", "name", "BookInput").booleanValue() 676 | hasValue(types, "kind", "INPUT_OBJECT", "name", "AuthorInput").booleanValue() 677 | } 678 | 679 | def "test introspection with multi scopes"() { 680 | given: 681 | def executionInput = ExecutionInput.newExecutionInput() 682 | .query(IntrospectionQuery.INTROSPECTION_QUERY) 683 | .context("Test.client4,Test.client2") 684 | .build() 685 | 686 | and: 687 | def result = graphql.execute(executionInput) 688 | GsonBuilder builder = new GsonBuilder() 689 | Gson gson = builder.create() 690 | JsonElement res = gson.toJsonTree(result.toSpecification()) 691 | JsonObject jsonres = res.getAsJsonObject().get("data").getAsJsonObject().get("__schema").getAsJsonObject() 692 | JsonArray types = jsonres.get("types").getAsJsonArray() 693 | 694 | expect: 695 | result.errors.size() == 0 696 | jsonres.size() == 4 697 | jsonres.get("queryType").toString() == "{\"name\":\"Query\"}" 698 | jsonres.get("mutationType").toString() == "{\"name\":\"Mutation\"}" 699 | types.size() == 19 700 | hasValue(types, "kind", "OBJECT", "name", "Author").booleanValue() 701 | hasValue(types, "kind", "OBJECT", "name", "Book").booleanValue() 702 | hasValue(types, "kind", "OBJECT", "name", "Query").booleanValue() 703 | hasValue(types, "kind", "OBJECT", "name", "Mutation").booleanValue() 704 | hasValue(types, "kind", "INPUT_OBJECT", "name", "BookID").booleanValue() 705 | hasValue(types, "kind", "INPUT_OBJECT", "name", "BookInput").booleanValue() 706 | hasValue(types, "kind", "INPUT_OBJECT", "name", "AuthorInput").booleanValue() 707 | getFields(types, "Query") == ["bookById"] 708 | getFields(types, "Author") == ["firstName"] 709 | getFields(types, "Book") == ["id", "name", "pageCount", "author"] 710 | getFields(types, "Mutation") == ["createNewBookRecord", "updateBookRecord", "removeBookRecord"] 711 | } 712 | 713 | def hasValue(JsonArray array, String key1, String value1, String key2, String value2) { 714 | for (element in array) { 715 | def obj = element.getAsJsonObject() 716 | if (obj.get(key1).getAsString() == value1 && obj.get(key2).getAsString() == value2) { 717 | return true 718 | } 719 | } 720 | return false 721 | } 722 | 723 | def getFields(JsonArray array, String fieldName) { 724 | def fields = [] 725 | array.iterator().each { element -> 726 | def jsonObject = element.getAsJsonObject() 727 | if (jsonObject.get("name").getAsString() == fieldName) { 728 | def fieldArray = jsonObject.getAsJsonArray("fields") 729 | fieldArray.iterator().each { fieldElement -> 730 | def fieldObject = fieldElement.getAsJsonObject() 731 | fields << fieldObject.get("name").getAsString() 732 | } 733 | } 734 | } 735 | return fields 736 | } 737 | 738 | } 739 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/context/ExecutionScopeFetcherTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.context; 2 | 3 | import static org.junit.Assert.assertTrue; 4 | 5 | import com.intuit.graphql.authorization.util.ScopeProvider; 6 | import graphql.schema.GraphQLObjectType; 7 | import org.junit.Test; 8 | import org.mockito.Mock; 9 | 10 | public class ExecutionScopeFetcherTest { 11 | 12 | ScopeProvider scopeProvider = new ScopeProvider() { 13 | }; 14 | 15 | @Mock 16 | GraphQLObjectType graphQLObjectType; 17 | 18 | 19 | @Test 20 | public void getScopesByDefault() { 21 | 22 | assertTrue(scopeProvider.getScopes(graphQLObjectType).isEmpty()); 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/AuthZListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static junit.framework.TestCase.assertEquals; 4 | import static junit.framework.TestCase.assertTrue; 5 | 6 | import com.intuit.graphql.authorization.config.AuthzClientConfiguration; 7 | import com.intuit.graphql.authorization.util.TestStaticResources; 8 | import graphql.ExecutionInput; 9 | import graphql.ExecutionResult; 10 | import graphql.GraphQL; 11 | import graphql.analysis.QueryVisitorFieldEnvironment; 12 | import graphql.execution.ExecutionContext; 13 | import graphql.schema.GraphQLSchema; 14 | import org.junit.Before; 15 | import org.junit.Test; 16 | 17 | public class AuthZListenerTest { 18 | 19 | 20 | private GraphQL graphql; 21 | private AuthzInstrumentation instrumentation; 22 | private TestAuthZListener authzListener; 23 | private AuthzClientConfiguration authzClientConfiguration; 24 | private String requestAllFields; 25 | private String requestWithFragments; 26 | private String requestWithInvalidFragment; 27 | 28 | 29 | @Before 30 | public void init() { 31 | 32 | requestAllFields = HelperUtils.readString("queries/requestAllFields.graphql"); 33 | requestWithFragments = HelperUtils.readString("queries/requestWithFragments.graphql"); 34 | requestWithInvalidFragment = HelperUtils.readString("queries/requestWithInvalidFragment.graphql"); 35 | 36 | //Executable Schema 37 | String sdl = TestStaticResources.TEST_SCHEMA; 38 | GraphQLSchema executableSchema = HelperBuildTestSchema.buildSchema(sdl); 39 | 40 | authzListener = new TestAuthZListener(); 41 | authzClientConfiguration = new HelperAuthzClientConfiguration(); 42 | instrumentation = AuthzInstrumentation.builder() 43 | .configuration(authzClientConfiguration) 44 | .schema(executableSchema) 45 | .scopeProvider(new HelperScopeProvider()) 46 | .authzListener(authzListener) 47 | .build(); 48 | 49 | 50 | GraphQL.Builder builder = GraphQL.newGraphQL(executableSchema); 51 | builder.instrumentation(instrumentation); 52 | graphql = builder.build(); 53 | } 54 | 55 | @Test 56 | public void authZWithSomeRedactionTest() { 57 | ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(requestAllFields).context("Test.client2") 58 | .build(); 59 | 60 | ExecutionResult result = graphql.execute(executionInput); 61 | 62 | assertTrue(result.getErrors().get(0).getMessage() 63 | .contains("403 - Not authorized to access field=lastName of type=Author")); 64 | assertTrue( 65 | result.getErrors().get(1).getMessage().contains("403 - Not authorized to access field=rating of type=Book")); 66 | assertTrue(result.getData().toString() 67 | .equals("{bookById={__typename=Book, id=book-2, name=Moby Dick, pageCount=635, author={__typename=Author, firstName=Herman}}}")); 68 | 69 | assertEquals(authzListener.countOnFieldRedaction, 2); 70 | assertEquals(authzListener.countOnEnforcement, 1); 71 | assertEquals(authzListener.countOnCreatingState, 1); 72 | } 73 | 74 | 75 | @Test 76 | public void authZWithNoFieldRedactionTest() { 77 | ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(requestAllFields).context("Test.client1") 78 | .build(); 79 | 80 | ExecutionResult result = graphql.execute(executionInput); 81 | 82 | assertTrue(result.getErrors().size() == 0); 83 | 84 | assertTrue(result.getData().toString().equals( 85 | "{bookById={__typename=Book, id=book-2, name=Moby Dick, pageCount=635, author={__typename=Author, firstName=Herman, lastName=Melville}, rating={__typename=Rating, comments=Excellent, stars=5}}}")); 86 | assertEquals(authzListener.countOnFieldRedaction, 0); 87 | assertEquals(authzListener.countOnEnforcement, 1); 88 | assertEquals(authzListener.countOnCreatingState, 1); 89 | } 90 | 91 | @Test 92 | public void authzWithFragmentRedactionTest() { 93 | ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(requestWithInvalidFragment) 94 | .context("Test.client2").build(); 95 | 96 | ExecutionResult result = graphql.execute(executionInput); 97 | 98 | assertTrue(result.getErrors().size() == 1); 99 | assertTrue(result.getErrors().get(0).getMessage() 100 | .contains("403 - Not authorized to access field=lastName of type=Author")); 101 | assertTrue(result.getData().toString().equals( 102 | "{bookById={id=book-3, name=Interview with the vampire, author={firstName=Anne}}}")); 103 | assertEquals(authzListener.countOnFieldRedaction, 1); 104 | assertEquals(authzListener.countOnEnforcement, 1); 105 | assertEquals(authzListener.countOnCreatingState, 1); 106 | } 107 | 108 | @Test 109 | public void authzNoFragmentRedactionTest() { 110 | ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(requestWithFragments) 111 | .context("Test.client1").build(); 112 | 113 | ExecutionResult result = graphql.execute(executionInput); 114 | 115 | assertTrue(result.getErrors().size() == 0); 116 | assertTrue(result.getData().toString().equals( 117 | "{bookById={id=book-3, name=Interview with the vampire, pageCount=371, author={firstName=Anne, lastName=Rice}, rating={comments=OK, stars=3}}}")); 118 | assertEquals(authzListener.countOnFieldRedaction, 0); 119 | assertEquals(authzListener.countOnEnforcement, 1); 120 | assertEquals(authzListener.countOnCreatingState, 1); 121 | } 122 | 123 | @Test 124 | public void noAuthZTest() { 125 | ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(requestAllFields).context("").build(); 126 | ExecutionResult result = graphql.execute(executionInput); 127 | 128 | assertTrue(result.getErrors().size() == 1); 129 | assertTrue( 130 | result.getErrors().get(0).getMessage().contains("403 - Not authorized to access field=bookById of type=Query")); 131 | assertEquals(authzListener.countOnFieldRedaction, 1); 132 | assertEquals(authzListener.countOnEnforcement, 1); 133 | assertEquals(authzListener.countOnCreatingState, 1); 134 | } 135 | 136 | 137 | @Test 138 | public void authzWithInvalidScopeTest() { 139 | ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(requestAllFields).context("invalid") 140 | .build(); 141 | ExecutionResult result = graphql.execute(executionInput); 142 | 143 | assertTrue(result.getErrors().size() == 1); 144 | assertTrue( 145 | result.getErrors().get(0).getMessage().contains("403 - Not authorized to access field=bookById of type=Query")); 146 | assertEquals(authzListener.countOnFieldRedaction, 1); 147 | assertEquals(authzListener.countOnEnforcement, 1); 148 | assertEquals(authzListener.countOnCreatingState, 1); 149 | } 150 | 151 | 152 | static class TestAuthZListener extends SimpleAuthZListener { 153 | 154 | int countOnFieldRedaction = 0; 155 | int countOnCreatingState = 0; 156 | int countOnEnforcement = 0; 157 | 158 | @Override 159 | public void onFieldRedaction(ExecutionContext executionContext, 160 | QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) { 161 | countOnFieldRedaction = countOnFieldRedaction + 1; 162 | } 163 | 164 | @Override 165 | public void onCreatingState(GraphQLSchema schema, ExecutionInput executionInput) { 166 | countOnCreatingState = countOnCreatingState + 1; 167 | } 168 | 169 | @Override 170 | public void onEnforcement(ExecutionContext originalExecutionContext, 171 | ExecutionContext enforcedExecutionContext) { 172 | countOnEnforcement = countOnEnforcement + 1; 173 | } 174 | } 175 | 176 | } 177 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/HelperAuthzClientConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import com.intuit.graphql.authorization.config.AuthzClient; 4 | import com.intuit.graphql.authorization.config.AuthzClientConfiguration; 5 | import java.io.IOException; 6 | import java.util.Arrays; 7 | import java.util.Collections; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | public class HelperAuthzClientConfiguration implements AuthzClientConfiguration { 13 | 14 | //Queries By Client 15 | public static Map> queriesByClient = new HashMap<>(); 16 | 17 | static { 18 | 19 | try { 20 | AuthzClient client1 = HelperUtils 21 | .yamlMapper().readValue(HelperUtils.read("mocks.graphqlauthz/client/client1.yml"), AuthzClient.class); 22 | AuthzClient client2 = HelperUtils 23 | .yamlMapper().readValue(HelperUtils.read("mocks.graphqlauthz/client/client2.yml"), AuthzClient.class); 24 | AuthzClient client3 = HelperUtils 25 | .yamlMapper().readValue(HelperUtils.read("mocks.graphqlauthz/client/client3.yml"), AuthzClient.class); 26 | AuthzClient client4 = HelperUtils 27 | .yamlMapper().readValue(HelperUtils.read("mocks.graphqlauthz/client/client4.yml"), AuthzClient.class); 28 | AuthzClient client5 = HelperUtils 29 | .yamlMapper().readValue(HelperUtils.read("mocks.graphqlauthz/client/client5-pa.yml"), AuthzClient.class); 30 | AuthzClient client6 = HelperUtils 31 | .yamlMapper().readValue(HelperUtils.read("mocks.graphqlauthz/client/client6.yml"), AuthzClient.class); 32 | 33 | queriesByClient.put(client1, Collections.singletonList( 34 | HelperUtils.readString("mocks.graphqlauthz/client/client1-permissions.graphql") 35 | )); 36 | queriesByClient.put(client2, Arrays.asList( 37 | HelperUtils.readString("mocks.graphqlauthz/client/client2-permissions-query.graphql"), 38 | HelperUtils.readString("mocks.graphqlauthz/client/client2-permissions-mutation.graphql") 39 | )); 40 | queriesByClient.put(client3, Arrays.asList( 41 | HelperUtils.readString("mocks.graphqlauthz/client/client3-permissions-query.graphql"))); 42 | queriesByClient.put(client4, Arrays.asList( 43 | HelperUtils.readString("mocks.graphqlauthz/client/client4-permissions-query.graphql"), 44 | HelperUtils.readString("mocks.graphqlauthz/client/client4-permissions-mutation1.graphql"), 45 | HelperUtils.readString("mocks.graphqlauthz/client/client4-permissions-mutation2.graphql") 46 | )); 47 | queriesByClient.put(client5, Arrays.asList( 48 | HelperUtils.readString("mocks.graphqlauthz/client/client5-permissions-query.graphql"), 49 | HelperUtils.readString("mocks.graphqlauthz/client/client5-permissions-mutation1.graphql"), 50 | HelperUtils.readString("mocks.graphqlauthz/client/client5-permissions-mutation2.graphql") 51 | )); 52 | queriesByClient.put(client6, Arrays.asList( 53 | HelperUtils.readString("mocks.graphqlauthz/client/client6-permissions-query.graphql") 54 | )); 55 | } catch (IOException e) { 56 | e.printStackTrace(); 57 | } 58 | } 59 | 60 | @Override 61 | public Map> getQueriesByClient() { 62 | return queriesByClient; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/HelperBuildTestSchema.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring; 4 | 5 | import graphql.schema.GraphQLSchema; 6 | import graphql.schema.idl.RuntimeWiring; 7 | import graphql.schema.idl.SchemaGenerator; 8 | import graphql.schema.idl.SchemaParser; 9 | import graphql.schema.idl.TypeDefinitionRegistry; 10 | 11 | public class HelperBuildTestSchema { 12 | 13 | static HelperGraphQLDataFetchers helperGraphQLDataFetchers = new HelperGraphQLDataFetchers(); 14 | 15 | public static GraphQLSchema buildSchema(String sdl) { 16 | TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl); 17 | RuntimeWiring runtimeWiring = buildWiring(); 18 | SchemaGenerator schemaGenerator = new SchemaGenerator(); 19 | return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring); 20 | } 21 | 22 | public static RuntimeWiring buildWiring() { 23 | return RuntimeWiring.newRuntimeWiring() 24 | .type(newTypeWiring("Query") 25 | .dataFetcher("bookById", helperGraphQLDataFetchers.getBookByIdDataFetcher())) 26 | .type(newTypeWiring("Query") 27 | .dataFetcher("allBooks", helperGraphQLDataFetchers.allBooksDataFetcher())) 28 | .type(newTypeWiring("Book") 29 | .dataFetcher("author", helperGraphQLDataFetchers.getAuthorDataFetcher())) 30 | .type(newTypeWiring("Book") 31 | .dataFetcher("rating", helperGraphQLDataFetchers.getRatingDataFetcher())) 32 | .type(newTypeWiring("Mutation") 33 | .dataFetcher("createNewBookRecord", helperGraphQLDataFetchers.addBookDataFetcher())) 34 | .type(newTypeWiring("Mutation") 35 | .dataFetcher("updateBookRecord", helperGraphQLDataFetchers.updateBookDataFetcher())) 36 | .type(newTypeWiring("Mutation") 37 | .dataFetcher("removeBookRecord", helperGraphQLDataFetchers.removeBookDataFetcher())) 38 | .build(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/HelperGraphQLDataFetchers.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | 4 | import com.google.common.collect.ImmutableMap; 5 | import graphql.schema.DataFetcher; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | 12 | public class HelperGraphQLDataFetchers { 13 | 14 | private static List> books = new ArrayList<>( 15 | Arrays.asList(ImmutableMap.of("id", "book-1", 16 | "name", "Harry Potter and the Philosopher's Stone", 17 | "pageCount", "223", 18 | "authorId", "author-1"), 19 | ImmutableMap.of("id", "book-2", 20 | "name", "Moby Dick", 21 | "pageCount", "635", 22 | "authorId", "author-2"), 23 | ImmutableMap.of("id", "book-3", 24 | "name", "Interview with the vampire", 25 | "pageCount", "371", 26 | "authorId", "author-3"))); 27 | 28 | private static List> authors = new ArrayList<>( 29 | Arrays.asList(ImmutableMap.of("id", "author-1", 30 | "firstName", "Joanne", 31 | "lastName", "Rowling"), 32 | ImmutableMap.of("id", "author-2", 33 | "firstName", "Herman", 34 | "lastName", "Melville"), 35 | ImmutableMap.of("id", "author-3", 36 | "firstName", "Anne", 37 | "lastName", "Rice") 38 | )); 39 | 40 | private static List> ratings = Arrays.asList( 41 | ImmutableMap.of("id", "book-1", 42 | "comments", "Good", 43 | "stars", "4"), 44 | ImmutableMap.of("id", "book-2", 45 | "comments", "Excellent", 46 | "stars", "5"), 47 | ImmutableMap.of("id", "book-3", 48 | "comments", "OK", 49 | "stars", "3") 50 | ); 51 | 52 | public DataFetcher getBookByIdDataFetcher() { 53 | return dataFetchingEnvironment -> { 54 | String bookId = dataFetchingEnvironment.getArgument("id"); 55 | return books 56 | .stream() 57 | .filter(book -> book.get("id").equals(bookId)) 58 | .findFirst() 59 | .orElse(null); 60 | }; 61 | } 62 | 63 | public DataFetcher allBooksDataFetcher() { 64 | return dataFetchingEnvironment -> books; 65 | } 66 | 67 | public DataFetcher getAuthorDataFetcher() { 68 | return dataFetchingEnvironment -> { 69 | Map book = dataFetchingEnvironment.getSource(); 70 | String authorId = book.get("authorId"); 71 | return authors 72 | .stream() 73 | .filter(author -> author.get("id").equals(authorId)) 74 | .findFirst() 75 | .orElse(null); 76 | }; 77 | } 78 | 79 | public DataFetcher getRatingDataFetcher() { 80 | return dataFetchingEnvironment -> { 81 | Map book = dataFetchingEnvironment.getSource(); 82 | String bookId = book.get("id"); 83 | return ratings 84 | .stream() 85 | .filter(rating -> rating.get("id").equals(bookId)) 86 | .findFirst() 87 | .orElse(null); 88 | }; 89 | } 90 | 91 | public DataFetcher addBookDataFetcher() { 92 | return dataFetchingEnvironment -> { 93 | Map bookInput = dataFetchingEnvironment.getArgument("input"); 94 | String bookId = bookInput.get("id").toString(); 95 | Map authorInfo = (Map) bookInput.get("author"); 96 | 97 | books.add(ImmutableMap.of("id", bookId, 98 | "name", bookInput.get("name").toString(), 99 | "pageCount", bookInput.get("pageCount").toString(), 100 | "authorId", authorInfo.get("id").toString())); 101 | 102 | authors.add(ImmutableMap.of("id", authorInfo.get("id").toString(), 103 | "firstName", authorInfo.get("firstName").toString(), 104 | "lastName", authorInfo.get("lastName").toString())); 105 | 106 | return books 107 | .stream() 108 | .filter(book1 -> book1.get("id").equals(bookId)) 109 | .findFirst() 110 | .orElse(null); 111 | }; 112 | } 113 | 114 | public DataFetcher updateBookDataFetcher() { 115 | return dataFetchingEnvironment -> { 116 | Map book = dataFetchingEnvironment.getArgument("input"); 117 | String bookId = book.get("id"); 118 | books.add(ImmutableMap.of("id", bookId, 119 | "name", book.get("name"), 120 | "pageCount", book.get("pageCount"))); 121 | return books 122 | .stream() 123 | .filter(book1 -> book1.get("id").equals(bookId)) 124 | .findFirst() 125 | .orElse(null); 126 | }; 127 | } 128 | 129 | public DataFetcher removeBookDataFetcher() { 130 | return dataFetchingEnvironment -> { 131 | Map book = dataFetchingEnvironment.getArgument("input"); 132 | String bookId = book.get("id"); 133 | Map b = books 134 | .stream() 135 | .filter(book1 -> book1.get("id").equals(bookId)) 136 | .findFirst() 137 | .orElse(null); 138 | 139 | if (b != null) { 140 | books.remove(b); 141 | } 142 | return book; 143 | }; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/HelperScopeProvider.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import com.intuit.graphql.authorization.util.ScopeProvider; 4 | import java.util.Arrays; 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | import org.apache.commons.lang3.StringUtils; 8 | 9 | public class HelperScopeProvider implements ScopeProvider { 10 | public Set getScopes(Object o) { 11 | return new HashSet(Arrays.asList(StringUtils.split(o.toString(),","))); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/HelperUtils.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; 6 | import com.google.common.io.Resources; 7 | import lombok.SneakyThrows; 8 | 9 | public class HelperUtils { 10 | 11 | private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory()) 12 | .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 13 | 14 | public static ObjectMapper yamlMapper() { 15 | return YAML_MAPPER; 16 | } 17 | 18 | @SneakyThrows 19 | public static byte[] read(String path) { 20 | return Resources.toByteArray(Resources.getResource(path)); 21 | } 22 | 23 | public static String readString(String path) { 24 | return new String(read(path)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/IntrospectionRedactingDataFetcherTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | public class IntrospectionRedactingDataFetcherTest { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/RedactingVisitorTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | import static org.mockito.ArgumentMatchers.any; 5 | import static org.mockito.ArgumentMatchers.eq; 6 | import static org.mockito.Mockito.times; 7 | import static org.mockito.Mockito.verify; 8 | import static org.mockito.Mockito.when; 9 | 10 | import com.intuit.graphql.authorization.extension.AuthorizationExtension; 11 | import com.intuit.graphql.authorization.extension.FieldAuthorizationResult; 12 | import com.intuit.graphql.authorization.util.ScopeProvider; 13 | import graphql.GraphQLError; 14 | import graphql.GraphqlErrorException; 15 | import graphql.analysis.QueryVisitorFieldEnvironment; 16 | import graphql.execution.ExecutionContext; 17 | import graphql.language.Field; 18 | import graphql.schema.GraphQLFieldDefinition; 19 | import graphql.schema.GraphQLObjectType; 20 | import graphql.schema.GraphQLSchema; 21 | import graphql.util.NodeZipper; 22 | import graphql.util.TraverserContext; 23 | import java.util.ArrayDeque; 24 | import java.util.ArrayList; 25 | import java.util.Collections; 26 | import java.util.List; 27 | import java.util.Queue; 28 | import org.junit.Before; 29 | import org.junit.Test; 30 | import org.junit.runner.RunWith; 31 | import org.mockito.Mock; 32 | import org.mockito.junit.MockitoJUnitRunner; 33 | 34 | @RunWith(MockitoJUnitRunner.class) 35 | public class RedactingVisitorTest { 36 | 37 | @Mock 38 | private AuthzInstrumentation.AuthzInstrumentationState instrumentationState; 39 | @Mock 40 | private ExecutionContext executionContext; 41 | @Mock 42 | private AuthzListener authzListener; 43 | @Mock 44 | private AuthorizationExtension authorizationExtension; 45 | @Mock 46 | private TypeFieldPermissionVerifier typeFieldPermissionVerifier; 47 | @Mock 48 | private GraphQLSchema graphQLSchema; 49 | @Mock 50 | private TraverserContext traverserContext; 51 | @Mock 52 | private NodeZipper nodeZipper; 53 | 54 | Queue zippers = new ArrayDeque<>(); 55 | 56 | @Mock 57 | private QueryVisitorFieldEnvironment queryVisitorFieldEnvironment; 58 | 59 | @Mock 60 | private ScopeProvider scopeProvider; 61 | 62 | @Mock 63 | private GraphQLFieldDefinition fieldDefinition; 64 | 65 | private static final GraphQLObjectType PARENT_TYPE = GraphQLObjectType.newObject().name("ParentType").build(); 66 | private static final Field FIELD = Field.newField("foo").build(); 67 | 68 | private RedactingVisitor subjectUnderTest; 69 | 70 | private List graphQLErrorList = new ArrayList<>(); 71 | 72 | @Before 73 | public void setup() { 74 | 75 | when(nodeZipper.deleteNode()).thenReturn(nodeZipper); 76 | when(traverserContext.getVar(NodeZipper.class)).thenReturn(nodeZipper); 77 | when(traverserContext.getSharedContextData()).thenReturn(zippers); 78 | 79 | when(instrumentationState.getTypeFieldPermissionVerifier()).thenReturn(typeFieldPermissionVerifier); 80 | when(instrumentationState.getAuthzErrors()).thenReturn(graphQLErrorList); 81 | 82 | subjectUnderTest = new RedactingVisitor(instrumentationState, executionContext, authzListener, 83 | authorizationExtension, scopeProvider); 84 | 85 | when(queryVisitorFieldEnvironment.getParentType()).thenReturn(PARENT_TYPE); 86 | when(queryVisitorFieldEnvironment.getFieldDefinition()).thenReturn(fieldDefinition); 87 | when(queryVisitorFieldEnvironment.getField()).thenReturn(FIELD); 88 | when(queryVisitorFieldEnvironment.getArguments()).thenReturn(Collections.emptyMap()); 89 | when(queryVisitorFieldEnvironment.getSchema()).thenReturn(graphQLSchema); 90 | when(queryVisitorFieldEnvironment.getTraverserContext()).thenReturn(traverserContext); 91 | } 92 | 93 | @Test 94 | public void visitField_typeFieldPermitted_authExtensionNotAllowed() { 95 | // GIVEN 96 | GraphqlErrorException graphqlErrorException = GraphqlErrorException.newErrorException().build(); 97 | 98 | when(typeFieldPermissionVerifier.isPermitted(eq(PARENT_TYPE), eq(fieldDefinition))) 99 | .thenReturn(true); 100 | when(authorizationExtension.authorize(any())).thenReturn(FieldAuthorizationResult.createDeniedResult(graphqlErrorException)); 101 | 102 | // WHEN 103 | subjectUnderTest.visitField(queryVisitorFieldEnvironment); 104 | 105 | // THEN 106 | verify(queryVisitorFieldEnvironment, times(2)).getFieldDefinition(); 107 | verify(typeFieldPermissionVerifier, times(1)).isPermitted(any(), any()); 108 | verify(authzListener, times(1)).onFieldRedaction(any(), any()); 109 | verify(nodeZipper, times(1)).deleteNode(); 110 | 111 | assertThat(graphQLErrorList).hasSize(1); 112 | assertThat(graphQLErrorList.get(0)).isSameAs(graphqlErrorException); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/TypeAndFieldAuthorizationHolderTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import com.intuit.graphql.authorization.config.AuthzClientConfiguration; 6 | import com.intuit.graphql.authorization.util.TestStaticResources; 7 | import graphql.schema.GraphQLFieldDefinition; 8 | import graphql.schema.GraphQLFieldsContainer; 9 | import graphql.schema.GraphQLSchema; 10 | import java.io.IOException; 11 | import java.util.Arrays; 12 | import java.util.HashSet; 13 | import java.util.Set; 14 | import org.junit.Before; 15 | import org.junit.Rule; 16 | import org.junit.Test; 17 | import org.junit.runner.RunWith; 18 | import org.mockito.junit.MockitoJUnit; 19 | import org.mockito.junit.MockitoJUnitRunner; 20 | import org.mockito.junit.MockitoRule; 21 | 22 | @RunWith(MockitoJUnitRunner.class) 23 | 24 | public class TypeAndFieldAuthorizationHolderTest { 25 | 26 | @Rule 27 | public MockitoRule mockitoRule = MockitoJUnit.rule(); 28 | GraphQLFieldsContainer queryType, bookType; 29 | GraphQLFieldDefinition bookInfo, authorInfo, ratingInfo; 30 | private AuthorizationHolder authorizationHolder; 31 | private AuthzClientConfiguration authzClientConfiguration; 32 | private GraphQLSchema schema; 33 | 34 | @Before 35 | public void init() throws IOException { 36 | 37 | String sdl = TestStaticResources.TEST_SCHEMA; 38 | schema = HelperBuildTestSchema.buildSchema(sdl); 39 | authzClientConfiguration = new HelperAuthzClientConfiguration(); 40 | queryType = (GraphQLFieldsContainer) schema.getType("Query"); 41 | bookType = (GraphQLFieldsContainer) schema.getType("Book"); 42 | bookInfo = queryType.getFieldDefinition("bookById"); 43 | authorInfo = bookType.getFieldDefinition("author"); 44 | ratingInfo = bookType.getFieldDefinition("rating"); 45 | 46 | this.authorizationHolder = new AuthorizationHolder( 47 | AuthzInstrumentation.getAuthorizationFactory(schema).parse(authzClientConfiguration.getQueriesByClient())); 48 | 49 | } 50 | 51 | @Test 52 | public void parsesCorrectConfiguration() { 53 | assertThat(authorizationHolder).isNotNull(); 54 | } 55 | 56 | @Test 57 | public void unknownScopeHasNoPermissions() { 58 | Set scopes = new HashSet(Arrays.asList("Test.unknown")); 59 | TypeFieldPermissionVerifier verifier = authorizationHolder.getPermissionsVerifier(scopes, schema); 60 | assertThat(verifier.isPermitted(bookType)).isFalse(); 61 | assertThat(verifier.isPermitted(queryType, bookInfo)).isFalse(); 62 | assertThat(verifier.isPermitted(bookType, authorInfo)).isFalse(); 63 | } 64 | 65 | @Test 66 | public void validScopeHasCorrectPermissions() { 67 | 68 | Set scopes = new HashSet(Arrays.asList("Test.client2")); 69 | TypeFieldPermissionVerifier verifier = authorizationHolder.getPermissionsVerifier(scopes, schema); 70 | assertThat(verifier.isPermitted(queryType)).isTrue(); 71 | assertThat(verifier.isPermitted(bookType)).isTrue(); 72 | assertThat(verifier.isPermitted(queryType, bookInfo)).isTrue(); 73 | assertThat(verifier.isPermitted(bookType, authorInfo)).isTrue(); 74 | assertThat(verifier.isPermitted(bookType, ratingInfo)).isFalse(); 75 | } 76 | 77 | @Test 78 | public void multipleScopesHaveMorePermissions() { 79 | Set scopes = new HashSet(Arrays.asList("Test.client2", "Test.client1")); 80 | TypeFieldPermissionVerifier verifier = authorizationHolder.getPermissionsVerifier(scopes, schema); 81 | assertThat(verifier.isPermitted(queryType)).isTrue(); 82 | assertThat(verifier.isPermitted(bookType)).isTrue(); 83 | assertThat(verifier.isPermitted(queryType, bookInfo)).isTrue(); 84 | assertThat(verifier.isPermitted(bookType, authorInfo)).isTrue(); 85 | assertThat(verifier.isPermitted(bookType, ratingInfo)).isTrue(); 86 | 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/enforcement/TypeFieldPermissionVerifierTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.enforcement; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import graphql.Scalars; 6 | import graphql.schema.GraphQLFieldDefinition; 7 | import graphql.schema.GraphQLNamedType; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.mockito.Mock; 11 | import org.mockito.junit.MockitoJUnitRunner; 12 | 13 | @RunWith(MockitoJUnitRunner.class) 14 | public class TypeFieldPermissionVerifierTest { 15 | 16 | PermissionVerifier permissionsVerifier = new PermissionVerifier() { 17 | }; 18 | 19 | @Mock 20 | GraphQLNamedType type; 21 | 22 | @Mock 23 | GraphQLFieldDefinition fieldDefinition; 24 | 25 | @Test 26 | public void isPermittedTypeReturnsFalseByDefault() { 27 | assertThat(permissionsVerifier.isPermitted(type)).isFalse(); 28 | } 29 | 30 | @Test 31 | public void isPermittedTypeAndFieldReturnsFalseByDefault() { 32 | assertThat(permissionsVerifier.isPermitted(type, fieldDefinition)).isFalse(); 33 | } 34 | 35 | @Test 36 | public void isPermittedInputTypeReturnsFalseByDefault() { 37 | assertThat(new TypeFieldPermissionVerifier(null, null) 38 | .isPermitted(Scalars.GraphQLString, fieldDefinition)) 39 | .isTrue(); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/rules/AuthorizationHolderFactoryTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 5 | import static org.mockito.ArgumentMatchers.any; 6 | import static org.mockito.ArgumentMatchers.anyString; 7 | import static org.mockito.Mockito.mock; 8 | import static org.mockito.Mockito.when; 9 | 10 | import com.intuit.graphql.authorization.config.AuthzClient; 11 | import graphql.schema.GraphQLObjectType; 12 | import graphql.schema.GraphQLSchema; 13 | import java.util.Arrays; 14 | import java.util.Collections; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.Set; 19 | import org.junit.Test; 20 | 21 | public class AuthorizationHolderFactoryTest { 22 | 23 | @Test 24 | public void failsToParseRules() { 25 | RuleParser ruleParser = mock(RuleParser.class); 26 | 27 | when(ruleParser.parseRule(anyString(), any(InvalidFieldsCollector.class))) 28 | .thenThrow(new RuntimeException("boom")); 29 | 30 | AuthorizationHolderFactory factory = new AuthorizationHolderFactory(ruleParser); 31 | 32 | Map> queriesByClient = new HashMap<>(); 33 | 34 | AuthzClient client = new AuthzClient(); 35 | client.setId("test-id"); 36 | 37 | queriesByClient.put(client, Collections.singletonList("test-query")); 38 | 39 | final Map>> result = factory 40 | .parse(queriesByClient); 41 | assertThat(result).isEmpty(); 42 | } 43 | 44 | @Test 45 | public void unknownFieldDuringParseRule() { 46 | GraphQLObjectType queryTypeMock = mock(GraphQLObjectType.class); 47 | 48 | GraphQLSchema graphQLSchemaMock = mock(GraphQLSchema.class); 49 | when(graphQLSchemaMock.getQueryType()).thenReturn(queryTypeMock); 50 | 51 | QueryRuleParser ruleParser = new QueryRuleParser(graphQLSchemaMock); 52 | AuthorizationHolderFactory factory = new AuthorizationHolderFactory(ruleParser); 53 | 54 | Map> queriesByClient = new HashMap<>(); 55 | 56 | AuthzClient client = new AuthzClient(); 57 | client.setId("test-id"); 58 | 59 | queriesByClient.put(client, Collections.singletonList("query { thisIsInValidField }")); 60 | 61 | final Map>> result = factory 62 | .parse(queriesByClient); 63 | assertThat(result).isEmpty(); 64 | } 65 | 66 | @Test 67 | public void mergesMultipleRules() { 68 | final RuleParser mockRuleParser = mock(RuleParser.class); 69 | 70 | Map> allowedTypesAndFields = new HashMap<>(); 71 | allowedTypesAndFields.put("type1", Collections.emptySet()); 72 | 73 | Map> secondTypesAndFields = new HashMap<>(); 74 | 75 | secondTypesAndFields.put("type2", Collections.emptySet()); 76 | 77 | when(mockRuleParser.parseRule(any(), any(InvalidFieldsCollector.class))) 78 | .thenReturn(allowedTypesAndFields) 79 | .thenReturn(secondTypesAndFields); 80 | 81 | AuthorizationHolderFactory factory = new AuthorizationHolderFactory(mockRuleParser); 82 | 83 | Map> queriesByClient = new HashMap<>(); 84 | AuthzClient client = new AuthzClient(); 85 | client.setId("test-id"); 86 | 87 | List queries = Arrays.asList("test-query", "second-query"); 88 | queriesByClient.put(client, queries); 89 | 90 | final Map>> result = factory.parse(queriesByClient); 91 | 92 | assertThat(result.get("test-id")).hasSize(2); 93 | } 94 | 95 | @Test 96 | public void noRuleParsers() { 97 | assertThatThrownBy(() -> new AuthorizationHolderFactory(null)).isInstanceOf(NullPointerException.class); 98 | } 99 | 100 | @Test 101 | public void returnsTypeMapForValidRules() { 102 | final RuleParser mockRuleParser = mock(RuleParser.class); 103 | 104 | Map> allowedTypesAndFields = new HashMap<>(); 105 | allowedTypesAndFields.put("type", Collections.emptySet()); 106 | 107 | when(mockRuleParser.parseRule(any(), any(InvalidFieldsCollector.class))) 108 | .thenReturn(allowedTypesAndFields); 109 | 110 | AuthorizationHolderFactory factory = new AuthorizationHolderFactory(mockRuleParser); 111 | 112 | Map> queriesByClient = new HashMap<>(); 113 | AuthzClient client = new AuthzClient(); 114 | client.setId("test-id"); 115 | 116 | List queries = Collections.singletonList("test-query"); 117 | queriesByClient.put(client, queries); 118 | 119 | final Map>> result = factory.parse(queriesByClient); 120 | 121 | assertThat(result).isNotEmpty(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/rules/InvalidFieldsCollectorTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | import static org.mockito.Mockito.mock; 5 | import static org.mockito.Mockito.when; 6 | 7 | import graphql.language.Field; 8 | import graphql.schema.FieldCoordinates; 9 | import graphql.schema.GraphQLFieldsContainer; 10 | import java.util.Set; 11 | import org.junit.Test; 12 | 13 | public class InvalidFieldsCollectorTest { 14 | 15 | private InvalidFieldsCollector subjectUnderTest = new InvalidFieldsCollector(); 16 | 17 | @Test 18 | public void collectsInvalidFieldsTest() { 19 | GraphQLFieldsContainer parentTypeMock = mock(GraphQLFieldsContainer.class); 20 | when(parentTypeMock.getName()).thenReturn("ParentTypeName"); 21 | Field fieldMock = mock(Field.class); 22 | when(fieldMock.getName()).thenReturn("fieldName"); 23 | 24 | subjectUnderTest.onQueryParsingError(parentTypeMock, fieldMock); 25 | 26 | Set actualInvalidField = subjectUnderTest.getInvalidFields(); 27 | assertThat(actualInvalidField).containsOnly(FieldCoordinates.coordinates("ParentTypeName","fieldName")); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/rules/QueryRuleParserTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.rules; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.Mockito.times; 5 | import static org.mockito.Mockito.verify; 6 | 7 | import com.intuit.graphql.authorization.enforcement.HelperBuildTestSchema; 8 | import com.intuit.graphql.authorization.util.TestStaticResources; 9 | import graphql.language.Field; 10 | import graphql.schema.GraphQLFieldsContainer; 11 | import java.util.HashSet; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.Map.Entry; 15 | import java.util.Set; 16 | import org.assertj.core.api.Assertions; 17 | import org.junit.Test; 18 | import org.junit.runner.RunWith; 19 | import org.mockito.ArgumentCaptor; 20 | import org.mockito.Mock; 21 | import org.mockito.junit.MockitoJUnitRunner; 22 | 23 | @RunWith(MockitoJUnitRunner.class) 24 | public class QueryRuleParserTest { 25 | 26 | @Mock 27 | private InvalidFieldsCollector invalidFieldsCollectorMock; 28 | 29 | @Test 30 | public void testQueryRuleParserOneUnknownFieldInQuery() { 31 | QueryRuleParser queryRuleParser = new QueryRuleParser( 32 | HelperBuildTestSchema.buildSchema(TestStaticResources.TEST_SCHEMA)); 33 | 34 | final Map> graphQLTypeSetMap = queryRuleParser.parseRule("{ unknownField { id }}", invalidFieldsCollectorMock); 35 | 36 | Assertions.assertThat(graphQLTypeSetMap).hasSize(0); 37 | 38 | ArgumentCaptor acParentType = ArgumentCaptor.forClass(GraphQLFieldsContainer.class); 39 | ArgumentCaptor acField = ArgumentCaptor.forClass(Field.class); 40 | verify(invalidFieldsCollectorMock, times(1)).onQueryParsingError(acParentType.capture(), acField.capture()); 41 | 42 | Assertions.assertThat(acParentType.getValue().getName()).isEqualTo("Query"); 43 | Assertions.assertThat(acField.getValue().getName()).isEqualTo("unknownField"); 44 | 45 | verify(invalidFieldsCollectorMock, times(1)).onQueryParsingError(any(), any()); 46 | } 47 | 48 | @Test 49 | public void testQueryRuleParserOneUnknownFieldAndOneValidFieldInQuery() { 50 | QueryRuleParser queryRuleParser = new QueryRuleParser( 51 | HelperBuildTestSchema.buildSchema(TestStaticResources.TEST_SCHEMA)); 52 | 53 | final Map> graphQLTypeSetMap = queryRuleParser.parseRule("{ unknownField { id } bookById { id } }", invalidFieldsCollectorMock); 54 | 55 | Assertions.assertThat(graphQLTypeSetMap).hasSize(2); 56 | final Set query = getFromMap(graphQLTypeSetMap, "Query"); 57 | Assertions.assertThat(query) 58 | .hasSize(1); 59 | 60 | Assertions.assertThat(query) 61 | .containsOnlyOnce("bookById"); 62 | 63 | final Set book = getFromMap(graphQLTypeSetMap, "Book"); 64 | Assertions.assertThat(book) 65 | .hasSize(1); 66 | 67 | Assertions.assertThat(book) 68 | .containsOnlyOnce("id"); 69 | 70 | 71 | ArgumentCaptor acParentType = ArgumentCaptor.forClass(GraphQLFieldsContainer.class); 72 | ArgumentCaptor acField = ArgumentCaptor.forClass(Field.class); 73 | verify(invalidFieldsCollectorMock, times(1)).onQueryParsingError(acParentType.capture(), acField.capture()); 74 | 75 | Assertions.assertThat(acParentType.getValue().getName()).isEqualTo("Query"); 76 | Assertions.assertThat(acField.getValue().getName()).isEqualTo("unknownField"); 77 | 78 | verify(invalidFieldsCollectorMock, times(1)).onQueryParsingError(any(), any()); 79 | } 80 | 81 | @Test 82 | public void testQueryRuleParserMultipleUnknownFieldInQuery() { 83 | QueryRuleParser queryRuleParser = new QueryRuleParser( 84 | HelperBuildTestSchema.buildSchema(TestStaticResources.TEST_SCHEMA)); 85 | 86 | String testQuery = "{ unknownField1 { child1 } unknownField2 { child2 } }"; 87 | final Map> graphQLTypeSetMap = queryRuleParser.parseRule(testQuery, invalidFieldsCollectorMock); 88 | 89 | Assertions.assertThat(graphQLTypeSetMap).hasSize(0); 90 | 91 | ArgumentCaptor acParentType = ArgumentCaptor.forClass(GraphQLFieldsContainer.class); 92 | ArgumentCaptor acField = ArgumentCaptor.forClass(Field.class); 93 | verify(invalidFieldsCollectorMock, times(2)).onQueryParsingError(acParentType.capture(), acField.capture()); 94 | 95 | List actualFieldContainers = acParentType.getAllValues(); 96 | List actualFields = acField.getAllValues(); 97 | Assertions.assertThat(actualFieldContainers.get(0).getName()).isEqualTo("Query"); 98 | Assertions.assertThat(actualFieldContainers.get(1).getName()).isEqualTo("Query"); 99 | Assertions.assertThat(actualFields.get(0).getName()).isEqualTo("unknownField1"); 100 | Assertions.assertThat(actualFields.get(1).getName()).isEqualTo("unknownField2"); 101 | 102 | verify(invalidFieldsCollectorMock, times(2)).onQueryParsingError(any(), any()); 103 | } 104 | 105 | @Test 106 | public void testQueryRuleParser() { 107 | QueryRuleParser queryRuleParser = new QueryRuleParser( 108 | HelperBuildTestSchema.buildSchema(TestStaticResources.TEST_SCHEMA)); 109 | final Map> graphQLTypeSetMap = queryRuleParser 110 | .parseRule(TestStaticResources.TEST_RULE_QUERY, invalidFieldsCollectorMock); 111 | 112 | Assertions.assertThat(graphQLTypeSetMap).hasSize(4); 113 | 114 | final Set query = getFromMap(graphQLTypeSetMap, "Query"); 115 | Assertions.assertThat(query) 116 | .hasSize(2); 117 | Assertions.assertThat(query).containsOnlyOnce("bookById", "allBooks"); 118 | 119 | final Set author = getFromMap(graphQLTypeSetMap, "Author"); 120 | Assertions.assertThat(author) 121 | .hasSize(3); 122 | Assertions.assertThat(author) 123 | .containsOnlyOnce("firstName", "lastName", "__typename"); 124 | 125 | final Set rating = getFromMap(graphQLTypeSetMap, "Rating"); 126 | Assertions.assertThat(rating) 127 | .hasSize(3); 128 | Assertions.assertThat(rating) 129 | .containsOnlyOnce("comments", "stars", "__typename"); 130 | 131 | final Set book = getFromMap(graphQLTypeSetMap, "Book"); 132 | Assertions.assertThat(book) 133 | .hasSize(6); 134 | 135 | Assertions.assertThat(book) 136 | .containsOnlyOnce("name", "id", "author", "rating", "pageCount", "__typename"); 137 | 138 | } 139 | 140 | @Test(expected = graphql.parser.InvalidSyntaxException.class) 141 | public void testQueryRuleParserWithInvalidQuery() { 142 | QueryRuleParser queryRuleParser = new QueryRuleParser( 143 | HelperBuildTestSchema.buildSchema(TestStaticResources.TEST_SCHEMA)); 144 | 145 | String invalidGraphQLQuery = "not a valid graphql query"; 146 | queryRuleParser.parseRule(invalidGraphQLQuery, invalidFieldsCollectorMock); 147 | } 148 | 149 | private Set getFromMap(Map> graphQLTypeSetMap, 150 | String name) { 151 | 152 | for (Entry> entry : graphQLTypeSetMap.entrySet()) { 153 | String key = entry.getKey(); 154 | Set value = entry.getValue(); 155 | if (key.equals(name)) { 156 | return value; 157 | } 158 | } 159 | return new HashSet<>(); 160 | } 161 | 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/util/FieldCoordinatesFormattingUtilTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.util; 2 | 3 | import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; 4 | 5 | import graphql.schema.FieldCoordinates; 6 | import java.util.Collections; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | import org.junit.Test; 10 | 11 | public class FieldCoordinatesFormattingUtilTest { 12 | 13 | @Test 14 | public void toStringTestEmpty() { 15 | String actual = FieldCoordinatesFormattingUtil.toString(Collections.emptySet()); 16 | assertThat(actual).isEqualTo(""); 17 | } 18 | 19 | @Test 20 | public void toStringTestNullInput() { 21 | String actual = FieldCoordinatesFormattingUtil.toString(null); 22 | assertThat(actual).isEqualTo(""); 23 | } 24 | 25 | @Test 26 | public void toStringTestOneFieldCoordinate() { 27 | Set fieldCoordinatesSet = new HashSet<>(); 28 | fieldCoordinatesSet.add(FieldCoordinates.coordinates("TestParentType", "testFieldName")); 29 | String actual = FieldCoordinatesFormattingUtil.toString(fieldCoordinatesSet); 30 | assertThat(actual).isEqualTo("TestParentType.testFieldName"); 31 | } 32 | 33 | @Test 34 | public void toStringTestMoreThatOneFieldCoordinate() { 35 | Set fieldCoordinatesSet = new HashSet<>(); 36 | fieldCoordinatesSet.add(FieldCoordinates.coordinates("TestParentType1", "testFieldName1")); 37 | fieldCoordinatesSet.add(FieldCoordinates.coordinates("TestParentType2", "testFieldName2")); 38 | String actual = FieldCoordinatesFormattingUtil.toString(fieldCoordinatesSet); 39 | assertThat(actual).isEqualTo("TestParentType1.testFieldName1,TestParentType2.testFieldName2"); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/util/GraphQLUtilTest.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.util; 2 | 3 | 4 | import graphql.Scalars; 5 | import graphql.introspection.Introspection; 6 | import graphql.language.Field; 7 | import graphql.language.OperationDefinition; 8 | import graphql.language.OperationDefinition.Operation; 9 | import graphql.language.SelectionSet; 10 | import graphql.schema.GraphQLFieldDefinition; 11 | import graphql.schema.GraphQLList; 12 | import graphql.schema.GraphQLNonNull; 13 | import graphql.schema.GraphQLObjectType; 14 | import graphql.schema.GraphQLSchema; 15 | import org.assertj.core.api.Assertions; 16 | import org.junit.Test; 17 | 18 | public class GraphQLUtilTest { 19 | 20 | final static GraphQLFieldDefinition fieldDefinition = GraphQLFieldDefinition.newFieldDefinition().name("foo") 21 | .type(Scalars.GraphQLString).build(); 22 | final static GraphQLSchema schema = GraphQLSchema.newSchema() 23 | .query(GraphQLObjectType.newObject().name("myQuery").field( 24 | fieldDefinition).build()) 25 | .mutation(GraphQLObjectType.newObject().name("myMutation").field( 26 | fieldDefinition).build()) 27 | .subscription(GraphQLObjectType.newObject().name("mySubscription").field( 28 | fieldDefinition).build()) 29 | .build(); 30 | 31 | @Test 32 | public void isOperationTypeTest() { 33 | schema.getMutationType(); 34 | Assertions.assertThat(GraphQLUtil.isOperationType(schema.getMutationType(), schema)).isTrue(); 35 | Assertions.assertThat(GraphQLUtil.isOperationType(schema.getQueryType(), schema)).isTrue(); 36 | Assertions.assertThat(GraphQLUtil.isOperationType(schema.getSubscriptionType(), schema)).isTrue(); 37 | Assertions.assertThat(GraphQLUtil.isOperationType(GraphQLObjectType.newObject().name("query").build(), schema)) 38 | .isFalse(); 39 | } 40 | 41 | @Test 42 | public void getRootTypeFromOperationDefinition() { 43 | final OperationDefinition query = OperationDefinition.newOperationDefinition().operation(Operation.QUERY) 44 | .build(); 45 | final OperationDefinition mutation = OperationDefinition.newOperationDefinition().operation(Operation.MUTATION) 46 | .build(); 47 | final OperationDefinition subscription = OperationDefinition.newOperationDefinition() 48 | .operation(Operation.SUBSCRIPTION) 49 | .build(); 50 | Assertions.assertThat(GraphQLUtil.getRootTypeFromOperation(query, schema).getName()).isEqualTo("myQuery"); 51 | Assertions.assertThat(GraphQLUtil.getRootTypeFromOperation(mutation, schema).getName()).isEqualTo("myMutation"); 52 | Assertions.assertThat(GraphQLUtil.getRootTypeFromOperation(subscription, schema).getName()) 53 | .isEqualTo("mySubscription"); 54 | 55 | final OperationDefinition none = OperationDefinition.newOperationDefinition().build(); 56 | Assertions.assertThatThrownBy(() -> GraphQLUtil.getRootTypeFromOperation(none, schema)).isInstanceOf( 57 | NullPointerException.class); 58 | 59 | } 60 | 61 | @Test 62 | public void isIntrospection__TypeTest() { 63 | Assertions.assertThat(GraphQLUtil.isIntrospection__Type(Introspection.__Type)).isTrue(); 64 | Assertions.assertThat(GraphQLUtil.isIntrospection__Type(GraphQLNonNull.nonNull((Introspection.__Type)))).isTrue(); 65 | Assertions.assertThat( 66 | GraphQLUtil.isIntrospection__Type(GraphQLNonNull.nonNull(GraphQLObjectType.newObject().name("fool").build()))) 67 | .isFalse(); 68 | Assertions.assertThat(GraphQLUtil.isIntrospection__Type(GraphQLObjectType.newObject().name("fool").build())) 69 | .isFalse(); 70 | } 71 | 72 | @Test 73 | public void isListOfIntrospection__TypeTest() { 74 | Assertions.assertThat(GraphQLUtil.isListOfIntrospection__Type(Introspection.__Type)).isFalse(); 75 | Assertions.assertThat(GraphQLUtil.isListOfIntrospection__Type(GraphQLNonNull.nonNull(Introspection.__Type))) 76 | .isFalse(); 77 | Assertions.assertThat(GraphQLUtil.isListOfIntrospection__Type(GraphQLList.list(Introspection.__Type))).isTrue(); 78 | Assertions.assertThat( 79 | GraphQLUtil.isListOfIntrospection__Type(GraphQLList.list(GraphQLNonNull.nonNull(Introspection.__Type)))) 80 | .isTrue(); 81 | Assertions.assertThat( 82 | GraphQLUtil.isListOfIntrospection__Type(GraphQLList.list(GraphQLObjectType.newObject().name("fool").build()))) 83 | .isFalse(); 84 | } 85 | 86 | @Test 87 | public void isNotEmptySelectionSet() { 88 | Assertions.assertThat(GraphQLUtil.isNotEmpty(SelectionSet.newSelectionSet().selection(new Field("foo")).build())) 89 | .isTrue(); 90 | Assertions.assertThat(GraphQLUtil.isNotEmpty(SelectionSet.newSelectionSet().build())).isFalse(); 91 | Assertions.assertThat(GraphQLUtil.isNotEmpty(null)).isFalse(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/test/java/com/intuit/graphql/authorization/util/TestStaticResources.java: -------------------------------------------------------------------------------- 1 | package com.intuit.graphql.authorization.util; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.io.Resources; 5 | import java.io.IOException; 6 | 7 | public class TestStaticResources { 8 | 9 | public static String TEST_SCHEMA = ""; 10 | public static String TEST_RULE_QUERY = ""; 11 | 12 | static { 13 | try { 14 | TEST_SCHEMA = Resources.toString(Resources.getResource("testschema.graphqls"), Charsets.UTF_8); 15 | TEST_RULE_QUERY = Resources.toString(Resources.getResource("test_rule_query.graphql"), Charsets.UTF_8); 16 | } catch (IOException e) { 17 | e.printStackTrace(); 18 | } 19 | } 20 | 21 | private TestStaticResources() { 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client1-permissions-mutation.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | createNewBookRecord 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client1-permissions.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | bookById { 3 | id 4 | name 5 | pageCount 6 | author { 7 | firstName 8 | lastName 9 | } 10 | rating{ 11 | comments 12 | stars 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client1.yml: -------------------------------------------------------------------------------- 1 | id: Test.client1 2 | description: this is a test 3 | type: OFFLINE 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client2-permissions-mutation.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | updateBookRecord 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client2-permissions-query.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | bookById{ 3 | id 4 | name 5 | pageCount 6 | author { 7 | firstName 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client2.yml: -------------------------------------------------------------------------------- 1 | id: Test.client2 2 | description: test 3 | type: OFFLINE 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client3-permissions-query.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | bookById{ 3 | id 4 | name 5 | pageCount 6 | rating{ 7 | comments 8 | stars 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client3.yml: -------------------------------------------------------------------------------- 1 | id: Test.client3 2 | description: this is test client3 3 | type: OFFLINE 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client4-permissions-mutation1.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | createNewBookRecord 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client4-permissions-mutation2.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | removeBookRecord 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client4-permissions-query.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | bookById{ 3 | id 4 | name 5 | author{ 6 | firstName 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client4.yml: -------------------------------------------------------------------------------- 1 | id: Test.client4 2 | description: this is a test 3 | type: OFFLINE 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client5-pa.yml: -------------------------------------------------------------------------------- 1 | id: Test.client5 2 | description: this is a test 3 | type: ONLINE 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client5-permissions-mutation1.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | createNewBookRecord 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client5-permissions-mutation2.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | removeBookRecord 3 | } 4 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client5-permissions-query.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | bookById{ 3 | id 4 | name 5 | author{ 6 | firstName 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client6-permissions-query.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | allBooks { 3 | id 4 | name 5 | author{ 6 | firstName 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/test/resources/mocks.graphqlauthz/client/client6.yml: -------------------------------------------------------------------------------- 1 | id: Test.client6 2 | description: this is a test 3 | type: OFFLINE 4 | -------------------------------------------------------------------------------- /src/test/resources/queries/mutationQuery.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | createNewBookRecord(input: { 3 | id: "Book-7", 4 | name: "New World", 5 | pageCount: 1001, 6 | author:{ 7 | id: "Author-7" 8 | firstName: "Mickey", 9 | lastName: "Mouse" 10 | } 11 | }) { 12 | id 13 | name 14 | pageCount 15 | author{ 16 | firstName 17 | lastName 18 | } 19 | } 20 | updateBookRecord(input: { 21 | id: "book-3", 22 | name: "test updates", 23 | pageCount: 100 24 | }) { 25 | id 26 | } 27 | removeBookRecord(input: { 28 | id: "book-1" 29 | }) { 30 | id 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/resources/queries/mutationQueryWithFragments.graphql: -------------------------------------------------------------------------------- 1 | mutation { 2 | createNewBookRecord(input: { 3 | id: "Book-7", 4 | name: "New World", 5 | pageCount: 1001, 6 | author:{ 7 | id: "Author-7" 8 | firstName: "Mickey", 9 | lastName: "Mouse" 10 | } 11 | }) { 12 | id 13 | name 14 | pageCount 15 | author{ 16 | ...nameFragment 17 | } 18 | } 19 | updateBookRecord(input: { 20 | id: "book-3", 21 | name: "test updates", 22 | pageCount: 100 23 | 24 | }) { 25 | id 26 | } 27 | removeBookRecord(input: { 28 | id: "book-1" 29 | }) { 30 | id 31 | } 32 | }fragment nameFragment on Author {firstName lastName} 33 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestAllBooks.graphql: -------------------------------------------------------------------------------- 1 | { 2 | allBooks { 3 | id 4 | name 5 | pageCount 6 | author { 7 | firstName 8 | lastName 9 | } 10 | rating { 11 | comments 12 | stars 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestAllFields.graphql: -------------------------------------------------------------------------------- 1 | { 2 | bookById(id: "book-2") { 3 | __typename 4 | id 5 | name 6 | pageCount 7 | author { 8 | __typename 9 | firstName 10 | lastName 11 | } 12 | rating { 13 | __typename 14 | comments 15 | stars 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestAllFieldsWithIntrospection.graphql: -------------------------------------------------------------------------------- 1 | { 2 | bookById(id: "book-2") { 3 | __typename 4 | id 5 | name 6 | pageCount 7 | author { 8 | __typename 9 | firstName 10 | lastName 11 | } 12 | rating { 13 | __typename 14 | comments 15 | stars 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestWithAllowedFields.graphql: -------------------------------------------------------------------------------- 1 | { 2 | bookById(id: "book-2") { 3 | id 4 | name 5 | pageCount 6 | author { 7 | firstName 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestWithFragments.graphql: -------------------------------------------------------------------------------- 1 | { 2 | bookById(id: "book-3") { 3 | id 4 | name 5 | pageCount 6 | author { 7 | ...nameFragment 8 | } 9 | rating { 10 | comments 11 | stars 12 | } 13 | } 14 | } 15 | fragment nameFragment on Author { 16 | firstName 17 | lastName 18 | } 19 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestWithInvalidFields.graphql: -------------------------------------------------------------------------------- 1 | { 2 | bookById(id: "book-2") { 3 | id 4 | userName 5 | pageCount 6 | author { 7 | firstName 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/resources/queries/requestWithInvalidFragment.graphql: -------------------------------------------------------------------------------- 1 | { 2 | bookById(id: "book-3") { 3 | id 4 | name 5 | author { 6 | ...nameFragment 7 | } 8 | } 9 | } 10 | fragment nameFragment on Author { 11 | firstName 12 | lastName 13 | } 14 | -------------------------------------------------------------------------------- /src/test/resources/test_rule_query.graphql: -------------------------------------------------------------------------------- 1 | query { 2 | allBooks { 3 | id 4 | name 5 | } 6 | bookById{ 7 | __typename 8 | id 9 | name 10 | pageCount 11 | author { 12 | __typename 13 | firstName 14 | lastName 15 | } 16 | rating{ 17 | __typename 18 | comments 19 | stars 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/resources/testschema.graphqls: -------------------------------------------------------------------------------- 1 | schema { 2 | query: Query 3 | mutation: Mutation 4 | } 5 | 6 | type Mutation{ 7 | createNewBookRecord(input: BookInput) : Book 8 | updateBookRecord(input: BookInput) : Book 9 | removeBookRecord(input: BookID!) : Book 10 | } 11 | 12 | type Query { 13 | bookById(id: ID!): Book 14 | allBooks: [Book] 15 | } 16 | 17 | type Book { 18 | id: ID 19 | name: String 20 | pageCount: Int 21 | author: Author 22 | rating: Rating 23 | } 24 | 25 | input BookInput { 26 | id: ID 27 | name: String 28 | pageCount: Int 29 | author: AuthorInput 30 | } 31 | 32 | input AuthorInput { 33 | id: ID 34 | firstName: String 35 | lastName: String 36 | } 37 | 38 | input BookID { 39 | id: ID 40 | } 41 | 42 | type Author { 43 | id: ID 44 | firstName: String 45 | lastName: String 46 | } 47 | 48 | type Rating { 49 | comments: String 50 | stars: String 51 | } --------------------------------------------------------------------------------