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