jentic-openapi-common 1.0.0a15__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.
- jentic_openapi_common-1.0.0a15/LICENSE +202 -0
- jentic_openapi_common-1.0.0a15/NOTICE +4 -0
- jentic_openapi_common-1.0.0a15/PKG-INFO +224 -0
- jentic_openapi_common-1.0.0a15/README.md +211 -0
- jentic_openapi_common-1.0.0a15/pyproject.toml +27 -0
- jentic_openapi_common-1.0.0a15/src/jentic/apitools/openapi/common/path_security.py +176 -0
- jentic_openapi_common-1.0.0a15/src/jentic/apitools/openapi/common/py.typed +0 -0
- jentic_openapi_common-1.0.0a15/src/jentic/apitools/openapi/common/subproc.py +114 -0
- jentic_openapi_common-1.0.0a15/src/jentic/apitools/openapi/common/uri.py +341 -0
|
@@ -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,224 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jentic-openapi-common
|
|
3
|
+
Version: 1.0.0a15
|
|
4
|
+
Summary: Jentic OpenAPI Common
|
|
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-Python: >=3.11
|
|
11
|
+
Project-URL: Homepage, https://github.com/jentic/jentic-openapi-tools
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# jentic-openapi-common
|
|
15
|
+
|
|
16
|
+
Common utilities for OpenAPI tools packages. This package provides shared functionality using PEP 420 namespace packages as contribution points.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
uv add jentic-openapi-common
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Modules
|
|
25
|
+
|
|
26
|
+
### uri
|
|
27
|
+
|
|
28
|
+
URI/URL/path utilities for working with OpenAPI document references.
|
|
29
|
+
|
|
30
|
+
**Available functions:**
|
|
31
|
+
|
|
32
|
+
- `is_uri_like(s: str | None) -> bool` - Check if a string looks like a URI/URL/path
|
|
33
|
+
- `is_http_https_url(s: str | None) -> bool` - Check if string is an HTTP(S) URL
|
|
34
|
+
- `is_file_uri(s: str | None) -> bool` - Check if string is a file:// URI
|
|
35
|
+
- `is_path(s: str | None) -> bool` - Check if string is a filesystem path (not a URL)
|
|
36
|
+
- `resolve_to_absolute(uri: str, base_uri: str | None = None) -> str` - Resolve relative URIs to absolute
|
|
37
|
+
|
|
38
|
+
**Exceptions:**
|
|
39
|
+
|
|
40
|
+
- `URIResolutionError` - Raised when URI resolution fails
|
|
41
|
+
|
|
42
|
+
### path_security
|
|
43
|
+
|
|
44
|
+
Path security utilities for validating and securing filesystem access. Provides defense-in-depth protection against path traversal attacks, directory escapes, and unauthorized file access.
|
|
45
|
+
|
|
46
|
+
**Available functions:**
|
|
47
|
+
|
|
48
|
+
- `validate_path(path, *, allowed_base=None, allowed_extensions=None, resolve_symlinks=True, as_string=True) -> str | Path` - Validate and canonicalize a filesystem path with security checks. Returns `str` by default, or `Path` when `as_string=False`
|
|
49
|
+
|
|
50
|
+
**Exceptions:**
|
|
51
|
+
|
|
52
|
+
- `PathSecurityError` - Base exception for path security violations
|
|
53
|
+
- `PathTraversalError` - Path attempts to escape allowed base directory
|
|
54
|
+
- `InvalidExtensionError` - Path has disallowed file extension
|
|
55
|
+
- `SymlinkSecurityError` - Path contains symlinks when not allowed or symlink escapes boundary
|
|
56
|
+
|
|
57
|
+
### subproc
|
|
58
|
+
|
|
59
|
+
Subprocess execution utilities with enhanced error handling and cross-platform support.
|
|
60
|
+
|
|
61
|
+
## Usage Examples
|
|
62
|
+
|
|
63
|
+
### URI Utilities
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from jentic.apitools.openapi.common.uri import (
|
|
67
|
+
is_uri_like,
|
|
68
|
+
is_http_https_url,
|
|
69
|
+
is_file_uri,
|
|
70
|
+
is_path,
|
|
71
|
+
resolve_to_absolute,
|
|
72
|
+
URIResolutionError,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
# Check URI types
|
|
76
|
+
is_uri_like("https://example.com/spec.yaml") # True
|
|
77
|
+
is_http_https_url("https://example.com/spec.yaml") # True
|
|
78
|
+
is_file_uri("file:///home/user/spec.yaml") # True
|
|
79
|
+
is_path("/home/user/spec.yaml") # True
|
|
80
|
+
is_path("https://example.com/spec.yaml") # False
|
|
81
|
+
|
|
82
|
+
# Resolve relative URIs
|
|
83
|
+
absolute = resolve_to_absolute("../spec.yaml", "/home/user/project/docs/")
|
|
84
|
+
# Returns: "/home/user/project/spec.yaml"
|
|
85
|
+
|
|
86
|
+
absolute = resolve_to_absolute("spec.yaml") # Resolves against current working directory
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Path Security
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from pathlib import Path
|
|
93
|
+
from jentic.apitools.openapi.common.path_security import (
|
|
94
|
+
validate_path,
|
|
95
|
+
PathSecurityError,
|
|
96
|
+
PathTraversalError,
|
|
97
|
+
InvalidExtensionError,
|
|
98
|
+
SymlinkSecurityError,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# Basic validation - converts to absolute path (returns string by default)
|
|
102
|
+
safe_path = validate_path("./specs/openapi.yaml")
|
|
103
|
+
print(safe_path) # '/current/working/dir/specs/openapi.yaml'
|
|
104
|
+
print(type(safe_path)) # <class 'str'>
|
|
105
|
+
|
|
106
|
+
# Request Path object with as_string=False
|
|
107
|
+
safe_path_obj = validate_path("./specs/openapi.yaml", as_string=False)
|
|
108
|
+
print(safe_path_obj) # Path('/current/working/dir/specs/openapi.yaml')
|
|
109
|
+
print(type(safe_path_obj)) # <class 'pathlib.Path'>
|
|
110
|
+
|
|
111
|
+
# Return type control with as_string parameter
|
|
112
|
+
# - as_string=True (default): Returns str - best for subprocess commands
|
|
113
|
+
# - as_string=False: Returns Path - best for file operations with pathlib
|
|
114
|
+
|
|
115
|
+
# Example: Using with subprocess commands (default string return)
|
|
116
|
+
import subprocess
|
|
117
|
+
doc_path = validate_path("./specs/openapi.yaml")
|
|
118
|
+
subprocess.run(["cat", doc_path]) # Works directly, no str() conversion needed
|
|
119
|
+
|
|
120
|
+
# Example: Using with pathlib operations (Path return)
|
|
121
|
+
from pathlib import Path
|
|
122
|
+
doc_path = validate_path("./specs/openapi.yaml", as_string=False)
|
|
123
|
+
if doc_path.exists():
|
|
124
|
+
content = doc_path.read_text() # Path methods available
|
|
125
|
+
|
|
126
|
+
# Boundary enforcement - restrict access to specific directory
|
|
127
|
+
try:
|
|
128
|
+
safe_path = validate_path(
|
|
129
|
+
"/var/app/data/spec.yaml",
|
|
130
|
+
allowed_base="/var/app",
|
|
131
|
+
)
|
|
132
|
+
print(f"Access granted: {safe_path}")
|
|
133
|
+
except PathTraversalError as e:
|
|
134
|
+
print(f"Access denied: {e}")
|
|
135
|
+
|
|
136
|
+
# Block directory traversal attacks
|
|
137
|
+
try:
|
|
138
|
+
safe_path = validate_path(
|
|
139
|
+
"/var/app/../../../etc/passwd",
|
|
140
|
+
allowed_base="/var/app",
|
|
141
|
+
)
|
|
142
|
+
except PathTraversalError:
|
|
143
|
+
print("Path traversal attack blocked!")
|
|
144
|
+
|
|
145
|
+
# Extension validation - whitelist approach
|
|
146
|
+
try:
|
|
147
|
+
safe_path = validate_path(
|
|
148
|
+
"spec.yaml",
|
|
149
|
+
allowed_extensions=(".yaml", ".yml", ".json"),
|
|
150
|
+
)
|
|
151
|
+
print(f"Valid extension: {safe_path}")
|
|
152
|
+
except InvalidExtensionError:
|
|
153
|
+
print("Invalid file extension")
|
|
154
|
+
|
|
155
|
+
# Combined security checks (recommended for web services)
|
|
156
|
+
try:
|
|
157
|
+
safe_path = validate_path(
|
|
158
|
+
user_provided_path,
|
|
159
|
+
allowed_base="/var/app/uploads",
|
|
160
|
+
allowed_extensions=(".yaml", ".yml", ".json"),
|
|
161
|
+
resolve_symlinks=True, # Default: resolve and check symlinks
|
|
162
|
+
)
|
|
163
|
+
# Safe to use safe_path for file operations
|
|
164
|
+
with open(safe_path) as f:
|
|
165
|
+
content = f.read()
|
|
166
|
+
except PathSecurityError as e:
|
|
167
|
+
print(f"Security validation failed: {e}")
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Subprocess Execution
|
|
171
|
+
|
|
172
|
+
#### Basic Command Execution
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
from jentic.apitools.openapi.common.subproc import run_subprocess
|
|
176
|
+
|
|
177
|
+
# Simple command
|
|
178
|
+
result = run_subprocess(["echo", "hello"])
|
|
179
|
+
print(result.stdout) # "hello\n"
|
|
180
|
+
print(result.returncode) # 0
|
|
181
|
+
|
|
182
|
+
# Command with working directory
|
|
183
|
+
result = run_subprocess(["pwd"], cwd="/tmp")
|
|
184
|
+
print(result.stdout.strip()) # "/tmp"
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Error Handling
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from jentic.apitools.openapi.common.subproc import (
|
|
191
|
+
run_subprocess,
|
|
192
|
+
SubprocessExecutionError
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# Handle errors manually
|
|
196
|
+
result = run_subprocess(["false"]) # Command that exits with code 1
|
|
197
|
+
if result.returncode != 0:
|
|
198
|
+
print(f"Command failed with code {result.returncode}")
|
|
199
|
+
|
|
200
|
+
# Automatic error handling
|
|
201
|
+
try:
|
|
202
|
+
result = run_subprocess(["false"], fail_on_error=True)
|
|
203
|
+
except SubprocessExecutionError as e:
|
|
204
|
+
print(f"Command {e.cmd} failed: {e}")
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Advanced Usage
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
from jentic.apitools.openapi.common.subproc import (
|
|
211
|
+
run_subprocess,
|
|
212
|
+
SubprocessExecutionError
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
# Timeout handling
|
|
216
|
+
try:
|
|
217
|
+
result = run_subprocess(["sleep", "10"], timeout=1)
|
|
218
|
+
except SubprocessExecutionError as e:
|
|
219
|
+
print("Command timed out")
|
|
220
|
+
|
|
221
|
+
# Custom encoding
|
|
222
|
+
result = run_subprocess(["python", "-c", "print('ñ')"], encoding="utf-8")
|
|
223
|
+
print(result.stdout) # "ñ\n"
|
|
224
|
+
```
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# jentic-openapi-common
|
|
2
|
+
|
|
3
|
+
Common utilities for OpenAPI tools packages. This package provides shared functionality using PEP 420 namespace packages as contribution points.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
uv add jentic-openapi-common
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Modules
|
|
12
|
+
|
|
13
|
+
### uri
|
|
14
|
+
|
|
15
|
+
URI/URL/path utilities for working with OpenAPI document references.
|
|
16
|
+
|
|
17
|
+
**Available functions:**
|
|
18
|
+
|
|
19
|
+
- `is_uri_like(s: str | None) -> bool` - Check if a string looks like a URI/URL/path
|
|
20
|
+
- `is_http_https_url(s: str | None) -> bool` - Check if string is an HTTP(S) URL
|
|
21
|
+
- `is_file_uri(s: str | None) -> bool` - Check if string is a file:// URI
|
|
22
|
+
- `is_path(s: str | None) -> bool` - Check if string is a filesystem path (not a URL)
|
|
23
|
+
- `resolve_to_absolute(uri: str, base_uri: str | None = None) -> str` - Resolve relative URIs to absolute
|
|
24
|
+
|
|
25
|
+
**Exceptions:**
|
|
26
|
+
|
|
27
|
+
- `URIResolutionError` - Raised when URI resolution fails
|
|
28
|
+
|
|
29
|
+
### path_security
|
|
30
|
+
|
|
31
|
+
Path security utilities for validating and securing filesystem access. Provides defense-in-depth protection against path traversal attacks, directory escapes, and unauthorized file access.
|
|
32
|
+
|
|
33
|
+
**Available functions:**
|
|
34
|
+
|
|
35
|
+
- `validate_path(path, *, allowed_base=None, allowed_extensions=None, resolve_symlinks=True, as_string=True) -> str | Path` - Validate and canonicalize a filesystem path with security checks. Returns `str` by default, or `Path` when `as_string=False`
|
|
36
|
+
|
|
37
|
+
**Exceptions:**
|
|
38
|
+
|
|
39
|
+
- `PathSecurityError` - Base exception for path security violations
|
|
40
|
+
- `PathTraversalError` - Path attempts to escape allowed base directory
|
|
41
|
+
- `InvalidExtensionError` - Path has disallowed file extension
|
|
42
|
+
- `SymlinkSecurityError` - Path contains symlinks when not allowed or symlink escapes boundary
|
|
43
|
+
|
|
44
|
+
### subproc
|
|
45
|
+
|
|
46
|
+
Subprocess execution utilities with enhanced error handling and cross-platform support.
|
|
47
|
+
|
|
48
|
+
## Usage Examples
|
|
49
|
+
|
|
50
|
+
### URI Utilities
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from jentic.apitools.openapi.common.uri import (
|
|
54
|
+
is_uri_like,
|
|
55
|
+
is_http_https_url,
|
|
56
|
+
is_file_uri,
|
|
57
|
+
is_path,
|
|
58
|
+
resolve_to_absolute,
|
|
59
|
+
URIResolutionError,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Check URI types
|
|
63
|
+
is_uri_like("https://example.com/spec.yaml") # True
|
|
64
|
+
is_http_https_url("https://example.com/spec.yaml") # True
|
|
65
|
+
is_file_uri("file:///home/user/spec.yaml") # True
|
|
66
|
+
is_path("/home/user/spec.yaml") # True
|
|
67
|
+
is_path("https://example.com/spec.yaml") # False
|
|
68
|
+
|
|
69
|
+
# Resolve relative URIs
|
|
70
|
+
absolute = resolve_to_absolute("../spec.yaml", "/home/user/project/docs/")
|
|
71
|
+
# Returns: "/home/user/project/spec.yaml"
|
|
72
|
+
|
|
73
|
+
absolute = resolve_to_absolute("spec.yaml") # Resolves against current working directory
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Path Security
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from pathlib import Path
|
|
80
|
+
from jentic.apitools.openapi.common.path_security import (
|
|
81
|
+
validate_path,
|
|
82
|
+
PathSecurityError,
|
|
83
|
+
PathTraversalError,
|
|
84
|
+
InvalidExtensionError,
|
|
85
|
+
SymlinkSecurityError,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# Basic validation - converts to absolute path (returns string by default)
|
|
89
|
+
safe_path = validate_path("./specs/openapi.yaml")
|
|
90
|
+
print(safe_path) # '/current/working/dir/specs/openapi.yaml'
|
|
91
|
+
print(type(safe_path)) # <class 'str'>
|
|
92
|
+
|
|
93
|
+
# Request Path object with as_string=False
|
|
94
|
+
safe_path_obj = validate_path("./specs/openapi.yaml", as_string=False)
|
|
95
|
+
print(safe_path_obj) # Path('/current/working/dir/specs/openapi.yaml')
|
|
96
|
+
print(type(safe_path_obj)) # <class 'pathlib.Path'>
|
|
97
|
+
|
|
98
|
+
# Return type control with as_string parameter
|
|
99
|
+
# - as_string=True (default): Returns str - best for subprocess commands
|
|
100
|
+
# - as_string=False: Returns Path - best for file operations with pathlib
|
|
101
|
+
|
|
102
|
+
# Example: Using with subprocess commands (default string return)
|
|
103
|
+
import subprocess
|
|
104
|
+
doc_path = validate_path("./specs/openapi.yaml")
|
|
105
|
+
subprocess.run(["cat", doc_path]) # Works directly, no str() conversion needed
|
|
106
|
+
|
|
107
|
+
# Example: Using with pathlib operations (Path return)
|
|
108
|
+
from pathlib import Path
|
|
109
|
+
doc_path = validate_path("./specs/openapi.yaml", as_string=False)
|
|
110
|
+
if doc_path.exists():
|
|
111
|
+
content = doc_path.read_text() # Path methods available
|
|
112
|
+
|
|
113
|
+
# Boundary enforcement - restrict access to specific directory
|
|
114
|
+
try:
|
|
115
|
+
safe_path = validate_path(
|
|
116
|
+
"/var/app/data/spec.yaml",
|
|
117
|
+
allowed_base="/var/app",
|
|
118
|
+
)
|
|
119
|
+
print(f"Access granted: {safe_path}")
|
|
120
|
+
except PathTraversalError as e:
|
|
121
|
+
print(f"Access denied: {e}")
|
|
122
|
+
|
|
123
|
+
# Block directory traversal attacks
|
|
124
|
+
try:
|
|
125
|
+
safe_path = validate_path(
|
|
126
|
+
"/var/app/../../../etc/passwd",
|
|
127
|
+
allowed_base="/var/app",
|
|
128
|
+
)
|
|
129
|
+
except PathTraversalError:
|
|
130
|
+
print("Path traversal attack blocked!")
|
|
131
|
+
|
|
132
|
+
# Extension validation - whitelist approach
|
|
133
|
+
try:
|
|
134
|
+
safe_path = validate_path(
|
|
135
|
+
"spec.yaml",
|
|
136
|
+
allowed_extensions=(".yaml", ".yml", ".json"),
|
|
137
|
+
)
|
|
138
|
+
print(f"Valid extension: {safe_path}")
|
|
139
|
+
except InvalidExtensionError:
|
|
140
|
+
print("Invalid file extension")
|
|
141
|
+
|
|
142
|
+
# Combined security checks (recommended for web services)
|
|
143
|
+
try:
|
|
144
|
+
safe_path = validate_path(
|
|
145
|
+
user_provided_path,
|
|
146
|
+
allowed_base="/var/app/uploads",
|
|
147
|
+
allowed_extensions=(".yaml", ".yml", ".json"),
|
|
148
|
+
resolve_symlinks=True, # Default: resolve and check symlinks
|
|
149
|
+
)
|
|
150
|
+
# Safe to use safe_path for file operations
|
|
151
|
+
with open(safe_path) as f:
|
|
152
|
+
content = f.read()
|
|
153
|
+
except PathSecurityError as e:
|
|
154
|
+
print(f"Security validation failed: {e}")
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Subprocess Execution
|
|
158
|
+
|
|
159
|
+
#### Basic Command Execution
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
from jentic.apitools.openapi.common.subproc import run_subprocess
|
|
163
|
+
|
|
164
|
+
# Simple command
|
|
165
|
+
result = run_subprocess(["echo", "hello"])
|
|
166
|
+
print(result.stdout) # "hello\n"
|
|
167
|
+
print(result.returncode) # 0
|
|
168
|
+
|
|
169
|
+
# Command with working directory
|
|
170
|
+
result = run_subprocess(["pwd"], cwd="/tmp")
|
|
171
|
+
print(result.stdout.strip()) # "/tmp"
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### Error Handling
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
from jentic.apitools.openapi.common.subproc import (
|
|
178
|
+
run_subprocess,
|
|
179
|
+
SubprocessExecutionError
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
# Handle errors manually
|
|
183
|
+
result = run_subprocess(["false"]) # Command that exits with code 1
|
|
184
|
+
if result.returncode != 0:
|
|
185
|
+
print(f"Command failed with code {result.returncode}")
|
|
186
|
+
|
|
187
|
+
# Automatic error handling
|
|
188
|
+
try:
|
|
189
|
+
result = run_subprocess(["false"], fail_on_error=True)
|
|
190
|
+
except SubprocessExecutionError as e:
|
|
191
|
+
print(f"Command {e.cmd} failed: {e}")
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Advanced Usage
|
|
195
|
+
|
|
196
|
+
```python
|
|
197
|
+
from jentic.apitools.openapi.common.subproc import (
|
|
198
|
+
run_subprocess,
|
|
199
|
+
SubprocessExecutionError
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Timeout handling
|
|
203
|
+
try:
|
|
204
|
+
result = run_subprocess(["sleep", "10"], timeout=1)
|
|
205
|
+
except SubprocessExecutionError as e:
|
|
206
|
+
print("Command timed out")
|
|
207
|
+
|
|
208
|
+
# Custom encoding
|
|
209
|
+
result = run_subprocess(["python", "-c", "print('ñ')"], encoding="utf-8")
|
|
210
|
+
print(result.stdout) # "ñ\n"
|
|
211
|
+
```
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "jentic-openapi-common"
|
|
3
|
+
version = "1.0.0-alpha.15"
|
|
4
|
+
description = "Jentic OpenAPI Common"
|
|
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
|
+
|
|
12
|
+
[tool.uv]
|
|
13
|
+
package = true
|
|
14
|
+
|
|
15
|
+
[tool.uv.build-backend]
|
|
16
|
+
namespace = true
|
|
17
|
+
module-name = "jentic.apitools.openapi.common"
|
|
18
|
+
module-root = "src/"
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://github.com/jentic/jentic-openapi-tools"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build~=0.8.15"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Path security utilities for safe filesystem access."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal, overload
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"PathSecurityError",
|
|
9
|
+
"PathTraversalError",
|
|
10
|
+
"InvalidExtensionError",
|
|
11
|
+
"SymlinkSecurityError",
|
|
12
|
+
"validate_path",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PathSecurityError(Exception):
|
|
17
|
+
"""Base exception for path security violations."""
|
|
18
|
+
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PathTraversalError(PathSecurityError):
|
|
23
|
+
"""Raised when a path attempts to escape the allowed base directory."""
|
|
24
|
+
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class InvalidExtensionError(PathSecurityError):
|
|
29
|
+
"""Raised when a file has a disallowed extension."""
|
|
30
|
+
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SymlinkSecurityError(PathSecurityError):
|
|
35
|
+
"""Raised when a path contains symlinks when not allowed or symlink escapes boundary."""
|
|
36
|
+
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@overload
|
|
41
|
+
def validate_path(
|
|
42
|
+
path: str | Path,
|
|
43
|
+
*,
|
|
44
|
+
allowed_base: str | Path | None = None,
|
|
45
|
+
allowed_extensions: tuple[str, ...] | None = None,
|
|
46
|
+
resolve_symlinks: bool = True,
|
|
47
|
+
as_string: Literal[True] = True,
|
|
48
|
+
) -> str: ...
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@overload
|
|
52
|
+
def validate_path(
|
|
53
|
+
path: str | Path,
|
|
54
|
+
*,
|
|
55
|
+
allowed_base: str | Path | None = None,
|
|
56
|
+
allowed_extensions: tuple[str, ...] | None = None,
|
|
57
|
+
resolve_symlinks: bool = True,
|
|
58
|
+
as_string: Literal[False],
|
|
59
|
+
) -> Path: ...
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_path(
|
|
63
|
+
path: str | Path,
|
|
64
|
+
*,
|
|
65
|
+
allowed_base: str | Path | None = None,
|
|
66
|
+
allowed_extensions: tuple[str, ...] | None = None,
|
|
67
|
+
resolve_symlinks: bool = True,
|
|
68
|
+
as_string: bool = True,
|
|
69
|
+
) -> str | Path:
|
|
70
|
+
"""
|
|
71
|
+
Validate and canonicalize a filesystem path with security checks.
|
|
72
|
+
|
|
73
|
+
This function provides defense-in-depth security for filesystem access by:
|
|
74
|
+
1. Converting to absolute path and resolving `.` and `..` components
|
|
75
|
+
2. Optionally resolving symlinks and checking they don't escape boundaries
|
|
76
|
+
3. Enforcing boundary restrictions (path must be within allowed_base)
|
|
77
|
+
4. Validating file extensions against a whitelist
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
path: The filesystem path to validate (string or Path object)
|
|
81
|
+
allowed_base: Optional base directory that path must be within.
|
|
82
|
+
If None, no boundary checking is performed.
|
|
83
|
+
allowed_extensions: Optional tuple of allowed file extensions (e.g., ('.yaml', '.json')).
|
|
84
|
+
Extensions are case-sensitive. If None, no extension checking is performed.
|
|
85
|
+
resolve_symlinks: If True (default), resolve symlinks using Path.resolve().
|
|
86
|
+
If False, use Path.absolute() to preserve symlinks.
|
|
87
|
+
as_string: If True (default), return str. If False, return Path object.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
Canonicalized path (str by default, or Path if as_string=False) that has passed all security checks.
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
PathTraversalError: If the path attempts to escape the allowed_base directory
|
|
94
|
+
InvalidExtensionError: If the file extension is not in allowed_extensions
|
|
95
|
+
SymlinkSecurityError: If symlink resolution reveals a security issue
|
|
96
|
+
|
|
97
|
+
Examples:
|
|
98
|
+
>>> # Basic validation with boundary enforcement (returns str by default)
|
|
99
|
+
>>> validate_path("/var/app/data/file.yaml", allowed_base="/var/app")
|
|
100
|
+
'/var/app/data/file.yaml'
|
|
101
|
+
|
|
102
|
+
>>> # Return Path object when needed
|
|
103
|
+
>>> validate_path("/var/app/data/file.yaml", allowed_base="/var/app", as_string=False)
|
|
104
|
+
Path('/var/app/data/file.yaml')
|
|
105
|
+
|
|
106
|
+
>>> # Prevent directory traversal
|
|
107
|
+
>>> validate_path("/var/app/../etc/passwd", allowed_base="/var/app")
|
|
108
|
+
PathTraversalError: Path '/etc/passwd' is outside allowed base '/var/app'
|
|
109
|
+
|
|
110
|
+
>>> # Extension validation
|
|
111
|
+
>>> validate_path("file.txt", allowed_extensions=('.yaml', '.json'))
|
|
112
|
+
InvalidExtensionError: Path 'file.txt' has disallowed extension '.txt'
|
|
113
|
+
"""
|
|
114
|
+
if not path:
|
|
115
|
+
raise PathSecurityError("Path cannot be empty or None")
|
|
116
|
+
|
|
117
|
+
# Convert to Path object
|
|
118
|
+
path_obj = Path(path)
|
|
119
|
+
|
|
120
|
+
# Canonicalize path (resolve . and ..)
|
|
121
|
+
if resolve_symlinks:
|
|
122
|
+
# Fully resolve including symlinks
|
|
123
|
+
try:
|
|
124
|
+
canonical_path = path_obj.resolve(strict=False)
|
|
125
|
+
except (OSError, RuntimeError) as e:
|
|
126
|
+
raise PathSecurityError(f"Failed to resolve path '{path}': {e}") from e
|
|
127
|
+
else:
|
|
128
|
+
# Convert to absolute but preserve symlinks
|
|
129
|
+
canonical_path = path_obj.absolute()
|
|
130
|
+
|
|
131
|
+
# Boundary enforcement
|
|
132
|
+
if allowed_base is not None:
|
|
133
|
+
allowed_base_path = Path(allowed_base)
|
|
134
|
+
if resolve_symlinks:
|
|
135
|
+
try:
|
|
136
|
+
canonical_base = allowed_base_path.resolve(strict=False)
|
|
137
|
+
except (OSError, RuntimeError) as e:
|
|
138
|
+
raise PathSecurityError(
|
|
139
|
+
f"Failed to resolve allowed_base '{allowed_base}': {e}"
|
|
140
|
+
) from e
|
|
141
|
+
else:
|
|
142
|
+
canonical_base = allowed_base_path.absolute()
|
|
143
|
+
|
|
144
|
+
# Check if canonical_path is within canonical_base
|
|
145
|
+
try:
|
|
146
|
+
canonical_path.relative_to(canonical_base)
|
|
147
|
+
except ValueError:
|
|
148
|
+
raise PathTraversalError(
|
|
149
|
+
f"Path '{canonical_path}' is outside allowed base '{canonical_base}'"
|
|
150
|
+
) from None
|
|
151
|
+
|
|
152
|
+
# Additional check: if resolve_symlinks is True, verify that no symlink in the path
|
|
153
|
+
# escapes the boundary. This is already handled by resolve() above, but we add
|
|
154
|
+
# an explicit check for symlinks that might have been followed
|
|
155
|
+
if resolve_symlinks and path_obj.is_symlink():
|
|
156
|
+
# If the original path was a symlink, verify the resolved target is still in bounds
|
|
157
|
+
try:
|
|
158
|
+
canonical_path.relative_to(canonical_base)
|
|
159
|
+
except ValueError:
|
|
160
|
+
raise SymlinkSecurityError(
|
|
161
|
+
f"Symlink '{path}' resolves to '{canonical_path}' which is outside allowed base '{canonical_base}'"
|
|
162
|
+
) from None
|
|
163
|
+
|
|
164
|
+
# Extension validation
|
|
165
|
+
if allowed_extensions is not None:
|
|
166
|
+
if not canonical_path.suffix:
|
|
167
|
+
raise InvalidExtensionError(
|
|
168
|
+
f"Path '{canonical_path}' has no file extension. Allowed extensions: {allowed_extensions}"
|
|
169
|
+
)
|
|
170
|
+
if canonical_path.suffix not in allowed_extensions:
|
|
171
|
+
raise InvalidExtensionError(
|
|
172
|
+
f"Path '{canonical_path}' has disallowed extension '{canonical_path.suffix}'. "
|
|
173
|
+
f"Allowed extensions: {allowed_extensions}"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
return str(canonical_path) if as_string else canonical_path
|
|
File without changes
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Subprocess execution utilities for OpenAPI tools."""
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__all__ = ["run_subprocess", "SubprocessExecutionResult", "SubprocessExecutionError"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class SubprocessExecutionResult:
|
|
13
|
+
"""Returned by a subprocess."""
|
|
14
|
+
|
|
15
|
+
returncode: int
|
|
16
|
+
stdout: str = ""
|
|
17
|
+
stderr: str = ""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
returncode: int,
|
|
22
|
+
stdout: str | None = None,
|
|
23
|
+
stderr: str | None = None,
|
|
24
|
+
):
|
|
25
|
+
self.returncode = returncode
|
|
26
|
+
self.stdout = stdout if isinstance(stdout, str) else ""
|
|
27
|
+
self.stderr = stderr if isinstance(stderr, str) else ""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SubprocessExecutionError(RuntimeError):
|
|
31
|
+
"""Raised when a subprocess exits with non-zero return code."""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
cmd: Sequence[str],
|
|
36
|
+
returncode: int,
|
|
37
|
+
stdout: str | None = None,
|
|
38
|
+
stderr: str | None = None,
|
|
39
|
+
):
|
|
40
|
+
self.cmd = list(cmd)
|
|
41
|
+
self.returncode = returncode
|
|
42
|
+
self.stdout = stdout if isinstance(stdout, str) else ""
|
|
43
|
+
self.stderr = stderr if isinstance(stderr, str) else ""
|
|
44
|
+
message = (
|
|
45
|
+
f"Command {self.cmd!r} failed with exit code {self.returncode}\n"
|
|
46
|
+
f"--- stdout ---\n{self.stdout}\n"
|
|
47
|
+
f"--- stderr ---\n{self.stderr}"
|
|
48
|
+
)
|
|
49
|
+
super().__init__(message)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def run_subprocess(
|
|
53
|
+
cmd: Sequence[str],
|
|
54
|
+
*,
|
|
55
|
+
fail_on_error: bool = False,
|
|
56
|
+
timeout: float | None = None,
|
|
57
|
+
encoding: str = "utf-8",
|
|
58
|
+
errors: str = "strict",
|
|
59
|
+
cwd: str | None = None,
|
|
60
|
+
) -> SubprocessExecutionResult:
|
|
61
|
+
"""
|
|
62
|
+
Run a subprocess command and return (stdout, stderr) as text.
|
|
63
|
+
Raises SubprocessExecutionError if the command fails.
|
|
64
|
+
|
|
65
|
+
Parameters
|
|
66
|
+
----------
|
|
67
|
+
cmd : sequence of str
|
|
68
|
+
The command and its arguments.
|
|
69
|
+
fail_on_error : bool
|
|
70
|
+
If True, raises SubprocessExecutionError for non-zero return codes.
|
|
71
|
+
timeout : float | None
|
|
72
|
+
Seconds before timing out.
|
|
73
|
+
encoding : str
|
|
74
|
+
Passed to subprocess.run so stdout/stderr are decoded as text.
|
|
75
|
+
errors : str
|
|
76
|
+
Error handler for text decoding.
|
|
77
|
+
cwd : str | None
|
|
78
|
+
Working directory for the subprocess.
|
|
79
|
+
|
|
80
|
+
Returns
|
|
81
|
+
-------
|
|
82
|
+
(stdout, stderr, returncode): SubprocessExecutionResult
|
|
83
|
+
"""
|
|
84
|
+
try:
|
|
85
|
+
completed_process = subprocess.run(
|
|
86
|
+
cmd,
|
|
87
|
+
check=False,
|
|
88
|
+
capture_output=True,
|
|
89
|
+
text=True,
|
|
90
|
+
shell=False,
|
|
91
|
+
encoding=encoding, # ensure the CompletedProcess has stdout/stderr
|
|
92
|
+
errors=errors,
|
|
93
|
+
timeout=timeout,
|
|
94
|
+
cwd=cwd,
|
|
95
|
+
)
|
|
96
|
+
except subprocess.TimeoutExpired as e:
|
|
97
|
+
stdout = e.stdout.decode(encoding, errors) if isinstance(e.stdout, bytes) else e.stdout
|
|
98
|
+
stderr = e.stderr.decode(encoding, errors) if isinstance(e.stderr, bytes) else e.stderr
|
|
99
|
+
raise SubprocessExecutionError(cmd, -1, stdout, stderr) from e
|
|
100
|
+
except OSError as e: # e.g., executable not found, permission denied
|
|
101
|
+
raise SubprocessExecutionError(cmd, -1, None, str(e)) from e
|
|
102
|
+
|
|
103
|
+
if completed_process.returncode != 0 and fail_on_error:
|
|
104
|
+
raise SubprocessExecutionError(
|
|
105
|
+
cmd,
|
|
106
|
+
completed_process.returncode,
|
|
107
|
+
completed_process.stdout,
|
|
108
|
+
completed_process.stderr,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# At this point CompletedProcess stdout/stderr are str due to text=True + encoding
|
|
112
|
+
return SubprocessExecutionResult(
|
|
113
|
+
completed_process.returncode, completed_process.stdout, completed_process.stderr
|
|
114
|
+
)
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from urllib.parse import urljoin, urlparse, urlsplit, urlunsplit
|
|
5
|
+
from urllib.request import url2pathname
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"URIResolutionError",
|
|
10
|
+
"is_uri_like",
|
|
11
|
+
"is_http_https_url",
|
|
12
|
+
"is_file_uri",
|
|
13
|
+
"is_scheme_relative_uri",
|
|
14
|
+
"is_absolute_uri",
|
|
15
|
+
"is_fragment_only_uri",
|
|
16
|
+
"is_path",
|
|
17
|
+
"resolve_to_absolute",
|
|
18
|
+
"file_uri_to_path",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
|
|
23
|
+
_WINDOWS_UNC_RE = re.compile(r"^(?:\\\\|//)[^\\/]+[\\/][^\\/]+")
|
|
24
|
+
|
|
25
|
+
# Matches:
|
|
26
|
+
# - http://... or https://...
|
|
27
|
+
# - file://...
|
|
28
|
+
# - POSIX absolute: /path or just "/"
|
|
29
|
+
# - Windows UNC: \\server\share\...
|
|
30
|
+
# - Windows root-relative: \path\to (current drive root)
|
|
31
|
+
# - Windows drive-absolute: C:\path\to or C:/path/to
|
|
32
|
+
# - Relative paths: ./path, ../path, .\path, ..\path, or plain relative paths
|
|
33
|
+
_URI_LIKE_RE = re.compile(
|
|
34
|
+
r"""^(?:
|
|
35
|
+
https?://[^\r\n]+ |
|
|
36
|
+
file://[^\r\n]+ |
|
|
37
|
+
/[^\r\n]* |
|
|
38
|
+
\\\\[^\r\n]+ |
|
|
39
|
+
\\[^\r\n]+ |
|
|
40
|
+
[A-Za-z]:\\[^\r\n]+ |
|
|
41
|
+
[A-Za-z]:/[^\r\n]+ |
|
|
42
|
+
\./[^\r\n]* |
|
|
43
|
+
\.\\/[^\r\n]* |
|
|
44
|
+
\.\.[/\\][^\r\n]* |
|
|
45
|
+
\.\.\\[^\r\n]* |
|
|
46
|
+
[a-zA-Z_][a-zA-Z0-9_.-]*(?:[/\\][a-zA-Z0-9_.-]+)+ |
|
|
47
|
+
[a-zA-Z_][a-zA-Z0-9_.-]*\.[a-zA-Z0-9]+(?![}\])])
|
|
48
|
+
)$""",
|
|
49
|
+
re.VERBOSE,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class URIResolutionError(ValueError):
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_uri_like(uri: str | None) -> bool:
|
|
58
|
+
r"""
|
|
59
|
+
Heuristic check: is `s` a URI-like reference or absolute/relative path?
|
|
60
|
+
- Accepts http(s)://, file://
|
|
61
|
+
- Accepts absolute POSIX (/...) and Windows (\\..., \..., C:\..., C:/...) paths
|
|
62
|
+
- Accepts relative paths (./..., ../..., .\..., ..\...)
|
|
63
|
+
- Must be a single line (no '\\n' or '\\r').
|
|
64
|
+
Leading/trailing whitespace is ignored.
|
|
65
|
+
"""
|
|
66
|
+
if not uri:
|
|
67
|
+
return False
|
|
68
|
+
uri = uri.strip()
|
|
69
|
+
# Enforce single line
|
|
70
|
+
if "\n" in uri or "\r" in uri:
|
|
71
|
+
return False
|
|
72
|
+
return bool(_URI_LIKE_RE.match(uri))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_path(s: str | None) -> bool:
|
|
76
|
+
"""
|
|
77
|
+
Check if `s` is a filesystem path (not a URL or URI).
|
|
78
|
+
|
|
79
|
+
Returns True for:
|
|
80
|
+
- Absolute POSIX paths: /home/file.txt
|
|
81
|
+
- Absolute Windows paths: C:\\Windows\\file.txt, \\\\server\\share\\path
|
|
82
|
+
- Relative paths: ./config.yaml, ../parent/file.txt
|
|
83
|
+
|
|
84
|
+
Returns False for:
|
|
85
|
+
- HTTP(S) URLs: http://example.com
|
|
86
|
+
- File URIs: file:///home/file.txt
|
|
87
|
+
- Other URIs: mailto:test@example.com, data:text/plain, ftp://ftp.example.com
|
|
88
|
+
- Empty or None strings
|
|
89
|
+
"""
|
|
90
|
+
if not s:
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
s = s.strip()
|
|
94
|
+
|
|
95
|
+
# Must match the URI-like pattern first
|
|
96
|
+
if not is_uri_like(s):
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
# Exclude HTTP(S) URLs
|
|
100
|
+
if is_http_https_url(s):
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
# Exclude file:// URIs
|
|
104
|
+
if is_file_uri(s):
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
# Exclude any other URI schemes (mailto:, data:, ftp:, etc.)
|
|
108
|
+
parsed = urlparse(s)
|
|
109
|
+
if parsed.scheme: # Has a scheme
|
|
110
|
+
return False
|
|
111
|
+
|
|
112
|
+
# It's a path!
|
|
113
|
+
return True
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def is_http_https_url(url: str) -> bool:
|
|
117
|
+
p = urlparse(url)
|
|
118
|
+
return p.scheme in ("http", "https") and bool(p.netloc)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def is_file_uri(uri: str) -> bool:
|
|
122
|
+
return urlparse(uri).scheme == "file"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def is_scheme_relative_uri(uri: str) -> bool:
|
|
126
|
+
"""
|
|
127
|
+
Check if `uri` is a scheme-relative URI (also called protocol-relative URI).
|
|
128
|
+
|
|
129
|
+
A scheme-relative URI starts with "//" followed by an authority component (netloc),
|
|
130
|
+
inheriting the scheme from the context (e.g., "//cdn.example.com/path").
|
|
131
|
+
|
|
132
|
+
This is defined in RFC 3986 section 4.2 as a network-path reference.
|
|
133
|
+
Per RFC 3986, a valid network-path reference must have an authority component.
|
|
134
|
+
|
|
135
|
+
Examples:
|
|
136
|
+
- "//cdn.example.com/x.yaml" -> True
|
|
137
|
+
- "//example.com/api" -> True
|
|
138
|
+
- "http://example.com" -> False (has scheme)
|
|
139
|
+
- "/path/to/file" -> False (single slash)
|
|
140
|
+
- "./relative" -> False (relative path)
|
|
141
|
+
- "//" -> False (no authority component)
|
|
142
|
+
- "///path" -> False (no authority component)
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
uri: The string to check
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
True if the string is a valid scheme-relative URI with authority, False otherwise
|
|
149
|
+
"""
|
|
150
|
+
if not uri.startswith("//"):
|
|
151
|
+
return False
|
|
152
|
+
p = urlparse(uri)
|
|
153
|
+
return bool(p.netloc)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def is_absolute_uri(uri: str) -> bool:
|
|
157
|
+
"""
|
|
158
|
+
Check if `uri` is an absolute URI according to RFC 3986.
|
|
159
|
+
|
|
160
|
+
An absolute URI is defined as having a scheme (e.g., "http:", "https:", "ftp:", "file:").
|
|
161
|
+
|
|
162
|
+
Note: Scheme-relative URIs (starting with "//") are NOT considered absolute URIs.
|
|
163
|
+
According to RFC 3986 section 4.2, scheme-relative URIs are classified as
|
|
164
|
+
"relative references" (specifically, "network-path references").
|
|
165
|
+
Use `is_scheme_relative_uri()` to check for those separately.
|
|
166
|
+
|
|
167
|
+
Examples:
|
|
168
|
+
- "http://example.com" -> True
|
|
169
|
+
- "https://example.com/path" -> True
|
|
170
|
+
- "ftp://ftp.example.com" -> True
|
|
171
|
+
- "file:///path/to/file" -> True
|
|
172
|
+
- "//cdn.example.com/x.yaml" -> False (scheme-relative, use is_scheme_relative_uri)
|
|
173
|
+
- "/path/to/file" -> False (absolute path, not URI)
|
|
174
|
+
- "./relative" -> False
|
|
175
|
+
- "#fragment" -> False
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
uri: The string to check
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
True if the string is an absolute URI (has a scheme), False otherwise
|
|
182
|
+
"""
|
|
183
|
+
p = urlparse(uri)
|
|
184
|
+
return bool(p.scheme)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def is_fragment_only_uri(uri: str) -> bool:
|
|
188
|
+
"""
|
|
189
|
+
Check if `uri` is a fragment-only reference.
|
|
190
|
+
|
|
191
|
+
A fragment-only reference consists solely of a fragment identifier (starts with "#").
|
|
192
|
+
These are used in JSON References and OpenAPI to refer to parts within the same document.
|
|
193
|
+
|
|
194
|
+
Note: This checks if the ENTIRE string is a fragment reference, not whether
|
|
195
|
+
a URI contains a fragment. For example, "http://example.com#section" would
|
|
196
|
+
return False because it's a full URI with a fragment, not fragment-only.
|
|
197
|
+
|
|
198
|
+
Examples:
|
|
199
|
+
- "#/definitions/User" -> True
|
|
200
|
+
- "#fragment" -> True
|
|
201
|
+
- "#" -> True (empty fragment identifier)
|
|
202
|
+
- "##" -> True (fragment identifier is "#")
|
|
203
|
+
- "http://example.com#section" -> False (full URI with fragment)
|
|
204
|
+
- "/path/to/file" -> False
|
|
205
|
+
- "./relative" -> False
|
|
206
|
+
- "" -> False
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
uri: The string to check
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
True if the string is a fragment-only reference, False otherwise
|
|
213
|
+
"""
|
|
214
|
+
return uri.startswith("#")
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def resolve_to_absolute(value: str, base_uri: str | None = None) -> str:
|
|
218
|
+
"""
|
|
219
|
+
Resolve `value` to either:
|
|
220
|
+
- an absolute URL (with scheme), OR
|
|
221
|
+
- an absolute filesystem path (no scheme)
|
|
222
|
+
|
|
223
|
+
• If `base_uri` is None AND `value` has no scheme (i.e., relative URI or path),
|
|
224
|
+
return an **absolute filesystem path** resolved against CWD.
|
|
225
|
+
|
|
226
|
+
Other rules:
|
|
227
|
+
• Absolute http(s) URLs ⇒ return absolute URL.
|
|
228
|
+
• file:// URIs ⇒ return absolute filesystem path.
|
|
229
|
+
• If `base_uri` is an http(s) URL, relative inputs resolve to absolute URLs.
|
|
230
|
+
• If `base_uri` is a path or file://, relative inputs resolve to absolute paths.
|
|
231
|
+
• Mixing a path-like `value` with an http(s) `base_uri` raises (ambiguous).
|
|
232
|
+
• Scheme-relative (“//host/path”) without a URL base ⇒ raises.
|
|
233
|
+
"""
|
|
234
|
+
_guard_single_line(value)
|
|
235
|
+
|
|
236
|
+
if is_http_https_url(value):
|
|
237
|
+
return _normalize_url(value)
|
|
238
|
+
|
|
239
|
+
if is_file_uri(value):
|
|
240
|
+
return file_uri_to_path(value)
|
|
241
|
+
|
|
242
|
+
if _looks_like_windows_path(value):
|
|
243
|
+
return _resolve_path_like(value, base_uri)
|
|
244
|
+
|
|
245
|
+
parsed = urlparse(value)
|
|
246
|
+
# Scheme-relative without URL base is ambiguous
|
|
247
|
+
if value.startswith("//"):
|
|
248
|
+
if base_uri and is_http_https_url(base_uri):
|
|
249
|
+
return _normalize_url(urljoin(base_uri, value))
|
|
250
|
+
raise URIResolutionError("Scheme-relative URLs require a URL base_uri.")
|
|
251
|
+
|
|
252
|
+
# Any other explicit scheme (mailto:, data:, ftp:, etc.) → accept as-is
|
|
253
|
+
if parsed.scheme:
|
|
254
|
+
if parsed.scheme in ("http", "https"):
|
|
255
|
+
if not parsed.netloc:
|
|
256
|
+
raise URIResolutionError(f"Malformed URL (missing host): {value!r}")
|
|
257
|
+
return _normalize_url(value)
|
|
258
|
+
if parsed.scheme == "file":
|
|
259
|
+
# handled above
|
|
260
|
+
raise AssertionError("unreachable")
|
|
261
|
+
return value # leave non-file, non-http schemes untouched
|
|
262
|
+
|
|
263
|
+
# --- No scheme: relative URI or path ---
|
|
264
|
+
if base_uri:
|
|
265
|
+
if is_http_https_url(base_uri):
|
|
266
|
+
# Relative URI against URL base → absolute URL
|
|
267
|
+
return _normalize_url(urljoin(base_uri, value))
|
|
268
|
+
# base is file path or file:// → absolute path
|
|
269
|
+
return _resolve_path_like(value, base_uri)
|
|
270
|
+
|
|
271
|
+
# **Your rule**: no base + no scheme ⇒ absolute filesystem path
|
|
272
|
+
return _resolve_path_like(value, None)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def file_uri_to_path(file_uri: str) -> str:
|
|
276
|
+
"""
|
|
277
|
+
Convert a file:// URI to an absolute filesystem path.
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
file_uri: A file:// URI string (e.g., "file:///path/to/file" or "file://server/share/path")
|
|
281
|
+
|
|
282
|
+
Returns:
|
|
283
|
+
Absolute filesystem path as a string
|
|
284
|
+
|
|
285
|
+
Raises:
|
|
286
|
+
URIResolutionError: If the input is not a valid file:// URI
|
|
287
|
+
|
|
288
|
+
Examples:
|
|
289
|
+
>>> file_uri_to_path("file:///home/user/doc.yaml")
|
|
290
|
+
'/home/user/doc.yaml'
|
|
291
|
+
>>> file_uri_to_path("file://localhost/etc/config.yaml")
|
|
292
|
+
'/etc/config.yaml'
|
|
293
|
+
"""
|
|
294
|
+
parsed_uri = urlparse(file_uri)
|
|
295
|
+
if parsed_uri.scheme != "file":
|
|
296
|
+
raise URIResolutionError(f"Not a file URI: {file_uri!r}")
|
|
297
|
+
if parsed_uri.netloc and parsed_uri.netloc not in ("", "localhost"):
|
|
298
|
+
# UNC: \\server\share\path
|
|
299
|
+
unc = f"//{parsed_uri.netloc}{parsed_uri.path}"
|
|
300
|
+
return str(Path(url2pathname(unc)).resolve())
|
|
301
|
+
path = url2pathname(parsed_uri.path)
|
|
302
|
+
return str(Path(path).resolve())
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _guard_single_line(s: str) -> None:
|
|
306
|
+
if not isinstance(s, str) or ("\n" in s or "\r" in s):
|
|
307
|
+
raise URIResolutionError("Input must be a single-line string.")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _looks_like_windows_path(s: str) -> bool:
|
|
311
|
+
return bool(_WINDOWS_DRIVE_RE.match(s) or _WINDOWS_UNC_RE.match(s))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _normalize_url(s: str) -> str:
|
|
315
|
+
import posixpath
|
|
316
|
+
|
|
317
|
+
parts = urlsplit(s)
|
|
318
|
+
# Normalize the path component using posixpath (URLs always use forward slashes)
|
|
319
|
+
normalized_path = posixpath.normpath(parts.path) if parts.path else "/"
|
|
320
|
+
# Ensure root path is "/"
|
|
321
|
+
if normalized_path == ".":
|
|
322
|
+
normalized_path = "/"
|
|
323
|
+
return urlunsplit((parts.scheme, parts.netloc, normalized_path, parts.query, parts.fragment))
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _resolve_path_like(value: str, base_uri: str | None) -> str:
|
|
327
|
+
value = os.path.expandvars(os.path.expanduser(value))
|
|
328
|
+
|
|
329
|
+
if base_uri:
|
|
330
|
+
if is_file_uri(base_uri):
|
|
331
|
+
base_path = Path(url2pathname(urlparse(base_uri).path))
|
|
332
|
+
elif is_http_https_url(base_uri):
|
|
333
|
+
# Don't silently combine a local path with a URL base
|
|
334
|
+
raise URIResolutionError("Cannot resolve a local path against an HTTP(S) base_uri.")
|
|
335
|
+
else:
|
|
336
|
+
base_path = Path(os.path.expandvars(os.path.expanduser(base_uri)))
|
|
337
|
+
else:
|
|
338
|
+
base_path = Path.cwd()
|
|
339
|
+
|
|
340
|
+
p = Path(value)
|
|
341
|
+
return str(p.resolve() if p.is_absolute() else (base_path / p).resolve())
|