1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0
//! Shared admin-role gate for HTTP handlers (v0.7.0 SHIP cluster
//! #946 / #957 / #960 / #961, 2026-05-20).
//!
//! Several v0.7.0 HTTP endpoints unavoidably return corpus-scale
//! metadata that crosses tenant boundaries — operator-facing exports,
//! agent enumeration, aggregate per-namespace stats, full-quota
//! tables. Pre-cluster, those endpoints landed open by default
//! because:
//!
//! 1. The legacy `api_key_auth` middleware passes through when the
//! operator hasn't configured an `api_key` (the default).
//! 2. No further role-check distinguished "an authenticated caller"
//! from "an authenticated *admin* caller".
//!
//! Either gap on its own is enough to leak the deployment: an HTTP
//! caller on the default install can dump every memory across every
//! owner (`GET /api/v1/export`), enumerate every registered agent
//! (`GET /api/v1/agents`), or read corpus-scale stats
//! (`GET /api/v1/stats`).
//!
//! This module exposes the canonical role-gate helpers every admin
//! handler in the cluster shares:
//!
//! - [`is_admin_caller`] — pure predicate. Reads the
//! `AppState.admin_agent_ids` allowlist and returns `true` iff the
//! resolved caller matches an entry.
//! - [`require_admin`] — guard that resolves the caller from the
//! request headers, audits the decision via the existing
//! forensic-chain sink, and returns either the validated caller
//! string or a sanitised `403 Forbidden` response ready to be
//! short-circuited from the handler.
//!
//! ## Safe-by-default posture
//!
//! When `[admin].agent_ids` is unset or empty (the v0.7.0 default),
//! the allowlist is empty and every admin-class endpoint returns
//! 403 to every caller. Operators MUST opt callers in via
//! `[admin] agent_ids = [...]` in `config.toml`. This is the same
//! `pm-v3` safe-by-default posture the SAL `bypass_visibility` flag
//! uses (see `src/store/mod.rs` `CallerContext::for_admin`).
//!
//! ## Audit chain
//!
//! Every role-gate decision (allow or deny) emits a
//! `governance::audit::record_decision` entry under the
//! `admin_role` action namespace so the forensic chain captures
//! who attempted what, when, and whether they were authorised.
//! The audit fire happens BEFORE the handler observes the body so
//! the chain entry lands even if the handler errors downstream.
use Json;
use ;
use ;
use json;
use AppState;
/// #1570 (H6) — operator escape hatch: when truthy (`1` / `true`), the
/// admin-role gate reverts to the legacy posture where a bare
/// `X-Agent-Id` header naming an allowlisted admin id mints the admin
/// role even on a deployment with NO request authentication (no
/// `api_key` configured). Default OFF = secure: on an unauthenticated
/// deployment the self-asserted header alone can never grant admin.
/// Mirrors the #1455 `AI_MEMORY_GOVERNANCE_FAIL_OPEN_ON_ERROR`
/// fail-closed-with-explicit-opt-out convention.
pub const ENV_ADMIN_HEADER_TRUST: &str = "AI_MEMORY_ADMIN_HEADER_TRUST";
/// #1570 — `true` when the operator explicitly opted into the legacy
/// trust-the-header posture via [`ENV_ADMIN_HEADER_TRUST`].
/// #1570 — process-wide marker: `true` when the running daemon has
/// request authentication configured (an `api_key`, enforced by the
/// `api_key_auth` middleware on every non-exempt route). Set once by
/// `bootstrap_serve`; defaults to `false` so embeddings that never ran
/// the daemon bootstrap (and the unauthenticated default install) stay
/// on the secure-deny side. A request that reached an admin handler on
/// a `true` deployment has, by middleware construction, presented the
/// key — so the `X-Agent-Id` role claim is at least bound to a caller
/// holding the transport credential. (#626 request-level attested
/// identity does not exist on the HTTP read surface at v0.7.0; when it
/// lands it becomes an additional accepted authn source here.)
static REQUEST_AUTHN_CONFIGURED: AtomicBool =
new;
/// #1570 — record at boot whether request authentication (`api_key`)
/// is configured. Called by `bootstrap_serve`; test fixtures that
/// model an authenticated deployment call it with `true`.
/// Pure predicate — `true` iff `caller` appears in `state`'s
/// admin-agent allowlist.
///
/// The allowlist is loaded once at daemon boot from
/// `[admin] agent_ids = [...]` in `config.toml`; entries are
/// validated against [`crate::validate::validate_agent_id`] and any
/// that fail are dropped with a `warn` log so a single typo cannot
/// lock the operator out. See [`crate::config::AdminConfig`].
///
/// Returns `false` when:
/// - the allowlist is empty (the v0.7.0 default — no admin caller
/// is configured),
/// - `caller` is an empty string,
/// - `caller` does not match any entry verbatim (no glob/prefix
/// support today — planned under #961).
/// #1582 (SEC, HIGH) — authn-gated companion to [`is_admin_caller`].
///
/// `is_admin_caller` is a PURE allowlist match: it answers "is this
/// name configured as an admin?" and nothing more. On its own it is
/// unsafe to use as a privilege grant on a deployment with NO request
/// authentication, because the `X-Agent-Id` header that produced
/// `caller` is self-asserted (no cryptographic binding exists for it
/// in v0.7.0) — any wire caller could type a configured admin id into
/// the header and mint admin.
///
/// This predicate adds the SAME #1570 (H6) gate [`require_admin`]
/// applies (`admin_role.rs` line ~246): the allowlisted name is
/// honored only when (a) the daemon has an `api_key` configured — the
/// middleware then guarantees every request reaching the handler
/// presented the transport credential — or (b) the operator explicitly
/// opted into the legacy header-trust posture via
/// [`ENV_ADMIN_HEADER_TRUST`]. Default = deny (fail closed).
///
/// Read handlers that OR an admin flag past the per-row
/// [`crate::visibility::is_visible_to_caller`] scope=private filter
/// MUST use this predicate, not the bare [`is_admin_caller`] — else a
/// self-asserted `X-Agent-Id` on a keyless deployment bypasses
/// cross-tenant private-row visibility (the #1582 finding).
/// Resolve the caller from `headers`, check it against the admin
/// allowlist, and either return the validated caller string OR a
/// pre-built `403 Forbidden` response the handler should
/// short-circuit on.
///
/// **Wire shape on rejection.** `403 Forbidden` with body
/// `{"error": "admin role required"}`. Intentionally generic — the
/// rejection does NOT leak whether the allowlist is empty vs. the
/// caller is just not in it, so a non-admin caller cannot probe the
/// `[admin].agent_ids` configuration. Matches the posture
/// `api_key_auth` uses on its own rejection.
///
/// **Audit.** Both the allow and the deny path emit a
/// [`crate::governance::audit::record_decision`] entry under
/// `action = "admin_role"` so the forensic chain captures every
/// attempt regardless of outcome. The audit fire happens BEFORE
/// any handler-specific work so the chain entry lands even if the
/// handler later errors. Action body carries `endpoint` so
/// operators can correlate which admin surface was probed.
///
/// # Errors
///
/// Returns `Err(Response)` when the caller fails the admin check;
/// the response is a ready-to-return 403 the handler can propagate
/// directly via `?` or `return`. Returns `Ok(caller)` when the
/// caller is admitted; the returned string is the resolved caller
/// id the handler can use for downstream calls + auditing.