lean-ctx 3.11.4

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// SPDX-License-Identifier: Apache-2.0
//! Built-in detectors behind `admit`, adapted from the existing scanners:
//! `secret_detection` (with the user's custom and exclude patterns),
//! checksum-validated `input_filters::pii`, the `output_sanitizer` injection
//! heuristic, `input_filters::classification` markings and
//! `io_boundary::is_secret_like` for paths.
//!
//! Detectors scan line-aligned chunks under a byte budget and a per-detector
//! deadline. Every built-in pattern is line-local, so line-aligned chunks
//! without overlap find exactly what a whole-text scan finds. Coverage is
//! reported as it happened: `complete` only when every byte was inspected,
//! `partial` when the budget or the deadline stopped the scan, `failed` when a
//! configured rule could not run, `not_required` when the detector is off.
//! Only counts leave this module, never matched values.

use std::path::Path;
use std::sync::OnceLock;
use std::time::{Duration, Instant};

use lean_ctx_protocol::context_gateway::{
    ClassificationV1, CoverageKindV1, DetectorCategoryV1, DetectorCoverageV1, DetectorRefV1,
    DetectorSignalV1, DetectorStatusV1, GatewayModeV1, ReasonCodeV1, SeverityV1,
};
use lean_ctx_protocol::{ProtocolReference, SemanticVersion};

use super::AdmissionCounts;
use crate::core::config::SecretDetectionConfig;
use crate::core::input_filters::{FilterAction, classification, injection, pii};
use crate::core::secret_detection;

/// Version of the built-in detector set; bump when a detector's semantics change.
const BUILTIN_VERSION: &str = "1.1.0";

/// Target chunk size; chunks end on a line boundary, so a chunk can be longer.
pub(super) const CHUNK_BYTES: usize = 256 * 1024;

#[derive(Debug, Clone, Copy)]
pub(super) struct Actions {
    pub(super) secrets: FilterAction,
    pub(super) pii: FilterAction,
    pub(super) injection: FilterAction,
    pub(super) classification: FilterAction,
}

/// How much one admission may inspect.
#[derive(Debug, Clone, Copy)]
pub(super) struct Budget {
    pub(super) max_bytes: usize,
    pub(super) deadline: Duration,
}

/// One detector's run over the chunked text.
#[derive(Debug, Clone)]
struct Run {
    hits: u32,
    latency_us: u64,
    bytes_inspected: u64,
    chunks_inspected: u32,
    status: DetectorStatusV1,
    /// Set when a configured rule could not run (the run is then `failed`).
    failure: Option<&'static str>,
}

impl Run {
    fn complete(&self, bytes_total: u64) -> bool {
        self.status == DetectorStatusV1::Completed
            && self.failure.is_none()
            && self.bytes_inspected == bytes_total
    }
}

/// What the detectors found in the original text.
#[derive(Debug, Default)]
pub(super) struct Findings {
    bytes_total: u64,
    chunks_total: u32,
    secrets: Option<Run>,
    secret_path: Option<Run>,
    pii: Option<Run>,
    injection: Option<Run>,
    markings: Option<(Run, ClassificationV1)>,
}

fn saturating_u32(n: usize) -> u32 {
    u32::try_from(n).unwrap_or(u32::MAX)
}

fn micros(elapsed: Duration) -> u64 {
    u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX)
}

/// Split `text` into chunks of about [`CHUNK_BYTES`] that end on a line
/// boundary (or at the end of the text).
fn line_chunks(text: &str) -> Vec<&str> {
    let mut chunks = Vec::new();
    let mut start = 0;
    while start < text.len() {
        let mut end = (start + CHUNK_BYTES).min(text.len());
        while !text.is_char_boundary(end) {
            end += 1;
        }
        if end < text.len() {
            end = text[end..]
                .find('\n')
                .map_or(text.len(), |offset| end + offset + 1);
        }
        chunks.push(&text[start..end]);
        start = end;
    }
    chunks
}

/// Run one detector over the chunks until the budget or the deadline stops it.
fn run_chunked(chunks: &[&str], budget: Budget, mut detect: impl FnMut(&str) -> usize) -> Run {
    let started = Instant::now();
    let mut run = Run {
        hits: 0,
        latency_us: 0,
        bytes_inspected: 0,
        chunks_inspected: 0,
        status: DetectorStatusV1::Completed,
        failure: None,
    };
    let mut inspected_bytes = 0usize;
    for chunk in chunks {
        if inspected_bytes + chunk.len() > budget.max_bytes {
            break;
        }
        if started.elapsed() >= budget.deadline {
            run.status = DetectorStatusV1::TimedOut;
            break;
        }
        run.hits = run.hits.saturating_add(saturating_u32(detect(chunk)));
        inspected_bytes += chunk.len();
        run.chunks_inspected += 1;
    }
    run.bytes_inspected = u64::try_from(inspected_bytes).unwrap_or(u64::MAX);
    run.latency_us = micros(started.elapsed());
    run
}

/// Scanner configuration for detection: never rewrites, always reports.
fn detect_only(patterns: &SecretDetectionConfig) -> SecretDetectionConfig {
    SecretDetectionConfig {
        enabled: true,
        redact: false,
        ..patterns.clone()
    }
}

fn secret_hits(text: &str, patterns: &SecretDetectionConfig) -> usize {
    secret_detection::scan_and_redact(text, &detect_only(patterns))
        .1
        .len()
}

fn pii_hits(text: &str) -> usize {
    pii::redact_checksummed(text).1.iter().map(|(_, n)| n).sum()
}

fn default_matcher() -> &'static classification::Matcher {
    static MATCHER: OnceLock<classification::Matcher> = OnceLock::new();
    MATCHER.get_or_init(|| classification::Matcher::new(&[]))
}

/// The classification an explicit marking asserts.
fn marking_level(label: &str) -> ClassificationV1 {
    match label {
        "TOP SECRET" | "SECRET" | "RESTRICTED" => ClassificationV1::Restricted,
        "INTERNAL ONLY" => ClassificationV1::Internal,
        _ => ClassificationV1::Confidential,
    }
}

/// A configured custom secret pattern that does not compile would otherwise be
/// skipped silently by the scanner — the run must say so instead.
fn invalid_custom_pattern(patterns: &SecretDetectionConfig) -> bool {
    patterns
        .custom_patterns
        .iter()
        .any(|pattern| regex::Regex::new(pattern).is_err())
}

pub(super) fn inspect(
    text: &str,
    path: Option<&Path>,
    actions: &Actions,
    patterns: &SecretDetectionConfig,
    budget: Budget,
) -> Findings {
    let chunks = line_chunks(text);
    let mut findings = Findings {
        bytes_total: u64::try_from(text.len()).unwrap_or(u64::MAX),
        chunks_total: saturating_u32(chunks.len()),
        ..Findings::default()
    };
    if !actions.secrets.is_off() {
        let mut run = run_chunked(&chunks, budget, |chunk| secret_hits(chunk, patterns));
        if invalid_custom_pattern(patterns) {
            run.status = DetectorStatusV1::Failed;
            run.failure = Some("detector.invalid_pattern");
        }
        findings.secrets = Some(run);
        if let Some(path) = path {
            let started = Instant::now();
            let secret_like = crate::core::io_boundary::is_secret_like(path).is_some();
            findings.secret_path = Some(Run {
                hits: u32::from(secret_like),
                latency_us: micros(started.elapsed()),
                bytes_inspected: findings.bytes_total,
                chunks_inspected: findings.chunks_total,
                status: DetectorStatusV1::Completed,
                failure: None,
            });
        }
    }
    if !actions.pii.is_off() {
        findings.pii = Some(run_chunked(&chunks, budget, pii_hits));
    }
    if !actions.injection.is_off() {
        findings.injection = Some(run_chunked(&chunks, budget, injection::detect));
    }
    if !actions.classification.is_off() {
        let mut labels = std::collections::BTreeSet::new();
        let run = run_chunked(&chunks, budget, |chunk| {
            let found = default_matcher().detect(chunk);
            let n = found.len();
            labels.extend(found);
            n
        });
        let level = labels
            .iter()
            .map(|label| marking_level(label))
            .max()
            .unwrap_or(ClassificationV1::Public);
        let run = Run {
            hits: saturating_u32(labels.len()),
            ..run
        };
        findings.markings = Some((run, level));
    }
    findings
}

impl Findings {
    fn runs(&self) -> [(Option<&Run>, &'static str); 4] {
        [
            (self.secrets.as_ref(), "secrets"),
            (self.pii.as_ref(), "pii"),
            (self.injection.as_ref(), "injection"),
            (self.markings.as_ref().map(|(run, _)| run), "classification"),
        ]
    }

    pub(super) fn counts(&self) -> AdmissionCounts {
        let hits = |run: Option<&Run>| run.map_or(0, |r| r.hits);
        AdmissionCounts {
            secrets: hits(self.secrets.as_ref()),
            pii: hits(self.pii.as_ref()),
            injection: hits(self.injection.as_ref()),
            markings: hits(self.markings.as_ref().map(|(run, _)| run)),
            incomplete: saturating_u32(self.incomplete().len()),
            semantic: 0,
        }
    }

    /// One reason per enabled detector that did not inspect the whole object.
    pub(super) fn incomplete(&self) -> Vec<ReasonCodeV1> {
        let mut reasons = Vec::new();
        for (run, _) in self.runs() {
            let Some(run) = run else { continue };
            if run.complete(self.bytes_total) {
                continue;
            }
            let code = match (run.failure, run.status) {
                (Some(failure), _) => failure,
                (None, DetectorStatusV1::TimedOut) => "detector.timed_out",
                _ => "coverage.partial",
            };
            let reason = ReasonCodeV1::new(code).expect("built-in reason codes are valid");
            if !reasons.contains(&reason) {
                reasons.push(reason);
            }
        }
        reasons
    }

    fn secret_path(&self) -> bool {
        self.secret_path.as_ref().is_some_and(|r| r.hits > 0)
    }

    /// Apply every `redact` action to the whole text. Secrets go last so no
    /// other marker can split a credential and hide it from the secrets pass.
    pub(super) fn redact(
        &self,
        text: &str,
        actions: &Actions,
        patterns: &SecretDetectionConfig,
    ) -> String {
        let counts = self.counts();
        let mut out = text.to_owned();
        if actions.injection == FilterAction::Redact && counts.injection > 0 {
            out = injection::redact(&out).0;
        }
        if actions.pii == FilterAction::Redact && counts.pii > 0 {
            out = pii::redact_checksummed(&out).0;
        }
        if actions.secrets == FilterAction::Redact && counts.secrets > 0 {
            let forced = SecretDetectionConfig {
                enabled: true,
                redact: true,
                ..patterns.clone()
            };
            out = secret_detection::scan_and_redact(&out, &forced).0;
        }
        out
    }

    /// Classification of the delivered object.
    pub(super) fn classification(
        &self,
        mode: GatewayModeV1,
        actions: &Actions,
    ) -> ClassificationV1 {
        let counts = self.counts();
        let mut level = mode.unclassified();
        if self.secret_path() {
            level = level.join(ClassificationV1::Restricted);
        }
        if let Some((run, marked)) = &self.markings
            && run.hits > 0
        {
            level = level.join(*marked);
        }
        // Values that are detected but deliberately delivered keep their weight.
        if counts.secrets > 0 && actions.secrets == FilterAction::Warn {
            level = level.join(ClassificationV1::Restricted);
        }
        if counts.pii > 0 && actions.pii == FilterAction::Warn {
            level = level.join(ClassificationV1::Confidential);
        }
        level
    }

    pub(super) fn signals(&self) -> Vec<DetectorSignalV1> {
        let scope = Scope {
            bytes_total: self.bytes_total,
            chunks_total: self.chunks_total,
        };
        let mut signals = vec![signal(
            "builtin.secrets",
            DetectorCategoryV1::Secret,
            SeverityV1::Critical,
            self.secrets.as_ref(),
            scope,
        )];
        if self.secret_path.is_some() {
            signals.push(signal(
                "builtin.secret_path",
                DetectorCategoryV1::Classification,
                SeverityV1::High,
                self.secret_path.as_ref(),
                scope,
            ));
        }
        signals.push(signal(
            "builtin.pii_checksum",
            DetectorCategoryV1::Pii,
            SeverityV1::High,
            self.pii.as_ref(),
            scope,
        ));
        signals.push(signal(
            "builtin.injection",
            DetectorCategoryV1::PromptInjection,
            SeverityV1::High,
            self.injection.as_ref(),
            scope,
        ));
        signals.push(signal(
            "builtin.classification_marking",
            DetectorCategoryV1::Classification,
            SeverityV1::Medium,
            self.markings.as_ref().map(|(run, _)| run),
            scope,
        ));
        signals
    }
}

#[derive(Debug, Clone, Copy)]
struct Scope {
    bytes_total: u64,
    chunks_total: u32,
}

fn detector_ref(id: &str) -> DetectorRefV1 {
    DetectorRefV1 {
        id: ProtocolReference::new(id).expect("built-in detector ids are valid"),
        version: SemanticVersion::new(BUILTIN_VERSION).expect("built-in version is valid"),
    }
}

fn reason(code: &str) -> Option<ReasonCodeV1> {
    Some(ReasonCodeV1::new(code).expect("built-in reason codes are valid"))
}

fn signal(
    id: &str,
    category: DetectorCategoryV1,
    severity: SeverityV1,
    run: Option<&Run>,
    scope: Scope,
) -> DetectorSignalV1 {
    let Some(run) = run else {
        return DetectorSignalV1 {
            detector: detector_ref(id),
            category,
            severity: SeverityV1::Info,
            confidence_milli: None,
            calibrated: false,
            evidence_count: 0,
            coverage: DetectorCoverageV1 {
                kind: CoverageKindV1::NotRequired,
                bytes_total: scope.bytes_total,
                bytes_inspected: 0,
                chunks_total: scope.chunks_total,
                chunks_inspected: 0,
                reason: None,
            },
            status: DetectorStatusV1::Skipped,
            latency_us: 0,
        };
    };
    let (kind, coverage_reason) = if let Some(failure) = run.failure {
        (CoverageKindV1::Failed, reason(failure))
    } else if run.complete(scope.bytes_total) {
        (CoverageKindV1::Complete, None)
    } else if run.status == DetectorStatusV1::TimedOut {
        (CoverageKindV1::Partial, reason("detector.timed_out"))
    } else {
        (CoverageKindV1::Partial, reason("coverage.budget_exhausted"))
    };
    DetectorSignalV1 {
        detector: detector_ref(id),
        category,
        severity: if run.hits > 0 {
            severity
        } else {
            SeverityV1::Info
        },
        confidence_milli: None,
        calibrated: false,
        evidence_count: run.hits,
        coverage: DetectorCoverageV1 {
            kind,
            bytes_total: scope.bytes_total,
            bytes_inspected: run.bytes_inspected,
            chunks_total: scope.chunks_total,
            chunks_inspected: run.chunks_inspected,
            reason: coverage_reason,
        },
        status: run.status,
        latency_us: run.latency_us,
    }
}

/// Signals for an object no built-in detector can read (an image): every
/// enabled detector reports `unsupported`, never a clean `complete`.
pub(super) fn unsupported_signals(actions: &Actions, bytes: u64) -> Vec<DetectorSignalV1> {
    let scope = Scope {
        bytes_total: bytes,
        chunks_total: 1,
    };
    [
        (
            actions.secrets,
            "builtin.secrets",
            DetectorCategoryV1::Secret,
        ),
        (actions.pii, "builtin.pii_checksum", DetectorCategoryV1::Pii),
        (
            actions.injection,
            "builtin.injection",
            DetectorCategoryV1::PromptInjection,
        ),
        (
            actions.classification,
            "builtin.classification_marking",
            DetectorCategoryV1::Classification,
        ),
    ]
    .into_iter()
    .map(|(action, id, category)| {
        if action.is_off() {
            return signal(id, category, SeverityV1::Info, None, scope);
        }
        DetectorSignalV1 {
            detector: detector_ref(id),
            category,
            severity: SeverityV1::Info,
            confidence_milli: None,
            calibrated: false,
            evidence_count: 0,
            coverage: DetectorCoverageV1 {
                kind: CoverageKindV1::Unsupported,
                bytes_total: scope.bytes_total,
                bytes_inspected: 0,
                chunks_total: 1,
                chunks_inspected: 0,
                reason: reason("coverage.unsupported_media"),
            },
            status: DetectorStatusV1::Skipped,
            latency_us: 0,
        }
    })
    .collect()
}

#[cfg(test)]
pub(super) fn secret_hits_for_bench(text: &str, patterns: &SecretDetectionConfig) -> usize {
    secret_hits(text, patterns)
}

#[cfg(test)]
pub(super) fn markings_for_bench(text: &str) -> usize {
    default_matcher().detect(text).len()
}

#[cfg(test)]
pub(super) fn chunks_for_test(text: &str) -> Vec<&str> {
    line_chunks(text)
}

/// True when a redacting detector can still find something in `output`.
pub(super) fn residual(output: &str, actions: &Actions, patterns: &SecretDetectionConfig) -> bool {
    (actions.secrets == FilterAction::Redact && secret_hits(output, patterns) > 0)
        || (actions.pii == FilterAction::Redact && pii_hits(output) > 0)
}