auditmysite 1.4.0

Resource-efficient WCAG 2.1 AA (+ select 2.2 criteria) Accessibility Checker in Rust
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! WCAG Types - Common types for WCAG rule checking
//!
//! Defines violations, severities, WCAG levels, and rule metadata.

use chromiumoxide::Page;
use serde::{Deserialize, Serialize};
use tracing::warn;

use crate::cli::WcagLevel;

// Re-export Severity from taxonomy module (single source of truth)
pub use crate::taxonomy::Severity;

/// Confidence level of a WCAG finding.
///
/// Distinguishes between definitive violations detected by the accessibility
/// tree and heuristic suspicions that require human verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum FindingKind {
    /// Automated check detected a concrete problem.
    #[default]
    Violation,
    /// Heuristic suspicion — automated tool cannot definitively confirm without
    /// behavioral testing (e.g. interactive-role without `focusable` attribute).
    Warning,
    /// Good accessibility pattern actively detected (skip link, main landmark,
    /// semantic structure). Surfaced for transparency, not as a problem.
    Positive,
    /// WCAG criterion exists but cannot be evaluated without human interaction
    /// (e.g. cognitive load, timed content, screen-reader behavior).
    NotTestable,
}

/// Machine-readable provenance for a single WCAG finding (issue #52).
///
/// `source` uses the same vocabulary as `assessment::EvidenceSource` but as a
/// plain string to avoid a circular crate dependency. Values: `"ax_tree"`,
/// `"dom_attribute"`, `"meta"`, `"css_property"`, `"http_header"`, `"computed"`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViolationEvidence {
    pub source: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
}

impl ViolationEvidence {
    pub fn ax_tree(value: impl Into<String>) -> Self {
        Self {
            source: "ax_tree".to_string(),
            field: None,
            value: Some(value.into()),
        }
    }

    pub fn dom_attribute(field: impl Into<String>, value: Option<String>) -> Self {
        Self {
            source: "dom_attribute".to_string(),
            field: Some(field.into()),
            value,
        }
    }

    /// A value derived from a live measurement (e.g. contrast ratio) rather
    /// than read directly off the DOM. Canonical English, JSON-safe (#406).
    pub fn computed(field: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            source: "computed".to_string(),
            field: Some(field.into()),
            value: Some(value.into()),
        }
    }
}

/// A WCAG violation found during audit
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Violation {
    /// The WCAG rule that was violated (e.g., "1.1.1")
    pub rule: String,
    /// Human-readable rule name
    pub rule_name: String,
    /// WCAG conformance level (A, AA, AAA)
    pub level: WcagLevel,
    /// Severity of the violation
    pub severity: Severity,
    /// Description of the violation
    pub message: String,
    /// The AXTree node ID that has the violation
    pub node_id: String,
    /// The element's role
    pub role: Option<String>,
    /// The element's accessible name (if any)
    pub name: Option<String>,
    /// HTML selector or description for locating the element
    pub selector: Option<String>,
    /// Suggested fix for the violation
    pub fix_suggestion: Option<String>,
    /// Link to WCAG documentation
    pub help_url: Option<String>,
    /// Stable axe-core-compatible rule ID (e.g., "landmark-one-main", "aria-required-attr")
    #[serde(default)]
    pub rule_id: Option<String>,
    /// Rule tags (e.g., ["wcag2a", "wcag412", "best-practice"])
    #[serde(default)]
    pub tags: Vec<String>,
    /// Impact level in axe-core terms: "critical", "serious", "moderate", "minor"
    #[serde(default)]
    pub impact: Option<String>,
    /// Raw outer HTML of the problematic element (fetched from live DOM during enrichment)
    #[serde(default)]
    pub html_snippet: Option<String>,
    /// Concrete code fix — the corrected HTML showing how the element should look
    #[serde(default)]
    pub suggested_code: Option<String>,
    /// Confidence level: whether this is a definitive violation, a heuristic
    /// warning, a positive signal, or an untestable criterion (issue #36).
    #[serde(default)]
    pub kind: FindingKind,
    /// Machine-readable provenance for this finding (issue #52).
    /// Populated incrementally — not all violations carry evidence yet.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<ViolationEvidence>,
    /// Cropped element screenshot captured during enrichment (evidence-grade
    /// findings). In-memory only — never part of the JSON report or cache.
    #[serde(skip)]
    pub evidence_screenshot: Option<Vec<u8>>,
    /// Which viewport pass produced `evidence_screenshot` ("desktop"/"mobile"),
    /// used to label the crop's caption in the PDF. In-memory only.
    #[serde(skip)]
    pub evidence_viewport: Option<&'static str>,
}

impl Violation {
    /// Create a new violation
    pub fn new(
        rule: impl Into<String>,
        rule_name: impl Into<String>,
        level: WcagLevel,
        severity: Severity,
        message: impl Into<String>,
        node_id: impl Into<String>,
    ) -> Self {
        let sev = severity;
        let impact = Some(Self::severity_to_impact(sev).to_string());
        Self {
            rule: rule.into(),
            rule_name: rule_name.into(),
            level,
            severity,
            message: message.into(),
            node_id: node_id.into(),
            role: None,
            name: None,
            selector: None,
            fix_suggestion: None,
            help_url: None,
            rule_id: None,
            tags: Vec::new(),
            impact,
            html_snippet: None,
            suggested_code: None,
            kind: FindingKind::Violation,
            evidence: Vec::new(),
            evidence_screenshot: None,
            evidence_viewport: None,
        }
    }

    /// Convert severity to axe-core impact string
    fn severity_to_impact(severity: Severity) -> &'static str {
        match severity {
            Severity::Critical => "critical",
            Severity::High => "serious",
            Severity::Medium => "moderate",
            Severity::Low => "minor",
        }
    }

    /// Derive impact string from the violation's current severity
    pub fn impact_str(&self) -> &str {
        Self::severity_to_impact(self.severity)
    }

    /// Add element role
    pub fn with_role(mut self, role: Option<String>) -> Self {
        self.role = role;
        self
    }

    /// Add element name
    pub fn with_name(mut self, name: Option<String>) -> Self {
        self.name = name;
        self
    }

    /// Add selector
    pub fn with_selector(mut self, selector: impl Into<String>) -> Self {
        self.selector = Some(selector.into());
        self
    }

    /// Add fix suggestion
    pub fn with_fix(mut self, fix: impl Into<String>) -> Self {
        self.fix_suggestion = Some(fix.into());
        self
    }

    /// Add help URL
    pub fn with_help_url(mut self, url: impl Into<String>) -> Self {
        self.help_url = Some(url.into());
        self
    }

    /// Set the stable axe-core-compatible rule ID
    pub fn with_rule_id(mut self, id: impl Into<String>) -> Self {
        self.rule_id = Some(id.into());
        self
    }

    /// Set rule tags
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set raw HTML snippet of the affected element
    pub fn with_html_snippet(mut self, snippet: impl Into<String>) -> Self {
        self.html_snippet = Some(snippet.into());
        self
    }

    /// Set the concrete code fix
    pub fn with_suggested_code(mut self, code: impl Into<String>) -> Self {
        self.suggested_code = Some(code.into());
        self
    }

    /// Override the default finding kind (defaults to `Violation`).
    pub fn with_kind(mut self, kind: FindingKind) -> Self {
        self.kind = kind;
        self
    }

    /// Convenience: mark as a heuristic warning rather than a confirmed violation.
    pub fn with_evidence_item(mut self, ev: ViolationEvidence) -> Self {
        self.evidence.push(ev);
        self
    }

    pub fn as_warning(self) -> Self {
        self.with_kind(FindingKind::Warning)
    }

    /// Convenience: mark as a positive signal (good pattern detected).
    pub fn as_positive(self) -> Self {
        self.with_kind(FindingKind::Positive)
    }
}

/// Internal marker returned by page rules when their browser-side measurement
/// could not be executed. `run_rules` consumes the marker into a failed
/// [`RuleOutcome`] instead of treating the empty result as a clean check.
pub fn technical_rule_failure(rule: &RuleMetadata, reason_code: &str) -> Violation {
    Violation::new(
        rule.id,
        rule.name,
        rule.level,
        Severity::Low,
        "The automated rule could not be evaluated.",
        "document",
    )
    .with_rule_id(rule.axe_id)
    .with_tags(vec![
        "audit-execution-failed".to_string(),
        format!("reason:{reason_code}"),
    ])
    .with_kind(FindingKind::NotTestable)
}

/// Variant for composite DOM checks whose table entry, rather than one
/// `RuleMetadata`, owns the public rule identifier.
pub fn technical_rule_failure_for(rule_id: &str, level: WcagLevel, reason_code: &str) -> Violation {
    Violation::new(
        rule_id,
        "Automated page check",
        level,
        Severity::Low,
        "The automated rule could not be evaluated.",
        "document",
    )
    .with_rule_id(rule_id)
    .with_tags(vec![
        "audit-execution-failed".to_string(),
        format!("reason:{reason_code}"),
    ])
    .with_kind(FindingKind::NotTestable)
}

/// Outcome of evaluating a rule's JS on the page, before it's turned into
/// the caller-specific `Violation` shape (`&RuleMetadata` vs. bare
/// `rule_id`/`level`) by [`evaluate_or_fail`]/[`evaluate_or_fail_for`].
enum EvalFailure {
    PageError(chromiumoxide::error::CdpError),
    MissingValue,
}

/// Shared prefix of [`evaluate_or_fail`]/[`evaluate_or_fail_for`]: evaluate
/// `js` on `page` and return its parsed value, or which of the two ways it
/// can fail. Was duplicated near-verbatim across ~20 rule files before
/// being extracted once here (see #515), then duplicated a second time
/// *between* the two wrapper functions below — factored out again so the
/// two public entry points differ only in how they report a failure, not in
/// how they detect one (judge `duplicate-code`, flagged against its own fix).
async fn evaluate_and_extract(page: &Page, js: &str) -> Result<serde_json::Value, EvalFailure> {
    let result = page.evaluate(js).await.map_err(EvalFailure::PageError)?;
    result.value().cloned().ok_or(EvalFailure::MissingValue)
}

fn eval_failure_reason(err: &EvalFailure) -> &'static str {
    match err {
        EvalFailure::PageError(_) => "page_evaluation_failed",
        EvalFailure::MissingValue => "missing_evaluation_value",
    }
}

/// Common prefix of every `check_*_with_page` DOM rule: evaluate `js` on
/// `page` and return its parsed value, or the appropriate
/// [`technical_rule_failure`] as an `Err` if evaluation failed or produced
/// no value.
pub async fn evaluate_or_fail(
    page: &Page,
    rule: &RuleMetadata,
    js: &str,
) -> Result<serde_json::Value, Vec<Violation>> {
    evaluate_and_extract(page, js)
        .await
        .map_err(|err| vec![technical_rule_failure(rule, eval_failure_reason(&err))])
}

/// [`evaluate_or_fail`] variant for composite DOM checks that identify
/// themselves by a bare rule id + level rather than a [`RuleMetadata`] (see
/// [`technical_rule_failure_for`]). Also logs the evaluation error via
/// `tracing::warn`, matching the call sites this replaces.
pub async fn evaluate_or_fail_for(
    page: &Page,
    rule_id: &str,
    level: WcagLevel,
    js: &str,
) -> Result<serde_json::Value, Vec<Violation>> {
    evaluate_and_extract(page, js).await.map_err(|err| {
        if let EvalFailure::PageError(ref e) = err {
            warn!("{rule_id} JS failed: {e}");
        }
        vec![technical_rule_failure_for(
            rule_id,
            level,
            eval_failure_reason(&err),
        )]
    })
}

pub fn technical_failure_reason(finding: &Violation) -> Option<&str> {
    if !finding
        .tags
        .iter()
        .any(|tag| tag == "audit-execution-failed")
    {
        return None;
    }
    finding
        .tags
        .iter()
        .find_map(|tag| tag.strip_prefix("reason:"))
        .or(Some("rule_execution_failed"))
}

// Severity enum is now defined in crate::taxonomy::severity
// and re-exported above. Old variants mapping:
// Minor → Low, Moderate → Medium, Serious → High, Critical → Critical

/// Metadata for a WCAG rule
#[derive(Debug, Clone)]
pub struct RuleMetadata {
    /// WCAG success criterion (e.g., "1.1.1")
    pub id: &'static str,
    /// Human-readable name
    pub name: &'static str,
    /// WCAG conformance level
    pub level: WcagLevel,
    /// Default severity for violations
    pub severity: Severity,
    /// Brief description
    pub description: &'static str,
    /// URL to WCAG documentation
    pub help_url: &'static str,
    /// Stable axe-core-compatible ID
    pub axe_id: &'static str,
    /// Tags for this rule
    pub tags: &'static [&'static str],
}

/// Result of running all WCAG checks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WcagResults {
    /// Confirmed violations (kind = Violation).
    pub violations: Vec<Violation>,
    /// Heuristic suspicions that need human confirmation (kind = Warning).
    #[serde(default)]
    pub warnings: Vec<Violation>,
    /// Good accessibility patterns actively detected (kind = Positive).
    #[serde(default)]
    pub positives: Vec<Violation>,
    /// Criteria that cannot be evaluated automatically — require manual testing (kind = NotTestable).
    #[serde(default)]
    pub not_testables: Vec<Violation>,
    /// Number of rules that passed
    pub passes: usize,
    /// Number of elements that couldn't be checked
    pub incomplete: usize,
    /// Total nodes checked
    pub nodes_checked: usize,
    /// One execution record per automated page-level rule and viewport.
    /// This distinguishes a clean check from a check that could not run.
    #[serde(default)]
    pub rule_outcomes: Vec<RuleOutcome>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RuleOutcomeStatus {
    ViolationsFound,
    NoViolationDetected,
    Warning,
    ManualReviewRequired,
    Failed,
    Skipped,
    NotApplicable,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleOutcome {
    pub rule_id: String,
    pub status: RuleOutcomeStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wcag_criterion: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub viewport: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    #[serde(default)]
    pub finding_count: usize,
}

impl WcagResults {
    /// Create new empty results
    pub fn new() -> Self {
        Self {
            violations: Vec::new(),
            warnings: Vec::new(),
            positives: Vec::new(),
            not_testables: Vec::new(),
            passes: 0,
            incomplete: 0,
            nodes_checked: 0,
            rule_outcomes: Vec::new(),
        }
    }

    /// Add a finding. Routes to the appropriate list based on `finding.kind`.
    pub fn add_violation(&mut self, finding: Violation) {
        match finding.kind {
            FindingKind::Warning => self.warnings.push(finding),
            FindingKind::Positive => self.positives.push(finding),
            FindingKind::NotTestable => self.not_testables.push(finding),
            FindingKind::Violation => self.violations.push(finding),
        }
    }

    /// Route each finding by its kind (use instead of `.violations.extend()` for mixed vecs).
    pub fn extend_findings(&mut self, findings: Vec<Violation>) {
        for f in findings {
            self.add_violation(f);
        }
    }

    /// Add a heuristic warning directly (without `as_warning()` call on the finding).
    pub fn add_warning(&mut self, mut finding: Violation) {
        finding.kind = FindingKind::Warning;
        self.warnings.push(finding);
    }

    /// Add a positive signal directly.
    pub fn add_positive(&mut self, mut finding: Violation) {
        finding.kind = FindingKind::Positive;
        self.positives.push(finding);
    }

    /// Add a not-testable note directly.
    pub fn add_not_testable(&mut self, mut finding: Violation) {
        finding.kind = FindingKind::NotTestable;
        self.not_testables.push(finding);
    }

    /// Count violations by severity
    pub fn count_by_severity(&self, severity: Severity) -> usize {
        self.violations
            .iter()
            .filter(|v| v.severity == severity)
            .count()
    }

    /// Count violations by level
    pub fn count_by_level(&self, level: WcagLevel) -> usize {
        self.violations.iter().filter(|v| v.level == level).count()
    }

    /// Count violations for a specific WCAG rule (e.g. `"1.1.1"`).
    ///
    /// This is the single canonical way to answer "how many violations does
    /// rule X have" — other modules that need this number (e.g.
    /// `source_quality`, `page_health`'s HTML-validation display) should call
    /// this instead of independently re-filtering `violations` or, worse,
    /// re-deriving the count from a separate raw DOM probe. Two independent
    /// derivations of "the same" count is exactly what caused #574 (a report
    /// claiming both "42 images without alt" and "all images have alt text"
    /// for the same page).
    pub fn count_by_rule(&self, rule: &str) -> usize {
        self.violations.iter().filter(|v| v.rule == rule).count()
    }

    /// Get all critical violations
    pub fn critical_violations(&self) -> Vec<&Violation> {
        self.violations
            .iter()
            .filter(|v| v.severity == Severity::Critical)
            .collect()
    }

    /// Check if the page passes at a given WCAG level
    pub fn passes_level(&self, level: WcagLevel) -> bool {
        !self.violations.iter().any(|v| {
            match level {
                WcagLevel::A => v.level == WcagLevel::A,
                WcagLevel::AA => v.level == WcagLevel::A || v.level == WcagLevel::AA,
                WcagLevel::AAA => true, // AAA includes all levels
            }
        })
    }

    /// Merge results from another check
    pub fn merge(&mut self, other: WcagResults) {
        self.violations.extend(other.violations);
        self.warnings.extend(other.warnings);
        self.positives.extend(other.positives);
        self.not_testables.extend(other.not_testables);
        self.passes += other.passes;
        self.incomplete += other.incomplete;
        self.nodes_checked += other.nodes_checked;
        self.rule_outcomes.extend(other.rule_outcomes);
    }
}

impl Default for WcagResults {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_violation_builder() {
        let violation = Violation::new(
            "1.1.1",
            "Non-text Content",
            WcagLevel::A,
            Severity::High,
            "Image missing alt text",
            "node-123",
        )
        .with_role(Some("image".to_string()))
        .with_fix("Add alt attribute to the image");

        assert_eq!(violation.rule, "1.1.1");
        assert_eq!(violation.role, Some("image".to_string()));
        assert!(violation.fix_suggestion.is_some());
    }

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Critical > Severity::High);
        assert!(Severity::High > Severity::Medium);
        assert!(Severity::Medium > Severity::Low);
    }

    #[test]
    fn violation_evidence_ax_tree_constructor() {
        let ev = ViolationEvidence::ax_tree("img#logo");
        assert_eq!(ev.source, "ax_tree");
        assert_eq!(ev.value.as_deref(), Some("img#logo"));
        assert!(ev.field.is_none());
    }

    #[test]
    fn violation_evidence_dom_attribute_constructor() {
        let ev = ViolationEvidence::dom_attribute("alt", Some("".to_string()));
        assert_eq!(ev.source, "dom_attribute");
        assert_eq!(ev.field.as_deref(), Some("alt"));
        assert_eq!(ev.value.as_deref(), Some(""));
    }

    #[test]
    fn violation_evidence_dom_attribute_no_value() {
        let ev = ViolationEvidence::dom_attribute("role", None);
        assert_eq!(ev.source, "dom_attribute");
        assert!(ev.value.is_none());
    }

    #[test]
    fn violation_with_evidence_item_accumulates() {
        let v = Violation::new(
            "1.1.1",
            "Non-text Content",
            WcagLevel::A,
            Severity::High,
            "msg",
            "n1",
        )
        .with_evidence_item(ViolationEvidence::ax_tree("img.hero"))
        .with_evidence_item(ViolationEvidence::dom_attribute("alt", None));
        assert_eq!(v.evidence.len(), 2);
        assert_eq!(v.evidence[0].source, "ax_tree");
        assert_eq!(v.evidence[1].source, "dom_attribute");
    }

    #[test]
    fn violation_new_starts_with_empty_evidence() {
        let v = Violation::new(
            "2.1.1",
            "Keyboard",
            WcagLevel::A,
            Severity::High,
            "msg",
            "n1",
        );
        assert!(v.evidence.is_empty());
    }
}