1pub mod capture;
19pub mod carrier;
20mod clean;
21pub(crate) mod cross_line;
22mod detectors;
23pub mod egress;
24pub mod hud;
25mod notes;
26pub mod origin;
27pub mod provider;
28pub mod receipt_store;
29pub mod recovery;
30pub(crate) mod semantic;
31pub mod semantic_deferred;
32pub mod stored;
33pub mod stores;
34pub mod tool_output;
35pub mod withheld;
36
37use std::path::Path;
38
39use lean_ctx_protocol::Sha256Digest;
40use lean_ctx_protocol::context_gateway::{
41 ClassificationV1, ContextDecisionV1, ContextDispositionV1, CoverageKindV1,
42 DestinationConstraintV1, DestinationLocalityV1, DestinationV1, DetectorSignalV1, GatewayModeV1,
43 ReasonCodeV1, TransformationKindV1, TrustLevelV1,
44};
45use serde::{Deserialize, Serialize};
46use sha2::{Digest, Sha256};
47
48use crate::core::config::SecretDetectionConfig;
49use crate::core::input_filters::FilterAction;
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(default)]
54pub struct ContextGatewayConfig {
55 pub enabled: bool,
57 pub mode: GatewayModeV1,
58 pub secrets: FilterAction,
60 pub pii: FilterAction,
62 pub injection: FilterAction,
64 pub classification: FilterAction,
66 pub max_inspected_bytes: usize,
70 pub detector_timeout_ms: u64,
72 pub destination_constraints: Vec<DestinationConstraintV1>,
75 pub allowed_destinations: Vec<DestinationV1>,
80 pub hud: hud::HudPlacement,
82}
83
84pub const DEFAULT_MAX_INSPECTED_BYTES: usize = 8 * 1024 * 1024;
86pub const DEFAULT_DETECTOR_TIMEOUT_MS: u64 = 2_000;
87
88impl Default for ContextGatewayConfig {
89 fn default() -> Self {
90 Self {
91 enabled: true,
92 mode: GatewayModeV1::Developer,
93 secrets: FilterAction::Redact,
94 pii: FilterAction::Redact,
95 injection: FilterAction::Warn,
96 classification: FilterAction::Warn,
97 max_inspected_bytes: DEFAULT_MAX_INSPECTED_BYTES,
98 detector_timeout_ms: DEFAULT_DETECTOR_TIMEOUT_MS,
99 destination_constraints: Vec::new(),
100 allowed_destinations: Vec::new(),
101 hud: hud::HudPlacement::Auto,
102 }
103 }
104}
105
106impl ContextGatewayConfig {
107 #[must_use]
114 pub fn enabled_effective(&self) -> bool {
115 self.enabled_under(EnvSwitch::read())
116 }
117
118 #[must_use]
122 pub(crate) fn enabled_under(&self, env: EnvSwitch) -> bool {
123 match self.kill_switch_under(env) {
124 KillSwitch::Unset | KillSwitch::Ignored => self.enabled,
125 KillSwitch::ForcedOn => true,
126 KillSwitch::Honoured => false,
127 }
128 }
129
130 #[must_use]
134 pub fn kill_switch(&self) -> KillSwitch {
135 self.kill_switch_under(EnvSwitch::read())
136 }
137
138 fn kill_switch_under(&self, env: EnvSwitch) -> KillSwitch {
139 match env {
140 EnvSwitch::Unset => return KillSwitch::Unset,
141 EnvSwitch::On => return KillSwitch::ForcedOn,
142 EnvSwitch::Off => {}
143 }
144 if self.mode == GatewayModeV1::Developer {
145 KillSwitch::Honoured
146 } else {
147 static REPORTED: std::sync::Once = std::sync::Once::new();
148 REPORTED.call_once(|| {
149 tracing::warn!(
150 "LEAN_CTX_CONTEXT_GATEWAY=off ignored: the context gateway runs in {:?} mode",
151 self.mode
152 );
153 });
154 KillSwitch::Ignored
155 }
156 }
157
158 #[must_use]
161 pub(crate) fn has_destination_policy(&self) -> bool {
162 !self.destination_constraints.is_empty() || !self.allowed_destinations.is_empty()
163 }
164
165 #[must_use]
167 pub(crate) fn allows_destination(&self, actual: &DestinationV1) -> bool {
168 if actual.locality == DestinationLocalityV1::Unknown
169 || !actual.satisfies_all(&self.destination_constraints)
170 {
171 return false;
172 }
173 self.allowed_destinations.is_empty()
174 || self.allowed_destinations.iter().any(|expected| {
175 expected.locality != DestinationLocalityV1::Unknown
176 && expected.provider == actual.provider
177 && expected.locality == actual.locality
178 && expected.organization_managed == actual.organization_managed
179 && expected
180 .model
181 .as_ref()
182 .is_none_or(|reference| actual.model.as_ref() == Some(reference))
183 && expected
184 .account_ref
185 .as_ref()
186 .is_none_or(|reference| actual.account_ref.as_ref() == Some(reference))
187 && expected
188 .region
189 .as_ref()
190 .is_none_or(|reference| actual.region.as_ref() == Some(reference))
191 })
192 }
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub(crate) enum EnvSwitch {
199 Unset,
200 Off,
202 On,
204}
205
206impl EnvSwitch {
207 pub(crate) fn read() -> Self {
209 match std::env::var("LEAN_CTX_CONTEXT_GATEWAY") {
210 Err(_) => Self::Unset,
211 Ok(value) if matches!(value.trim(), "0" | "false" | "off") => Self::Off,
212 Ok(_) => Self::On,
213 }
214 }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum KillSwitch {
220 Unset,
221 ForcedOn,
223 Honoured,
225 Ignored,
227}
228
229#[derive(Debug, Clone)]
231pub struct AdmissionPolicy {
232 pub gateway: ContextGatewayConfig,
233 pub secret_patterns: SecretDetectionConfig,
236 pub(crate) semantic: Option<semantic::SemanticDetector>,
238 load_failure: Option<crate::core::config::ConfigLoadFailure>,
243 env_switch: EnvSwitch,
245}
246
247impl AdmissionPolicy {
248 #[must_use]
252 pub fn from_config(config: &crate::core::config::Config) -> Self {
253 Self {
254 gateway: config.context_gateway.clone(),
255 secret_patterns: config.secret_detection.clone(),
256 semantic: semantic::SemanticDetector::for_snapshot(config),
257 load_failure: config.load_failure,
258 env_switch: EnvSwitch::read(),
259 }
260 }
261
262 #[must_use]
264 pub fn builtin(gateway: ContextGatewayConfig, secret_patterns: SecretDetectionConfig) -> Self {
265 Self {
266 gateway,
267 secret_patterns,
268 semantic: None,
269 load_failure: None,
270 env_switch: EnvSwitch::read(),
271 }
272 }
273
274 #[must_use]
277 pub fn config_unloadable(&self) -> bool {
278 self.load_failure.is_some()
279 }
280
281 pub(crate) fn config_refusal_codes(&self) -> Option<[&'static str; 2]> {
285 self.load_failure
286 .map(|failure| ["gateway.config_unloadable", failure.code()])
287 }
288
289 #[must_use]
293 pub fn enabled_effective(&self) -> bool {
294 self.config_unloadable() || self.gateway_switch()
295 }
296
297 fn gateway_switch(&self) -> bool {
303 self.gateway.enabled_under(self.env_switch)
304 }
305
306 fn secrets_action(&self) -> FilterAction {
307 if self.secret_patterns.enabled {
308 self.gateway.secrets
309 } else {
310 FilterAction::Off
311 }
312 }
313
314 fn actions(&self) -> detectors::Actions {
315 detectors::Actions {
316 secrets: self.secrets_action(),
317 pii: self.gateway.pii,
318 injection: self.gateway.injection,
319 classification: self.gateway.classification,
320 }
321 }
322
323 fn budget(&self) -> detectors::Budget {
324 detectors::Budget {
325 max_bytes: self.gateway.max_inspected_bytes,
326 deadline: std::time::Duration::from_millis(self.gateway.detector_timeout_ms),
327 }
328 }
329
330 fn fingerprint(&self) -> Vec<u8> {
334 let mut value = serde_json::json!({
335 "gateway": &self.gateway,
336 "secret_patterns": &self.secret_patterns,
337 "semantic": self
340 .semantic
341 .as_ref()
342 .map_or(serde_json::Value::Bool(false), semantic::SemanticDetector::identity),
343 });
344 if let Some(failure) = self.load_failure
347 && let Some(map) = value.as_object_mut()
348 {
349 map.insert("config_unloadable".to_owned(), failure.code().into());
350 }
351 let effective = self.enabled_effective();
357 if effective != self.gateway.enabled
358 && let Some(map) = value.as_object_mut()
359 {
360 map.insert("enabled_effective".to_owned(), effective.into());
361 }
362 serde_json::to_vec(&value).unwrap_or_default()
363 }
364
365 fn detectors_mandatory(&self) -> bool {
368 self.gateway.mode != GatewayModeV1::Developer
369 }
370}
371
372#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
374pub struct AdmissionCounts {
375 pub secrets: u32,
376 pub pii: u32,
377 pub injection: u32,
380 pub injection_patterns: u8,
383 pub markings: u32,
384 pub incomplete: u32,
386 pub semantic: u32,
388}
389
390#[derive(Debug, Clone)]
392pub struct Admission {
393 pub text: Option<String>,
395 pub classification: ClassificationV1,
396 pub trust: TrustLevelV1,
397 pub decision: ContextDecisionV1,
398 pub counts: AdmissionCounts,
399}
400
401impl Admission {
402 #[must_use]
403 pub fn disposition(&self) -> ContextDispositionV1 {
404 self.decision.disposition
405 }
406
407 #[must_use]
410 pub fn storable(&self) -> bool {
411 self.text.is_some() && self.classification < ClassificationV1::Restricted
412 }
413
414 #[must_use]
417 pub fn hud_line(&self) -> Option<String> {
418 self.hud_line_placed(true)
419 }
420
421 #[must_use]
428 pub fn hud_line_placed(&self, redaction_counts: bool) -> Option<String> {
429 render_hud(
430 self.counts,
431 &self.decision,
432 self.text.is_none(),
433 redaction_counts,
434 )
435 }
436}
437
438fn render_hud(
440 c: AdmissionCounts,
441 decision: &ContextDecisionV1,
442 withheld: bool,
443 redaction_counts: bool,
444) -> Option<String> {
445 let mut parts = Vec::new();
446 let redacted = decision.disposition == ContextDispositionV1::AllowRedacted;
447 let verb = if redacted { "redacted" } else { "detected" };
448 let show_values = !redacted || redaction_counts;
449 if c.secrets > 0 && show_values {
450 parts.push(format!("{} secret(s) {verb}", c.secrets));
451 }
452 if c.pii > 0 && show_values {
453 parts.push(format!("{} PII value(s) {verb}", c.pii));
454 }
455 if c.injection > 0 {
456 parts.push(format!("{} prompt-injection signal(s)", c.injection));
457 }
458 if c.markings > 0 {
459 parts.push(format!("{} classification marking(s)", c.markings));
460 }
461 let codes = || decision.reason_codes.iter().map(ReasonCodeV1::as_str);
462 if c.incomplete > 0 {
463 let reasons: Vec<&str> = codes()
464 .filter(|code| code.starts_with("coverage.") || code.starts_with("detector."))
465 .collect();
466 parts.push(format!("not fully inspected ({})", reasons.join(", ")));
467 }
468 if c.semantic > 0 {
469 parts.push(format!("{} semantic finding(s)", c.semantic));
470 }
471 let semantic_gaps: Vec<&str> = codes()
472 .filter(|code| {
473 matches!(*code, "semantic.partial" | "semantic.unavailable")
474 || (code.starts_with("semantic.") && code.ends_with(".not_inspected"))
475 })
476 .collect();
477 if !semantic_gaps.is_empty() {
478 parts.push(format!(
479 "semantic check incomplete ({})",
480 semantic_gaps.join(", ")
481 ));
482 }
483 if withheld {
484 let reasons: Vec<&str> = codes().collect();
485 return Some(format!(
486 "[lean-ctx gateway: content withheld — {}]",
487 reasons.join(", ")
488 ));
489 }
490 (!parts.is_empty()).then(|| format!("[lean-ctx gateway: {}]", parts.join(" · ")))
491}
492
493#[must_use]
503pub fn admit(
504 text: &str,
505 path: Option<&Path>,
506 class: &origin::SourceClass,
507 policy: &AdmissionPolicy,
508) -> Admission {
509 capture::note_origin(class);
510 let floor = class.origin_floor();
511 let object = content_digest(text);
512 let gateway = &policy.gateway;
513 if let Some(codes) = policy.config_refusal_codes() {
514 return Admission {
518 text: None,
519 classification: gateway.mode.unclassified(),
520 trust: TrustLevelV1::Unknown,
521 decision: ContextDecisionV1 {
522 object,
523 disposition: ContextDispositionV1::Deny,
524 reason_codes: codes.iter().map(|code| reason(code)).collect(),
525 signals: Vec::new(),
526 required_transformations: Vec::new(),
527 },
528 counts: AdmissionCounts::default(),
529 };
530 }
531 if !policy.gateway_switch() {
532 return Admission {
535 text: Some(text.to_owned()),
536 classification: gateway.mode.unclassified(),
537 trust: floor,
538 decision: ContextDecisionV1 {
539 object,
540 disposition: ContextDispositionV1::Allow,
541 reason_codes: vec![reason("gateway.disabled")],
542 signals: Vec::new(),
543 required_transformations: Vec::new(),
544 },
545 counts: AdmissionCounts::default(),
546 };
547 }
548
549 let mut actions = policy.actions();
550 if class.is_external_or_unknown()
551 && !capture::egress_check_active()
552 && actions.injection == FilterAction::Warn
553 {
554 actions.injection = FilterAction::Redact;
557 }
558 let findings = detectors::inspect(
559 text,
560 path,
561 &actions,
562 &policy.secret_patterns,
563 policy.budget(),
564 );
565 let mut counts = findings.counts();
566
567 let mut reasons = Vec::new();
568 let mut disposition = ContextDispositionV1::Allow;
569 for incomplete in findings.incomplete() {
572 reasons.push(incomplete);
573 if policy.detectors_mandatory() {
574 disposition = ContextDispositionV1::Deny;
575 }
576 }
577 let mut transformations = Vec::new();
578 for (action, hits, code) in [
579 (actions.secrets, counts.secrets, "secret"),
580 (actions.pii, counts.pii, "pii"),
581 (actions.injection, counts.injection, "injection"),
582 (actions.classification, counts.markings, "classification"),
583 ] {
584 if hits == 0 {
585 continue;
586 }
587 let step = match action {
588 FilterAction::Block => {
589 reasons.push(reason(&format!("{code}.blocked")));
590 ContextDispositionV1::Deny
591 }
592 FilterAction::Redact if code == "classification" => {
594 reasons.push(reason(&format!("{code}.blocked")));
595 ContextDispositionV1::Deny
596 }
597 FilterAction::Redact => {
598 reasons.push(reason(&format!("{code}.redacted")));
599 if !transformations.contains(&TransformationKindV1::Redaction) {
600 transformations.push(TransformationKindV1::Redaction);
601 }
602 ContextDispositionV1::AllowRedacted
603 }
604 FilterAction::Warn => {
605 reasons.push(reason(&format!("{code}.flagged")));
606 ContextDispositionV1::Allow
607 }
608 FilterAction::Off => continue,
609 };
610 disposition = disposition.most_restrictive(step);
611 }
612
613 let semantic = policy
616 .semantic
617 .as_ref()
618 .map(|detect| semantic::run(text, detect, &actions, gateway.max_inspected_bytes));
619 if let Some(outcome) = &semantic {
620 counts.semantic = outcome.hits;
621 for (step, code) in &outcome.steps {
622 reasons.push(code.clone());
623 if *step == ContextDispositionV1::AllowRedacted
624 && !transformations.contains(&TransformationKindV1::Redaction)
625 {
626 transformations.push(TransformationKindV1::Redaction);
627 }
628 disposition = disposition.most_restrictive(*step);
629 }
630 if let Some(code) = &outcome.incomplete {
631 reasons.push(code.clone());
632 }
633 }
634
635 let mut delivered = if disposition == ContextDispositionV1::Deny {
636 None
637 } else {
638 let semantic_masked = semantic
640 .as_ref()
641 .filter(|outcome| !outcome.redactions.is_empty())
642 .map(|outcome| semantic::redact(text, &outcome.redactions));
643 let source = semantic_masked.as_deref().unwrap_or(text);
644 Some(findings.redact(source, &actions, &policy.secret_patterns))
645 };
646 let reported = (actions.secrets == FilterAction::Redact && counts.secrets > 0)
652 || (actions.pii == FilterAction::Redact && counts.pii > 0);
653 if let Some(output) = &delivered
654 && (output != text || reported)
655 && detectors::residual(output, &actions, &policy.secret_patterns)
656 {
657 reasons.push(reason("redaction.incomplete"));
658 disposition = ContextDispositionV1::Deny;
659 delivered = None;
660 }
661
662 let classification = findings.classification(gateway.mode, &actions);
663 let semantic_injection = semantic.as_ref().is_some_and(|outcome| {
664 outcome
665 .steps
666 .iter()
667 .any(|(_, code)| {
669 let code = code.as_str();
670 code.starts_with("semantic.prompt_injection") && !code.ends_with(".not_inspected")
671 })
672 });
673 let content_trust = if counts.injection > 0 || semantic_injection {
674 TrustLevelV1::Untrusted
675 } else {
676 TrustLevelV1::Internal
677 };
678 let trust = floor.min(content_trust);
679 let mut signals: Vec<DetectorSignalV1> = findings.signals();
680 if let Some(outcome) = semantic {
681 signals.push(outcome.signal);
682 }
683 Admission {
684 text: delivered,
685 classification,
686 trust,
687 decision: ContextDecisionV1 {
688 object,
689 disposition,
690 reason_codes: reasons,
691 signals,
692 required_transformations: transformations,
693 },
694 counts,
695 }
696}
697
698#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
701pub struct OutputCompleteness {
702 pub truncated: bool,
703 pub timed_out: bool,
704 pub reader_incomplete: bool,
705 pub cancelled: bool,
706 pub decode_lossy: bool,
709}
710
711impl OutputCompleteness {
712 pub const fn complete() -> Self {
713 Self {
714 truncated: false,
715 timed_out: false,
716 reader_incomplete: false,
717 cancelled: false,
718 decode_lossy: false,
719 }
720 }
721
722 pub fn is_complete(self) -> bool {
723 !(self.truncated
724 || self.timed_out
725 || self.reader_incomplete
726 || self.cancelled
727 || self.decode_lossy)
728 }
729
730 fn reason_codes(self) -> Vec<&'static str> {
731 let mut reasons = Vec::new();
732 if self.truncated {
733 reasons.push("coverage.output_truncated");
734 }
735 if self.timed_out {
736 reasons.push("coverage.output_timed_out");
737 }
738 if self.reader_incomplete {
739 reasons.push("coverage.output_reader_incomplete");
740 }
741 if self.cancelled {
742 reasons.push("coverage.output_cancelled");
743 }
744 if self.decode_lossy {
745 reasons.push("coverage.output_decode_lossy");
746 }
747 reasons
748 }
749}
750
751#[derive(Debug, Clone)]
754pub struct ToolOutputAdmission {
755 pub text: Option<String>,
756 pub notice: Option<String>,
757}
758
759impl ToolOutputAdmission {
760 pub fn withheld(&self) -> bool {
761 self.text.is_none()
762 }
763
764 pub fn rendered(&self) -> String {
765 match (&self.text, &self.notice) {
766 (Some(text), Some(notice)) if text.is_empty() => notice.clone(),
767 (Some(text), Some(notice)) => format!("{notice}\n{text}"),
768 (Some(text), None) => text.clone(),
769 (None, Some(notice)) => notice.clone(),
770 (None, None) => "[lean-ctx gateway: content withheld]".to_string(),
771 }
772 }
773}
774
775pub fn admit_tool_output(text: &str, completeness: OutputCompleteness) -> ToolOutputAdmission {
781 let class = capture::current()
782 .and_then(|capture| capture.output_class())
783 .unwrap_or(origin::SourceClass::Unclassified {
784 tool: "tool_output",
785 });
786 admit_tool_output_as(text, completeness, &class)
787}
788
789pub fn admit_tool_output_as(
791 text: &str,
792 completeness: OutputCompleteness,
793 class: &origin::SourceClass,
794) -> ToolOutputAdmission {
795 capture::note_origin(class);
796 let project_original = crate::core::policy::content::protect_active(text);
799 let project_rewrote = project_original
800 .as_ref()
801 .is_ok_and(|admitted| admitted.as_ref() != text);
802 let policy = carrier::current_policy();
803 let mut admission = admit(text, None, class, &policy);
804 mark_capture_incomplete(&mut admission, completeness, &policy);
805
806 let gateway_output = admission.text.clone();
807 let text = project_original
808 .as_deref()
809 .ok()
810 .zip(gateway_output.as_deref())
811 .and_then(|(project_original, gateway_output)| {
812 compose_active_gateway_output(
813 project_original,
814 gateway_output,
815 class,
816 &policy,
817 completeness,
818 )
819 });
820 let policy_withheld = project_original.is_err() || (gateway_output.is_some() && text.is_none());
821 if let Some(admitted) = &text {
822 admission.text = Some(admitted.clone());
823 if project_rewrote
824 || gateway_output
825 .as_deref()
826 .is_some_and(|gateway| gateway != admitted)
827 {
828 mark_project_redaction(&mut admission);
829 }
830 } else if policy_withheld {
831 mark_policy_withheld(&mut admission, "policy.content_withheld");
832 }
833
834 let capture = capture::current();
835 if let Some(capture) = &capture {
836 capture.bind_policy(
837 policy.gateway.mode,
838 fingerprint_digest(&policy.fingerprint()),
839 );
840 capture.record_as(
841 &admission.decision,
842 admission.counts,
843 class.is_external_or_unknown(),
844 );
845 }
846 let mut notice = admission.hud_line_placed(policy.gateway.hud.redaction_counts_in_band());
847 if policy_withheld {
848 notice.get_or_insert_with(|| "[lean-ctx policy: content withheld]".to_string());
849 }
850 ToolOutputAdmission { text, notice }
851}
852
853fn mark_project_redaction(admission: &mut Admission) {
854 admission.decision.disposition = admission
855 .decision
856 .disposition
857 .most_restrictive(ContextDispositionV1::AllowRedacted);
858 let reason = reason("policy.content_redacted");
859 if !admission.decision.reason_codes.contains(&reason) {
860 admission.decision.reason_codes.push(reason);
861 }
862 if !admission
863 .decision
864 .required_transformations
865 .contains(&TransformationKindV1::Redaction)
866 {
867 admission
868 .decision
869 .required_transformations
870 .push(TransformationKindV1::Redaction);
871 }
872}
873
874fn mark_policy_withheld(admission: &mut Admission, reason_code: &str) {
875 admission.text = None;
876 admission.decision.disposition = ContextDispositionV1::Deny;
877 let reason = reason(reason_code);
878 if !admission.decision.reason_codes.contains(&reason) {
879 admission.decision.reason_codes.push(reason);
880 }
881}
882
883pub(crate) fn compose_active_gateway_output(
887 project_original: &str,
888 gateway_output: &str,
889 class: &origin::SourceClass,
890 policy: &AdmissionPolicy,
891 completeness: OutputCompleteness,
892) -> Option<String> {
893 let project_after_gateway = crate::core::policy::content::protect_active(gateway_output)
894 .ok()?
895 .into_owned();
896 let mut gateway_after_project = admit(project_original, None, class, policy);
897 mark_capture_incomplete(&mut gateway_after_project, completeness, policy);
898 let gateway_after_project = gateway_after_project.text?;
899 (project_after_gateway == gateway_after_project).then_some(project_after_gateway)
900}
901
902pub(super) fn admit_output_for_storage(
903 text: &str,
904 completeness: OutputCompleteness,
905 policy: &AdmissionPolicy,
906) -> Option<String> {
907 if !completeness.is_complete() {
910 return None;
911 }
912 let project_original = crate::core::policy::content::protect_active(text).ok()?;
913 let mut admission = admit(text, None, &origin::SourceClass::Project, policy);
914 mark_capture_incomplete(&mut admission, completeness, policy);
915 if !admission.storable() {
916 return None;
917 }
918 let gateway_output = admission.text?;
919 compose_active_gateway_output(
920 project_original.as_ref(),
921 &gateway_output,
922 &origin::SourceClass::Project,
923 policy,
924 completeness,
925 )
926}
927
928pub(super) fn admit_output_for_poll(
933 text: &str,
934 completeness: OutputCompleteness,
935 policy: &AdmissionPolicy,
936) -> Option<String> {
937 let without_reader = OutputCompleteness {
938 reader_incomplete: false,
939 ..completeness
940 };
941 if !completeness.reader_incomplete {
942 return admit_output_for_storage(text, completeness, policy);
943 }
944 if !without_reader.is_complete() || (policy.enabled_effective() && policy.detectors_mandatory())
945 {
946 return None;
947 }
948 admit_output_for_storage(text, without_reader, policy)
949}
950
951fn mark_capture_incomplete(
952 admission: &mut Admission,
953 completeness: OutputCompleteness,
954 policy: &AdmissionPolicy,
955) {
956 if completeness.is_complete() || !policy.enabled_effective() {
957 return;
958 }
959 for code in completeness.reason_codes() {
960 let reason = reason(code);
961 if !admission.decision.reason_codes.contains(&reason) {
962 admission.decision.reason_codes.push(reason);
963 }
964 }
965 let partial_reason = reason("coverage.output_partial");
966 if !admission.decision.reason_codes.contains(&partial_reason) {
967 admission.decision.reason_codes.push(partial_reason.clone());
968 }
969 for signal in &mut admission.decision.signals {
970 if signal.coverage.kind != CoverageKindV1::Complete {
971 continue;
972 }
973 signal.coverage.kind = CoverageKindV1::Partial;
977 signal.coverage.bytes_total = signal.coverage.bytes_inspected.saturating_add(1);
978 signal.coverage.chunks_total = signal.coverage.chunks_inspected.saturating_add(1);
979 signal.coverage.reason = Some(partial_reason.clone());
980 }
981 admission.counts.incomplete = admission.counts.incomplete.max(1);
982 if policy.detectors_mandatory() {
983 admission.decision.disposition = ContextDispositionV1::Deny;
984 admission.text = None;
985 }
986}
987
988#[derive(Debug, Clone, PartialEq, Eq)]
991pub struct SourceAdmission {
992 pub text: String,
993 pub storable: bool,
994 pub(crate) classification: ClassificationV1,
996}
997
998pub fn admit_source(
1004 text: &str,
1005 path: &str,
1006 preserve_bytes: bool,
1007 class: &origin::SourceClass,
1008) -> Result<String, std::io::Error> {
1009 admit_source_with_storage(
1010 text,
1011 path,
1012 preserve_bytes,
1013 OutputCompleteness::complete(),
1014 class,
1015 )
1016 .map(|admission| admission.text)
1017}
1018
1019pub fn admit_instance_source(
1022 text: &str,
1023 label: &str,
1024 preserve_bytes: bool,
1025) -> Result<String, std::io::Error> {
1026 admit_source(text, label, preserve_bytes, &origin::SourceClass::Project)
1027}
1028
1029pub fn admit_instance_context_source(text: &str) -> Result<SourceAdmission, std::io::Error> {
1033 admit_context_source(text, &origin::SourceClass::Project)
1034}
1035
1036pub(crate) fn admit_project_file_with_storage(
1039 text: &str,
1040 path: &str,
1041 preserve_bytes: bool,
1042 completeness: OutputCompleteness,
1043) -> Result<SourceAdmission, std::io::Error> {
1044 admit_source_with_storage(
1045 text,
1046 path,
1047 preserve_bytes,
1048 completeness,
1049 &origin::SourceClass::Project,
1050 )
1051}
1052
1053pub(crate) fn admit_source_with_storage(
1056 text: &str,
1057 path: &str,
1058 preserve_bytes: bool,
1059 completeness: OutputCompleteness,
1060 class: &origin::SourceClass,
1061) -> Result<SourceAdmission, std::io::Error> {
1062 admit_source_inner(text, Some(path), preserve_bytes, completeness, None, class)
1063}
1064
1065pub fn admit_context_source(
1068 text: &str,
1069 class: &origin::SourceClass,
1070) -> Result<SourceAdmission, std::io::Error> {
1071 admit_source_inner(
1072 text,
1073 None,
1074 false,
1075 OutputCompleteness::complete(),
1076 None,
1077 class,
1078 )
1079}
1080
1081pub(crate) fn admit_bound_context_source(
1086 text: &str,
1087 class: &origin::SourceClass,
1088) -> Result<SourceAdmission, std::io::Error> {
1089 admit_source_inner(
1090 text,
1091 None,
1092 true,
1093 OutputCompleteness::complete(),
1094 None,
1095 class,
1096 )
1097}
1098
1099pub(crate) fn admit_source_with_snapshot(
1104 text: &str,
1105 path: &str,
1106 preserve_bytes: bool,
1107 completeness: OutputCompleteness,
1108 snapshot: &stores::StoreAdmission,
1109) -> Result<SourceAdmission, std::io::Error> {
1110 admit_source_inner(
1111 text,
1112 Some(path),
1113 preserve_bytes,
1114 completeness,
1115 Some(snapshot.admission_policy()),
1116 &origin::SourceClass::Project,
1117 )
1118}
1119
1120fn admit_source_inner(
1121 text: &str,
1122 path: Option<&str>,
1123 preserve_bytes: bool,
1124 completeness: OutputCompleteness,
1125 policy_snapshot: Option<&AdmissionPolicy>,
1126 class: &origin::SourceClass,
1127) -> Result<SourceAdmission, std::io::Error> {
1128 capture::note_origin(class);
1129 admit_source_typed(
1130 text,
1131 path,
1132 preserve_bytes,
1133 completeness,
1134 policy_snapshot,
1135 class,
1136 )
1137 .map_err(|reasons| {
1138 let hint = withheld_remedy(&reasons);
1139 let reasons: Vec<&str> = reasons.iter().map(ReasonCodeV1::as_str).collect();
1140 std::io::Error::new(
1141 std::io::ErrorKind::PermissionDenied,
1142 format!(
1143 "source content withheld by the context gateway ({}){hint}",
1144 reasons.join(", ")
1145 ),
1146 )
1147 })
1148}
1149
1150fn withheld_remedy(reasons: &[ReasonCodeV1]) -> &'static str {
1154 let has = |code: &str| reasons.iter().any(|reason| reason.as_str() == code);
1155 if has("gateway.config_unloadable") {
1156 " — the global config.toml could not be loaded; fix it (lean-ctx doctor) to restore reads"
1157 } else if has("coverage.partial") || has("coverage.budget_exhausted") {
1158 " — the object exceeds [context_gateway] max_inspected_bytes and governed/sovereign mode \
1159 withholds what detectors cannot fully inspect"
1160 } else if has("detector.timed_out") {
1161 " — a detector exceeded [context_gateway] detector_timeout_ms in governed/sovereign mode"
1162 } else if has("classification.blocked") {
1163 " — a classification marking matched [context_gateway] classification = redact|block"
1164 } else if has("secret.blocked") {
1165 " — a secret matched [context_gateway] secrets = \"block\""
1166 } else if has("injection.blocked") {
1167 " — prompt-injection text matched [context_gateway] injection = \"block\""
1168 } else if has("redaction.incomplete") {
1169 " — a redaction left a detectable value behind, so nothing is delivered"
1170 } else if has("policy.content_withheld") {
1171 " — withheld by the project or organization policy"
1172 } else {
1173 ""
1174 }
1175}
1176
1177fn admit_source_typed(
1180 text: &str,
1181 path: Option<&str>,
1182 preserve_bytes: bool,
1183 completeness: OutputCompleteness,
1184 policy_snapshot: Option<&AdmissionPolicy>,
1185 class: &origin::SourceClass,
1186) -> Result<SourceAdmission, Vec<ReasonCodeV1>> {
1187 let external = class.is_external_or_unknown();
1188 let project_original = crate::core::policy::content::protect_active(text);
1191 let project_rewrote = project_original
1192 .as_ref()
1193 .is_ok_and(|admitted| admitted.as_ref() != text);
1194 let policy = policy_snapshot
1195 .cloned()
1196 .unwrap_or_else(carrier::current_policy);
1197 let fingerprint = policy.fingerprint();
1198 let capture = capture::current();
1199 if let Some(capture) = &capture {
1200 capture.bind_policy(policy.gateway.mode, fingerprint_digest(&fingerprint));
1201 }
1202 let memo_key = path.and_then(|path| {
1205 (completeness.is_complete()
1206 && project_original.is_ok()
1207 && !project_rewrote
1208 && policy.semantic.is_none()
1209 && !policy.config_unloadable()
1210 && policy.gateway_switch())
1211 .then(|| clean::key(&fingerprint, path, text))
1212 });
1213 if let Some(key) = &memo_key
1214 && let Some(decision) = clean::get_source(key)
1215 {
1216 if let Some(capture) = &capture {
1217 capture.record_as(&decision.decision, AdmissionCounts::default(), external);
1218 }
1219 return Ok(SourceAdmission {
1220 text: project_original
1221 .expect("memo key requires accepted project policy")
1222 .into_owned(),
1223 storable: decision.storable,
1224 classification: decision.classification,
1225 });
1226 }
1227
1228 let mut admission = admit(text, path.map(Path::new), class, &policy);
1229 mark_capture_incomplete(&mut admission, completeness, &policy);
1230 let storable = completeness.is_complete() && admission.storable();
1231 let gateway_admitted = admission.text.clone();
1232 let mut project_admitted = project_original
1233 .as_deref()
1234 .ok()
1235 .zip(gateway_admitted.as_deref())
1236 .and_then(|(project_original, gateway_admitted)| {
1237 compose_active_gateway_output(
1238 project_original,
1239 gateway_admitted,
1240 class,
1241 &policy,
1242 completeness,
1243 )
1244 });
1245 let mut refusal_reason = if project_original.is_err()
1246 || (gateway_admitted.is_some() && project_admitted.is_none())
1247 {
1248 Some("policy.content_withheld")
1249 } else {
1250 None
1251 };
1252
1253 if let Some(admitted) = &project_admitted {
1254 if project_rewrote
1255 || gateway_admitted
1256 .as_deref()
1257 .is_some_and(|gateway| gateway != admitted)
1258 {
1259 admission.text = Some(admitted.clone());
1260 mark_project_redaction(&mut admission);
1261 }
1262 }
1263 if preserve_bytes
1264 && let Some(gateway_admitted) = gateway_admitted.as_deref()
1265 && let Some(project_admitted_text) = project_admitted.as_deref()
1266 && preserve_bytes_rewrite_reason(
1267 text,
1268 gateway_admitted,
1269 project_admitted_text,
1270 project_rewrote,
1271 )
1272 .is_some()
1273 {
1274 project_admitted = None;
1275 refusal_reason = Some("source.bytes_not_preserved");
1276 }
1277 if let Some(reason_code) = refusal_reason {
1278 mark_policy_withheld(&mut admission, reason_code);
1279 }
1280 if let Some(capture) = &capture {
1281 capture.record_as(&admission.decision, admission.counts, external);
1282 }
1283
1284 let Some(project_admitted) = project_admitted else {
1285 return Err(admission.decision.reason_codes);
1286 };
1287
1288 if let Some(key) = memo_key
1289 && admission.disposition() == ContextDispositionV1::Allow
1290 && admission.decision.reason_codes.is_empty()
1291 && admission.text.as_deref() == Some(text)
1292 && project_admitted == text
1293 {
1294 clean::insert_source(
1295 key,
1296 admission.decision.clone(),
1297 admission.classification,
1298 admission.storable(),
1299 );
1300 }
1301 let redaction_counts = policy.gateway.hud.redaction_counts_in_band();
1302 if admission.hud_line_placed(redaction_counts).is_some() {
1303 notes::record(
1304 project_admitted.as_ref(),
1305 notes::Note {
1306 counts: admission.counts,
1307 decision: admission.decision.clone(),
1308 redaction_counts,
1309 },
1310 );
1311 }
1312 Ok(SourceAdmission {
1313 text: project_admitted,
1314 storable,
1315 classification: admission.classification,
1316 })
1317}
1318
1319fn preserve_bytes_rewrite_reason(
1320 source: &str,
1321 gateway_admitted: &str,
1322 project_admitted: &str,
1323 project_rewrote_original: bool,
1324) -> Option<&'static str> {
1325 if project_rewrote_original || project_admitted != gateway_admitted {
1326 Some("source content withheld: an active policy would rewrite a digest-bound source")
1327 } else if gateway_admitted != source {
1328 Some("source content withheld: the context gateway would rewrite a digest-bound source")
1329 } else {
1330 None
1331 }
1332}
1333
1334#[must_use]
1338pub fn admit_uninspectable(path: Option<&Path>, bytes: u64, policy: &AdmissionPolicy) -> Admission {
1339 let gateway = &policy.gateway;
1340 let object = content_digest(&format!("uninspectable:{bytes}"));
1341 let actions = policy.actions();
1342 let signals = detectors::unsupported_signals(&actions, bytes);
1343 let required = signals.iter().any(|signal| {
1344 signal.coverage.kind == lean_ctx_protocol::context_gateway::CoverageKindV1::Unsupported
1345 });
1346 if policy.config_unloadable() || !policy.gateway_switch() || !required {
1347 return admit("", path, &origin::SourceClass::Project, policy);
1348 }
1349 let restricted_path =
1350 path.is_some_and(|p| crate::core::io_boundary::is_secret_like(p).is_some());
1351 let mandatory = policy.detectors_mandatory();
1352 Admission {
1353 text: (!mandatory).then(String::new),
1354 classification: if restricted_path {
1355 ClassificationV1::Restricted
1356 } else {
1357 gateway.mode.unclassified()
1358 },
1359 trust: TrustLevelV1::Unknown,
1360 decision: ContextDecisionV1 {
1361 object,
1362 disposition: if mandatory {
1363 ContextDispositionV1::Deny
1364 } else {
1365 ContextDispositionV1::Allow
1366 },
1367 reason_codes: vec![reason("coverage.unsupported_media")],
1368 signals,
1369 required_transformations: Vec::new(),
1370 },
1371 counts: AdmissionCounts {
1372 incomplete: 1,
1373 ..AdmissionCounts::default()
1374 },
1375 }
1376}
1377
1378pub fn admit_media(path: &str, bytes: u64) -> Result<Option<String>, std::io::Error> {
1381 let policy = carrier::current_policy();
1382 let admission = admit_uninspectable(Some(Path::new(path)), bytes, &policy);
1383 if let Some(capture) = capture::current() {
1384 capture.bind_policy(
1385 policy.gateway.mode,
1386 fingerprint_digest(&policy.fingerprint()),
1387 );
1388 capture.record(&admission.decision, admission.counts);
1389 }
1390 if admission.text.is_none() {
1391 return Err(std::io::Error::new(
1392 std::io::ErrorKind::PermissionDenied,
1393 "media withheld by the context gateway (coverage.unsupported_media)",
1394 ));
1395 }
1396 Ok((admission.counts.incomplete > 0)
1397 .then(|| "[lean-ctx gateway: media not inspected (coverage.unsupported_media)]".to_owned()))
1398}
1399
1400#[cfg(any(test, feature = "test-support"))]
1402pub fn clear_clean_memo() {
1403 clean::clear();
1404}
1405
1406#[must_use]
1413pub fn note_for(admitted: &str, delivered: &str) -> Option<String> {
1414 let note = notes::lookup(admitted)?;
1415 let mut counts = note.counts;
1416 if note.decision.disposition == ContextDispositionV1::AllowRedacted {
1417 let pii = crate::core::input_filters::pii::checksummed_marker_count(delivered);
1418 let other = delivered
1419 .matches("[REDACTED:")
1420 .count()
1421 .saturating_sub(pii + delivered.matches(INJECTION_MARKER).count());
1422 counts.pii = counts.pii.min(saturating_u32(pii));
1423 counts.secrets = counts.secrets.min(saturating_u32(other));
1424 }
1425 render_hud(counts, ¬e.decision, false, note.redaction_counts)
1426}
1427
1428const INJECTION_MARKER: &str = "[REDACTED:prompt-injection]";
1429
1430fn saturating_u32(n: usize) -> u32 {
1431 u32::try_from(n).unwrap_or(u32::MAX)
1432}
1433
1434fn reason(code: &str) -> ReasonCodeV1 {
1435 ReasonCodeV1::new(code).expect("built-in reason codes are valid")
1436}
1437
1438pub(crate) fn record_recheck_refusal(
1446 admission: &stores::StoreAdmission,
1447 validity: lean_ctx_protocol::context_lineage::SourceValidityV1,
1448) {
1449 let Some(capture) = capture::current() else {
1450 return;
1451 };
1452 let policy = admission.admission_policy();
1453 capture.bind_policy(
1454 policy.gateway.mode,
1455 fingerprint_digest(&policy.fingerprint()),
1456 );
1457 let decision = ContextDecisionV1 {
1458 object: fingerprint_digest(b"source-recheck-refused"),
1459 disposition: ContextDispositionV1::Deny,
1460 reason_codes: vec![reason(validity.reason_code())],
1461 signals: Vec::new(),
1462 required_transformations: Vec::new(),
1463 };
1464 capture.record(&decision, AdmissionCounts::default());
1465}
1466
1467fn fingerprint_digest(fingerprint: &[u8]) -> Sha256Digest {
1469 let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(fingerprint));
1470 Sha256Digest::new(format!("sha256:{digest}")).expect("SHA-256 digest is canonical")
1471}
1472
1473fn content_digest(text: &str) -> Sha256Digest {
1474 let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(text.as_bytes()));
1475 Sha256Digest::new(format!("sha256:{digest}")).expect("SHA-256 digest is canonical")
1476}
1477
1478#[cfg(test)]
1479mod shell_admission_regression_tests;
1480
1481#[cfg(test)]
1482mod tests;
1483
1484#[cfg(test)]
1485mod operand_tests;
1486
1487#[cfg(test)]
1488mod receipt_tests;
1489
1490#[cfg(test)]
1491mod store_tests;
1492
1493#[cfg(test)]
1494mod egress_tests;
1495
1496#[cfg(test)]
1497mod egress_api_tests;