agentlighthouse-governance 0.4.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.
@@ -0,0 +1,74 @@
1
+ # --- Internal working docs (never published) ---
2
+ # Blueprints, phase plans, progress tracking, the self-audit, the test plan.
3
+ # Build process and internal notes, not product. The published docs are in
4
+ # docs/ (architecture, OWASP mapping, demos, rollout, compliance).
5
+ /.internal/
6
+ # Product strategy working docs (never published).
7
+ /product_strategy/
8
+
9
+ # Progress and planning notes belong in .internal/. These names sat at the
10
+ # repo root before the public reorganisation; keep a stray copy from being
11
+ # committed again.
12
+ /STATUS.md
13
+ /ToDo.md
14
+ /TODO.md
15
+ /MEMORY.md
16
+ /GAPS.md
17
+ /Plan_V2.md
18
+ /[0-9][0-9]_*.md
19
+
20
+ # --- Paper ---
21
+ /paper/*
22
+ # --- general files ---
23
+ CLAUDE.md
24
+ # AI assistant session state, local settings and memory.
25
+ .claude/
26
+
27
+ # --- Secrets & keys (NEVER commit — invariant D5) ---
28
+ keys/
29
+ .env
30
+ *.pem
31
+ *_ed25519
32
+ *_ed25519.pub
33
+ !keys/.gitkeep
34
+ # The key-management source package, not key material.
35
+ !core/al_core/keys/
36
+
37
+ # --- Python / uv ---
38
+ __pycache__/
39
+ *.py[cod]
40
+ .venv/
41
+ uv.lock.local
42
+ .pytest_cache/
43
+ .coverage
44
+ htmlcov/
45
+ *.egg-info/
46
+ dist/
47
+ build/
48
+
49
+ # --- Node (dashboard build toolchain only) ---
50
+ node_modules/
51
+ governance/dashboard/dist/
52
+ frontend/dist/
53
+ frontend/test-results/
54
+ frontend/playwright-report/
55
+ frontend/.playwright/
56
+ *.tsbuildinfo
57
+
58
+ # --- Runtime data (JSONL/SQLite live outside the tree in prod) ---
59
+ data/
60
+ examples/memory-poison/run/
61
+ examples/tool-response-injection/run/
62
+ examples/a2a-lab/run/
63
+ *.sqlite
64
+ *.sqlite-wal
65
+ *.sqlite-shm
66
+ *.jsonl
67
+
68
+ # --- OS / editors ---
69
+ .DS_Store
70
+ Thumbs.db
71
+ .vscode/
72
+ .idea/
73
+
74
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amit Kala
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.
@@ -0,0 +1,220 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentlighthouse-governance
3
+ Version: 0.4.0
4
+ Summary: AgentLighthouse governance: org tenancy, RBAC, budgets, signed posture attestation
5
+ Project-URL: Homepage, https://github.com/neural-nomad1709/agentlighthouse
6
+ Project-URL: Repository, https://github.com/neural-nomad1709/agentlighthouse
7
+ Author: Amit Kala
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: agentlighthouse-core
12
+ Requires-Dist: agentlighthouse-verify
13
+ Requires-Dist: cryptography>=43
14
+ Requires-Dist: fastapi>=0.111
15
+ Requires-Dist: typer>=0.12
16
+ Requires-Dist: uvicorn>=0.30
17
+ Provides-Extra: postgres
18
+ Requires-Dist: psycopg[binary]>=3.2; extra == 'postgres'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # agentlighthouse-governance
22
+
23
+ **Multi-organization governance for AgentLighthouse.**
24
+
25
+ [AgentLighthouse](https://github.com/neural-nomad1709/agentlighthouse) is a
26
+ security mediator for AI agents that signs a receipt for every decision it
27
+ takes. This package adds what a team running more than one agent fleet needs
28
+ on top of it: organizations as tenants, role-based access, per-organization
29
+ budgets with cost reporting, and a **signed posture attestation** whose
30
+ evidence level is computed from the ledger.
31
+
32
+ It provides the `al-gov` command line and a governed control-plane service.
33
+
34
+ - **Source and full documentation:** <https://github.com/neural-nomad1709/agentlighthouse>
35
+ - **License:** MIT
36
+ - **Python:** 3.12 or newer
37
+
38
+ ## Contents
39
+
40
+ - [Install](#install)
41
+ - [Quick start](#quick-start)
42
+ - [Organizations](#organizations)
43
+ - [Users and roles](#users-and-roles)
44
+ - [Posture attestation](#posture-attestation)
45
+ - [Budgets and cost](#budgets-and-cost)
46
+ - [The governed control plane](#the-governed-control-plane)
47
+ - [Where tenant isolation is enforced](#where-tenant-isolation-is-enforced)
48
+ - [Command reference](#command-reference)
49
+ - [Related packages](#related-packages)
50
+ - [License](#license)
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install agentlighthouse-governance
56
+ ```
57
+
58
+ This installs `al-gov`, and with it the mediator
59
+ ([agentlighthouse-core](https://pypi.org/project/agentlighthouse-core/),
60
+ command `al`) and the standalone verifier
61
+ ([agentlighthouse-verify](https://pypi.org/project/agentlighthouse-verify/),
62
+ command `al-verify`).
63
+
64
+ The governance layer runs on the control host, next to the control plane. It
65
+ is not part of the agent-facing data plane.
66
+
67
+ ## Quick start
68
+
69
+ Start from a workspace created with `al init`.
70
+
71
+ ```bash
72
+ al-gov org create acme # create a tenant
73
+ al-gov user add alice@acme --org acme --role admin # prints the user's token once
74
+
75
+ al-gov attest export acme > acme.attest.json # signed posture attestation
76
+ al-gov attest verify acme.attest.json # verified, with its evidence level
77
+
78
+ al-gov cost --org acme # today's spend per virtual key
79
+ al-gov serve # governed control plane and dashboard
80
+ ```
81
+
82
+ ## Organizations
83
+
84
+ An organization is a tenant. Its slug is the organization segment of its
85
+ agents' identities:
86
+
87
+ ```
88
+ spiffe://<org>/agent/<name>
89
+ ```
90
+
91
+ An agent identified as `spiffe://acme/agent/research-agent` belongs to the
92
+ organization `acme`, and its receipts are that organization's evidence. A slug
93
+ is made of lowercase letters, digits, `.`, `_` and `-`.
94
+
95
+ ```bash
96
+ al-gov org create acme
97
+ al-gov org list
98
+ ```
99
+
100
+ ## Users and roles
101
+
102
+ | Role | Capabilities |
103
+ |---|---|
104
+ | `admin` | View and verify evidence, resolve approvals, configure, export attestations |
105
+ | `operator` | View and verify evidence, resolve approvals |
106
+ | `viewer` | View and verify evidence |
107
+
108
+ A user belongs to one organization and sees only that organization's evidence.
109
+ A fleet administrator has no organization and sees across all of them; that
110
+ scope is available to administrators only.
111
+
112
+ ```bash
113
+ al-gov user add alice@acme --org acme --role admin
114
+ al-gov user list
115
+ al-gov user revoke alice@acme
116
+ ```
117
+
118
+ A token is printed once, when the user is added. It is stored hashed and
119
+ cannot be recovered. A revoked token stops authenticating immediately,
120
+ including against a control plane that is already running.
121
+
122
+ ## Posture attestation
123
+
124
+ An attestation is a signed statement about one organization over a period:
125
+
126
+ - its posture (mode, environment, whether the mediator is enforcing, whether
127
+ the egress self-test is enforced, and the configuration hash)
128
+ - its evidence, counted by verdict, action, block reason and OWASP Agentic
129
+ risk
130
+ - the head of the receipt chain it was cut from
131
+
132
+ It is signed with the mediator's key and can be verified by anyone holding the
133
+ public key, using the standalone verifier:
134
+
135
+ ```bash
136
+ al-gov attest export acme > acme.attest.json
137
+ al-verify acme.attest.json --pubkey keys/mediator_ed25519.pub
138
+ ```
139
+
140
+ ### The evidence level is computed
141
+
142
+ The attestation carries an Agent Evidence Level. It is derived from the
143
+ evidence and can only be reduced by a failing condition, so a deployment
144
+ cannot claim a level it has not earned.
145
+
146
+ | Level | Condition |
147
+ |---|---|
148
+ | `AEL-0` | The chain does not verify. Nothing in the attestation is trusted. |
149
+ | `AEL-1` | Every decision is signed and the chain verifies from genesis. |
150
+ | `AEL-2` | AEL-1, and the mediator enforces. A deployment in `audit` mode cannot reach this level. |
151
+ | `AEL-3` | AEL-2, and the egress choke-point self-test is enforced. |
152
+
153
+ Exporting an attestation before and after a change of mode turns the change
154
+ itself into evidence.
155
+
156
+ ## Budgets and cost
157
+
158
+ Each organization can carry daily request and token budgets. A request over
159
+ budget is refused by the mediator.
160
+
161
+ `al-gov cost` reports the day's usage per virtual key, for one organization or
162
+ for the whole fleet:
163
+
164
+ ```bash
165
+ al-gov cost --org acme
166
+ al-gov cost --org acme --usd-per-mtok 3.0 # price it with a blended rate
167
+ ```
168
+
169
+ Cost is derived from recorded usage. When no rate is supplied the report gives
170
+ no dollar figure, because an unknown price is not zero.
171
+
172
+ ## The governed control plane
173
+
174
+ `al-gov serve` runs the control plane with the organization directory as its
175
+ authenticator, and serves the evidence dashboard and the governance API.
176
+
177
+ ```bash
178
+ al-gov serve --host 127.0.0.1 --port 8888
179
+ ```
180
+
181
+ Every read is scoped to the caller's organization. Asking for a receipt that
182
+ belongs to another tenant returns "not found" and never "forbidden", because
183
+ confirming that a receipt exists would itself leak information.
184
+
185
+ Bind the service to the control network only. Agents must have no route to it.
186
+
187
+ ## Where tenant isolation is enforced
188
+
189
+ Isolation is enforced in the mediator, `agentlighthouse-core`, which never
190
+ imports this package. The governance layer supplies the directory of
191
+ organizations and users, and the core applies the scope to every evidence
192
+ read. A defect in this layer can therefore narrow what a caller sees and
193
+ cannot widen it.
194
+
195
+ ## Command reference
196
+
197
+ | Command | Purpose |
198
+ |---|---|
199
+ | `al-gov org create <slug>` | Create a tenant |
200
+ | `al-gov org list` | List tenants |
201
+ | `al-gov user add <subject> --org <slug> --role <role>` | Add a user and print its token once |
202
+ | `al-gov user list` | List users, never their tokens |
203
+ | `al-gov user revoke <subject>` | Revoke a user |
204
+ | `al-gov attest export <slug>` | Export a signed posture attestation |
205
+ | `al-gov attest verify <file>` | Verify an attestation |
206
+ | `al-gov cost [--org <slug>]` | Report spend per virtual key |
207
+ | `al-gov serve` | Serve the governed control plane |
208
+
209
+ Run any command with `--help` for its options.
210
+
211
+ ## Related packages
212
+
213
+ | Package | What it is |
214
+ |---|---|
215
+ | [agentlighthouse-core](https://pypi.org/project/agentlighthouse-core/) | The mediator: proxies, scanners, policy engine, evidence ledger. |
216
+ | [agentlighthouse-verify](https://pypi.org/project/agentlighthouse-verify/) | The standalone verifier for receipts and attestations. |
217
+
218
+ ## License
219
+
220
+ MIT. See the `LICENSE` file shipped with this package.
@@ -0,0 +1,200 @@
1
+ # agentlighthouse-governance
2
+
3
+ **Multi-organization governance for AgentLighthouse.**
4
+
5
+ [AgentLighthouse](https://github.com/neural-nomad1709/agentlighthouse) is a
6
+ security mediator for AI agents that signs a receipt for every decision it
7
+ takes. This package adds what a team running more than one agent fleet needs
8
+ on top of it: organizations as tenants, role-based access, per-organization
9
+ budgets with cost reporting, and a **signed posture attestation** whose
10
+ evidence level is computed from the ledger.
11
+
12
+ It provides the `al-gov` command line and a governed control-plane service.
13
+
14
+ - **Source and full documentation:** <https://github.com/neural-nomad1709/agentlighthouse>
15
+ - **License:** MIT
16
+ - **Python:** 3.12 or newer
17
+
18
+ ## Contents
19
+
20
+ - [Install](#install)
21
+ - [Quick start](#quick-start)
22
+ - [Organizations](#organizations)
23
+ - [Users and roles](#users-and-roles)
24
+ - [Posture attestation](#posture-attestation)
25
+ - [Budgets and cost](#budgets-and-cost)
26
+ - [The governed control plane](#the-governed-control-plane)
27
+ - [Where tenant isolation is enforced](#where-tenant-isolation-is-enforced)
28
+ - [Command reference](#command-reference)
29
+ - [Related packages](#related-packages)
30
+ - [License](#license)
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install agentlighthouse-governance
36
+ ```
37
+
38
+ This installs `al-gov`, and with it the mediator
39
+ ([agentlighthouse-core](https://pypi.org/project/agentlighthouse-core/),
40
+ command `al`) and the standalone verifier
41
+ ([agentlighthouse-verify](https://pypi.org/project/agentlighthouse-verify/),
42
+ command `al-verify`).
43
+
44
+ The governance layer runs on the control host, next to the control plane. It
45
+ is not part of the agent-facing data plane.
46
+
47
+ ## Quick start
48
+
49
+ Start from a workspace created with `al init`.
50
+
51
+ ```bash
52
+ al-gov org create acme # create a tenant
53
+ al-gov user add alice@acme --org acme --role admin # prints the user's token once
54
+
55
+ al-gov attest export acme > acme.attest.json # signed posture attestation
56
+ al-gov attest verify acme.attest.json # verified, with its evidence level
57
+
58
+ al-gov cost --org acme # today's spend per virtual key
59
+ al-gov serve # governed control plane and dashboard
60
+ ```
61
+
62
+ ## Organizations
63
+
64
+ An organization is a tenant. Its slug is the organization segment of its
65
+ agents' identities:
66
+
67
+ ```
68
+ spiffe://<org>/agent/<name>
69
+ ```
70
+
71
+ An agent identified as `spiffe://acme/agent/research-agent` belongs to the
72
+ organization `acme`, and its receipts are that organization's evidence. A slug
73
+ is made of lowercase letters, digits, `.`, `_` and `-`.
74
+
75
+ ```bash
76
+ al-gov org create acme
77
+ al-gov org list
78
+ ```
79
+
80
+ ## Users and roles
81
+
82
+ | Role | Capabilities |
83
+ |---|---|
84
+ | `admin` | View and verify evidence, resolve approvals, configure, export attestations |
85
+ | `operator` | View and verify evidence, resolve approvals |
86
+ | `viewer` | View and verify evidence |
87
+
88
+ A user belongs to one organization and sees only that organization's evidence.
89
+ A fleet administrator has no organization and sees across all of them; that
90
+ scope is available to administrators only.
91
+
92
+ ```bash
93
+ al-gov user add alice@acme --org acme --role admin
94
+ al-gov user list
95
+ al-gov user revoke alice@acme
96
+ ```
97
+
98
+ A token is printed once, when the user is added. It is stored hashed and
99
+ cannot be recovered. A revoked token stops authenticating immediately,
100
+ including against a control plane that is already running.
101
+
102
+ ## Posture attestation
103
+
104
+ An attestation is a signed statement about one organization over a period:
105
+
106
+ - its posture (mode, environment, whether the mediator is enforcing, whether
107
+ the egress self-test is enforced, and the configuration hash)
108
+ - its evidence, counted by verdict, action, block reason and OWASP Agentic
109
+ risk
110
+ - the head of the receipt chain it was cut from
111
+
112
+ It is signed with the mediator's key and can be verified by anyone holding the
113
+ public key, using the standalone verifier:
114
+
115
+ ```bash
116
+ al-gov attest export acme > acme.attest.json
117
+ al-verify acme.attest.json --pubkey keys/mediator_ed25519.pub
118
+ ```
119
+
120
+ ### The evidence level is computed
121
+
122
+ The attestation carries an Agent Evidence Level. It is derived from the
123
+ evidence and can only be reduced by a failing condition, so a deployment
124
+ cannot claim a level it has not earned.
125
+
126
+ | Level | Condition |
127
+ |---|---|
128
+ | `AEL-0` | The chain does not verify. Nothing in the attestation is trusted. |
129
+ | `AEL-1` | Every decision is signed and the chain verifies from genesis. |
130
+ | `AEL-2` | AEL-1, and the mediator enforces. A deployment in `audit` mode cannot reach this level. |
131
+ | `AEL-3` | AEL-2, and the egress choke-point self-test is enforced. |
132
+
133
+ Exporting an attestation before and after a change of mode turns the change
134
+ itself into evidence.
135
+
136
+ ## Budgets and cost
137
+
138
+ Each organization can carry daily request and token budgets. A request over
139
+ budget is refused by the mediator.
140
+
141
+ `al-gov cost` reports the day's usage per virtual key, for one organization or
142
+ for the whole fleet:
143
+
144
+ ```bash
145
+ al-gov cost --org acme
146
+ al-gov cost --org acme --usd-per-mtok 3.0 # price it with a blended rate
147
+ ```
148
+
149
+ Cost is derived from recorded usage. When no rate is supplied the report gives
150
+ no dollar figure, because an unknown price is not zero.
151
+
152
+ ## The governed control plane
153
+
154
+ `al-gov serve` runs the control plane with the organization directory as its
155
+ authenticator, and serves the evidence dashboard and the governance API.
156
+
157
+ ```bash
158
+ al-gov serve --host 127.0.0.1 --port 8888
159
+ ```
160
+
161
+ Every read is scoped to the caller's organization. Asking for a receipt that
162
+ belongs to another tenant returns "not found" and never "forbidden", because
163
+ confirming that a receipt exists would itself leak information.
164
+
165
+ Bind the service to the control network only. Agents must have no route to it.
166
+
167
+ ## Where tenant isolation is enforced
168
+
169
+ Isolation is enforced in the mediator, `agentlighthouse-core`, which never
170
+ imports this package. The governance layer supplies the directory of
171
+ organizations and users, and the core applies the scope to every evidence
172
+ read. A defect in this layer can therefore narrow what a caller sees and
173
+ cannot widen it.
174
+
175
+ ## Command reference
176
+
177
+ | Command | Purpose |
178
+ |---|---|
179
+ | `al-gov org create <slug>` | Create a tenant |
180
+ | `al-gov org list` | List tenants |
181
+ | `al-gov user add <subject> --org <slug> --role <role>` | Add a user and print its token once |
182
+ | `al-gov user list` | List users, never their tokens |
183
+ | `al-gov user revoke <subject>` | Revoke a user |
184
+ | `al-gov attest export <slug>` | Export a signed posture attestation |
185
+ | `al-gov attest verify <file>` | Verify an attestation |
186
+ | `al-gov cost [--org <slug>]` | Report spend per virtual key |
187
+ | `al-gov serve` | Serve the governed control plane |
188
+
189
+ Run any command with `--help` for its options.
190
+
191
+ ## Related packages
192
+
193
+ | Package | What it is |
194
+ |---|---|
195
+ | [agentlighthouse-core](https://pypi.org/project/agentlighthouse-core/) | The mediator: proxies, scanners, policy engine, evidence ledger. |
196
+ | [agentlighthouse-verify](https://pypi.org/project/agentlighthouse-verify/) | The standalone verifier for receipts and attestations. |
197
+
198
+ ## License
199
+
200
+ MIT. See the `LICENSE` file shipped with this package.
@@ -0,0 +1,14 @@
1
+ """AgentLighthouse governance layer — org tenancy, RBAC, budgets, attestation.
2
+
3
+ MIT-licensed, like the rest of the workspace. The core never imports this
4
+ package; this package builds on the core.
5
+ """
6
+
7
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
8
+
9
+ # The version lives in pyproject.toml (scripts/bump-version.sh); read it back
10
+ # from the installed distribution so the two cannot drift.
11
+ try:
12
+ __version__ = _dist_version("agentlighthouse-governance")
13
+ except PackageNotFoundError: # running from a source tree that is not installed
14
+ __version__ = "0+unknown"
@@ -0,0 +1,111 @@
1
+ """Governed control plane: the core app + multi-org auth and governance routes.
2
+
3
+ This is the core control-plane app with two changes:
4
+
5
+ * its authenticator is the :class:`OrgStore` directory, so every request
6
+ resolves to a real user's Principal (org + role) — and core's own scoping
7
+ then confines every evidence query to that org;
8
+ * it adds the governance-only routes: ``/api/orgs``, ``/api/users``,
9
+ ``/api/attestation``, ``/api/cost``.
10
+
11
+ Core never imports this module. The isolation is enforced *below* here, so a
12
+ bug in governance can only narrow what a caller sees, never widen it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from pathlib import Path
18
+
19
+ from fastapi import FastAPI, Request
20
+ from fastapi.responses import JSONResponse
21
+
22
+ from al_core.app import bearer, create_app
23
+
24
+ from .attestation import build_attestation
25
+ from .billing import cost_report
26
+ from .tenancy import OrgStore
27
+
28
+
29
+ def create_governed_app(
30
+ config_path: str | Path | None = None,
31
+ *,
32
+ data_dir: str | Path = "data",
33
+ store_path: Path | None = None,
34
+ **overrides,
35
+ ) -> FastAPI:
36
+ data = Path(data_dir)
37
+ store = OrgStore(store_path or data / "orgs.json")
38
+ app = create_app(config_path, data_dir=data,
39
+ authenticator=store.authenticate, **overrides)
40
+ runtime = app.state.runtime
41
+ app.state.org_store = store
42
+
43
+ def _principal(request: Request):
44
+ return store.authenticate(bearer(request.headers.get("authorization")))
45
+
46
+ def _deny(p, capability: str) -> JSONResponse | None:
47
+ if p is None:
48
+ return JSONResponse({"error": "unauthorized"}, status_code=401,
49
+ headers={"WWW-Authenticate": "Bearer"})
50
+ if not p.can(capability):
51
+ return JSONResponse(
52
+ {"error": "forbidden", "detail": f"capability '{capability}' required"},
53
+ status_code=403)
54
+ return None
55
+
56
+ @app.get("/api/orgs")
57
+ def api_orgs(request: Request) -> JSONResponse:
58
+ """Orgs visible to the caller. A tenant sees only its own — the org
59
+ list names your competitors, so it is itself tenant-sensitive."""
60
+ p = _principal(request)
61
+ if (err := _deny(p, "view")) is not None:
62
+ return err
63
+ orgs = store.orgs()
64
+ if p.org is not None:
65
+ orgs = [o for o in orgs if o["org"] == p.org]
66
+ return JSONResponse({"orgs": orgs})
67
+
68
+ @app.get("/api/users")
69
+ def api_users(request: Request) -> JSONResponse:
70
+ """Users in the caller's org (fleet admin: all). Token hashes are never
71
+ returned — not even to an admin; a hash is still a credential shape."""
72
+ p = _principal(request)
73
+ if (err := _deny(p, "configure")) is not None:
74
+ return err
75
+ users = store.users(p.org)
76
+ return JSONResponse({"users": [
77
+ {"subject": u.subject, "org": u.org, "role": u.role,
78
+ "created_ts": u.created_ts} for u in users
79
+ ]})
80
+
81
+ @app.get("/api/attestation")
82
+ def api_attestation(request: Request, org: str | None = None,
83
+ since: str | None = None, until: str | None = None) -> JSONResponse:
84
+ """Signed posture attestation for the caller's org (fleet admin may name
85
+ one). Verifiable by anyone with `al-verify` — no runtime required."""
86
+ p = _principal(request)
87
+ if (err := _deny(p, "attest")) is not None:
88
+ return err
89
+ target = p.org if p.org is not None else org
90
+ if target is None:
91
+ return JSONResponse(
92
+ {"error": "org_required",
93
+ "detail": "fleet admin must name an org: ?org=<name>"},
94
+ status_code=400)
95
+ if p.org is not None and org is not None and org != p.org:
96
+ return JSONResponse({"error": "forbidden"}, status_code=403)
97
+ return JSONResponse(build_attestation(runtime, target, since=since, until=until))
98
+
99
+ @app.get("/api/cost")
100
+ def api_cost(request: Request, usd_per_mtok: float | None = None) -> JSONResponse:
101
+ """Today's spend for the caller's org (fleet admin: the whole fleet)."""
102
+ p = _principal(request)
103
+ if (err := _deny(p, "view")) is not None:
104
+ return err
105
+ return JSONResponse(cost_report(
106
+ runtime.ledger.db, runtime.vkeys, org=p.org, usd_per_mtok=usd_per_mtok))
107
+
108
+ return app
109
+
110
+
111
+ __all__ = ["create_governed_app"]
@@ -0,0 +1,129 @@
1
+ """Signed per-org posture attestation.
2
+
3
+ The artefact a design partner's auditor actually wants: a single signed
4
+ statement of what this org's mediator *was configured to do* and what it
5
+ *actually did* over a period — tied to the receipt chain it was cut from, and
6
+ verifiable with the standalone ``al-verify`` (no al-core, no governance).
7
+
8
+ It is deliberately not a summary you could fabricate: every count is derived
9
+ from the ledger, the chain head is quoted, and the whole document is signed
10
+ with the mediator key. If the ledger were edited afterwards, the chain would
11
+ fail to verify and the attestation's quoted head would no longer match.
12
+
13
+ **Evidence level** (an honest, computed ladder — never asserted):
14
+
15
+ * ``AEL-0`` — self-reported; the chain does not verify. Nothing here is trusted.
16
+ * ``AEL-1`` — every decision is signed and the chain verifies from genesis.
17
+ * ``AEL-2`` — AEL-1 **and** the plane enforces (mode is not ``audit``): the
18
+ receipts describe blocks that actually happened, not observations.
19
+ * ``AEL-3`` — AEL-2 **and** the choke-point is self-proving in production: the
20
+ L0 egress bypass self-test is enforced, so the mediator refuses to run in a
21
+ deployment it could be routed around.
22
+
23
+ A level is only ever *reduced* by a failing condition, so a misconfigured
24
+ deployment cannot claim a level it has not earned.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+ from al_core.egress import self_test_enabled
32
+ from al_core.keys import public_key_hex
33
+ from al_core.receipt import sign_receipt, utcnow_iso
34
+ from al_core.runtime import Runtime
35
+ from al_verify.verify import ATTESTATION_KIND
36
+
37
+ #: OWASP ASI risks we report coverage for (findings carry the tag).
38
+ _ASI_KEYS = [f"ASI{i:02d}" for i in range(1, 11)]
39
+
40
+
41
+ def evidence_level(*, chain_verified: bool, enforcing: bool, self_test: bool) -> str:
42
+ if not chain_verified:
43
+ return "AEL-0"
44
+ if not enforcing:
45
+ return "AEL-1"
46
+ if not self_test:
47
+ return "AEL-2"
48
+ return "AEL-3"
49
+
50
+
51
+ def build_attestation(
52
+ runtime: Runtime, org: str, *, since: str | None = None, until: str | None = None,
53
+ ) -> dict[str, Any]:
54
+ """Build and sign an org's posture attestation from the ledger + config."""
55
+ db = runtime.ledger.db
56
+ settings = runtime.settings
57
+ health = runtime.healthz()
58
+ chain = health["chain"]
59
+
60
+ # Every receipt in the period — never ``search`` (capped for the UI): a
61
+ # signed count cut short would be a signed lie.
62
+ events = 0
63
+ by_verdict: dict[str, int] = {}
64
+ by_action: dict[str, int] = {}
65
+ by_reason: dict[str, int] = {}
66
+ asi: dict[str, int] = {}
67
+ for r in db.iter_receipts(org=org, since=since, until=until):
68
+ events += 1
69
+ by_verdict[r["verdict"]] = by_verdict.get(r["verdict"], 0) + 1
70
+ by_action[r["action"]] = by_action.get(r["action"], 0) + 1
71
+ if r.get("block_reason"):
72
+ by_reason[r["block_reason"]] = by_reason.get(r["block_reason"], 0) + 1
73
+ for f in r.get("findings") or []:
74
+ tag = f.get("owasp")
75
+ if tag in _ASI_KEYS:
76
+ asi[tag] = asi.get(tag, 0) + 1
77
+
78
+ enforcing = settings.mode != "audit"
79
+ self_test = self_test_enabled(settings.egress, settings.env)
80
+ level = evidence_level(chain_verified=chain["verified"], enforcing=enforcing,
81
+ self_test=self_test)
82
+
83
+ doc: dict[str, Any] = {
84
+ "kind": ATTESTATION_KIND,
85
+ "org": org,
86
+ "issued_ts": utcnow_iso(),
87
+ "period": {"since": since, "until": until},
88
+ "posture": {
89
+ "mode": settings.mode,
90
+ "env": settings.env,
91
+ "enforcing": enforcing,
92
+ "egress_self_test": self_test,
93
+ "config_hash": runtime.config_hash,
94
+ "killswitch_engaged": runtime.killswitch.engaged(),
95
+ },
96
+ "evidence": {
97
+ "events": events,
98
+ "blocks": by_verdict.get("block", 0),
99
+ "by_verdict": dict(sorted(by_verdict.items())),
100
+ "by_action": dict(sorted(by_action.items())),
101
+ "by_block_reason": dict(sorted(by_reason.items())),
102
+ "asi_findings": dict(sorted(asi.items())),
103
+ },
104
+ "chain": {
105
+ "verified": chain["verified"],
106
+ "length": chain["length"],
107
+ "head": _chain_head(runtime),
108
+ },
109
+ "evidence_level": level,
110
+ "mediator_public_key": public_key_hex(runtime.public_key),
111
+ }
112
+ # Drop the period when unbounded so the canonical form stays minimal.
113
+ if since is None and until is None:
114
+ doc.pop("period")
115
+ return sign_receipt(doc, runtime.signing_key)
116
+
117
+
118
+ def _chain_head(runtime: Runtime) -> str | None:
119
+ """The record_hash of the ledger's newest receipt — what this attestation
120
+ was cut from. Unscoped by design: the chain is one chain, and quoting its
121
+ head is what lets an auditor tie the attestation back to the ledger."""
122
+ latest = runtime.ledger.db.latest_seq()
123
+ if latest is None:
124
+ return None
125
+ receipt = runtime.ledger.db.receipt_by_seq(latest)
126
+ return receipt.get("record_hash") if receipt else None
127
+
128
+
129
+ __all__ = ["ATTESTATION_KIND", "build_attestation", "evidence_level"]
@@ -0,0 +1,129 @@
1
+ """Per-org budgets + cost tracking.
2
+
3
+ Phase 1 gave every *virtual key* a daily request/token budget. Governance adds
4
+ the tier above it: an **org-wide** daily budget, so one runaway agent cannot
5
+ spend the whole tenant's allowance, plus a cost view an operator can bill from.
6
+
7
+ Both ride the Phase-0 quotas table (atomic check-and-increment, UTC-day
8
+ rollover) — no new storage, and the same fail-closed semantics: over budget is
9
+ a denial, never a warning.
10
+
11
+ **Cost is derived, never invented.** Receipts deliberately carry no token
12
+ counts (the evidence schema is counts-and-classes only), so spend is read from
13
+ the quotas table the reverse proxy already writes: per-virtual-key requests and
14
+ tokens for the current UTC day, attributed to an org through the key's actor.
15
+ Pricing needs a rate the operator supplies; without one the report says
16
+ ``usd: null`` rather than quietly billing zero — an unknown price is not free.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import datetime as _dt
22
+ from dataclasses import dataclass
23
+ from typing import Any, Callable
24
+
25
+ from al_core.audit.db import SqliteMirror, org_of
26
+ from al_core.gateway.decision import BlockReason
27
+ from al_core.gateway.vkeys import BudgetLedger, VirtualKeyStore
28
+
29
+
30
+ def utc_today() -> str:
31
+ return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%d")
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class OrgBudget:
36
+ org: str
37
+ max_requests_per_day: int | None = None
38
+ max_tokens_per_day: int | None = None
39
+
40
+
41
+ class OrgBudgetLedger:
42
+ """Org-scoped daily budgets on the shared quotas table.
43
+
44
+ Same contract as the per-key ``BudgetLedger`` it sits above: ``try_request``
45
+ is the atomic pre-flight gate; ``record_usage`` records post-hoc tokens
46
+ unconditionally (usage that already happened is never dropped — the *next*
47
+ pre-flight denies)."""
48
+
49
+ def __init__(self, db: SqliteMirror, budgets: dict[str, OrgBudget] | None = None,
50
+ *, today: Callable[[], str] | None = None) -> None:
51
+ self._db = db
52
+ self._budgets = budgets or {}
53
+ self._today = today or utc_today
54
+
55
+ def budget(self, org: str) -> OrgBudget | None:
56
+ return self._budgets.get(org)
57
+
58
+ def try_request(self, org: str, tokens: int = 0) -> tuple[bool, str | None]:
59
+ """Atomically charge one request (+ tokens) against the org's day.
60
+
61
+ Returns (allowed, block_reason). An org with no budget is allowed — a
62
+ budget is a limit the operator opts into, not a default deny (the tool
63
+ policy is the default-deny surface; this is denial-of-wallet control)."""
64
+ b = self._budgets.get(org)
65
+ if b is None:
66
+ return True, None
67
+ ok, _, _ = self._db.quota_try_consume(
68
+ f"org:{org}", self._today(),
69
+ count_delta=1, bytes_delta=tokens,
70
+ max_count=b.max_requests_per_day, max_bytes=b.max_tokens_per_day,
71
+ )
72
+ return (True, None) if ok else (False, BlockReason.BUDGET_EXCEEDED)
73
+
74
+ def record_usage(self, org: str, tokens: int) -> None:
75
+ """Post-hoc token accounting (streamed replies count after the fact)."""
76
+ self._db.quota_try_consume(f"org:{org}", self._today(), bytes_delta=tokens)
77
+
78
+ def usage(self, org: str) -> tuple[int, int]:
79
+ """(requests, tokens) consumed by the org in the current UTC day."""
80
+ return self._db.quota_usage(f"org:{org}", self._today())
81
+
82
+
83
+ def cost_report(
84
+ db: SqliteMirror,
85
+ vkeys: VirtualKeyStore,
86
+ *,
87
+ org: str | None = None,
88
+ usd_per_mtok: float | None = None,
89
+ ) -> dict[str, Any]:
90
+ """Today's spend for an org (or the fleet), from the quotas table.
91
+
92
+ ``usd_per_mtok`` is the operator's blended rate. Receipts carry no model
93
+ attribution (``llm_call`` targets are provider+path), so this reports a
94
+ blended figure honestly rather than fabricating a per-model split. Omit the
95
+ rate and ``usd`` is ``None``.
96
+ """
97
+ budgets = BudgetLedger(db)
98
+ keys = []
99
+ total_requests = total_tokens = 0
100
+ for key in vkeys.list():
101
+ key_org = org_of(key.actor)
102
+ if org is not None and key_org != org:
103
+ continue
104
+ requests, tokens = budgets.usage(key)
105
+ total_requests += requests
106
+ total_tokens += tokens
107
+ keys.append({
108
+ "key_id": key.key_id,
109
+ "actor": key.actor,
110
+ "org": key_org,
111
+ "requests": requests,
112
+ "tokens": tokens,
113
+ "disabled": key.disabled,
114
+ })
115
+
116
+ usd = (round(total_tokens * usd_per_mtok / 1_000_000, 6)
117
+ if usd_per_mtok is not None else None)
118
+ return {
119
+ "org": org,
120
+ "day": utc_today(),
121
+ "keys": sorted(keys, key=lambda k: -k["tokens"]),
122
+ "total_requests": total_requests,
123
+ "total_tokens": total_tokens,
124
+ "usd": usd,
125
+ "rate_usd_per_mtok": usd_per_mtok,
126
+ }
127
+
128
+
129
+ __all__ = ["OrgBudget", "OrgBudgetLedger", "cost_report", "utc_today"]
@@ -0,0 +1,200 @@
1
+ """``al-gov`` — multi-org governance CLI.
2
+
3
+ Kept out of the core ``al`` CLI on purpose: the core must never import the
4
+ governance layer. Commands: org create/list, user add/list/revoke,
5
+ attest export/verify, cost, serve.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ import typer
14
+
15
+ app = typer.Typer(
16
+ name="al-gov",
17
+ help="AgentLighthouse governance — orgs, RBAC, budgets, signed posture attestation.",
18
+ no_args_is_help=True,
19
+ add_completion=False,
20
+ )
21
+ org_app = typer.Typer(help="Manage orgs (tenants).")
22
+ app.add_typer(org_app, name="org")
23
+ user_app = typer.Typer(help="Manage users + roles (admin/operator/viewer).")
24
+ app.add_typer(user_app, name="user")
25
+ attest_app = typer.Typer(help="Signed per-org posture attestation.")
26
+ app.add_typer(attest_app, name="attest")
27
+
28
+ DEFAULT_DATA = Path("data")
29
+
30
+
31
+ def _err(msg: str) -> "typer.Exit":
32
+ typer.secho(f"error: {msg}", fg=typer.colors.RED, err=True)
33
+ return typer.Exit(1)
34
+
35
+
36
+ def _store(data_dir: Path):
37
+ from .tenancy import OrgStore
38
+
39
+ return OrgStore(data_dir / "orgs.json")
40
+
41
+
42
+ @org_app.command("create")
43
+ def org_create(
44
+ org: str = typer.Argument(..., help="org slug, e.g. acme (matches spiffe://acme/...)"),
45
+ display_name: str = typer.Option(None, "--name", help="human-readable name"),
46
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
47
+ ) -> None:
48
+ """Create a tenant. The slug must match the org in its agents' SPIFFE ids."""
49
+ try:
50
+ created = _store(data_dir).create_org(org, display_name=display_name)
51
+ except ValueError as exc:
52
+ raise _err(str(exc))
53
+ typer.secho(f"created org {created['org']}", fg=typer.colors.GREEN)
54
+
55
+
56
+ @org_app.command("list")
57
+ def org_list(data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir")) -> None:
58
+ """List tenants."""
59
+ orgs = _store(data_dir).orgs()
60
+ if not orgs:
61
+ typer.echo("(no orgs — create one with: al-gov org create <slug>)")
62
+ return
63
+ for o in orgs:
64
+ typer.echo(f"{o['org']:20} {o['display_name']:30} {o['created_ts']}")
65
+
66
+
67
+ @user_app.command("add")
68
+ def user_add(
69
+ subject: str = typer.Argument(..., help="user id, e.g. alice@acme"),
70
+ org: str = typer.Option(None, "--org", help="tenant (omit with --fleet)"),
71
+ role: str = typer.Option("viewer", "--role", help="admin | operator | viewer"),
72
+ fleet: bool = typer.Option(False, "--fleet", help="cross-org admin (no single org)"),
73
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
74
+ ) -> None:
75
+ """Add a user and print its token ONCE (stored hashed, never recoverable)."""
76
+ if fleet and org:
77
+ raise _err("--fleet is cross-org; do not also pass --org")
78
+ if not fleet and not org:
79
+ raise _err("pass --org <tenant> (or --fleet for a cross-org admin)")
80
+ try:
81
+ issued = _store(data_dir).add_user(subject, org=None if fleet else org, role=role)
82
+ except ValueError as exc:
83
+ raise _err(str(exc))
84
+ scope = "fleet (all orgs)" if fleet else f"org {org}"
85
+ typer.secho(f"created {subject} — {role} in {scope}", fg=typer.colors.GREEN)
86
+ typer.secho("token (shown once, store it now):", fg=typer.colors.YELLOW)
87
+ typer.echo(issued.token)
88
+
89
+
90
+ @user_app.command("list")
91
+ def user_list(
92
+ org: str = typer.Option(None, "--org", help="only this tenant"),
93
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
94
+ ) -> None:
95
+ """List users (never their tokens)."""
96
+ users = _store(data_dir).users(org)
97
+ if not users:
98
+ typer.echo("(no users)")
99
+ return
100
+ for u in users:
101
+ typer.echo(f"{u.subject:24} {(u.org or 'FLEET'):12} {u.role:9} {u.created_ts}")
102
+
103
+
104
+ @user_app.command("revoke")
105
+ def user_revoke(
106
+ subject: str = typer.Argument(...),
107
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
108
+ ) -> None:
109
+ """Revoke a user (its token stops authenticating immediately)."""
110
+ if not _store(data_dir).revoke(subject):
111
+ raise _err(f"no such user: {subject}")
112
+ typer.secho(f"revoked {subject}", fg=typer.colors.GREEN)
113
+
114
+
115
+ @attest_app.command("export")
116
+ def attest_export(
117
+ org: str = typer.Argument(..., help="tenant to attest"),
118
+ output: Path = typer.Option(None, "--out", "-o", help="write here (default: stdout)"),
119
+ since: str = typer.Option(None, "--since", help="ISO-8601 lower bound"),
120
+ until: str = typer.Option(None, "--until", help="ISO-8601 upper bound"),
121
+ config: Path = typer.Option(None, "--config", "-c", help="config YAML"),
122
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
123
+ ) -> None:
124
+ """Export a signed posture attestation for an org (verifiable by al-verify)."""
125
+ from al_core.runtime import Runtime
126
+
127
+ from .attestation import build_attestation
128
+
129
+ try:
130
+ runtime = Runtime(config, data_dir=data_dir)
131
+ except Exception as exc: # noqa: BLE001 — boot is fail-closed
132
+ raise _err(f"refusing to start: {exc}")
133
+ doc = build_attestation(runtime, org, since=since, until=until)
134
+ runtime.close()
135
+ blob = json.dumps(doc, indent=2, ensure_ascii=False)
136
+ if output is None:
137
+ typer.echo(blob)
138
+ return
139
+ output.write_text(blob + "\n", encoding="utf-8")
140
+ typer.secho(
141
+ f"attestation for {org} -> {output} (evidence level {doc['evidence_level']}, "
142
+ f"{doc['evidence']['events']} events)", fg=typer.colors.GREEN)
143
+
144
+
145
+ @attest_app.command("verify")
146
+ def attest_verify(
147
+ attestation: Path = typer.Argument(..., help="attestation .json"),
148
+ pubkey: Path = typer.Option(Path("keys/mediator_ed25519.pub"), "--pubkey"),
149
+ ) -> None:
150
+ """Verify an attestation with the standalone verifier (exit 1 on failure)."""
151
+ from al_verify.cli import main as verify_main
152
+
153
+ raise typer.Exit(verify_main([str(attestation), "--pubkey", str(pubkey)]))
154
+
155
+
156
+ @app.command()
157
+ def cost(
158
+ org: str = typer.Option(None, "--org", help="tenant (omit = whole fleet)"),
159
+ usd_per_mtok: float = typer.Option(None, "--usd-per-mtok", help="blended rate"),
160
+ config: Path = typer.Option(None, "--config", "-c", help="config YAML"),
161
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
162
+ ) -> None:
163
+ """Today's spend (requests + tokens) per virtual key, scoped to an org."""
164
+ from al_core.runtime import Runtime
165
+
166
+ from .billing import cost_report
167
+
168
+ try:
169
+ runtime = Runtime(config, data_dir=data_dir)
170
+ except Exception as exc: # noqa: BLE001
171
+ raise _err(f"refusing to start: {exc}")
172
+ report = cost_report(runtime.ledger.db, runtime.vkeys, org=org,
173
+ usd_per_mtok=usd_per_mtok)
174
+ runtime.close()
175
+ typer.echo(json.dumps(report, indent=2))
176
+
177
+
178
+ @app.command()
179
+ def serve(
180
+ config: Path = typer.Option(None, "--config", "-c", help="config YAML"),
181
+ host: str = typer.Option("127.0.0.1", "--host", help="bind (control-net only)"),
182
+ port: int = typer.Option(8888, "--port"),
183
+ data_dir: Path = typer.Option(DEFAULT_DATA, "--data-dir"),
184
+ ) -> None:
185
+ """Serve the governed control plane (multi-org auth + dashboard + governance API)."""
186
+ import uvicorn
187
+
188
+ from .app import create_governed_app
189
+
190
+ try:
191
+ application = create_governed_app(config, data_dir=data_dir)
192
+ except Exception as exc: # noqa: BLE001 — boot is fail-closed
193
+ raise _err(f"refusing to start: {exc}")
194
+ typer.secho(f"governed control plane on http://{host}:{port}/dashboard",
195
+ fg=typer.colors.GREEN)
196
+ uvicorn.run(application, host=host, port=port)
197
+
198
+
199
+ if __name__ == "__main__": # pragma: no cover
200
+ app()
@@ -0,0 +1,157 @@
1
+ """Org + user directory (multi-tenant RBAC).
2
+
3
+ The core plane enforces isolation; this module is the *directory* it enforces
4
+ against — orgs, their users, each user's role, and the token that authenticates
5
+ them. Tokens are stored **hashed** (SHA-256) and shown exactly once at issue,
6
+ like the Phase-1 virtual keys: a stolen store yields no usable credential.
7
+
8
+ Roles come from the core capability table (admin / operator / viewer) so the
9
+ dashboard's capability gating needs no governance-specific knowledge.
10
+
11
+ An org's users are bound to that org: authenticating returns a Principal whose
12
+ ``org`` is the user's own, and core scopes every query to it. A **fleet admin**
13
+ (``org=None``, created with ``--fleet``) is the only principal that sees across
14
+ orgs — that is a deliberate, auditable escalation, not a default.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import logging
21
+ import secrets
22
+ from dataclasses import asdict, dataclass
23
+ from pathlib import Path
24
+
25
+ from al_core.identity import require_org_slug
26
+ from al_core.jsonstore import JsonFile
27
+ from al_core.principal import CAPABILITIES, Principal
28
+ from al_core.receipt import utcnow_iso
29
+
30
+ log = logging.getLogger("al.governance.tenancy")
31
+
32
+ TOKEN_PREFIX = "alg_" # governance user token (cf. alk_ virtual keys)
33
+
34
+
35
+ def hash_token(token: str) -> str:
36
+ return "sha256:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class User:
41
+ subject: str # "alice@acme"
42
+ org: str | None # None = fleet scope (cross-org admin)
43
+ role: str # admin | operator | viewer
44
+ token_hash: str
45
+ created_ts: str
46
+
47
+ def principal(self) -> Principal:
48
+ return Principal(subject=self.subject, role=self.role, org=self.org)
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Issued:
53
+ user: User
54
+ token: str # shown once, never stored
55
+
56
+
57
+ class OrgStore:
58
+ """Orgs + users, persisted as JSON. Small by design: a directory, not a DB.
59
+
60
+ The file is re-read whenever it has changed, so a user added or revoked
61
+ with ``al-gov`` takes effect in a running control plane on its next
62
+ request."""
63
+
64
+ def __init__(self, path: Path) -> None:
65
+ self._file = JsonFile(path)
66
+ self._orgs: dict[str, dict] = {}
67
+ self._users: dict[str, User] = {}
68
+ self._refresh()
69
+
70
+ def _refresh(self) -> None:
71
+ if not self._file.changed():
72
+ return
73
+ raw = self._file.read() or {}
74
+ users = {k: User(**v) for k, v in raw.get("users", {}).items()}
75
+ self._orgs, self._users = raw.get("orgs", {}), users
76
+
77
+ def _save(self) -> None:
78
+ self._file.write({
79
+ "orgs": dict(sorted(self._orgs.items())),
80
+ "users": {k: asdict(u) for k, u in sorted(self._users.items())},
81
+ })
82
+
83
+ # -- orgs ------------------------------------------------------------------
84
+
85
+ def create_org(self, org: str, *, display_name: str | None = None) -> dict:
86
+ self._refresh()
87
+ if org in self._orgs:
88
+ raise ValueError(f"org already exists: {org}")
89
+ if org == "system":
90
+ raise ValueError("'system' is reserved (non-agent actors)")
91
+ require_org_slug(org)
92
+ self._orgs[org] = {"org": org, "display_name": display_name or org,
93
+ "created_ts": utcnow_iso()}
94
+ self._save()
95
+ return self._orgs[org]
96
+
97
+ def orgs(self) -> list[dict]:
98
+ self._refresh()
99
+ return [self._orgs[k] for k in sorted(self._orgs)]
100
+
101
+ def has_org(self, org: str) -> bool:
102
+ self._refresh()
103
+ return org in self._orgs
104
+
105
+ # -- users -----------------------------------------------------------------
106
+
107
+ def add_user(self, subject: str, *, org: str | None, role: str) -> Issued:
108
+ """Create a user and issue its token (returned once, stored hashed)."""
109
+ self._refresh()
110
+ if role not in CAPABILITIES:
111
+ raise ValueError(f"unknown role: {role} (want {', '.join(CAPABILITIES)})")
112
+ if subject in self._users:
113
+ raise ValueError(f"user already exists: {subject}")
114
+ if org is not None and org not in self._orgs:
115
+ raise ValueError(f"no such org: {org} — create it first")
116
+ if org is None and role != "admin":
117
+ raise ValueError("fleet scope (org=None) is admin-only")
118
+ token = TOKEN_PREFIX + secrets.token_urlsafe(32)
119
+ user = User(subject=subject, org=org, role=role,
120
+ token_hash=hash_token(token), created_ts=utcnow_iso())
121
+ self._users[subject] = user
122
+ self._save()
123
+ return Issued(user=user, token=token)
124
+
125
+ def users(self, org: str | None = None) -> list[User]:
126
+ self._refresh()
127
+ out = [u for u in self._users.values() if org is None or u.org == org]
128
+ return sorted(out, key=lambda u: (u.org or "", u.subject))
129
+
130
+ def revoke(self, subject: str) -> bool:
131
+ self._refresh()
132
+ if self._users.pop(subject, None) is None:
133
+ return False
134
+ self._save()
135
+ return True
136
+
137
+ # -- authentication ----------------------------------------------------------
138
+
139
+ def authenticate(self, token: str | None) -> Principal | None:
140
+ """Token -> Principal. Constant-time compare against the stored hashes;
141
+ an unknown token is indistinguishable from a wrong one."""
142
+ if not token or not token.startswith(TOKEN_PREFIX):
143
+ return None
144
+ try:
145
+ self._refresh()
146
+ except (OSError, ValueError, KeyError, TypeError):
147
+ # Stale users may include revoked ones, so do not serve them.
148
+ log.exception("org store %s is unreadable; denying", self._file.path)
149
+ return None
150
+ presented = hash_token(token)
151
+ for user in self._users.values():
152
+ if secrets.compare_digest(user.token_hash, presented):
153
+ return user.principal()
154
+ return None
155
+
156
+
157
+ __all__ = ["Issued", "OrgStore", "TOKEN_PREFIX", "User", "hash_token"]
@@ -0,0 +1,40 @@
1
+ # al-governance — multi-org governance layer (MIT). Depends on al-core; al-core
2
+ # never depends on this.
3
+ [project]
4
+ name = "agentlighthouse-governance"
5
+ version = "0.4.0"
6
+ description = "AgentLighthouse governance: org tenancy, RBAC, budgets, signed posture attestation"
7
+ authors = [{ name = "Amit Kala" }]
8
+ requires-python = ">=3.12"
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ readme = "README.md"
12
+ dependencies = [
13
+ "agentlighthouse-core",
14
+ "agentlighthouse-verify",
15
+ "cryptography>=43",
16
+ "fastapi>=0.111",
17
+ "typer>=0.12",
18
+ "uvicorn>=0.30",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/neural-nomad1709/agentlighthouse"
23
+ Repository = "https://github.com/neural-nomad1709/agentlighthouse"
24
+
25
+ [project.optional-dependencies]
26
+ postgres = ["psycopg[binary]>=3.2"]
27
+
28
+ [project.scripts]
29
+ al-gov = "al_governance.cli:app"
30
+
31
+ [tool.uv.sources]
32
+ agentlighthouse-core = { workspace = true }
33
+ agentlighthouse-verify = { workspace = true }
34
+
35
+ [build-system]
36
+ requires = ["hatchling"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["al_governance"]