Skip to main content

vault_core/
composite.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Composite secrets (Phase 24.1) — one value with secrets inside it.
4//!
5//! The motivating case is a calendar-sharing URL,
6//! `https://outlook.office365.com/owa/calendar/{mailbox_id}@inf.elte.hu/{calendar_key}/calendar.ics`,
7//! where two path segments are credentials and the rest is structure. The
8//! root is the **template**; each placeholder is a **part**. Parts are
9//! ordinary `extra_vars` — see the design note in `src/ts/composite.rs`'s
10//! TypeScript twin (`src/ts/composite.ts`) for why a second array was
11//! rejected. This module renders the template against a set of parts and does
12//! nothing else: it does not know about `VaultEntry`, redaction, or `${…}`
13//! references.
14//!
15//! This is a twin pair with `src/ts/composite.ts`, pinned by
16//! `tests/fixtures/parity/composite.json` — the form needs a live preview, so
17//! rendering exists in both languages, and two implementations of one
18//! template language drift silently if nothing asserts they agree.
19//!
20//! ## Encoding — decided 2026-09-14
21//!
22//! A URL is several zones with different reserved characters, and a value
23//! inserted raw can change what the URL *means*
24//! (`postgres://app:p@ss@db/prod` parses with host `ss@db`). So: parts are
25//! stored **raw** (the vault holds the credential the issuer gave), and the
26//! renderer classifies each placeholder by the zone it sits in — from a parse
27//! of the **template text**, not of a URL built from real values — and
28//! percent-encodes accordingly. `custom` never encodes: the preview shows the
29//! encoded result, so what is copied is what was seen.
30//!
31//! The encoder implements exactly RFC 3986's unreserved set
32//! (`ALPHA / DIGIT / "-" / "." / "_" / "~"`) rather than delegating to a
33//! JS/Rust built-in — `encodeURIComponent` and this module must byte-for-byte
34//! agree, and the built-ins on the two sides do not use the same unreserved
35//! set (JS additionally leaves `! ~ * ' ( )` unescaped).
36
37use std::collections::BTreeMap;
38use std::fmt;
39
40/// What a composite template *is*, which decides its encoding and whether an
41/// Open action is offered. Open past the four presets, the same
42/// open-vocabulary reasoning as `primary_role`.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Kind {
45    /// `http(s)://` only; Open behind a confirmation; zone-aware encoding.
46    Link,
47    /// A presigned/SAS URL — same zone encoding as `Link`. Whether editing
48    /// outside the signature part is refused is a form-level rule (C10), not
49    /// a rendering one, so it is not enforced here.
50    SignedLink,
51    /// A connection string (`postgres://user:pass@host/db`) — same zone
52    /// encoding; userinfo encoding is what stops a `@`/`:` in a password from
53    /// moving the host.
54    Connection,
55    /// Not a URL. No encoding, no zone classification.
56    Custom,
57    /// An unrecognised kind string. Treated as `Custom` — the safe default,
58    /// since assuming URL structure over an unknown shape as easily
59    /// *corrupts* a rendered value as it protects one.
60    Other,
61}
62
63impl Kind {
64    pub fn parse(s: &str) -> Self {
65        match s {
66            "link" => Kind::Link,
67            "signed_link" => Kind::SignedLink,
68            "connection" => Kind::Connection,
69            "custom" => Kind::Custom,
70            _ => Kind::Other,
71        }
72    }
73
74    fn is_url_shaped(self) -> bool {
75        matches!(self, Kind::Link | Kind::SignedLink | Kind::Connection)
76    }
77}
78
79/// Where in the template a placeholder sits, decided by a parse of the
80/// template text around it — never by parsing the rendered output, which
81/// would already contain the (possibly `/`- or `@`-bearing) part value.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83enum Zone {
84    /// Before `://`, or the whole string when there is no `://` at all
85    /// (a `custom`-shaped value, or a URL-kind template with no scheme).
86    Unstructured,
87    UserInfo,
88    Host,
89    Path,
90    QueryName,
91    QueryValue,
92    Fragment,
93}
94
95/// One named `{part}` and the raw value it holds.
96#[derive(Debug, Clone)]
97pub struct Part {
98    pub key: String,
99    pub value: String,
100}
101
102/// What went wrong rendering a template. `Display` gives the user-facing text.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum RenderError {
105    /// A `{name}` with no matching part. The name is the placeholder, exactly
106    /// as it appeared in the template.
107    UnfilledPlaceholder(String),
108    /// A `{` that starts neither `{{` nor a valid `{name}` — a template typo,
109    /// not a literal brace.
110    UnbalancedBrace(usize),
111    /// A part's raw value contains a newline or control character, and the
112    /// kind is URL-shaped (link/signed_link/connection) — C6.
113    ControlCharacterInPart(String),
114}
115
116impl fmt::Display for RenderError {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        match self {
119            RenderError::UnfilledPlaceholder(name) => {
120                write!(
121                    f,
122                    "no part named \"{name}\" — the template cannot render without it"
123                )
124            }
125            RenderError::UnbalancedBrace(at) => {
126                write!(
127                    f,
128                    "unbalanced '{{' at position {at} — use '{{{{' for a literal brace"
129                )
130            }
131            RenderError::ControlCharacterInPart(name) => {
132                write!(f, "part \"{name}\" contains a newline or control character, which a URL cannot carry")
133            }
134        }
135    }
136}
137
138/// The result of a successful render: the text, and which parts were used.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Rendered {
141    pub text: String,
142    /// Placeholder names actually found in the template, in first-use order.
143    pub used: Vec<String>,
144    /// Parts supplied but never referenced by any placeholder (C8's sibling —
145    /// not an error, a health-scan-shaped warning for the caller to raise).
146    pub unused: Vec<String>,
147}
148
149/// Exactly RFC 3986's unreserved set. Deliberately not `encodeURIComponent`
150/// (JS) or `percent-encoding`'s `NON_ALPHANUMERIC` (Rust) — both leave a
151/// different, larger set unescaped than this, and the two sides must agree on
152/// every byte, not merely on "encoded enough".
153fn percent_encode(s: &str) -> String {
154    let mut out = String::with_capacity(s.len());
155    for b in s.bytes() {
156        match b {
157            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
158                out.push(b as char);
159            }
160            _ => out.push_str(&format!("%{b:02X}")),
161        }
162    }
163    out
164}
165
166fn has_control_char(s: &str) -> bool {
167    s.chars().any(|c| c.is_control())
168}
169
170/// One token of a tokenised template: either literal text or a placeholder.
171enum Token {
172    Literal(String),
173    /// `(name, byte_offset_in_template)` — the offset is what `classify_zone`
174    /// needs, and it is the offset in the *template*, before substitution.
175    Placeholder(String, usize),
176}
177
178/// Splits a template into literal and placeholder tokens, validating brace
179/// balance and placeholder-name syntax as it goes.
180fn tokenize(template: &str) -> Result<Vec<Token>, RenderError> {
181    let bytes = template.as_bytes();
182    let mut tokens = Vec::new();
183    let mut literal = String::new();
184    let mut i = 0;
185    while i < bytes.len() {
186        match bytes[i] {
187            b'{' if bytes.get(i + 1) == Some(&b'{') => {
188                literal.push('{');
189                i += 2;
190            }
191            b'}' if bytes.get(i + 1) == Some(&b'}') => {
192                literal.push('}');
193                i += 2;
194            }
195            b'{' => {
196                let start = i;
197                let close = template[i..].find('}').map(|p| p + i);
198                let close = match close {
199                    Some(c) => c,
200                    None => return Err(RenderError::UnbalancedBrace(start)),
201                };
202                let name = &template[i + 1..close];
203                if name.is_empty() || !is_valid_name(name) {
204                    return Err(RenderError::UnbalancedBrace(start));
205                }
206                if !literal.is_empty() {
207                    tokens.push(Token::Literal(std::mem::take(&mut literal)));
208                }
209                tokens.push(Token::Placeholder(name.to_string(), start));
210                i = close + 1;
211            }
212            b'}' => return Err(RenderError::UnbalancedBrace(i)),
213            _ => {
214                // Push whole UTF-8 scalar values, not raw bytes, so a
215                // multi-byte character is never split across two pushes.
216                let ch = template[i..].chars().next().unwrap();
217                literal.push(ch);
218                i += ch.len_utf8();
219            }
220        }
221    }
222    if !literal.is_empty() {
223        tokens.push(Token::Literal(literal));
224    }
225    Ok(tokens)
226}
227
228fn is_valid_name(s: &str) -> bool {
229    let mut chars = s.chars();
230    match chars.next() {
231        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
232        _ => return false,
233    }
234    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
235}
236
237/// Classifies the zone a placeholder at `at` (a byte offset into `template`)
238/// sits in, by scanning the template's own structural characters —
239/// `://`, `@`, `/`, `?`, `#`, `&`, `=` — never the rendered output.
240fn classify_zone(template: &str, at: usize) -> Zone {
241    let scheme_end = match template.find("://") {
242        Some(p) => p + 3,
243        None => return Zone::Unstructured,
244    };
245    if at < scheme_end {
246        return Zone::Unstructured;
247    }
248    // The authority region runs from the scheme to the first '/', '?' or '#'.
249    let authority_end = template[scheme_end..]
250        .find(['/', '?', '#'])
251        .map(|p| p + scheme_end)
252        .unwrap_or(template.len());
253    if at < authority_end {
254        let authority = &template[scheme_end..authority_end];
255        if let Some(at_sign) = authority.find('@') {
256            let at_sign = at_sign + scheme_end;
257            return if at < at_sign {
258                Zone::UserInfo
259            } else {
260                Zone::Host
261            };
262        }
263        return Zone::Host;
264    }
265    let query_start = template[authority_end..]
266        .find('?')
267        .map(|p| p + authority_end);
268    let fragment_start = template[authority_end..]
269        .find('#')
270        .map(|p| p + authority_end);
271    if let Some(fs) = fragment_start {
272        if at >= fs {
273            return Zone::Fragment;
274        }
275    }
276    if let Some(qs) = query_start {
277        if at >= qs {
278            let query_end = fragment_start.unwrap_or(template.len());
279            let query = &template[qs..query_end];
280            // Which '&'-delimited segment contains `at`, and is `at` before or
281            // after that segment's '='?
282            let rel = at - qs;
283            let seg_start = query[..rel].rfind('&').map(|p| p + 1).unwrap_or(0);
284            let seg_end = query[rel..]
285                .find('&')
286                .map(|p| p + rel)
287                .unwrap_or(query.len());
288            let segment = &query[seg_start..seg_end];
289            return match segment.find('=') {
290                Some(eq) if rel - seg_start > eq => Zone::QueryValue,
291                Some(_) => Zone::QueryName,
292                None => Zone::QueryName,
293            };
294        }
295    }
296    Zone::Path
297}
298
299/// Renders `template` against `parts`, refusing on any unfilled placeholder,
300/// unbalanced brace, or (for a URL-shaped kind) a control character in a part.
301///
302/// `custom` and unrecognised kinds render every placeholder raw. Every other
303/// kind percent-encodes by zone, computed from the **template's** structure —
304/// see the module doc for why that has to be the template and not the output.
305pub fn render(template: &str, parts: &[Part], kind: Kind) -> Result<Rendered, RenderError> {
306    let by_name: BTreeMap<&str, &str> = parts
307        .iter()
308        .map(|p| (p.key.as_str(), p.value.as_str()))
309        .collect();
310    let tokens = tokenize(template)?;
311
312    let mut text = String::new();
313    let mut used = Vec::new();
314    let encode = kind.is_url_shaped();
315
316    for tok in &tokens {
317        match tok {
318            Token::Literal(s) => text.push_str(s),
319            Token::Placeholder(name, at) => {
320                let value = *by_name
321                    .get(name.as_str())
322                    .ok_or_else(|| RenderError::UnfilledPlaceholder(name.clone()))?;
323                if encode && has_control_char(value) {
324                    return Err(RenderError::ControlCharacterInPart(name.clone()));
325                }
326                if !used.contains(name) {
327                    used.push(name.clone());
328                }
329                if encode {
330                    let zone = classify_zone(template, *at);
331                    text.push_str(&match zone {
332                        Zone::Unstructured => value.to_string(),
333                        Zone::UserInfo
334                        | Zone::Host
335                        | Zone::Path
336                        | Zone::QueryName
337                        | Zone::QueryValue
338                        | Zone::Fragment => percent_encode(value),
339                    });
340                } else {
341                    text.push_str(value);
342                }
343            }
344        }
345    }
346
347    let unused: Vec<String> = parts
348        .iter()
349        .map(|p| p.key.clone())
350        .filter(|k| !used.contains(k))
351        .collect();
352
353    Ok(Rendered { text, used, unused })
354}
355
356/// The placeholder names a template references, without needing any parts —
357/// used by the form to build "Make part" suggestions and by the health scan
358/// to find orphaned parts, without rendering (and therefore without needing
359/// every part filled in first).
360pub fn placeholders(template: &str) -> Result<Vec<String>, RenderError> {
361    let mut names = Vec::new();
362    for tok in tokenize(template)? {
363        if let Token::Placeholder(name, _) = tok {
364            if !names.contains(&name) {
365                names.push(name);
366            }
367        }
368    }
369    Ok(names)
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    fn part(k: &str, v: &str) -> Part {
377        Part {
378            key: k.into(),
379            value: v.into(),
380        }
381    }
382
383    #[test]
384    fn renders_a_calendar_url_with_two_parts() {
385        let tpl = "https://outlook.office365.com/owa/calendar/{mailbox_id}@inf.elte.hu/{calendar_key}/calendar.ics";
386        let r = render(
387            tpl,
388            &[
389                part("mailbox_id", "js.doe"),
390                part("calendar_key", "abc-123"),
391            ],
392            Kind::Link,
393        )
394        .unwrap();
395        assert_eq!(
396            r.text,
397            "https://outlook.office365.com/owa/calendar/js.doe@inf.elte.hu/abc-123/calendar.ics"
398        );
399        assert_eq!(r.used, vec!["mailbox_id", "calendar_key"]);
400        assert!(r.unused.is_empty());
401    }
402
403    #[test]
404    fn refuses_an_unfilled_placeholder() {
405        let err = render("https://x/{a}", &[], Kind::Link).unwrap_err();
406        assert_eq!(err, RenderError::UnfilledPlaceholder("a".into()));
407    }
408
409    #[test]
410    fn double_braces_are_literal() {
411        let r = render("{{literal}}", &[], Kind::Custom).unwrap();
412        assert_eq!(r.text, "{literal}");
413    }
414
415    #[test]
416    fn an_unbalanced_brace_is_a_form_error_not_a_literal() {
417        assert!(matches!(
418            render("https://x/{oops", &[], Kind::Link),
419            Err(RenderError::UnbalancedBrace(_))
420        ));
421    }
422
423    #[test]
424    fn one_placeholder_used_twice_is_one_part_filled_twice() {
425        // C3
426        let r = render("{tok}/x/{tok}", &[part("tok", "abc")], Kind::Custom).unwrap();
427        assert_eq!(r.text, "abc/x/abc");
428        assert_eq!(r.used, vec!["tok"]);
429    }
430
431    #[test]
432    fn a_part_no_placeholder_uses_is_reported_not_refused() {
433        let r = render("no holes here", &[part("orphan", "v")], Kind::Custom).unwrap();
434        assert_eq!(r.unused, vec!["orphan"]);
435    }
436
437    #[test]
438    fn userinfo_encoding_stops_at_and_colon_from_moving_the_host() {
439        // The motivating bug: postgres://app:p@ss@db/prod parses with host ss@db.
440        let r = render(
441            "postgres://{user}:{pass}@db.example.com/prod",
442            &[part("user", "app"), part("pass", "p@ss:word")],
443            Kind::Connection,
444        )
445        .unwrap();
446        assert_eq!(r.text, "postgres://app:p%40ss%3Aword@db.example.com/prod");
447    }
448
449    #[test]
450    fn query_value_is_encoded_and_query_name_is_too() {
451        let r = render(
452            "https://x/?{name}={value}",
453            &[
454                part("name", "a b"),
455                part("value", "bot applications.commands"),
456            ],
457            Kind::Link,
458        )
459        .unwrap();
460        assert_eq!(r.text, "https://x/?a%20b=bot%20applications.commands");
461    }
462
463    #[test]
464    fn custom_never_encodes() {
465        let r = render("{a}", &[part("a", "sp ace/slash")], Kind::Custom).unwrap();
466        assert_eq!(r.text, "sp ace/slash");
467    }
468
469    #[test]
470    fn control_character_in_a_url_shaped_part_is_refused() {
471        let err = render("https://x/{a}", &[part("a", "line\nbreak")], Kind::Link).unwrap_err();
472        assert_eq!(err, RenderError::ControlCharacterInPart("a".into()));
473    }
474
475    #[test]
476    fn control_character_in_a_custom_part_is_allowed() {
477        let r = render("{a}", &[part("a", "line\nbreak")], Kind::Custom).unwrap();
478        assert_eq!(r.text, "line\nbreak");
479    }
480
481    #[test]
482    fn placeholders_lists_names_with_no_parts_needed() {
483        assert_eq!(
484            placeholders("https://x/{a}/{b}/{a}").unwrap(),
485            vec!["a".to_string(), "b".to_string()]
486        );
487    }
488
489    #[test]
490    fn an_unknown_kind_string_behaves_like_custom() {
491        // Assuming URL structure over an unrecognised shape corrupts a value
492        // as easily as it protects one.
493        assert_eq!(Kind::parse("nonsense"), Kind::Other);
494        let r = render("{a}", &[part("a", "raw value")], Kind::parse("nonsense")).unwrap();
495        assert_eq!(r.text, "raw value");
496    }
497}