Skip to main content

vgi_cli/
shell.rs

1//! DID syntax and shell quoting for the command `vgi repo init` prints.
2//!
3//! The printed `cnm git adopt …` line is meant to be copied into a shell, so
4//! every argument in it is either DID-core-validated or a normalised
5//! resource, and is quoted anyway: a value that needs no quoting is printed
6//! bare, anything else in single quotes.
7
8use anyhow::{Result, bail};
9
10/// The prefix of a `did:scid:vh:1` identifier.
11const SCID_VH_PREFIX: &str = "did:scid:vh:1:";
12
13/// Check `did` against the DID-core `did` production (a DID, not a DID URL):
14///
15/// ```text
16/// did                = "did:" method-name ":" method-specific-id
17/// method-name        = 1*method-char          ; %x61-7A / DIGIT
18/// method-specific-id = *( *idchar ":" ) 1*idchar
19/// idchar             = ALPHA / DIGIT / "." / "-" / "_" / pct-encoded
20/// ```
21///
22/// One DID URL is admitted: a `did:scid:vh:1` identity with its `?src=`
23/// locator and no other query, path or fragment. The identity is the DID, but
24/// whoever reads these values (the repository's verifier, a stranger) needs
25/// the source to resolve it, so a bare `did:scid:vh:1` is refused here and the
26/// DID URL is required (VTI-KEY-160, VTI-KEY-163).
27pub fn check_did(field: &str, did: &str) -> Result<()> {
28    if did.starts_with(SCID_VH_PREFIX) {
29        return check_scid_did_url(field, did);
30    }
31    check_bare_did(field, did)
32}
33
34/// A `did:scid:vh:1:<scid>?src=<source>` DID URL: the DID passes the DID-core
35/// production, and `<source>` is a non-empty host and path with nothing a
36/// shell or a second query parameter could hide in.
37fn check_scid_did_url(field: &str, did_url: &str) -> Result<()> {
38    let Some((did, query)) = did_url.split_once('?') else {
39        bail!(
40            "{field} `{}` is a did:scid with no `?src=` locator; give it as \
41             `did:scid:vh:1:<scid>?src=<host>[/<path>]` so its log can be found",
42            did_url.escape_debug()
43        );
44    };
45    check_bare_did(field, did)?;
46    let src_ok = query.strip_prefix("src=").is_some_and(|src| {
47        !src.is_empty()
48            && src.len() <= 2048
49            && !src.starts_with('/')
50            && src.bytes().all(|b| {
51                b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'/' | b':' | b'%')
52            })
53    });
54    if !src_ok {
55        bail!(
56            "{field} `{}` is not a did:scid DID URL (expected \
57             `did:scid:vh:1:<scid>?src=<host>[/<path>]`, with no other query or fragment)",
58            did_url.escape_debug()
59        );
60    }
61    Ok(())
62}
63
64fn check_bare_did(field: &str, did: &str) -> Result<()> {
65    let bad = || -> Result<()> {
66        bail!(
67            "{field} `{}` is not a DID (expected `did:<method>:<method-specific-id>`, \
68             DID-core syntax, no path, query or fragment)",
69            did.escape_debug()
70        )
71    };
72    let Some(rest) = did.strip_prefix("did:") else {
73        return bad();
74    };
75    let Some((method, id)) = rest.split_once(':') else {
76        return bad();
77    };
78    if method.is_empty()
79        || !method
80            .bytes()
81            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
82    {
83        return bad();
84    }
85    // The last segment must be non-empty; earlier ones may be empty.
86    if id.is_empty() || id.ends_with(':') || did.len() > 2048 {
87        return bad();
88    }
89    let bytes = id.as_bytes();
90    let mut i = 0;
91    while i < bytes.len() {
92        match bytes[i] {
93            b'%' => {
94                let hex = |j: usize| bytes.get(j).is_some_and(u8::is_ascii_hexdigit);
95                if !(hex(i + 1) && hex(i + 2)) {
96                    return bad();
97                }
98                i += 3;
99            }
100            b if b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':') => i += 1,
101            _ => return bad(),
102        }
103    }
104    Ok(())
105}
106
107/// Quote `arg` for a POSIX shell: bare when every character is one no shell
108/// treats specially, otherwise in single quotes (a `'` inside becoming
109/// `'\''`).
110pub fn quote(arg: &str) -> String {
111    let safe = !arg.is_empty()
112        && arg.bytes().all(|b| {
113            b.is_ascii_alphanumeric()
114                || matches!(
115                    b,
116                    b'_' | b'@' | b'%' | b'+' | b'=' | b':' | b',' | b'.' | b'/' | b'-'
117                )
118        });
119    if safe {
120        arg.to_string()
121    } else {
122        format!("'{}'", arg.replace('\'', r"'\''"))
123    }
124}
125
126/// `argv` as one line a POSIX shell reads back as the same arguments.
127pub fn command_line<S: AsRef<str>>(argv: &[S]) -> String {
128    argv.iter()
129        .map(|a| quote(a.as_ref()))
130        .collect::<Vec<_>>()
131        .join(" ")
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn dids_follow_did_core() {
140        for ok in [
141            "did:web:example.com",
142            "did:webvh:QmScid:example.com%3A8443:alice",
143            "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
144            "did:example::a",
145        ] {
146            assert!(check_did("owner", ok).is_ok(), "{ok}");
147        }
148        for bad in [
149            "",
150            "did:",
151            "did:web",
152            "did:Web:example.com",
153            "did:web:",
154            "did:web:a:",
155            "did:web:a b",
156            "did:web:a;rm -rf ~",
157            "did:web:a'b",
158            "did:web:a#frag",
159            "did:web:a/path",
160            "did:web:a?q",
161            "did:web:%zz",
162            "did:web:%4",
163            "web:example.com",
164            "did:web:$(id)",
165            "did:web:a\nb",
166        ] {
167            assert!(check_did("owner", bad).is_err(), "{bad:?}");
168        }
169    }
170
171    #[test]
172    fn a_did_scid_is_admitted_only_with_its_src_locator() {
173        for ok in [
174            "did:scid:vh:1:QmScid?src=example.com",
175            "did:scid:vh:1:QmScid?src=dids.example.org/farm-auth",
176            "did:scid:vh:1:QmScid?src=localhost%3A8000/a",
177        ] {
178            assert!(check_did("owner", ok).is_ok(), "{ok}");
179        }
180        for bad in [
181            "did:scid:vh:1:QmScid",
182            "did:scid:vh:1:QmScid?src=",
183            "did:scid:vh:1:QmScid?versionId=1",
184            "did:scid:vh:1:QmScid?src=a.example&x=1",
185            "did:scid:vh:1:QmScid?src=a.example#key-0",
186            "did:scid:vh:1:QmScid?src=a b",
187            "did:scid:vh:1:QmScid?src=a.example;rm -rf ~",
188            "did:scid:vh:1:QmScid?src=a.example?src=b",
189            "did:scid:vh:1:Qm Scid?src=a.example",
190            "did:scid:vh:1:?src=a.example",
191            "did:web:a?src=example.com",
192        ] {
193            assert!(check_did("owner", bad).is_err(), "{bad:?}");
194        }
195    }
196
197    #[test]
198    fn a_did_scid_url_is_quoted_for_the_shell() {
199        let url = "did:scid:vh:1:QmScid?src=example.com/a";
200        assert_eq!(quote(url), format!("'{url}'"));
201    }
202
203    #[test]
204    fn quoting_round_trips_through_a_shell() {
205        assert_eq!(quote("github.com/acme/widgets"), "github.com/acme/widgets");
206        assert_eq!(
207            quote("did:webvh:Qm:x.example%3A80"),
208            "did:webvh:Qm:x.example%3A80"
209        );
210        assert_eq!(quote(""), "''");
211        assert_eq!(quote("a b"), "'a b'");
212        assert_eq!(quote("it's"), r"'it'\''s'");
213        assert_eq!(quote("$(id)"), "'$(id)'");
214        assert_eq!(quote("`id`;x"), "'`id`;x'");
215        assert_eq!(quote("--owner"), "--owner");
216    }
217
218    #[cfg(unix)]
219    #[test]
220    fn a_quoted_line_is_read_back_unchanged() {
221        let args = [
222            "cnm",
223            "git",
224            "adopt",
225            "github.com/acme/widgets",
226            "--owner",
227            "did:web:a.example",
228            "it's $(x) `y` \"z\" \\ ;&|<>*?[]{}~#!",
229        ];
230        let line = command_line(&args);
231        let out = std::process::Command::new("sh")
232            .arg("-c")
233            .arg(format!("printf '%s\\n' {line}"))
234            .output()
235            .unwrap();
236        let back: Vec<&str> = std::str::from_utf8(&out.stdout).unwrap().lines().collect();
237        assert_eq!(back, args);
238    }
239}