1use std::sync::Arc;
4
5use khive_storage::Entity;
6use serde_json::Value;
7
8use super::manifest::{digest_to_hex, scoped_digest, ManifestSnapshot, RuntimeFieldScope};
9use super::outcome::{FinalizerOutcome, ManifestFault};
10use crate::secret_gate::property_context::PropertyContext;
11use crate::{EventAttribution, NamespaceToken, RuntimeError, RuntimeResult};
12
13#[cfg(test)]
14pub(crate) mod fixture;
15
16pub(crate) const EXEMPTION_STAMP: &str = "exempted:content-sha256-manifest-v1";
17
18#[derive(Debug, Clone, Copy)]
19pub(crate) enum EntityEntryPoint {
20 Create,
21 Claim,
22 Update,
23 Bulk,
24 CodeIngest,
25 CodeFindingsIngest,
26}
27
28impl EntityEntryPoint {
29 pub(crate) fn family(self, replacing: bool) -> &'static str {
30 match self {
31 Self::Update => "entity.update",
32 Self::Bulk => "entity.bulk",
33 Self::CodeIngest | Self::CodeFindingsIngest if replacing => "entity.update",
34 _ => "entity.create",
35 }
36 }
37
38 pub(crate) fn verb(self) -> &'static str {
39 match self {
40 Self::Update => "update",
41 Self::CodeIngest => "code.ingest",
42 Self::CodeFindingsIngest => "code.findings_ingest",
43 _ => "create",
44 }
45 }
46}
47
48#[derive(Debug, Clone, Copy)]
50pub enum EntityCandidateOrigin {
51 CodeIngest,
52 CodeFindingsIngest,
53}
54
55#[derive(Debug, Clone)]
58pub struct EntityCandidateContext {
59 namespace: String,
60 snapshot: Arc<ManifestSnapshot>,
61 entry: EntityEntryPoint,
62 record: String,
63}
64
65#[derive(Debug)]
67pub struct EntityCandidatePrepared {
68 context: EntityCandidateContext,
69 candidate: Entity,
70}
71
72impl EntityCandidatePrepared {
73 pub fn entity(&self) -> &Entity {
74 &self.candidate
75 }
76
77 pub(crate) fn admit(self, token: &NamespaceToken) -> RuntimeResult<EntityAdmission> {
78 if token.namespace().as_str() != self.context.namespace {
79 return Err(RuntimeError::InvalidInput(
80 "direct-ingest candidate namespace differs from its authorization token".into(),
81 ));
82 }
83 admit(self.context, token, self.candidate)
84 }
85}
86
87impl EntityCandidateContext {
88 pub fn new(namespace: &str, origin: EntityCandidateOrigin) -> Self {
89 Self::capture(
90 namespace,
91 match origin {
92 EntityCandidateOrigin::CodeIngest => EntityEntryPoint::CodeIngest,
93 EntityCandidateOrigin::CodeFindingsIngest => EntityEntryPoint::CodeFindingsIngest,
94 },
95 )
96 }
97
98 fn capture(namespace: &str, entry: EntityEntryPoint) -> Self {
99 #[cfg(test)]
100 let snapshot = fixture::snapshot(namespace);
101 #[cfg(not(test))]
102 let snapshot = ManifestSnapshot::empty();
103 Self {
104 namespace: namespace.into(),
105 snapshot,
106 entry,
107 record: "entity".into(),
108 }
109 }
110
111 pub fn check_name_description(&self, value: &str) -> RuntimeResult<()> {
112 self.check_value(RuntimeFieldScope::NameDescription, value)
113 }
114
115 pub fn check_properties(&self, properties: Option<&Value>) -> RuntimeResult<()> {
116 crate::secret_gate::reject_reserved_secret_gate_property(properties)?;
117 if let Some(value) = properties {
118 let mut found = None;
119 scan_properties(self, value, &mut found)?;
120 }
121 Ok(())
122 }
123
124 pub fn check_tags(&self, tags: &[String]) -> RuntimeResult<()> {
125 for tag in tags {
126 self.check_value(RuntimeFieldScope::Tags, tag)?;
127 }
128 Ok(())
129 }
130
131 pub fn prepare(self, candidate: Entity) -> RuntimeResult<EntityCandidatePrepared> {
133 if candidate.namespace != self.namespace {
134 return Err(RuntimeError::InvalidInput(
135 "direct-ingest candidate namespace changed after preflight".into(),
136 ));
137 }
138 let matched = scan_candidate(&self, &candidate)?;
139 if matched.is_some() && candidate.content_ref.is_some() {
142 return Err(RuntimeError::InvalidInput(
143 "manifest direct-ingest candidates must not carry content_ref; use the attachment-aware entity constructor".into(),
144 ));
145 }
146 Ok(EntityCandidatePrepared {
147 context: self,
148 candidate,
149 })
150 }
151
152 fn check_value(&self, scope: RuntimeFieldScope, value: &str) -> RuntimeResult<()> {
153 if self.snapshot.lookup(scope, value).is_some() {
154 Ok(())
155 } else {
156 crate::secret_gate::check(value)
157 }
158 }
159}
160
161pub(crate) enum EntityAdmission {
162 Legacy(Entity),
163 Exempt(PreparedEntityExemption),
164}
165
166pub(crate) struct OrdinaryEntityUpdateContext(EntityCandidateContext);
169
170impl OrdinaryEntityUpdateContext {
171 pub(crate) fn capture(token: &NamespaceToken) -> Self {
172 Self(EntityCandidateContext::capture(
173 token.namespace().as_str(),
174 EntityEntryPoint::Update,
175 ))
176 }
177
178 pub(crate) fn check_patch(
179 &self,
180 name: Option<&str>,
181 description: Option<&str>,
182 properties: Option<&Value>,
183 tags: Option<&[String]>,
184 ) -> RuntimeResult<()> {
185 crate::secret_gate::reject_reserved_secret_gate_property(properties)?;
186 if let Some(name) = name {
187 crate::secret_gate::locate(self.0.check_name_description(name), "entity", "name")?;
188 }
189 if let Some(description) = description {
190 crate::secret_gate::locate(
191 self.0.check_name_description(description),
192 "entity",
193 "description",
194 )?;
195 }
196 if let Some(properties) = properties {
197 crate::secret_gate::locate(
198 self.0.check_properties(Some(properties)),
199 "entity",
200 "properties",
201 )?;
202 }
203 if let Some(tags) = tags {
204 crate::secret_gate::locate(self.0.check_tags(tags), "entity", "tags")?;
205 }
206 Ok(())
207 }
208
209 pub(crate) fn admit(
210 self,
211 token: &NamespaceToken,
212 candidate: Entity,
213 ) -> RuntimeResult<EntityAdmission> {
214 if self.0.snapshot.is_empty() {
215 crate::secret_gate::reject_reserved_secret_gate_property(
216 candidate.properties.as_ref(),
217 )?;
218 reject_injected_manifest_fault(&candidate.namespace)?;
219 Ok(EntityAdmission::Legacy(candidate))
220 } else {
221 admit(self.0, token, candidate)
222 }
223 }
224}
225
226#[derive(Debug, Clone)]
227pub(crate) struct PreparedEntityExemption {
228 pub(super) entity: Entity,
229 pub(super) snapshot: Arc<ManifestSnapshot>,
230 pub(super) entry: EntityEntryPoint,
231 pub(super) attribution: EventAttribution,
232 pub(super) digest_sha256: String,
233 pub(super) field_scope: &'static str,
234 pub(super) overridden_detector: String,
235}
236
237impl PreparedEntityExemption {
238 pub(crate) fn entity(&self) -> &Entity {
241 &self.entity
242 }
243}
244
245pub(crate) fn prepare_entity_admission(
246 token: &NamespaceToken,
247 entry: EntityEntryPoint,
248 candidate: Entity,
249) -> RuntimeResult<EntityAdmission> {
250 prepare_entity_admission_at(token, entry, candidate, "entity")
251}
252
253pub(crate) fn prepare_entity_admission_at(
254 token: &NamespaceToken,
255 entry: EntityEntryPoint,
256 candidate: Entity,
257 record: &str,
258) -> RuntimeResult<EntityAdmission> {
259 let mut context = EntityCandidateContext::capture(&candidate.namespace, entry);
260 context.record = record.into();
261 admit(context, token, candidate)
262}
263
264fn admit(
265 context: EntityCandidateContext,
266 token: &NamespaceToken,
267 mut candidate: Entity,
268) -> RuntimeResult<EntityAdmission> {
269 reject_injected_manifest_fault(&candidate.namespace)?;
270 let matched = scan_candidate(&context, &candidate)?;
271 let Some((scope, digest_sha256, overridden_detector)) = matched else {
272 return Ok(EntityAdmission::Legacy(candidate));
273 };
274 let properties = candidate
275 .properties
276 .get_or_insert_with(|| serde_json::json!({}));
277 let Some(properties) = properties.as_object_mut() else {
278 return Err(RuntimeError::InvalidInput(
279 "manifest-exempt entity properties must be an object".into(),
280 ));
281 };
282 properties.insert(
283 crate::secret_gate::RESERVED_SECRET_GATE_KEY.into(),
284 EXEMPTION_STAMP.into(),
285 );
286 let record_token = token.with_namespace(
287 crate::Namespace::parse(&candidate.namespace)
288 .map_err(|_| RuntimeError::InvalidInput("invalid entity namespace".into()))?,
289 );
290 Ok(EntityAdmission::Exempt(PreparedEntityExemption {
291 entity: candidate,
292 snapshot: context.snapshot,
293 entry: context.entry,
294 attribution: EventAttribution::from_token(&record_token),
295 digest_sha256,
296 field_scope: match scope {
297 RuntimeFieldScope::NameDescription => "name-description",
298 RuntimeFieldScope::JsonProperties => "json-properties",
299 RuntimeFieldScope::JsonPropertiesContextV2 => "json-properties-context-v2",
300 RuntimeFieldScope::Tags => "tags",
301 RuntimeFieldScope::RecordContent => "record-content",
302 RuntimeFieldScope::CodeSource => "code-source",
303 },
304 overridden_detector,
305 }))
306}
307
308fn reject_injected_manifest_fault(namespace: &str) -> RuntimeResult<()> {
309 if let Some(fault) = super::faults::consume_manifest_invalid(namespace) {
310 observe(namespace, FinalizerOutcome::ManifestInvalid(fault));
311 return Err(RuntimeError::InvalidInput(
312 "secret-gate manifest invalid".into(),
313 ));
314 }
315 Ok(())
316}
317
318type CandidateMatch = (RuntimeFieldScope, String, String);
319
320fn scan_candidate(
321 context: &EntityCandidateContext,
322 entity: &Entity,
323) -> RuntimeResult<Option<CandidateMatch>> {
324 crate::secret_gate::reject_reserved_secret_gate_property(entity.properties.as_ref())?;
325 if context.snapshot.is_empty() {
326 crate::secret_gate::check_at(&entity.name, &context.record, "name")?;
327 if let Some(description) = &entity.description {
328 crate::secret_gate::check_at(description, &context.record, "description")?;
329 }
330 if let Some(properties) = &entity.properties {
331 crate::secret_gate::check_json_at(properties, &context.record, "properties")?;
332 }
333 crate::secret_gate::check_tags_at(&entity.tags, &context.record, "tags")?;
334 return Ok(None);
335 }
336 let mut found = None;
337 scan_scalar(
338 context,
339 RuntimeFieldScope::NameDescription,
340 &entity.name,
341 "name",
342 &mut found,
343 )?;
344 if let Some(description) = &entity.description {
345 scan_scalar(
346 context,
347 RuntimeFieldScope::NameDescription,
348 description,
349 "description",
350 &mut found,
351 )?;
352 }
353 if let Some(properties) = &entity.properties {
354 scan_properties(context, properties, &mut found)?;
355 }
356 for tag in &entity.tags {
357 scan_scalar(context, RuntimeFieldScope::Tags, tag, "tags", &mut found)?;
358 }
359 Ok(found)
360}
361
362fn add_match(
363 context: &EntityCandidateContext,
364 found: &mut Option<CandidateMatch>,
365 scope: RuntimeFieldScope,
366 digest: String,
367 detector: &str,
368) -> RuntimeResult<()> {
369 if found
370 .as_ref()
371 .is_some_and(|(old_scope, old_digest, _)| *old_scope != scope || *old_digest != digest)
372 {
373 observe(
374 &context.namespace,
375 FinalizerOutcome::ManifestInvalid(ManifestFault::MultipleMatches),
376 );
377 return Err(RuntimeError::InvalidInput(
378 "secret-gate manifest has multiple candidate matches".into(),
379 ));
380 }
381 *found = Some((scope, digest, detector.into()));
382 Ok(())
383}
384
385fn scan_scalar(
386 context: &EntityCandidateContext,
387 scope: RuntimeFieldScope,
388 value: &str,
389 field: &str,
390 found: &mut Option<CandidateMatch>,
391) -> RuntimeResult<()> {
392 if let Some(meta) = context.snapshot.lookup(scope, value) {
393 add_match(
394 context,
395 found,
396 scope,
397 digest_to_hex(&scoped_digest(scope, value)),
398 &meta.overridden_detector,
399 )
400 } else {
401 crate::secret_gate::check_at(value, &context.record, field)
402 }
403}
404
405fn scan_properties(
406 context: &EntityCandidateContext,
407 properties: &Value,
408 found: &mut Option<CandidateMatch>,
409) -> RuntimeResult<()> {
410 let properties = PropertyContext::new(properties)?;
411 for scanned in properties.scan_atoms()? {
412 let scanned = scanned?;
413 if let Some(meta) = context.snapshot.lookup_property(scanned.atom) {
414 add_match(
415 context,
416 found,
417 RuntimeFieldScope::JsonPropertiesContextV2,
418 digest_to_hex(scanned.atom.digest()),
419 &meta.overridden_detector,
420 )?;
421 } else if let Some(matched) = scanned.matches.into_iter().next() {
422 return crate::secret_gate::locate(
423 Err(RuntimeError::SecretDetected(matched)),
424 &context.record,
425 "properties",
426 );
427 }
428 }
429 Ok(())
430}
431
432pub(super) fn observe(namespace: &str, outcome: FinalizerOutcome) {
433 #[cfg(test)]
434 fixture::record_outcome(namespace, outcome);
435 #[cfg(not(test))]
436 let _ = (namespace, outcome);
437}