Skip to main content

bynk_emit/emitter/
toml_doc.rs

1//! P7.3 (#1303): a minimal typed TOML tree and printer — the one piece of
2//! R7.8 (`Artefacts` is a keyed set of typed documents, never a `String` at
3//! construction) landable ahead of `bynk-ts` (Arc B, P7.5+), since
4//! `wrangler.toml` is the one document `bynk-emit` produces that isn't
5//! TypeScript. Not a general TOML library: `TomlValue` represents exactly
6//! what `emitter::wrangler::emit_wrangler_toml` needs to build a
7//! `wrangler.toml` today, no more.
8//!
9//! [`print_toml_document`] is the *only* function in this crate that writes
10//! TOML syntax — `emit_wrangler_toml` builds a [`TomlDocument`], this module
11//! renders it. That split is what makes string-escaping a printer guarantee
12//! (every `TomlValue::Str` is escaped unconditionally, §"Decision B" of
13//! #1303) rather than a per-call-site judgement call, which is what left
14//! `wrangler.rs`'s own `name`/`binding`/`class_name` values unescaped before
15//! this — safe today only because those particular values happen to be
16//! compiler-derived identifiers that can't contain a TOML-breaking
17//! character, not because anything enforced it structurally.
18
19use std::fmt::Write as _;
20
21/// A TOML document: the root block's entries (review of #1304, finding 3 —
22/// a field set once at construction, not a `TomlBlock` a caller could
23/// accidentally `push_block` out of first position, which `push_block`
24/// itself couldn't have rejected: TOML has no marker distinguishing "the
25/// root block" from "a table block with no header" once both are just
26/// entries in the same list) followed by any number of headed blocks. Every
27/// block, printed — root included — is followed by exactly one blank line
28/// (including the last — confirmed against every current
29/// `expected/**/wrangler.toml` golden fixture, which all end in a trailing
30/// blank line).
31pub struct TomlDocument {
32    header_comment: &'static str,
33    root: Vec<TomlEntry>,
34    blocks: Vec<TomlBlock>,
35}
36
37impl TomlDocument {
38    /// `header_comment` is the leading `# …` line's text *without* the `#`
39    /// marker — [`print_toml_document`] prepends it, the same convention
40    /// [`TomlEntry::with_comment`] already used (review of #1304, finding
41    /// 2: the two used to disagree, one taking a marker-inclusive literal
42    /// and the other marker-exclusive, with nothing enforcing either).
43    pub(crate) fn new(header_comment: &'static str, root: Vec<TomlEntry>) -> Self {
44        Self {
45            header_comment,
46            root,
47            blocks: Vec::new(),
48        }
49    }
50
51    pub(crate) fn push_block(&mut self, block: TomlBlock) {
52        self.blocks.push(block);
53    }
54
55    /// Set the root `main` entry's value in place — the structural,
56    /// tree-level equivalent of the old text-based `toml_edit` patch this
57    /// replaces (P7.6, #1309, Decision E): a caller that already holds the
58    /// real tree (`bynk-strip::strip_project_to_js`) uses this instead of
59    /// printing then re-parsing just to change one field.
60    ///
61    /// Returns `false`, changing nothing, if the document has no root
62    /// `main` entry — the caller's job to treat that as an error (P7.4,
63    /// #1305's own guardrail against a silently-unpatched JS artefact whose
64    /// manifest still names the stripped `.ts` entry: this method reports
65    /// the miss, it doesn't decide it's fine).
66    #[must_use]
67    pub fn set_main(&mut self, value: impl Into<String>) -> bool {
68        for entry in &mut self.root {
69            if entry.key == "main" {
70                entry.value = TomlValue::Str(value.into());
71                return true;
72            }
73        }
74        false
75    }
76}
77
78/// One `[path]` or `[[path]]` section plus its `key = value` entries, in
79/// order. Always headed — the document's own root block is
80/// [`TomlDocument`]'s own field, not constructible as a `TomlBlock` (review
81/// of #1304, finding 3).
82pub(crate) struct TomlBlock {
83    header: TomlHeader,
84    entries: Vec<TomlEntry>,
85}
86
87enum TomlHeader {
88    Table(&'static str),
89    ArrayTable(&'static str),
90    /// #1796: `[parent.key]`, where `key` is chosen at emit time rather than
91    /// fixed by the generator (a Durable Object class name under `exports`).
92    /// The printer renders `key` bare when it is a TOML bare key and as an
93    /// escaped basic string otherwise, so a key, like a value, can't break
94    /// out of its header whatever it contains.
95    KeyedTable(&'static str, String),
96}
97
98impl TomlBlock {
99    pub(crate) fn table(path: &'static str, entries: Vec<TomlEntry>) -> Self {
100        Self {
101            header: TomlHeader::Table(path),
102            entries,
103        }
104    }
105
106    pub(crate) fn array_table(path: &'static str, entries: Vec<TomlEntry>) -> Self {
107        Self {
108            header: TomlHeader::ArrayTable(path),
109            entries,
110        }
111    }
112
113    /// `[parent.key]` — one entry of a table keyed by a runtime name, such as
114    /// `[exports.Alpha]` (#1796).
115    pub(crate) fn keyed_table(
116        parent: &'static str,
117        key: impl Into<String>,
118        entries: Vec<TomlEntry>,
119    ) -> Self {
120        Self {
121            header: TomlHeader::KeyedTable(parent, key.into()),
122            entries,
123        }
124    }
125}
126
127/// One `key = value` line, with an optional trailing `# comment` — TOML's
128/// own comment syntax, not an escape hatch; `wrangler.toml`'s one instance
129/// today is the KV namespace id's `# set at deploy time`.
130pub(crate) struct TomlEntry {
131    key: &'static str,
132    value: TomlValue,
133    comment: Option<&'static str>,
134}
135
136impl TomlEntry {
137    pub(crate) fn kv(key: &'static str, value: TomlValue) -> Self {
138        Self {
139            key,
140            value,
141            comment: None,
142        }
143    }
144
145    pub(crate) fn with_comment(key: &'static str, value: TomlValue, comment: &'static str) -> Self {
146        Self {
147            key,
148            value,
149            comment: Some(comment),
150        }
151    }
152}
153
154/// Exactly the value shapes `wrangler.toml` generation writes today — a
155/// basic string (always escaped on render, unconditionally), a bare
156/// integer, and an array (rendered as `[a, b, …]`, TOML's inline-array
157/// form). No bool, no float, no inline table, no nesting beyond one section
158/// level: none of those appear in the current output, and widening this
159/// when a real future value needs it (R8.20's deploy-time `Placeholder`,
160/// P7.4) is cheap.
161pub(crate) enum TomlValue {
162    Str(String),
163    Int(i64),
164    Array(Vec<TomlValue>),
165}
166
167impl TomlValue {
168    pub(crate) fn str(s: impl Into<String>) -> Self {
169        Self::Str(s.into())
170    }
171}
172
173/// Render `doc` to TOML text. The one function in this module — and, per
174/// this file's own module doc, in `bynk-emit`'s TOML-producing surface —
175/// that calls `write!`/`writeln!`/`format!` to build TOML syntax.
176pub fn print_toml_document(doc: &TomlDocument) -> String {
177    let mut out = String::new();
178    let _ = writeln!(out, "# {}", doc.header_comment);
179    print_entries(&mut out, &doc.root);
180    let _ = writeln!(out);
181    for block in &doc.blocks {
182        match &block.header {
183            TomlHeader::Table(path) => {
184                let _ = writeln!(out, "[{path}]");
185            }
186            TomlHeader::ArrayTable(path) => {
187                let _ = writeln!(out, "[[{path}]]");
188            }
189            TomlHeader::KeyedTable(parent, key) => {
190                let _ = writeln!(out, "[{parent}.{}]", render_key(key));
191            }
192        }
193        print_entries(&mut out, &block.entries);
194        let _ = writeln!(out);
195    }
196    out
197}
198
199fn print_entries(out: &mut String, entries: &[TomlEntry]) {
200    for entry in entries {
201        let value = render_value(&entry.value);
202        match entry.comment {
203            Some(comment) => {
204                let _ = writeln!(out, "{} = {value} # {comment}", entry.key);
205            }
206            None => {
207                let _ = writeln!(out, "{} = {value}", entry.key);
208            }
209        }
210    }
211}
212
213/// A key segment, bare when TOML allows it (`A-Za-z0-9_-`, non-empty) and a
214/// quoted basic string otherwise — the same escaping [`render_value`] gives
215/// every string value.
216fn render_key(key: &str) -> String {
217    let bare = !key.is_empty()
218        && key
219            .chars()
220            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
221    if bare {
222        key.to_string()
223    } else {
224        format!("\"{}\"", escape_toml_basic_string(key))
225    }
226}
227
228fn render_value(value: &TomlValue) -> String {
229    match value {
230        TomlValue::Str(s) => format!("\"{}\"", escape_toml_basic_string(s)),
231        TomlValue::Int(n) => n.to_string(),
232        TomlValue::Array(items) => {
233            let rendered: Vec<String> = items.iter().map(render_value).collect();
234            format!("[{}]", rendered.join(", "))
235        }
236    }
237}
238
239/// Escape a source string literal for interpolation into a TOML *basic*
240/// string (the `"…"` form). Queue names and cron expressions come from user
241/// string literals, which can decode to contain `"`, `\`, newline and tab
242/// (`bynk-syntax/src/lexer.rs`) — all of which would otherwise break out of
243/// the TOML string and inject config keys. Every character we escape maps
244/// to a valid TOML compact escape; remaining control characters fall back
245/// to the `\uXXXX` form so the output is always a well-formed basic string.
246///
247/// Applied unconditionally by [`render_value`] to every [`TomlValue::Str`] —
248/// not just the values a caller happens to know are user-supplied. Relocated
249/// here from `emitter/wrangler.rs` (P7.3, #1303): escaping is the printer's
250/// job now, applied structurally to every string this module renders, not a
251/// per-call-site judgement about which particular value might need it.
252fn escape_toml_basic_string(s: &str) -> String {
253    let mut out = String::with_capacity(s.len());
254    for c in s.chars() {
255        match c {
256            '\\' => out.push_str("\\\\"),
257            '"' => out.push_str("\\\""),
258            '\n' => out.push_str("\\n"),
259            '\t' => out.push_str("\\t"),
260            '\r' => out.push_str("\\r"),
261            // Control characters have no compact TOML escape besides the ones
262            // above and must not appear raw in a basic string.
263            c if (c as u32) < 0x20 || c == '\u{7f}' => {
264                let _ = write!(out, "\\u{:04X}", c as u32);
265            }
266            c => out.push(c),
267        }
268    }
269    out
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn escape_toml_basic_string_neutralises_injection() {
278        // The trigger from the defect report: a queue name whose decoded value
279        // carries a quote + newline would otherwise close the string and inject
280        // a config key.
281        assert_eq!(
282            escape_toml_basic_string("q\nkey = \"injected"),
283            "q\\nkey = \\\"injected"
284        );
285        assert_eq!(escape_toml_basic_string("a\\b"), "a\\\\b");
286        assert_eq!(escape_toml_basic_string("a\tb"), "a\\tb");
287    }
288
289    #[test]
290    fn set_main_changes_only_the_main_entry() {
291        let mut doc = TomlDocument::new(
292            "Generated by bynkc — do not edit by hand.",
293            vec![
294                TomlEntry::kv("name", TomlValue::str("api")),
295                TomlEntry::kv("main", TomlValue::str("index.ts")),
296            ],
297        );
298        doc.push_block(TomlBlock::table(
299            "triggers",
300            vec![TomlEntry::kv(
301                "crons",
302                TomlValue::Array(vec![TomlValue::str("*/5 * * * *")]),
303            )],
304        ));
305
306        assert!(doc.set_main("index.js"));
307
308        let text = print_toml_document(&doc);
309        let parsed: toml::Table = text.parse().expect("valid TOML");
310        assert_eq!(parsed["main"].as_str(), Some("index.js"));
311        assert_eq!(parsed["name"].as_str(), Some("api"));
312        let crons = parsed["triggers"]["crons"].as_array().expect("crons");
313        assert_eq!(crons[0].as_str(), Some("*/5 * * * *"));
314    }
315
316    #[test]
317    fn set_main_reports_a_missing_root_main_entry_rather_than_swallowing_it() {
318        let mut doc = TomlDocument::new(
319            "Generated by bynkc — do not edit by hand.",
320            vec![TomlEntry::kv("name", TomlValue::str("api"))],
321        );
322        assert!(!doc.set_main("index.js"));
323        let parsed: toml::Table = print_toml_document(&doc).parse().expect("valid TOML");
324        assert!(parsed.get("main").is_none());
325    }
326
327    #[test]
328    fn escape_toml_basic_string_passes_plain_values_through() {
329        // Ordinary cron expressions and queue names are untouched.
330        assert_eq!(escape_toml_basic_string("*/5 * * * *"), "*/5 * * * *");
331        assert_eq!(escape_toml_basic_string("order-events"), "order-events");
332    }
333
334    #[test]
335    fn escape_toml_basic_string_escapes_other_control_chars() {
336        // A NUL has no compact escape and must not appear raw in a basic string.
337        assert_eq!(escape_toml_basic_string("a\u{0}b"), "a\\u0000b");
338        assert_eq!(escape_toml_basic_string("a\u{7f}b"), "a\\u007Fb");
339    }
340
341    #[test]
342    fn escaped_value_is_valid_toml_and_round_trips() {
343        // The security invariant, enforced by a real TOML parser (not a golden
344        // byte-compare): interpolating the escaped value produces a well-formed
345        // single-key table whose decoded value is *exactly* the input — no
346        // injected keys, no broken string. Covers the injection payload from the
347        // defect report plus a control char that takes the `\uXXXX` fallback.
348        for input in ["q\nkey = \"injected", "*/5 * * * *\\\"", "a\u{0}b\ttail"] {
349            let doc = format!("queue = \"{}\"", escape_toml_basic_string(input));
350            let table: toml::Table = doc
351                .parse()
352                .unwrap_or_else(|e| panic!("escaped {input:?} is invalid TOML: {e} ({doc:?})"));
353            assert_eq!(
354                table.len(),
355                1,
356                "escaped {input:?} injected extra keys: {table:?}"
357            );
358            assert_eq!(
359                table["queue"].as_str(),
360                Some(input),
361                "escaped {input:?} did not round-trip"
362            );
363        }
364    }
365
366    #[test]
367    fn print_toml_document_renders_a_representative_document_and_round_trips() {
368        // Not a golden byte-compare (that's `bless_positive_fixtures`'s job) —
369        // this proves the printer's *general* shape (root block, a `[[…]]`
370        // array table, a `[…]` table, an array value, a commented entry) is
371        // well-formed TOML a real parser accepts, with every value surviving
372        // exactly. `TomlBlock`/`TomlEntry` construction mirrors
373        // `emit_wrangler_toml`'s own shape one-for-one.
374        //
375        // Review of #1304, finding 1: the `name` and the one `crons` element
376        // below are the injection payload from the defect report, not an
377        // ordinary identifier — every value the *golden* corpus carries today
378        // is compiler-derived and never needs escaping, which means a
379        // zero-diff `bless_positive_fixtures` run cannot tell an escaping
380        // `render_value` from a `render_value` that stopped escaping
381        // entirely. This is the one test standing between "the printer
382        // escapes every string" (this module's whole point) and that claim
383        // quietly going false — it has to drive a hostile value *through*
384        // `print_toml_document`, not just through `escape_toml_basic_string`
385        // directly (the tests above) or a hand-built fragment (the test
386        // below).
387        let hostile = "q\nkey = \"injected";
388        let mut doc = TomlDocument::new(
389            "Generated by bynkc — do not edit by hand.",
390            vec![
391                TomlEntry::kv("name", TomlValue::str(hostile)),
392                TomlEntry::kv("main", TomlValue::str("index.ts")),
393            ],
394        );
395        doc.push_block(TomlBlock::array_table(
396            "services",
397            vec![
398                TomlEntry::kv("binding", TomlValue::str("COMMERCE_PAYMENT")),
399                TomlEntry::kv("service", TomlValue::str("commerce-payment")),
400            ],
401        ));
402        doc.push_block(TomlBlock::array_table(
403            "kv_namespaces",
404            vec![
405                TomlEntry::kv("binding", TomlValue::str("BYNK_KV")),
406                TomlEntry::with_comment(
407                    "id",
408                    TomlValue::str("<KV_NAMESPACE_ID>"),
409                    "set at deploy time",
410                ),
411            ],
412        ));
413        doc.push_block(TomlBlock::table(
414            "triggers",
415            vec![TomlEntry::kv(
416                "crons",
417                TomlValue::Array(vec![TomlValue::str("*/5 * * * *"), TomlValue::str(hostile)]),
418            )],
419        ));
420
421        let text = print_toml_document(&doc);
422        let parsed: toml::Table = text
423            .parse()
424            .unwrap_or_else(|e| panic!("printer produced invalid TOML: {e}\n{text}"));
425
426        assert_eq!(
427            parsed.len(),
428            5,
429            "the hostile `name` value injected extra root keys: {parsed:?}"
430        );
431        assert_eq!(parsed["name"].as_str(), Some(hostile));
432        assert_eq!(parsed["main"].as_str(), Some("index.ts"));
433        let services = parsed["services"].as_array().expect("services array");
434        assert_eq!(services.len(), 1);
435        assert_eq!(services[0]["binding"].as_str(), Some("COMMERCE_PAYMENT"));
436        let kv = parsed["kv_namespaces"].as_array().expect("kv array");
437        assert_eq!(kv[0]["id"].as_str(), Some("<KV_NAMESPACE_ID>"));
438        let crons = parsed["triggers"]["crons"].as_array().expect("crons array");
439        assert_eq!(crons.len(), 2, "the hostile crons element broke the array");
440        assert_eq!(crons[0].as_str(), Some("*/5 * * * *"));
441        assert_eq!(crons[1].as_str(), Some(hostile));
442
443        // Every block, including the last, is followed by exactly one blank
444        // line — the shape every current golden `wrangler.toml` fixture has.
445        assert!(text.ends_with("\n\n"));
446    }
447
448    #[test]
449    fn keyed_table_keys_are_bare_when_they_can_be_and_quoted_otherwise() {
450        // #1796: `[exports.<Class>]`. A Bynk class name is always a bare key
451        // (`__EventsFanout` included), but the printer, not the caller, owns
452        // that guarantee, so a hostile key must stay inside its header too.
453        let hostile = "a.b]\nx = \"y";
454        let mut doc = TomlDocument::new("t", vec![]);
455        for key in ["Alpha", "__EventsFanout", hostile] {
456            doc.push_block(TomlBlock::keyed_table(
457                "exports",
458                key,
459                vec![TomlEntry::kv("type", TomlValue::str("durable-object"))],
460            ));
461        }
462        let text = print_toml_document(&doc);
463        assert!(text.contains("[exports.Alpha]\n"), "{text}");
464        assert!(text.contains("[exports.__EventsFanout]\n"), "{text}");
465
466        let parsed: toml::Table = text
467            .parse()
468            .unwrap_or_else(|e| panic!("printer produced invalid TOML: {e}\n{text}"));
469        assert_eq!(parsed.len(), 1, "a key escaped its header: {parsed:?}");
470        let exports = parsed["exports"].as_table().expect("exports table");
471        assert_eq!(exports.len(), 3);
472        assert_eq!(exports[hostile]["type"].as_str(), Some("durable-object"));
473    }
474}