From threatmodel-skills
Lints OpenAPI, AsyncAPI, and Arazzo specifications for security vulnerabilities, design flaws, and compliance using Spectral. Enforces OWASP API Top 10 and custom rules in CI/CD pipelines.
npx claudepluginhub agentsecops/secopsagentkit --plugin offsec-skillsThis skill uses the workspace's default tool permissions.
Spectral is a flexible JSON/YAML linter from Stoplight that validates API specifications against
Designs and optimizes AI agent action spaces, tool definitions, observation formats, error recovery, and context for higher task completion rates.
Compares coding agents like Claude Code and Aider on custom YAML-defined codebase tasks using git worktrees, measuring pass rate, cost, time, and consistency.
Designs, implements, and audits WCAG 2.2 AA accessible UIs for Web (ARIA/HTML5), iOS (SwiftUI traits), and Android (Compose semantics). Audits code for compliance gaps.
Spectral is a flexible JSON/YAML linter from Stoplight that validates API specifications against security best practices and organizational standards. With built-in rulesets for OpenAPI v2/v3.x, AsyncAPI v2.x, and Arazzo v1.0, Spectral helps identify security vulnerabilities, design flaws, and compliance issues during the API design phase—before code is written. Custom rulesets enable enforcement of OWASP API Security Top 10 patterns, authentication standards, and data protection requirements across your entire API portfolio.
# Install via npm
npm install -g @stoplight/spectral-cli
# Or using Yarn
yarn global add @stoplight/spectral-cli
# Or using Docker
docker pull stoplight/spectral
# Verify installation
spectral --version
# Lint OpenAPI specification with built-in rules
spectral lint openapi.yaml
# Lint with specific ruleset
spectral lint openapi.yaml --ruleset .spectral.yaml
# Output as JSON for CI/CD integration
spectral lint openapi.yaml --format json --output results.json
# Create security-focused ruleset
echo 'extends: ["spectral:oas"]' > .spectral.yaml
# Lint API specification
spectral lint api-spec.yaml --ruleset .spectral.yaml
Progress: [ ] 1. Install Spectral and select appropriate base rulesets [ ] 2. Create or configure ruleset with security rules [ ] 3. Identify API specifications to validate (OpenAPI, AsyncAPI, Arazzo) [ ] 4. Run linting with appropriate severity thresholds [ ] 5. Review findings and categorize by security impact [ ] 6. Map findings to OWASP API Security Top 10 [ ] 7. Create custom rules for organization-specific security patterns [ ] 8. Integrate into CI/CD pipeline with failure thresholds [ ] 9. Generate reports with remediation guidance [ ] 10. Establish continuous validation process
Work through each step systematically. Check off completed items.
Create a .spectral.yaml ruleset extending built-in security rules:
# .spectral.yaml - Basic security-focused ruleset
extends: ["spectral:oas", "spectral:asyncapi"]
rules:
# Enforce HTTPS for all API endpoints
oas3-valid-schema-example: true
oas3-server-not-example.com: true
# Authentication security
operation-security-defined: error
# Information disclosure prevention
info-contact: warn
info-description: warn
Built-in Rulesets:
spectral:oas - OpenAPI v2/v3.x security and best practicesspectral:asyncapi - AsyncAPI v2.x validation rulesspectral:arazzo - Arazzo v1.0 workflow specificationsRuleset Selection Best Practices:
error severity for critical security issues (authentication, HTTPS)warn for recommended practices and information disclosure risksinfo for style guide compliance and documentation completenessFor advanced ruleset patterns, see references/ruleset_patterns.md.
Run Spectral with security-specific validation:
# Comprehensive security scan
spectral lint openapi.yaml \
--ruleset .spectral.yaml \
--format stylish \
--verbose
# Focus on error-level findings only (critical security issues)
spectral lint openapi.yaml \
--ruleset .spectral.yaml \
--fail-severity error
# Scan multiple specifications
spectral lint api-specs/*.yaml --ruleset .spectral.yaml
# Generate JSON report for further analysis
spectral lint openapi.yaml \
--ruleset .spectral.yaml \
--format json \
--output security-findings.json
Output Formats:
stylish - Human-readable terminal output (default)json - Machine-readable JSON for CI/CD integrationjunit - JUnit XML for test reporting platformshtml - HTML report (requires additional plugins)github-actions - GitHub Actions annotations formatValidate API specifications against OWASP API Security Top 10:
# .spectral-owasp.yaml - OWASP API Security focused rules
extends: ["spectral:oas"]
rules:
# API1:2023 - Broken Object Level Authorization
operation-security-defined:
severity: error
message: "All operations must have security defined (OWASP API1)"
# API2:2023 - Broken Authentication
security-schemes-defined:
severity: error
message: "API must define security schemes (OWASP API2)"
# API3:2023 - Broken Object Property Level Authorization
no-additional-properties:
severity: warn
message: "Consider disabling additionalProperties to prevent data leakage (OWASP API3)"
# API5:2023 - Broken Function Level Authorization
operation-tag-defined:
severity: warn
message: "Operations should be tagged for authorization policy mapping (OWASP API5)"
# API7:2023 - Server Side Request Forgery
no-http-basic:
severity: error
message: "HTTP Basic auth transmits credentials in plain text (OWASP API7)"
# API8:2023 - Security Misconfiguration
servers-use-https:
description: All server URLs must use HTTPS
severity: error
given: $.servers[*].url
then:
function: pattern
functionOptions:
match: "^https://"
message: "Server URL must use HTTPS (OWASP API8)"
# API9:2023 - Improper Inventory Management
api-version-required:
severity: error
given: $.info
then:
field: version
function: truthy
message: "API version must be specified (OWASP API9)"
Run OWASP-focused validation:
spectral lint openapi.yaml --ruleset .spectral-owasp.yaml
For complete OWASP API Security Top 10 rule mappings, see references/owasp_api_mappings.md.
Create organization-specific security rules using Spectral's rule engine:
# .spectral-custom.yaml
extends: ["spectral:oas"]
rules:
# Require API key authentication
require-api-key-auth:
description: All APIs must support API key authentication
severity: error
given: $.components.securitySchemes[*]
then:
field: type
function: enumeration
functionOptions:
values: [apiKey, oauth2, openIdConnect]
message: "API must define apiKey, OAuth2, or OpenID Connect security"
# Prevent PII in query parameters
no-pii-in-query:
description: Prevent PII exposure in URL query parameters
severity: error
given: $.paths[*][*].parameters[?(@.in == 'query')].name
then:
function: pattern
functionOptions:
notMatch: "(ssn|social.?security|credit.?card|password|secret|token)"
message: "Query parameters must not contain PII identifiers"
# Require rate limiting headers
require-rate-limit-headers:
description: API responses should include rate limit headers
severity: warn
given: $.paths[*][*].responses[*].headers
then:
function: schema
functionOptions:
schema:
type: object
properties:
X-RateLimit-Limit: true
X-RateLimit-Remaining: true
message: "Consider adding rate limit headers for security"
# Enforce consistent error responses
error-response-format:
description: Error responses must follow standard format
severity: error
given: $.paths[*][*].responses[?(@property >= 400)].content.application/json.schema
then:
function: schema
functionOptions:
schema:
type: object
required: [error, message]
properties:
error:
type: string
message:
type: string
message: "Error responses must include 'error' and 'message' fields"
Custom Rule Development Resources:
references/custom_rules_guide.md - Complete rule authoring guide with functionsreferences/custom_functions.md - Creating custom JavaScript/TypeScript functionsassets/rule-templates/ - Reusable rule templates for common security patternsIntegrate Spectral into continuous integration workflows:
GitHub Actions:
# .github/workflows/api-security-lint.yml
name: API Security Linting
on: [push, pull_request]
jobs:
spectral:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install Spectral
run: npm install -g @stoplight/spectral-cli
- name: Lint API Specifications
run: |
spectral lint api-specs/*.yaml \
--ruleset .spectral.yaml \
--format github-actions \
--fail-severity error
- name: Generate Report
if: always()
run: |
spectral lint api-specs/*.yaml \
--ruleset .spectral.yaml \
--format json \
--output spectral-report.json
- name: Upload Report
if: always()
uses: actions/upload-artifact@v3
with:
name: spectral-security-report
path: spectral-report.json
GitLab CI:
# .gitlab-ci.yml
api-security-lint:
stage: test
image: node:18
script:
- npm install -g @stoplight/spectral-cli
- spectral lint api-specs/*.yaml --ruleset .spectral.yaml --fail-severity error
artifacts:
when: always
reports:
junit: spectral-report.xml
Docker-Based Pipeline:
# Run in CI/CD with Docker
docker run --rm \
-v $(pwd):/work \
stoplight/spectral lint /work/openapi.yaml \
--ruleset /work/.spectral.yaml \
--format json \
--output /work/results.json
# Fail build on critical security issues
if jq -e '.[] | select(.severity == 0)' results.json > /dev/null; then
echo "Critical security issues detected!"
exit 1
fi
For complete CI/CD integration examples, see scripts/ci_integration_examples/.
Analyze findings and provide security remediation:
# Parse Spectral JSON output for security report
python3 scripts/parse_spectral_results.py \
--input spectral-report.json \
--output security-report.html \
--map-owasp \
--severity-threshold error
# Generate remediation guidance
python3 scripts/generate_remediation.py \
--input spectral-report.json \
--output remediation-guide.md
Validation Workflow:
Feedback Loop Pattern:
# 1. Initial lint
spectral lint openapi.yaml --ruleset .spectral.yaml -o scan1.json
# 2. Apply security fixes to API specification
# 3. Re-lint to verify fixes
spectral lint openapi.yaml --ruleset .spectral.yaml -o scan2.json
# 4. Compare results
python3 scripts/compare_spectral_results.py scan1.json scan2.json
Enforce consistent security standards across API portfolio:
# Scan all API specifications with organization ruleset
find api-specs/ -name "*.yaml" -o -name "*.json" | while read spec; do
echo "Linting: $spec"
spectral lint "$spec" \
--ruleset .spectral-org-standards.yaml \
--format json \
--output "reports/$(basename $spec .yaml)-report.json"
done
# Aggregate findings across portfolio
python3 scripts/aggregate_api_findings.py \
--input-dir reports/ \
--output portfolio-security-report.html
Start with warnings and progressively enforce stricter rules:
# .spectral-phase1.yaml - Initial rollout (warnings only)
extends: ["spectral:oas"]
rules:
servers-use-https: warn
operation-security-defined: warn
# .spectral-phase2.yaml - Enforcement phase (errors)
extends: ["spectral:oas"]
rules:
servers-use-https: error
operation-security-defined: error
# Phase 1: Awareness (don't fail builds)
spectral lint openapi.yaml --ruleset .spectral-phase1.yaml
# Phase 2: Enforcement (fail on violations)
spectral lint openapi.yaml --ruleset .spectral-phase2.yaml --fail-severity error
Prevent insecure API specifications from being committed:
# .git/hooks/pre-commit
#!/bin/bash
# Find staged API specification files
SPECS=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(yaml|yml|json)$' | grep -E '(openapi|swagger|api)')
if [ -n "$SPECS" ]; then
echo "Validating API specifications..."
for spec in $SPECS; do
spectral lint "$spec" --ruleset .spectral.yaml --fail-severity error
if [ $? -ne 0 ]; then
echo "Security validation failed for $spec"
exit 1
fi
done
fi
Generate security review comments for pull requests:
# Generate PR review comments from Spectral findings
spectral lint openapi.yaml \
--ruleset .spectral.yaml \
--format json | \
python3 scripts/generate_pr_comments.py \
--file openapi.yaml \
--severity error,warn \
--output pr-comments.json
# Post to GitHub PR via gh CLI
gh pr comment $PR_NUMBER --body-file pr-comments.json
Create custom JavaScript functions for complex security validation:
// spectral-functions/check-jwt-expiry.js
export default (targetVal, opts) => {
// Validate JWT security scheme includes expiration
if (targetVal.type === 'http' && targetVal.scheme === 'bearer') {
if (!targetVal.bearerFormat || targetVal.bearerFormat !== 'JWT') {
return [{
message: 'Bearer authentication should specify JWT format'
}];
}
}
return [];
};
# .spectral.yaml with custom function
functions:
- check-jwt-expiry
functionsDir: ./spectral-functions
rules:
jwt-security-check:
description: Validate JWT security configuration
severity: error
given: $.components.securitySchemes[*]
then:
function: check-jwt-expiry
For complete custom function development guide, see references/custom_functions.md.
# Automated daily API specification scanning
./scripts/spectral_scheduler.sh \
--schedule daily \
--specs-dir api-specs/ \
--ruleset .spectral-owasp.yaml \
--output-dir scan-results/ \
--alert-on error \
--slack-webhook $SLACK_WEBHOOK
# Monitor API specifications for security regressions
./scripts/spectral_monitor.sh \
--baseline baseline-scan.json \
--current-scan latest-scan.json \
--alert-on-new-findings \
--email security-team@example.com
scripts/)parse_spectral_results.py - Parse Spectral JSON output and generate security reports with OWASP mappinggenerate_remediation.py - Generate remediation guidance based on Spectral findingscompare_spectral_results.py - Compare two Spectral scans to track remediation progressaggregate_api_findings.py - Aggregate findings across multiple API specificationsspectral_ci.sh - CI/CD integration wrapper with exit code handlingspectral_scheduler.sh - Scheduled scanning with alertingspectral_monitor.sh - Continuous monitoring with baseline comparisongenerate_pr_comments.py - Convert Spectral findings to PR review commentsreferences/)owasp_api_mappings.md - Complete OWASP API Security Top 10 rule mappingscustom_rules_guide.md - Custom rule authoring with examplescustom_functions.md - Creating custom JavaScript/TypeScript validation functionsruleset_patterns.md - Reusable ruleset patterns for common security scenariosapi_security_checklist.md - API security validation checklistassets/)spectral-owasp.yaml - Comprehensive OWASP API Security Top 10 rulesetspectral-org-template.yaml - Organization-wide API security standards templategithub-actions-template.yml - Complete GitHub Actions workflowgitlab-ci-template.yml - GitLab CI integration templaterule-templates/ - Reusable security rule templatesValidate API specifications during design phase:
# Design phase validation (strict security rules)
spectral lint api-design.yaml \
--ruleset .spectral-owasp.yaml \
--fail-severity warn \
--verbose
Detect security regressions between API versions:
# Compare two API specification versions
spectral lint api-v2.yaml --ruleset .spectral.yaml -o v2-findings.json
spectral lint api-v1.yaml --ruleset .spectral.yaml -o v1-findings.json
python3 scripts/compare_spectral_results.py \
--baseline v1-findings.json \
--current v2-findings.json \
--show-regressions
Different rulesets for development, staging, production:
# .spectral-dev.yaml (permissive)
extends: ["spectral:oas"]
rules:
servers-use-https: warn
# .spectral-prod.yaml (strict)
extends: ["spectral:oas"]
rules:
servers-use-https: error
operation-security-defined: error
Solution:
error severity only: spectral lint --fail-severity erroroverrides section in ruleset to exclude specific pathsreferences/ruleset_patterns.md for filtering strategiesSolution:
spectral lint --ruleset .spectral.yaml --verbose--verbose flag to see which rules are being appliedSolution:
spectral lint api-spec.yaml --ignore-paths "components/examples"--skip-rules to disable expensive rules temporarilySolution:
--fail-severity to control when builds should failscripts/spectral_ci.sh