├── .github └── workflows │ ├── pr-pipeline.yml │ └── wiki-pipeline.yml ├── .gitignore ├── .nvmrc ├── CODEOWNERS ├── LICENSE ├── README.md ├── assets ├── jetbrains_spectral_config.png └── jetbrains_spectral_linting.png ├── jest.config.js ├── package-lock.json ├── package.json ├── rules ├── documentation │ ├── contact-information.spec.ts │ ├── contact-information.yml │ ├── info-description.spec.ts │ └── info-description.yml ├── endpoint │ ├── common-response-unauthorized.spec.ts │ ├── common-responses-unauthorized.yml │ ├── must-define-example-schema.spec.ts │ ├── must-define-example-schema.yml │ ├── no-http-verbs-in-resources.spec.ts │ ├── no-http-verbs-in-resources.yml │ ├── path-must-specify-tags.spec.ts │ └── path-must-specify-tags.yml └── general │ ├── must-have-path.spec.ts │ ├── must-have-path.yml │ ├── operation-tag-defined.spec.ts │ ├── operation-tag-defined.yml │ ├── path-must-match-api-standards.spec.ts │ ├── path-must-match-api-standards.yml │ ├── servers-must-match-api-standards.spec.ts │ └── servers-must-match-api-standards.yml ├── spectral-api.yml ├── spectral-async-api.yml ├── spectral-async-bounded-api.yml ├── spectral-async-product-api.yml ├── spectral-bff.yml ├── spectral-legacy.yml ├── spectral.yml ├── tsconfig.json └── util ├── scripts ├── checkApiTypeRules.sh ├── checkSpectralYaml.sh ├── generateDocs.sh └── mergeRules.sh └── setup-spectral.ts /.github/workflows/pr-pipeline.yml: -------------------------------------------------------------------------------- 1 | name: PR Pipeline 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | 7 | # Allows you to run this workflow manually from the Actions tab 8 | workflow_dispatch: 9 | 10 | jobs: 11 | checkRules: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | 17 | - name: install yq 18 | uses: mikefarah/yq@v4.18.1 19 | 20 | # Merge individual rules into spectral.yml 21 | - name: Merge rules 22 | run: bash ./util/scripts/mergeRules.sh 23 | 24 | # Check that the commited spectral.yml is up to date 25 | - name: Check spectral.yml 26 | run: bash ./util/scripts/checkSpectralYaml.sh 27 | 28 | # Check that all api types overwrite all rules of spectral.yml 29 | - name: Check spectral-*.yml 30 | run: bash ./util/scripts/checkApiTypeRules.sh 31 | 32 | runTests: 33 | runs-on: ubuntu-latest 34 | 35 | steps: 36 | - uses: actions/checkout@v2 37 | 38 | - name: Setup Node.js 39 | uses: actions/setup-node@v2 40 | with: 41 | node-version: '18' 42 | cache: npm 43 | 44 | - name: Install Dependencies 45 | run: npm ci 46 | 47 | - name: Run Tests 48 | run: npm run test -------------------------------------------------------------------------------- /.github/workflows/wiki-pipeline.yml: -------------------------------------------------------------------------------- 1 | name: Wiki Pipeline 2 | 3 | on: 4 | push: 5 | branches: 6 | - "main" 7 | 8 | # Allows you to run this workflow manually from the Actions tab 9 | workflow_dispatch: 10 | 11 | jobs: 12 | updateWiki: 13 | runs-on: ubuntu-latest 14 | env: 15 | working-directory: ./wiki 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | # Checking out the wiki repo under the path ./wiki/ 21 | - uses: actions/checkout@v2 22 | with: 23 | repository: ${{github.repository}}.wiki 24 | path: wiki 25 | 26 | - name: install yq 27 | uses: mikefarah/yq@v4.18.1 28 | 29 | # Generating the wiki pages from the comments inside the rules 30 | - name: generate docs 31 | run: bash ./util/scripts/generateDocs.sh ./rules ./wiki 32 | 33 | - name: set commit user 34 | working-directory: ${{env.working-directory}} 35 | run: git config --global user.email "wiki@pipeline" && git config --global user.name "Wiki Pipeline" 36 | 37 | - name: stage updates 38 | working-directory: ${{env.working-directory}} 39 | run: git add *.md 40 | 41 | - name: commit updates 42 | working-directory: ${{env.working-directory}} 43 | run: git commit -m "Generated Wiki" 44 | 45 | - name: push changes 46 | working-directory: ${{env.working-directory}} 47 | run: git push -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | demo* 3 | node_modules 4 | wiki 5 | .npmrc 6 | 7 | .DS_Store -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 18 -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @sn0wbi @markbrockhoff -------------------------------------------------------------------------------- /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 | # api-linter-rules 2 | 3 | [![SIT](https://img.shields.io/badge/SIT-awesome-blueviolet.svg)](https://jobs.schwarz) 4 | 5 | Schwarz API spectral custom rulesets to be used with [Spectral Linter](https://github.com/stoplightio/spectral) toolset. You can use this rules to integrate them in your own development workflow or you can build upon your own interpretation of how an API should look like. 6 | 7 | Rulesets are based on file inheritance on custom rulesets as supported by [Spectral Rulesets](https://meta.stoplight.io/docs/spectral/ZG9jOjYyMDc0NA-rulesets) assuming that different API types use the same ruleset but different severity levels as provided by [Spectral Custom Rulesets](https://meta.stoplight.io/docs/spectral/ZG9jOjI1MTg5-custom-rulesets). All API type specific rulesets depend on the same [base ruleset file](./spectral.yml) and just overwrite rulesets or severity levels. 8 | 9 | Rules Wiki and HowTo´s can be found [here](https://github.com/SchwarzIT/api-linter-rules/wiki). 10 | 11 | Example how to overwrite severity levels in [spectral-api.yml](./spectral-api.yml): 12 | 13 | ```yaml 14 | extends: 15 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral.yml 16 | rules: 17 | operation-tag-defined: off 18 | path-must-match-api-standards: warn 19 | servers-must-match-api-standards: warn 20 | common-responses-unauthorized: warn 21 | no-http-verbs-in-resources: warn 22 | description-is-mandatory: warn 23 | ``` 24 | 25 | *** 26 | 27 | ## Base ruleset 28 | 29 | * Base ruleset is defined in [spectral.yml](./spectral.yml) 30 | * Extends from spectral:oas [recommended rules](https://meta.stoplight.io/docs/spectral/ZG9jOjExNw-open-api-rules) 31 | * Is generated by merging it with all individual rules at build time 32 | 33 | ```yml 34 | extends: [[spectral:oas, recommended]] 35 | ``` 36 | ## Supported API Types 37 | 38 | * Product API ruleset is defined in [spectral-api.yml](./spectral-api.yml) 39 | ``` 40 | https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral-api.yml 41 | ``` 42 | * Backend For Frontend is defined in [spectral-bff.yml](./spectral-bff.yml) 43 | ``` 44 | https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral-bff.yml 45 | ``` 46 | * Legacy API is defined in [spectral-legacy.yml](./spectral-legacy.yml) 47 | ``` 48 | https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral-legacy.yml 49 | ``` 50 | 51 | ## Local usage in IDE 52 | 53 | ### Visual Studio Code 54 | 55 | * Install [Spectral Linter for VS Code](https://github.com/stoplightio/vscode-spectral) 56 | * Copy rules in your repo and create VS Code settings as described in the plugin repo OR just reference the desired API type validation from this repository like shown underneath: 57 | 58 | 1. Create "spectral.config.yml" in the root of you repository and paste below content into it 59 | 60 | ```yaml 61 | extends: 62 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral-{API_TYPE}.yml 63 | ```` 64 | 65 | 2. Adapt VS Code settings in .vscode/settings.json 66 | 67 | ```json 68 | "spectral.rulesetFile": "./spectral.config.yml", 69 | "spectral.validateFiles": [ 70 | "**/openapi/**/*.json", 71 | ], 72 | ``` 73 | 3. Place your open api spec in a folder called "openapi" 74 | 75 | 4. Enjoy API Linting 76 | 77 | ### Jetbrains IDE family 78 | 79 | * Install [Spectral Linter for Jetbrains IDE´s](https://github.com/SchwarzIT/spectral-intellij-plugin) 80 | 81 | * Open Jetbrains IDE preferences/tools/spectral and configure source rule set (see API Types above) for API linting and files to be linted 82 | 83 | ![jetbrains_spectral_config.png](./assets/jetbrains_spectral_config.png) 84 | 85 | * Enjoy API linting in Jetbrains IDE family 86 | 87 | ![jetbrains_spectral_linting.png](./assets/jetbrains_spectral_linting.png) 88 | 89 | ## Usage in CI 90 | 91 | Comming soon.. 92 | 93 | ## Usage in API design first approach 94 | 95 | Comming soon.. 96 | 97 | ## Building 98 | 99 | In order to save on http requests, when using one of the rulesets, the individual rules are not extended but bundled. 100 | In a build step all individual rules are collected and merged into the file spectral.yml. 101 | Splitting our ruleset into individual rules also improves maintainability as well as testing. 102 | 103 | For this the cli tool [yq](https://github.com/mikefarah/yq) is used. 104 | So in order to build the rules you need to have it installed locally. (See [installing yq](https://github.com/mikefarah/yq#install)) 105 | 106 | Also keep in mind, that the rules are built using bash scripts. So if you're on windows, you might want to use something like GitBash or [WSL](https://docs.microsoft.com/de-de/windows/wsl/about) 107 | 108 | ### CI 109 | 110 | During CI the same tool and script is used to merge the Rules. 111 | Afterwards the script [checkSpectralYaml.sh](./util/scripts/checkSpectralYaml.sh) is executed to find out whether the commited spectral.yml is up to date. 112 | If that's not the case, the pipeline fails asking you to build the rules before committing. 113 | If [spectral.yml](./spectral.yml) is valid, the api type specific rulesets will be checked. Each of them must specify a severity for every rule inside [spectral.yml](./spectral.yml). 114 | 115 | ## Testing 116 | 117 | To test our ruleset we decided to split it into individual rulesets containing only one rule. 118 | As written above, all individual rules will be merged during build. 119 | Splitting the ruleset enables us to test each rule isolated from the others. 120 | To do this we created a custom [jest-transformer](./util/transforms/spectralRuleTransformer.js) for `.yml` files. 121 | That way it's possible to just import an individual rule in a test and use it. 122 | 123 | Example: 124 | 125 | ```ts 126 | import { Spectral } from "@stoplight/spectral-core"; 127 | import ruleset from "./path-must-match-api-standards.yml"; 128 | 129 | describe("path-must-match-api-standards", () => { 130 | let spectral: Spectral; 131 | 132 | beforeEach(() => { spectral = setupSpectral(ruleset); }); 133 | 134 | it("has a correct path", async () => { 135 | const result = await spectral.run(`{"paths": {"/api-linting/api/v1/rules": {}}}`); 136 | expect(result).toHaveLength(0); 137 | }); 138 | }; 139 | ``` 140 | 141 | [setupSpectral()](./util/jest.setup.ts) is a global utility function that creates a usable Spectral instance from a ruleset. 142 | 143 | ## Documentation 144 | 145 | Since it would be pretty cumbersome to document the wiki pages of this project for all rules, we decided to automate this process. 146 | On every push to main the [wiki-pipeline](.github/workflows/wiki-pipeline.yml) checks out the wiki-repo, re-builds the documentation and pushes it to the wiki-repo. 147 | The documentation is generated by extracting the head comment of all the individual rules. So a comment like this: 148 | 149 | ```yaml 150 | # Comment shown in Wiki description 151 | # **bold text** 152 | 153 | rules: 154 | ## Comment shown in source code ## 155 | path-must-match-api-standards: 156 | ``` 157 | 158 | Is turned into a heading with the rule name, the upper comment, the severity levels specified inside the `spectral-*.yml` files and the implementation of the rule. 159 | It's even possible to use Markdown inside the head comment like in the example above. 160 | -------------------------------------------------------------------------------- /assets/jetbrains_spectral_config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/68d460e890baef7e55f9420ab4e693f2f0a14d3c/assets/jetbrains_spectral_config.png -------------------------------------------------------------------------------- /assets/jetbrains_spectral_linting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/68d460e890baef7e55f9420ab4e693f2f0a14d3c/assets/jetbrains_spectral_linting.png -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').JestConfigWithTsJest} */ 2 | const config = { 3 | preset: "ts-jest", 4 | testEnvironment: "node", 5 | }; 6 | 7 | module.exports = config; 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-linter-rules", 3 | "version": "1.0.0", 4 | "description": "[![SIT](https://img.shields.io/badge/SIT-awesome-blueviolet.svg)](https://jobs.schwarz)", 5 | "license": "Apache-2.0", 6 | "devDependencies": { 7 | "@stoplight/spectral-core": "^1.18.3", 8 | "@stoplight/spectral-ruleset-bundler": "^1.5.2", 9 | "@types/jest": "^29.5.3", 10 | "jest": "^29.6.1", 11 | "ts-jest": "^29.1.1", 12 | "typescript": "^5.1.6", 13 | "yaml": "^2.3.1" 14 | }, 15 | "scripts": { 16 | "test": "jest", 17 | "test:watch": "npm run test -- --watch", 18 | "build": "bash util/scripts/mergeRules.sh", 19 | "postinstall": "chmod +x util/scripts/*" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/SchwarzIT/api-linter-rules.git" 24 | }, 25 | "bugs": { 26 | "url": "https://github.com/SchwarzIT/api-linter-rules/issues" 27 | }, 28 | "homepage": "https://github.com/SchwarzIT/api-linter-rules#readme", 29 | "engines": { 30 | "node": ">=16.0.0", 31 | "npm": ">=7.0.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /rules/documentation/contact-information.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("contact-information", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/documentation/contact-information.yml"); 9 | }); 10 | 11 | it("has no errors", async () => { 12 | const result = await spectral.run(getTestSpec("name", "email", "url")); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it("is missing the required property name", async () => { 17 | const result = await spectral.run(getTestSpec(undefined, "email", "url")); 18 | expect(result).toHaveLength(1); 19 | expect(result[0].code).toEqual("contact-information"); 20 | expect(result[0].message).toContain("name is missing"); 21 | }); 22 | 23 | it("is missing the required property email", async () => { 24 | const result = await spectral.run(getTestSpec("name", undefined, "url")); 25 | expect(result).toHaveLength(1); 26 | expect(result[0].code).toEqual("contact-information"); 27 | expect(result[0].message).toContain("email is missing"); 28 | }); 29 | 30 | it("is missing the required property url", async () => { 31 | const result = await spectral.run(getTestSpec("name", "email", undefined)); 32 | expect(result).toHaveLength(1); 33 | expect(result[0].code).toEqual("contact-information"); 34 | expect(result[0].message).toContain("url is missing"); 35 | }); 36 | 37 | const getTestSpec = (name?: string, email?: string, url?: string) => 38 | JSON.stringify( 39 | { 40 | info: { 41 | contact: { 42 | name, 43 | email, 44 | url, 45 | }, 46 | }, 47 | }, 48 | null, 49 | 2 50 | ); 51 | }); 52 | -------------------------------------------------------------------------------- /rules/documentation/contact-information.yml: -------------------------------------------------------------------------------- 1 | # Rule to check if the contact data for the provided API is in place 2 | 3 | rules: 4 | contact-information: 5 | description: Every API must have a contact containing name, email and a url 6 | message: "{{description}}; property {{property}} is missing" 7 | severity: error 8 | given: $.info.contact 9 | then: 10 | - field: name 11 | function: truthy 12 | - field: email 13 | function: truthy 14 | - field: url 15 | function: truthy -------------------------------------------------------------------------------- /rules/documentation/info-description.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("info-description", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/documentation/info-description.yml"); 9 | }); 10 | 11 | it("has no errors", async () => { 12 | const result = await spectral.run(getTestSpec("#".repeat(100))); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it("fails no description is provided", async () => { 17 | const result = await spectral.run(getTestSpec(undefined)); 18 | expect(result).toHaveLength(1); 19 | expect(result[0].code).toEqual("info-description"); 20 | }); 21 | 22 | it("fails no description is less than 100 characters long", async () => { 23 | const result = await spectral.run(getTestSpec("#".repeat(99))); 24 | expect(result).toHaveLength(1); 25 | expect(result[0].code).toEqual("info-description"); 26 | }); 27 | 28 | const getTestSpec = (description?: string) => 29 | JSON.stringify( 30 | { 31 | info: { 32 | description, 33 | }, 34 | }, 35 | null, 36 | 2 37 | ); 38 | }); 39 | -------------------------------------------------------------------------------- /rules/documentation/info-description.yml: -------------------------------------------------------------------------------- 1 | # Rule to check the global description of the provided API. 2 | # It must be present and at least 100 characters long. 3 | 4 | rules: 5 | info-description: 6 | description: Every API must have a global description 7 | message: "OpenAPI object info `description` must be present and at least 100 chars long." 8 | severity: error 9 | given: $.info 10 | then: 11 | - field: description 12 | function: truthy 13 | - field: description 14 | function: length 15 | functionOptions: 16 | min: 100 -------------------------------------------------------------------------------- /rules/endpoint/common-response-unauthorized.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("common-responses-unauthorized", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/endpoint/common-responses-unauthorized.yml"); 9 | }); 10 | 11 | it("has no errors if a 401 response is defined", async () => { 12 | const result = await spectral.run(getTestSpec({ 401: 42 })); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it.each[0]>([ 17 | { 200: "" }, 18 | { 404: "" }, 19 | { 200: "", 201: "" }, 20 | { 400: "", 200: "", 500: "" }, 21 | ])("fails if no 401 response is defined", async (responses) => { 22 | const result = await spectral.run(getTestSpec(responses)); 23 | expect(result).toHaveLength(1); 24 | expect(result[0].code).toEqual("common-responses-unauthorized"); 25 | }); 26 | 27 | const getTestSpec = (responses: Record) => 28 | JSON.stringify( 29 | { 30 | paths: { 31 | "/api/some/path": { 32 | get: { 33 | responses, 34 | }, 35 | }, 36 | }, 37 | }, 38 | null, 39 | 2 40 | ); 41 | }); 42 | -------------------------------------------------------------------------------- /rules/endpoint/common-responses-unauthorized.yml: -------------------------------------------------------------------------------- 1 | # Rule to check if a 401 response is implemented on all paths responses 2 | 3 | rules: 4 | common-responses-unauthorized: 5 | description: Responses should contain common response - 401 (unauthorized) 6 | message: "{{description}}. Missing {{property}}" 7 | severity: error 8 | given: $.paths[?(!@property.match(/well-known/ig))]..responses 9 | then: 10 | - field: '401' 11 | function: truthy -------------------------------------------------------------------------------- /rules/endpoint/must-define-example-schema.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("must-define-example-schema", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/endpoint/must-define-example-schema.yml"); 9 | }); 10 | 11 | it("has no errors if just example is defined", async () => { 12 | const result = await spectral.run(getTestSpec({ example: true })); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it("has no errors if just examples is defined", async () => { 17 | const result = await spectral.run(getTestSpec({ examples: true })); 18 | expect(result).toHaveLength(0); 19 | }); 20 | 21 | it("fails if example and examples are defined", async () => { 22 | const result = await spectral.run(getTestSpec({ example: true, examples: true })); 23 | expect(result).toHaveLength(1); 24 | expect(result[0].code).toEqual("must-define-example-schema"); 25 | }); 26 | 27 | it("fails if example and examples are undefined", async () => { 28 | const result = await spectral.run(getTestSpec({})); 29 | expect(result).toHaveLength(1); 30 | expect(result[0].code).toEqual("must-define-example-schema"); 31 | }); 32 | 33 | const getTestSpec = (examples: { example?: boolean; examples?: boolean }): string => 34 | JSON.stringify( 35 | { 36 | components: { 37 | schemas: { 38 | ExampleDTO: { 39 | ...examples 40 | } 41 | } 42 | }, 43 | }, 44 | null, 45 | 2 46 | ); 47 | }); 48 | -------------------------------------------------------------------------------- /rules/endpoint/must-define-example-schema.yml: -------------------------------------------------------------------------------- 1 | # Rule to check that every DTO has at least one example 2 | 3 | rules: 4 | must-define-example-schema: 5 | description: Every DTO must define at least one example 6 | message: "{{description}}; DTO is lacking an example {{path}}" 7 | severity: error 8 | given: $.components.schemas.* 9 | then: 10 | - function: xor 11 | functionOptions: 12 | properties: 13 | - example 14 | - examples -------------------------------------------------------------------------------- /rules/endpoint/no-http-verbs-in-resources.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("no-http-verbs-in-resources", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/endpoint/no-http-verbs-in-resources.yml"); 9 | }); 10 | 11 | it("has no errors if no http verb is used inside the path", async () => { 12 | const result = await spectral.run(getTestSpec("/api/test")); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it.each<`/${string}${"get" | "post" | "put" | "patch" | "delete"}${string}`>([ 17 | "/get/", 18 | "/get", 19 | "/api/get", 20 | "/api/get/test", 21 | "/post/", 22 | "/post", 23 | "/api/post", 24 | "/api/post/test", 25 | "/put/", 26 | "/put", 27 | "/api/put", 28 | "/api/put/test", 29 | "/patch/", 30 | "/patch", 31 | "/api/patch", 32 | "/api/patch/test", 33 | "/delete/", 34 | "/delete", 35 | "/api/delete", 36 | "/api/delete/test", 37 | ])("fails if the path %s is used", async (path) => { 38 | const result = await spectral.run(getTestSpec(path)); 39 | expect(result).toHaveLength(1); 40 | expect(result[0].code).toEqual("no-http-verbs-in-resources"); 41 | }); 42 | 43 | const getTestSpec = (path: string) => 44 | JSON.stringify({ 45 | paths: { 46 | [path]: true, 47 | }, 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /rules/endpoint/no-http-verbs-in-resources.yml: -------------------------------------------------------------------------------- 1 | # Rule to check misuse of http verbs in url names 2 | 3 | rules: 4 | no-http-verbs-in-resources: 5 | description: The HTTP Verbs should not be used in the route path to define different actions on a resource 6 | message: "{{description}}; {{property}} Instead use HTTP verbs to define actions on a resource. Example: PUT - /digital-twin/api/v1/products/42" 7 | severity: error 8 | given: $.paths[?(!@property.match(/well-known/ig))]~ 9 | then: 10 | function: pattern 11 | functionOptions: 12 | notMatch: \/(get|post|put|patch|delete)(\/|$) -------------------------------------------------------------------------------- /rules/endpoint/path-must-specify-tags.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("path-must-specify-tags", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/endpoint/path-must-specify-tags.yml"); 9 | }); 10 | 11 | it("has no errors if tags are provided", async () => { 12 | const result = await spectral.run(getTestSpec(["tag"])); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it("fails if no tags were provided", async () => { 17 | const result = await spectral.run(getTestSpec()); 18 | expect(result).toHaveLength(1); 19 | expect(result[0].code).toEqual("path-must-specify-tags"); 20 | }); 21 | 22 | it("fails if the number of tag is less than 1", async () => { 23 | const result = await spectral.run(getTestSpec([])); 24 | expect(result).toHaveLength(1); 25 | expect(result[0].code).toEqual("path-must-specify-tags"); 26 | }); 27 | 28 | it("do not fail if the keywords for http methods are used in components", async () => { 29 | const result = await spectral.run(getComponentTestSpec()); 30 | expect(result).toHaveLength(0); 31 | }); 32 | 33 | it("ignores paths under the well-known route", async () => { 34 | const result = await spectral.run(getTestSpec(undefined, "/well-known/health")); 35 | expect(result).toHaveLength(0); 36 | }); 37 | 38 | it('ignores non http verb fields', async () => { 39 | const result = await spectral.run(JSON.stringify({ 40 | openapi: "3.0", 41 | paths: { 42 | "/test/{param}": { 43 | summary: "", 44 | description: "", 45 | servers: [], 46 | parameters: [{ 47 | name: 'param', 48 | in: "path", 49 | schema: {type: "string"} 50 | }] 51 | } 52 | } 53 | })) 54 | expect(result).toHaveLength(0); 55 | }) 56 | 57 | const getTestSpec = (tags?: string[], path = "/api/some/path") => 58 | JSON.stringify({ 59 | openapi: '3.0', 60 | paths: { 61 | [path]: { 62 | post: { 63 | tags, 64 | }, 65 | }, 66 | }, 67 | }); 68 | 69 | const getComponentTestSpec = (tags?: string[], path = "/api/some/path") => 70 | JSON.stringify({ 71 | "openapi": "3.0.2", 72 | "tags": [ 73 | { 74 | "name": "SomeTag", 75 | "description": "some description" 76 | } 77 | ], 78 | "paths": { 79 | "/twin/api/v1/somethings": { 80 | "get": { 81 | "operationId": "GetSomething", 82 | "description": "hi test", 83 | "tags": [ 84 | "SomeTag" 85 | ], 86 | } 87 | } 88 | }, 89 | "components": { 90 | "schemas": { 91 | "ShowMe": { 92 | "type": "object", 93 | "properties": { 94 | "input": { 95 | "type": "object", 96 | "properties": { 97 | "get": { 98 | "type": "string" 99 | }, 100 | "delete": { 101 | "type": "boolean" 102 | }, 103 | "options": { 104 | "type": "string", 105 | "nullable": true 106 | } 107 | } 108 | } 109 | } 110 | } 111 | } 112 | } 113 | }); 114 | }); 115 | -------------------------------------------------------------------------------- /rules/endpoint/path-must-specify-tags.yml: -------------------------------------------------------------------------------- 1 | # Rule to check if every path specifies at least one tag 2 | 3 | rules: 4 | path-must-specify-tags: 5 | description: Every route must specify at least one tag it belongs to 6 | message: "{{description}}; property tags is missing at: {{path}}" 7 | severity: error 8 | formats: 9 | - oas3 10 | given: $.paths[?(!@property.match(/well-known/ig))][get,post,put,delete,patch,options,head,trace] 11 | then: 12 | - field: tags 13 | function: truthy 14 | - field: tags 15 | function: length 16 | functionOptions: 17 | min: 1 -------------------------------------------------------------------------------- /rules/general/must-have-path.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("must-have-path", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/general/must-have-path.yml"); 9 | }); 10 | 11 | it("has no errors", async () => { 12 | const result = await spectral.run(getTestSpec({ path: 42 })); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it("fails if no paths are provided", async () => { 17 | const result = await spectral.run(getTestSpec({})); 18 | expect(result).toHaveLength(1); 19 | expect(result[0].code).toEqual("must-have-path"); 20 | expect(result[0].message).toContain("`paths` is empty"); 21 | }); 22 | 23 | const getTestSpec = (paths: Record) => 24 | JSON.stringify( 25 | { 26 | paths, 27 | }, 28 | null, 29 | 2 30 | ); 31 | }); 32 | -------------------------------------------------------------------------------- /rules/general/must-have-path.yml: -------------------------------------------------------------------------------- 1 | # Rule to check if the given API spec does have at least one path defined 2 | 3 | rules: 4 | must-have-path: 5 | description: Every API must have at least one path 6 | message: "{{description}}; property `paths` is empty" 7 | severity: error 8 | given: $ 9 | then: 10 | - field: paths 11 | function: length 12 | functionOptions: 13 | min: 1 -------------------------------------------------------------------------------- /rules/general/operation-tag-defined.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("operation-tag-defined", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/general/operation-tag-defined.yml"); 9 | }); 10 | 11 | it("does not contain the operation-tag-defined error", async () => { 12 | const result = await spectral.run(getTestSpec()); 13 | expect(result.find((issue) => issue.code === "operation-tag-defined")).toBeUndefined(); 14 | }); 15 | 16 | const getTestSpec = () => 17 | JSON.stringify( 18 | { 19 | openapi: "3.0.0", 20 | paths: { 21 | "/api/v1/test": { 22 | get: { 23 | operationId: "Id", 24 | }, 25 | }, 26 | }, 27 | }, 28 | null, 29 | 2 30 | ); 31 | }); 32 | -------------------------------------------------------------------------------- /rules/general/operation-tag-defined.yml: -------------------------------------------------------------------------------- 1 | # The Rule "operation-tag-defined" from the spectral:oas recommended ruleset was disabled 2 | 3 | extends: 4 | - ["spectral:oas", recommended] 5 | rules: 6 | operation-tag-defined: off 7 | -------------------------------------------------------------------------------- /rules/general/path-must-match-api-standards.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("path-must-match-api-standards", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/general/path-must-match-api-standards.yml"); 9 | }); 10 | 11 | it("has a correct path", async () => { 12 | const result = await spectral.run(getTestSpec("/api-linting/api/v1/rules")); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it("fails if the version is missing", async () => { 17 | const result = await spectral.run(getTestSpec("/api-linting/api/rules")); 18 | 19 | expect(result).toHaveLength(1); 20 | expect(result[0].code).toEqual("path-must-match-api-standards"); 21 | expect(result[0].range).toEqual({ 22 | start: { line: 3, character: 33 }, 23 | end: { line: 3, character: 36 }, 24 | }); 25 | }); 26 | 27 | it.each<`${string}well-known${string}`>(["/well-known/", "well-known", "/api/well-known/test", "/well-known/api/v2"])( 28 | "ignores the 'well-known' routes", 29 | async (route) => { 30 | const result = await spectral.run(getTestSpec(route)); 31 | expect(result).toHaveLength(0); 32 | } 33 | ); 34 | 35 | const getTestSpec = (path: string) => ` 36 | { 37 | "paths": { 38 | "${path}": {} 39 | } 40 | } 41 | `; 42 | }); 43 | -------------------------------------------------------------------------------- /rules/general/path-must-match-api-standards.yml: -------------------------------------------------------------------------------- 1 | # Used to check if provided paths stick to API best practices 2 | # Status: DEACTIVATED - in discussion 3 | 4 | rules: 5 | path-must-match-api-standards: 6 | description: API Path must match company API uri standards 7 | message: "{{description}}; {{property}} incorrect. Example: /digital-twin/api/v1/products" 8 | severity: error 9 | resolved: false 10 | given: $.paths[?(!@property.match(/well-known/ig))~] 11 | then: 12 | function: pattern 13 | functionOptions: 14 | match: ^\/([a-z-]+)\/api\/(v[1-9])\/([a-z]+(\w+s\b.*)) -------------------------------------------------------------------------------- /rules/general/servers-must-match-api-standards.spec.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { setupSpectral } from "../../util/setup-spectral"; 3 | 4 | describe("servers-must-match-api-standards", () => { 5 | let spectral: Spectral; 6 | 7 | beforeEach(async () => { 8 | spectral = await setupSpectral("rules/general/servers-must-match-api-standards.yml"); 9 | }); 10 | 11 | it("has no errors", async () => { 12 | const result = await spectral.run(getTestSpec(["https://live.api.schwarz/digital-twin/api/v1/products"])); 13 | expect(result).toHaveLength(0); 14 | }); 15 | 16 | it.each([ 17 | [["test"]], 18 | [["www.google.com"]], 19 | [["https://www.google.com"]], 20 | [["https://live.api.schwarz/digital-twin/api/v1/products", "error.schwarz"]], 21 | ])("fails if any of the server urls does not match the expected pattern", async (urls) => { 22 | const result = await spectral.run(getTestSpec(urls)); 23 | expect(result.length).toBeGreaterThanOrEqual(1); 24 | expect(result[0].code).toEqual("servers-must-match-api-standards"); 25 | }); 26 | 27 | const getTestSpec = (urls: string[]) => 28 | JSON.stringify( 29 | { 30 | servers: urls.map((url) => ({ url })), 31 | }, 32 | null, 33 | 2 34 | ); 35 | }); 36 | -------------------------------------------------------------------------------- /rules/general/servers-must-match-api-standards.yml: -------------------------------------------------------------------------------- 1 | # Rule to check if provided server urls stick to the API best practices 2 | # Status: DEACTIVATED - in discussion 3 | 4 | rules: 5 | servers-must-match-api-standards: 6 | description: Schema and host in URL must match company API standards 7 | message: "{{description}}; {{property}}:{{value}} incorrect. Example: https://live.api.schwarz/digital-twin/api/v1/products" 8 | severity: error 9 | resolved: false 10 | given: "$.servers..url" 11 | then: 12 | function: pattern 13 | functionOptions: 14 | match: ^((http[s]?):\/\/)([a-z]+)([.+])api.schwarz -------------------------------------------------------------------------------- /spectral-api.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral.yml 3 | rules: 4 | tag-description: info # Rule enabled from spectral openapi ruleset 5 | operation-tag-defined: off 6 | path-must-match-api-standards: off # Rule is still under discussion and therefore disabled 7 | servers-must-match-api-standards: off # Rule is still under discussion and therefore disabled 8 | common-responses-unauthorized: hint 9 | no-http-verbs-in-resources: warn 10 | info-description: warn 11 | contact-information: warn 12 | must-have-path: warn 13 | must-define-example-schema: warn 14 | path-must-specify-tags: warn 15 | 16 | # We do not want to hinder anyone from deploying, therefore we overwrite all default rules from spectral with a severity of error to warning 17 | operation-operationId-unique: warn 18 | path-params: warn 19 | no-$ref-siblings: warn 20 | oas2-discriminator: warn 21 | oas2-valid-schema-example: warn 22 | oas2-valid-media-example: warn 23 | oas2-schema: off 24 | oas3-valid-media-example: warn 25 | oas3-valid-schema-example: warn 26 | oas3-schema: off 27 | operation-description: off 28 | -------------------------------------------------------------------------------- /spectral-async-api.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - ["spectral:asyncapi", recommended] -------------------------------------------------------------------------------- /spectral-async-bounded-api.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral-async-api.yml 3 | -------------------------------------------------------------------------------- /spectral-async-product-api.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral-async-api.yml 3 | -------------------------------------------------------------------------------- /spectral-bff.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral.yml 3 | rules: 4 | tag-description: info # Rule enabled from spectral openapi ruleset 5 | operation-tag-defined: off 6 | path-must-match-api-standards: off # Rule is still under discussion and therefore disabled 7 | servers-must-match-api-standards: off # Rule is still under discussion and therefore disabled 8 | common-responses-unauthorized: hint 9 | no-http-verbs-in-resources: info 10 | info-description: info 11 | contact-information: info 12 | must-have-path: info 13 | must-define-example-schema: info 14 | path-must-specify-tags: info 15 | 16 | # We do not want to hinder anyone from deploying, therefore we overwrite all default rules from spectral with a severity of error to warning 17 | operation-operationId-unique: warn 18 | path-params: warn 19 | no-$ref-siblings: warn 20 | oas2-discriminator: warn 21 | oas2-valid-schema-example: warn 22 | oas2-valid-media-example: warn 23 | oas2-schema: off 24 | oas2-api-host: info 25 | oas2-api-schemes: info 26 | oas3-valid-media-example: warn 27 | oas3-valid-schema-example: warn 28 | oas3-schema: off 29 | oas3-api-servers: info 30 | operation-description: off -------------------------------------------------------------------------------- /spectral-legacy.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - https://raw.githubusercontent.com/SchwarzIT/api-linter-rules/main/spectral.yml 3 | rules: 4 | tag-description: info # Rule enabled from spectral openapi ruleset 5 | operation-tag-defined: off 6 | path-must-match-api-standards: off # Rule is still under discussion and therefore disabled 7 | servers-must-match-api-standards: off # Rule is still under discussion and therefore disabled 8 | common-responses-unauthorized: hint 9 | no-http-verbs-in-resources: info 10 | info-description: info 11 | contact-information: info 12 | must-have-path: info 13 | must-define-example-schema: info 14 | path-must-specify-tags: info 15 | 16 | # We do not want to hinder anyone from deploying, therefore we overwrite all default rules from spectral with a severity of error to info 17 | operation-operationId-unique: info 18 | path-params: info 19 | no-$ref-siblings: info 20 | oas2-discriminator: info 21 | oas2-valid-schema-example: info 22 | oas2-valid-media-example: info 23 | oas2-schema: off 24 | oas2-api-host: info 25 | oas2-api-schemes: info 26 | oas3-valid-media-example: info 27 | oas3-valid-schema-example: info 28 | oas3-schema: off 29 | oas3-api-servers: info 30 | operation-description: off -------------------------------------------------------------------------------- /spectral.yml: -------------------------------------------------------------------------------- 1 | extends: 2 | - ["spectral:oas", recommended] 3 | rules: 4 | operation-tag-defined: off 5 | path-must-match-api-standards: 6 | description: API Path must match company API uri standards 7 | message: "{{description}}; {{property}} incorrect. Example: /digital-twin/api/v1/products" 8 | severity: error 9 | resolved: false 10 | given: $.paths[?(!@property.match(/well-known/ig))~] 11 | then: 12 | function: pattern 13 | functionOptions: 14 | match: ^\/([a-z-]+)\/api\/(v[1-9])\/([a-z]+(\w+s\b.*)) 15 | servers-must-match-api-standards: 16 | description: Schema and host in URL must match company API standards 17 | message: "{{description}}; {{property}}:{{value}} incorrect. Example: https://live.api.schwarz/digital-twin/api/v1/products" 18 | severity: error 19 | resolved: false 20 | given: "$.servers..url" 21 | then: 22 | function: pattern 23 | functionOptions: 24 | match: ^((http[s]?):\/\/)([a-z]+)([.+])api.schwarz 25 | info-description: 26 | description: Every API must have a global description 27 | message: "OpenAPI object info `description` must be present and at least 100 chars long." 28 | severity: error 29 | given: $.info 30 | then: 31 | - field: description 32 | function: truthy 33 | - field: description 34 | function: length 35 | functionOptions: 36 | min: 100 37 | contact-information: 38 | description: Every API must have a contact containing name, email and a url 39 | message: "{{description}}; property {{property}} is missing" 40 | severity: error 41 | given: $.info.contact 42 | then: 43 | - field: name 44 | function: truthy 45 | - field: email 46 | function: truthy 47 | - field: url 48 | function: truthy 49 | must-have-path: 50 | description: Every API must have at least one path 51 | message: "{{description}}; property `paths` is empty" 52 | severity: error 53 | given: $ 54 | then: 55 | - field: paths 56 | function: length 57 | functionOptions: 58 | min: 1 59 | common-responses-unauthorized: 60 | description: Responses should contain common response - 401 (unauthorized) 61 | message: "{{description}}. Missing {{property}}" 62 | severity: error 63 | given: $.paths[?(!@property.match(/well-known/ig))]..responses 64 | then: 65 | - field: '401' 66 | function: truthy 67 | no-http-verbs-in-resources: 68 | description: The HTTP Verbs should not be used in the route path to define different actions on a resource 69 | message: "{{description}}; {{property}} Instead use HTTP verbs to define actions on a resource. Example: PUT - /digital-twin/api/v1/products/42" 70 | severity: error 71 | given: $.paths[?(!@property.match(/well-known/ig))]~ 72 | then: 73 | function: pattern 74 | functionOptions: 75 | notMatch: \/(get|post|put|patch|delete)(\/|$) 76 | must-define-example-schema: 77 | description: Every DTO must define at least one example 78 | message: "{{description}}; DTO is lacking an example {{path}}" 79 | severity: error 80 | given: $.components.schemas.* 81 | then: 82 | - function: xor 83 | functionOptions: 84 | properties: 85 | - example 86 | - examples 87 | path-must-specify-tags: 88 | description: Every route must specify at least one tag it belongs to 89 | message: "{{description}}; property tags is missing at: {{path}}" 90 | severity: error 91 | given: $.paths[?(!@property.match(/well-known/ig))][get,post,put,delete,patch,options,head,trace] 92 | then: 93 | - field: tags 94 | function: truthy 95 | - field: tags 96 | function: length 97 | functionOptions: 98 | min: 1 99 | formats: 100 | - oas3 101 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2021", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ 4 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 5 | "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 6 | "noEmit": true, /* Do not emit outputs. */ 7 | 8 | /* Strict Type-Checking Options */ 9 | "strict": true, /* Enable all strict type-checking options. */ 10 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 11 | "moduleResolution": "node16", 12 | 13 | /* Advanced Options */ 14 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 15 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /util/scripts/checkApiTypeRules.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | includesRules() { 4 | # Checking that all rulenames of the first file are included in the rulesnames of the second one 5 | yq eval-all -e 'select(fileIndex == 0) .rules as $a | select(fileIndex == 1) .rules as $b | $b | keys | contains($a | keys)' $2 $1 > /dev/null 2>&1 6 | 7 | if [[ $? -ne 0 ]] ; then 8 | echo "Error: $1 does not overwrite all rules of $2, it should at leas specify the severiy level of each rule" 9 | echo "The following paths are not overwritten inside $1:" 10 | # Showing all the rulenames in the second file, that are not overwritten by the first file 11 | yq eval-all -e 'select(fileIndex == 0) .rules as $a | select(fileIndex == 1) .rules as $b | $a | keys - ($b | keys)' $2 $1 12 | exit 1 13 | else 14 | echo "Success" 15 | fi 16 | } 17 | 18 | includesRules spectral-api.yml spectral.yml 19 | includesRules spectral-bff.yml spectral.yml 20 | includesRules spectral-legacy.yml spectral.yml -------------------------------------------------------------------------------- /util/scripts/checkSpectralYaml.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Checking whether there were changes to the repo. This is used after the file spectral.yml was re-built. 4 | git diff --exit-code > /dev/null 5 | 6 | if [[ $? -ne 0 ]] ; then 7 | echo "Error: The currently commited spectral.yml is not up to date and needs to be re-build" 8 | echo "Please run the script 'mergeRules.sh' under util/scripts/" 9 | exit 1 10 | else 11 | echo "Success" 12 | exit 0 13 | fi -------------------------------------------------------------------------------- /util/scripts/generateDocs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | NL=$'\n' 3 | 4 | function printRules() { 5 | for file in "$1"/* 6 | do 7 | if [ ! -d "${file}" ] ; then 8 | if [[ ( $file == *.yml ) || ( $file == *.yaml )]] ; then 9 | comment=`yq 'headComment' $file` # Extracting the head comment from the rule 10 | ruleName=`basename ${file%.*}` # Getting the name of the rule by removing the suffix from the file name 11 | echo "### $ruleName$NL" >> $2 12 | 13 | # If there's a head comment it gets added to the wiki 14 | [ ! -z "$comment" ] && echo "$comment$NL" >> $2 15 | 16 | # Getting the severity levels for that rule from the api types 17 | echo "**Severities**$NL" >> $2 18 | echo "- Product API Severity Level: $(yq .rules."$ruleName" spectral-api.yml)" >> $2 19 | echo "- BFF API Severity Level: $(yq .rules."$ruleName" spectral-bff.yml)" >> $2 20 | echo "- Legacy API Severity Level: $(yq .rules."$ruleName" spectral-legacy.yml)$NL" >> $2 21 | 22 | # Extracting the rules source code and adding it to the wiki 23 | sourceCode=`yq ".rules."$ruleName" | parent" "$file"` 24 | echo "\`\`\`yml" >> $2 25 | echo "$sourceCode" >> $2 26 | echo "\`\`\`$NL" >> $2 27 | fi 28 | fi 29 | done 30 | } 31 | 32 | function addTrailingSlash() { 33 | length=${#1} 34 | last_char=${1:length-1:1} 35 | 36 | [[ $last_char != "/" ]] && STR="$1/"; : 37 | 38 | echo $STR 39 | } 40 | 41 | # Iterates over every folder in the specified directory 42 | # then creates a wiki page with its name and appends the rules to it. 43 | for file in "$1"/* 44 | do 45 | if [ -d "${file}" ] ; then 46 | folder=`basename ${file%}` 47 | # Uppercasing folder names (needed to support bash v3) 48 | folder="$(tr '[:lower:]' '[:upper:]' <<< ${folder:0:1})${folder:1}" 49 | fileName="$(addTrailingSlash $2)$folder-API-Linting-Rules.md" 50 | rm $fileName 51 | 52 | echo "Schwarz API custom rulesets depend heavily on [Spectral OAS Recommended Rules](https://meta.stoplight.io/docs/spectral/ZG9jOjExNw-open-api-rules#license-url). We consider them to be a very good starting point that we built our custom rules on top of it.$NL" >> $fileName 53 | echo "Below you'll find a more semantic description about the API $folder rulesets.$NL" >> $fileName 54 | echo "***$NL" >> $fileName 55 | echo "## API $folder rules$NL" >> $fileName 56 | printRules "${file}" $fileName $2 57 | fi 58 | done -------------------------------------------------------------------------------- /util/scripts/mergeRules.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Merging all rules with the main ruleset "spectral.yml" 4 | # All comments are removed from this file to make the merge saver 5 | yq eval-all -i '... comments="" | . as $item ireduce ({}; . * $item )' spectral.yml rules/**/*.yml 6 | 7 | if [[ $? -ne 0 ]] ; then 8 | echo "Error: Unable to merge individual files into spectral.yml" 9 | exit 1 10 | else 11 | echo "Success" 12 | exit 0 13 | fi -------------------------------------------------------------------------------- /util/setup-spectral.ts: -------------------------------------------------------------------------------- 1 | import { Spectral } from "@stoplight/spectral-core"; 2 | import { bundleAndLoadRuleset } from "@stoplight/spectral-ruleset-bundler/with-loader"; 3 | import path from "path"; 4 | import fs from "fs"; 5 | import { fetch } from "@stoplight/spectral-runtime"; 6 | 7 | export async function setupSpectral(rulesetFile: string) { 8 | const spectral = new Spectral(); 9 | const ruleset = await bundleAndLoadRuleset(path.resolve(rulesetFile), { fs, fetch }); 10 | spectral.setRuleset(ruleset); 11 | return spectral; 12 | } 13 | --------------------------------------------------------------------------------