Skip to main content

cargo/diagnostics/rules/
text_direction_codepoint_in_literal.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::Patch;
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::diagnostics::Lint;
20use crate::diagnostics::LintLevelProduct;
21use crate::diagnostics::ManifestFor;
22use crate::diagnostics::ScopedDiagnosticStats;
23use crate::diagnostics::workspace_rel_path;
24use crate::workspace::MaybePackage;
25use crate::workspace::Workspace;
26
27pub static LINT: &Lint = &Lint {
28    name: "text_direction_codepoint_in_literal",
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 literals in manifests that change the visual representation of text on screen
36in a way that does not correspond to their on memory representation.
37
38### Why is this 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 literal can make code that will be compiled appear to be part of a literal,
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 toml_source = Source::new(contents);
93    let events = bidi_events(&toml_source, &bidi_spans);
94    let manifest_path = workspace_rel_path(ws, manifest_path);
95    let mut emitted_source = None;
96    for event in events {
97        let token_span = event.token.span();
98        let token_span = token_span.start()..token_span.end();
99        let mut snippet = Snippet::source(contents).path(&manifest_path).annotation(
100            AnnotationKind::Context
101                .span(token_span.clone())
102                .label("this literal contains an invisible unicode text flow control codepoint"),
103        );
104        for bidi_span in event.bidi_spans {
105            let bidi_span = bidi_span.0..bidi_span.1;
106            let escaped = format!("{:?}", &contents[bidi_span.clone()]);
107            snippet = snippet.annotation(AnnotationKind::Primary.span(bidi_span).label(escaped));
108        }
109        let mut help_snippet = Snippet::source(contents).path(&manifest_path);
110        if let Some(original_raw) = toml_source.get(&event.token) {
111            let mut decoded = String::new();
112            let replacement = match event.token.kind() {
113                toml_parser::parser::EventKind::SimpleKey => {
114                    use toml_writer::ToTomlKey as _;
115                    original_raw.decode_key(&mut decoded, &mut ());
116                    let builder = toml_writer::TomlKeyBuilder::new(&decoded);
117                    let replacement = builder.as_basic();
118                    Some(replacement.to_toml_key())
119                }
120                toml_parser::parser::EventKind::Scalar => {
121                    use toml_writer::ToTomlValue as _;
122                    let kind = original_raw.decode_scalar(&mut decoded, &mut ());
123                    if matches!(kind, toml_parser::decoder::ScalarKind::String) {
124                        let builder = toml_writer::TomlStringBuilder::new(&decoded);
125                        let replacement = match event.token.encoding() {
126                            Some(toml_parser::decoder::Encoding::BasicString)
127                            | Some(toml_parser::decoder::Encoding::LiteralString)
128                            | None => builder.as_basic(),
129                            Some(toml_parser::decoder::Encoding::MlBasicString)
130                            | Some(toml_parser::decoder::Encoding::MlLiteralString) => {
131                                builder.as_ml_basic()
132                            }
133                        };
134                        Some(replacement.to_toml_value())
135                    } else {
136                        None
137                    }
138                }
139                _ => None,
140            };
141            if let Some(mut replacement) = replacement {
142                for (bidi, escaped, _) in UNICODE_BIDI_CODEPOINTS {
143                    replacement = replacement.replace(*bidi, escaped);
144                }
145                help_snippet = help_snippet.patch(Patch::new(token_span.clone(), replacement));
146            }
147        }
148
149        let level = lint_level.to_diagnostic_level();
150        let mut primary = Group::with_title(level.primary_title(
151            "unicode codepoint changing visible direction of text present in literal",
152        ))
153        .element(snippet);
154        if emitted_source.is_none() {
155            emitted_source = Some(LINT.emitted_source(lint_level, source));
156            primary = primary.element(Level::NOTE.message(emitted_source.as_ref().unwrap()));
157        }
158
159        let help = Group::with_title(Level::HELP.secondary_title("if you want to keep them but make them visible in your source code, you can escape them")).element(help_snippet);
160
161        let report = [primary, help];
162
163        pkg_stats.record_lint(lint_level);
164        gctx.shell().print_report(&report, lint_level.force())?;
165    }
166
167    Ok(())
168}
169
170const UNICODE_BIDI_CODEPOINTS: &[(char, &str, &str)] = &[
171    ('\u{202A}', r"\u{202A}", "LEFT-TO-RIGHT EMBEDDING"),
172    ('\u{202B}', r"\u{202B}", "RIGHT-TO-LEFT EMBEDDING"),
173    ('\u{202C}', r"\u{202C}", "POP DIRECTIONAL FORMATTING"),
174    ('\u{202D}', r"\u{202D}", "LEFT-TO-RIGHT OVERRIDE"),
175    ('\u{202E}', r"\u{202E}", "RIGHT-TO-LEFT OVERRIDE"),
176    ('\u{2066}', r"\u{2066}", "LEFT-TO-RIGHT ISOLATE"),
177    ('\u{2067}', r"\u{2067}", "RIGHT-TO-LEFT ISOLATE"),
178    ('\u{2068}', r"\u{2068}", "FIRST STRONG ISOLATE"),
179    ('\u{2069}', r"\u{2069}", "POP DIRECTIONAL ISOLATE"),
180];
181
182struct BiDiEvent {
183    token: Event,
184    bidi_spans: Vec<(usize, usize)>,
185}
186
187fn bidi_events(source: &Source<'_>, bidi_spans: &[(usize, usize)]) -> Vec<BiDiEvent> {
188    let mut bidi_spans = bidi_spans.iter();
189    let bidi_span = bidi_spans.next().copied();
190
191    let tokens = source.lex().into_vec();
192    let mut collector = BiDiCollector {
193        bidi_span,
194        bidi_spans,
195        events: Vec::new(),
196    };
197    let mut errors = ();
198    toml_parser::parser::parse_document(&tokens, &mut collector, &mut errors);
199
200    collector.events
201}
202
203struct BiDiCollector<'b> {
204    bidi_span: Option<(usize, usize)>,
205    bidi_spans: std::slice::Iter<'b, (usize, usize)>,
206    events: Vec<BiDiEvent>,
207}
208
209impl BiDiCollector<'_> {
210    fn process(&mut self, kind: EventKind, encoding: Option<Encoding>, span: Span) {
211        let mut event_bidi_spans = Vec::new();
212        while let Some(bidi_span) = self.bidi_span {
213            if bidi_span.0 < span.start() {
214                self.bidi_span = self.bidi_spans.next().copied();
215                continue;
216            } else if span.end() <= bidi_span.0 {
217                break;
218            }
219
220            event_bidi_spans.push(bidi_span);
221            self.bidi_span = self.bidi_spans.next().copied();
222        }
223
224        if !event_bidi_spans.is_empty() {
225            let token = Event::new_unchecked(kind, encoding, span);
226            self.events.push(BiDiEvent {
227                token,
228                bidi_spans: event_bidi_spans,
229            });
230        }
231    }
232}
233
234impl EventReceiver for BiDiCollector<'_> {
235    fn simple_key(
236        &mut self,
237        span: Span,
238        encoding: Option<Encoding>,
239        _error: &mut dyn toml_parser::ErrorSink,
240    ) {
241        self.process(EventKind::SimpleKey, encoding, span)
242    }
243    fn scalar(
244        &mut self,
245        span: Span,
246        encoding: Option<Encoding>,
247        _error: &mut dyn toml_parser::ErrorSink,
248    ) {
249        self.process(EventKind::Scalar, encoding, span)
250    }
251}