Skip to main content

cargo/diagnostics/rules/
text_direction_codepoint_in_comment.rs

1use std::path::Path;
2
3use cargo_util_schemas::manifest::TomlToolLints;
4use cargo_util_terminal::report::AnnotationKind;
5use cargo_util_terminal::report::Group;
6use cargo_util_terminal::report::Level;
7use cargo_util_terminal::report::Snippet;
8use toml_parser::Source;
9use toml_parser::Span;
10use toml_parser::decoder::Encoding;
11use toml_parser::parser::Event;
12use toml_parser::parser::EventKind;
13use toml_parser::parser::EventReceiver;
14use tracing::instrument;
15
16use super::CORRECTNESS;
17use crate::CargoResult;
18use crate::GlobalContext;
19use crate::core::MaybePackage;
20use crate::diagnostics::Lint;
21use crate::diagnostics::LintLevel;
22use crate::diagnostics::ManifestFor;
23use crate::diagnostics::rel_cwd_manifest_path;
24
25pub static LINT: &Lint = &Lint {
26    name: "text_direction_codepoint_in_comment",
27    desc: "unicode codepoint changing visible direction of text present in comment",
28    primary_group: &CORRECTNESS,
29    msrv: Some(super::CARGO_LINTS_MSRV),
30    feature_gate: None,
31    docs: Some(
32        r#"
33### What it does
34Detects Unicode codepoints in manifest comments that change the visual representation of text on screen
35in a way that does not correspond to their on memory representation.
36
37### Why it is bad
38Unicode allows changing the visual flow of text on screen
39in order to support scripts that are written right-to-left,
40but a specially crafted comment can make code that will be compiled appear to be part of a comment,
41depending on the software used to read the code.
42To avoid potential problems or confusion,
43such as in CVE-2021-42574,
44by default we deny their use.
45"#,
46    ),
47};
48
49#[instrument(skip_all)]
50pub fn text_direction_codepoint_in_comment(
51    manifest: ManifestFor<'_>,
52    manifest_path: &Path,
53    cargo_lints: &TomlToolLints,
54    error_count: &mut usize,
55    gctx: &GlobalContext,
56) -> CargoResult<()> {
57    let (lint_level, source) = manifest.lint_level(cargo_lints, LINT);
58    if lint_level == LintLevel::Allow {
59        return Ok(());
60    }
61
62    if matches!(
63        &manifest,
64        ManifestFor::Workspace {
65            maybe_pkg: MaybePackage::Package { .. },
66            ..
67        }
68    ) {
69        // For real manifests, lint as a package, rather than a workspace
70        return Ok(());
71    }
72
73    let Some(contents) = manifest.contents() else {
74        return Ok(());
75    };
76
77    let bidi_spans = contents
78        .char_indices()
79        .filter(|(_i, c)| {
80            UNICODE_BIDI_CODEPOINTS
81                .iter()
82                .any(|(bidi, _name)| c == bidi)
83        })
84        .map(|(i, c)| (i, i + c.len_utf8()))
85        .collect::<Vec<_>>();
86    if bidi_spans.is_empty() {
87        return Ok(());
88    }
89
90    let events = bidi_events(contents, &bidi_spans);
91    let manifest_path = rel_cwd_manifest_path(manifest_path, gctx);
92    let mut emitted_source = None;
93    for event in events {
94        if lint_level.is_error() {
95            *error_count += 1;
96        }
97
98        let token_span = event.token.span();
99        let token_span = token_span.start()..token_span.end();
100        let mut snippet = Snippet::source(contents).path(&manifest_path).annotation(
101            AnnotationKind::Context
102                .span(token_span)
103                .label("this comment contains an invisible unicode text flow control codepoint"),
104        );
105        for bidi_span in event.bidi_spans {
106            let bidi_span = bidi_span.0..bidi_span.1;
107            let escaped = format!("{:?}", &contents[bidi_span.clone()]);
108            snippet = snippet.annotation(AnnotationKind::Primary.span(bidi_span).label(escaped));
109        }
110
111        let level = lint_level.to_diagnostic_level();
112        let mut primary = Group::with_title(level.primary_title(LINT.desc)).element(snippet);
113        if emitted_source.is_none() {
114            emitted_source = Some(LINT.emitted_source(lint_level, source));
115            primary = primary.element(Level::NOTE.message(emitted_source.as_ref().unwrap()));
116        }
117
118        let report = [primary];
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}