linter

package
v1.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2026 License: MIT Imports: 7 Imported by: 0

README

OpenAPI Linter

The OpenAPI linter validates OpenAPI specifications for style, consistency, and best practices beyond basic spec validation.

Quick Start

CLI
# Lint an OpenAPI specification
openapi spec lint api.yaml

# Output as JSON
openapi spec lint --format json api.yaml

# Disable specific rules
openapi spec lint --disable semantic-path-params api.yaml
Go API
import (
    "context"
    "fmt"
    "os"
    
    "github.com/speakeasy-api/openapi/linter"
    "github.com/speakeasy-api/openapi/openapi"
    openapiLinter "github.com/speakeasy-api/openapi/openapi/linter"
)

func main() {
    ctx := context.Background()
    
    // Load your OpenAPI document
    f, _ := os.Open("api.yaml")
    doc, validationErrors, _ := openapi.Unmarshal(ctx, f)
    
    // Create linter with default configuration
    config := linter.NewConfig()
    lint := openapiLinter.NewLinter(config)
    
    // Run linting
    output, _ := lint.Lint(ctx, linter.NewDocumentInfo(doc, "api.yaml"), validationErrors, nil)
    
    // Print results
    fmt.Println(output.FormatText())
}

Available Rules

Rule Severity Description
oas-schema-check error Schemas must use type-appropriate constraints and have valid constraint values. For example, string types should use minLength/maxLength/pattern, numbers should use minimum/maximum/multipleOf, and constraint values must be logically valid (e.g., maxLength >= minLength).
oas3-example-missing hint Schemas, parameters, headers, and media types should include example values to illustrate expected data formats. Examples improve documentation quality, help developers understand how to use the API correctly, and enable better testing and validation.
oas3-no-nullable warning The nullable keyword is not supported in OpenAPI 3.1+ and should be replaced with a type array that includes null (e.g., type: [string, null]). This change aligns OpenAPI 3.1 with JSON Schema Draft 2020-12, which uses type arrays to express nullable values.
owasp-additional-properties-constrained hint Schemas with additionalProperties set to true or a schema should define maxProperties to limit object size. Without size limits, APIs are vulnerable to resource exhaustion attacks where clients send excessively large objects.
owasp-array-limit error Array schemas must specify maxItems to prevent resource exhaustion attacks. Without array size limits, malicious clients could send extremely large arrays that consume excessive memory or processing time.
owasp-auth-insecure-schemes error Authentication schemes using outdated or insecure methods must be avoided or upgraded. Insecure authentication schemes like API keys in query parameters or HTTP Basic over HTTP expose credentials and create security vulnerabilities.
owasp-define-error-responses-401 warning Operations should define a 401 Unauthorized response with a proper schema to handle authentication failures. Documenting authentication error responses helps clients implement proper error handling and understand when credentials are invalid or missing.
owasp-define-error-responses-429 warning Operations should define a 429 Too Many Requests response with a proper schema to indicate rate limiting. Rate limit responses help clients understand when they've exceeded usage thresholds and need to slow down requests.
owasp-define-error-responses-500 warning Operations should define a 500 Internal Server Error response with a proper schema to handle unexpected failures. Documenting server error responses helps clients distinguish between client-side and server-side problems.
owasp-define-error-validation warning Operations should define validation error responses (400, 422, or 4XX) to indicate request data problems. Validation error responses help clients understand when and why their request data is invalid or malformed.
owasp-integer-format error Integer schemas must specify a format of int32 or int64 to define the expected size and range. Explicit integer formats prevent overflow vulnerabilities and ensure clients and servers agree on numeric boundaries.
owasp-integer-limit error Integer schemas must specify minimum and maximum values (or exclusive variants) to prevent unbounded inputs. Without numeric limits, APIs are vulnerable to overflow attacks and unexpected behavior from extreme values.
owasp-jwt-best-practices error Security schemes using OAuth2 or JWT must explicitly declare support for RFC8725 (JWT Best Current Practices) in the description. RFC8725 compliance ensures JWTs are validated properly and protected against common attacks like algorithm confusion.
owasp-no-additional-properties error Object schemas must not allow arbitrary additional properties (set additionalProperties to false or omit it). Allowing unexpected properties can lead to mass assignment vulnerabilities where attackers inject unintended fields.
owasp-no-api-keys-in-url error API keys must not be passed via URL parameters (query or path) as they are logged and cached. URL-based API keys appear in browser history, server logs, and proxy caches, creating security exposure.
owasp-no-credentials-in-url error URL parameters must not contain credentials like API keys, passwords, or secrets. Credentials in URLs are logged by servers, proxies, and browsers, creating significant security risks.
owasp-no-http-basic error Security schemes must not use HTTP Basic authentication without additional security layers. HTTP Basic sends credentials in easily-decoded base64 encoding, making it vulnerable to interception without HTTPS.
owasp-no-numeric-ids error Resource identifiers must use random values like UUIDs instead of sequential numeric IDs. Sequential IDs enable enumeration attacks where attackers can guess valid IDs and access unauthorized resources.
owasp-protection-global-safe hint Safe operations (GET, HEAD) should be protected by security schemes or explicitly marked as public. Unprotected read operations may expose sensitive data to unauthorized users.
owasp-protection-global-unsafe error Unsafe operations (POST, PUT, PATCH, DELETE) must be protected by security schemes to prevent unauthorized modifications. Write operations without authentication create serious security vulnerabilities allowing data tampering.
owasp-protection-global-unsafe-strict hint Unsafe operations (POST, PUT, PATCH, DELETE) must be protected by non-empty security schemes without explicit opt-outs. Strict authentication requirements ensure write operations cannot bypass security even with empty security arrays.
owasp-rate-limit error 2XX and 4XX responses must define rate limiting headers (X-RateLimit-Limit, X-RateLimit-Remaining) to prevent API overload. Rate limit headers help clients manage their usage and avoid hitting limits.
owasp-rate-limit-retry-after error 429 Too Many Requests responses must include a Retry-After header indicating when clients can retry. Retry-After headers prevent thundering herd problems by telling clients exactly when to resume requests.
owasp-security-hosts-https-oas3 error Server URLs must begin with https:// as the only permitted protocol. Using HTTPS is essential for protecting API traffic from interception, tampering, and eavesdropping attacks.
owasp-string-limit error String schemas must specify maxLength, const, or enum to prevent unbounded data. Without string length limits, APIs are vulnerable to resource exhaustion from extremely long inputs.
owasp-string-restricted error String schemas must specify format, const, enum, or pattern to restrict content. String restrictions prevent injection attacks and ensure data conforms to expected formats.
semantic-duplicated-enum warning Enum arrays should not contain duplicate values. Duplicate enum values are redundant and can cause confusion or unexpected behavior in client code generation and validation.
semantic-link-operation error Link operationId must reference an existing operation in the API specification. This ensures that links point to valid operations, including those defined in external documents that are referenced in the specification.
semantic-no-ambiguous-paths error Path definitions must be unambiguous and distinguishable from each other to ensure correct request routing. Ambiguous paths like /users/{id} and /users/{name} can cause runtime routing conflicts since both match the same URL pattern.
semantic-no-eval-in-markdown error Markdown descriptions must not contain eval() statements, which pose serious security risks. Including eval() in documentation could enable code injection attacks if the documentation is rendered in contexts that execute JavaScript.
semantic-no-script-tags-in-markdown error Markdown descriptions must not contain

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterCustomRuleLoader

func RegisterCustomRuleLoader(loader CustomRuleLoaderFunc)

RegisterCustomRuleLoader registers a custom rule loader. This is called by the customrules package's init() function. Loaders are invoked in registration order during NewLinter.

Types

type CustomRuleLoaderFunc

type CustomRuleLoaderFunc func(config *baseLinter.CustomRulesConfig) ([]baseLinter.RuleRunner[*openapi.OpenAPI], error)

CustomRuleLoaderFunc loads custom rules from configuration. It is called during NewLinter when custom rules are configured.

type Linter

type Linter struct {
	// contains filtered or unexported fields
}

Linter is an OpenAPI-specific linter that automatically builds an index before running rules. This provides rules with efficient access to indexed document data via GetIndex().

func NewLinter

func NewLinter(config *baseLinter.Config, opts ...NewLinterOption) (*Linter, error)

NewLinter creates a new OpenAPI linter. By default, all built-in rules are registered. Use WithoutDefaultRules() to create a linter with no rules registered.

Returns an error if custom rules are configured and fail to load.

Example - Default behavior (all rules):

linter, err := NewLinter(config)

Example - No rules registered:

linter, err := NewLinter(config, WithoutDefaultRules())
linter.Registry().Register(&rules.PathParamsRule{})

The linter automatically builds an index before running rules.

func (*Linter) FilterErrors

func (l *Linter) FilterErrors(errs []error) []error

FilterErrors applies rule-level overrides and match filters to arbitrary errors. This is useful when you collect additional validation errors after the main lint run.

func (*Linter) Lint

func (l *Linter) Lint(ctx context.Context, docInfo *baseLinter.DocumentInfo[*openapi.OpenAPI], preExistingErrors []error, opts *baseLinter.LintOptions) (*baseLinter.Output, error)

Lint runs all configured rules against the document. The index is automatically built and made available to rules via DocumentInfo.Index.

func (*Linter) Registry

func (l *Linter) Registry() *baseLinter.Registry[*openapi.OpenAPI]

Registry returns the rule registry for documentation generation

type NewLinterOption

type NewLinterOption func(*newLinterOpts)

NewLinterOption is a functional option for configuring linter creation.

func WithoutDefaultRules

func WithoutDefaultRules() NewLinterOption

WithoutDefaultRules creates a linter with no rules registered. This is useful for advanced use cases where you want to register custom rules or selectively register only specific rules via the Registry() method.

Example:

linter := NewLinter(config, WithoutDefaultRules())
linter.Registry().Register(&rules.PathParamsRule{})

Directories

Path Synopsis
customrules module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL