opa-py-wasm 1.2.1__py3-none-any.whl
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.
- opa_py_wasm-1.2.1.dist-info/METADATA +212 -0
- opa_py_wasm-1.2.1.dist-info/RECORD +17 -0
- opa_py_wasm-1.2.1.dist-info/WHEEL +4 -0
- opa_py_wasm-1.2.1.dist-info/licenses/LICENSE +21 -0
- opapywasm/__init__.py +74 -0
- opapywasm/abi.py +331 -0
- opapywasm/builtins.py +227 -0
- opapywasm/data.py +110 -0
- opapywasm/errors.py +101 -0
- opapywasm/evaluator.py +214 -0
- opapywasm/instance.py +244 -0
- opapywasm/memory.py +268 -0
- opapywasm/policy.py +387 -0
- opapywasm/pool.py +314 -0
- opapywasm/py.typed +3 -0
- opapywasm/runtime.py +488 -0
- opapywasm/types.py +159 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: opa-py-wasm
|
|
3
|
+
Version: 1.2.1
|
|
4
|
+
Summary: In-process, thread-safe Python SDK for evaluating OPA policies compiled to WebAssembly, built on wasmtime.py
|
|
5
|
+
Keywords: opa,open-policy-agent,wasm,webassembly,policy,authorization
|
|
6
|
+
Author: Sanjana Goel, Ravi Chauhan
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Security
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Dist: wasmtime>=46.0.0,<47.0.0
|
|
22
|
+
Requires-Dist: pyyaml>=6.0 ; extra == 'yaml'
|
|
23
|
+
Requires-Python: >=3.10, <4.0
|
|
24
|
+
Project-URL: Homepage, https://github.com/intuit/opa-py-wasm
|
|
25
|
+
Project-URL: Repository, https://github.com/intuit/opa-py-wasm
|
|
26
|
+
Project-URL: Issues, https://github.com/intuit/opa-py-wasm/issues
|
|
27
|
+
Project-URL: Changelog, https://github.com/intuit/opa-py-wasm/blob/main/CHANGELOG.md
|
|
28
|
+
Provides-Extra: yaml
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# opa-py-wasm
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+
[](https://github.com/intuit/opa-py-wasm/actions/workflows/ci.yml)
|
|
35
|
+

|
|
36
|
+
[](https://pypi.org/project/opa-py-wasm/)
|
|
37
|
+
[](https://github.com/intuit/opa-py-wasm/blob/main/LICENSE)
|
|
38
|
+
|
|
39
|
+
`opa-py-wasm` is an in-process, thread-safe Python SDK for evaluating
|
|
40
|
+
[Open Policy Agent](https://www.openpolicyagent.org/) policies compiled to
|
|
41
|
+
WebAssembly, built on [`wasmtime.py`](https://github.com/bytecodealliance/wasmtime-py).
|
|
42
|
+
It requires no OPA server, no OPA binary, no subprocess, and no network at
|
|
43
|
+
runtime. It is functionally comparable to StyraOSS `opa-java-wasm`, with a
|
|
44
|
+
Pythonic API and explicit thread-safety guarantees.
|
|
45
|
+
|
|
46
|
+
> **Import name:** the package installs as `opa-py-wasm` and is imported as
|
|
47
|
+
> `opapywasm`.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```shell
|
|
52
|
+
pip install opa-py-wasm
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Or with [uv](https://docs.astral.sh/uv/):
|
|
56
|
+
|
|
57
|
+
```shell
|
|
58
|
+
uv add opa-py-wasm
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Requires Python 3.10 or newer. The only runtime dependency is
|
|
62
|
+
[`wasmtime`](https://pypi.org/project/wasmtime/).
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from opapywasm import UNDEFINED, OpaWasmPolicy, PolicyConfig
|
|
68
|
+
|
|
69
|
+
policy = OpaWasmPolicy.from_wasm_file(
|
|
70
|
+
"policy.wasm",
|
|
71
|
+
config=PolicyConfig(
|
|
72
|
+
pool_size=8,
|
|
73
|
+
default_entrypoint="authz/allow",
|
|
74
|
+
eval_timeout_seconds=30.0, # per-eval deadline (epoch interruption)
|
|
75
|
+
max_memory_pages=4096, # per-instance linear-memory cap (256 MiB)
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
policy.set_data({"roles": {"alice": "admin", "bob": "viewer"}})
|
|
80
|
+
|
|
81
|
+
decision = policy.evaluate({"user": "alice", "action": "delete"}) # simplified decision
|
|
82
|
+
raw = policy.evaluate_raw({"user": "alice", "action": "delete"}) # full OPA result set
|
|
83
|
+
|
|
84
|
+
# `evaluate` distinguishes an undefined decision from a defined JSON null:
|
|
85
|
+
if decision is UNDEFINED:
|
|
86
|
+
... # policy produced no result
|
|
87
|
+
elif decision is None:
|
|
88
|
+
... # policy result was JSON null
|
|
89
|
+
|
|
90
|
+
# Custom host builtins (receive decoded Python args, return JSON-compatible values):
|
|
91
|
+
policy.register_builtin("my.custom", lambda x: {"ok": True})
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`OpaWasmPolicy` is a bounded, thread-safe pool — construct it once and call
|
|
95
|
+
`evaluate` from many threads. Runnable scripts are in [`examples/`](https://github.com/intuit/opa-py-wasm/tree/main/examples):
|
|
96
|
+
`basic_authz.py`, `pooled_eval.py`, `custom_builtin.py`, `yaml_builtin.py`.
|
|
97
|
+
|
|
98
|
+
For the YAML default builtins, install the optional extra:
|
|
99
|
+
|
|
100
|
+
```shell
|
|
101
|
+
uv add "opa-py-wasm[yaml]"
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Start with the [**user guide**](https://github.com/intuit/opa-py-wasm/blob/main/docs/guide.md) — an end-to-end walkthrough
|
|
105
|
+
covering compiling a policy, result semantics, concurrency, data updates, memory
|
|
106
|
+
behaviour, host builtins, and a production adoption checklist.
|
|
107
|
+
|
|
108
|
+
See [`docs/`](https://github.com/intuit/opa-py-wasm/tree/main/docs) for the focused references: architecture, thread-safety,
|
|
109
|
+
the OPA Wasm ABI, the `opa-java-wasm` parity table, and
|
|
110
|
+
[capacity-planning guidance](https://github.com/intuit/opa-py-wasm/blob/main/docs/capacity_planning.md) for sizing pool size
|
|
111
|
+
and concurrency.
|
|
112
|
+
|
|
113
|
+
### Test fixtures (dev only)
|
|
114
|
+
|
|
115
|
+
Compiled `.wasm` fixtures are committed under `tests/fixtures/wasm`, so the test
|
|
116
|
+
suite needs no OPA CLI. To regenerate them from the Rego sources in
|
|
117
|
+
`tests/fixtures/rego`, install the [OPA CLI](https://www.openpolicyagent.org/docs/latest/#running-opa)
|
|
118
|
+
and run:
|
|
119
|
+
|
|
120
|
+
```shell
|
|
121
|
+
python scripts/build_fixtures.py # all fixtures
|
|
122
|
+
python scripts/build_fixtures.py allow_true # a single fixture
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Local Development
|
|
126
|
+
|
|
127
|
+
### uv
|
|
128
|
+
|
|
129
|
+
This library uses [uv to manage Python dependencies](https://docs.astral.sh/uv/getting-started/features/#projects).
|
|
130
|
+
`brew` is The easiest way to install on macOS:
|
|
131
|
+
|
|
132
|
+
```shell
|
|
133
|
+
brew install uv
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
For additional installation options (e.g. setting the PATH, installing a specific version, etc),
|
|
137
|
+
see the installation docs:
|
|
138
|
+
https://docs.astral.sh/uv/getting-started/installation/
|
|
139
|
+
|
|
140
|
+
## Python Versions Supported
|
|
141
|
+
|
|
142
|
+
Python 3.10 through 3.14 are supported and tested in CI.
|
|
143
|
+
|
|
144
|
+
To change which versions are supported and tested:
|
|
145
|
+
- Update "envlist" in "tox" section of [tox.ini](/tox.ini)
|
|
146
|
+
- Update "Supported Python versions" badge in [README.md](/README.md)
|
|
147
|
+
- Update "project.requires-python" in [pyproject.toml](/pyproject.toml) (if needed)
|
|
148
|
+
- Update "tool.black.target-version" in [pyproject.toml](/pyproject.toml) (optional)
|
|
149
|
+
- Update the matrix in [.github/workflows/ci.yml](/.github/workflows/ci.yml)
|
|
150
|
+
|
|
151
|
+
### Virtual Environment
|
|
152
|
+
|
|
153
|
+
Create by running:
|
|
154
|
+
|
|
155
|
+
```shell
|
|
156
|
+
uv sync --all-extras
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Run a command from the virtual environment, like code formatting:
|
|
160
|
+
|
|
161
|
+
```shell
|
|
162
|
+
uv run black .
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
To activate the virtual environment:
|
|
166
|
+
|
|
167
|
+
```shell
|
|
168
|
+
source .venv/bin/activate
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
For more information, refer to [uv's documentation](https://docs.astral.sh/uv/pip/environments/#using-a-virtual-environment).
|
|
172
|
+
|
|
173
|
+
### Type checking (mypy)
|
|
174
|
+
|
|
175
|
+
This library supports Python type [annotation](https://peps.python.org/pep-0484/).
|
|
176
|
+
Types will be checked as part of the test suite (see below).
|
|
177
|
+
For more information, see the [mypy documentation](https://mypy.readthedocs.io/en/stable/getting_started.html#dynamic-vs-static-typing).
|
|
178
|
+
|
|
179
|
+
### Testing
|
|
180
|
+
|
|
181
|
+
To run the test suite locally:
|
|
182
|
+
```shell
|
|
183
|
+
uv run tox
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Coverage is enforced on every CI run by `fail_under = 90` in
|
|
187
|
+
[`tool.coverage.report`](https://github.com/intuit/opa-py-wasm/blob/main/pyproject.toml); the suite currently sits at 99%. The
|
|
188
|
+
coverage badge at the top of this file is static — if you change coverage
|
|
189
|
+
materially, update the percentage in that badge along with your change.
|
|
190
|
+
|
|
191
|
+
## Releasing
|
|
192
|
+
|
|
193
|
+
Releases are cut by maintainers by pushing a `vX.Y.Z` tag, which triggers an
|
|
194
|
+
automated build and publish to PyPI. See [`RELEASING.md`](https://github.com/intuit/opa-py-wasm/blob/main/RELEASING.md) for
|
|
195
|
+
the process and the versioning policy. Published versions are listed on
|
|
196
|
+
[PyPI](https://pypi.org/project/opa-py-wasm/), and each release's changes are in
|
|
197
|
+
[`CHANGELOG.md`](https://github.com/intuit/opa-py-wasm/blob/main/CHANGELOG.md).
|
|
198
|
+
|
|
199
|
+
## Contributing
|
|
200
|
+
|
|
201
|
+
Contributions are welcome — see the [Contribution Guidelines](https://github.com/intuit/opa-py-wasm/blob/main/CONTRIBUTING.md)
|
|
202
|
+
and our [Code of Conduct](https://github.com/intuit/opa-py-wasm/blob/main/CODE_OF_CONDUCT.md).
|
|
203
|
+
|
|
204
|
+
## Support
|
|
205
|
+
|
|
206
|
+
Please open a [GitHub issue](https://github.com/intuit/opa-py-wasm/issues) for
|
|
207
|
+
bugs and feature requests, or start a
|
|
208
|
+
[discussion](https://github.com/intuit/opa-py-wasm/discussions) for questions.
|
|
209
|
+
|
|
210
|
+
## License
|
|
211
|
+
|
|
212
|
+
Released under the [MIT License](https://github.com/intuit/opa-py-wasm/blob/main/LICENSE).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
opapywasm/__init__.py,sha256=0_HGf8tIjuz_dR73SLlwKt73NkhhWD25ZvjNzyRJ7j8,2261
|
|
2
|
+
opapywasm/abi.py,sha256=akDrpD0MEsS56vbSGNhVYMpWPW4qXg0nD5LpWgLries,12895
|
|
3
|
+
opapywasm/builtins.py,sha256=9OgV8CM1dN_FPevoGQL3aNk3-XRkrw5vupLusK8SXnk,8864
|
|
4
|
+
opapywasm/data.py,sha256=39220B2rLwIj8LCvzN9KgWBmh47tikSusd1mH9CAkVg,4346
|
|
5
|
+
opapywasm/errors.py,sha256=ss4coJlseVXmA2Ug5xfo0KG4QwokF5d9uX6_Qmr3Ux8,3056
|
|
6
|
+
opapywasm/evaluator.py,sha256=jjEsIpczOVbpysWbkXaI1loEmzfrRqiagNfUCunNmU4,9472
|
|
7
|
+
opapywasm/instance.py,sha256=3a6tJegvSf5UNo7gDncyrv-XMO_4gSnXU6HIEuv3GcA,10442
|
|
8
|
+
opapywasm/memory.py,sha256=GlL6SWGTcq5OfxhDUtN0jZbHsJgamPaXDzj6SdFLKtQ,12291
|
|
9
|
+
opapywasm/policy.py,sha256=929nhb3nr7Eq18q4cR4wWC-c9G5N2nTqoYZ6E2JOEwc,17005
|
|
10
|
+
opapywasm/pool.py,sha256=OCSVmnx1Z_M0cv1WleALuUQ40bSgFqEbLtml4TWlOJw,13070
|
|
11
|
+
opapywasm/py.typed,sha256=Y2bzeO4tHJlTrLnOh4twETUGyy3X-dO-n04VWA8tkiw,164
|
|
12
|
+
opapywasm/runtime.py,sha256=er2U1xe8qiyavku1lLTn32YkIQdEmgJVDnhdZyY2VXY,21562
|
|
13
|
+
opapywasm/types.py,sha256=MTaE1fgueSesl5zYQ-Q0CsNFvv_thqzHeEyVLTuOrSc,7245
|
|
14
|
+
opa_py_wasm-1.2.1.dist-info/licenses/LICENSE,sha256=DUwW94JMWqhk1evJO7mh7Vfetx0QPyOq20_Q4IwqzAU,1068
|
|
15
|
+
opa_py_wasm-1.2.1.dist-info/WHEEL,sha256=_d8F1e7SqtoW6CDj4Gi8lFC26a_7I17R7zPLCKTp4Fg,81
|
|
16
|
+
opa_py_wasm-1.2.1.dist-info/METADATA,sha256=g6dwqqQ89wMAQvIe8j45aafc4Ek3CETvEV6Tg8gGNOg,8133
|
|
17
|
+
opa_py_wasm-1.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Intuit Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
opapywasm/__init__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""opapywasm — in-process, thread-safe Python SDK for evaluating OPA policies
|
|
2
|
+
compiled to WebAssembly, built on ``wasmtime.py``.
|
|
3
|
+
|
|
4
|
+
Public API (see :class:`~opapywasm.policy.OpaWasmPolicy`)::
|
|
5
|
+
|
|
6
|
+
from opapywasm import OpaWasmPolicy, PolicyConfig
|
|
7
|
+
|
|
8
|
+
policy = OpaWasmPolicy.from_wasm_file("policy.wasm")
|
|
9
|
+
policy.set_data({"roles": {"alice": "admin"}})
|
|
10
|
+
decision = policy.evaluate({"user": "alice", "action": "delete"})
|
|
11
|
+
|
|
12
|
+
The ``OpaWasmPolicy`` facade owns a bounded, thread-safe pool of single-use
|
|
13
|
+
Wasm instances; application threads own request-level concurrency.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from .builtins import BuiltinRegistry
|
|
19
|
+
from .errors import (
|
|
20
|
+
OpaAbiError,
|
|
21
|
+
OpaAbortError,
|
|
22
|
+
OpaBuiltinError,
|
|
23
|
+
OpaDataError,
|
|
24
|
+
OpaEntrypointError,
|
|
25
|
+
OpaEvaluationError,
|
|
26
|
+
OpaInvalidInputError,
|
|
27
|
+
OpaInvalidPolicyError,
|
|
28
|
+
OpaMemoryError,
|
|
29
|
+
OpaPolicyClosedError,
|
|
30
|
+
OpaPoolTimeoutError,
|
|
31
|
+
OpaWasmError,
|
|
32
|
+
)
|
|
33
|
+
from .policy import OpaWasmPolicy
|
|
34
|
+
from .types import UNDEFINED, BuiltinCallable, JSONInput, JSONValue, PolicyConfig, Undefined
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
# Facade — a bounded, thread-safe pool of policy instances.
|
|
38
|
+
"OpaWasmPolicy",
|
|
39
|
+
"BuiltinRegistry",
|
|
40
|
+
# Configuration & types
|
|
41
|
+
"PolicyConfig",
|
|
42
|
+
"JSONValue",
|
|
43
|
+
"JSONInput",
|
|
44
|
+
"BuiltinCallable",
|
|
45
|
+
"Undefined",
|
|
46
|
+
"UNDEFINED",
|
|
47
|
+
# Errors
|
|
48
|
+
"OpaWasmError",
|
|
49
|
+
"OpaInvalidPolicyError",
|
|
50
|
+
"OpaAbiError",
|
|
51
|
+
"OpaAbortError",
|
|
52
|
+
"OpaEvaluationError",
|
|
53
|
+
"OpaBuiltinError",
|
|
54
|
+
"OpaMemoryError",
|
|
55
|
+
"OpaPoolTimeoutError",
|
|
56
|
+
"OpaPolicyClosedError",
|
|
57
|
+
"OpaInvalidInputError",
|
|
58
|
+
"OpaEntrypointError",
|
|
59
|
+
"OpaDataError",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
# Sourced from installed package metadata so it can never drift from
|
|
63
|
+
# pyproject.toml. Falls back to "0.0.0+unknown" when running from a source tree
|
|
64
|
+
# that was never installed (e.g. some editable/CI layouts).
|
|
65
|
+
try:
|
|
66
|
+
from importlib.metadata import PackageNotFoundError
|
|
67
|
+
from importlib.metadata import version as _pkg_version
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
__version__ = _pkg_version("opa-py-wasm")
|
|
71
|
+
except PackageNotFoundError: # pragma: no cover - only in an uninstalled tree
|
|
72
|
+
__version__ = "0.0.0+unknown"
|
|
73
|
+
except ImportError: # pragma: no cover - importlib.metadata always present on 3.10+
|
|
74
|
+
__version__ = "0.0.0+unknown"
|
opapywasm/abi.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""OPA Wasm ABI adapter (milestone C2).
|
|
2
|
+
|
|
3
|
+
Two layers:
|
|
4
|
+
|
|
5
|
+
``OpaAbiSpec``
|
|
6
|
+
Immutable, shareable knowledge about the OPA Wasm ABI: required export
|
|
7
|
+
names, version-support policy, and capability rules. Safe to share across
|
|
8
|
+
instances.
|
|
9
|
+
|
|
10
|
+
``OpaAbi``
|
|
11
|
+
A per-instance adapter *bound* to one :class:`~opapywasm.runtime.WasmtimeRuntime`
|
|
12
|
+
(its ``Store`` / ``Instance`` / ``Memory`` / exports). Never shared across
|
|
13
|
+
instances — OPA value addresses and heap state are instance-local.
|
|
14
|
+
|
|
15
|
+
ABI facts (names, signatures, version semantics) come from the OPA Wasm ABI
|
|
16
|
+
documentation; see docs/opa_abi.md. Where the module varies by ABI version we
|
|
17
|
+
inspect exports and fail with :class:`OpaAbiError` rather than guessing.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import TYPE_CHECKING
|
|
24
|
+
|
|
25
|
+
import wasmtime
|
|
26
|
+
|
|
27
|
+
from .errors import OpaAbiError
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from .runtime import WasmtimeRuntime
|
|
31
|
+
|
|
32
|
+
__all__ = ["OpaAbiSpec", "OpaAbi"]
|
|
33
|
+
|
|
34
|
+
# ABI version globals exported by every OPA policy module.
|
|
35
|
+
_ABI_VERSION_GLOBAL = "opa_wasm_abi_version"
|
|
36
|
+
_ABI_MINOR_GLOBAL = "opa_wasm_abi_minor_version"
|
|
37
|
+
|
|
38
|
+
# Exports required of every supported OPA policy, independent of ABI minor.
|
|
39
|
+
_REQUIRED_EXPORTS: tuple[str, ...] = (
|
|
40
|
+
"opa_malloc",
|
|
41
|
+
"opa_free",
|
|
42
|
+
"opa_json_parse",
|
|
43
|
+
"opa_json_dump",
|
|
44
|
+
"opa_heap_ptr_get",
|
|
45
|
+
"opa_heap_ptr_set",
|
|
46
|
+
"entrypoints",
|
|
47
|
+
"builtins",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Capability-gating exports. Presence of these toggles the corresponding flag.
|
|
51
|
+
_OPA_EVAL_EXPORT = "opa_eval"
|
|
52
|
+
_EVAL_CTX_EXPORTS: tuple[str, ...] = (
|
|
53
|
+
"opa_eval_ctx_new",
|
|
54
|
+
"opa_eval_ctx_set_input",
|
|
55
|
+
"opa_eval_ctx_set_data",
|
|
56
|
+
"opa_eval_ctx_set_entrypoint",
|
|
57
|
+
"eval",
|
|
58
|
+
"opa_eval_ctx_get_result",
|
|
59
|
+
)
|
|
60
|
+
_HEAP_STASH_EXPORTS: tuple[str, ...] = (
|
|
61
|
+
"opa_heap_blocks_stash",
|
|
62
|
+
"opa_heap_blocks_restore",
|
|
63
|
+
"opa_heap_stash_clear",
|
|
64
|
+
)
|
|
65
|
+
_VALUE_FREE_EXPORT = "opa_value_free"
|
|
66
|
+
|
|
67
|
+
# Expected Wasm signatures of the exports we actually call, as
|
|
68
|
+
# ``(param_valtypes, result_valtypes)`` in ``i32`` terms. Validated at
|
|
69
|
+
# construction so a mistyped export fails fast with a clear error rather than
|
|
70
|
+
# trapping mid-evaluation. OPA emits everything as i32 (memory offsets / sizes).
|
|
71
|
+
_I32 = "i32"
|
|
72
|
+
_EXPECTED_SIGNATURES: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
|
|
73
|
+
"opa_malloc": ((_I32,), (_I32,)),
|
|
74
|
+
"opa_free": ((_I32,), ()),
|
|
75
|
+
"opa_json_parse": ((_I32, _I32), (_I32,)),
|
|
76
|
+
"opa_json_dump": ((_I32,), (_I32,)),
|
|
77
|
+
"opa_heap_ptr_get": ((), (_I32,)),
|
|
78
|
+
"opa_heap_ptr_set": ((_I32,), ()),
|
|
79
|
+
"entrypoints": ((), (_I32,)),
|
|
80
|
+
"builtins": ((), (_I32,)),
|
|
81
|
+
# opa_eval(reserved, entrypoint, data, input, input_len, heap_ptr, format)
|
|
82
|
+
"opa_eval": ((_I32,) * 7, (_I32,)),
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class OpaAbiSpec:
|
|
88
|
+
"""Immutable, shareable ABI policy for a compiled OPA module.
|
|
89
|
+
|
|
90
|
+
Encodes which ABI versions this SDK supports and which exports are required.
|
|
91
|
+
Holds no per-instance state, so a single spec is shared by every instance of
|
|
92
|
+
a policy.
|
|
93
|
+
|
|
94
|
+
Attributes:
|
|
95
|
+
min_major / max_major: supported ABI major-version range (inclusive).
|
|
96
|
+
min_minor_for_eval: the ABI minor version at which the one-shot
|
|
97
|
+
``opa_eval`` fast path becomes available. MVP requires ABI >= 1.2.
|
|
98
|
+
required_exports: exports every supported policy must provide.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
min_major: int = 1
|
|
102
|
+
max_major: int = 1
|
|
103
|
+
min_minor_for_eval: int = 2
|
|
104
|
+
required_exports: tuple[str, ...] = field(default=_REQUIRED_EXPORTS)
|
|
105
|
+
|
|
106
|
+
def check_version(self, major: int, minor: int) -> None:
|
|
107
|
+
"""Validate a detected (major, minor) ABI version against this spec.
|
|
108
|
+
|
|
109
|
+
Raises:
|
|
110
|
+
OpaAbiError: if the major version is outside the supported range.
|
|
111
|
+
"""
|
|
112
|
+
if not (self.min_major <= major <= self.max_major):
|
|
113
|
+
raise OpaAbiError(
|
|
114
|
+
f"unsupported OPA Wasm ABI major version {major}.{minor}; " f"this SDK supports {self.min_major}.x"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
def requires_eval_fast_path(self, minor: int) -> bool:
|
|
118
|
+
"""Whether the detected ABI minor version implies the ``opa_eval`` path."""
|
|
119
|
+
return minor >= self.min_minor_for_eval
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class OpaAbi:
|
|
123
|
+
"""Per-instance adapter binding an OPA module's ABI to one runtime.
|
|
124
|
+
|
|
125
|
+
On construction it reads the ABI version globals, validates them against the
|
|
126
|
+
:class:`OpaAbiSpec`, verifies required exports are present, and computes
|
|
127
|
+
capability flags. It then offers typed wrappers around the OPA exports.
|
|
128
|
+
|
|
129
|
+
Not thread-safe; bound to exactly one instance.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
def __init__(self, runtime: WasmtimeRuntime, spec: OpaAbiSpec | None = None) -> None:
|
|
133
|
+
self._rt = runtime
|
|
134
|
+
self._spec = spec or OpaAbiSpec()
|
|
135
|
+
|
|
136
|
+
self._abi_major, self._abi_minor = self._read_version()
|
|
137
|
+
self._spec.check_version(self._abi_major, self._abi_minor)
|
|
138
|
+
self._validate_required_exports()
|
|
139
|
+
|
|
140
|
+
# Capability flags — derived once from the exports present.
|
|
141
|
+
self._supports_opa_eval = runtime.has_export(_OPA_EVAL_EXPORT) and self._spec.requires_eval_fast_path(
|
|
142
|
+
self._abi_minor
|
|
143
|
+
)
|
|
144
|
+
self._supports_eval_context = all(runtime.has_export(name) for name in _EVAL_CTX_EXPORTS)
|
|
145
|
+
self._supports_heap_stash = all(runtime.has_export(name) for name in _HEAP_STASH_EXPORTS)
|
|
146
|
+
self._supports_value_free = runtime.has_export(_VALUE_FREE_EXPORT)
|
|
147
|
+
|
|
148
|
+
# This SDK evaluates exclusively via the opa_eval fast path (ABI >= 1.2).
|
|
149
|
+
# The eval-context fallback is deliberately not implemented, so we fail
|
|
150
|
+
# fast at construction if it is unavailable rather than letting a
|
|
151
|
+
# context-only module construct and then error on first evaluate().
|
|
152
|
+
if not self._supports_opa_eval:
|
|
153
|
+
raise OpaAbiError(
|
|
154
|
+
f"policy ABI {self._abi_major}.{self._abi_minor} does not expose the opa_eval "
|
|
155
|
+
"fast path (requires ABI >= 1.2 with an 'opa_eval' export); this SDK does not "
|
|
156
|
+
"implement the eval-context fallback"
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
# Validate the signatures of the exports we call, so a mistyped export is
|
|
160
|
+
# a clear construction-time error, not a mid-eval trap.
|
|
161
|
+
self._validate_export_signatures()
|
|
162
|
+
|
|
163
|
+
# -- version & capabilities ---------------------------------------------
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def abi_version(self) -> tuple[int, int]:
|
|
167
|
+
"""Detected ``(major, minor)`` ABI version."""
|
|
168
|
+
return (self._abi_major, self._abi_minor)
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def supports_opa_eval(self) -> bool:
|
|
172
|
+
return self._supports_opa_eval
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def supports_eval_context(self) -> bool:
|
|
176
|
+
return self._supports_eval_context
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def supports_heap_stash(self) -> bool:
|
|
180
|
+
return self._supports_heap_stash
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def supports_value_free(self) -> bool:
|
|
184
|
+
return self._supports_value_free
|
|
185
|
+
|
|
186
|
+
# -- raw memory access (for the per-instance MemoryCodec) ----------------
|
|
187
|
+
|
|
188
|
+
def memory_write(self, addr: int, data: bytes) -> None:
|
|
189
|
+
"""Write ``data`` into this instance's Wasm memory at ``addr``."""
|
|
190
|
+
self._rt.memory.write(self._rt.store, data, addr)
|
|
191
|
+
|
|
192
|
+
def memory_read(self, start: int, stop: int) -> bytearray:
|
|
193
|
+
"""Read this instance's Wasm memory over ``[start, stop)``."""
|
|
194
|
+
data: bytearray = self._rt.memory.read(self._rt.store, start, stop)
|
|
195
|
+
return data
|
|
196
|
+
|
|
197
|
+
def memory_len(self) -> int:
|
|
198
|
+
"""Current size of this instance's Wasm memory, in bytes."""
|
|
199
|
+
return int(self._rt.memory.data_len(self._rt.store))
|
|
200
|
+
|
|
201
|
+
def set_epoch_deadline(self, ticks: int) -> None:
|
|
202
|
+
"""Arm this instance's per-evaluation epoch deadline (see runtime)."""
|
|
203
|
+
self._rt.set_epoch_deadline(ticks)
|
|
204
|
+
|
|
205
|
+
def clear_epoch_deadline(self) -> None:
|
|
206
|
+
"""Clear the per-evaluation deadline after a successful eval (see runtime)."""
|
|
207
|
+
self._rt.clear_epoch_deadline()
|
|
208
|
+
|
|
209
|
+
def _read_version(self) -> tuple[int, int]:
|
|
210
|
+
"""Read the ABI version globals.
|
|
211
|
+
|
|
212
|
+
The minor global was added in ABI 1.1; if it is absent the minor version
|
|
213
|
+
is treated as 0.
|
|
214
|
+
|
|
215
|
+
Raises:
|
|
216
|
+
OpaAbiError: if the mandatory major-version global is missing or not
|
|
217
|
+
an integer global.
|
|
218
|
+
"""
|
|
219
|
+
major_global = self._rt.exports().get(_ABI_VERSION_GLOBAL)
|
|
220
|
+
if not isinstance(major_global, wasmtime.Global):
|
|
221
|
+
raise OpaAbiError(f"policy is missing the {_ABI_VERSION_GLOBAL!r} ABI global; not an OPA policy")
|
|
222
|
+
major = major_global.value(self._rt.store)
|
|
223
|
+
|
|
224
|
+
minor_global = self._rt.exports().get(_ABI_MINOR_GLOBAL)
|
|
225
|
+
minor = minor_global.value(self._rt.store) if isinstance(minor_global, wasmtime.Global) else 0
|
|
226
|
+
|
|
227
|
+
if not isinstance(major, int) or not isinstance(minor, int):
|
|
228
|
+
raise OpaAbiError("OPA ABI version globals are not integers")
|
|
229
|
+
return major, minor
|
|
230
|
+
|
|
231
|
+
def _validate_required_exports(self) -> None:
|
|
232
|
+
missing = [name for name in self._spec.required_exports if not self._rt.has_export(name)]
|
|
233
|
+
if missing:
|
|
234
|
+
raise OpaAbiError(
|
|
235
|
+
f"policy is missing required OPA ABI export(s): {', '.join(sorted(missing))} "
|
|
236
|
+
f"(ABI {self._abi_major}.{self._abi_minor})"
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
def _validate_export_signatures(self) -> None:
|
|
240
|
+
"""Check that every export we call has the expected ``i32`` signature.
|
|
241
|
+
|
|
242
|
+
A signature mismatch means the module is not the OPA ABI we target;
|
|
243
|
+
surfacing it here (rather than as an opaque trap during evaluation) makes
|
|
244
|
+
the failure actionable.
|
|
245
|
+
"""
|
|
246
|
+
for name, (want_params, want_results) in _EXPECTED_SIGNATURES.items():
|
|
247
|
+
if not self._rt.has_export(name):
|
|
248
|
+
# opa_eval presence is already enforced; other names are in the
|
|
249
|
+
# required-export set. Anything genuinely absent was caught above.
|
|
250
|
+
continue
|
|
251
|
+
func = self._rt.get_func(name)
|
|
252
|
+
func_type = func.type(self._rt.store)
|
|
253
|
+
got_params = tuple(str(v) for v in func_type.params)
|
|
254
|
+
got_results = tuple(str(v) for v in func_type.results)
|
|
255
|
+
if got_params != want_params or got_results != want_results:
|
|
256
|
+
raise OpaAbiError(
|
|
257
|
+
f"OPA export {name!r} has unexpected signature "
|
|
258
|
+
f"{got_params}->{got_results}; expected {want_params}->{want_results}"
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
# -- typed export wrappers ----------------------------------------------
|
|
262
|
+
#
|
|
263
|
+
# Each wrapper calls the corresponding OPA export with the instance's store.
|
|
264
|
+
# Addresses are opaque i32 handles into this instance's Wasm memory; callers
|
|
265
|
+
# (MemoryCodec, DataManager, Evaluator) must never share them across
|
|
266
|
+
# instances.
|
|
267
|
+
|
|
268
|
+
def _call(self, name: str, *args: int) -> int:
|
|
269
|
+
func = self._rt.get_func(name)
|
|
270
|
+
return int(func(self._rt.store, *args))
|
|
271
|
+
|
|
272
|
+
def opa_malloc(self, size: int) -> int:
|
|
273
|
+
"""Allocate ``size`` bytes in the instance heap; return the address."""
|
|
274
|
+
return self._call("opa_malloc", size)
|
|
275
|
+
|
|
276
|
+
def opa_free(self, addr: int) -> None:
|
|
277
|
+
self._rt.get_func("opa_free")(self._rt.store, addr)
|
|
278
|
+
|
|
279
|
+
def opa_json_parse(self, addr: int, length: int) -> int:
|
|
280
|
+
"""Parse JSON bytes at ``addr`` into an OPA value; return its address."""
|
|
281
|
+
return self._call("opa_json_parse", addr, length)
|
|
282
|
+
|
|
283
|
+
def opa_json_dump(self, value_addr: int) -> int:
|
|
284
|
+
"""Dump an OPA value to a NUL-terminated JSON string; return its address."""
|
|
285
|
+
return self._call("opa_json_dump", value_addr)
|
|
286
|
+
|
|
287
|
+
def opa_heap_ptr_get(self) -> int:
|
|
288
|
+
return self._call("opa_heap_ptr_get")
|
|
289
|
+
|
|
290
|
+
def opa_heap_ptr_set(self, addr: int) -> None:
|
|
291
|
+
self._rt.get_func("opa_heap_ptr_set")(self._rt.store, addr)
|
|
292
|
+
|
|
293
|
+
def entrypoints(self) -> int:
|
|
294
|
+
"""Return the address of the OPA value describing entrypoints (name->id)."""
|
|
295
|
+
return self._call("entrypoints")
|
|
296
|
+
|
|
297
|
+
def builtins(self) -> int:
|
|
298
|
+
"""Return the address of the OPA value describing builtins (name->id)."""
|
|
299
|
+
return self._call("builtins")
|
|
300
|
+
|
|
301
|
+
def opa_eval(
|
|
302
|
+
self,
|
|
303
|
+
entrypoint_id: int,
|
|
304
|
+
data_addr: int,
|
|
305
|
+
input_addr: int,
|
|
306
|
+
input_len: int,
|
|
307
|
+
heap_ptr: int,
|
|
308
|
+
*,
|
|
309
|
+
reserved: int = 0,
|
|
310
|
+
result_format: int = 0,
|
|
311
|
+
) -> int:
|
|
312
|
+
"""One-shot evaluation (ABI 1.2+ fast path).
|
|
313
|
+
|
|
314
|
+
Signature (per the OPA Wasm ABI):
|
|
315
|
+
``opa_eval(reserved, entrypoint_id, data, input, input_len, heap_ptr, format)``
|
|
316
|
+
returning the address of a NUL-terminated JSON result string.
|
|
317
|
+
|
|
318
|
+
The ``opa_eval`` fast path is guaranteed present: :class:`OpaAbi`
|
|
319
|
+
construction rejects any module lacking it, so no runtime guard is
|
|
320
|
+
needed here.
|
|
321
|
+
"""
|
|
322
|
+
return self._call(
|
|
323
|
+
_OPA_EVAL_EXPORT,
|
|
324
|
+
reserved,
|
|
325
|
+
entrypoint_id,
|
|
326
|
+
data_addr,
|
|
327
|
+
input_addr,
|
|
328
|
+
input_len,
|
|
329
|
+
heap_ptr,
|
|
330
|
+
result_format,
|
|
331
|
+
)
|