| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The hub over HTTP: a blocking client on ureq, with rustls and the ring |
| 5 | //! provider, trusting the operating system's root certificates. |
| 6 | //! |
| 7 | //! Every request carries `Authorization: Bearer <token>` when there is a |
| 8 | //! token, and `User-Agent: braid/<version>`. Redirects are not followed, so |
| 9 | //! the token goes to the hub named and nowhere else. Error answers |
| 10 | //! (`{"error", "detail"}`) become [`HubError::Api`]. |
| 11 | |
| 12 | use std::cell::OnceCell; |
| 13 | use std::io::Read; |
| 14 | use std::sync::Arc; |
| 15 | use std::time::Duration; |
| 16 | |
| 17 | use braid_format::{Kind, ObjectId}; |
| 18 | use braid_hubproto::api::{ |
| 19 | DevicePoll, DevicePollRequest, DeviceStart, ErrorBody, LacksRequest, LacksResponse, |
| 20 | LandRequest, LandResponse, Me, MissingRequest, Refs, RepoCreate, RepoInfo, Root, RootLimits, |
| 21 | Stored, |
| 22 | }; |
| 23 | use braid_hubproto::{KIND_HEADER, OBJECTS_MEDIA_TYPE, RepoPath, Token}; |
| 24 | use serde::Serialize; |
| 25 | use serde::de::DeserializeOwned; |
| 26 | use ureq::http::{HeaderValue, Response}; |
| 27 | use ureq::tls::{Certificate, RootCerts, TlsConfig, TlsProvider}; |
| 28 | use ureq::{Agent, Body, RequestBuilder, SendBody}; |
| 29 | |
| 30 | use super::creds::{TokenSource, authority, is_loopback, redact}; |
| 31 | use super::device::DeviceFlow; |
| 32 | use super::remote::{HubError, LACKS_BATCH, MAX_BODY, Remote, shown}; |
| 33 | |
| 34 | /// What braid says it is. |
| 35 | const USER_AGENT: &str = concat!("braid/", env!("CARGO_PKG_VERSION")); |
| 36 | |
| 37 | /// The most a JSON answer may hold. |
| 38 | const MAX_JSON: u64 = 64 << 20; |
| 39 | |
| 40 | /// The most of an error answer that is read. |
| 41 | const MAX_ERROR: u64 = 1 << 20; |
| 42 | |
| 43 | /// A hub, at one URL, with or without a token. |
| 44 | pub(crate) struct HttpHub { |
| 45 | agent: Agent, |
| 46 | url: String, |
| 47 | token: Option<Token>, |
| 48 | /// Where the token came from, for what a refusal of it says. |
| 49 | source: TokenSource, |
| 50 | /// The hub `BRAID_TOKEN` is for, when it is set but not sent to this |
| 51 | /// one. |
| 52 | withheld: Option<String>, |
| 53 | max_body: u64, |
| 54 | /// The sizes the hub says it takes (`GET /v1`), asked once, by the |
| 55 | /// first request that needs them; `None` when it did not say. |
| 56 | announced: OnceCell<Option<RootLimits>>, |
| 57 | } |
| 58 | |
| 59 | impl HttpHub { |
| 60 | /// The same client, saying where its token came from: refusing it then |
| 61 | /// says what to do about that source. |
| 62 | pub(crate) fn with_source(mut self, source: TokenSource) -> HttpHub { |
| 63 | self.source = source; |
| 64 | self |
| 65 | } |
| 66 | |
| 67 | /// The same client, knowing that `BRAID_TOKEN` is set for the hub |
| 68 | /// `meant`, and not sent to this one: a refusal then says so. |
| 69 | pub(crate) fn with_withheld(mut self, meant: Option<String>) -> HttpHub { |
| 70 | self.withheld = meant; |
| 71 | self |
| 72 | } |
| 73 | |
| 74 | /// A client for the hub at `url`, which [`normalize_url`] made. |
| 75 | /// |
| 76 | /// [`normalize_url`]: super::creds::normalize_url |
| 77 | pub(crate) fn new(url: &str, token: Option<Token>) -> Result<HttpHub, HubError> { |
| 78 | let mut config = Agent::config_builder() |
| 79 | // Error answers carry a JSON body: read it rather than fail. |
| 80 | .http_status_as_error(false) |
| 81 | .max_redirects(0) |
| 82 | .user_agent(USER_AGENT) |
| 83 | .timeout_connect(Some(Duration::from_secs(30))) |
| 84 | .timeout_recv_response(Some(Duration::from_secs(600))); |
| 85 | if is_loopback(authority(url)) { |
| 86 | // An address on this machine is never reached through a proxy. |
| 87 | config = config.proxy(None); |
| 88 | } |
| 89 | if url.starts_with("https://") { |
| 90 | config = config.tls_config(tls_config(url)?); |
| 91 | } |
| 92 | let source = if token.is_some() { |
| 93 | TokenSource::File |
| 94 | } else { |
| 95 | TokenSource::None |
| 96 | }; |
| 97 | Ok(HttpHub { |
| 98 | agent: config.build().new_agent(), |
| 99 | url: url.to_owned(), |
| 100 | token, |
| 101 | source, |
| 102 | withheld: None, |
| 103 | max_body: MAX_BODY, |
| 104 | announced: OnceCell::new(), |
| 105 | }) |
| 106 | } |
| 107 | |
| 108 | /// The same client, sending upload bodies of at most `max_body` bytes. |
| 109 | pub(crate) fn with_max_body(mut self, max_body: u64) -> HttpHub { |
| 110 | self.max_body = max_body.min(MAX_BODY); |
| 111 | self |
| 112 | } |
| 113 | |
| 114 | /// Whether requests carry a token. |
| 115 | pub(crate) fn has_token(&self) -> bool { |
| 116 | self.token.is_some() |
| 117 | } |
| 118 | |
| 119 | /// One of the hub's repositories. |
| 120 | pub(crate) fn repo(&self, path: RepoPath) -> HttpRepo<'_> { |
| 121 | HttpRepo { hub: self, path } |
| 122 | } |
| 123 | |
| 124 | /// The largest body an upload sends: the size this client was given |
| 125 | /// (`BRAID_HUB_MAX_BODY`, or the protocol's 256 MiB), or the hub's own |
| 126 | /// when it takes less, asked once. |
| 127 | fn upload_limit(&self) -> u64 { |
| 128 | let hub = self.announced().map(|limits| limits.max_body); |
| 129 | upload_limit(self.max_body, hub) |
| 130 | } |
| 131 | |
| 132 | /// The most ids one list of a request holds: the protocol's 10,000, or |
| 133 | /// fewer when the hub says it takes fewer, asked once. |
| 134 | fn id_limit(&self) -> usize { |
| 135 | let hub = self |
| 136 | .announced() |
| 137 | .and_then(|limits| usize::try_from(limits.max_ids).ok()); |
| 138 | match hub { |
| 139 | Some(hub) if hub > 0 => hub.min(LACKS_BATCH), |
| 140 | _ => LACKS_BATCH, |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// What `GET /v1` says the hub takes, asked once. |
| 145 | fn announced(&self) -> Option<&RootLimits> { |
| 146 | self.announced |
| 147 | .get_or_init(|| self.root().ok().map(|root| root.limits)) |
| 148 | .as_ref() |
| 149 | } |
| 150 | |
| 151 | /// `GET /v1`: the protocol version and the sizes the hub takes. |
| 152 | pub(crate) fn root(&self) -> Result<Root, HubError> { |
| 153 | self.get_json("/v1") |
| 154 | } |
| 155 | |
| 156 | /// `POST /v1/login/device`. |
| 157 | pub(crate) fn device_start(&self) -> Result<DeviceStart, HubError> { |
| 158 | self.post_json("/v1/login/device", &serde_json::json!({})) |
| 159 | } |
| 160 | |
| 161 | /// `GET /v1/me`. |
| 162 | pub(crate) fn me(&self) -> Result<Me, HubError> { |
| 163 | self.get_json("/v1/me") |
| 164 | } |
| 165 | |
| 166 | /// `DELETE /v1/tokens/{id}`. |
| 167 | pub(crate) fn delete_token(&self, id: &str) -> Result<(), HubError> { |
| 168 | if !id.bytes().all(|b| b.is_ascii_alphanumeric()) { |
| 169 | return Err(HubError::Protocol(format!("{id:?} is not a token id"))); |
| 170 | } |
| 171 | let request = self.authorize(self.agent.delete(self.uri(&format!("/v1/tokens/{id}")))); |
| 172 | self.check(request.call())?; |
| 173 | Ok(()) |
| 174 | } |
| 175 | |
| 176 | /// `POST /v1/repos`. |
| 177 | pub(crate) fn create_repo(&self, request: &RepoCreate) -> Result<RepoInfo, HubError> { |
| 178 | self.post_json("/v1/repos", request) |
| 179 | } |
| 180 | |
| 181 | fn uri(&self, path: &str) -> String { |
| 182 | format!("{}{path}", self.url) |
| 183 | } |
| 184 | |
| 185 | /// Adds the token, as a header that debug output hides. |
| 186 | fn authorize<B>(&self, request: RequestBuilder<B>) -> RequestBuilder<B> { |
| 187 | match &self.token { |
| 188 | Some(token) => match HeaderValue::from_str(&format!("Bearer {}", token.expose())) { |
| 189 | Ok(mut value) => { |
| 190 | value.set_sensitive(true); |
| 191 | request.header("Authorization", value) |
| 192 | } |
| 193 | Err(_) => request, |
| 194 | }, |
| 195 | None => request, |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | fn transport(&self, err: ureq::Error) -> HubError { |
| 200 | HubError::Transport { |
| 201 | hub: self.url.clone(), |
| 202 | detail: err.to_string(), |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// The answer if it is a success; its error otherwise. |
| 207 | fn check( |
| 208 | &self, |
| 209 | result: Result<Response<Body>, ureq::Error>, |
| 210 | ) -> Result<Response<Body>, HubError> { |
| 211 | let mut response = result.map_err(|err| self.transport(err))?; |
| 212 | let status = response.status().as_u16(); |
| 213 | if (200..300).contains(&status) { |
| 214 | return Ok(response); |
| 215 | } |
| 216 | if (300..400).contains(&status) { |
| 217 | let to = response |
| 218 | .headers() |
| 219 | .get("location") |
| 220 | .and_then(|value| value.to_str().ok()) |
| 221 | .unwrap_or("another address"); |
| 222 | return Err(HubError::Protocol(format!( |
| 223 | "{} redirects to {}; braid follows no redirect, so that the token goes to the hub named and nowhere else: give that hub's URL instead", |
| 224 | self.url, |
| 225 | shown(to) |
| 226 | ))); |
| 227 | } |
| 228 | let retry_after = response |
| 229 | .headers() |
| 230 | .get("retry-after") |
| 231 | .and_then(|value| value.to_str().ok()) |
| 232 | .and_then(|value| value.trim().parse().ok()); |
| 233 | let bytes = response |
| 234 | .body_mut() |
| 235 | .with_config() |
| 236 | .limit(MAX_ERROR) |
| 237 | .read_to_vec() |
| 238 | .unwrap_or_default(); |
| 239 | let mut body = match serde_json::from_slice::<ErrorBody>(&bytes) { |
| 240 | Ok(mut body) => { |
| 241 | body.retry_after = body.retry_after.or(retry_after); |
| 242 | body |
| 243 | } |
| 244 | Err(_) => { |
| 245 | let text = excerpt(&bytes); |
| 246 | ErrorBody { |
| 247 | error: format!("http_{status}"), |
| 248 | detail: if text.is_empty() { |
| 249 | "no detail".to_owned() |
| 250 | } else { |
| 251 | text |
| 252 | }, |
| 253 | ids: Vec::new(), |
| 254 | retry_after, |
| 255 | head: None, |
| 256 | } |
| 257 | } |
| 258 | }; |
| 259 | // A hub or a proxy that echoes the request never gets its token |
| 260 | // into what braid prints. |
| 261 | body.detail = redact(&body.detail).into_owned(); |
| 262 | if status == 401 && self.token.is_some() { |
| 263 | return Err(HubError::Refused { |
| 264 | hub: self.url.clone(), |
| 265 | source: self.source, |
| 266 | detail: body.detail, |
| 267 | }); |
| 268 | } |
| 269 | if self.token.is_none() && matches!(status, 401 | 403 | 404) { |
| 270 | match &self.withheld { |
| 271 | Some(meant) => body.detail.push_str(&format!( |
| 272 | " (no token was sent: BRAID_TOKEN is for {meant}, the hub BRAID_HUB_URL names or else the one used by default; set BRAID_HUB_URL={} to send it to this one)", |
| 273 | self.url |
| 274 | )), |
| 275 | // A private repository hides from whoever is not signed in. |
| 276 | None if status != 401 => body.detail.push_str( |
| 277 | " (no token was sent: sign in with `braid login`, or set BRAID_TOKEN)", |
| 278 | ), |
| 279 | None => {} |
| 280 | } |
| 281 | } |
| 282 | Err(HubError::Api { status, body }) |
| 283 | } |
| 284 | |
| 285 | /// The JSON answer of a request to `path`. |
| 286 | fn read_json<T: DeserializeOwned>( |
| 287 | &self, |
| 288 | path: &str, |
| 289 | mut response: Response<Body>, |
| 290 | ) -> Result<T, HubError> { |
| 291 | let bytes = response |
| 292 | .body_mut() |
| 293 | .with_config() |
| 294 | .limit(MAX_JSON) |
| 295 | .read_to_vec() |
| 296 | .map_err(|err| self.transport(err))?; |
| 297 | serde_json::from_slice(&bytes).map_err(|err| { |
| 298 | HubError::Protocol(format!( |
| 299 | "{}{path} answered with something that is not the hub protocol ({err}): {}", |
| 300 | self.url, |
| 301 | excerpt(&bytes) |
| 302 | )) |
| 303 | }) |
| 304 | } |
| 305 | |
| 306 | fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T, HubError> { |
| 307 | let request = self.authorize(self.agent.get(self.uri(path))); |
| 308 | let response = self.check(request.call())?; |
| 309 | self.read_json(path, response) |
| 310 | } |
| 311 | |
| 312 | fn post_json<T: DeserializeOwned>( |
| 313 | &self, |
| 314 | path: &str, |
| 315 | body: &impl Serialize, |
| 316 | ) -> Result<T, HubError> { |
| 317 | let body = serde_json::to_vec(body).map_err(|err| HubError::Protocol(err.to_string()))?; |
| 318 | let request = self |
| 319 | .authorize(self.agent.post(self.uri(path))) |
| 320 | .header("Content-Type", "application/json"); |
| 321 | let response = self.check(request.send(&body[..]))?; |
| 322 | self.read_json(path, response) |
| 323 | } |
| 324 | |
| 325 | /// Any route of the hub: `method` on `path` (`/v1/…`), with the token, |
| 326 | /// `headers` and `body`, if any. The answer's body when it succeeds, |
| 327 | /// at most 64 MiB; its error otherwise, as [`HubError::Api`] for an |
| 328 | /// error answer. |
| 329 | pub(crate) fn call( |
| 330 | &self, |
| 331 | method: &str, |
| 332 | path: &str, |
| 333 | headers: &[(&str, &str)], |
| 334 | body: Option<&[u8]>, |
| 335 | ) -> Result<Vec<u8>, HubError> { |
| 336 | let mut request = ureq::http::Request::builder() |
| 337 | .method(method) |
| 338 | .uri(self.uri(path)); |
| 339 | if let Some(token) = &self.token |
| 340 | && let Ok(mut value) = HeaderValue::from_str(&format!("Bearer {}", token.expose())) |
| 341 | { |
| 342 | value.set_sensitive(true); |
| 343 | request = request.header("Authorization", value); |
| 344 | } |
| 345 | for (name, value) in headers { |
| 346 | request = request.header(*name, *value); |
| 347 | } |
| 348 | let invalid = |err: ureq::http::Error| { |
| 349 | HubError::Protocol(format!( |
| 350 | "{method} {} is not a request braid can send: {err}", |
| 351 | shown(path) |
| 352 | )) |
| 353 | }; |
| 354 | let sent = match body { |
| 355 | Some(body) => self |
| 356 | .agent |
| 357 | .run(request.body(body.to_vec()).map_err(invalid)?), |
| 358 | None => self.agent.run(request.body(()).map_err(invalid)?), |
| 359 | }; |
| 360 | let mut response = self.check(sent)?; |
| 361 | response |
| 362 | .body_mut() |
| 363 | .with_config() |
| 364 | .limit(MAX_JSON) |
| 365 | .read_to_vec() |
| 366 | .map_err(|err| self.transport(err)) |
| 367 | } |
| 368 | |
| 369 | /// [`call`](Self::call) with a JSON body, if any, whose answer is JSON. |
| 370 | #[allow(dead_code)] |
| 371 | pub(crate) fn call_json<T: DeserializeOwned>( |
| 372 | &self, |
| 373 | method: &str, |
| 374 | path: &str, |
| 375 | headers: &[(&str, &str)], |
| 376 | body: Option<&serde_json::Value>, |
| 377 | ) -> Result<T, HubError> { |
| 378 | let bytes = body |
| 379 | .map(serde_json::to_vec) |
| 380 | .transpose() |
| 381 | .map_err(|err| HubError::Protocol(err.to_string()))?; |
| 382 | let mut all = headers.to_vec(); |
| 383 | if bytes.is_some() { |
| 384 | all.push(("Content-Type", "application/json")); |
| 385 | } |
| 386 | let answer = self.call(method, path, &all, bytes.as_deref())?; |
| 387 | serde_json::from_slice(&answer).map_err(|err| { |
| 388 | HubError::Protocol(format!( |
| 389 | "{}{path} answered with something that is not the hub protocol ({err}): {}", |
| 390 | self.url, |
| 391 | excerpt(&answer) |
| 392 | )) |
| 393 | }) |
| 394 | } |
| 395 | |
| 396 | /// `POST path` (`/v1/…`) with the JSON `body`, answered as an object |
| 397 | /// stream, read as it comes, whatever its size: what the `missing` |
| 398 | /// routes answer to `Accept: application/x-braid-objects`. |
| 399 | pub(crate) fn post_for_objects( |
| 400 | &self, |
| 401 | path: &str, |
| 402 | body: &impl Serialize, |
| 403 | ) -> Result<Box<dyn Read + '_>, HubError> { |
| 404 | let body = serde_json::to_vec(body).map_err(|err| HubError::Protocol(err.to_string()))?; |
| 405 | let http = self |
| 406 | .authorize(self.agent.post(self.uri(path))) |
| 407 | .header("Content-Type", "application/json") |
| 408 | .header("Accept", OBJECTS_MEDIA_TYPE); |
| 409 | let response = self.check(http.send(&body[..]))?; |
| 410 | let media = response |
| 411 | .headers() |
| 412 | .get("content-type") |
| 413 | .and_then(|value| value.to_str().ok()) |
| 414 | .unwrap_or(""); |
| 415 | if !media.starts_with(OBJECTS_MEDIA_TYPE) { |
| 416 | return Err(HubError::Protocol(format!( |
| 417 | "asked for {OBJECTS_MEDIA_TYPE}, the hub answered {media:?}" |
| 418 | ))); |
| 419 | } |
| 420 | Ok(Box::new(response.into_body().into_reader())) |
| 421 | } |
| 422 | |
| 423 | /// `GET path` (`/v1/…`), with the token, its answer's body written to |
| 424 | /// `out` as it comes, whatever its size: a raw file. A failure to write |
| 425 | /// is [`HubError::Io`]. |
| 426 | pub(crate) fn get_to(&self, path: &str, out: &mut dyn std::io::Write) -> Result<(), HubError> { |
| 427 | let request = self.authorize(self.agent.get(self.uri(path))); |
| 428 | let response = self.check(request.call())?; |
| 429 | let mut reader = response.into_body().into_reader(); |
| 430 | let mut buffer = vec![0u8; 64 << 10]; |
| 431 | loop { |
| 432 | let n = match reader.read(&mut buffer) { |
| 433 | Ok(0) => return Ok(()), |
| 434 | Ok(n) => n, |
| 435 | Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue, |
| 436 | Err(err) => { |
| 437 | return Err(HubError::Transport { |
| 438 | hub: self.url.clone(), |
| 439 | detail: err.to_string(), |
| 440 | }); |
| 441 | } |
| 442 | }; |
| 443 | out.write_all(&buffer[..n]).map_err(HubError::Io)?; |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /// The start of an answer, for an error to quote: at most 200 characters, |
| 449 | /// without the secret of any token in it. |
| 450 | fn excerpt(bytes: &[u8]) -> String { |
| 451 | let text = String::from_utf8_lossy(bytes); |
| 452 | redact(text.trim()).chars().take(200).collect() |
| 453 | } |
| 454 | |
| 455 | impl DeviceFlow for HttpHub { |
| 456 | fn poll(&self, poll: &str) -> Result<DevicePoll, HubError> { |
| 457 | self.post_json( |
| 458 | "/v1/login/device/poll", |
| 459 | &DevicePollRequest { |
| 460 | poll: poll.to_owned(), |
| 461 | }, |
| 462 | ) |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | /// TLS through rustls with the ring provider, given explicitly, and the |
| 467 | /// root certificates the operating system trusts. |
| 468 | fn tls_config(url: &str) -> Result<TlsConfig, HubError> { |
| 469 | let found = rustls_native_certs::load_native_certs(); |
| 470 | let roots: Vec<Certificate<'static>> = found |
| 471 | .certs |
| 472 | .iter() |
| 473 | .map(|der| Certificate::from_der(der.as_ref()).to_owned()) |
| 474 | .collect(); |
| 475 | if roots.is_empty() { |
| 476 | let detail = match found.errors.first() { |
| 477 | Some(err) => format!("the system's root certificates cannot be read: {err}"), |
| 478 | None => "the system trusts no root certificate".to_owned(), |
| 479 | }; |
| 480 | return Err(HubError::Transport { |
| 481 | hub: url.to_owned(), |
| 482 | detail, |
| 483 | }); |
| 484 | } |
| 485 | Ok(TlsConfig::builder() |
| 486 | .provider(TlsProvider::Rustls) |
| 487 | .root_certs(RootCerts::Specific(Arc::new(roots))) |
| 488 | .unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider())) |
| 489 | .build()) |
| 490 | } |
| 491 | |
| 492 | /// One repository of an [`HttpHub`]. |
| 493 | pub(crate) struct HttpRepo<'h> { |
| 494 | hub: &'h HttpHub, |
| 495 | path: RepoPath, |
| 496 | } |
| 497 | |
| 498 | impl HttpRepo<'_> { |
| 499 | fn route(&self, rest: &str) -> String { |
| 500 | format!("{}{rest}", self.path.api_path()) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | impl Remote for HttpRepo<'_> { |
| 505 | fn refs(&self) -> Result<Refs, HubError> { |
| 506 | self.hub.get_json(&self.route("/refs")) |
| 507 | } |
| 508 | |
| 509 | fn info(&self) -> Result<RepoInfo, HubError> { |
| 510 | self.hub.get_json(&self.path.api_path()) |
| 511 | } |
| 512 | |
| 513 | fn kind(&self, id: &ObjectId) -> Result<Option<Kind>, HubError> { |
| 514 | let uri = self.hub.uri(&self.route(&format!("/o/{id}"))); |
| 515 | let request = self.hub.authorize(self.hub.agent.head(uri)); |
| 516 | let response = match self.hub.check(request.call()) { |
| 517 | Ok(response) => response, |
| 518 | Err(HubError::Api { status: 404, .. }) => return Ok(None), |
| 519 | Err(err) => return Err(err), |
| 520 | }; |
| 521 | let name = response |
| 522 | .headers() |
| 523 | .get(KIND_HEADER) |
| 524 | .and_then(|value| value.to_str().ok()) |
| 525 | .unwrap_or(""); |
| 526 | Kind::ALL |
| 527 | .into_iter() |
| 528 | .find(|kind| kind.name() == name) |
| 529 | .map(Some) |
| 530 | .ok_or_else(|| HubError::Protocol(format!("object {id} has no valid {KIND_HEADER}"))) |
| 531 | } |
| 532 | |
| 533 | fn lacks(&self, ids: &[ObjectId]) -> Result<Vec<ObjectId>, HubError> { |
| 534 | let request = LacksRequest { ids: ids.to_vec() }; |
| 535 | let response: LacksResponse = self.hub.post_json(&self.route("/lacks"), &request)?; |
| 536 | Ok(response.lacks) |
| 537 | } |
| 538 | |
| 539 | fn send_objects(&self, body: &mut dyn Read, len: u64) -> Result<u64, HubError> { |
| 540 | let route = self.route("/objects"); |
| 541 | let request = self |
| 542 | .hub |
| 543 | .authorize(self.hub.agent.post(self.hub.uri(&route))) |
| 544 | .header("Content-Type", OBJECTS_MEDIA_TYPE) |
| 545 | .header("Content-Length", len.to_string()); |
| 546 | let response = self.hub.check(request.send(SendBody::from_reader(body)))?; |
| 547 | let stored: Stored = self.hub.read_json(&route, response)?; |
| 548 | Ok(stored.stored) |
| 549 | } |
| 550 | |
| 551 | fn missing(&self, request: &MissingRequest) -> Result<Box<dyn Read + '_>, HubError> { |
| 552 | self.hub.post_for_objects(&self.route("/missing"), request) |
| 553 | } |
| 554 | |
| 555 | fn land(&self, request: &LandRequest) -> Result<LandResponse, HubError> { |
| 556 | self.hub.post_json(&self.route("/land"), request) |
| 557 | } |
| 558 | |
| 559 | fn max_body(&self) -> u64 { |
| 560 | self.hub.upload_limit() |
| 561 | } |
| 562 | |
| 563 | fn max_ids(&self) -> usize { |
| 564 | self.hub.id_limit() |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | /// The largest body to send, given the size this client was given and the |
| 569 | /// one the hub says it takes, if it said. |
| 570 | fn upload_limit(given: u64, hub: Option<u64>) -> u64 { |
| 571 | match hub { |
| 572 | Some(hub) if hub > 0 => given.min(hub), |
| 573 | _ => given, |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | #[cfg(test)] |
| 578 | mod tests { |
| 579 | use std::io::{BufRead, BufReader, Write as _}; |
| 580 | use std::net::{TcpListener, TcpStream}; |
| 581 | use std::thread::JoinHandle; |
| 582 | |
| 583 | use serde_json::{Value, json}; |
| 584 | |
| 585 | use super::*; |
| 586 | |
| 587 | #[test] |
| 588 | fn uploads_fit_the_hub_and_the_client() { |
| 589 | assert_eq!(upload_limit(MAX_BODY, None), MAX_BODY); |
| 590 | assert_eq!(upload_limit(MAX_BODY, Some(64 << 10)), 64 << 10); |
| 591 | assert_eq!(upload_limit(1 << 20, Some(MAX_BODY)), 1 << 20); |
| 592 | assert_eq!(upload_limit(1 << 20, Some(0)), 1 << 20); |
| 593 | } |
| 594 | |
| 595 | /// A request as [`fake_hub`] read it: its request line, its headers |
| 596 | /// with their names lowercase, and its body. |
| 597 | #[derive(Debug, Default)] |
| 598 | struct Seen { |
| 599 | line: String, |
| 600 | headers: Vec<(String, String)>, |
| 601 | body: Vec<u8>, |
| 602 | } |
| 603 | |
| 604 | impl Seen { |
| 605 | fn header(&self, name: &str) -> Option<&str> { |
| 606 | self.headers |
| 607 | .iter() |
| 608 | .find(|(key, _)| key == name) |
| 609 | .map(|(_, value)| value.as_str()) |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | /// A stand-in for a hub, listening on this machine: it reads one |
| 614 | /// request per connection, gives each of `answers` in turn (a status, |
| 615 | /// and a JSON body, or none when it is empty), and hands back what it |
| 616 | /// was sent. |
| 617 | fn fake_hub(answers: Vec<(&'static str, &'static str)>) -> (String, JoinHandle<Vec<Seen>>) { |
| 618 | let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); |
| 619 | let url = format!("http://{}", listener.local_addr().unwrap()); |
| 620 | let server = std::thread::spawn(move || { |
| 621 | let mut seen = Vec::new(); |
| 622 | for (status, body) in answers { |
| 623 | let (stream, _) = listener.accept().unwrap(); |
| 624 | seen.push(read_request(&stream)); |
| 625 | answer(stream, status, body); |
| 626 | } |
| 627 | seen |
| 628 | }); |
| 629 | (url, server) |
| 630 | } |
| 631 | |
| 632 | fn read_request(stream: &TcpStream) -> Seen { |
| 633 | let mut reader = BufReader::new(stream); |
| 634 | let mut seen = Seen::default(); |
| 635 | reader.read_line(&mut seen.line).unwrap(); |
| 636 | seen.line.truncate(seen.line.trim_end().len()); |
| 637 | loop { |
| 638 | let mut line = String::new(); |
| 639 | reader.read_line(&mut line).unwrap(); |
| 640 | let line = line.trim_end(); |
| 641 | if line.is_empty() { |
| 642 | break; |
| 643 | } |
| 644 | let (name, value) = line.split_once(':').unwrap(); |
| 645 | seen.headers |
| 646 | .push((name.trim().to_ascii_lowercase(), value.trim().to_owned())); |
| 647 | } |
| 648 | let length = seen |
| 649 | .header("content-length") |
| 650 | .map_or(0, |n| n.parse().unwrap()); |
| 651 | seen.body = vec![0; length]; |
| 652 | reader.read_exact(&mut seen.body).unwrap(); |
| 653 | seen |
| 654 | } |
| 655 | |
| 656 | /// Answers with `status` and the JSON `body`, if any, and closes. |
| 657 | fn answer(mut stream: TcpStream, status: &str, body: &str) { |
| 658 | if body.is_empty() { |
| 659 | write!(stream, "HTTP/1.1 {status}\r\nConnection: close\r\n\r\n").unwrap(); |
| 660 | } else { |
| 661 | write!( |
| 662 | stream, |
| 663 | "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", |
| 664 | body.len() |
| 665 | ) |
| 666 | .unwrap(); |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | #[test] |
| 671 | fn any_route_with_or_without_a_body() { |
| 672 | let (url, server) = fake_hub(vec![ |
| 673 | ("200 OK", r#"{"login":"ada"}"#), |
| 674 | ("201 Created", r#"{"name":"demo","private":true}"#), |
| 675 | ("204 No Content", ""), |
| 676 | ( |
| 677 | "404 Not Found", |
| 678 | r#"{"error":"not_found","detail":"no such repository"}"#, |
| 679 | ), |
| 680 | ("200 OK", r#"{"version":1}"#), |
| 681 | ]); |
| 682 | let token = Token::from_random([1; 5], [2; 32]); |
| 683 | let client = HttpHub::new(&url, Some(token.clone())).unwrap(); |
| 684 | let me: Value = client.call_json("GET", "/v1/me", &[], None).unwrap(); |
| 685 | assert_eq!(me["login"], "ada"); |
| 686 | let body = json!({"name": "demo"}); |
| 687 | let made: Value = client |
| 688 | .call_json( |
| 689 | "POST", |
| 690 | "/v1/repos", |
| 691 | &[("Idempotency-Key", "k1")], |
| 692 | Some(&body), |
| 693 | ) |
| 694 | .unwrap(); |
| 695 | assert_eq!(made["private"], true); |
| 696 | // An answer without a body; an error answer. |
| 697 | let gone = client.call("DELETE", "/v1/r/ada/demo", &[], None).unwrap(); |
| 698 | assert!(gone.is_empty()); |
| 699 | match client.call("GET", "/v1/r/ada/demo", &[], None) { |
| 700 | Err(HubError::Api { status: 404, body }) => assert_eq!(body.error, "not_found"), |
| 701 | other => panic!("{other:?}"), |
| 702 | } |
| 703 | let anonymous = HttpHub::new(&url, None).unwrap(); |
| 704 | let root: Value = anonymous.call_json("GET", "/v1", &[], None).unwrap(); |
| 705 | assert_eq!(root["version"], 1); |
| 706 | |
| 707 | let seen = server.join().unwrap(); |
| 708 | let lines: Vec<&str> = seen.iter().map(|request| request.line.as_str()).collect(); |
| 709 | assert_eq!( |
| 710 | lines, |
| 711 | [ |
| 712 | "GET /v1/me HTTP/1.1", |
| 713 | "POST /v1/repos HTTP/1.1", |
| 714 | "DELETE /v1/r/ada/demo HTTP/1.1", |
| 715 | "GET /v1/r/ada/demo HTTP/1.1", |
| 716 | "GET /v1 HTTP/1.1", |
| 717 | ] |
| 718 | ); |
| 719 | // The token goes with every request of the client that has one, and |
| 720 | // with no other; every request says it is braid. |
| 721 | let bearer = format!("Bearer {}", token.expose()); |
| 722 | for request in &seen[..4] { |
| 723 | assert_eq!(request.header("authorization"), Some(bearer.as_str())); |
| 724 | } |
| 725 | assert_eq!(seen[4].header("authorization"), None); |
| 726 | assert!( |
| 727 | seen.iter() |
| 728 | .all(|request| request.header("user-agent") == Some(USER_AGENT)) |
| 729 | ); |
| 730 | // A JSON body goes as JSON, with the headers asked for, and the |
| 731 | // requests without one carry none. |
| 732 | assert_eq!(seen[1].header("content-type"), Some("application/json")); |
| 733 | assert_eq!(seen[1].header("idempotency-key"), Some("k1")); |
| 734 | assert_eq!( |
| 735 | serde_json::from_slice::<Value>(&seen[1].body).unwrap(), |
| 736 | body |
| 737 | ); |
| 738 | for (n, request) in seen.iter().enumerate().filter(|(n, _)| *n != 1) { |
| 739 | assert!(request.body.is_empty(), "request {n}"); |
| 740 | assert_eq!(request.header("content-type"), None, "request {n}"); |
| 741 | } |
| 742 | } |
| 743 | } |