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