authzai 0.2.0__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.
- agentic_auth/__init__.py +8 -0
- agentic_auth/_extras.py +24 -0
- agentic_auth/api/__init__.py +0 -0
- agentic_auth/api/deps.py +112 -0
- agentic_auth/api/errors.py +51 -0
- agentic_auth/api/responses.py +38 -0
- agentic_auth/api/service_deps.py +113 -0
- agentic_auth/api/v1/__init__.py +0 -0
- agentic_auth/api/v1/agents.py +88 -0
- agentic_auth/api/v1/audit.py +67 -0
- agentic_auth/api/v1/authorize.py +439 -0
- agentic_auth/api/v1/consent.py +21 -0
- agentic_auth/api/v1/decisions.py +43 -0
- agentic_auth/api/v1/enrollment.py +48 -0
- agentic_auth/api/v1/identity.py +97 -0
- agentic_auth/api/v1/jwks.py +21 -0
- agentic_auth/api/v1/manifests.py +68 -0
- agentic_auth/api/v1/scopes.py +22 -0
- agentic_auth/api/v1/token.py +203 -0
- agentic_auth/api/v1/transaction.py +94 -0
- agentic_auth/boundary/__init__.py +26 -0
- agentic_auth/boundary/guarantee.py +96 -0
- agentic_auth/cli/__init__.py +27 -0
- agentic_auth/cli/audit.py +130 -0
- agentic_auth/cli/drift.py +164 -0
- agentic_auth/cli/drift_render.py +148 -0
- agentic_auth/cli/identity.py +63 -0
- agentic_auth/cli/manifest.py +275 -0
- agentic_auth/config.py +182 -0
- agentic_auth/db.py +49 -0
- agentic_auth/embedded/__init__.py +427 -0
- agentic_auth/embedded/_schema.py +8 -0
- agentic_auth/embedded/_transport.py +39 -0
- agentic_auth/embedded/capabilities.py +34 -0
- agentic_auth/embedded/export.py +86 -0
- agentic_auth/embedded/idp.py +78 -0
- agentic_auth/embedded/store.py +240 -0
- agentic_auth/errors.py +145 -0
- agentic_auth/main.py +141 -0
- agentic_auth/models/__init__.py +70 -0
- agentic_auth/models/agent.py +58 -0
- agentic_auth/models/audit_decision.py +199 -0
- agentic_auth/models/compiled_policy.py +28 -0
- agentic_auth/models/manifest.py +96 -0
- agentic_auth/models/reconciliation_report.py +27 -0
- agentic_auth/models/sandbox_run.py +93 -0
- agentic_auth/models/session.py +63 -0
- agentic_auth/models/step_up_grant.py +106 -0
- agentic_auth/models/transaction_token.py +73 -0
- agentic_auth/models/trust_anchor.py +59 -0
- agentic_auth/models/types.py +95 -0
- agentic_auth/observability/__init__.py +370 -0
- agentic_auth/observability/config.py +137 -0
- agentic_auth/observability/context.py +128 -0
- agentic_auth/observability/ids.py +122 -0
- agentic_auth/observability/logs.py +191 -0
- agentic_auth/observability/pep.py +169 -0
- agentic_auth/observability/spans.py +225 -0
- agentic_auth/observability/surface.py +286 -0
- agentic_auth/observability/tracing.py +167 -0
- agentic_auth/redis.py +27 -0
- agentic_auth/repositories/__init__.py +0 -0
- agentic_auth/repositories/agents.py +96 -0
- agentic_auth/repositories/audit_decisions.py +152 -0
- agentic_auth/repositories/compiled_policies.py +72 -0
- agentic_auth/repositories/manifests.py +149 -0
- agentic_auth/repositories/reconciliation_reports.py +40 -0
- agentic_auth/repositories/sessions.py +41 -0
- agentic_auth/repositories/transaction_tokens.py +60 -0
- agentic_auth/repositories/trust_anchors.py +150 -0
- agentic_auth/runtime.py +81 -0
- agentic_auth/schemas/__init__.py +0 -0
- agentic_auth/schemas/agent.py +58 -0
- agentic_auth/schemas/audit.py +207 -0
- agentic_auth/schemas/authorize.py +205 -0
- agentic_auth/schemas/common.py +40 -0
- agentic_auth/schemas/consent.py +74 -0
- agentic_auth/schemas/dag.py +39 -0
- agentic_auth/schemas/edge_trace.py +166 -0
- agentic_auth/schemas/identity.py +152 -0
- agentic_auth/schemas/manifest.py +117 -0
- agentic_auth/schemas/manifest_api.py +38 -0
- agentic_auth/schemas/reconciliation.py +49 -0
- agentic_auth/schemas/token.py +122 -0
- agentic_auth/schemas/transaction.py +28 -0
- agentic_auth/sdk/__init__.py +114 -0
- agentic_auth/sdk/client.py +677 -0
- agentic_auth/sdk/context.py +95 -0
- agentic_auth/sdk/drift.py +118 -0
- agentic_auth/sdk/errors.py +147 -0
- agentic_auth/sdk/identity.py +162 -0
- agentic_auth/sdk/planes.py +362 -0
- agentic_auth/sdk/provenance.py +63 -0
- agentic_auth/services/__init__.py +0 -0
- agentic_auth/services/anchors.py +81 -0
- agentic_auth/services/audit.py +222 -0
- agentic_auth/services/audit_chain.py +144 -0
- agentic_auth/services/audit_cursor.py +55 -0
- agentic_auth/services/catalog_service.py +58 -0
- agentic_auth/services/chain_query.py +152 -0
- agentic_auth/services/dag_compiler.py +199 -0
- agentic_auth/services/decision_cache.py +123 -0
- agentic_auth/services/decision_history.py +71 -0
- agentic_auth/services/discovery.py +95 -0
- agentic_auth/services/drift.py +330 -0
- agentic_auth/services/edge_rules.py +62 -0
- agentic_auth/services/edge_trace.py +198 -0
- agentic_auth/services/enrollment.py +310 -0
- agentic_auth/services/enrollment_rules.py +80 -0
- agentic_auth/services/manifest_service.py +166 -0
- agentic_auth/services/metrics.py +419 -0
- agentic_auth/services/pdp.py +312 -0
- agentic_auth/services/policy_loader.py +255 -0
- agentic_auth/services/principal.py +143 -0
- agentic_auth/services/reconciler.py +119 -0
- agentic_auth/services/revocation.py +149 -0
- agentic_auth/services/sessions.py +231 -0
- agentic_auth/services/taint.py +204 -0
- agentic_auth/services/tokens/__init__.py +11 -0
- agentic_auth/services/tokens/act_chain.py +76 -0
- agentic_auth/services/tokens/exchange.py +319 -0
- agentic_auth/services/tokens/jwt_profile.py +362 -0
- agentic_auth/services/tokens/keys.py +117 -0
- agentic_auth/services/tokens/profile.py +167 -0
- agentic_auth/services/tokens/replay.py +53 -0
- agentic_auth/services/transactions.py +172 -0
- agentic_auth/sidecar/__init__.py +7 -0
- agentic_auth/sidecar/__main__.py +66 -0
- agentic_auth/sidecar/app.py +349 -0
- agentic_auth/sidecar/config.py +253 -0
- agentic_auth/sidecar/deny.py +108 -0
- agentic_auth/sidecar/enforce.py +640 -0
- agentic_auth/sidecar/identity.py +37 -0
- agentic_auth/verify/__init__.py +208 -0
- agentic_auth/verify/admit.py +131 -0
- agentic_auth/verify/anchors.py +250 -0
- agentic_auth/verify/canonical.py +228 -0
- agentic_auth/verify/grants.py +158 -0
- agentic_auth/verify/identity.py +111 -0
- agentic_auth/verify/replay.py +67 -0
- agentic_auth/verify/transaction.py +164 -0
- authzai-0.2.0.dist-info/METADATA +276 -0
- authzai-0.2.0.dist-info/RECORD +148 -0
- authzai-0.2.0.dist-info/WHEEL +5 -0
- authzai-0.2.0.dist-info/entry_points.txt +5 -0
- authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
- authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
- authzai-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Single-use guard on the *decision* an exchange spends.
|
|
2
|
+
|
|
3
|
+
A hop token is bound to one target (``aud``), one data class (``scope``) and one depth
|
|
4
|
+
(``hop``). Phase 2 added a fourth binding, one *use per token*. Phase 4 moves it to one
|
|
5
|
+
*use per recorded allow decision* (``spent:{action_id}``): an agent may exchange the same
|
|
6
|
+
delegation token for as many calls as the PDP records allows for, and each recorded allow
|
|
7
|
+
still mints exactly one token.
|
|
8
|
+
The theft case the per-token guard partly covered is closed properly by proof of
|
|
9
|
+
possession at the exchange.
|
|
10
|
+
|
|
11
|
+
If the guard cannot be written the exchange fails closed. The other bindings and a
|
|
12
|
+
60-second lifetime still hold, but a guarantee that quietly degrades is worse than one
|
|
13
|
+
that refuses, because nothing downstream can tell the difference.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from redis.asyncio import Redis
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ReplayGuardUnavailable(RuntimeError):
|
|
22
|
+
"""The single-use guard could not be applied. Always fatal to the exchange."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TokenAlreadyExchanged(RuntimeError):
|
|
26
|
+
"""This subject token was already spent."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def spent_key(action_id: object) -> str:
|
|
30
|
+
"""One exchange per recorded allow decision."""
|
|
31
|
+
return f"spent:{action_id}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def consume(
|
|
35
|
+
redis: Redis | None, key: str, *, ttl_seconds: int, subject_jti: str | None = None
|
|
36
|
+
) -> None:
|
|
37
|
+
"""Claim ``key`` exactly once, or raise.
|
|
38
|
+
|
|
39
|
+
``subject_jti`` only shapes the error text, which the sidecar and SDK surface to the
|
|
40
|
+
agent: the token is fine, but this decision has already been spent.
|
|
41
|
+
"""
|
|
42
|
+
if redis is None:
|
|
43
|
+
raise ReplayGuardUnavailable("no replay store configured")
|
|
44
|
+
try:
|
|
45
|
+
# SET NX is the atomic claim: the first caller wins, everyone after sees None.
|
|
46
|
+
claimed = await redis.set(key, "1", ex=max(ttl_seconds, 1), nx=True)
|
|
47
|
+
except Exception as exc:
|
|
48
|
+
raise ReplayGuardUnavailable(f"replay store unreachable: {exc}") from exc
|
|
49
|
+
if not claimed:
|
|
50
|
+
who = subject_jti or key
|
|
51
|
+
raise TokenAlreadyExchanged(
|
|
52
|
+
f"subject token {who} has already been exchanged for this decision"
|
|
53
|
+
)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Minting call-bound authority — ``POST /v1/token/transaction``.
|
|
2
|
+
|
|
3
|
+
One transaction token per recorded allow decision. The row that records it is committed
|
|
4
|
+
**before** the token is minted, so a token that exists always has a row and a second mint
|
|
5
|
+
for the same decision is an ``IntegrityError`` on ``UNIQUE (action_id)``, never a second
|
|
6
|
+
token.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import uuid
|
|
13
|
+
from datetime import UTC, datetime, timedelta
|
|
14
|
+
|
|
15
|
+
from redis.asyncio import Redis
|
|
16
|
+
from sqlalchemy.exc import IntegrityError
|
|
17
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
18
|
+
|
|
19
|
+
from agentic_auth.config import get_settings
|
|
20
|
+
from agentic_auth.errors import (
|
|
21
|
+
PolicyDenied,
|
|
22
|
+
TransactionAlreadyMinted,
|
|
23
|
+
TransactionValidationError,
|
|
24
|
+
UnauthorizedError,
|
|
25
|
+
)
|
|
26
|
+
from agentic_auth.repositories import audit_decisions as audit_repo
|
|
27
|
+
from agentic_auth.repositories import transaction_tokens as txn_repo
|
|
28
|
+
from agentic_auth.schemas.authorize import DenyReason, Taint
|
|
29
|
+
from agentic_auth.schemas.transaction import TransactionMinted
|
|
30
|
+
from agentic_auth.services import policy_loader
|
|
31
|
+
from agentic_auth.services.metrics import get_metrics
|
|
32
|
+
from agentic_auth.services.sessions import SessionService
|
|
33
|
+
from agentic_auth.services.tokens.profile import TokenProfile, VerifiedToken
|
|
34
|
+
from agentic_auth.verify.canonical import CanonicalizationError, binding_hash, canonical_json
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _normalized(session_id: str) -> str:
|
|
40
|
+
try:
|
|
41
|
+
return str(uuid.UUID(session_id))
|
|
42
|
+
except (ValueError, TypeError, AttributeError):
|
|
43
|
+
return session_id
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TransactionService:
|
|
47
|
+
def __init__(self, tokens: TokenProfile, sessions: SessionService) -> None:
|
|
48
|
+
self._tokens = tokens
|
|
49
|
+
self._sessions = sessions
|
|
50
|
+
|
|
51
|
+
async def mint(
|
|
52
|
+
self,
|
|
53
|
+
db: AsyncSession,
|
|
54
|
+
redis: Redis | None,
|
|
55
|
+
token: VerifiedToken,
|
|
56
|
+
params: dict[str, object],
|
|
57
|
+
) -> TransactionMinted:
|
|
58
|
+
settings = get_settings()
|
|
59
|
+
metrics = get_metrics()
|
|
60
|
+
|
|
61
|
+
# The bearer must be a token minted FOR this tool call: a tool-call token names a
|
|
62
|
+
# resource, never an agent, and cannot be exchanged further.
|
|
63
|
+
if token.holder is not None:
|
|
64
|
+
metrics.transaction_mints.labels(result="invalid_token").inc()
|
|
65
|
+
raise UnauthorizedError(
|
|
66
|
+
"transaction tokens are minted against the hop token issued for the tool call, "
|
|
67
|
+
"not a delegation token or root grant"
|
|
68
|
+
)
|
|
69
|
+
if token.action_id is None:
|
|
70
|
+
metrics.transaction_mints.labels(result="invalid_token").inc()
|
|
71
|
+
raise UnauthorizedError("hop token names no recorded decision")
|
|
72
|
+
|
|
73
|
+
action_id = uuid.UUID(token.action_id)
|
|
74
|
+
row = await audit_repo.get_committed_allow(db, action_id)
|
|
75
|
+
if (
|
|
76
|
+
row is None
|
|
77
|
+
or row.outcome != "allow"
|
|
78
|
+
or str(row.session_id) != _normalized(token.session_id)
|
|
79
|
+
or row.target != token.aud
|
|
80
|
+
):
|
|
81
|
+
metrics.transaction_mints.labels(result="invalid_token").inc()
|
|
82
|
+
raise UnauthorizedError(
|
|
83
|
+
f"recorded decision {action_id} does not authorize a transaction for this token"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
session = await self._sessions.get(db, redis, token.session_id)
|
|
87
|
+
policy = await policy_loader.load(db, redis, session.scope, session.policy_version)
|
|
88
|
+
caller = row.acting_agent
|
|
89
|
+
if caller is None or not policy.is_privileged(caller, token.aud):
|
|
90
|
+
metrics.transaction_mints.labels(result="not_privileged").inc()
|
|
91
|
+
raise TransactionValidationError(
|
|
92
|
+
"target is not privileged",
|
|
93
|
+
[
|
|
94
|
+
{
|
|
95
|
+
"loc": ["target"],
|
|
96
|
+
"msg": f"{token.aud} is not privileged in policy version "
|
|
97
|
+
f"{session.policy_version}",
|
|
98
|
+
}
|
|
99
|
+
],
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# Defence in depth behind decide(): a tainted context never mints call-bound
|
|
103
|
+
# authority for a protected target, whatever the row says. Off with the taint
|
|
104
|
+
# enforcement flag, like decide() itself (recorded, never refused).
|
|
105
|
+
if (
|
|
106
|
+
settings.taint_enforcement_enabled
|
|
107
|
+
and token.taint is Taint.UNTRUSTED_EXTERNAL
|
|
108
|
+
and policy.is_protected(caller, token.aud, row.data_class)
|
|
109
|
+
):
|
|
110
|
+
metrics.transaction_mints.labels(result="tainted").inc()
|
|
111
|
+
raise PolicyDenied(
|
|
112
|
+
"tainted context cannot mint call-bound authority",
|
|
113
|
+
{
|
|
114
|
+
"reason": DenyReason.TAINTED_INTO_PRIVILEGED.value,
|
|
115
|
+
"recoverable": False,
|
|
116
|
+
"target": token.aud,
|
|
117
|
+
},
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
if len(canonical_json(params)) > settings.max_privileged_body_bytes:
|
|
122
|
+
metrics.transaction_mints.labels(result="too_large").inc()
|
|
123
|
+
raise TransactionValidationError(
|
|
124
|
+
"params exceed the binding size cap",
|
|
125
|
+
[{"loc": ["params"], "msg": f"> {settings.max_privileged_body_bytes} bytes"}],
|
|
126
|
+
)
|
|
127
|
+
binding = policy.binding_params(caller, token.aud)
|
|
128
|
+
params_hash = binding_hash(token.aud, params, binding)
|
|
129
|
+
except CanonicalizationError as exc:
|
|
130
|
+
metrics.transaction_mints.labels(result="too_large").inc()
|
|
131
|
+
raise TransactionValidationError(
|
|
132
|
+
"params cannot be canonicalized", [{"loc": ["params"], "msg": str(exc)}]
|
|
133
|
+
) from exc
|
|
134
|
+
|
|
135
|
+
issued_at = datetime.now(UTC)
|
|
136
|
+
expires_at = issued_at + timedelta(seconds=settings.transaction_token_ttl_seconds)
|
|
137
|
+
jti = str(uuid.uuid4())
|
|
138
|
+
try:
|
|
139
|
+
await txn_repo.append(
|
|
140
|
+
db,
|
|
141
|
+
jti=jti,
|
|
142
|
+
action_id=action_id,
|
|
143
|
+
session_id=row.session_id,
|
|
144
|
+
target=token.aud,
|
|
145
|
+
params_hash=params_hash,
|
|
146
|
+
binding=binding,
|
|
147
|
+
issued_at=issued_at,
|
|
148
|
+
expires_at=expires_at,
|
|
149
|
+
)
|
|
150
|
+
# Committed BEFORE minting: a token that exists always has a row.
|
|
151
|
+
await db.commit()
|
|
152
|
+
except IntegrityError as exc:
|
|
153
|
+
await db.rollback()
|
|
154
|
+
metrics.transaction_mints.labels(result="already_minted").inc()
|
|
155
|
+
raise TransactionAlreadyMinted(
|
|
156
|
+
f"decision {action_id} already has a transaction token",
|
|
157
|
+
{"action_id": str(action_id)},
|
|
158
|
+
) from exc
|
|
159
|
+
|
|
160
|
+
raw = self._tokens.mint_transaction_token(
|
|
161
|
+
hop=token, params_hash=params_hash, binding=binding
|
|
162
|
+
)
|
|
163
|
+
# The row's jti must be the token's: re-read is not possible without decoding, so the
|
|
164
|
+
# profile is asked to mint with the jti we recorded.
|
|
165
|
+
metrics.transaction_mints.labels(result="minted").inc()
|
|
166
|
+
return TransactionMinted(
|
|
167
|
+
transaction_token=raw,
|
|
168
|
+
expires_in=settings.transaction_token_ttl_seconds,
|
|
169
|
+
params_hash=params_hash,
|
|
170
|
+
binding=binding,
|
|
171
|
+
action_id=action_id,
|
|
172
|
+
)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""The sidecar PEP: enforcement for agent code the integrator did not write.
|
|
2
|
+
|
|
3
|
+
Checks that live inside an agent's own process can be skipped by the agent. Moving them
|
|
4
|
+
into a process the integrator controls is what makes the guarantee real. Runs as its own
|
|
5
|
+
uvicorn process (``agentic-auth-sidecar``) and shares this package's schemas, deny
|
|
6
|
+
vocabulary and token helpers rather than re-declaring them.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""``agentic-auth-sidecar`` entrypoint.
|
|
2
|
+
|
|
3
|
+
Exits non-zero rather than starting when it cannot enforce. A sidecar that comes up
|
|
4
|
+
without a PDP or an upstream map looks healthy while doing nothing useful, which is the
|
|
5
|
+
worst of the available failure modes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import logging
|
|
12
|
+
import socket
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
import uvicorn
|
|
16
|
+
|
|
17
|
+
from agentic_auth.observability import logs
|
|
18
|
+
from agentic_auth.sidecar.app import build_app
|
|
19
|
+
from agentic_auth.sidecar.config import SidecarConfigError, load
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> int:
|
|
23
|
+
parser = argparse.ArgumentParser(prog="agentic-auth-sidecar", description="Sidecar PEP")
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--config", default=None, help="YAML/JSON config file; omit to read AGENTIC_AUTH_SIDECAR_*"
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument("--log-level", default="info")
|
|
28
|
+
args = parser.parse_args()
|
|
29
|
+
|
|
30
|
+
logging.basicConfig(level=args.log_level.upper())
|
|
31
|
+
# Structured, machine-parsable records with correlation fields.
|
|
32
|
+
# Added after basicConfig so the JSON handler sits alongside the default stream handler
|
|
33
|
+
# rather than replacing it, and a developer watching a terminal still sees plain lines.
|
|
34
|
+
logs.configure()
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
config = load(args.config)
|
|
38
|
+
except SidecarConfigError as exc:
|
|
39
|
+
print(f"sidecar: refusing to start: {exc}", file=sys.stderr)
|
|
40
|
+
return 2
|
|
41
|
+
except OSError as exc:
|
|
42
|
+
print(f"sidecar: cannot read config: {exc}", file=sys.stderr)
|
|
43
|
+
return 2
|
|
44
|
+
|
|
45
|
+
# Bind-check before uvicorn so the failure is one clear line, not a traceback.
|
|
46
|
+
probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
47
|
+
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
48
|
+
try:
|
|
49
|
+
probe.bind((config.host, config.port))
|
|
50
|
+
except OSError as exc:
|
|
51
|
+
print(f"sidecar: cannot bind {config.listen_addr}: {exc}", file=sys.stderr)
|
|
52
|
+
return 2
|
|
53
|
+
finally:
|
|
54
|
+
probe.close()
|
|
55
|
+
|
|
56
|
+
if config.observe_mode:
|
|
57
|
+
logging.getLogger(__name__).warning(
|
|
58
|
+
"OBSERVE MODE: denials are recorded but NOT enforced. Not a security posture."
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
uvicorn.run(build_app(config), host=config.host, port=config.port, log_level=args.log_level)
|
|
62
|
+
return 0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
if __name__ == "__main__":
|
|
66
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""The sidecar reverse proxy.
|
|
2
|
+
|
|
3
|
+
A reverse proxy rather than a forward/CONNECT proxy: no TLS interception, no CA to trust
|
|
4
|
+
in the agent runtime, no root privileges. The agent's tool base URL points here.
|
|
5
|
+
|
|
6
|
+
Bodies stream in both directions so a large tool payload never buffers in memory.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import AsyncIterator
|
|
17
|
+
from dataclasses import asdict
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
|
21
|
+
from starlette.applications import Starlette
|
|
22
|
+
from starlette.requests import Request
|
|
23
|
+
from starlette.responses import JSONResponse, Response, StreamingResponse
|
|
24
|
+
from starlette.routing import Route
|
|
25
|
+
|
|
26
|
+
from agentic_auth import observability
|
|
27
|
+
from agentic_auth.observability import pep as pep_telemetry
|
|
28
|
+
from agentic_auth.observability import surface
|
|
29
|
+
from agentic_auth.services.edge_trace import EdgeRecorder
|
|
30
|
+
from agentic_auth.services.metrics import build_pep_metrics
|
|
31
|
+
from agentic_auth.sidecar.config import RESERVED_PATH_PREFIX, SidecarConfig
|
|
32
|
+
from agentic_auth.sidecar.enforce import Allow, Blocked, Observed, enforce
|
|
33
|
+
from agentic_auth.sidecar.identity import load_identity
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
|
38
|
+
|
|
39
|
+
# This enforcement point's own version, reported as a label on agentic_auth_pep_info.
|
|
40
|
+
PEP_VERSION = "0.1.0"
|
|
41
|
+
|
|
42
|
+
# Hop-by-hop headers must not be relayed (RFC 9110 §7.6.1); Host and Content-Length are
|
|
43
|
+
# recomputed by the client for the upstream request.
|
|
44
|
+
_SKIP_REQUEST_HEADERS = {
|
|
45
|
+
"host",
|
|
46
|
+
"content-length",
|
|
47
|
+
"connection",
|
|
48
|
+
"keep-alive",
|
|
49
|
+
"transfer-encoding",
|
|
50
|
+
"upgrade",
|
|
51
|
+
"proxy-authorization",
|
|
52
|
+
"proxy-authenticate",
|
|
53
|
+
"te",
|
|
54
|
+
"trailer",
|
|
55
|
+
}
|
|
56
|
+
_SKIP_RESPONSE_HEADERS = {
|
|
57
|
+
"content-length",
|
|
58
|
+
"content-encoding",
|
|
59
|
+
"connection",
|
|
60
|
+
"keep-alive",
|
|
61
|
+
"transfer-encoding",
|
|
62
|
+
"upgrade",
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _upstream_digest(config: SidecarConfig) -> str:
|
|
67
|
+
"""A stable digest of the upstream map, for comparing two PEPs that should match."""
|
|
68
|
+
payload = json.dumps(
|
|
69
|
+
{
|
|
70
|
+
prefix: [u.url, u.target, u.data_class]
|
|
71
|
+
for prefix, u in sorted(config.upstream_map.items())
|
|
72
|
+
},
|
|
73
|
+
sort_keys=True,
|
|
74
|
+
)
|
|
75
|
+
return "sha256:" + hashlib.sha256(payload.encode()).hexdigest()[:16]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build_app(config: SidecarConfig, client: httpx.AsyncClient | None = None) -> Starlette:
|
|
79
|
+
# One pooled client for the whole process. A per-request client would spend the
|
|
80
|
+
# entire per-hop latency budget on connection setup alone.
|
|
81
|
+
owned = client is None
|
|
82
|
+
http = client or httpx.AsyncClient()
|
|
83
|
+
# Passive: one event per call, written after the outcome is fixed. A recorder failure is
|
|
84
|
+
# counted into the events file, never raised here (agentic_auth/services/edge_trace.py).
|
|
85
|
+
recorder = EdgeRecorder(config.trace_path, "sidecar") if config.trace_path else None
|
|
86
|
+
# Phase 4: with a key configured, every exchange carries an actor_token and every
|
|
87
|
+
# forwarded call an Agent-Identity assertion. Loaded once; a bad key fails startup.
|
|
88
|
+
identity = load_identity(config)
|
|
89
|
+
|
|
90
|
+
# -- telemetry -------------------------------------------------
|
|
91
|
+
# One registry per process, served at GET /__agentic/metrics. Before this, nothing here
|
|
92
|
+
# emitted anything: a sidecar that had been silently forwarding every call looked exactly
|
|
93
|
+
# like a healthy one.
|
|
94
|
+
metrics = build_pep_metrics()
|
|
95
|
+
mode = surface.PEP_MODE_OBSERVING if config.observe_mode else surface.PEP_MODE_ENFORCING
|
|
96
|
+
metrics.up.set(1)
|
|
97
|
+
metrics.info.labels(mode=mode, version=PEP_VERSION).set(1)
|
|
98
|
+
telemetry = observability.setup(
|
|
99
|
+
service_name=surface.COMPONENT_PEP,
|
|
100
|
+
resolved=observability.ObservabilityConfig.resolve(
|
|
101
|
+
enabled=config.telemetry_enabled,
|
|
102
|
+
key=config.telemetry_key,
|
|
103
|
+
identity_disclosure=config.telemetry_identity_disclosure,
|
|
104
|
+
allow_sample_ratio=config.telemetry_allow_sample_ratio,
|
|
105
|
+
service_name=surface.COMPONENT_PEP,
|
|
106
|
+
),
|
|
107
|
+
metrics=metrics,
|
|
108
|
+
)
|
|
109
|
+
metrics.telemetry_identity_disclosure.set(1 if telemetry.identity_disclosure else 0)
|
|
110
|
+
started_at = time.monotonic()
|
|
111
|
+
# Derived from the last real control-plane call, not from a probe: a probe adds a request
|
|
112
|
+
# the dispatch path does not need and can report healthy while real calls fail.
|
|
113
|
+
pdp_state: dict[str, float | None] = {"last_success": None}
|
|
114
|
+
|
|
115
|
+
async def proxy(request: Request) -> StreamingResponse | JSONResponse:
|
|
116
|
+
path = request.url.path
|
|
117
|
+
|
|
118
|
+
async def read_body(cap: int) -> bytes | None:
|
|
119
|
+
"""Buffer up to ``cap`` bytes; ``None`` past it. Only called for privileged calls."""
|
|
120
|
+
chunks: list[bytes] = []
|
|
121
|
+
total = 0
|
|
122
|
+
async for chunk in request.stream():
|
|
123
|
+
total += len(chunk)
|
|
124
|
+
if total > cap:
|
|
125
|
+
return None
|
|
126
|
+
chunks.append(chunk)
|
|
127
|
+
return b"".join(chunks)
|
|
128
|
+
|
|
129
|
+
timer = pep_telemetry.StageTimer(metrics)
|
|
130
|
+
session_hint = request.headers.get("x-agentic-session")
|
|
131
|
+
parent = observability.extract_parent(
|
|
132
|
+
request.headers,
|
|
133
|
+
session_id=session_hint,
|
|
134
|
+
key=telemetry.key,
|
|
135
|
+
metrics=metrics,
|
|
136
|
+
)
|
|
137
|
+
outcome = await enforce(
|
|
138
|
+
http,
|
|
139
|
+
config,
|
|
140
|
+
path=path,
|
|
141
|
+
headers=request.headers,
|
|
142
|
+
body_reader=read_body,
|
|
143
|
+
identity=identity,
|
|
144
|
+
timer=timer,
|
|
145
|
+
)
|
|
146
|
+
if recorder is not None:
|
|
147
|
+
recorder.record(**asdict(outcome.attribution))
|
|
148
|
+
|
|
149
|
+
# One mapping for all ~20 of enforce()'s return paths, because every one of them
|
|
150
|
+
# already produces an EdgeAttribution. The alternative — a counter increment at each
|
|
151
|
+
# return — would have missed one eventually.
|
|
152
|
+
classification = pep_telemetry.classify(
|
|
153
|
+
outcome.attribution.outcome, outcome.attribution.reason
|
|
154
|
+
)
|
|
155
|
+
pep_telemetry.record(metrics, classification)
|
|
156
|
+
_emit_forward_span(
|
|
157
|
+
parent=parent,
|
|
158
|
+
method=request.method,
|
|
159
|
+
classification=classification,
|
|
160
|
+
session_id=session_hint,
|
|
161
|
+
)
|
|
162
|
+
# Only a call that actually reached the decision endpoint says anything about whether
|
|
163
|
+
# it is reachable. A refusal before dispatch — an unauthorized bearer, an unmapped
|
|
164
|
+
# path — never contacted it, and counting those as success made `/status` report the
|
|
165
|
+
# control plane healthy while it was in fact dead.
|
|
166
|
+
if "decide" in timer.stages and classification.block_cause != "pdp_unreachable":
|
|
167
|
+
pdp_state["last_success"] = time.monotonic()
|
|
168
|
+
|
|
169
|
+
if isinstance(outcome, Blocked):
|
|
170
|
+
timer.finish()
|
|
171
|
+
return outcome.response
|
|
172
|
+
|
|
173
|
+
if isinstance(outcome, Observed):
|
|
174
|
+
# Denied, but the operator asked to watch rather than block. The ORIGINAL
|
|
175
|
+
# token goes upstream — no exchange happened for a denied hop.
|
|
176
|
+
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
|
|
177
|
+
upstream, prefix = outcome.upstream, outcome.prefix
|
|
178
|
+
elif isinstance(outcome, Allow):
|
|
179
|
+
token, upstream, prefix = outcome.token, outcome.upstream, outcome.prefix
|
|
180
|
+
else: # pragma: no cover - the union is closed; a new member must be handled
|
|
181
|
+
logger.error("unhandled enforcement outcome %r — blocking", type(outcome).__name__)
|
|
182
|
+
return JSONResponse(
|
|
183
|
+
status_code=503,
|
|
184
|
+
content={
|
|
185
|
+
"error": {
|
|
186
|
+
"code": "policy_denied",
|
|
187
|
+
"message": "unhandled enforcement outcome",
|
|
188
|
+
"details": {"reason": "PDP_UNAVAILABLE", "recoverable": False},
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
suffix = path[len(prefix.rstrip("/")) :] or "/"
|
|
194
|
+
url = httpx.URL(f"{upstream.url}{suffix}", query=request.url.query.encode())
|
|
195
|
+
|
|
196
|
+
headers = {
|
|
197
|
+
k: v for k, v in request.headers.items() if k.lower() not in _SKIP_REQUEST_HEADERS
|
|
198
|
+
}
|
|
199
|
+
# The narrowed token replaces the presented one. The presented token is never
|
|
200
|
+
# forwarded unchanged on an allowed hop.
|
|
201
|
+
headers["authorization"] = f"Bearer {token}"
|
|
202
|
+
# `traceparent` is not a hop-by-hop header and is deliberately absent from
|
|
203
|
+
# `_SKIP_REQUEST_HEADERS`, so a caller-supplied one already passes through untouched.
|
|
204
|
+
# This adds one when the caller sent none, so the upstream lands in the same trace
|
|
205
|
+
# either way. Do not "tidy" traceparent into the skip list.
|
|
206
|
+
observability.inject(headers)
|
|
207
|
+
content: object = request.stream()
|
|
208
|
+
if isinstance(outcome, Allow):
|
|
209
|
+
if outcome.transaction_token is not None:
|
|
210
|
+
headers["txn-token"] = outcome.transaction_token
|
|
211
|
+
if outcome.identity_assertion is not None:
|
|
212
|
+
headers["agent-identity"] = outcome.identity_assertion
|
|
213
|
+
if outcome.body is not None:
|
|
214
|
+
# Buffered to bind it; forward exactly those bytes.
|
|
215
|
+
content = outcome.body
|
|
216
|
+
|
|
217
|
+
upstream_request = http.build_request(
|
|
218
|
+
request.method,
|
|
219
|
+
url,
|
|
220
|
+
headers=headers,
|
|
221
|
+
content=content, # type: ignore[arg-type]
|
|
222
|
+
timeout=httpx.Timeout(config.request_timeout_seconds),
|
|
223
|
+
)
|
|
224
|
+
upstream_started = time.perf_counter()
|
|
225
|
+
try:
|
|
226
|
+
response = await http.send(upstream_request, stream=True)
|
|
227
|
+
except Exception as exc:
|
|
228
|
+
timer.finish()
|
|
229
|
+
logger.warning(
|
|
230
|
+
"upstream unreachable",
|
|
231
|
+
extra={"authz.component": "pep", "error.type": type(exc).__name__},
|
|
232
|
+
)
|
|
233
|
+
return JSONResponse(
|
|
234
|
+
status_code=502,
|
|
235
|
+
content={
|
|
236
|
+
"error": {
|
|
237
|
+
"code": "upstream_unreachable",
|
|
238
|
+
"message": f"upstream did not respond: {exc}",
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
async def body() -> AsyncIterator[bytes]:
|
|
244
|
+
try:
|
|
245
|
+
async for chunk in response.aiter_raw():
|
|
246
|
+
yield chunk
|
|
247
|
+
finally:
|
|
248
|
+
await response.aclose()
|
|
249
|
+
# The upstream stage ends when its body is fully relayed, so overhead is
|
|
250
|
+
# measured against the whole call rather than against the headers only.
|
|
251
|
+
timer._record("upstream", time.perf_counter() - upstream_started)
|
|
252
|
+
timer.finish()
|
|
253
|
+
|
|
254
|
+
return StreamingResponse(
|
|
255
|
+
body(),
|
|
256
|
+
status_code=response.status_code,
|
|
257
|
+
headers={
|
|
258
|
+
k: v for k, v in response.headers.items() if k.lower() not in _SKIP_RESPONSE_HEADERS
|
|
259
|
+
},
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
async def pep_metrics(_request: Request) -> Response:
|
|
263
|
+
"""This enforcement point's own Prometheus exposition.
|
|
264
|
+
|
|
265
|
+
Served on the existing listener — no new port. A PEP that is not scraped is not
|
|
266
|
+
observable, and no amount of instrumentation inside it changes that: see
|
|
267
|
+
https://authzai.dev/how-to/observe-the-guardrail for the deployment
|
|
268
|
+
obligation this route creates.
|
|
269
|
+
"""
|
|
270
|
+
return Response(generate_latest(metrics.registry), media_type=CONTENT_TYPE_LATEST)
|
|
271
|
+
|
|
272
|
+
async def pep_status(_request: Request) -> JSONResponse:
|
|
273
|
+
"""Mode, liveness and dependency health, for an operator or a readiness probe.
|
|
274
|
+
|
|
275
|
+
``upstream_map_digest`` is a digest rather than the map itself: upstream URLs carry
|
|
276
|
+
internal hostnames, and two PEPs that are supposed to be configured identically are
|
|
277
|
+
compared by digest anyway.
|
|
278
|
+
"""
|
|
279
|
+
last = pdp_state["last_success"]
|
|
280
|
+
return JSONResponse(
|
|
281
|
+
{
|
|
282
|
+
"mode": mode,
|
|
283
|
+
"uptime_seconds": round(time.monotonic() - started_at, 3),
|
|
284
|
+
"upstreams": len(config.upstream_map),
|
|
285
|
+
"upstream_map_digest": _upstream_digest(config),
|
|
286
|
+
"pdp": {
|
|
287
|
+
"reachable": last is not None,
|
|
288
|
+
"last_success_seconds_ago": (
|
|
289
|
+
None if last is None else round(time.monotonic() - last, 3)
|
|
290
|
+
),
|
|
291
|
+
},
|
|
292
|
+
"telemetry": {
|
|
293
|
+
"enabled": telemetry.enabled,
|
|
294
|
+
"state": telemetry.state,
|
|
295
|
+
"identity_disclosure": telemetry.identity_disclosure,
|
|
296
|
+
},
|
|
297
|
+
"version": PEP_VERSION,
|
|
298
|
+
}
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
def _emit_forward_span(
|
|
302
|
+
*,
|
|
303
|
+
parent: object,
|
|
304
|
+
method: str,
|
|
305
|
+
classification: pep_telemetry.Classification,
|
|
306
|
+
session_id: str | None,
|
|
307
|
+
) -> None:
|
|
308
|
+
"""``pep.forward`` — the enforcement point's view of one proxied call.
|
|
309
|
+
|
|
310
|
+
The stage children (`pep.decide` and friends) are not emitted as separate spans: the
|
|
311
|
+
same boundaries are already in the stage histograms, and a span per stage would triple
|
|
312
|
+
the volume for a number an operator reads off a dashboard anyway.
|
|
313
|
+
"""
|
|
314
|
+
if not telemetry.enabled:
|
|
315
|
+
return
|
|
316
|
+
attributes = observability.pep_attributes(
|
|
317
|
+
telemetry,
|
|
318
|
+
mode=mode,
|
|
319
|
+
outcome=classification.outcome,
|
|
320
|
+
block_cause=classification.block_cause,
|
|
321
|
+
session_id=session_id,
|
|
322
|
+
http_method=method,
|
|
323
|
+
)
|
|
324
|
+
with observability.tracer().start_as_current_span(
|
|
325
|
+
surface.SPAN_PEP_FORWARD,
|
|
326
|
+
context=parent,
|
|
327
|
+
attributes=attributes,
|
|
328
|
+
record_exception=False,
|
|
329
|
+
):
|
|
330
|
+
pass
|
|
331
|
+
|
|
332
|
+
@contextlib.asynccontextmanager
|
|
333
|
+
async def lifespan(_app: Starlette) -> AsyncIterator[None]:
|
|
334
|
+
yield
|
|
335
|
+
observability.shutdown()
|
|
336
|
+
metrics.up.set(0)
|
|
337
|
+
if owned: # only close what we created; an injected client is the caller's
|
|
338
|
+
await http.aclose()
|
|
339
|
+
|
|
340
|
+
return Starlette(
|
|
341
|
+
routes=[
|
|
342
|
+
# Before the catch-all, and under a prefix `validate()` refuses to let an
|
|
343
|
+
# upstream mapping shadow.
|
|
344
|
+
Route(f"{RESERVED_PATH_PREFIX}/metrics", pep_metrics, methods=["GET"]),
|
|
345
|
+
Route(f"{RESERVED_PATH_PREFIX}/status", pep_status, methods=["GET"]),
|
|
346
|
+
Route("/{path:path}", proxy, methods=METHODS),
|
|
347
|
+
],
|
|
348
|
+
lifespan=lifespan,
|
|
349
|
+
)
|