pedant-core 0.13.0

Analysis engine for pedant: IR extraction, style checks, and capability detection
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
use std::borrow::Cow;
use std::sync::Arc;

use pedant_types::{
    Capability, CapabilityFinding, CapabilityProfile, ExecutionContext, FindingOrigin,
    SourceLocation,
};

use crate::ir::FileIr;

/// Validator: receives (full value, suffix after prefix) and returns whether it matches.
type PrefixValidator = fn(&str, &str) -> bool;

// --- Prefix tables for path-based capability resolution ---

const NETWORK_PREFIXES: &[(&str, Capability)] = &[
    ("std::net", Capability::Network),
    ("tokio::net", Capability::Network),
    ("reqwest", Capability::Network),
    ("hyper", Capability::Network),
    ("ureq", Capability::Network),
    ("curl", Capability::Network),
    ("tungstenite", Capability::Network),
];

const FILESYSTEM_PREFIXES: &[(&str, Capability)] = &[
    ("std::fs", Capability::FileRead),
    ("tokio::fs", Capability::FileRead),
    ("walkdir", Capability::FileRead),
    ("glob", Capability::FileRead),
    ("tempfile", Capability::FileWrite),
];

const PROCESS_PREFIXES: &[(&str, Capability)] = &[
    ("std::process", Capability::ProcessExec),
    ("tokio::process", Capability::ProcessExec),
    ("duct", Capability::ProcessExec),
];

const ENV_PREFIXES: &[(&str, Capability)] = &[
    ("std::env::var", Capability::EnvAccess),
    ("std::env::vars", Capability::EnvAccess),
    ("dotenvy", Capability::EnvAccess),
    ("envy", Capability::EnvAccess),
];

const FFI_PREFIXES: &[(&str, Capability)] = &[
    ("libc", Capability::Ffi),
    ("nix", Capability::Ffi),
    ("winapi", Capability::Ffi),
    ("windows_sys", Capability::Ffi),
];

const CRYPTO_PREFIXES: &[(&str, Capability)] = &[
    ("ring", Capability::Crypto),
    ("rustls", Capability::Crypto),
    ("openssl", Capability::Crypto),
    ("aes", Capability::Crypto),
    ("sha2", Capability::Crypto),
    ("hmac", Capability::Crypto),
    ("ed25519_dalek", Capability::Crypto),
    ("x25519_dalek", Capability::Crypto),
];

const SYSTEM_TIME_PREFIXES: &[(&str, Capability)] = &[
    ("std::time::SystemTime", Capability::SystemTime),
    ("std::time::Instant", Capability::SystemTime),
    ("chrono", Capability::SystemTime),
    ("time", Capability::SystemTime),
];

const ALL_PREFIX_TABLES: &[&[(&str, Capability)]] = &[
    NETWORK_PREFIXES,
    FILESYSTEM_PREFIXES,
    PROCESS_PREFIXES,
    ENV_PREFIXES,
    FFI_PREFIXES,
    CRYPTO_PREFIXES,
    SYSTEM_TIME_PREFIXES,
];

/// Function suffixes that indicate filesystem write operations.
const FS_WRITE_SUFFIXES: &[&str] = &[
    "copy",
    "create_dir",
    "create_dir_all",
    "hard_link",
    "remove_dir",
    "remove_dir_all",
    "remove_file",
    "rename",
    "set_permissions",
    "write",
];

/// Prefixes for filesystem write function paths.
const FS_WRITE_PREFIXES: &[&str] = &["std::fs::", "tokio::fs::"];

fn is_fs_write_function(path: &str) -> bool {
    FS_WRITE_PREFIXES.iter().any(|prefix| {
        path.strip_prefix(prefix)
            .is_some_and(|suffix| FS_WRITE_SUFFIXES.contains(&suffix))
    })
}

use crate::ir::PATH_SEPARATOR;

fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    path == prefix
        || (path.starts_with(prefix)
            && path
                .as_bytes()
                .get(prefix.len()..prefix.len() + PATH_SEPARATOR.len())
                == Some(PATH_SEPARATOR.as_bytes()))
}

/// Map a use-path to its capability, checking write-function overrides first.
fn resolve_capabilities(path: &str) -> Option<Capability> {
    if is_fs_write_function(path) {
        return Some(Capability::FileWrite);
    }

    ALL_PREFIX_TABLES
        .iter()
        .flat_map(|table| table.iter())
        .find_map(|(prefix, capability)| path_matches_prefix(path, prefix).then_some(*capability))
}

const URL_SCHEMES: &[&str] = &["http://", "https://", "ws://", "wss://"];

/// Heuristic: URLs, IPv4 with port, or IPv6 addresses.
fn check_string_for_endpoint(value: &str) -> bool {
    if value.len() < 8 {
        return false;
    }
    URL_SCHEMES.iter().any(|s| value.starts_with(s))
        || looks_like_ipv4(value)
        || looks_like_ipv6(value)
}

fn strip_port_suffix(s: &str) -> Option<&str> {
    let pos = s.rfind(':')?;
    let (host, port) = s.split_at(pos);
    port[1..].parse::<u16>().ok().map(|_| host)
}

fn looks_like_ipv4(s: &str) -> bool {
    let host = match (s.rfind(':'), strip_port_suffix(s)) {
        (Some(_), Some(h)) => h,
        (Some(_), None) => return false,
        (None, _) => s,
    };
    let mut parts = host.split('.');
    let mut count = 0;
    let valid = parts.all(|p| {
        count += 1;
        p.parse::<u8>().is_ok()
    });
    valid && count == 4
}

fn extract_ipv6_body(s: &str) -> &str {
    match s.strip_prefix('[') {
        Some(inner) => inner
            .strip_suffix(']')
            .or_else(|| inner.rfind("]:").map(|pos| &inner[..pos]))
            .unwrap_or(inner),
        None => s,
    }
}

fn looks_like_ipv6(s: &str) -> bool {
    let trimmed = extract_ipv6_body(s);
    if trimmed.len() < 3 {
        return false;
    }
    let mut groups = trimmed.split(':');
    let mut count = 0;
    let valid = groups.all(|g| {
        count += 1;
        g.is_empty() || g.chars().all(|c| c.is_ascii_hexdigit())
    });
    valid && count > 2
}

/// Heuristic: looks for PEM block header prefix.
fn check_string_for_pem(value: &str) -> bool {
    value.contains("-----BEGIN ")
}

/// Truncate long evidence strings to avoid leaking full keys.
///
/// Strings ≤ 40 chars are returned unchanged. Longer strings return the first
/// 16 chars, an ellipsis, and the last 4 chars.
pub fn truncate_evidence(value: &str) -> Cow<'_, str> {
    match value.len() <= 40 {
        true => Cow::Borrowed(value),
        false => {
            let char_count = value.chars().count();
            let tail_offset = char_count.saturating_sub(4);
            let mut indices = value.char_indices();
            let head_end = indices.nth(16).map_or(value.len(), |(i, _)| i);
            let skip = tail_offset.saturating_sub(17);
            let tail_start = indices.nth(skip).map_or(0, |(i, _)| i);
            Cow::Owned(format!("{}…{}", &value[..head_end], &value[tail_start..]))
        }
    }
}

/// Check whether a string is a hex-encoded key at a known private key size.
///
/// Returns true for even-length pure hex strings of 64, 96, or ≥ 128 chars.
fn check_string_for_hex_key(value: &str) -> bool {
    let len = value.len();
    if len < 64 || len % 2 != 0 {
        return false;
    }
    if !value.bytes().all(|b| b.is_ascii_hexdigit()) {
        return false;
    }
    matches!(len, 64 | 96) || len >= 128
}

const fn base58_table() -> [bool; 256] {
    let mut table = [false; 256];
    let alphabet = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    let mut i = 0;
    while i < alphabet.len() {
        table[alphabet[i] as usize] = true;
        i += 1;
    }
    table
}

const BASE58_TABLE: [bool; 256] = base58_table();

fn is_base58(value: &str) -> bool {
    value.bytes().all(|b| BASE58_TABLE[b as usize])
}

/// Check whether a string is a base58-encoded private key.
///
/// Matches Bitcoin WIF keys (51–52 chars, first char in {5, K, L}) and
/// Solana keypairs (64–88 base58 chars).
fn check_string_for_base58_key(value: &str) -> bool {
    let len = value.len();
    match value.as_bytes().first() {
        Some(b'5' | b'K' | b'L') if (51..=52).contains(&len) => is_base58(value),
        _ if (64..=88).contains(&len) => is_base58(value),
        _ => false,
    }
}

/// Check whether a string starts with a known cryptographic key prefix.
///
/// Matches AGE-SECRET-KEY-1, xprv (BIP32), ed25519: (NEAR), and 0x + 64 hex (Ethereum).
fn check_string_for_key_prefix(value: &str) -> bool {
    const KEY_PREFIXES: &[(&str, PrefixValidator)] = &[
        ("AGE-SECRET-KEY-1", |v, _| v.len() > 16),
        ("xprv", |v, suffix| v.len() >= 111 && is_base58(suffix)),
        ("ed25519:", |v, _| v.len() > 8),
        ("0x", |v, suffix| {
            v.len() == 66 && suffix.bytes().all(|b| b.is_ascii_hexdigit())
        }),
    ];
    KEY_PREFIXES.iter().any(|(prefix, validate)| {
        value
            .strip_prefix(prefix)
            .is_some_and(|suffix| validate(value, suffix))
    })
}

/// Check whether a string starts with a known credential prefix.
///
/// Matches AWS access keys (AKIA), GitHub tokens (ghp_, gho_, ghs_, ghr_),
/// and Stripe/OpenAI-style secrets (sk-, sk_live_, sk_test_).
/// Validates that the suffix is at least 24 ASCII alphanumeric characters.
/// Shared by sk_live_, sk_test_, and sk- credential prefixes.
fn validate_sk_suffix(_full: &str, suffix: &str) -> bool {
    suffix.len() >= 24 && suffix.bytes().all(|b| b.is_ascii_alphanumeric())
}

fn check_string_for_credential_prefix(value: &str) -> bool {
    const CREDENTIAL_PREFIXES: &[(&str, PrefixValidator)] = &[
        ("AKIA", |v, suffix| {
            v.len() == 20
                && suffix
                    .bytes()
                    .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
        }),
        ("sk_live_", validate_sk_suffix),
        ("sk_test_", validate_sk_suffix),
        ("sk-", validate_sk_suffix),
    ];
    // GitHub tokens use a 4-char prefix checked separately.
    match starts_with_github_prefix(value) {
        true => value.len() == 40 && value[4..].bytes().all(|b| b.is_ascii_alphanumeric()),
        false => CREDENTIAL_PREFIXES.iter().any(|(prefix, validate)| {
            value
                .strip_prefix(prefix)
                .is_some_and(|suffix| validate(value, suffix))
        }),
    }
}

fn starts_with_github_prefix(value: &str) -> bool {
    matches!(value.get(..4), Some("ghp_" | "gho_" | "ghs_" | "ghr_"))
}

// --- IR-based capability detection ---

/// Accumulator for building capability findings during detection.
struct FindingEmitter<'a> {
    findings: &'a mut Vec<CapabilityFinding>,
    file: &'a Arc<str>,
    origin: FindingOrigin,
    execution_context: Option<ExecutionContext>,
}

impl FindingEmitter<'_> {
    fn emit(&mut self, capability: Capability, line: usize, column: usize, evidence: &str) {
        self.findings.push(CapabilityFinding {
            capability,
            location: SourceLocation {
                file: Arc::clone(self.file),
                line,
                column: column + 1,
            },
            evidence: Arc::from(evidence),
            origin: Some(self.origin),
            language: None,
            execution_context: self.execution_context,
            reachable: None,
        });
    }

    /// Iterate IR facts, map each to a capability finding, and emit matches.
    fn emit_from_facts<'a, T: 'a>(
        &mut self,
        facts: &'a [T],
        mut mapper: impl FnMut(&'a T) -> Option<(Capability, usize, usize, &'a str)>,
    ) {
        for fact in facts {
            if let Some((capability, line, column, evidence)) = mapper(fact) {
                self.emit(capability, line, column, evidence);
            }
        }
    }
}

/// Key-material checks that are mutually exclusive (a string matches at most one).
const KEY_MATERIAL_CHECKS: &[fn(&str) -> bool] = &[
    check_string_for_hex_key,
    check_string_for_base58_key,
    check_string_for_key_prefix,
    check_string_for_credential_prefix,
];

type StringLiteralCheck = (fn(&str) -> bool, Capability);

const STRING_LITERAL_CHECKS: &[StringLiteralCheck] = &[
    (check_string_for_endpoint, Capability::Network),
    (check_string_for_pem, Capability::Crypto),
];

/// Scan all IR facts for capability usage and produce a profile.
///
/// When `execution_context` is `Some`, every finding is tagged with that context
/// (e.g., `BuildHook` for `build.rs`).
pub fn detect_capabilities(
    ir: &FileIr,
    execution_context: Option<ExecutionContext>,
) -> CapabilityProfile {
    let file_path = &ir.file_path;
    let mut findings = Vec::new();

    detect_use_paths(ir, file_path, execution_context, &mut findings);
    detect_unsafe_sites(ir, file_path, execution_context, &mut findings);
    detect_extern_blocks(ir, file_path, execution_context, &mut findings);
    detect_attributes(ir, file_path, execution_context, &mut findings);
    detect_string_literals(ir, file_path, execution_context, &mut findings);

    CapabilityProfile {
        findings: findings.into_boxed_slice(),
    }
}

fn detect_use_paths(
    ir: &FileIr,
    file_path: &Arc<str>,
    execution_context: Option<ExecutionContext>,
    findings: &mut Vec<CapabilityFinding>,
) {
    let mut emitter = FindingEmitter {
        findings,
        file: file_path,
        origin: FindingOrigin::Import,
        execution_context,
    };
    emitter.emit_from_facts(&ir.use_paths, |use_path| {
        resolve_capabilities(&use_path.path).map(|cap| {
            (
                cap,
                use_path.span.line,
                use_path.span.column,
                use_path.path.as_ref(),
            )
        })
    });
}

fn detect_unsafe_sites(
    ir: &FileIr,
    file_path: &Arc<str>,
    execution_context: Option<ExecutionContext>,
    findings: &mut Vec<CapabilityFinding>,
) {
    let mut emitter = FindingEmitter {
        findings,
        file: file_path,
        origin: FindingOrigin::CodeSite,
        execution_context,
    };
    emitter.emit_from_facts(&ir.unsafe_sites, |site| {
        Some((
            Capability::UnsafeCode,
            site.span.line,
            site.span.column,
            site.evidence.as_ref(),
        ))
    });
}

fn detect_extern_blocks(
    ir: &FileIr,
    file_path: &Arc<str>,
    execution_context: Option<ExecutionContext>,
    findings: &mut Vec<CapabilityFinding>,
) {
    let mut emitter = FindingEmitter {
        findings,
        file: file_path,
        origin: FindingOrigin::CodeSite,
        execution_context,
    };
    emitter.emit_from_facts(&ir.extern_blocks, |block| {
        Some((
            Capability::Ffi,
            block.span.line,
            block.span.column,
            "extern block",
        ))
    });
}

fn detect_attributes(
    ir: &FileIr,
    file_path: &Arc<str>,
    execution_context: Option<ExecutionContext>,
    findings: &mut Vec<CapabilityFinding>,
) {
    let mut emitter = FindingEmitter {
        findings,
        file: file_path,
        origin: FindingOrigin::Attribute,
        execution_context,
    };
    emitter.emit_from_facts(&ir.attributes, |attr| {
        let (cap, evidence) = match &*attr.name {
            "link" => (Capability::Ffi, "#[link]"),
            "proc_macro" => (Capability::ProcMacro, "#[proc_macro]"),
            "proc_macro_derive" => (Capability::ProcMacro, "#[proc_macro_derive]"),
            "proc_macro_attribute" => (Capability::ProcMacro, "#[proc_macro_attribute]"),
            _ => return None,
        };
        Some((cap, attr.span.line, attr.span.column, evidence))
    });
}

fn detect_string_literals(
    ir: &FileIr,
    file_path: &Arc<str>,
    execution_context: Option<ExecutionContext>,
    findings: &mut Vec<CapabilityFinding>,
) {
    let mut emitter = FindingEmitter {
        findings,
        file: file_path,
        origin: FindingOrigin::StringLiteral,
        execution_context,
    };
    for lit in &ir.string_literals {
        let line = lit.span.line;
        let column = lit.span.column;

        if let Some(&(_, capability)) = STRING_LITERAL_CHECKS
            .iter()
            .find(|&&(checker, _)| checker(&lit.value))
        {
            emitter.emit(capability, line, column, &lit.value);
        }
        if KEY_MATERIAL_CHECKS.iter().any(|check| check(&lit.value)) {
            let evidence = truncate_evidence(&lit.value);
            emitter.emit(Capability::Crypto, line, column, &evidence);
        }
    }
}