khive_runtime/pack/request_identity.rs
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3
4use khive_gate::GateRef;
5use khive_storage::EventStore;
6use khive_types::Namespace;
7use serde_json::Value;
8
9use crate::error::RuntimeError;
10use crate::runtime::NamespaceToken;
11
12use super::{
13 AuditSuccessRowForcingRule, AuditSuccessRowsMode, DispatchHook, EdgeEndpointRule, EndpointKind,
14 HandlerDef, PackByIdResolver, PackRuntime, SPECIAL_RELATIONS,
15};
16
17/// Immutable registry that dispatches verb calls to registered packs.
18///
19/// Clone shares pack state and retains its runtime audit binding. Built by `VerbRegistryBuilder`.
20#[derive(Clone)]
21pub struct VerbRegistry {
22 pub(super) packs: std::sync::Arc<Vec<Box<dyn PackRuntime>>>,
23 /// Pack ownership and endpoint rules captured together at registry construction.
24 pub(super) attributed_edge_rules: Arc<Vec<(String, EdgeEndpointRule)>>,
25 pub(super) pack_versions: Arc<HashMap<String, &'static str>>,
26 /// Validated property-policy declarations captured once, before activation.
27 pub(super) note_property_policies: Arc<Vec<khive_types::NotePropertyPolicySpec>>,
28 /// Pack-level by-ID resolvers, in registration order.
29 pub(super) resolvers: std::sync::Arc<Vec<(String, Box<dyn PackByIdResolver>)>>,
30 /// Read-only KG lookup topology; never used to redirect a pack write.
31 pub(super) kg_read_resolver: Option<Arc<crate::kg_read::KgReadResolver>>,
32 pub(super) gate: GateRef,
33 pub(super) default_namespace: String,
34 /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
35 ///
36 /// On the default (no explicit `namespace=` param) dispatch path, reads fan
37 /// out over `['local'] ∪ visible_namespaces`. Writes are unaffected — they
38 /// still pin to `'local'`. An explicit `namespace=` request param is a
39 /// precise single-namespace escape and is not widened by this set.
40 pub(super) visible_namespaces: Vec<Namespace>,
41 /// Configured actor identity label (ADR-057). When `Some`, dispatch mints
42 /// tokens carrying this actor so that `comm.inbox` applies the `to_actor`
43 /// filter. When `None`, tokens carry `ActorRef::anonymous()` (party-line).
44 pub(super) actor_id: Option<String>,
45 /// Audit event sink — `None` means tracing-only (v0.2 default).
46 pub(super) event_store: Option<Arc<dyn EventStore>>,
47 /// Actual runtime clone whose ledger belongs to the configured audit sink.
48 /// Explicit, read-only and absent sinks retain no runtime binding.
49 pub(super) config_lock_runtime: Option<crate::KhiveRuntime>,
50 /// Distinguishes ordinary tracing-only construction from a sink omitted
51 /// deliberately because its configured backend is read-only.
52 pub(super) audit_store_read_only: bool,
53 /// Post-dispatch hook: `None` means no real-time observation.
54 pub(super) dispatch_hook: Option<Arc<dyn DispatchHook>>,
55 /// Names of all `Visibility::Verb` handlers across all packs, precomputed
56 /// once at `build()` time. Used only to render the unknown-verb error
57 /// message — the pack set is fixed after construction, so there is no
58 /// need to re-scan every pack's handlers on every miss.
59 pub(super) available_verbs: Arc<Vec<&'static str>>,
60 pub(super) disabled_verbs: Arc<HashSet<&'static str>>,
61 /// Static handler metadata indexed once at build time. Duplicate internal
62 /// subhandler names retain the first pack's declaration, as before.
63 pub(super) handler_by_name: Arc<HashMap<&'static str, &'static HandlerDef>>,
64 /// Verbs eligible for admission-pressure audit degradation, precomputed
65 /// once at `build()` time from registration-time pack trust plus each
66 /// handler's declared category and
67 /// [`VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS`]. See
68 /// [`VerbRegistry::admission_degrade_safe`].
69 pub(super) degrade_safe_verbs: Arc<HashSet<&'static str>>,
70 pub(super) audit_success_rows_mode: AuditSuccessRowsMode,
71 pub(super) audit_success_row_omitted_verbs: Arc<HashSet<&'static str>>,
72 pub(super) audit_success_row_sampled_verbs:
73 Arc<HashMap<&'static str, (u64, AuditSuccessRowForcingRule)>>,
74 /// Trusted canonical public handlers classified Read by the shared effects table.
75 pub(super) read_replay_safe_verbs: Arc<HashSet<&'static str>>,
76 /// Recently-referenced ring (unified-verb draft ADR, Slice 1). Daemon-warm,
77 /// actor-scoped, never persisted — see `crate::reference_ring`. Shared
78 /// across every clone of this registry via the `Arc`, so admissions made
79 /// by one dispatch are visible to the next on the same warm daemon.
80 pub(super) reference_ring: Arc<crate::reference_ring::ReferenceRing>,
81 /// ADR-133 audit-batch seam. `None` exactly when `event_store` is
82 /// `None` — no store configured means no seam to construct, and every
83 /// audit call site falls back to its pre-ADR-133 tracing-only/no-op
84 /// path.
85 pub(super) audit_batch: Option<Arc<crate::audit_batch::AuditBatch>>,
86}
87
88/// Result of an operation handled outside normal pack dispatch, paired with
89/// typed transport metadata that must survive the gate/audit boundary.
90///
91/// The canonical `result` remains the value used for audit accounting. The
92/// metadata is returned to the intercepting transport without being smuggled
93/// through a mutex side channel or folded into the verb's public result shape.
94#[derive(Debug, Clone, PartialEq)]
95pub struct InterceptedDispatchResult<M> {
96 /// Canonical verb result used for audit and resource accounting.
97 pub result: Value,
98 /// Transport-owned metadata that must accompany the canonical result.
99 pub metadata: M,
100}
101
102impl<M> InterceptedDispatchResult<M> {
103 /// Pair a canonical result with its typed transport metadata.
104 pub fn new(result: Value, metadata: M) -> Self {
105 Self { result, metadata }
106 }
107}
108
109/// Per-request identity context that overrides a [`VerbRegistry`]'s
110/// construction-baked `default_namespace` / `actor_id` / `visible_namespaces`
111/// for exactly one [`VerbRegistry::dispatch_with_identity`] call (ADR-096
112/// Fork 1 — warm-daemon per-request identity).
113///
114/// A single warm registry is built once with a baked identity, but must be
115/// able to serve requests whose caller resolved a *different* attribution
116/// identity (e.g. a different project-local `[actor]`) without a cold
117/// fallback and without mis-stamping writes under the registry's own baked
118/// actor. Supplying `Some(RequestIdentity { .. })` threads the caller's
119/// identity through token minting for that one call; the registry's fields
120/// (and every other in-flight call) are untouched. `None` is exactly
121/// [`VerbRegistry::dispatch`] — the baked scalars apply, unchanged from
122/// before this type existed.
123#[derive(Debug, Clone, Default)]
124pub struct RequestIdentity {
125 /// Storage/gate default namespace for this request (used when the verb's
126 /// own params carry no explicit `namespace` field). Overrides
127 /// `VerbRegistry::default_namespace`.
128 pub namespace: String,
129 /// Write-stamp / gate actor label for this request (ADR-057). Overrides
130 /// `VerbRegistry::actor_id`. `None` mints `ActorRef::anonymous()`, same
131 /// as an unconfigured baked `actor_id`.
132 pub actor_id: Option<String>,
133 /// Extra read-visibility namespaces for this request (ADR-007 Rev 4 Rule
134 /// 3b). Overrides `VerbRegistry::visible_namespaces`. Entries that fail
135 /// `Namespace::parse` are skipped with a `tracing::warn!` rather than
136 /// failing the whole request — a single malformed visibility entry from a
137 /// caller-supplied frame must not block dispatch.
138 pub visible_namespaces: Vec<String>,
139 /// Opaque process provenance resolved by the originating request process.
140 /// `None` means the origin did not set one; a warm daemon must not replace
141 /// it with its own process environment. This field is attribution-only and
142 /// never participates in the gate or token authority.
143 pub process_ref: Option<String>,
144 /// Caller-supplied correlation id for this request (khive#948), carried
145 /// unchanged from the daemon frame's `request_id` field. Every operation
146 /// in one batch or chain receives the same value: it is a request-group
147 /// selector, never an operation-unique id. Stamped into the audit event's
148 /// `resource.request_id` on every outcome (success, error, and denied) so
149 /// a client can join its own pre-send sample to all server-side audit rows
150 /// for that request. `None` means the caller
151 /// supplied no id (a pre-#948 client, or an internal/non-benchmark
152 /// caller) — the audit row then carries no `request_id` key at all.
153 pub request_id: Option<u64>,
154}
155
156impl RequestIdentity {
157 /// Reconstruct the effective principal and namespace scope carried by an
158 /// already-authorized token for a nested registry dispatch.
159 ///
160 /// Cross-pack calls must still pass through the registry Gate, but using
161 /// the registry's construction-baked identity would silently replace a
162 /// warm daemon request's actor and visibility (ADR-096). This projection
163 /// preserves the token's exact primary namespace, actor, and read-visible
164 /// namespaces, and the origin's process provenance rider. Nested calls
165 /// intentionally use `request_id: None` even when the token retains the
166 /// ingress id for audit rows within its originating dispatch; `process_ref` IS carried by
167 /// the token (ADR-096: an absent value stays absent, a present origin
168 /// rider survives nested dispatch without reading the daemon
169 /// environment).
170 pub fn from_token(token: &NamespaceToken) -> Self {
171 Self {
172 namespace: token.namespace().as_str().to_string(),
173 actor_id: token.actor().binding_id().map(str::to_string),
174 visible_namespaces: token
175 .visible_namespaces()
176 .iter()
177 .map(|namespace| namespace.as_str().to_string())
178 .collect(),
179 process_ref: token.process_ref().map(str::to_owned),
180 request_id: None,
181 }
182 }
183}
184
185/// A non-blank, out-of-band authenticated principal for [`VerbRegistry::dispatch_as`].
186///
187/// Embedding hosts authenticate a principal through their own channel (not the
188/// request DSL) and then need that principal to become the effective actor
189/// for one dispatch. The constructor rejects an empty or whitespace-only
190/// identifier so an authentication-integration failure (an empty subject)
191/// fails closed at construction time instead of silently resolving to the
192/// anonymous/local actor at dispatch time — see [`crate::actor_identity::resolve_actor`].
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct VerifiedActor(String);
195
196impl VerifiedActor {
197 /// Validate and wrap a verified principal identifier.
198 ///
199 /// Returns `RuntimeError::InvalidInput` when `id` is empty or contains
200 /// only whitespace.
201 pub fn new(id: impl Into<String>) -> Result<Self, RuntimeError> {
202 let id = id.into();
203 if id.trim().is_empty() {
204 return Err(RuntimeError::InvalidInput(
205 "VerifiedActor: identifier must not be empty or whitespace-only".to_string(),
206 ));
207 }
208 Ok(Self(id))
209 }
210
211 /// Borrow the validated identifier.
212 pub fn as_str(&self) -> &str {
213 &self.0
214 }
215
216 pub(super) fn into_inner(self) -> String {
217 self.0
218 }
219}
220
221/// Error returned by [`VerbRegistry::apply_schema_plans_with_map`] when two
222/// packs on the same backend declare the same auxiliary table (ADR-028 §7).
223#[derive(Debug)]
224pub struct PackSchemaCollisionError {
225 /// First pack to declare the table.
226 pub pack_a: &'static str,
227 /// Second pack that collides with `pack_a`.
228 pub pack_b: &'static str,
229 /// Table name or DDL error description.
230 pub table: String,
231}
232
233impl std::fmt::Display for PackSchemaCollisionError {
234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 if self.pack_a == self.pack_b {
236 write!(
237 f,
238 "pack schema boot failure for pack {:?}: {}",
239 self.pack_a, self.table
240 )
241 } else {
242 write!(
243 f,
244 "pack schema collision: packs {:?} and {:?} both declare table {:?} \
245 on the same backend — move one pack to a separate backend or rename the table",
246 self.pack_a, self.pack_b, self.table
247 )
248 }
249 }
250}
251
252impl std::error::Error for PackSchemaCollisionError {}
253
254/// Extract table names from every statement in a DDL entry.
255///
256/// Handles SQL trivia, SQLite identifier quoting, optional TEMP/VIRTUAL and a
257/// `main.` qualifier. Index and other non-table DDL return no table names.
258pub(super) fn extract_table_names(stmt: &str) -> Vec<String> {
259 enum SqlToken {
260 Bare(String),
261 Quoted(String),
262 Punctuation(char),
263 }
264
265 let mut tokens = Vec::new();
266 let mut chars = stmt.chars().peekable();
267 while let Some(ch) = chars.next() {
268 if ch.is_whitespace() {
269 continue;
270 }
271 if ch == '-' && chars.peek() == Some(&'-') {
272 chars.next();
273 for next in chars.by_ref() {
274 if next == '\n' {
275 break;
276 }
277 }
278 continue;
279 }
280 if ch == '/' && chars.peek() == Some(&'*') {
281 chars.next();
282 let mut previous = '\0';
283 for next in chars.by_ref() {
284 if previous == '*' && next == '/' {
285 break;
286 }
287 previous = next;
288 }
289 continue;
290 }
291 if matches!(ch, '"' | '`' | '[' | '\'') {
292 let closing = if ch == '[' { ']' } else { ch };
293 let mut token = String::new();
294 while let Some(next) = chars.next() {
295 if next == closing {
296 if chars.peek() == Some(&closing) {
297 chars.next();
298 token.push(closing);
299 } else {
300 break;
301 }
302 } else {
303 token.push(next);
304 }
305 }
306 tokens.push(SqlToken::Quoted(token));
307 continue;
308 }
309 if matches!(ch, '.' | '(' | ';') {
310 tokens.push(SqlToken::Punctuation(ch));
311 continue;
312 }
313 let mut token = ch.to_string();
314 while let Some(next) = chars.peek().copied() {
315 let begins_comment = (next == '-' && chars.clone().nth(1) == Some('-'))
316 || (next == '/' && chars.clone().nth(1) == Some('*'));
317 if next.is_whitespace()
318 || matches!(next, '.' | '(' | ';' | '"' | '`' | '[' | '\'')
319 || begins_comment
320 {
321 break;
322 }
323 token.push(next);
324 chars.next();
325 }
326 tokens.push(SqlToken::Bare(token));
327 }
328
329 tokens
330 .split(|token| matches!(token, SqlToken::Punctuation(';')))
331 .filter_map(|statement| {
332 let keyword = |index: usize, word: &str| matches!(statement.get(index), Some(SqlToken::Bare(token)) if token.eq_ignore_ascii_case(word));
333 if !keyword(0, "CREATE") {
334 return None;
335 }
336 let mut index = 1;
337 if keyword(index, "TEMP") || keyword(index, "TEMPORARY") {
338 index += 1;
339 }
340 if keyword(index, "VIRTUAL") {
341 index += 1;
342 }
343 if !keyword(index, "TABLE") {
344 return None;
345 }
346 index += 1;
347 if keyword(index, "IF") && keyword(index + 1, "NOT") && keyword(index + 2, "EXISTS") {
348 index += 3;
349 }
350 let main_qualifier = matches!(
351 statement.get(index),
352 Some(SqlToken::Bare(name) | SqlToken::Quoted(name)) if name.eq_ignore_ascii_case("main")
353 );
354 if main_qualifier
355 && matches!(statement.get(index + 1), Some(SqlToken::Punctuation('.')))
356 {
357 index += 2;
358 }
359 match statement.get(index) {
360 Some(SqlToken::Bare(name) | SqlToken::Quoted(name)) if !name.is_empty() => {
361 Some(name.to_ascii_lowercase())
362 }
363 _ => None,
364 }
365 })
366 .collect()
367}
368
369/// Render an [`EndpointKind`] as the `"<substrate>:<kind>"` label used in
370/// `link(help=true)`'s `endpoint_rules` table.
371fn endpoint_kind_label(kind: &EndpointKind) -> String {
372 match kind {
373 EndpointKind::EntityOfKind(k) => format!("entity:{k}"),
374 EndpointKind::NoteOfKind(k) => format!("note:{k}"),
375 EndpointKind::EntityOfType { kind, entity_type } => {
376 format!("entity:{kind}({entity_type})")
377 }
378 }
379}
380
381pub(crate) fn is_special_relation(relation: khive_types::EdgeRelation) -> bool {
382 SPECIAL_RELATIONS.contains(&relation)
383}
384
385/// Compose the full per-relation endpoint allowlist surfaced by
386/// `link(help=true)` (issue #964).
387///
388/// Combines the base entity-to-entity endpoint contract
389/// (`operations::base_entity_endpoint_rules`) with every loaded pack's
390/// additive `EDGE_RULES`, the unconditional `note -> note` allowance for the
391/// three special relations (`supersedes` / `supports` / `refutes` —
392/// `operations.rs`'s dedicated special-relation branch), and the
393/// `annotates` note-to-any special case — the exact same sources
394/// `valid_relations_for_entity_pair` (`khive-pack-kg`) consults when
395/// enriching a rejected `link` call, so a caller reading this table cannot
396/// diverge from what the validator itself accepts.
397///
398/// Pack `EDGE_RULES` for a special relation are deliberately excluded: the
399/// validator's special-relation branch returns before `pack_rule_allows` is
400/// ever reached (`operations.rs`), so advertising such a rule here would
401/// claim enforcement that never actually happens.
402pub(super) fn edge_endpoint_table(packs: &[Box<dyn PackRuntime>]) -> Vec<Value> {
403 let mut rows: Vec<Value> = crate::operations::base_entity_endpoint_rules()
404 .iter()
405 .map(|(src, rel, tgt)| {
406 serde_json::json!({
407 "relation": rel.as_str(),
408 "source": format!("entity:{src}"),
409 "target": format!("entity:{tgt}"),
410 })
411 })
412 .collect();
413
414 for rel in SPECIAL_RELATIONS {
415 rows.push(serde_json::json!({
416 "relation": rel.as_str(),
417 "source": "note:*",
418 "target": "note:*",
419 }));
420 }
421
422 for pack in packs.iter() {
423 for rule in pack.edge_rules().iter() {
424 if is_special_relation(rule.relation) {
425 continue;
426 }
427 rows.push(serde_json::json!({
428 "relation": rule.relation.as_str(),
429 "source": endpoint_kind_label(&rule.source),
430 "target": endpoint_kind_label(&rule.target),
431 }));
432 }
433 }
434
435 rows.push(serde_json::json!({
436 "relation": "annotates",
437 "source": "note:*",
438 "target": "any (entity, note, edge, or event)",
439 }));
440
441 rows
442}