Skip to content

Commit

Permalink
feat(spectral): add rule to prevent external relative references (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
Enda authored Aug 6, 2021
1 parent 8c9707b commit ecb823c
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 3 deletions.
8 changes: 8 additions & 0 deletions spectral/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,14 @@ List:

**Severity**: warning

### rhoas-external-$ref

`$ref` values cannot be a relative path to an external file. Please use the absolute URL or convert it to an internal `$ref`.

**Recommended**: Yes

**Severity**: error

## Development

> NOTE: This project uses [Yarn workspaces](https://classic.yarnpkg.com/en/docs/workspaces/) for easier development.
Expand Down
8 changes: 7 additions & 1 deletion spectral/examples/openapi-invalid.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
"400":
description: br
content:
application/json:
schema:
$ref: 'openapi-invalid.yaml#/components/schemas/Error'
/api/foo_mgmt/v1beta/foos/{id}:
get:
operationId: getFooById
Expand Down Expand Up @@ -90,4 +96,4 @@ components:
Bearer:
scheme: 'bearer'
bearerFormat: 'JWT'
type: 'http'
type: 'http'
2 changes: 1 addition & 1 deletion spectral/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@rhoas/spectral-ruleset",
"version": "0.1.1",
"version": "0.1.2",
"description": "Spectral ruleset",
"private": false,
"main": "ruleset.yaml",
Expand Down
10 changes: 9 additions & 1 deletion spectral/ruleset.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,18 @@ functions:
- securitySchemes
- infoLicenseApache2
- schemaDefinition
- externalRefs
rules:
openapi-tags: off
operation-tags: off

rhoas-external-$ref:
given: "$..['$ref']"
severity: error
type: 'validation'
resolved: false
then:
function: externalRefs
rhoas-oas3minimum:
given: "$"
description: OpenAPI version must be >= 3
Expand Down Expand Up @@ -163,4 +171,4 @@ rules:
required: true
total:
type: integer
required: true
required: true
15 changes: 15 additions & 0 deletions spectral/src/functions/externalRefs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { IFunctionResult } from "@stoplight/spectral";

export default (targetVal: any): IFunctionResult[] => {
if (!targetVal || !targetVal.length) {
return
}

if (targetVal.startsWith('https') || targetVal.startsWith('http') || targetVal.startsWith('#/')) {
return;
} else {
return [{
message: 'Only local relative `$ref` or absolute external URL `$ref` is allowed'
}]
}
}

0 comments on commit ecb823c

Please sign in to comment.