Skip to main content

cargo/diagnostics/rules/
text_direction_codepoint_in_comment.rs

1use std::path::Path;
2
3use cargo_util_terminal::report::AnnotationKind;
4use cargo_util_terminal::report::Group;
5use cargo_util_terminal::report::Level;
6use cargo_util_terminal::report::Snippet;
7use toml_parser::Source;
8use toml_parser::Span;
9use toml_parser::decoder::Encoding;
10use toml_parser::parser::Event;
11use toml_parser::parser::EventKind;
12use toml_parser::parser::EventReceiver;
13use tracing::instrument;
14
15use super::CORRECTNESS;
16use crate::CargoResult;
17use crate::GlobalContext;
18use crate::core::MaybePackage;
19use crate::core::Workspace;
20use crate::diagnostics::Lint;
21use crate::diagnostics::LintLevelProduct;
22use crate::diagnostics::ManifestFor;
23use crate::diagnostics::ScopedDiagnosticStats;
24use crate::diagnostics::workspace_rel_path;
25
26pub static LINT: &Lint = &Lint {
27    name: "text_direction_codepoint_in_comment",
28    desc: "unicode codepoint changing visible direction of text present in comment",
29    primary_group: &CORRECTNESS,
30    msrv: Some(super::CARGO_LINTS_MSRV),
31    feature_gate: None,
32    docs: Some(
33        r#"
34### What it does
35Detects Unicode codepoints in manifest comments that change the visual representation of text on screen
36in a way that does not correspond to their on memory representation.
37
38### Why it is bad
39Unicode allows changing the visual flow of text on screen
40in order to support scripts that are written right-to-left,
41but a specially crafted comment can make code that will be compiled appear to be part of a comment,
42depending on the software used to read the code.
43To avoid potential problems or confusion,
44such as in CVE-2021-42574,
45by default we deny their use.
46"#,
47    ),
48};
49
50#[instrument(skip_all)]
51pub(crate) fn lint_manifest(
52    ws: &Workspace<'_>,
53    manifest: ManifestFor<'_>,
54    manifest_path: &Path,
55    level: LintLevelProduct,
56    pkg_stats: &mut ScopedDiagnosticStats<'_>,
57    gctx: &GlobalContext,
58) -> CargoResult<()> {
59    let LintLevelProduct {
60        level: lint_level,
61        source,
62    } = level;
63
64    if matches!(
65        &manifest,
66        ManifestFor::Workspace {
67            maybe_pkg: MaybePackage::Package { .. },
68            ..
69        }
70    ) {
71        // For real manifests, lint as a package, rather than a workspace
72        return Ok(());
73    }
74
75    let Some(contents) = manifest.contents() else {
76        return Ok(());
77    };
78
79    let bidi_spans = contents
80        .char_indices()
81        .filter(|(_i, c)| {
82            UNICODE_BIDI_CODEPOINTS
83                .iter()
84                .any(|(bidi, _name)| c == bidi)
85        })
86        .map(|(i, c)| (i, i + c.len_utf8()))
87        .collect::<Vec<_>>();
88    if bidi_spans.is_empty() {
89        return Ok(());
90    }
91
92    let events = bidi_events(contents, &bidi_spans);
93    let manifest_path = workspace_rel_path(ws, manifest_path);
94    let mut emitted_source = None;
95    for event in events {
96        let token_span = event.token.span();
97        let token_span = token_span.start()..token_span.end();
98        let mut snippet = Snippet::source(contents).path(&manifest_path).annotation(
99            AnnotationKind::Context
100                .span(token_span)
101                .label("this comment contains an invisible unicode text flow control codepoint"),
102        );
103        for bidi_span in event.bidi_spans {
104            let bidi_span = bidi_span.0..bidi_span.1;
105            let escaped = format!("{:?}", &contents[bidi_span.clone()]);
106            snippet = snippet.annotation(AnnotationKind::Primary.span(bidi_span).label(escaped));
107        }
108
109        let level = lint_level.to_diagnostic_level();
110        let mut primary = Group::with_title(level.primary_title(LINT.desc)).element(snippet);
111        if emitted_source.is_none() {
112            emitted_source = Some(LINT.emitted_source(lint_level, source));
113            primary = primary.element(Level::NOTE.message(emitted_source.as_ref().unwrap()));
114        }
115
116        let report = [primary];
117
118        pkg_stats.record_lint(lint_level);
119        gctx.shell().print_report(&report, lint_level.force())?;
120    }
121
122    Ok(())
123}
124
125const UNICODE_BIDI_CODEPOINTS: &[(char, &str)] = &[
126    ('\u{202A}', "LEFT-TO-RIGHT EMBEDDING"),
127    ('\u{202B}', "RIGHT-TO-LEFT EMBEDDING"),
128    ('\u{202C}', "POP DIRECTIONAL FORMATTING"),
129    ('\u{202D}', "LEFT-TO-RIGHT OVERRIDE"),
130    ('\u{202E}', "RIGHT-TO-LEFT OVERRIDE"),
131    ('\u{2066}', "LEFT-TO-RIGHT ISOLATE"),
132    ('\u{2067}', "RIGHT-TO-LEFT ISOLATE"),
133    ('\u{2068}', "FIRST STRONG ISOLATE"),
134    ('\u{2069}', "POP DIRECTIONAL ISOLATE"),
135];
136
137struct BiDiEvent {
138    token: Event,
139    bidi_spans: Vec<(usize, usize)>,
140}
141
142fn bidi_events(contents: &str, bidi_spans: &[(usize, usize)]) -> Vec<BiDiEvent> {
143    let mut bidi_spans = bidi_spans.iter();
144    let bidi_span = bidi_spans.next().copied();
145
146    let source = Source::new(contents);
147    let tokens = source.lex().into_vec();
148    let mut collector = BiDiCollector {
149        bidi_span,
150        bidi_spans,
151        events: Vec::new(),
152    };
153    let mut errors = ();
154    toml_parser::parser::parse_document(&tokens, &mut collector, &mut errors);
155
156    collector.events
157}
158
159struct BiDiCollector<'b> {
160    bidi_span: Option<(usize, usize)>,
161    bidi_spans: std::slice::Iter<'b, (usize, usize)>,
162    events: Vec<BiDiEvent>,
163}
164
165impl BiDiCollector<'_> {
166    fn process(&mut self, kind: EventKind, encoding: Option<Encoding>, span: Span) {
167        let mut event_bidi_spans = Vec::new();
168        while let Some(bidi_span) = self.bidi_span {
169            if bidi_span.0 < span.start() {
170                self.bidi_span = self.bidi_spans.next().copied();
171                continue;
172            } else if span.end() <= bidi_span.0 {
173                break;
174            }
175
176            event_bidi_spans.push(bidi_span);
177            self.bidi_span = self.bidi_spans.next().copied();
178        }
179
180        if !event_bidi_spans.is_empty() {
181            let token = Event::new_unchecked(kind, encoding, span);
182            self.events.push(BiDiEvent {
183                token,
184                bidi_spans: event_bidi_spans,
185            });
186        }
187    }
188}
189
190impl EventReceiver for BiDiCollector<'_> {
191    fn comment(&mut self, span: Span, _error: &mut dyn toml_parser::ErrorSink) {
192        self.process(EventKind::Comment, None, span)
193    }
194}