Debian Codegraph @

_transport_rs/src/http/mod.rs

raw
1 //! Python bindings for the HTTP helper functions in `dromedary::http`.
2
3 pub(crate) mod client;
4 mod response;
5 pub(crate) mod transport;
6
7 use std::sync::Mutex;
8
9 use lazy_static::lazy_static;
10 use pyo3::exceptions::PyValueError;
11 use pyo3::prelude::*;
12 use pyo3::types::{PyList, PyTuple};
13 use pyo3::IntoPyObjectExt;
14
15 // ---------------------------------------------------------------------------
16 // Credential-lookup callback. Breezy registers a Python callable that
17 // maps (protocol, host, port, path, realm) to (user, password). We
18 // store the Py<PyAny> here so the hot-path auth code in urllib.py (and
19 // eventually the Rust HTTP client) can call into it without round-
20 // tripping through module-attribute lookup.
21 // ---------------------------------------------------------------------------
22
23 lazy_static! {
24 /// Registered credential-lookup callback. `None` means no
25 /// callback has been set and `get_credentials` should return
26 /// `(None, None)`.
27 static ref CREDENTIAL_LOOKUP: Mutex<Option<Py<PyAny>>> = Mutex::new(None);
28 /// Registered Negotiate (Kerberos) initial-token callback.
29 /// Called as `cb(host) -> Optional[str]`; the returned string
30 /// goes after `Negotiate ` in the Authorization header.
31 static ref NEGOTIATE_PROVIDER: Mutex<Option<Py<PyAny>>> = Mutex::new(None);
32 /// Registered preemptive token-provider callback. Called as
33 /// `cb(protocol, host, port=None, path=None) -> (token, scheme)`
34 /// or `(None, None)` when no token is configured. The HTTP
35 /// client uses the result to attach `Authorization: <scheme>
36 /// <token>` before the request goes on the wire — no server
37 /// challenge required.
38 static ref TOKEN_PROVIDER: Mutex<Option<Py<PyAny>>> = Mutex::new(None);
39 /// Registered auth-header-sent callback. The Rust client calls
40 /// this just before sending a request carrying an Authorization
41 /// or Proxy-Authorization header; breezy uses it to emit a
42 /// `trace.mutter("> %s: <masked>", header_name)` line when the
43 /// `http` debug flag is on, so users can confirm auth happened
44 /// without leaking the credential value into logs.
45 static ref AUTH_HEADER_TRACE: Mutex<Option<Py<PyAny>>> = Mutex::new(None);
46 }
47
48 /// Invoke the registered auth-header-trace callback. No-op if no
49 /// callback is set. Errors from the callback are swallowed — this
50 /// is a tracing hook, not a control-flow one, so a broken logger
51 /// mustn't break HTTP auth.
52 pub(crate) fn invoke_auth_header_trace(header_name: &str) {
53 Python::attach(|py| {
54 let cb = {
55 let guard = AUTH_HEADER_TRACE.lock().unwrap();
56 guard.as_ref().map(|p| p.clone_ref(py))
57 };
58 if let Some(cb) = cb {
59 let _ = cb.bind(py).call1((header_name,));
60 }
61 });
62 }
63
64 /// Invoke the registered token-provider callback. Returns `None`
65 /// if no callback is set, the callback raised, or it returned
66 /// `(None, _)` / `(_, None)`. The breezy callback maps this to an
67 /// `authentication.conf` lookup against the request URL.
68 pub(super) fn invoke_token_provider(
69 protocol: &str,
70 host: &str,
71 port: Option<u16>,
72 path: Option<&str>,
73 ) -> Option<(String, String)> {
74 Python::attach(|py| {
75 let cb = {
76 let guard = TOKEN_PROVIDER.lock().unwrap();
77 guard.as_ref().map(|p| p.clone_ref(py))
78 };
79 let cb = cb?;
80 let kwargs = pyo3::types::PyDict::new(py);
81 kwargs.set_item("port", port).ok()?;
82 kwargs.set_item("path", path).ok()?;
83 let result = cb.bind(py).call((protocol, host), Some(&kwargs)).ok()?;
84 let tup = result.cast::<PyTuple>().ok()?;
85 if tup.len() != 2 {
86 return None;
87 }
88 let token: Option<String> = tup.get_item(0).ok()?.extract().ok()?;
89 let scheme: Option<String> = tup.get_item(1).ok()?.extract().ok()?;
90 match (token, scheme) {
91 (Some(t), Some(s)) => Some((s, t)),
92 _ => None,
93 }
94 })
95 }
96
97 /// Invoke the registered Negotiate callback. Returns `None` if no
98 /// callback is set, the callback returned a non-string, or it
99 /// raised. Matches the behaviour of the old Python
100 /// `_auth_match_kerberos` which quietly returned `None` on any
101 /// GSSAPI error.
102 pub(super) fn invoke_negotiate_provider(host: &str) -> Option<String> {
103 Python::attach(|py| {
104 let cb = {
105 let guard = NEGOTIATE_PROVIDER.lock().unwrap();
106 guard.as_ref().map(|p| p.clone_ref(py))
107 };
108 let cb = cb?;
109 let result = cb.bind(py).call1((host,)).ok()?;
110 if result.is_none() {
111 return None;
112 }
113 result.extract::<String>().ok()
114 })
115 }
116
117 /// Invoke the registered credential-lookup callback with the given
118 /// arguments. Returns `(None, None)` if no callback is set, or if
119 /// the callback raises — we don't surface those errors because the
120 /// auth layer treats them as "no credentials available".
121 pub(super) fn invoke_credential_lookup(
122 protocol: &str,
123 host: &str,
124 port: Option<u16>,
125 realm: Option<&str>,
126 user: Option<&str>,
127 is_proxy: bool,
128 ) -> (Option<String>, Option<String>) {
129 Python::attach(|py| {
130 let cb = {
131 let guard = CREDENTIAL_LOOKUP.lock().unwrap();
132 guard.as_ref().map(|p| p.clone_ref(py))
133 };
134 let Some(cb) = cb else {
135 return (None, None);
136 };
137 let kwargs = pyo3::types::PyDict::new(py);
138 // The Python callback signature is
139 // `(protocol, host, port=None, path=None, realm=None, user=None,
140 // is_proxy=False)`;
141 // we leave `path` as None because the Rust client doesn't track
142 // it per-request (breezy's urllib version did, but the value was
143 // rarely used by downstream credential stores). `user` is the
144 // URL-embedded username hint — breezy's AuthenticationConfig
145 // uses it to skip its own user prompt when the URL already
146 // names one. `is_proxy` tells the callback that the credentials
147 // are for a proxy (407) rather than the origin (401), so it can
148 // label interactive prompts accordingly.
149 let _ = kwargs.set_item("port", port);
150 let _ = kwargs.set_item("path", py.None());
151 let _ = kwargs.set_item("realm", realm);
152 if let Some(u) = user {
153 let _ = kwargs.set_item("user", u);
154 }
155 if is_proxy {
156 let _ = kwargs.set_item("is_proxy", true);
157 }
158 let mut result = cb.bind(py).call((protocol, host), Some(&kwargs));
159 // Older callbacks may not accept the `user` / `is_proxy` kwargs.
160 // If that's the cause of a TypeError, drop them progressively so
161 // we don't regress on callers that haven't been updated.
162 if result.is_err() && is_proxy {
163 let _ = kwargs.del_item("is_proxy");
164 result = cb.bind(py).call((protocol, host), Some(&kwargs));
165 }
166 if result.is_err() && user.is_some() {
167 let _ = kwargs.del_item("user");
168 result = cb.bind(py).call((protocol, host), Some(&kwargs));
169 }
170 match result {
171 Ok(obj) => {
172 let tup = match obj.cast::<PyTuple>() {
173 Ok(t) => t,
174 Err(_) => return (None, None),
175 };
176 if tup.len() != 2 {
177 return (None, None);
178 }
179 let user = tup
180 .get_item(0)
181 .ok()
182 .and_then(|v| v.extract::<Option<String>>().ok())
183 .flatten();
184 let password = tup
185 .get_item(1)
186 .ok()
187 .and_then(|v| v.extract::<Option<String>>().ok())
188 .flatten();
189 (user, password)
190 }
191 Err(_) => (None, None),
192 }
193 })
194 }
195
196 #[pyfunction]
197 #[pyo3(signature = (use_cache=true))]
198 fn get_ca_path(use_cache: bool) -> String {
199 dromedary::http::get_ca_path(use_cache)
200 }
201
202 #[pyfunction]
203 fn clear_ca_path_cache() {
204 dromedary::http::clear_ca_path_cache();
205 }
206
207 #[pyfunction]
208 fn default_ca_certs() -> String {
209 dromedary::http::default_ca_certs()
210 }
211
212 /// Split a `host[:port]` string. Returns `(host, port_or_none)`.
213 #[pyfunction]
214 fn splitport(py: Python, host: &str) -> PyResult<Py<PyAny>> {
215 let (h, p) = dromedary::http::splitport(host);
216 let tup = PyTuple::new(py, [h.into_py_any(py)?, p.into_py_any(py)?])?;
217 Ok(tup.into())
218 }
219
220 /// Split a WWW-Authenticate header into `(scheme_lower, remainder_or_none)`.
221 #[pyfunction]
222 fn parse_auth_header(py: Python, header: &str) -> PyResult<Py<PyAny>> {
223 let (scheme, rest) = dromedary::http::parse_auth_header(header);
224 let tup = PyTuple::new(py, [scheme.into_py_any(py)?, rest.into_py_any(py)?])?;
225 Ok(tup.into())
226 }
227
228 /// Parse an RFC 2068 §2 comma-separated list honouring quoted strings.
229 #[pyfunction]
230 fn parse_http_list(s: &str) -> Vec<String> {
231 dromedary::http::parse_http_list(s)
232 }
233
234 /// Parse a list of `key=value` pairs (typically produced by
235 /// [`parse_http_list`]) into a dict.
236 #[pyfunction]
237 fn parse_keqv_list(items: Vec<String>) -> std::collections::HashMap<String, String> {
238 dromedary::http::parse_keqv_list(&items)
239 }
240
241 /// Compute the HTTP Digest `H(x)` function for the given algorithm. The
242 /// algorithm name is the value of the server's `algorithm=` parameter
243 /// (`"MD5"` or `"SHA"`). Raises `ValueError` for unsupported algorithms
244 /// so callers get a clear error rather than a silent mismatch.
245 #[pyfunction]
246 fn digest_h(algorithm: &str, data: &[u8]) -> PyResult<String> {
247 let algo = dromedary::http::DigestAlgorithm::parse(algorithm)
248 .ok_or_else(|| PyValueError::new_err(format!("unsupported algorithm: {}", algorithm)))?;
249 Ok(algo.h(data))
250 }
251
252 /// Compute the HTTP Digest `KD(secret, data) = H(secret ":" data)`.
253 #[pyfunction]
254 fn digest_kd(algorithm: &str, secret: &str, data: &str) -> PyResult<String> {
255 let algo = dromedary::http::DigestAlgorithm::parse(algorithm)
256 .ok_or_else(|| PyValueError::new_err(format!("unsupported algorithm: {}", algorithm)))?;
257 Ok(algo.kd(secret, data))
258 }
259
260 /// Check whether an `algorithm=` name is one we can compute.
261 #[pyfunction]
262 fn digest_algorithm_supported(algorithm: &str) -> bool {
263 dromedary::http::DigestAlgorithm::parse(algorithm).is_some()
264 }
265
266 /// Generate a client nonce for HTTP Digest authentication.
267 #[pyfunction]
268 fn get_new_cnonce(nonce: &str, nonce_count: u64) -> String {
269 dromedary::http::new_cnonce(nonce, nonce_count)
270 }
271
272 /// Check a host against a `no_proxy` list. Returns `True` to bypass
273 /// the proxy, `False` to use it, or `None` if the caller should fall
274 /// back to the platform-specific proxy-bypass logic (Python's
275 /// `urllib.request.proxy_bypass`).
276 ///
277 /// This preserves the Python `ProxyHandler.evaluate_proxy_bypass`
278 /// contract byte-for-byte, including the surprising prefix-only
279 /// match that lets `example.com` in `no_proxy` match
280 /// `example.com.evil.com`.
281 #[pyfunction]
282 #[pyo3(signature = (host, no_proxy))]
283 fn evaluate_proxy_bypass(py: Python, host: &str, no_proxy: Option<&str>) -> Py<PyAny> {
284 use dromedary::http::ProxyBypass;
285 match dromedary::http::evaluate_proxy_bypass(host, no_proxy) {
286 ProxyBypass::Bypass => true.into_py_any(py).unwrap(),
287 ProxyBypass::UseProxy => false.into_py_any(py).unwrap(),
288 ProxyBypass::Undecided => py.None(),
289 }
290 }
291
292 /// Replace the global User-Agent prefix.
293 #[pyfunction]
294 fn set_user_agent(prefix: String) {
295 dromedary::http::set_user_agent(prefix);
296 }
297
298 /// Return the current User-Agent prefix.
299 #[pyfunction]
300 fn default_user_agent() -> String {
301 dromedary::http::default_user_agent()
302 }
303
304 /// Platform-default certificate verification requirement. Returns an
305 /// integer matching `ssl.CERT_NONE` / `ssl.CERT_REQUIRED` so the
306 /// Python side can compare against `ssl.*` constants directly.
307 #[pyfunction]
308 fn default_cert_reqs() -> u8 {
309 dromedary::http::default_cert_reqs().to_int()
310 }
311
312 /// Register a credential-lookup callable. The callable is invoked as
313 /// `func(protocol, host, port=None, path=None, realm=None)` and
314 /// should return `(user, password)` (either may be `None`).
315 ///
316 /// Passing `None` clears any previously-registered callback so
317 /// subsequent [`get_credentials`] calls fall back to the `(None,
318 /// None)` default.
319 #[pyfunction]
320 fn set_credential_lookup(py: Python, func: Py<PyAny>) {
321 let mut slot = CREDENTIAL_LOOKUP.lock().unwrap();
322 *slot = if func.bind(py).is_none() {
323 None
324 } else {
325 Some(func)
326 };
327 }
328
329 /// Return the currently-registered credential-lookup callable, or
330 /// `None` if none is set. Mainly useful for tests that want to save
331 /// and restore the callback around assertions.
332 #[pyfunction]
333 fn get_credential_lookup(py: Python) -> Py<PyAny> {
334 CREDENTIAL_LOOKUP
335 .lock()
336 .unwrap()
337 .as_ref()
338 .map(|p| p.clone_ref(py))
339 .unwrap_or_else(|| py.None())
340 }
341
342 /// Register a Negotiate (Kerberos) initial-token callback. The
343 /// callable is invoked as `func(host)` and should return the
344 /// base64-encoded token to send after `Negotiate ` in the
345 /// Authorization header, or `None` if no token is available (no
346 /// ticket / library missing / wrong realm).
347 ///
348 /// Passing `None` clears any previously-registered callback.
349 #[pyfunction]
350 fn set_negotiate_provider(py: Python, func: Py<PyAny>) {
351 let mut slot = NEGOTIATE_PROVIDER.lock().unwrap();
352 *slot = if func.bind(py).is_none() {
353 None
354 } else {
355 Some(func)
356 };
357 }
358
359 /// Register a callback invoked when the HTTP client is about to
360 /// send an Authorization or Proxy-Authorization header. The
361 /// callable is invoked as `func(header_name)` — breezy uses this
362 /// for debug tracing so users can confirm auth credentials were
363 /// sent without exposing the values themselves in logs.
364 ///
365 /// Passing `None` clears any previously-registered callback.
366 #[pyfunction]
367 fn set_auth_header_trace(py: Python, func: Py<PyAny>) {
368 let mut slot = AUTH_HEADER_TRACE.lock().unwrap();
369 *slot = if func.bind(py).is_none() {
370 None
371 } else {
372 Some(func)
373 };
374 }
375
376 /// Return the currently-registered Negotiate callback, or `None`.
377 #[pyfunction]
378 fn get_negotiate_provider(py: Python) -> Py<PyAny> {
379 NEGOTIATE_PROVIDER
380 .lock()
381 .unwrap()
382 .as_ref()
383 .map(|p| p.clone_ref(py))
384 .unwrap_or_else(|| py.None())
385 }
386
387 /// Register a preemptive token-provider callback. The callable is
388 /// invoked as `func(protocol, host, port=None, path=None)` and
389 /// should return `(token, scheme)`, with either field `None` when
390 /// no token applies. The HTTP client attaches `Authorization:
391 /// <scheme> <token>` before the request goes out — caller-supplied
392 /// `Authorization` headers always win.
393 ///
394 /// Passing `None` clears any previously-registered callback.
395 #[pyfunction]
396 fn set_token_provider(py: Python, func: Py<PyAny>) {
397 let mut slot = TOKEN_PROVIDER.lock().unwrap();
398 *slot = if func.bind(py).is_none() {
399 None
400 } else {
401 Some(func)
402 };
403 }
404
405 /// Return the currently-registered token-provider callback, or `None`.
406 #[pyfunction]
407 fn get_token_provider(py: Python) -> Py<PyAny> {
408 TOKEN_PROVIDER
409 .lock()
410 .unwrap()
411 .as_ref()
412 .map(|p| p.clone_ref(py))
413 .unwrap_or_else(|| py.None())
414 }
415
416 /// Look up credentials via the registered callback. Returns
417 /// `(None, None)` if no callback is set (the historical default).
418 #[pyfunction]
419 #[pyo3(signature = (protocol, host, port=None, path=None, realm=None))]
420 fn get_credentials(
421 py: Python,
422 protocol: &str,
423 host: &str,
424 port: Option<Py<PyAny>>,
425 path: Option<Py<PyAny>>,
426 realm: Option<Py<PyAny>>,
427 ) -> PyResult<Py<PyAny>> {
428 let cb = {
429 let guard = CREDENTIAL_LOOKUP.lock().unwrap();
430 guard.as_ref().map(|p| p.clone_ref(py))
431 };
432 match cb {
433 Some(cb) => {
434 let kwargs = pyo3::types::PyDict::new(py);
435 kwargs.set_item("port", port.unwrap_or_else(|| py.None()))?;
436 kwargs.set_item("path", path.unwrap_or_else(|| py.None()))?;
437 kwargs.set_item("realm", realm.unwrap_or_else(|| py.None()))?;
438 let result = cb.bind(py).call((protocol, host), Some(&kwargs))?;
439 Ok(result.unbind())
440 }
441 None => {
442 let tup = PyTuple::new(py, [py.None(), py.None()])?;
443 Ok(tup.into())
444 }
445 }
446 }
447
448 pub(crate) fn register(py: Python, m: &Bound<PyModule>) -> PyResult<()> {
449 m.add_function(wrap_pyfunction!(get_ca_path, m)?)?;
450 m.add_function(wrap_pyfunction!(clear_ca_path_cache, m)?)?;
451 m.add_function(wrap_pyfunction!(default_ca_certs, m)?)?;
452 m.add_function(wrap_pyfunction!(splitport, m)?)?;
453 m.add_function(wrap_pyfunction!(parse_auth_header, m)?)?;
454 m.add_function(wrap_pyfunction!(parse_http_list, m)?)?;
455 m.add_function(wrap_pyfunction!(parse_keqv_list, m)?)?;
456 m.add_function(wrap_pyfunction!(digest_h, m)?)?;
457 m.add_function(wrap_pyfunction!(digest_kd, m)?)?;
458 m.add_function(wrap_pyfunction!(digest_algorithm_supported, m)?)?;
459 m.add_function(wrap_pyfunction!(get_new_cnonce, m)?)?;
460 m.add_function(wrap_pyfunction!(set_user_agent, m)?)?;
461 m.add_function(wrap_pyfunction!(default_user_agent, m)?)?;
462 m.add_function(wrap_pyfunction!(default_cert_reqs, m)?)?;
463 m.add_function(wrap_pyfunction!(set_credential_lookup, m)?)?;
464 m.add_function(wrap_pyfunction!(get_credential_lookup, m)?)?;
465 m.add_function(wrap_pyfunction!(get_credentials, m)?)?;
466 m.add_function(wrap_pyfunction!(set_negotiate_provider, m)?)?;
467 m.add_function(wrap_pyfunction!(get_negotiate_provider, m)?)?;
468 m.add_function(wrap_pyfunction!(set_token_provider, m)?)?;
469 m.add_function(wrap_pyfunction!(get_token_provider, m)?)?;
470 m.add_function(wrap_pyfunction!(set_auth_header_trace, m)?)?;
471 m.add_function(wrap_pyfunction!(evaluate_proxy_bypass, m)?)?;
472
473 client::register(m)?;
474 response::register(m)?;
475 transport::register(m)?;
476
477 let locations = PyList::new(py, dromedary::http::SSL_CA_CERTS_KNOWN_LOCATIONS)?;
478 m.add("SSL_CA_CERTS_KNOWN_LOCATIONS", locations)?;
479
480 Ok(())
481 }