1use crate::config::ConfigSet;
7use crate::error::{ConfigError, Error};
8use thiserror::Error;
9
10#[derive(Clone, Debug, Error, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum ProtocolError {
14 #[error("protocol '{protocol}' is not allowed by GIT_ALLOW_PROTOCOL")]
16 NotAllowedByEnvironment {
17 protocol: String,
19 },
20 #[error("protocol '{protocol}' is not allowed")]
22 NotAllowed {
23 protocol: String,
25 },
26 #[error("unknown protocol.allow value '{value}' for protocol '{protocol}'")]
28 UnknownAllowValue {
29 protocol: String,
31 value: String,
33 },
34}
35
36#[derive(Clone, Debug, Default)]
38pub struct ProtocolPolicyInputs {
39 pub git_allow_protocol: Option<String>,
41 pub git_protocol_from_user: Option<String>,
43 pub specific_allow: Option<String>,
45 pub blanket_allow: Option<String>,
47}
48
49pub 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#[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#[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
141pub 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
153pub 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#[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#[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}