permission-auditor 0.1.0

Audit a list of Chrome / Manifest V3 extension permissions against a curated risk database: every MV3 permission + host-access patterns + plain-English risk descriptions, summarized into a per-extension report. Powers the zovo.one extension security scanner.
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
//! The audit engine: turn a manifest's permission list into a structured
//! [`AuditReport`].

use crate::db::{find_permission, RiskLevel, PermissionEntry};
use crate::host::{classify_host_pattern, is_host_access_pattern, HostScope};

/// Whether a finding came from the curated named-token database or was
/// synthesised for a host match-pattern / unknown token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FindingKind {
    /// Looked up directly in [`crate::RISK_DATABASE`].
    Known,
    /// A host match-pattern synthesised by classifying its scope.
    HostPattern,
    /// An unrecognised token (private, partner, or future API). Surfaced
    /// rather than silently escalated.
    Unknown,
}

/// A single audited permission: the token, the resolved risk level, a
/// description, and where the classification came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    /// The exact manifest token that produced this finding.
    pub token: String,
    /// The risk level assigned.
    pub level: RiskLevel,
    /// Plain-English description of what the grant allows.
    pub description: String,
    /// The classification provenance.
    pub kind: FindingKind,
}

/// A complete audit of one extension's permission list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuditReport {
    /// One [`Finding`] per input token, in input order.
    pub findings: Vec<Finding>,
    /// The overall (highest) risk level across all findings.
    pub overall: RiskLevel,
    /// Count of `Critical` findings.
    pub critical_count: usize,
    /// Count of `High` findings.
    pub high_count: usize,
    /// Count of `Medium` findings.
    pub medium_count: usize,
    /// Count of `Low` findings.
    pub low_count: usize,
    /// The manifest version the audit assumed (2 = MV2, 3 = MV3, None =
    /// unspecified). Affects how `webRequest`-style permissions are
    /// interpreted and which tokens are even legal.
    pub manifest_version: Option<i64>,
}

impl AuditReport {
    /// A one-line summary suitable for a list view.
    ///
    /// ```
    /// use permission_auditor::audit;
    /// let r = audit(&["activeTab", "cookies"]);
    /// let s = r.summary();
    /// assert!(s.contains("HIGH") || s.contains("CRITICAL"));
    /// ```
    pub fn summary(&self) -> String {
        format!(
            "{} overall ({} critical, {} high, {} medium, {} low)",
            self.overall.label(),
            self.critical_count,
            self.high_count,
            self.medium_count,
            self.low_count,
        )
    }

    /// Findings at or above the given level, in input order. Useful for a
    /// "what should I worry about" view.
    pub fn findings_at_or_above(&self, level: RiskLevel) -> Vec<&Finding> {
        self.findings
            .iter()
            .filter(|f| f.level >= level)
            .collect()
    }
}

/// Audit a list of manifest permission tokens and return a structured
/// [`AuditReport`].
///
/// Accepts any iterable of string-like items (`&[&str]`, `Vec<&str>`,
/// `Vec<String>`, an array, ...). For each token:
///
/// 1. If it is in [`crate::RISK_DATABASE`], the entry's level + description
///    are used directly.
/// 2. Otherwise, if it looks like a host match-pattern, its
///    [`HostScope`] is used to assign a level (All/Scheme → Critical,
///    Scoped → Medium) and a synthesised description.
/// 3. Otherwise it is surfaced as an `Unknown` Low finding with a
///    "review manually" note — never silently escalated.
///
/// The overall report level is the highest finding's level, with one
/// escalation rule: an extension that requests **any blanket/critical host
/// access** together with **`scripting`, `debugger`, `cookies`, or
/// `webRequest`** is the canonical spyware capability set and is escalated
/// to `Critical` regardless of how the individual tokens were classified.
///
/// ```
/// use permission_auditor::{audit, RiskLevel};
///
/// // The full spyware set.
/// let r = audit(&["<all_urls>", "scripting", "cookies"]);
/// assert_eq!(r.overall, RiskLevel::Critical);
/// assert!(r.critical_count >= 1);
///
/// // Benign.
/// let r = audit(&["activeTab", "storage"]);
/// assert_eq!(r.overall, RiskLevel::Low);
/// ```
pub fn audit<I, S>(permissions: I) -> AuditReport
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    audit_with_manifest_version(permissions, None)
}

/// Like [`audit`] but also takes the manifest version, which is surfaced on
/// the report. A missing/unknown version is treated permissively (no
/// downgrades), since MV2 extensions are still in the wild and we'd rather
/// over-report than miss a `webRequest`-blocking grant.
pub fn audit_with_manifest_version<I, S>(
    permissions: I,
    manifest_version: Option<i64>,
) -> AuditReport
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut findings: Vec<Finding> = Vec::new();
    for item in permissions {
        let token = item.as_ref();
        let (finding, _scope) = classify_token(token);
        findings.push(finding);
    }

    // Aggregate counts.
    let mut critical_count = 0usize;
    let mut high_count = 0usize;
    let mut medium_count = 0usize;
    let mut low_count = 0usize;
    for f in &findings {
        match f.level {
            RiskLevel::Critical => critical_count += 1,
            RiskLevel::High => high_count += 1,
            RiskLevel::Medium => medium_count += 1,
            RiskLevel::Low => low_count += 1,
        }
    }

    // Overall = max of finding levels, escalated to Critical when the spyware
    // capability combo (broad host + code/cookie access) is present.
    let base_overall = findings
        .iter()
        .map(|f| f.level)
        .max()
        .unwrap_or(RiskLevel::Low);
    let overall = if is_spyware_capability_set(&findings) {
        RiskLevel::Critical
    } else {
        base_overall
    };

    AuditReport {
        findings,
        overall,
        critical_count,
        high_count,
        medium_count,
        low_count,
        manifest_version,
    }
}

/// Classify a single token into a [`Finding`], returning the finding plus
/// the [`HostScope`] (if it was a host pattern).
fn classify_token(token: &str) -> (Finding, HostScope) {
    // 1. Direct database hit.
    if let Some(PermissionEntry { token: _, level, description }) = find_permission(token) {
        return (
            Finding {
                token: token.to_string(),
                level: *level,
                description: description.to_string(),
                kind: FindingKind::Known,
            },
            HostScope::Unknown,
        );
    }
    // 2. Host match-pattern.
    if is_host_access_pattern(token) {
        let scope = classify_host_pattern(token);
        let (level, description) = host_finding(scope);
        return (
            Finding {
                token: token.to_string(),
                level,
                description: description.to_string(),
                kind: FindingKind::HostPattern,
            },
            scope,
        );
    }
    // 3. Unknown token.
    (
        Finding {
            token: token.to_string(),
            level: RiskLevel::Low,
            description: "This permission is not in the curated risk database. It may \
                          be a private, enterprise, partner, or future API; treat as \
                          unclassified until manually reviewed."
                .to_string(),
            kind: FindingKind::Unknown,
        },
        HostScope::Unknown,
    )
}

/// Resolve a [`HostScope`] to a risk level + description for a synthesised
/// finding. Blanket and scheme-wide patterns are Critical; scoped patterns
/// are Medium (sensitive but bounded to one site family); unknowns fall back
/// to Low.
fn host_finding(scope: HostScope) -> (RiskLevel, &'static str) {
    match scope {
        HostScope::All => (
            RiskLevel::Critical,
            "A blanket host match-pattern (e.g. <all_urls> or *://*/*). Grants the \
             extension read and script access to every site on the web — the \
             canonical spyware grant.",
        ),
        HostScope::Scheme => (
            RiskLevel::Critical,
            "A scheme-wide host match-pattern (e.g. https://*/*). Grants the \
             extension read and script access to every URL under that scheme.",
        ),
        HostScope::Scoped => (
            RiskLevel::Medium,
            "A scoped host match-pattern (e.g. *://*.example.com/*). Grants the \
             extension read and script access to the matching sites only — less \
             broad than <all_urls>, still sensitive.",
        ),
        HostScope::Unknown => (
            RiskLevel::Low,
            "An unrecognized host-pattern-shaped token. Treat as unclassified \
             until manually reviewed.",
        ),
    }
}

/// The spyware capability detector: an extension that requests arbitrary
/// host access (Critical) AND the ability to run code or read session state
/// on those hosts is, for practical purposes, a surveillance tool.
fn is_spyware_capability_set(findings: &[Finding]) -> bool {
    const CODE_OR_SESSION_TOKENS: &[&str] =
        &["scripting", "debugger", "cookies", "webRequest", "webRequestBlocking"];
    let has_broad_host = findings
        .iter()
        .any(|f| f.level == RiskLevel::Critical && f.kind == FindingKind::HostPattern)
        || findings.iter().any(|f| {
            matches!(
                f.token.as_str(),
                "<all_urls>" | "*://*/*" | "https://*/*" | "http://*/*" | "*://*"
            )
        });
    let has_code_or_session = findings
        .iter()
        .any(|f| CODE_OR_SESSION_TOKENS.contains(&f.token.as_str()));
    has_broad_host && has_code_or_session
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_input_is_low() {
        let r = audit(std::iter::empty::<&str>());
        assert_eq!(r.overall, RiskLevel::Low);
        assert!(r.findings.is_empty());
        assert_eq!(r.summary(), "LOW overall (0 critical, 0 high, 0 medium, 0 low)");
    }

    #[test]
    fn benign_permissions_are_low() {
        let r = audit(&["activeTab", "storage", "notifications"]);
        assert_eq!(r.overall, RiskLevel::Low);
        assert_eq!(r.low_count, 3);
        assert_eq!(r.critical_count, 0);
        assert_eq!(r.high_count, 0);
    }

    #[test]
    fn medium_permissions_dominate_low() {
        let r = audit(&["activeTab", "tabs", "history"]);
        assert_eq!(r.overall, RiskLevel::Medium);
        assert_eq!(r.medium_count, 2);
        assert_eq!(r.low_count, 1);
    }

    #[test]
    fn high_permissions_dominate_medium() {
        let r = audit(&["tabs", "cookies", "system.cpu"]);
        assert_eq!(r.overall, RiskLevel::High);
        assert!(r.high_count >= 2);
    }

    #[test]
    fn all_urls_alone_is_critical() {
        let r = audit(&["activeTab", "<all_urls>"]);
        assert_eq!(r.overall, RiskLevel::Critical);
        assert_eq!(r.critical_count, 1);
        let all = r.findings.iter().find(|f| f.token == "<all_urls>").unwrap();
        assert_eq!(all.level, RiskLevel::Critical);
        assert_eq!(all.kind, FindingKind::Known);
    }

    #[test]
    fn spyware_combo_escalates_to_critical() {
        // <all_urls> + scripting + cookies is the full surveillance set.
        let r = audit(&["<all_urls>", "scripting", "cookies"]);
        assert_eq!(r.overall, RiskLevel::Critical);
        assert!(r.critical_count >= 1);
        assert!(r.high_count >= 2); // scripting + cookies are High
    }

    #[test]
    fn scripting_without_host_access_stays_high() {
        // scripting alone (no host access) is High, not escalated to Critical.
        let r = audit(&["scripting"]);
        assert_eq!(r.overall, RiskLevel::High);
        assert_eq!(r.critical_count, 0);
    }

    #[test]
    fn scoped_host_pattern_is_medium() {
        let r = audit(&["https://*.example.com/*"]);
        assert_eq!(r.overall, RiskLevel::Medium);
        let f = &r.findings[0];
        assert_eq!(f.level, RiskLevel::Medium);
        assert_eq!(f.kind, FindingKind::HostPattern);
        assert!(f.description.contains("scoped"));
    }

    #[test]
    fn scheme_wildcard_pattern_is_critical() {
        let r = audit(&["ftp://*/*"]);
        // ftp://*/* is not in the database but classifies as scheme-wide.
        assert_eq!(r.overall, RiskLevel::Critical);
        let f = &r.findings[0];
        assert_eq!(f.kind, FindingKind::HostPattern);
        assert_eq!(f.level, RiskLevel::Critical);
    }

    #[test]
    fn unknown_token_is_low_not_critical() {
        let r = audit(&["somePrivateEnterpriseApi"]);
        assert_eq!(r.overall, RiskLevel::Low);
        let f = &r.findings[0];
        assert_eq!(f.level, RiskLevel::Low);
        assert_eq!(f.kind, FindingKind::Unknown);
        assert!(f.description.contains("not in the curated"));
    }

    #[test]
    fn findings_preserve_input_order() {
        let r = audit(&["cookies", "activeTab", "tabs"]);
        assert_eq!(
            r.findings.iter().map(|f| f.token.as_str()).collect::<Vec<_>>(),
            ["cookies", "activeTab", "tabs"]
        );
    }

    #[test]
    fn works_with_owned_strings() {
        let perms = vec!["activeTab".to_string(), "storage".to_string()];
        let r = audit(perms);
        assert_eq!(r.overall, RiskLevel::Low);
        assert_eq!(r.findings.len(), 2);
    }

    #[test]
    fn manifest_version_round_trips() {
        let r = audit_with_manifest_version(&["activeTab"], Some(3));
        assert_eq!(r.manifest_version, Some(3));
    }

    #[test]
    fn findings_at_or_above_filters() {
        let r = audit(&["activeTab", "tabs", "cookies", "<all_urls>"]);
        let high_or_worse = r.findings_at_or_above(RiskLevel::High);
        assert!(high_or_worse.iter().all(|f| f.level >= RiskLevel::High));
        // activeTab (Low) and tabs (Medium) excluded.
        assert!(high_or_worse.iter().all(|f| f.token != "activeTab"));
        assert!(high_or_worse.iter().all(|f| f.token != "tabs"));
        // cookies + <all_urls> present.
        assert!(high_or_worse.iter().any(|f| f.token == "cookies"));
        assert!(high_or_worse.iter().any(|f| f.token == "<all_urls>"));
    }

    #[test]
    fn summary_contains_counts_and_label() {
        let r = audit(&["activeTab", "tabs", "cookies", "<all_urls>"]);
        let s = r.summary();
        assert!(s.contains("CRITICAL"), "{}", s);
        assert!(s.contains("critical"), "{}", s);
        assert!(s.contains("high"), "{}", s);
    }

    #[test]
    fn realistic_manifest_audits_correctly() {
        // A plausible ad-blocker-shaped manifest.
        let adblock = audit(&[
            "declarativeNetRequest",
            "storage",
            "tabs",
            "activeTab",
            "*://*/*", // blanket host — Critical
        ]);
        assert_eq!(adblock.overall, RiskLevel::Critical);
        // Note: *://*/* is in the database as Critical.
        assert!(adblock.critical_count >= 1);

        // A plausible benign devtools helper.
        let helper = audit(&["activeTab", "storage", "sidePanel"]);
        assert_eq!(helper.overall, RiskLevel::Low);
    }

    #[test]
    fn full_findings_have_descriptions() {
        let r = audit(&["activeTab", "cookies", "https://*.example.com/*", "??unknown??"]);
        for f in &r.findings {
            assert!(
                f.description.len() >= 25,
                "thin description for {:?}: {}",
                f.token,
                f.description
            );
        }
    }
}