jentic-openapi-validator-speclynx 1.0.0a34__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ Jentic OpenAPI Tools
2
+ Copyright (c) 2026 Jentic
3
+ Jentic OpenAPI Tools is licensed under Apache 2.0 license.
4
+ Copy of the Apache 2.0 license can be found in `LICENSE` file.
@@ -0,0 +1,311 @@
1
+ Metadata-Version: 2.4
2
+ Name: jentic-openapi-validator-speclynx
3
+ Version: 1.0.0a34
4
+ Summary: Jentic OpenAPI SpecLynx Validator Backend
5
+ Author: Jentic
6
+ Author-email: Jentic <hello@jentic.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Requires-Dist: jentic-openapi-common~=1.0.0a34
11
+ Requires-Dist: jentic-openapi-validator~=1.0.0a34
12
+ Requires-Dist: lsprotocol~=2025.0.0
13
+ Requires-Python: >=3.11
14
+ Project-URL: Homepage, https://github.com/jentic/jentic-openapi-tools
15
+ Description-Content-Type: text/markdown
16
+
17
+ # jentic-openapi-validator-speclynx
18
+
19
+ A [SpecLynx ApiDOM](https://github.com/speclynx/apidom) validator backend for the Jentic OpenAPI Tools ecosystem.
20
+ This package provides OpenAPI document validation using SpecLynx ApiDOM with comprehensive error reporting and flexible
21
+ configuration options.
22
+
23
+ ## Features
24
+
25
+ - **Multiple input formats**: Validate OpenAPI documents from file URIs or Python dictionaries
26
+ - **Custom plugins**: Use built-in plugins or provide your own validation plugins
27
+ - **Configurable timeouts**: Control execution time limits for different use cases
28
+ - **Rich diagnostics**: Detailed validation results with line/column information
29
+ - **Type-safe API**: Full typing support with Literal types and comprehensive docstrings
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install jentic-openapi-validator-speclynx
35
+ ```
36
+
37
+ **Prerequisites:**
38
+
39
+ - Node.js and npm (for SpecLynx CLI)
40
+ - Python 3.11+
41
+
42
+ The SpecLynx dependencies will be automatically installed via npm on first use.
43
+
44
+ ## Quick Start
45
+
46
+ ### Basic Usage
47
+
48
+ ```python
49
+ from jentic.apitools.openapi.validator.backends.speclynx import SpeclynxValidatorBackend
50
+
51
+ # Create validator with defaults
52
+ validator = SpeclynxValidatorBackend()
53
+
54
+ # Validate from file URI
55
+ result = validator.validate("file:///path/to/openapi.yaml")
56
+ print(f"Valid: {result.valid}")
57
+
58
+ # Check for validation issues
59
+ if not result.valid:
60
+ for diagnostic in result.diagnostics:
61
+ print(f"Error: {diagnostic.message}")
62
+ ```
63
+
64
+ ### Validate Dictionary Documents
65
+
66
+ ```python
67
+ # Validate from dictionary
68
+ openapi_doc = {
69
+ "openapi": "3.0.0",
70
+ "info": {"title": "My API", "version": "1.0.0"},
71
+ "paths": {}
72
+ }
73
+
74
+ result = validator.validate(openapi_doc)
75
+ print(f"Document is valid: {result.valid}")
76
+ ```
77
+
78
+ ## Configuration Options
79
+
80
+ ### Custom Plugins Directory
81
+
82
+ ```python
83
+ # Use additional plugins directory (merged with built-in plugins)
84
+ validator = SpeclynxValidatorBackend(plugins_dir="/path/to/custom-plugins")
85
+
86
+ # The validator loads all .mjs files from both:
87
+ # 1. Built-in plugins directory (always loaded)
88
+ # 2. Custom plugins directory (merged with built-in plugins)
89
+ ```
90
+
91
+ ### Timeout Configuration
92
+
93
+ ```python
94
+ # Short timeout for CI/CD (10 seconds)
95
+ validator = SpeclynxValidatorBackend(timeout=10.0)
96
+
97
+ # Extended timeout for large documents (2 minutes)
98
+ validator = SpeclynxValidatorBackend(timeout=120.0)
99
+
100
+ # Combined configuration (45 seconds)
101
+ validator = SpeclynxValidatorBackend(
102
+ plugins_dir="/path/to/custom-plugins",
103
+ timeout=45.0
104
+ )
105
+ ```
106
+
107
+ ### Custom SpecLynx Path
108
+
109
+ By default, the validator uses the bundled SpecLynx CLI via npx. You can override this to use a custom installation:
110
+
111
+ ```python
112
+ # Use custom speclynx installation
113
+ validator = SpeclynxValidatorBackend(speclynx_path="/usr/local/bin/speclynx")
114
+
115
+ # Install additional npm packages for custom plugins that have dependencies
116
+ # The -p flag installs packages before running the CLI
117
+ validator = SpeclynxValidatorBackend(
118
+ speclynx_path="npx --yes -p lodash -p moment jentic-openapi-validator-speclynx-0.1.0.tgz"
119
+ )
120
+ ```
121
+
122
+ ### Path Security
123
+
124
+ Use `allowed_base_dir` to restrict file access when processing untrusted input or running as a web service:
125
+
126
+ ```python
127
+ from jentic.apitools.openapi.common.path_security import (
128
+ PathTraversalError,
129
+ InvalidExtensionError,
130
+ )
131
+
132
+ # Restrict file access to /var/app/documents directory
133
+ validator = SpeclynxValidatorBackend(
134
+ allowed_base_dir="/var/app/documents"
135
+ )
136
+
137
+ # Valid paths within allowed directory work normally
138
+ result = validator.validate("/var/app/documents/specs/openapi.yaml")
139
+
140
+ # Path traversal attempts are blocked
141
+ try:
142
+ result = validator.validate("/var/app/documents/../../etc/passwd")
143
+ except PathTraversalError as e:
144
+ print(f"Security violation: {e}")
145
+
146
+ # Invalid file extensions are rejected
147
+ try:
148
+ result = validator.validate("/var/app/documents/malicious.exe")
149
+ except InvalidExtensionError as e:
150
+ print(f"Invalid file type: {e}")
151
+
152
+ # HTTP(S) URLs bypass path validation (as expected)
153
+ result = validator.validate("https://example.com/openapi.yaml")
154
+
155
+ # Combined security configuration for web services
156
+ validator = SpeclynxValidatorBackend(
157
+ allowed_base_dir="/var/app/uploads",
158
+ plugins_dir="/var/app/config/custom-plugins",
159
+ timeout=600.0
160
+ )
161
+ ```
162
+
163
+ **Security Benefits:**
164
+
165
+ - Prevents path traversal attacks (`../../etc/passwd`)
166
+ - Restricts access to allowed directories only (when `allowed_base_dir` is set)
167
+ - Validates file extensions (`.yaml`, `.yml`, `.json`) - **always enforced**, even when `allowed_base_dir=None`
168
+ - Checks symlinks don't escape boundaries (when `allowed_base_dir` is set)
169
+
170
+ **Note:** File extension validation (`.yaml`, `.yml`, `.json`) is always performed for filesystem paths, regardless of
171
+ whether `allowed_base_dir` is set. When `allowed_base_dir=None`, only the base directory containment check is skipped.
172
+
173
+ ## Advanced Usage
174
+
175
+ ### Error Handling
176
+
177
+ ```python
178
+ from jentic.apitools.openapi.common.subproc import SubprocessExecutionError
179
+
180
+ try:
181
+ result = validator.validate("file:///path/to/openapi.yaml")
182
+
183
+ if result.valid:
184
+ print("Document is valid")
185
+ else:
186
+ print("Validation failed:")
187
+ for diagnostic in result.diagnostics:
188
+ severity = diagnostic.severity.name
189
+ line = diagnostic.range.start.line + 1
190
+ print(f" {severity}: {diagnostic.message} (line {line})")
191
+
192
+ except SubprocessExecutionError as e:
193
+ print(f"SpecLynx execution failed: {e}")
194
+ except TypeError as e:
195
+ print(f"Invalid document type: {e}")
196
+ ```
197
+
198
+ ### Supported Document Formats
199
+
200
+ ```python
201
+ # Check what formats the validator supports
202
+ formats = validator.accepts()
203
+ print(formats) # ['uri', 'dict']
204
+
205
+ # Validate different input types
206
+ if "uri" in validator.accepts():
207
+ result = validator.validate("file:///path/to/spec.yaml")
208
+
209
+ if "dict" in validator.accepts():
210
+ result = validator.validate({"openapi": "3.0.0", ...})
211
+ ```
212
+
213
+ ## Custom Plugins
214
+
215
+ Create custom validation plugins as ES modules (`.mjs` files). Plugins use the ApiDOM visitor pattern:
216
+
217
+ ```javascript
218
+ // custom-plugin.mjs
219
+ import {toValue} from '@speclynx/apidom-core';
220
+ import {DiagnosticSeverity} from 'vscode-languageserver-types';
221
+
222
+ export default ({diagnostics}) => () => ({
223
+ pre() {
224
+ },
225
+ visitor: {
226
+ InfoElement(path) {
227
+ const info = path.node;
228
+ const version = info.get('version');
229
+
230
+ if (version && typeof toValue(version) !== 'string') {
231
+ diagnostics.push({
232
+ severity: DiagnosticSeverity.Error,
233
+ message: 'info.version must be a string',
234
+ code: 'invalid-info-version-type',
235
+ range: {
236
+ start: {line: 0, character: 0},
237
+ end: {line: 0, character: 0}
238
+ },
239
+ data: {path: ['info', 'version']}
240
+ });
241
+ }
242
+ }
243
+ },
244
+ post() {
245
+ },
246
+ });
247
+ ```
248
+
249
+ Use it with the validator:
250
+
251
+ ```python
252
+ validator = SpeclynxValidatorBackend(plugins_dir="./custom-plugins")
253
+ result = validator.validate("file:///path/to/openapi.yaml")
254
+ ```
255
+
256
+ **Note:** Custom plugins are merged with built-in plugins. Both the built-in plugins and your custom plugins will run
257
+ during validation.
258
+
259
+ ## Testing
260
+
261
+ ### Integration Tests
262
+
263
+ The integration tests require Node.js to be available. They will be automatically skipped if Node.js is not installed.
264
+
265
+ **Run the integration test:**
266
+
267
+ ```bash
268
+ uv run --package jentic-openapi-validator-speclynx pytest packages/jentic-openapi-validator-speclynx -v
269
+ ```
270
+
271
+ ## API Reference
272
+
273
+ ### SpeclynxValidatorBackend
274
+
275
+ ```python
276
+ class SpeclynxValidatorBackend(BaseValidatorBackend):
277
+ def __init__(
278
+ self,
279
+ speclynx_path: str = "npx --yes jentic-openapi-validator-speclynx-0.1.0.tgz",
280
+ timeout: float = 600.0,
281
+ allowed_base_dir: str | Path | None = None,
282
+ plugins_dir: str | Path | None = None,
283
+ ) -> None
284
+ ```
285
+
286
+ **Parameters:**
287
+
288
+ - `speclynx_path`: Path to the SpecLynx CLI executable. Default uses bundled npm tarball via npx. Can be a custom path
289
+ like `/usr/local/bin/speclynx` or an npx command with additional packages (optional)
290
+ - `timeout`: Maximum execution time in seconds (default: 600.0)
291
+ - `allowed_base_dir`: Optional base directory for path security validation. When set, all document paths are validated
292
+ to be within this directory, providing defense against path traversal attacks. When `None` (default), only file
293
+ extension validation is performed (no base directory containment check). Recommended for web services or untrusted
294
+ input (optional)
295
+ - `plugins_dir`: Optional directory containing additional validation plugins (`.mjs` files). When specified, custom
296
+ plugins are merged with built-in plugins (both are loaded). If `None` (default), only built-in plugins are used
297
+ (optional)
298
+
299
+ **Methods:**
300
+
301
+ - `accepts() -> list[Literal["uri", "dict"]]`: Returns supported document format identifiers
302
+ - `validate(document: str | dict, *, base_url: str | None = None, target: str | None = None) -> ValidationResult`:
303
+ Validates an OpenAPI document
304
+
305
+ **Exceptions:**
306
+
307
+ - `RuntimeError`: SpecLynx execution fails
308
+ - `SubprocessExecutionError`: SpecLynx times out or fails to start
309
+ - `TypeError`: Unsupported document type
310
+ - `PathTraversalError`: Document path attempts to escape allowed_base_dir (only when `allowed_base_dir` is set)
311
+ - `InvalidExtensionError`: Document path has disallowed file extension (always checked for filesystem paths)
@@ -0,0 +1,295 @@
1
+ # jentic-openapi-validator-speclynx
2
+
3
+ A [SpecLynx ApiDOM](https://github.com/speclynx/apidom) validator backend for the Jentic OpenAPI Tools ecosystem.
4
+ This package provides OpenAPI document validation using SpecLynx ApiDOM with comprehensive error reporting and flexible
5
+ configuration options.
6
+
7
+ ## Features
8
+
9
+ - **Multiple input formats**: Validate OpenAPI documents from file URIs or Python dictionaries
10
+ - **Custom plugins**: Use built-in plugins or provide your own validation plugins
11
+ - **Configurable timeouts**: Control execution time limits for different use cases
12
+ - **Rich diagnostics**: Detailed validation results with line/column information
13
+ - **Type-safe API**: Full typing support with Literal types and comprehensive docstrings
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install jentic-openapi-validator-speclynx
19
+ ```
20
+
21
+ **Prerequisites:**
22
+
23
+ - Node.js and npm (for SpecLynx CLI)
24
+ - Python 3.11+
25
+
26
+ The SpecLynx dependencies will be automatically installed via npm on first use.
27
+
28
+ ## Quick Start
29
+
30
+ ### Basic Usage
31
+
32
+ ```python
33
+ from jentic.apitools.openapi.validator.backends.speclynx import SpeclynxValidatorBackend
34
+
35
+ # Create validator with defaults
36
+ validator = SpeclynxValidatorBackend()
37
+
38
+ # Validate from file URI
39
+ result = validator.validate("file:///path/to/openapi.yaml")
40
+ print(f"Valid: {result.valid}")
41
+
42
+ # Check for validation issues
43
+ if not result.valid:
44
+ for diagnostic in result.diagnostics:
45
+ print(f"Error: {diagnostic.message}")
46
+ ```
47
+
48
+ ### Validate Dictionary Documents
49
+
50
+ ```python
51
+ # Validate from dictionary
52
+ openapi_doc = {
53
+ "openapi": "3.0.0",
54
+ "info": {"title": "My API", "version": "1.0.0"},
55
+ "paths": {}
56
+ }
57
+
58
+ result = validator.validate(openapi_doc)
59
+ print(f"Document is valid: {result.valid}")
60
+ ```
61
+
62
+ ## Configuration Options
63
+
64
+ ### Custom Plugins Directory
65
+
66
+ ```python
67
+ # Use additional plugins directory (merged with built-in plugins)
68
+ validator = SpeclynxValidatorBackend(plugins_dir="/path/to/custom-plugins")
69
+
70
+ # The validator loads all .mjs files from both:
71
+ # 1. Built-in plugins directory (always loaded)
72
+ # 2. Custom plugins directory (merged with built-in plugins)
73
+ ```
74
+
75
+ ### Timeout Configuration
76
+
77
+ ```python
78
+ # Short timeout for CI/CD (10 seconds)
79
+ validator = SpeclynxValidatorBackend(timeout=10.0)
80
+
81
+ # Extended timeout for large documents (2 minutes)
82
+ validator = SpeclynxValidatorBackend(timeout=120.0)
83
+
84
+ # Combined configuration (45 seconds)
85
+ validator = SpeclynxValidatorBackend(
86
+ plugins_dir="/path/to/custom-plugins",
87
+ timeout=45.0
88
+ )
89
+ ```
90
+
91
+ ### Custom SpecLynx Path
92
+
93
+ By default, the validator uses the bundled SpecLynx CLI via npx. You can override this to use a custom installation:
94
+
95
+ ```python
96
+ # Use custom speclynx installation
97
+ validator = SpeclynxValidatorBackend(speclynx_path="/usr/local/bin/speclynx")
98
+
99
+ # Install additional npm packages for custom plugins that have dependencies
100
+ # The -p flag installs packages before running the CLI
101
+ validator = SpeclynxValidatorBackend(
102
+ speclynx_path="npx --yes -p lodash -p moment jentic-openapi-validator-speclynx-0.1.0.tgz"
103
+ )
104
+ ```
105
+
106
+ ### Path Security
107
+
108
+ Use `allowed_base_dir` to restrict file access when processing untrusted input or running as a web service:
109
+
110
+ ```python
111
+ from jentic.apitools.openapi.common.path_security import (
112
+ PathTraversalError,
113
+ InvalidExtensionError,
114
+ )
115
+
116
+ # Restrict file access to /var/app/documents directory
117
+ validator = SpeclynxValidatorBackend(
118
+ allowed_base_dir="/var/app/documents"
119
+ )
120
+
121
+ # Valid paths within allowed directory work normally
122
+ result = validator.validate("/var/app/documents/specs/openapi.yaml")
123
+
124
+ # Path traversal attempts are blocked
125
+ try:
126
+ result = validator.validate("/var/app/documents/../../etc/passwd")
127
+ except PathTraversalError as e:
128
+ print(f"Security violation: {e}")
129
+
130
+ # Invalid file extensions are rejected
131
+ try:
132
+ result = validator.validate("/var/app/documents/malicious.exe")
133
+ except InvalidExtensionError as e:
134
+ print(f"Invalid file type: {e}")
135
+
136
+ # HTTP(S) URLs bypass path validation (as expected)
137
+ result = validator.validate("https://example.com/openapi.yaml")
138
+
139
+ # Combined security configuration for web services
140
+ validator = SpeclynxValidatorBackend(
141
+ allowed_base_dir="/var/app/uploads",
142
+ plugins_dir="/var/app/config/custom-plugins",
143
+ timeout=600.0
144
+ )
145
+ ```
146
+
147
+ **Security Benefits:**
148
+
149
+ - Prevents path traversal attacks (`../../etc/passwd`)
150
+ - Restricts access to allowed directories only (when `allowed_base_dir` is set)
151
+ - Validates file extensions (`.yaml`, `.yml`, `.json`) - **always enforced**, even when `allowed_base_dir=None`
152
+ - Checks symlinks don't escape boundaries (when `allowed_base_dir` is set)
153
+
154
+ **Note:** File extension validation (`.yaml`, `.yml`, `.json`) is always performed for filesystem paths, regardless of
155
+ whether `allowed_base_dir` is set. When `allowed_base_dir=None`, only the base directory containment check is skipped.
156
+
157
+ ## Advanced Usage
158
+
159
+ ### Error Handling
160
+
161
+ ```python
162
+ from jentic.apitools.openapi.common.subproc import SubprocessExecutionError
163
+
164
+ try:
165
+ result = validator.validate("file:///path/to/openapi.yaml")
166
+
167
+ if result.valid:
168
+ print("Document is valid")
169
+ else:
170
+ print("Validation failed:")
171
+ for diagnostic in result.diagnostics:
172
+ severity = diagnostic.severity.name
173
+ line = diagnostic.range.start.line + 1
174
+ print(f" {severity}: {diagnostic.message} (line {line})")
175
+
176
+ except SubprocessExecutionError as e:
177
+ print(f"SpecLynx execution failed: {e}")
178
+ except TypeError as e:
179
+ print(f"Invalid document type: {e}")
180
+ ```
181
+
182
+ ### Supported Document Formats
183
+
184
+ ```python
185
+ # Check what formats the validator supports
186
+ formats = validator.accepts()
187
+ print(formats) # ['uri', 'dict']
188
+
189
+ # Validate different input types
190
+ if "uri" in validator.accepts():
191
+ result = validator.validate("file:///path/to/spec.yaml")
192
+
193
+ if "dict" in validator.accepts():
194
+ result = validator.validate({"openapi": "3.0.0", ...})
195
+ ```
196
+
197
+ ## Custom Plugins
198
+
199
+ Create custom validation plugins as ES modules (`.mjs` files). Plugins use the ApiDOM visitor pattern:
200
+
201
+ ```javascript
202
+ // custom-plugin.mjs
203
+ import {toValue} from '@speclynx/apidom-core';
204
+ import {DiagnosticSeverity} from 'vscode-languageserver-types';
205
+
206
+ export default ({diagnostics}) => () => ({
207
+ pre() {
208
+ },
209
+ visitor: {
210
+ InfoElement(path) {
211
+ const info = path.node;
212
+ const version = info.get('version');
213
+
214
+ if (version && typeof toValue(version) !== 'string') {
215
+ diagnostics.push({
216
+ severity: DiagnosticSeverity.Error,
217
+ message: 'info.version must be a string',
218
+ code: 'invalid-info-version-type',
219
+ range: {
220
+ start: {line: 0, character: 0},
221
+ end: {line: 0, character: 0}
222
+ },
223
+ data: {path: ['info', 'version']}
224
+ });
225
+ }
226
+ }
227
+ },
228
+ post() {
229
+ },
230
+ });
231
+ ```
232
+
233
+ Use it with the validator:
234
+
235
+ ```python
236
+ validator = SpeclynxValidatorBackend(plugins_dir="./custom-plugins")
237
+ result = validator.validate("file:///path/to/openapi.yaml")
238
+ ```
239
+
240
+ **Note:** Custom plugins are merged with built-in plugins. Both the built-in plugins and your custom plugins will run
241
+ during validation.
242
+
243
+ ## Testing
244
+
245
+ ### Integration Tests
246
+
247
+ The integration tests require Node.js to be available. They will be automatically skipped if Node.js is not installed.
248
+
249
+ **Run the integration test:**
250
+
251
+ ```bash
252
+ uv run --package jentic-openapi-validator-speclynx pytest packages/jentic-openapi-validator-speclynx -v
253
+ ```
254
+
255
+ ## API Reference
256
+
257
+ ### SpeclynxValidatorBackend
258
+
259
+ ```python
260
+ class SpeclynxValidatorBackend(BaseValidatorBackend):
261
+ def __init__(
262
+ self,
263
+ speclynx_path: str = "npx --yes jentic-openapi-validator-speclynx-0.1.0.tgz",
264
+ timeout: float = 600.0,
265
+ allowed_base_dir: str | Path | None = None,
266
+ plugins_dir: str | Path | None = None,
267
+ ) -> None
268
+ ```
269
+
270
+ **Parameters:**
271
+
272
+ - `speclynx_path`: Path to the SpecLynx CLI executable. Default uses bundled npm tarball via npx. Can be a custom path
273
+ like `/usr/local/bin/speclynx` or an npx command with additional packages (optional)
274
+ - `timeout`: Maximum execution time in seconds (default: 600.0)
275
+ - `allowed_base_dir`: Optional base directory for path security validation. When set, all document paths are validated
276
+ to be within this directory, providing defense against path traversal attacks. When `None` (default), only file
277
+ extension validation is performed (no base directory containment check). Recommended for web services or untrusted
278
+ input (optional)
279
+ - `plugins_dir`: Optional directory containing additional validation plugins (`.mjs` files). When specified, custom
280
+ plugins are merged with built-in plugins (both are loaded). If `None` (default), only built-in plugins are used
281
+ (optional)
282
+
283
+ **Methods:**
284
+
285
+ - `accepts() -> list[Literal["uri", "dict"]]`: Returns supported document format identifiers
286
+ - `validate(document: str | dict, *, base_url: str | None = None, target: str | None = None) -> ValidationResult`:
287
+ Validates an OpenAPI document
288
+
289
+ **Exceptions:**
290
+
291
+ - `RuntimeError`: SpecLynx execution fails
292
+ - `SubprocessExecutionError`: SpecLynx times out or fails to start
293
+ - `TypeError`: Unsupported document type
294
+ - `PathTraversalError`: Document path attempts to escape allowed_base_dir (only when `allowed_base_dir` is set)
295
+ - `InvalidExtensionError`: Document path has disallowed file extension (always checked for filesystem paths)
@@ -0,0 +1,46 @@
1
+ [project]
2
+ name = "jentic-openapi-validator-speclynx"
3
+ version = "1.0.0-alpha.34"
4
+ description = "Jentic OpenAPI SpecLynx Validator Backend"
5
+ readme = "README.md"
6
+ authors = [{ name = "Jentic", email = "hello@jentic.com" }]
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "jentic-openapi-common~=1.0.0-alpha.34",
12
+ "jentic-openapi-validator~=1.0.0-alpha.34",
13
+ "lsprotocol~=2025.0.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/jentic/jentic-openapi-tools"
18
+
19
+ [tool.uv]
20
+ package = true
21
+
22
+ [tool.uv.build-backend]
23
+ namespace = true
24
+ module-name = "jentic.apitools.openapi.validator.backends.speclynx"
25
+ module-root = "src/"
26
+ # Only include .tgz tarball, exclude source files
27
+ source-exclude = ["resources/*.mjs", "resources/*.json", "resources/plugins"]
28
+ wheel-exclude = ["resources/*.mjs", "resources/*.json", "resources/plugins"]
29
+ source-include = ["resources/*.tgz"]
30
+ wheel-include = ["resources/*.tgz"]
31
+
32
+ [tool.uv.sources]
33
+ jentic-openapi-common = { workspace = true }
34
+ jentic-openapi-validator = { workspace = true }
35
+
36
+ [build-system]
37
+ requires = ["uv_build~=0.8.15"]
38
+ build-backend = "uv_build"
39
+
40
+ [tool.poe.tasks]
41
+ [tool.poe.tasks."speclynx:pack"]
42
+ shell = "npm pack src/jentic/apitools/openapi/validator/backends/speclynx/resources --pack-destination src/jentic/apitools/openapi/validator/backends/speclynx/resources"
43
+
44
+
45
+ [project.entry-points."jentic.apitools.openapi.validator.backends"]
46
+ speclynx = "jentic.apitools.openapi.validator.backends.speclynx:SpeclynxValidatorBackend"
@@ -0,0 +1,289 @@
1
+ import json
2
+ import logging
3
+ import shlex
4
+ import tempfile
5
+ from collections.abc import Sequence
6
+ from importlib.resources import as_file, files
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from lsprotocol.types import DiagnosticSeverity, Position, Range
11
+
12
+ from jentic.apitools.openapi.common.path_security import validate_path
13
+ from jentic.apitools.openapi.common.subproc import (
14
+ SubprocessExecutionError,
15
+ SubprocessExecutionResult,
16
+ run_subprocess,
17
+ )
18
+ from jentic.apitools.openapi.common.uri import file_uri_to_path, is_file_uri, is_path
19
+ from jentic.apitools.openapi.validator.backends.base import BaseValidatorBackend
20
+ from jentic.apitools.openapi.validator.core import JenticDiagnostic, ValidationResult
21
+
22
+
23
+ __all__ = ["SpeclynxValidatorBackend"]
24
+
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ _TARBALL_NAME = "jentic-openapi-validator-speclynx-0.1.0.tgz"
29
+ _DEFAULT_SPECLYNX_PATH = f"npx --yes {_TARBALL_NAME}"
30
+
31
+ resources_dir = files("jentic.apitools.openapi.validator.backends.speclynx.resources")
32
+ tarball_file = resources_dir.joinpath(_TARBALL_NAME)
33
+
34
+
35
+ class SpeclynxValidatorBackend(BaseValidatorBackend):
36
+ def __init__(
37
+ self,
38
+ speclynx_path: str = _DEFAULT_SPECLYNX_PATH,
39
+ timeout: float = 600.0,
40
+ allowed_base_dir: str | Path | None = None,
41
+ plugins_dir: str | Path | None = None,
42
+ ):
43
+ """
44
+ Initialize the SpeclynxValidatorBackend.
45
+
46
+ Args:
47
+ speclynx_path: Path to the speclynx CLI executable (default: uses bundled npm tarball via npx).
48
+ Can be a custom path like "/usr/local/bin/speclynx" or an npx command.
49
+ Uses shell-safe parsing to handle quoted arguments properly.
50
+ timeout: Maximum time in seconds to wait for validation execution (default: 600.0)
51
+ allowed_base_dir: Optional base directory for path security validation.
52
+ When set, all document paths will be validated to ensure they
53
+ are within this directory. This provides defense against path traversal attacks
54
+ and is recommended for web services or when processing untrusted input.
55
+ If None (default), only file extension validation is performed (no base directory
56
+ containment check). Extension validation ensures only .yaml, .yml, and .json files
57
+ are processed.
58
+ plugins_dir: Optional directory containing additional validation plugins (.mjs files).
59
+ Plugins are loaded automatically and used to validate the OpenAPI document.
60
+ When specified, custom plugins are merged with the built-in plugins (both are loaded).
61
+ If None (default), only the built-in plugins directory is used (which is empty by default).
62
+ See resources/plugins/example-plugin.mjs.sample for plugin format.
63
+ """
64
+ self.speclynx_path = speclynx_path
65
+ self.timeout = timeout
66
+ self.allowed_base_dir = allowed_base_dir
67
+ self.plugins_dir = Path(plugins_dir) if plugins_dir else None
68
+
69
+ @staticmethod
70
+ def accepts() -> Sequence[Literal["uri", "dict"]]:
71
+ """Return the document formats this validator can accept.
72
+
73
+ Returns:
74
+ Sequence of supported document format identifiers:
75
+ - "uri": File path or URI pointing to OpenAPI Document
76
+ - "dict": Python dictionary containing OpenAPI Document data
77
+ """
78
+ return ["uri", "dict"]
79
+
80
+ def validate(
81
+ self, document: str | dict, *, base_url: str | None = None, target: str | None = None
82
+ ) -> ValidationResult:
83
+ """
84
+ Validate an OpenAPI document using SpecLynx ApiDOM.
85
+
86
+ Args:
87
+ document: Path to the OpenAPI document file to validate, or dict containing the document
88
+ base_url: Optional base URL for resolving relative references
89
+ target: Optional target identifier for validation context
90
+
91
+ Returns:
92
+ ValidationResult containing any validation issues found
93
+
94
+ Raises:
95
+ RuntimeError: If validation execution fails
96
+ SubprocessExecutionError: If validation execution times out or fails to start
97
+ TypeError: If a document type is not supported
98
+ PathTraversalError: Document path attempts to escape allowed_base_dir (only when allowed_base_dir is set)
99
+ InvalidExtensionError: Document path has disallowed file extension (always checked for filesystem paths)
100
+ """
101
+ if isinstance(document, str):
102
+ return self._validate_uri(document, base_url=base_url, target=target)
103
+ elif isinstance(document, dict):
104
+ return self._validate_dict(document, base_url=base_url, target=target)
105
+ else:
106
+ raise TypeError(f"Unsupported document type: {type(document)!r}")
107
+
108
+ def _validate_uri(
109
+ self, document: str, *, base_url: str | None = None, target: str | None = None
110
+ ) -> ValidationResult:
111
+ """
112
+ Validate an OpenAPI document using SpecLynx ApiDOM.
113
+
114
+ Args:
115
+ document: Path to the OpenAPI document file to validate
116
+ base_url: Optional base URL for resolving relative references
117
+ target: Optional target identifier for validation context
118
+
119
+ Returns:
120
+ ValidationResult containing any validation issues found
121
+ """
122
+ result: SubprocessExecutionResult | None = None
123
+
124
+ try:
125
+ doc_path = file_uri_to_path(document) if is_file_uri(document) else document
126
+
127
+ # Validate document path if it's a filesystem path (skip non-path URIs like HTTP(S))
128
+ validated_doc_path = (
129
+ validate_path(
130
+ doc_path,
131
+ allowed_base=self.allowed_base_dir,
132
+ allowed_extensions=(".yaml", ".yml", ".json"),
133
+ )
134
+ if is_path(doc_path)
135
+ else doc_path
136
+ )
137
+
138
+ # Determine output file path
139
+ with tempfile.NamedTemporaryFile() as tmp_output:
140
+ output_path = tmp_output.name
141
+
142
+ try:
143
+ cmd = [
144
+ *shlex.split(self.speclynx_path),
145
+ validated_doc_path,
146
+ "-o",
147
+ output_path,
148
+ ]
149
+ if base_url:
150
+ cmd.extend(["--base-uri", base_url])
151
+ if self.plugins_dir:
152
+ cmd.extend(["--plugins", str(self.plugins_dir)])
153
+ if self.allowed_base_dir:
154
+ cmd.extend(["--allowed-base-dir", str(self.allowed_base_dir)])
155
+
156
+ # npx with bundled tarball requires cwd set to resources directory
157
+ if self.speclynx_path == _DEFAULT_SPECLYNX_PATH:
158
+ with as_file(tarball_file) as tarball_path:
159
+ resources_path = tarball_path.parent
160
+ result = run_subprocess(cmd, timeout=self.timeout, cwd=str(resources_path))
161
+ else:
162
+ result = run_subprocess(cmd, timeout=self.timeout)
163
+
164
+ if result is None:
165
+ raise RuntimeError("SpecLynx validation failed - no result returned")
166
+
167
+ # Check for execution errors
168
+ # Exit code 0 = valid, exit code 1 = has validation errors, other = execution error
169
+ if result.returncode not in (0, 1):
170
+ stderr_msg = result.stderr.strip()
171
+ custom_diagnostics = self._handle_error(
172
+ stderr_msg, result, validated_doc_path, target
173
+ )
174
+ if custom_diagnostics is not None:
175
+ return custom_diagnostics
176
+
177
+ # Default error handling
178
+ msg = stderr_msg or f"SpecLynx exited with code {result.returncode}"
179
+ raise RuntimeError(msg)
180
+
181
+ # Read and parse output file
182
+ try:
183
+ with open(output_path, encoding="utf-8") as f:
184
+ diagnostics_data: list[dict] = json.load(f)
185
+ except FileNotFoundError:
186
+ if result.stderr:
187
+ raise RuntimeError(
188
+ f"SpecLynx did not create output file: {result.stderr.strip()}"
189
+ )
190
+ logger.warning("SpecLynx output file not found, returning empty diagnostics")
191
+ return ValidationResult(diagnostics=[])
192
+ except json.JSONDecodeError as e:
193
+ if result.stderr:
194
+ raise RuntimeError(
195
+ f"SpecLynx output is not valid JSON: {result.stderr.strip()}"
196
+ )
197
+ logger.warning(
198
+ f"SpecLynx output is not valid JSON: {e}, returning empty diagnostics"
199
+ )
200
+ return ValidationResult(diagnostics=[])
201
+ finally:
202
+ # Clean up the temp output file
203
+ Path(output_path).unlink(missing_ok=True)
204
+
205
+ except SubprocessExecutionError as e:
206
+ # only timeout and OS errors, as run_subprocess has a default `fail_on_error = False`
207
+ raise e
208
+
209
+ # Convert diagnostics to JenticDiagnostic format (already LSP compatible)
210
+ diagnostics: list[JenticDiagnostic] = []
211
+ for issue in diagnostics_data:
212
+ range_data = issue["range"]
213
+ diagnostic = JenticDiagnostic(
214
+ range=Range(
215
+ start=Position(**range_data["start"]),
216
+ end=Position(**range_data["end"]),
217
+ ),
218
+ message=issue["message"],
219
+ severity=DiagnosticSeverity(issue["severity"]),
220
+ code=issue.get("code"),
221
+ source="speclynx-validator",
222
+ )
223
+ diagnostic.set_target(target)
224
+ if "data" in issue and "path" in issue["data"]:
225
+ diagnostic.set_path(issue["data"]["path"])
226
+ diagnostics.append(diagnostic)
227
+
228
+ return ValidationResult(diagnostics=diagnostics)
229
+
230
+ def _validate_dict(
231
+ self, document: dict, *, base_url: str | None = None, target: str | None = None
232
+ ) -> ValidationResult:
233
+ """Validate a dict document by creating a temporary file and using _validate_uri."""
234
+ with tempfile.NamedTemporaryFile(
235
+ mode="w", suffix=".json", delete=True, encoding="utf-8"
236
+ ) as temp_file:
237
+ json.dump(document, temp_file)
238
+ temp_file.flush() # Ensure content is written to disk
239
+
240
+ return self._validate_uri(
241
+ Path(temp_file.name).as_uri(), base_url=base_url, target=target
242
+ )
243
+
244
+ def _handle_error(
245
+ self,
246
+ stderr_msg: str,
247
+ result: SubprocessExecutionResult,
248
+ document_path: str,
249
+ target: str | None = None,
250
+ ) -> ValidationResult | None:
251
+ """Handle custom error cases from SpecLynx execution.
252
+
253
+ This is an extension point for subclasses to provide custom error handling.
254
+ By default, returns None to proceed with standard error handling (raising RuntimeError).
255
+
256
+ If this method returns a ValidationResult, that result will be returned to the caller.
257
+ If this method returns None, the default error handling will proceed (raising RuntimeError).
258
+
259
+ Args:
260
+ stderr_msg: The stderr output from SpecLynx
261
+ result: The subprocess execution result from SpecLynx
262
+ document_path: The path or URL being validated
263
+ target: Optional target identifier for validation context
264
+
265
+ Returns:
266
+ ValidationResult if the error was handled, None to proceed with default handling
267
+
268
+ Example:
269
+ Override this method to handle specific errors gracefully:
270
+
271
+ def _handle_error(self, stderr_msg, result, document_path, target):
272
+ # Handle fetch errors (403, 404, etc.) by returning diagnostics
273
+ if "Could not parse" in stderr_msg and "://" in document_path:
274
+ diagnostic = JenticDiagnostic(
275
+ range=Range(start=Position(line=0, character=0),
276
+ end=Position(line=0, character=0)),
277
+ message=f"Could not fetch document: {document_path}",
278
+ severity=DiagnosticSeverity.Error,
279
+ code="document-fetch-error",
280
+ source="speclynx-validator",
281
+ )
282
+ diagnostic.set_target(target)
283
+ return ValidationResult(diagnostics=[diagnostic])
284
+
285
+ # Fall back to default behavior
286
+ return super()._handle_error(stderr_msg, result, document_path, target)
287
+ """
288
+ # Return None to proceed with default error handling (raising RuntimeError)
289
+ return None