Jentic OpenAPI Redocly Validator Backend
Project description
jentic-openapi-validator-redocly
A Redocly validator backend for the Jentic OpenAPI Tools ecosystem. This package provides OpenAPI document validation using Redocly CLI with comprehensive error reporting and flexible configuration options.
Features
- Multiple input formats: Validate OpenAPI documents from file URIs or Python dictionaries
- Custom rulesets: Use built-in rules or provide your own Redocly ruleset
- Configurable timeouts: Control execution time limits for different use cases
- Rich diagnostics: Detailed validation results with line/column information
- Type-safe API: Full typing support with Literal types and comprehensive docstrings
Installation
pip install jentic-openapi-validator-redocly
Prerequisites:
- Node.js and npm (for Redocly CLI)
- Python 3.11+
The Redocly CLI will be automatically downloaded via npx on first use, or you can install it globally:
npm install -g @redocly/cli@2.20.0
Quick Start
Basic Usage
from jentic.apitools.openapi.validator.backends.redocly import RedoclyValidatorBackend
# Create validator with defaults
validator = RedoclyValidatorBackend()
# Validate from file URI
result = validator.validate("file:///path/to/openapi.yaml")
print(f"Valid: {result.valid}")
# Check for validation issues
if not result.valid:
for diagnostic in result.diagnostics:
print(f"Error: {diagnostic.message}")
Validate Dictionary Documents
# Validate from dictionary
openapi_doc = {
"openapi": "3.0.0",
"info": {"title": "My API", "version": "1.0.0"},
"paths": {}
}
result = validator.validate(openapi_doc)
print(f"Document is valid: {result.valid}")
Configuration Options
Custom Redocly CLI Path
# Use local Redocly installation
validator = RedoclyValidatorBackend(redocly_path="/usr/local/bin/redocly")
# Use specific version via npx
validator = RedoclyValidatorBackend(redocly_path="npx --yes @redocly/cli@2.20.0")
Custom Rulesets
# Use custom ruleset file
validator = RedoclyValidatorBackend(ruleset_path="/path/to/custom-rules.yaml")
# The validator automatically falls back to bundled rulesets if no custom path is provided
Timeout Configuration
# Short timeout for CI/CD (10 seconds)
validator = RedoclyValidatorBackend(timeout=10.0)
# Extended timeout for large documents (2 minutes)
validator = RedoclyValidatorBackend(timeout=120.0)
# Combined configuration (45 seconds)
validator = RedoclyValidatorBackend(
redocly_path="/usr/local/bin/redocly",
ruleset_path="/path/to/strict-rules.yaml",
timeout=45.0
)
Path Security
Use allowed_base_dir to restrict file access when processing untrusted input or running as a web service:
from jentic.apitools.openapi.common.path_security import (
PathTraversalError,
InvalidExtensionError,
)
# Restrict file access to /var/app/documents directory
validator = RedoclyValidatorBackend(
allowed_base_dir="/var/app/documents"
)
# Valid paths within allowed directory work normally
result = validator.validate("/var/app/documents/specs/openapi.yaml")
# Path traversal attempts are blocked
try:
result = validator.validate("/var/app/documents/../../etc/passwd")
except PathTraversalError as e:
print(f"Security violation: {e}")
# Invalid file extensions are rejected
try:
result = validator.validate("/var/app/documents/malicious.exe")
except InvalidExtensionError as e:
print(f"Invalid file type: {e}")
# HTTP(S) URLs bypass path validation (as expected)
result = validator.validate("https://example.com/openapi.yaml")
# Combined security configuration for web services
validator = RedoclyValidatorBackend(
allowed_base_dir="/var/app/uploads",
ruleset_path="/var/app/config/custom-rules.yaml", # Also validated
timeout=30.0
)
Security Benefits:
- Prevents path traversal attacks (
../../etc/passwd) - Restricts access to allowed directories only (when
allowed_base_diris set) - Validates file extensions (
.yaml,.yml,.json) - always enforced, even whenallowed_base_dir=None - Checks symlinks don't escape boundaries (when
allowed_base_diris set) - Validates both document and ruleset paths
Note: File extension validation (.yaml, .yml, .json) is always performed for filesystem paths, regardless of
whether allowed_base_dir is set. When allowed_base_dir=None, only the base directory containment check is skipped.
Advanced Usage
Error Handling
from jentic.apitools.openapi.common.subproc import SubprocessExecutionError
try:
result = validator.validate("file:///path/to/openapi.yaml")
if result.valid:
print("✅ Document is valid")
else:
print("❌ Validation failed:")
for diagnostic in result.diagnostics:
severity = diagnostic.severity.name
line = diagnostic.range.start.line + 1
print(f" {severity}: {diagnostic.message} (line {line})")
except FileNotFoundError as e:
print(f"Ruleset file not found: {e}")
except SubprocessExecutionError as e:
print(f"Redocly execution failed: {e}")
except TypeError as e:
print(f"Invalid document type: {e}")
Supported Document Formats
# Check what formats the validator supports
formats = validator.accepts()
print(formats) # ['uri', 'dict']
# Validate different input types
if "uri" in validator.accepts():
result = validator.validate("file:///path/to/spec.yaml")
if "dict" in validator.accepts():
result = validator.validate({"openapi": "3.0.0", ...})
Custom Rulesets
Create a custom Redocly ruleset file:
# custom-rules.yaml
extends:
- recommended
rules:
info-contact: error
info-description: error
operation-description: error
operation-summary: warn
path-parameters-defined: error
# Disable specific rules
no-server-example.com: off
Use it with the validator:
validator = RedoclyValidatorBackend(ruleset_path="./custom-rules.yaml")
result = validator.validate("file:///path/to/openapi.yaml")
Testing
Integration Tests
The integration tests require Redocly CLI to be available. They will be automatically skipped if Redocly is not installed.
Run the integration test:
uv run --package jentic-openapi-validator-redocly pytest packages/jentic-openapi-validator-redocly -v
API Reference
RedoclyValidatorBackend
class RedoclyValidatorBackend(BaseValidatorBackend):
def __init__(
self,
redocly_path: str = "npx --yes @redocly/cli@2.20.0",
ruleset_path: str | None = None,
timeout: float = 600.0,
allowed_base_dir: str | Path | None = None,
) -> None
Parameters:
redocly_path: Path to Redocly CLI executableruleset_path: Path to a custom ruleset file (optional)timeout: Maximum execution time in secondsallowed_base_dir: Optional base directory for path security validation. When set, all document and ruleset paths are validated to be within this directory, providing defense against path traversal attacks. WhenNone(default), only file extension validation is performed (no base directory containment check). Recommended for web services or untrusted input (optional)
Methods:
accepts() -> list[Literal["uri", "dict"]]: Returns supported document format identifiersvalidate(document: str | dict, *, base_url: str | None = None, target: str | None = None) -> ValidationResult: Validates an OpenAPI document
Exceptions:
FileNotFoundError: Custom ruleset file doesn't existRuntimeError: Redocly execution failsSubprocessExecutionError: Redocly times out or fails to startTypeError: Unsupported document typePathTraversalError: Document or ruleset path attempts to escape allowed_base_dir (only whenallowed_base_diris set)InvalidExtensionError: Document or ruleset path has disallowed file extension (always checked for filesystem paths)
Exit Codes
Redocly CLI uses the following exit codes:
- 0: No validation errors found
- 1: Validation errors found (document has issues)
- 2+: Command-line or configuration errors
License
Apache License 2.0 - See LICENSE file for details.
Links
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jentic_openapi_validator_redocly-1.0.0a45.tar.gz.
File metadata
- Download URL: jentic_openapi_validator_redocly-1.0.0a45.tar.gz
- Upload date:
- Size: 11.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ed13d9e52661948f97363dc47b2156a3ef713eafd81bf8407a861bddf44ee60d
|
|
| MD5 |
370cc3ccf26a38d1ebacf799a60d5631
|
|
| BLAKE2b-256 |
ae3df114ae803237aad5779dabe596554453ce2f6f84cfd1785316df60c36541
|
Provenance
The following attestation bundles were made for jentic_openapi_validator_redocly-1.0.0a45.tar.gz:
Publisher:
release.yml on jentic/jentic-openapi-tools
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
jentic_openapi_validator_redocly-1.0.0a45.tar.gz -
Subject digest:
ed13d9e52661948f97363dc47b2156a3ef713eafd81bf8407a861bddf44ee60d - Sigstore transparency entry: 1066669461
- Sigstore integration time:
-
Permalink:
jentic/jentic-openapi-tools@119834da8b938509548f8e0b38a03db9bdc387b1 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/jentic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@119834da8b938509548f8e0b38a03db9bdc387b1 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file jentic_openapi_validator_redocly-1.0.0a45-py3-none-any.whl.
File metadata
- Download URL: jentic_openapi_validator_redocly-1.0.0a45-py3-none-any.whl
- Upload date:
- Size: 15.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f1830d1d785213017b2d85dc03b874129aab70c25da1463678a08fd5cc0c9654
|
|
| MD5 |
8411671c6120082d2c5ac8603c407e95
|
|
| BLAKE2b-256 |
e83cd2b9f90f59fc39274a7a9be5dfccf6ce010a7153380c24db9853aa2edd05
|
Provenance
The following attestation bundles were made for jentic_openapi_validator_redocly-1.0.0a45-py3-none-any.whl:
Publisher:
release.yml on jentic/jentic-openapi-tools
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
jentic_openapi_validator_redocly-1.0.0a45-py3-none-any.whl -
Subject digest:
f1830d1d785213017b2d85dc03b874129aab70c25da1463678a08fd5cc0c9654 - Sigstore transparency entry: 1066669494
- Sigstore integration time:
-
Permalink:
jentic/jentic-openapi-tools@119834da8b938509548f8e0b38a03db9bdc387b1 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/jentic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@119834da8b938509548f8e0b38a03db9bdc387b1 -
Trigger Event:
workflow_dispatch
-
Statement type: