pytrat-otel 0.1.0__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.
- pytrat_otel-0.1.0/.gitignore +27 -0
- pytrat_otel-0.1.0/LICENSE +202 -0
- pytrat_otel-0.1.0/PKG-INFO +72 -0
- pytrat_otel-0.1.0/README.md +42 -0
- pytrat_otel-0.1.0/pyproject.toml +43 -0
- pytrat_otel-0.1.0/src/pytrat/otel/__init__.py +16 -0
- pytrat_otel-0.1.0/src/pytrat/otel/_attributes.py +135 -0
- pytrat_otel-0.1.0/src/pytrat/otel/py.typed +0 -0
- pytrat_otel-0.1.0/src/pytrat/otel/semconv.py +50 -0
- pytrat_otel-0.1.0/src/pytrat/otel/sink.py +114 -0
- pytrat_otel-0.1.0/tests/test_otel_sink.py +337 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
.venv/
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.mypy_cache/
|
|
6
|
+
.ruff_cache/
|
|
7
|
+
.hypothesis/
|
|
8
|
+
.coverage
|
|
9
|
+
.coverage.*
|
|
10
|
+
htmlcov/
|
|
11
|
+
coverage.xml
|
|
12
|
+
dist/
|
|
13
|
+
build/
|
|
14
|
+
*.egg-info/
|
|
15
|
+
.benchmarks/
|
|
16
|
+
site/
|
|
17
|
+
*.sqlite3
|
|
18
|
+
*.db
|
|
19
|
+
*.jsonl
|
|
20
|
+
examples/**/keys/
|
|
21
|
+
.env
|
|
22
|
+
.DS_Store
|
|
23
|
+
.claude/worktrees/
|
|
24
|
+
.fuzz-work/
|
|
25
|
+
crash-*
|
|
26
|
+
leak-*
|
|
27
|
+
timeout-*
|
|
@@ -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,72 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pytrat-otel
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: OpenTelemetry audit sink for PyTraT: span events and decision metrics.
|
|
5
|
+
Project-URL: Homepage, https://github.com/roshanlam/pytrat
|
|
6
|
+
Project-URL: Documentation, https://github.com/roshanlam/pytrat/tree/main/docs
|
|
7
|
+
Project-URL: Source, https://github.com/roshanlam/pytrat
|
|
8
|
+
Project-URL: Issues, https://github.com/roshanlam/pytrat/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/roshanlam/pytrat/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Roshan Lamichhane <roshanlamichhanenepali@gmail.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: ai-agents,authorization,jwt,microservices,oauth,transaction-tokens,txn-token,zero-trust
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
23
|
+
Classifier: Topic :: Security
|
|
24
|
+
Classifier: Topic :: System :: Monitoring
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.12
|
|
27
|
+
Requires-Dist: opentelemetry-api>=1.27
|
|
28
|
+
Requires-Dist: pytrat-core<0.2,>=0.1.0
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# pytrat-otel
|
|
32
|
+
|
|
33
|
+
OpenTelemetry audit sink for PyTraT. Every audit event (authorization decision, token rejection,
|
|
34
|
+
issuance, replacement) becomes a span event on the current span and one increment of a decision
|
|
35
|
+
counter. Depends only on `opentelemetry-api`; configure the SDK and exporters in your application.
|
|
36
|
+
|
|
37
|
+
<!-- --8<-- [start:usage] -->
|
|
38
|
+
```python
|
|
39
|
+
from pytrat.fastapi import PyTraT
|
|
40
|
+
from pytrat.otel import OpenTelemetryAuditSink
|
|
41
|
+
|
|
42
|
+
pytrat = PyTraT(
|
|
43
|
+
service="ledger-service",
|
|
44
|
+
verifier=verifier,
|
|
45
|
+
authenticator=authenticator,
|
|
46
|
+
audit=OpenTelemetryAuditSink(), # global TracerProvider / MeterProvider
|
|
47
|
+
protected_prefixes=("/internal",),
|
|
48
|
+
)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Pass `tracer_provider=` / `meter_provider=` to use specific providers instead of the global ones.
|
|
52
|
+
The sink records telemetry, not the audit trail of record: keep a durable sink (for example
|
|
53
|
+
`JsonLinesSink`) as well if you need one.
|
|
54
|
+
|
|
55
|
+
| Kind | Name | Attributes |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| span event | `pytrat.<event_type>` (e.g. `pytrat.authorization.denied`) | see below |
|
|
58
|
+
| span (only when no span is recording) | `pytrat.audit` | as the event |
|
|
59
|
+
| counter | `pytrat.authorization.decisions` | `pytrat.decision`, `pytrat.reason_code`, `pytrat.service` |
|
|
60
|
+
| counter | `pytrat.issuance.decisions` | same |
|
|
61
|
+
| counter | `pytrat.replacement.decisions` | same |
|
|
62
|
+
|
|
63
|
+
Span event attributes: `pytrat.audit.schema_version`, `pytrat.event.type`, `pytrat.decision`
|
|
64
|
+
(`allow`/`deny`), `pytrat.reason_code`, `pytrat.service`, `pytrat.transaction.id`, `pytrat.scope`,
|
|
65
|
+
`pytrat.policy.id`, `pytrat.workload.requesting`, `pytrat.workload.caller`, `pytrat.token.digest`,
|
|
66
|
+
`pytrat.agent.originator`, `pytrat.agent.proximate`, `pytrat.agent.hop_count`,
|
|
67
|
+
`pytrat.agent.min_assurance_level`, and `pytrat.detail.<key>` for each detail label. Absent fields
|
|
68
|
+
are omitted. The subject is not exported. Any string shaped like a compact JWS/JWE is withheld.
|
|
69
|
+
|
|
70
|
+
The sink never raises: telemetry failures are logged (exception type only) and counted in
|
|
71
|
+
`sink.failed`; withheld attributes are counted in `sink.redacted`.
|
|
72
|
+
<!-- --8<-- [end:usage] -->
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# pytrat-otel
|
|
2
|
+
|
|
3
|
+
OpenTelemetry audit sink for PyTraT. Every audit event (authorization decision, token rejection,
|
|
4
|
+
issuance, replacement) becomes a span event on the current span and one increment of a decision
|
|
5
|
+
counter. Depends only on `opentelemetry-api`; configure the SDK and exporters in your application.
|
|
6
|
+
|
|
7
|
+
<!-- --8<-- [start:usage] -->
|
|
8
|
+
```python
|
|
9
|
+
from pytrat.fastapi import PyTraT
|
|
10
|
+
from pytrat.otel import OpenTelemetryAuditSink
|
|
11
|
+
|
|
12
|
+
pytrat = PyTraT(
|
|
13
|
+
service="ledger-service",
|
|
14
|
+
verifier=verifier,
|
|
15
|
+
authenticator=authenticator,
|
|
16
|
+
audit=OpenTelemetryAuditSink(), # global TracerProvider / MeterProvider
|
|
17
|
+
protected_prefixes=("/internal",),
|
|
18
|
+
)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Pass `tracer_provider=` / `meter_provider=` to use specific providers instead of the global ones.
|
|
22
|
+
The sink records telemetry, not the audit trail of record: keep a durable sink (for example
|
|
23
|
+
`JsonLinesSink`) as well if you need one.
|
|
24
|
+
|
|
25
|
+
| Kind | Name | Attributes |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| span event | `pytrat.<event_type>` (e.g. `pytrat.authorization.denied`) | see below |
|
|
28
|
+
| span (only when no span is recording) | `pytrat.audit` | as the event |
|
|
29
|
+
| counter | `pytrat.authorization.decisions` | `pytrat.decision`, `pytrat.reason_code`, `pytrat.service` |
|
|
30
|
+
| counter | `pytrat.issuance.decisions` | same |
|
|
31
|
+
| counter | `pytrat.replacement.decisions` | same |
|
|
32
|
+
|
|
33
|
+
Span event attributes: `pytrat.audit.schema_version`, `pytrat.event.type`, `pytrat.decision`
|
|
34
|
+
(`allow`/`deny`), `pytrat.reason_code`, `pytrat.service`, `pytrat.transaction.id`, `pytrat.scope`,
|
|
35
|
+
`pytrat.policy.id`, `pytrat.workload.requesting`, `pytrat.workload.caller`, `pytrat.token.digest`,
|
|
36
|
+
`pytrat.agent.originator`, `pytrat.agent.proximate`, `pytrat.agent.hop_count`,
|
|
37
|
+
`pytrat.agent.min_assurance_level`, and `pytrat.detail.<key>` for each detail label. Absent fields
|
|
38
|
+
are omitted. The subject is not exported. Any string shaped like a compact JWS/JWE is withheld.
|
|
39
|
+
|
|
40
|
+
The sink never raises: telemetry failures are logged (exception type only) and counted in
|
|
41
|
+
`sink.failed`; withheld attributes are counted in `sink.redacted`.
|
|
42
|
+
<!-- --8<-- [end:usage] -->
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pytrat-otel"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "OpenTelemetry audit sink for PyTraT: span events and decision metrics."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Roshan Lamichhane", email = "roshanlamichhanenepali@gmail.com" }]
|
|
9
|
+
keywords = ["oauth", "transaction-tokens", "txn-token", "jwt", "authorization", "zero-trust", "microservices", "ai-agents"]
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
# The API only. Applications choose and configure the SDK and exporters.
|
|
12
|
+
dependencies = ["pytrat-core>=0.1.0,<0.2", "opentelemetry-api>=1.27"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"Topic :: Security",
|
|
23
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
24
|
+
"Topic :: System :: Monitoring",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/roshanlam/pytrat"
|
|
30
|
+
Documentation = "https://github.com/roshanlam/pytrat/tree/main/docs"
|
|
31
|
+
Source = "https://github.com/roshanlam/pytrat"
|
|
32
|
+
Issues = "https://github.com/roshanlam/pytrat/issues"
|
|
33
|
+
Changelog = "https://github.com/roshanlam/pytrat/blob/main/CHANGELOG.md"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["hatchling>=1.26"]
|
|
37
|
+
build-backend = "hatchling.build"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/pytrat"]
|
|
41
|
+
|
|
42
|
+
[tool.uv.sources]
|
|
43
|
+
pytrat-core = { workspace = true }
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""PyTraT OpenTelemetry: record audit events as span events and decision metrics.
|
|
2
|
+
|
|
3
|
+
Depends only on ``opentelemetry-api``; the application configures the SDK and exporters::
|
|
4
|
+
|
|
5
|
+
from pytrat.otel import OpenTelemetryAuditSink
|
|
6
|
+
|
|
7
|
+
pytrat = PyTraT(service="ledger", verifier=verifier, audit=OpenTelemetryAuditSink())
|
|
8
|
+
|
|
9
|
+
Attribute, span event and instrument names are in :mod:`pytrat.otel.semconv`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from pytrat.otel import semconv
|
|
13
|
+
from pytrat.otel._attributes import looks_like_jose
|
|
14
|
+
from pytrat.otel.sink import OpenTelemetryAuditSink
|
|
15
|
+
|
|
16
|
+
__all__ = ["OpenTelemetryAuditSink", "looks_like_jose", "semconv"]
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Pure mapping from :class:`AuditEvent` to OpenTelemetry attributes. No I/O."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
from typing import Final
|
|
10
|
+
|
|
11
|
+
from pytrat.core.audit import SCHEMA_VERSION, AuditEvent, EventType
|
|
12
|
+
from pytrat.otel import semconv
|
|
13
|
+
|
|
14
|
+
type AttributeValue = str | int
|
|
15
|
+
"""The only attribute value types this package produces: primitives, never sequences."""
|
|
16
|
+
|
|
17
|
+
# A compact JWS or JWE (RFC 7515 §7.1, RFC 7516 §7.1) starts with a base64url JSON header, so
|
|
18
|
+
# "ey" or "ew"; a header plus one more dot-separated segment counts as a token. The standard
|
|
19
|
+
# base64 alphabet is accepted so re-encoded tokens are caught, and the pattern is searched so a
|
|
20
|
+
# token inside a longer string ("Bearer eyJ...") is caught too.
|
|
21
|
+
_JOSE_SHAPE: Final = re.compile(r"e[yw][A-Za-z0-9_\-+/=]{8,}\.[A-Za-z0-9_\-+/=]*\.")
|
|
22
|
+
|
|
23
|
+
_REDACTED_DETAIL_KEY: Final = semconv.DETAIL_PREFIX + "*"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class Outcome:
|
|
28
|
+
"""How an event type is counted."""
|
|
29
|
+
|
|
30
|
+
metric: str
|
|
31
|
+
decision: str
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
OUTCOMES: Final[Mapping[EventType, Outcome]] = MappingProxyType(
|
|
35
|
+
{
|
|
36
|
+
EventType.AUTHORIZATION_GRANTED: Outcome(
|
|
37
|
+
semconv.AUTHORIZATION_DECISIONS, semconv.DECISION_ALLOW
|
|
38
|
+
),
|
|
39
|
+
EventType.AUTHORIZATION_DENIED: Outcome(
|
|
40
|
+
semconv.AUTHORIZATION_DECISIONS, semconv.DECISION_DENY
|
|
41
|
+
),
|
|
42
|
+
# A rejected token is an authorization-path denial (no policy was reached).
|
|
43
|
+
EventType.TOKEN_REJECTED: Outcome(semconv.AUTHORIZATION_DECISIONS, semconv.DECISION_DENY),
|
|
44
|
+
EventType.TOKEN_ISSUED: Outcome(semconv.ISSUANCE_DECISIONS, semconv.DECISION_ALLOW),
|
|
45
|
+
EventType.ISSUANCE_DENIED: Outcome(semconv.ISSUANCE_DECISIONS, semconv.DECISION_DENY),
|
|
46
|
+
EventType.TOKEN_REPLACED: Outcome(semconv.REPLACEMENT_DECISIONS, semconv.DECISION_ALLOW),
|
|
47
|
+
EventType.REPLACEMENT_DENIED: Outcome(semconv.REPLACEMENT_DECISIONS, semconv.DECISION_DENY),
|
|
48
|
+
}
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def looks_like_jose(value: str) -> bool:
|
|
53
|
+
"""Return True if ``value`` contains something shaped like a compact JWS or JWE."""
|
|
54
|
+
return _JOSE_SHAPE.search(value) is not None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class EventAttributes:
|
|
59
|
+
"""Attributes for one audit event.
|
|
60
|
+
|
|
61
|
+
Attributes:
|
|
62
|
+
counter: Name of the counter this event increments.
|
|
63
|
+
span: Every attribute, for the span event.
|
|
64
|
+
metric: The bounded-cardinality subset (:data:`semconv.METRIC_ATTRIBUTES`).
|
|
65
|
+
dropped: Names of attributes withheld because they looked like a token. A detail entry
|
|
66
|
+
whose *key* looked like a token is reported as ``pytrat.detail.*`` so the name itself
|
|
67
|
+
is safe to log.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
counter: str
|
|
71
|
+
span: Mapping[str, AttributeValue]
|
|
72
|
+
metric: Mapping[str, AttributeValue]
|
|
73
|
+
dropped: tuple[str, ...]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def event_attributes(event: AuditEvent) -> EventAttributes:
|
|
77
|
+
"""Map ``event`` to primitive OpenTelemetry attributes, withholding token-shaped strings.
|
|
78
|
+
|
|
79
|
+
``subject`` is deliberately not exported: it is usually a user identifier, and telemetry
|
|
80
|
+
pipelines are rarely held to audit-log retention and access rules. Correlate by
|
|
81
|
+
``pytrat.transaction.id`` instead. ``trace_id`` and ``timestamp`` are carried by the span
|
|
82
|
+
itself.
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
KeyError: If ``event.event_type`` has no :data:`OUTCOMES` entry (a new event type that
|
|
86
|
+
this package has not been updated for).
|
|
87
|
+
"""
|
|
88
|
+
outcome = OUTCOMES[event.event_type]
|
|
89
|
+
candidates: dict[str, str | int | None] = {
|
|
90
|
+
semconv.AUDIT_SCHEMA_VERSION: SCHEMA_VERSION,
|
|
91
|
+
semconv.EVENT_TYPE: event.event_type.value,
|
|
92
|
+
semconv.DECISION: outcome.decision,
|
|
93
|
+
semconv.REASON_CODE: event.reason_code.value if event.reason_code else None,
|
|
94
|
+
semconv.SERVICE: event.service,
|
|
95
|
+
semconv.TRANSACTION_ID: event.transaction_id,
|
|
96
|
+
semconv.SCOPE: event.scope,
|
|
97
|
+
semconv.POLICY_ID: event.policy_id,
|
|
98
|
+
semconv.REQUESTING_WORKLOAD: event.requesting_workload,
|
|
99
|
+
semconv.CALLER_WORKLOAD: event.caller_workload,
|
|
100
|
+
semconv.TOKEN_DIGEST: event.token_digest,
|
|
101
|
+
}
|
|
102
|
+
agent = event.agent_context
|
|
103
|
+
if agent is not None:
|
|
104
|
+
candidates[semconv.AGENT_ORIGINATOR] = agent.originator
|
|
105
|
+
candidates[semconv.AGENT_PROXIMATE] = agent.proximate
|
|
106
|
+
candidates[semconv.AGENT_HOP_COUNT] = agent.hop_count
|
|
107
|
+
candidates[semconv.AGENT_MIN_ASSURANCE_LEVEL] = agent.min_assurance_level
|
|
108
|
+
|
|
109
|
+
attributes: dict[str, AttributeValue] = {}
|
|
110
|
+
dropped: list[str] = []
|
|
111
|
+
for name, value in candidates.items():
|
|
112
|
+
if value is None:
|
|
113
|
+
continue
|
|
114
|
+
if isinstance(value, str) and looks_like_jose(value):
|
|
115
|
+
dropped.append(name)
|
|
116
|
+
continue
|
|
117
|
+
attributes[name] = value
|
|
118
|
+
for key, value in event.detail.items():
|
|
119
|
+
name = semconv.DETAIL_PREFIX + key
|
|
120
|
+
if looks_like_jose(name):
|
|
121
|
+
dropped.append(_REDACTED_DETAIL_KEY)
|
|
122
|
+
elif looks_like_jose(value):
|
|
123
|
+
dropped.append(name)
|
|
124
|
+
else:
|
|
125
|
+
attributes[name] = value
|
|
126
|
+
|
|
127
|
+
metric: dict[str, AttributeValue] = {
|
|
128
|
+
name: attributes[name] for name in semconv.METRIC_ATTRIBUTES if name in attributes
|
|
129
|
+
}
|
|
130
|
+
return EventAttributes(
|
|
131
|
+
counter=outcome.metric,
|
|
132
|
+
span=MappingProxyType(attributes),
|
|
133
|
+
metric=MappingProxyType(metric),
|
|
134
|
+
dropped=tuple(dropped),
|
|
135
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Names of the span events, attributes and instruments that :mod:`pytrat.otel` emits.
|
|
2
|
+
|
|
3
|
+
Follows OpenTelemetry semantic-convention style: a ``pytrat.`` namespace, dot-separated
|
|
4
|
+
components, ``snake_case`` words. These names are public API: add, never rename.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Final
|
|
10
|
+
|
|
11
|
+
INSTRUMENTATION_SCOPE: Final = "pytrat.otel"
|
|
12
|
+
|
|
13
|
+
# Span events
|
|
14
|
+
EVENT_NAME_PREFIX: Final = "pytrat."
|
|
15
|
+
"""Span event name is this prefix plus the audit event type, e.g. ``pytrat.token.issued``."""
|
|
16
|
+
|
|
17
|
+
AUDIT_SPAN_NAME: Final = "pytrat.audit"
|
|
18
|
+
"""Name of the short span recorded when no span is active."""
|
|
19
|
+
|
|
20
|
+
# Attributes
|
|
21
|
+
AUDIT_SCHEMA_VERSION: Final = "pytrat.audit.schema_version"
|
|
22
|
+
EVENT_TYPE: Final = "pytrat.event.type"
|
|
23
|
+
DECISION: Final = "pytrat.decision"
|
|
24
|
+
REASON_CODE: Final = "pytrat.reason_code"
|
|
25
|
+
SERVICE: Final = "pytrat.service"
|
|
26
|
+
TRANSACTION_ID: Final = "pytrat.transaction.id"
|
|
27
|
+
SCOPE: Final = "pytrat.scope"
|
|
28
|
+
POLICY_ID: Final = "pytrat.policy.id"
|
|
29
|
+
REQUESTING_WORKLOAD: Final = "pytrat.workload.requesting"
|
|
30
|
+
CALLER_WORKLOAD: Final = "pytrat.workload.caller"
|
|
31
|
+
TOKEN_DIGEST: Final = "pytrat.token.digest"
|
|
32
|
+
AGENT_ORIGINATOR: Final = "pytrat.agent.originator"
|
|
33
|
+
AGENT_PROXIMATE: Final = "pytrat.agent.proximate"
|
|
34
|
+
AGENT_HOP_COUNT: Final = "pytrat.agent.hop_count"
|
|
35
|
+
AGENT_MIN_ASSURANCE_LEVEL: Final = "pytrat.agent.min_assurance_level"
|
|
36
|
+
DETAIL_PREFIX: Final = "pytrat.detail."
|
|
37
|
+
"""Each ``AuditEvent.detail`` entry becomes ``pytrat.detail.<key>``."""
|
|
38
|
+
|
|
39
|
+
# Attribute values
|
|
40
|
+
DECISION_ALLOW: Final = "allow"
|
|
41
|
+
DECISION_DENY: Final = "deny"
|
|
42
|
+
|
|
43
|
+
# Metrics
|
|
44
|
+
AUTHORIZATION_DECISIONS: Final = "pytrat.authorization.decisions"
|
|
45
|
+
ISSUANCE_DECISIONS: Final = "pytrat.issuance.decisions"
|
|
46
|
+
REPLACEMENT_DECISIONS: Final = "pytrat.replacement.decisions"
|
|
47
|
+
DECISIONS_UNIT: Final = "{decision}"
|
|
48
|
+
|
|
49
|
+
METRIC_ATTRIBUTES: Final = (DECISION, REASON_CODE, SERVICE)
|
|
50
|
+
"""The only attributes put on metric points: bounded cardinality by construction."""
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""An :class:`~pytrat.core.audit.AuditSink` that records audit events in OpenTelemetry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from opentelemetry import metrics, trace
|
|
10
|
+
|
|
11
|
+
from pytrat.otel import semconv
|
|
12
|
+
from pytrat.otel._attributes import event_attributes
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
|
|
17
|
+
from pytrat.core.audit import AuditEvent
|
|
18
|
+
|
|
19
|
+
_logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
_COUNTERS = (
|
|
22
|
+
(semconv.AUTHORIZATION_DECISIONS, "Authorization decisions taken by PyTraT enforcement."),
|
|
23
|
+
(semconv.ISSUANCE_DECISIONS, "Transaction Token issuance outcomes at the TTS."),
|
|
24
|
+
(semconv.REPLACEMENT_DECISIONS, "Transaction Token replacement outcomes at the TTS."),
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OpenTelemetryAuditSink:
|
|
29
|
+
"""Records each :class:`AuditEvent` as an OpenTelemetry span event and counts decisions.
|
|
30
|
+
|
|
31
|
+
Tracing: the event is added to the current span when it is recording, so it shares the
|
|
32
|
+
request's trace id (the same id the ``AuditEvent`` carries). Otherwise a short
|
|
33
|
+
``pytrat.audit`` span is started in the current context to carry it, so uninstrumented
|
|
34
|
+
applications still see events and a sampled-out parent still samples it out.
|
|
35
|
+
|
|
36
|
+
Metrics: one increment of ``pytrat.authorization.decisions``,
|
|
37
|
+
``pytrat.issuance.decisions`` or ``pytrat.replacement.decisions`` per event, with only the
|
|
38
|
+
``pytrat.decision``, ``pytrat.reason_code`` and ``pytrat.service`` attributes.
|
|
39
|
+
|
|
40
|
+
Attributes are primitives built from identifiers, reason codes and digests only. As defence
|
|
41
|
+
in depth, any string shaped like a compact JWS or JWE is withheld and counted in
|
|
42
|
+
:attr:`redacted`.
|
|
43
|
+
|
|
44
|
+
Like every :class:`~pytrat.core.audit.AuditSink`, :meth:`emit` never raises: a failure is
|
|
45
|
+
logged (exception type only) and counted in :attr:`failed`. The decision is already taken
|
|
46
|
+
when the event is emitted, so a telemetry failure cannot turn a denial into an allow.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
tracer_provider: Provider for the tracer. Defaults to the global provider.
|
|
50
|
+
meter_provider: Provider for the meter. Defaults to the global provider.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
failed: Events that could not be recorded.
|
|
54
|
+
redacted: Attributes withheld because they looked like a token.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
__slots__ = ("_counters", "_tracer", "failed", "redacted")
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
tracer_provider: trace.TracerProvider | None = None,
|
|
63
|
+
meter_provider: metrics.MeterProvider | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
self._tracer = trace.get_tracer(
|
|
66
|
+
semconv.INSTRUMENTATION_SCOPE, tracer_provider=tracer_provider
|
|
67
|
+
)
|
|
68
|
+
meter = metrics.get_meter(semconv.INSTRUMENTATION_SCOPE, meter_provider=meter_provider)
|
|
69
|
+
self._counters = MappingProxyType(
|
|
70
|
+
{
|
|
71
|
+
name: meter.create_counter(
|
|
72
|
+
name, unit=semconv.DECISIONS_UNIT, description=description
|
|
73
|
+
)
|
|
74
|
+
for name, description in _COUNTERS
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
self.failed = 0
|
|
78
|
+
self.redacted = 0
|
|
79
|
+
|
|
80
|
+
def emit(self, event: AuditEvent) -> None:
|
|
81
|
+
"""Record ``event``. Never raises."""
|
|
82
|
+
try:
|
|
83
|
+
self._record(event)
|
|
84
|
+
except Exception as exc: # noqa: BLE001 - sinks must not raise (pytrat.core.audit)
|
|
85
|
+
self.failed += 1
|
|
86
|
+
# Type only: an exporter's message could echo attribute values.
|
|
87
|
+
_logger.error("OpenTelemetry audit export failed: %s", type(exc).__name__) # noqa: TRY400
|
|
88
|
+
|
|
89
|
+
def _record(self, event: AuditEvent) -> None:
|
|
90
|
+
attributes = event_attributes(event)
|
|
91
|
+
if attributes.dropped:
|
|
92
|
+
self.redacted += len(attributes.dropped)
|
|
93
|
+
_logger.warning(
|
|
94
|
+
"withheld token-shaped audit attributes: %s", ",".join(attributes.dropped)
|
|
95
|
+
)
|
|
96
|
+
name = semconv.EVENT_NAME_PREFIX + event.event_type.value
|
|
97
|
+
timestamp = _nanoseconds(event.timestamp)
|
|
98
|
+
span = trace.get_current_span()
|
|
99
|
+
if span.is_recording():
|
|
100
|
+
span.add_event(name, attributes.span, timestamp=timestamp)
|
|
101
|
+
else:
|
|
102
|
+
audit_span = self._tracer.start_span(
|
|
103
|
+
semconv.AUDIT_SPAN_NAME,
|
|
104
|
+
kind=trace.SpanKind.INTERNAL,
|
|
105
|
+
attributes=attributes.span,
|
|
106
|
+
start_time=timestamp,
|
|
107
|
+
)
|
|
108
|
+
audit_span.add_event(name, attributes.span, timestamp=timestamp)
|
|
109
|
+
audit_span.end()
|
|
110
|
+
self._counters[attributes.counter].add(1, attributes.metric)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _nanoseconds(moment: datetime) -> int:
|
|
114
|
+
return round(moment.timestamp() * 1_000_000) * 1_000
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""OpenTelemetryAuditSink: exact span events, exact metric points, token guard, failure handling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
from hypothesis import given
|
|
12
|
+
from hypothesis import strategies as st
|
|
13
|
+
from opentelemetry import trace
|
|
14
|
+
from opentelemetry.sdk.metrics import MeterProvider
|
|
15
|
+
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
|
|
16
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
17
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
18
|
+
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
19
|
+
from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags
|
|
20
|
+
|
|
21
|
+
from pytrat.core import AgentAuditContext, AuditEvent, EventType, ReasonCode
|
|
22
|
+
from pytrat.core.testing import TokenFactory, b64url
|
|
23
|
+
from pytrat.otel import OpenTelemetryAuditSink, looks_like_jose, semconv
|
|
24
|
+
from pytrat.otel._attributes import OUTCOMES
|
|
25
|
+
|
|
26
|
+
MOMENT = datetime(2026, 11, 17, 12, 0, 0, 123456, tzinfo=UTC)
|
|
27
|
+
MOMENT_NS = 1_794_916_800_123_456_000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Telemetry:
|
|
31
|
+
def __init__(self) -> None:
|
|
32
|
+
self.spans = InMemorySpanExporter()
|
|
33
|
+
self.tracer_provider = TracerProvider()
|
|
34
|
+
self.tracer_provider.add_span_processor(SimpleSpanProcessor(self.spans))
|
|
35
|
+
self.reader = InMemoryMetricReader()
|
|
36
|
+
self.meter_provider = MeterProvider(metric_readers=[self.reader])
|
|
37
|
+
self.sink = OpenTelemetryAuditSink(
|
|
38
|
+
tracer_provider=self.tracer_provider, meter_provider=self.meter_provider
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def points(self) -> dict[str, list[tuple[dict[str, object], int]]]:
|
|
42
|
+
data = self.reader.get_metrics_data()
|
|
43
|
+
found: dict[str, list[tuple[dict[str, object], int]]] = {}
|
|
44
|
+
if data is None:
|
|
45
|
+
return found
|
|
46
|
+
for resource in data.resource_metrics:
|
|
47
|
+
for scope in resource.scope_metrics:
|
|
48
|
+
assert scope.scope.name == "pytrat.otel"
|
|
49
|
+
for metric in scope.metrics:
|
|
50
|
+
assert metric.unit == "{decision}"
|
|
51
|
+
found[metric.name] = [
|
|
52
|
+
(dict(point.attributes or {}), point.value)
|
|
53
|
+
for point in metric.data.data_points # type: ignore[union-attr]
|
|
54
|
+
]
|
|
55
|
+
return found
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@pytest.fixture
|
|
59
|
+
def otel() -> Telemetry:
|
|
60
|
+
return Telemetry()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def full_event(**overrides: object) -> AuditEvent:
|
|
64
|
+
fields: dict[str, object] = {
|
|
65
|
+
"event_type": EventType.AUTHORIZATION_DENIED,
|
|
66
|
+
"service": "ledger-service",
|
|
67
|
+
"timestamp": MOMENT,
|
|
68
|
+
"transaction_id": "txn-123",
|
|
69
|
+
"subject": "user:alice",
|
|
70
|
+
"scope": "payments.transfer",
|
|
71
|
+
"policy_id": "transfer",
|
|
72
|
+
"reason_code": ReasonCode.TRANSACTION_CONTEXT_MISMATCH,
|
|
73
|
+
"requesting_workload": "api-gateway",
|
|
74
|
+
"caller_workload": "payment-service",
|
|
75
|
+
"token_digest": "a" * 64,
|
|
76
|
+
"agent_context": AgentAuditContext(
|
|
77
|
+
originator="user:alice",
|
|
78
|
+
proximate="agent:planner",
|
|
79
|
+
hop_count=2,
|
|
80
|
+
min_assurance_level="high",
|
|
81
|
+
),
|
|
82
|
+
"trace_id": None,
|
|
83
|
+
"detail": MappingProxyType({"check": "tctx.amount_minor", "bound_fields": "amount_minor"}),
|
|
84
|
+
**overrides,
|
|
85
|
+
}
|
|
86
|
+
return AuditEvent(**fields) # type: ignore[arg-type]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
FULL_ATTRIBUTES = {
|
|
90
|
+
"pytrat.audit.schema_version": 1,
|
|
91
|
+
"pytrat.event.type": "authorization.denied",
|
|
92
|
+
"pytrat.decision": "deny",
|
|
93
|
+
"pytrat.reason_code": "TRANSACTION_CONTEXT_MISMATCH",
|
|
94
|
+
"pytrat.service": "ledger-service",
|
|
95
|
+
"pytrat.transaction.id": "txn-123",
|
|
96
|
+
"pytrat.scope": "payments.transfer",
|
|
97
|
+
"pytrat.policy.id": "transfer",
|
|
98
|
+
"pytrat.workload.requesting": "api-gateway",
|
|
99
|
+
"pytrat.workload.caller": "payment-service",
|
|
100
|
+
"pytrat.token.digest": "a" * 64,
|
|
101
|
+
"pytrat.agent.originator": "user:alice",
|
|
102
|
+
"pytrat.agent.proximate": "agent:planner",
|
|
103
|
+
"pytrat.agent.hop_count": 2,
|
|
104
|
+
"pytrat.agent.min_assurance_level": "high",
|
|
105
|
+
"pytrat.detail.check": "tctx.amount_minor",
|
|
106
|
+
"pytrat.detail.bound_fields": "amount_minor",
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_event_is_added_to_the_current_recording_span_with_exact_attributes(
|
|
111
|
+
otel: Telemetry,
|
|
112
|
+
) -> None:
|
|
113
|
+
tracer = otel.tracer_provider.get_tracer("app")
|
|
114
|
+
with tracer.start_as_current_span("POST /internal/transfer"):
|
|
115
|
+
otel.sink.emit(full_event())
|
|
116
|
+
[span] = otel.spans.get_finished_spans()
|
|
117
|
+
assert span.name == "POST /internal/transfer"
|
|
118
|
+
[event] = span.events
|
|
119
|
+
assert event.name == "pytrat.authorization.denied"
|
|
120
|
+
assert event.timestamp == MOMENT_NS
|
|
121
|
+
assert dict(event.attributes or {}) == FULL_ATTRIBUTES
|
|
122
|
+
assert otel.sink.failed == 0
|
|
123
|
+
assert otel.sink.redacted == 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_subject_is_never_exported(otel: Telemetry) -> None:
|
|
127
|
+
otel.sink.emit(full_event(subject="user:bob-unique-subject"))
|
|
128
|
+
[span] = otel.spans.get_finished_spans()
|
|
129
|
+
exported = [*span.events[0].attributes.values(), *span.attributes.values()] # type: ignore[union-attr]
|
|
130
|
+
assert "user:bob-unique-subject" not in exported
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_without_an_active_span_a_short_audit_span_carries_the_event(otel: Telemetry) -> None:
|
|
134
|
+
otel.sink.emit(full_event())
|
|
135
|
+
[span] = otel.spans.get_finished_spans()
|
|
136
|
+
assert span.name == "pytrat.audit"
|
|
137
|
+
assert span.kind is trace.SpanKind.INTERNAL
|
|
138
|
+
assert span.parent is None
|
|
139
|
+
assert span.start_time == MOMENT_NS
|
|
140
|
+
assert dict(span.attributes or {}) == FULL_ATTRIBUTES
|
|
141
|
+
[event] = span.events
|
|
142
|
+
assert event.name == "pytrat.authorization.denied"
|
|
143
|
+
assert dict(event.attributes or {}) == FULL_ATTRIBUTES
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def test_a_sampled_out_parent_also_samples_out_the_audit_span(otel: Telemetry) -> None:
|
|
147
|
+
parent = NonRecordingSpan(
|
|
148
|
+
SpanContext(trace_id=0x1234, span_id=0x5678, is_remote=True, trace_flags=TraceFlags(0))
|
|
149
|
+
)
|
|
150
|
+
with trace.use_span(parent):
|
|
151
|
+
otel.sink.emit(full_event())
|
|
152
|
+
assert otel.spans.get_finished_spans() == ()
|
|
153
|
+
# Metrics are not sampled.
|
|
154
|
+
assert otel.points()[semconv.AUTHORIZATION_DECISIONS][0][1] == 1
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def test_absent_optional_fields_are_omitted(otel: Telemetry) -> None:
|
|
158
|
+
otel.sink.emit(
|
|
159
|
+
AuditEvent(
|
|
160
|
+
event_type=EventType.TOKEN_REJECTED,
|
|
161
|
+
service="ledger-service",
|
|
162
|
+
timestamp=MOMENT,
|
|
163
|
+
reason_code=ReasonCode.TOKEN_MISSING,
|
|
164
|
+
trace_id=None,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
[span] = otel.spans.get_finished_spans()
|
|
168
|
+
assert dict(span.events[0].attributes or {}) == {
|
|
169
|
+
"pytrat.audit.schema_version": 1,
|
|
170
|
+
"pytrat.event.type": "token.rejected",
|
|
171
|
+
"pytrat.decision": "deny",
|
|
172
|
+
"pytrat.reason_code": "TOKEN_MISSING",
|
|
173
|
+
"pytrat.service": "ledger-service",
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_agent_without_assurance_level_omits_it(otel: Telemetry) -> None:
|
|
178
|
+
agent = AgentAuditContext(originator="user:alice", proximate="agent:a", hop_count=1)
|
|
179
|
+
otel.sink.emit(full_event(agent_context=agent))
|
|
180
|
+
attributes = dict(otel.spans.get_finished_spans()[0].events[0].attributes or {})
|
|
181
|
+
assert attributes["pytrat.agent.hop_count"] == 1
|
|
182
|
+
assert "pytrat.agent.min_assurance_level" not in attributes
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def test_every_event_type_has_a_counter_and_decision() -> None:
|
|
186
|
+
assert set(OUTCOMES) == set(EventType)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@pytest.mark.parametrize(
|
|
190
|
+
("event_type", "counter", "decision"),
|
|
191
|
+
[
|
|
192
|
+
(EventType.AUTHORIZATION_GRANTED, "pytrat.authorization.decisions", "allow"),
|
|
193
|
+
(EventType.AUTHORIZATION_DENIED, "pytrat.authorization.decisions", "deny"),
|
|
194
|
+
(EventType.TOKEN_REJECTED, "pytrat.authorization.decisions", "deny"),
|
|
195
|
+
(EventType.TOKEN_ISSUED, "pytrat.issuance.decisions", "allow"),
|
|
196
|
+
(EventType.ISSUANCE_DENIED, "pytrat.issuance.decisions", "deny"),
|
|
197
|
+
(EventType.TOKEN_REPLACED, "pytrat.replacement.decisions", "allow"),
|
|
198
|
+
(EventType.REPLACEMENT_DENIED, "pytrat.replacement.decisions", "deny"),
|
|
199
|
+
],
|
|
200
|
+
)
|
|
201
|
+
def test_each_event_increments_exactly_one_counter_with_bounded_attributes(
|
|
202
|
+
otel: Telemetry, event_type: EventType, counter: str, decision: str
|
|
203
|
+
) -> None:
|
|
204
|
+
otel.sink.emit(full_event(event_type=event_type, reason_code=ReasonCode.SCOPE_INSUFFICIENT))
|
|
205
|
+
otel.sink.emit(full_event(event_type=event_type, reason_code=ReasonCode.SCOPE_INSUFFICIENT))
|
|
206
|
+
points = otel.points()
|
|
207
|
+
assert {name for name, values in points.items() if values} == {counter}
|
|
208
|
+
assert points[counter] == [
|
|
209
|
+
(
|
|
210
|
+
{
|
|
211
|
+
"pytrat.decision": decision,
|
|
212
|
+
"pytrat.reason_code": "SCOPE_INSUFFICIENT",
|
|
213
|
+
"pytrat.service": "ledger-service",
|
|
214
|
+
},
|
|
215
|
+
2,
|
|
216
|
+
)
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def test_allow_without_reason_code_has_no_reason_attribute(otel: Telemetry) -> None:
|
|
221
|
+
otel.sink.emit(full_event(event_type=EventType.AUTHORIZATION_GRANTED, reason_code=None))
|
|
222
|
+
assert otel.points()[semconv.AUTHORIZATION_DECISIONS] == [
|
|
223
|
+
({"pytrat.decision": "allow", "pytrat.service": "ledger-service"}, 1)
|
|
224
|
+
]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
FACTORY = TokenFactory.create()
|
|
228
|
+
SIGNED = FACTORY.mint(txn="txn-guard")
|
|
229
|
+
UNSIGNED = FACTORY.unsigned()
|
|
230
|
+
SPACED_HEADER = b64url(b'{ "alg": "ES256" }')
|
|
231
|
+
NEWLINE_HEADER = b64url(b'{\n"alg":"ES256"}')
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@pytest.mark.parametrize(
|
|
235
|
+
"smuggled",
|
|
236
|
+
[
|
|
237
|
+
SIGNED,
|
|
238
|
+
UNSIGNED,
|
|
239
|
+
f"Bearer {SIGNED}",
|
|
240
|
+
SIGNED.replace("-", "+").replace("_", "/"),
|
|
241
|
+
f"{SPACED_HEADER}.{b64url(b'{}')}.sig",
|
|
242
|
+
f"{NEWLINE_HEADER}..detached",
|
|
243
|
+
],
|
|
244
|
+
ids=["signed", "alg-none", "embedded", "standard-base64", "spaced-header", "detached"],
|
|
245
|
+
)
|
|
246
|
+
def test_token_smuggled_into_any_string_field_never_reaches_telemetry(
|
|
247
|
+
otel: Telemetry, smuggled: str, caplog: pytest.LogCaptureFixture
|
|
248
|
+
) -> None:
|
|
249
|
+
caplog.set_level(logging.DEBUG)
|
|
250
|
+
otel.sink.emit(
|
|
251
|
+
full_event(
|
|
252
|
+
scope=smuggled,
|
|
253
|
+
policy_id=smuggled,
|
|
254
|
+
service=smuggled,
|
|
255
|
+
transaction_id=smuggled,
|
|
256
|
+
detail={"check": smuggled, smuggled: "value", "kept": "tctx.currency"},
|
|
257
|
+
)
|
|
258
|
+
)
|
|
259
|
+
[span] = otel.spans.get_finished_spans()
|
|
260
|
+
exported = {**dict(span.attributes or {}), **dict(span.events[0].attributes or {})}
|
|
261
|
+
for name, value in exported.items():
|
|
262
|
+
assert smuggled not in name
|
|
263
|
+
assert smuggled not in str(value)
|
|
264
|
+
assert exported["pytrat.detail.kept"] == "tctx.currency"
|
|
265
|
+
for absent in ("pytrat.scope", "pytrat.policy.id", "pytrat.service", "pytrat.transaction.id"):
|
|
266
|
+
assert absent not in exported
|
|
267
|
+
assert "pytrat.detail.check" not in exported
|
|
268
|
+
assert otel.sink.redacted == 6
|
|
269
|
+
assert smuggled not in caplog.text
|
|
270
|
+
assert "pytrat.detail.*" in caplog.text
|
|
271
|
+
for points in otel.points().values():
|
|
272
|
+
for attributes, _ in points:
|
|
273
|
+
assert smuggled not in attributes.values()
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@pytest.mark.parametrize(
|
|
277
|
+
"benign",
|
|
278
|
+
[
|
|
279
|
+
"payments.transfer.read",
|
|
280
|
+
"a" * 64,
|
|
281
|
+
"txn-0f3a9c",
|
|
282
|
+
"tctx.amount_minor",
|
|
283
|
+
"every.thing.is.fine",
|
|
284
|
+
"spiffe://payments.internal/ns/default/sa/ledger",
|
|
285
|
+
"eyes.only.",
|
|
286
|
+
],
|
|
287
|
+
)
|
|
288
|
+
def test_ordinary_identifiers_are_not_mistaken_for_tokens(benign: str) -> None:
|
|
289
|
+
assert not looks_like_jose(benign)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@given(
|
|
293
|
+
header=st.dictionaries(st.text(min_size=1), st.text() | st.integers(), max_size=4).map(
|
|
294
|
+
lambda extra: {"alg": "ES256", **extra}
|
|
295
|
+
),
|
|
296
|
+
payload=st.binary(max_size=64),
|
|
297
|
+
signature=st.binary(max_size=64),
|
|
298
|
+
indent=st.sampled_from([None, 1, "\t"]),
|
|
299
|
+
)
|
|
300
|
+
def test_any_compact_serialization_is_recognised(
|
|
301
|
+
header: dict[str, object], payload: bytes, signature: bytes, indent: int | str | None
|
|
302
|
+
) -> None:
|
|
303
|
+
raw_header = json.dumps(header, indent=indent).encode()
|
|
304
|
+
assert looks_like_jose(f"{b64url(raw_header)}.{b64url(payload)}.{b64url(signature)}")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class _ExplodingCounter:
|
|
308
|
+
def add(self, amount: int, attributes: object = None) -> None:
|
|
309
|
+
raise RuntimeError(f"export failed for {SIGNED}")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _ExplodingMeter:
|
|
313
|
+
def create_counter(self, name: str, unit: str = "", description: str = "") -> object:
|
|
314
|
+
return _ExplodingCounter()
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class _ExplodingMeterProvider:
|
|
318
|
+
def get_meter(self, *args: object, **kwargs: object) -> _ExplodingMeter:
|
|
319
|
+
return _ExplodingMeter()
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def test_exporter_failure_is_counted_and_logged_without_its_message(
|
|
323
|
+
caplog: pytest.LogCaptureFixture,
|
|
324
|
+
) -> None:
|
|
325
|
+
sink = OpenTelemetryAuditSink(meter_provider=_ExplodingMeterProvider()) # type: ignore[arg-type]
|
|
326
|
+
caplog.set_level(logging.ERROR, logger="pytrat.otel")
|
|
327
|
+
sink.emit(full_event())
|
|
328
|
+
assert sink.failed == 1
|
|
329
|
+
assert "OpenTelemetry audit export failed: RuntimeError" in caplog.text
|
|
330
|
+
assert SIGNED not in caplog.text
|
|
331
|
+
assert "Traceback" not in caplog.text
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def test_default_global_providers_work_without_an_sdk() -> None:
|
|
335
|
+
sink = OpenTelemetryAuditSink()
|
|
336
|
+
sink.emit(full_event())
|
|
337
|
+
assert sink.failed == 0
|