Skip to main content

grit_lib/
protocol.rs

1//! Protocol allow/deny policy and client wire-protocol version selection.
2//!
3//! Implements the `protocol.<name>.allow` config and `GIT_ALLOW_PROTOCOL`
4//! environment semantics without reading process-global state directly.
5
6use crate::config::ConfigSet;
7use crate::error::{ConfigError, Error};
8use thiserror::Error;
9
10/// Errors returned when a transport protocol is not allowed.
11#[derive(Clone, Debug, Error, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum ProtocolError {
14    /// Protocol is not included in `GIT_ALLOW_PROTOCOL`.
15    #[error("protocol '{protocol}' is not allowed by GIT_ALLOW_PROTOCOL")]
16    NotAllowedByEnvironment {
17        /// Protocol name that was denied.
18        protocol: String,
19    },
20    /// Protocol is denied by config or default policy.
21    #[error("protocol '{protocol}' is not allowed")]
22    NotAllowed {
23        /// Protocol name that was denied.
24        protocol: String,
25    },
26    /// Config contains an unknown allow value.
27    #[error("unknown protocol.allow value '{value}' for protocol '{protocol}'")]
28    UnknownAllowValue {
29        /// Protocol name whose policy was evaluated.
30        protocol: String,
31        /// Unknown config value.
32        value: String,
33    },
34}
35
36/// Explicit inputs for protocol allow/deny evaluation.
37#[derive(Clone, Debug, Default)]
38pub struct ProtocolPolicyInputs {
39    /// `GIT_ALLOW_PROTOCOL` value, when set.
40    pub git_allow_protocol: Option<String>,
41    /// `GIT_PROTOCOL_FROM_USER` value, when set.
42    pub git_protocol_from_user: Option<String>,
43    /// `protocol.<name>.allow` config value.
44    pub specific_allow: Option<String>,
45    /// `protocol.allow` config value.
46    pub blanket_allow: Option<String>,
47}
48
49/// Check whether a given protocol (e.g. `file`, `git`, `ssh`, `https`) is allowed.
50///
51/// Rules match Git's `transport.c` / `is_transport_allowed`:
52/// 1. `GIT_ALLOW_PROTOCOL` is a colon- or comma-separated whitelist.
53/// 2. `protocol.<name>.allow` overrides the blanket config.
54/// 3. `protocol.allow` supplies a blanket default.
55/// 4. Built-in defaults: `http`, `https`, `git`, and `ssh` are always allowed;
56///    `ext` is never allowed; any other protocol is `user`.
57pub fn check_protocol_allowed_with(
58    protocol: &str,
59    inputs: &ProtocolPolicyInputs,
60) -> Result<(), ProtocolError> {
61    if let Some(val) = inputs.git_allow_protocol.as_deref() {
62        let allowed: Vec<&str> = val
63            .split([':', ','])
64            .map(str::trim)
65            .filter(|s| !s.is_empty())
66            .collect();
67        if allowed.contains(&protocol) {
68            return Ok(());
69        }
70        return Err(ProtocolError::NotAllowedByEnvironment {
71            protocol: protocol.to_owned(),
72        });
73    }
74
75    if let Some(ref val) = inputs.specific_allow {
76        return check_allow_value(protocol, val, inputs.git_protocol_from_user.as_deref());
77    }
78
79    if let Some(ref val) = inputs.blanket_allow {
80        return check_allow_value(protocol, val, inputs.git_protocol_from_user.as_deref());
81    }
82
83    match protocol.to_ascii_lowercase().as_str() {
84        "http" | "https" | "git" | "ssh" => Ok(()),
85        "ext" => Err(ProtocolError::NotAllowed {
86            protocol: protocol.to_owned(),
87        }),
88        _ => check_allow_value(protocol, "user", inputs.git_protocol_from_user.as_deref()),
89    }
90}
91
92fn check_allow_value(
93    protocol: &str,
94    value: &str,
95    git_protocol_from_user: Option<&str>,
96) -> Result<(), ProtocolError> {
97    match value.to_lowercase().as_str() {
98        "always" => Ok(()),
99        "never" => Err(ProtocolError::NotAllowed {
100            protocol: protocol.to_owned(),
101        }),
102        "user" => {
103            if protocol_from_user(git_protocol_from_user) {
104                Ok(())
105            } else {
106                Err(ProtocolError::NotAllowed {
107                    protocol: protocol.to_owned(),
108                })
109            }
110        }
111        other => Err(ProtocolError::UnknownAllowValue {
112            protocol: protocol.to_owned(),
113            value: other.to_owned(),
114        }),
115    }
116}
117
118/// Whether `protocol.<name>.allow=user` should be considered allowed.
119#[must_use]
120pub fn protocol_from_user(raw: Option<&str>) -> bool {
121    match raw {
122        None => true,
123        Some(v) => {
124            let v = v.trim().to_ascii_lowercase();
125            v.is_empty() || !matches!(v.as_str(), "0" | "false" | "no" | "off")
126        }
127    }
128}
129
130/// Parse a protocol version digit (`0`, `1`, or `2`).
131#[must_use]
132pub(crate) fn parse_protocol_version_digit(s: &str) -> Option<u8> {
133    match s.trim() {
134        "0" => Some(0),
135        "1" => Some(1),
136        "2" => Some(2),
137        _ => None,
138    }
139}
140
141/// Parse `protocol.version` from config (strict: invalid values are rejected).
142///
143/// Returns [`Error::Config`] when the value is present but not `0`, `1`, or `2`.
144pub fn try_protocol_version_from_config_value(raw: &str) -> Result<u8, Error> {
145    parse_protocol_version_digit(raw).ok_or_else(|| {
146        Error::Config(ConfigError::UnknownValue {
147            key: "protocol.version".to_owned(),
148            value: raw.to_owned(),
149        })
150    })
151}
152
153/// Effective client-side protocol version from `protocol.version` in `config`.
154///
155/// Defaults to `2` when unset. A value that is not `0`, `1`, or `2` is rejected with
156/// [`Error::Config`].
157pub fn try_effective_client_protocol_version_from_config(config: &ConfigSet) -> Result<u8, Error> {
158    config
159        .value("protocol.version")
160        .map_or(Ok(2), |v| try_protocol_version_from_config_value(&v))
161}
162
163/// Value for the HTTP `Git-Protocol` request header for a client protocol version.
164///
165/// Version `0` means no header (classic v0 advertisement); `1` and `2` send
166/// `version=1` / `version=2` respectively.
167#[must_use]
168#[cfg_attr(not(any(test, feature = "http-ureq")), allow(dead_code))]
169pub(crate) fn client_git_protocol_header_value(version: u8) -> Option<String> {
170    match version {
171        0 => None,
172        1 => Some("version=1".to_string()),
173        _ => Some("version=2".to_string()),
174    }
175}
176
177/// `Git-Protocol` header value implied by `protocol.version` in `config`.
178///
179/// # Errors
180///
181/// Returns [`Error::Config`] when `protocol.version` is set to an invalid value.
182#[cfg_attr(not(any(test, feature = "http-ureq")), allow(dead_code))]
183pub(crate) fn client_git_protocol_header_from_config(
184    config: &ConfigSet,
185) -> Result<Option<String>, Error> {
186    Ok(client_git_protocol_header_value(
187        try_effective_client_protocol_version_from_config(config)?,
188    ))
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn client_git_protocol_header_matches_version() {
197        assert_eq!(client_git_protocol_header_value(0), None);
198        assert_eq!(
199            client_git_protocol_header_value(1).as_deref(),
200            Some("version=1")
201        );
202        assert_eq!(
203            client_git_protocol_header_value(2).as_deref(),
204            Some("version=2")
205        );
206    }
207
208    #[test]
209    fn protocol_version_from_config_defaults_to_v2_header() {
210        let config = ConfigSet::new();
211        assert_eq!(
212            client_git_protocol_header_from_config(&config)
213                .expect("header")
214                .as_deref(),
215            Some("version=2")
216        );
217    }
218
219    #[test]
220    fn protocol_version_from_config_honors_protocol_version_key() {
221        let mut config = ConfigSet::new();
222        config
223            .add_command_override("protocol.version", "1")
224            .expect("override");
225        assert_eq!(
226            client_git_protocol_header_from_config(&config)
227                .expect("header")
228                .as_deref(),
229            Some("version=1")
230        );
231    }
232
233    #[test]
234    fn protocol_version_rejects_invalid_config_value() {
235        let mut config = ConfigSet::new();
236        config
237            .add_command_override("protocol.version", "9")
238            .expect("override");
239        let err = client_git_protocol_header_from_config(&config).expect_err("invalid");
240        assert!(
241            matches!(err, Error::Config(_)),
242            "expected ConfigError, got {err:?}"
243        );
244    }
245
246    #[test]
247    fn protocol_version_defaults_to_two_and_honors_config() {
248        let mut config = ConfigSet::new();
249        assert_eq!(
250            try_effective_client_protocol_version_from_config(&config).expect("default"),
251            2
252        );
253        config
254            .add_command_override("protocol.version", "0")
255            .expect("override");
256        assert_eq!(
257            try_effective_client_protocol_version_from_config(&config).expect("v0"),
258            0
259        );
260    }
261
262    #[test]
263    fn protocol_from_user_defaults_true() {
264        assert!(protocol_from_user(None));
265    }
266
267    #[test]
268    fn try_protocol_version_from_config_value_accepts_v2_and_rejects_unknown() {
269        use crate::error::{ConfigError, Error};
270        let err = try_protocol_version_from_config_value("3").expect_err("v3");
271        match err {
272            Error::Config(ConfigError::UnknownValue { key, value }) => {
273                assert_eq!(key, "protocol.version");
274                assert_eq!(value, "3");
275            }
276            other => panic!("expected UnknownValue for protocol.version, got {other:?}"),
277        }
278        assert_eq!(try_protocol_version_from_config_value("2").expect("v2"), 2);
279    }
280}