cloudiful-redactor 0.2.9

Structured text redaction with reversible sessions for secrets, domains, URLs, and related sensitive values.
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
use serde::{Deserialize, Serialize};
use std::ops::Range;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FindingKind {
    Secret,
    Domain,
    Url,
    Email,
    Ip,
    Cidr,
    Phone,
    Person,
    Organization,
    CustomString,
    CustomFile,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct RedactionRules {
    pub secret: bool,
    pub domain: bool,
    pub url: bool,
    pub email: bool,
    pub ip: bool,
    pub cidr: bool,
    pub phone: bool,
    pub person: bool,
    pub organization: bool,
}

impl Default for RedactionRules {
    fn default() -> Self {
        Self {
            secret: false,
            domain: false,
            url: false,
            email: true,
            ip: true,
            cidr: true,
            phone: false,
            person: false,
            organization: false,
        }
    }
}

impl RedactionRules {
    pub fn with_kind(mut self, kind: FindingKind, enabled: bool) -> Self {
        self.set_kind(kind, enabled);
        self
    }

    pub fn set_kind(&mut self, kind: FindingKind, enabled: bool) {
        match kind {
            FindingKind::Secret => self.secret = enabled,
            FindingKind::Domain => self.domain = enabled,
            FindingKind::Url => self.url = enabled,
            FindingKind::Email => self.email = enabled,
            FindingKind::Ip => self.ip = enabled,
            FindingKind::Cidr => self.cidr = enabled,
            FindingKind::Phone => self.phone = enabled,
            FindingKind::Person => self.person = enabled,
            FindingKind::Organization => self.organization = enabled,
            FindingKind::CustomString | FindingKind::CustomFile => {}
        }
    }

    pub fn is_enabled(self, kind: FindingKind) -> bool {
        match kind {
            FindingKind::Secret => self.secret,
            FindingKind::Domain => self.domain,
            FindingKind::Url => self.url,
            FindingKind::Email => self.email,
            FindingKind::Ip => self.ip,
            FindingKind::Cidr => self.cidr,
            FindingKind::Phone => self.phone,
            FindingKind::Person => self.person,
            FindingKind::Organization => self.organization,
            FindingKind::CustomString | FindingKind::CustomFile => true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomStringMatch {
    Exact,
    Contains,
    Regex,
}

impl Default for CustomStringMatch {
    fn default() -> Self {
        Self::Exact
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomStringScope {
    Text,
    Line,
}

impl Default for CustomStringScope {
    fn default() -> Self {
        Self::Text
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomStringRule {
    pub pattern: String,
    #[serde(default)]
    pub match_type: CustomStringMatch,
    #[serde(default)]
    pub scope: CustomStringScope,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomFileRule {
    pub path: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedactionPolicy {
    #[serde(flatten)]
    pub rules: RedactionRules,
    #[serde(default)]
    pub custom_strings: Vec<CustomStringRule>,
    #[serde(default)]
    pub custom_files: Vec<CustomFileRule>,
}

impl Default for RedactionPolicy {
    fn default() -> Self {
        Self {
            rules: RedactionRules::default(),
            custom_strings: Vec::new(),
            custom_files: Vec::new(),
        }
    }
}

impl RedactionPolicy {
    pub fn with_kind(mut self, kind: FindingKind, enabled: bool) -> Self {
        self.rules.set_kind(kind, enabled);
        self
    }

    pub fn with_custom_string(mut self, rule: CustomStringRule) -> Self {
        self.custom_strings.push(rule);
        self
    }

    pub fn with_custom_file(mut self, rule: CustomFileRule) -> Self {
        self.custom_files.push(rule);
        self
    }

    pub fn with_custom_strings<I: IntoIterator<Item = CustomStringRule>>(mut self, rules: I) -> Self {
        self.custom_strings.extend(rules);
        self
    }

    pub fn with_custom_files<I: IntoIterator<Item = CustomFileRule>>(mut self, rules: I) -> Self {
        self.custom_files.extend(rules);
        self
    }

    pub fn validate(&self) -> Result<(), String> {
        for (index, rule) in self.custom_strings.iter().enumerate() {
            if rule.pattern.is_empty() {
                return Err(format!(
                    "custom_strings[{index}]: pattern must not be empty"
                ));
            }
            if matches!(rule.match_type, CustomStringMatch::Regex) {
                if regex::Regex::new(&rule.pattern).is_err() {
                    return Err(format!(
                        "custom_strings[{index}]: invalid regex pattern: {}",
                        rule.pattern
                    ));
                }
            }
        }
        for (index, rule) in self.custom_files.iter().enumerate() {
            if rule.path.is_empty() {
                return Err(format!(
                    "custom_files[{index}]: path must not be empty"
                ));
            }
        }
        Ok(())
    }
}

impl From<RedactionRules> for RedactionPolicy {
    fn from(rules: RedactionRules) -> Self {
        Self {
            rules,
            custom_strings: Vec::new(),
            custom_files: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FindingKindMeta {
    label: &'static str,
    token_label: &'static str,
    priority: u8,
    containment_priority: u8,
}

impl FindingKind {
    const fn meta(self) -> FindingKindMeta {
        match self {
            Self::Secret => FindingKindMeta {
                label: "secret",
                token_label: "SECRET",
                priority: 100,
                containment_priority: 75,
            },
            Self::Domain => FindingKindMeta {
                label: "domain",
                token_label: "DOMAIN",
                priority: 70,
                containment_priority: 80,
            },
            Self::Url => FindingKindMeta {
                label: "url",
                token_label: "URL",
                priority: 90,
                containment_priority: 100,
            },
            Self::Email => FindingKindMeta {
                label: "email",
                token_label: "EMAIL",
                priority: 85,
                containment_priority: 95,
            },
            Self::Ip => FindingKindMeta {
                label: "ip",
                token_label: "IP",
                priority: 75,
                containment_priority: 85,
            },
            Self::Cidr => FindingKindMeta {
                label: "cidr",
                token_label: "CIDR",
                priority: 80,
                containment_priority: 90,
            },
            Self::Phone => FindingKindMeta {
                label: "phone",
                token_label: "PHONE",
                priority: 60,
                containment_priority: 70,
            },
            Self::Person => FindingKindMeta {
                label: "person",
                token_label: "PERSON",
                priority: 50,
                containment_priority: 50,
            },
            Self::Organization => FindingKindMeta {
                label: "organization",
                token_label: "ORG",
                priority: 45,
                containment_priority: 45,
            },
            Self::CustomString => FindingKindMeta {
                label: "custom_string",
                token_label: "CSTR",
                priority: 95,
                containment_priority: 40,
            },
            Self::CustomFile => FindingKindMeta {
                label: "custom_file",
                token_label: "FILE",
                priority: 99,
                containment_priority: 99,
            },
        }
    }

    pub fn label(self) -> &'static str {
        self.meta().label
    }

    pub fn token_label(self) -> &'static str {
        self.meta().token_label
    }

    pub fn priority(self) -> u8 {
        self.meta().priority
    }

    pub fn containment_priority(self) -> u8 {
        self.meta().containment_priority
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FindingSource {
    Rule,
    Llm,
}

impl FindingSource {
    pub fn bonus(self) -> u8 {
        match self {
            Self::Rule => 10,
            Self::Llm => 0,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Finding {
    pub kind: FindingKind,
    pub source: FindingSource,
    pub match_text: String,
    pub normalized_key: String,
    pub confidence: u8,
    pub start: usize,
    pub end: usize,
}

impl Finding {
    pub fn range(&self) -> Range<usize> {
        self.start..self.end
    }

    pub fn score(&self) -> u16 {
        u16::from(self.kind.priority())
            + u16::from(self.source.bonus())
            + u16::from(self.confidence)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReplacementStrategy {
    StructuredToken,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppliedReplacement {
    pub kind: FindingKind,
    #[serde(skip_serializing)]
    pub original: String,
    pub replacement: String,
    pub strategy: ReplacementStrategy,
    pub display_value: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedactionStats {
    pub total_findings: usize,
    pub applied_replacements: usize,
    pub dropped_findings: usize,
    pub llm_configured: bool,
    pub llm_request_failed: bool,
    pub llm_candidates_accepted: usize,
    pub llm_candidates_rejected: usize,
    pub llm_error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedactionResult {
    pub redacted_text: String,
    pub findings: Vec<Finding>,
    pub applied_replacements: Vec<AppliedReplacement>,
    pub stats: RedactionStats,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedactionArtifact {
    pub result: RedactionResult,
    pub session: RedactionSession,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RestorationEntry {
    pub token: String,
    pub kind: FindingKind,
    pub original: String,
    pub replacement_hint: Option<String>,
    pub occurrences: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedactionSession {
    pub version: u32,
    pub session_id: String,
    pub fingerprint: String,
    pub redacted_fingerprint: String,
    pub redacted_text: String,
    #[serde(default)]
    pub policy: RedactionPolicy,
    pub entries: Vec<RestorationEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RestoreResult {
    pub restored_text: String,
    pub restored_count: usize,
    pub unresolved_tokens: Vec<String>,
    pub validation_errors: Vec<String>,
}

impl RestoreResult {
    pub fn is_valid(&self) -> bool {
        self.validation_errors.is_empty() && self.unresolved_tokens.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionEntrySummary {
    pub token: String,
    pub kind: FindingKind,
    pub replacement_hint: Option<String>,
    pub occurrences: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionSummary {
    pub version: u32,
    pub session_id: String,
    pub fingerprint: String,
    pub redacted_fingerprint: String,
    pub entry_count: usize,
    pub entries: Vec<SessionEntrySummary>,
}