Elffuss BraidHub

utopia-ia/elffuss-braid public

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