Skip to main content

gix_credentials/protocol/context/
serde.rs

1use bstr::BStr;
2
3use crate::protocol::context::Error;
4
5mod write {
6    use bstr::{BStr, BString};
7
8    use crate::protocol::{Context, ContextOptions, context::serde::validate};
9
10    impl Context {
11        /// Write ourselves to `out` such that [`from_bytes()`][Self::from_bytes()] can decode it losslessly.
12        pub fn write_to(&self, mut out: impl std::io::Write) -> std::io::Result<()> {
13            use bstr::ByteSlice;
14            fn write_key(out: &mut impl std::io::Write, key: &str, value: &BStr) -> std::io::Result<()> {
15                out.write_all(key.as_bytes())?;
16                out.write_all(b"=")?;
17                out.write_all(value)?;
18                out.write_all(b"\n")
19            }
20            let Context {
21                options: ContextOptions { protect_protocol },
22                protocol,
23                host,
24                path,
25                username,
26                password,
27                oauth_refresh_token,
28                password_expiry_utc,
29                url,
30                // We only decode quit and interpret it, but won't get to pass it on as it means to stop the
31                // credential helper invocation chain.
32                quit: _,
33            } = self;
34            for (key, value) in [("url", url), ("path", path)] {
35                if let Some(value) = value {
36                    validate(key, value.as_slice().into(), *protect_protocol).map_err(std::io::Error::other)?;
37                    write_key(&mut out, key, value.as_ref()).ok();
38                }
39            }
40            for (key, value) in [
41                ("protocol", protocol),
42                ("host", host),
43                ("username", username),
44                ("password", password),
45                ("oauth_refresh_token", oauth_refresh_token),
46            ] {
47                if let Some(value) = value {
48                    validate(key, value.as_str().into(), *protect_protocol).map_err(std::io::Error::other)?;
49                    write_key(&mut out, key, value.as_bytes().as_bstr()).ok();
50                }
51            }
52            if let Some(value) = password_expiry_utc {
53                let key = "password_expiry_utc";
54                let value = value.to_string();
55                validate(key, value.as_str().into(), *protect_protocol).map_err(std::io::Error::other)?;
56                write_key(&mut out, key, value.as_bytes().as_bstr()).ok();
57            }
58            Ok(())
59        }
60
61        /// Like [`write_to()`][Self::write_to()], but writes infallibly into memory.
62        pub fn to_bstring(&self) -> BString {
63            let mut buf = Vec::<u8>::new();
64            self.write_to(&mut buf).expect("infallible");
65            buf.into()
66        }
67    }
68}
69
70///
71pub mod decode {
72    use bstr::{BString, ByteSlice};
73
74    use crate::protocol::{Context, ContextOptions, context, context::serde::validate};
75
76    /// The error returned by [`from_bytes()`][Context::from_bytes()].
77    #[derive(Debug, thiserror::Error)]
78    #[expect(missing_docs)]
79    pub enum Error {
80        #[error("Illformed UTF-8 in value of key {key:?}: {value:?}")]
81        IllformedUtf8InValue { key: String, value: BString },
82        #[error(transparent)]
83        Encoding(#[from] context::Error),
84        #[error("Invalid format in line {line:?}, expecting key=value")]
85        Syntax { line: BString },
86    }
87
88    impl Context {
89        /// Decode ourselves from `input` which is the format written by [`write_to()`][Self::write_to()].
90        /// `options` control what to support during deserialization.
91        pub fn from_bytes(input: &[u8], options: ContextOptions) -> Result<Self, Error> {
92            let mut ctx = Context {
93                options,
94                ..Context::default()
95            };
96            let Context {
97                options: _,
98                protocol,
99                host,
100                path,
101                username,
102                password,
103                oauth_refresh_token,
104                password_expiry_utc,
105                url,
106                quit,
107            } = &mut ctx;
108            for res in input.lines().take_while(|line| !line.is_empty()).map(|line| {
109                let mut it = line.splitn(2, |b| *b == b'=');
110                match (
111                    it.next().and_then(|k| k.to_str().ok()),
112                    it.next().map(ByteSlice::as_bstr),
113                ) {
114                    (Some(key), Some(value)) => validate(key, value, options.protect_protocol)
115                        .map(|_| (key, value.to_owned()))
116                        .map_err(Into::into),
117                    _ => Err(Error::Syntax { line: line.into() }),
118                }
119            }) {
120                let (key, value) = res?;
121                match key {
122                    "protocol" | "host" | "username" | "password" | "oauth_refresh_token" => {
123                        if !value.is_utf8() {
124                            return Err(Error::IllformedUtf8InValue { key: key.into(), value });
125                        }
126                        let value = value.to_string();
127                        *match key {
128                            "protocol" => &mut *protocol,
129                            "host" => host,
130                            "username" => username,
131                            "password" => password,
132                            "oauth_refresh_token" => oauth_refresh_token,
133                            _ => unreachable!("checked field names in match above"),
134                        } = Some(value);
135                    }
136                    "password_expiry_utc" => {
137                        *password_expiry_utc = value.to_str().ok().and_then(|value| value.parse().ok());
138                    }
139                    "url" => *url = Some(value),
140                    "path" => *path = Some(value),
141                    "quit" => {
142                        *quit = gix_config_value::Boolean::try_from(value.as_bstr())
143                            .ok()
144                            .map(Into::into);
145                    }
146                    _ => {}
147                }
148            }
149            Ok(ctx)
150        }
151    }
152}
153
154fn validate(key: &str, value: &BStr, protect_protocol: bool) -> Result<(), Error> {
155    if key.contains('\0')
156        || key.contains('\n')
157        || key.contains('\r')
158        || value.contains(&0)
159        || value.contains(&b'\n')
160        || (protect_protocol && value.contains(&b'\r'))
161    {
162        return Err(Error::Encoding {
163            key: key.to_owned(),
164            value: value.to_owned(),
165        });
166    }
167    Ok(())
168}