| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The hub commands of the `braid` binary where no hub answers: what is |
| 5 | //! refused before anything goes over the network, what a linked repository |
| 6 | //! does when its hub cannot be reached, and how `--local` and |
| 7 | //! `BRAID_HUB=off` keep landing and updating local; and `braid hub verify` |
| 8 | //! against a stand-in that gives the answers a hub would. Every test gets a |
| 9 | //! configuration directory of its own, and a token is never printed. |
| 10 | |
| 11 | use std::fs; |
| 12 | use std::io::{BufRead, BufReader, Read, Write}; |
| 13 | use std::net::{TcpListener, TcpStream}; |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | use std::process::{Command, Output}; |
| 16 | use std::thread::JoinHandle; |
| 17 | |
| 18 | use serde_json::Value; |
| 19 | |
| 20 | /// A home, a configuration directory and a repository, in a temporary |
| 21 | /// directory. |
| 22 | struct Place { |
| 23 | _temp: tempfile::TempDir, |
| 24 | base: PathBuf, |
| 25 | root: PathBuf, |
| 26 | } |
| 27 | |
| 28 | impl Place { |
| 29 | fn new() -> Place { |
| 30 | let temp = tempfile::tempdir().unwrap(); |
| 31 | let base = fs::canonicalize(temp.path()).unwrap(); |
| 32 | let root = base.join("repo"); |
| 33 | let place = Place { |
| 34 | _temp: temp, |
| 35 | base, |
| 36 | root, |
| 37 | }; |
| 38 | let out = place.braid(&place.base, &["init", "repo"], &[]); |
| 39 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 40 | place |
| 41 | } |
| 42 | |
| 43 | /// Runs braid in `dir`, with `env` on top of a clean environment. |
| 44 | fn braid(&self, dir: &Path, args: &[&str], env: &[(&str, &str)]) -> Output { |
| 45 | let mut command = Command::new(env!("CARGO_BIN_EXE_braid")); |
| 46 | command |
| 47 | .current_dir(dir) |
| 48 | .args(args) |
| 49 | .env("HOME", self.base.join("home")) |
| 50 | .env("XDG_CONFIG_HOME", self.base.join("config")) |
| 51 | .env("BRAID_AUTHOR", "Ada <ada@example.org>") |
| 52 | .env("BRAID_AGENT", "tester") |
| 53 | .env_remove("BRAID_TOKEN") |
| 54 | .env_remove("BRAID_HUB_URL") |
| 55 | .env_remove("BRAID_HUB"); |
| 56 | for (key, value) in env { |
| 57 | command.env(key, value); |
| 58 | } |
| 59 | command.output().unwrap() |
| 60 | } |
| 61 | |
| 62 | /// Links the repository to a hub on this machine where nothing |
| 63 | /// listens, and returns its URL. |
| 64 | fn link_to_nowhere(&self) -> String { |
| 65 | let port = TcpListener::bind("127.0.0.1:0") |
| 66 | .unwrap() |
| 67 | .local_addr() |
| 68 | .unwrap() |
| 69 | .port(); |
| 70 | let url = format!("http://127.0.0.1:{port}"); |
| 71 | fs::write( |
| 72 | self.root.join(".braid/hub"), |
| 73 | format!("{{\"url\": \"{url}\", \"repo\": \"ada/demo\"}}\n"), |
| 74 | ) |
| 75 | .unwrap(); |
| 76 | url |
| 77 | } |
| 78 | |
| 79 | /// Makes a workspace and commits a file in it. |
| 80 | fn workspace_with_a_commit(&self, name: &str) -> PathBuf { |
| 81 | let out = self.braid(&self.root, &["workspace", "add", name], &[]); |
| 82 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 83 | let dir = self.root.join(".braid/work").join(name); |
| 84 | self.commit(&dir, "a.txt", "one\n"); |
| 85 | dir |
| 86 | } |
| 87 | |
| 88 | fn commit(&self, dir: &Path, path: &str, content: &str) { |
| 89 | fs::write(dir.join(path), content).unwrap(); |
| 90 | let out = self.braid(dir, &["commit", "-m", path], &[]); |
| 91 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | fn text(bytes: &[u8]) -> String { |
| 96 | String::from_utf8_lossy(bytes).into_owned() |
| 97 | } |
| 98 | |
| 99 | /// Asserts that `out` failed with status 1, nothing on standard output, |
| 100 | /// and an error that says `expected`. |
| 101 | fn fails_with(out: &Output, expected: &str) { |
| 102 | let err = text(&out.stderr); |
| 103 | assert_eq!(out.status.code(), Some(1), "{err}"); |
| 104 | assert!(out.stdout.is_empty(), "{}", text(&out.stdout)); |
| 105 | assert!(err.starts_with("braid: error: "), "{err}"); |
| 106 | assert!(err.contains(expected), "expected {expected:?} in {err}"); |
| 107 | } |
| 108 | |
| 109 | fn json(out: &Output) -> Value { |
| 110 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 111 | serde_json::from_slice(&out.stdout).unwrap() |
| 112 | } |
| 113 | |
| 114 | #[test] |
| 115 | fn refused_before_any_request() { |
| 116 | let p = Place::new(); |
| 117 | fails_with( |
| 118 | &p.braid(&p.root, &["hub", "status"], &[]), |
| 119 | "not linked to a hub", |
| 120 | ); |
| 121 | fails_with( |
| 122 | &p.braid(&p.root, &["hub", "fetch"], &[]), |
| 123 | "not linked to a hub", |
| 124 | ); |
| 125 | // Publishing needs a token, and nothing is linked without one. |
| 126 | fails_with( |
| 127 | &p.braid(&p.root, &["hub", "publish"], &[]), |
| 128 | "publishing needs signing in", |
| 129 | ); |
| 130 | assert!(!p.root.join(".braid/hub").exists()); |
| 131 | // A token is never sent in clear to another machine. |
| 132 | fails_with( |
| 133 | &p.braid(&p.base, &["login", "--hub", "http://hub.example.org"], &[]), |
| 134 | "would send the token in clear", |
| 135 | ); |
| 136 | fails_with( |
| 137 | &p.braid( |
| 138 | &p.root, |
| 139 | &["hub", "publish"], |
| 140 | &[("BRAID_HUB_URL", "http://hub.example.org")], |
| 141 | ), |
| 142 | "would send the token in clear", |
| 143 | ); |
| 144 | fails_with( |
| 145 | &p.braid(&p.base, &["hub", "clone", "nobody"], &[]), |
| 146 | "is not a repository", |
| 147 | ); |
| 148 | fails_with( |
| 149 | &p.braid( |
| 150 | &p.base, |
| 151 | &["hub", "clone", "ada/demo", "--paths", "../etc"], |
| 152 | &[], |
| 153 | ), |
| 154 | "is not a path prefix", |
| 155 | ); |
| 156 | // A malformed token is refused without being repeated. |
| 157 | let secret = "brd_aaaaaaaa_this-is-not-base32-and-must-not-show"; |
| 158 | fails_with( |
| 159 | &p.braid(&p.root, &["hub", "publish"], &[("BRAID_TOKEN", secret)]), |
| 160 | "BRAID_TOKEN is not a braid hub token", |
| 161 | ); |
| 162 | let out = p.braid(&p.root, &["hub", "publish"], &[("BRAID_TOKEN", secret)]); |
| 163 | assert!(!text(&out.stderr).contains("must-not-show")); |
| 164 | // Logging out of a hub never signed in to says so. |
| 165 | let out = p.braid(&p.base, &["logout", "--json"], &[]); |
| 166 | let value = json(&out); |
| 167 | assert_eq!(value["signed_in"], false); |
| 168 | assert_eq!(value["hub"], "https://braidhub.elffuss.com"); |
| 169 | fails_with( |
| 170 | &p.braid(&p.base, &["hub", "whoami"], &[]), |
| 171 | "no one is signed in to https://braidhub.elffuss.com: run `braid login`, or set BRAID_TOKEN", |
| 172 | ); |
| 173 | fails_with( |
| 174 | &p.braid( |
| 175 | &p.base, |
| 176 | &["hub", "whoami", "--hub", "http://localhost:1"], |
| 177 | &[], |
| 178 | ), |
| 179 | "run `braid login --hub http://localhost:1`", |
| 180 | ); |
| 181 | fails_with( |
| 182 | &p.braid( |
| 183 | &p.root, |
| 184 | &["hub", "publish"], |
| 185 | &[ |
| 186 | ( |
| 187 | "BRAID_TOKEN", |
| 188 | "brd_aaaaaaaa_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", |
| 189 | ), |
| 190 | ("BRAID_HUB_MAX_BODY", "lots"), |
| 191 | ], |
| 192 | ), |
| 193 | "BRAID_HUB_MAX_BODY takes a number of bytes", |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn the_autopublish_answer_is_kept_for_every_project() { |
| 199 | let p = Place::new(); |
| 200 | let ask = |args: &[&str]| -> String { |
| 201 | let out = p.braid(&p.base, args, &[]); |
| 202 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 203 | text(&out.stdout) |
| 204 | }; |
| 205 | assert_eq!(ask(&["hub", "autopublish"]), "unset\n"); |
| 206 | let file = p.base.join("config/braid/hub.json"); |
| 207 | assert!(!file.exists()); |
| 208 | assert_eq!(ask(&["hub", "autopublish", "on"]), "on\n"); |
| 209 | assert_eq!(ask(&["hub", "autopublish"]), "on\n"); |
| 210 | let value = json(&p.braid(&p.root, &["hub", "autopublish", "--json"], &[])); |
| 211 | assert_eq!(value, serde_json::json!({ "autopublish": "on" })); |
| 212 | let value = json(&p.braid(&p.root, &["hub", "autopublish", "off", "--json"], &[])); |
| 213 | assert_eq!(value["autopublish"], "off"); |
| 214 | let saved: Value = serde_json::from_slice(&fs::read(&file).unwrap()).unwrap(); |
| 215 | assert_eq!(saved["autopublish"], false); |
| 216 | #[cfg(unix)] |
| 217 | { |
| 218 | use std::os::unix::fs::PermissionsExt; |
| 219 | let mode = fs::metadata(&file).unwrap().permissions().mode() & 0o777; |
| 220 | assert_eq!(mode, 0o600); |
| 221 | } |
| 222 | let out = p.braid(&p.base, &["hub", "autopublish", "maybe"], &[]); |
| 223 | assert_eq!(out.status.code(), Some(2), "{}", text(&out.stderr)); |
| 224 | assert_eq!(ask(&["hub", "autopublish"]), "off\n"); |
| 225 | } |
| 226 | |
| 227 | /// The ```bash blocks and the code spans of a Markdown text: its lines that |
| 228 | /// may hold commands. |
| 229 | fn command_lines(text: &str) -> Vec<String> { |
| 230 | let mut lines = Vec::new(); |
| 231 | let mut fenced = None; |
| 232 | let mut prose = Vec::new(); |
| 233 | for line in text.lines() { |
| 234 | let trimmed = line.trim(); |
| 235 | if trimmed.starts_with("```") { |
| 236 | fenced = match fenced { |
| 237 | None => Some(trimmed == "```bash"), |
| 238 | Some(_) => None, |
| 239 | }; |
| 240 | continue; |
| 241 | } |
| 242 | match fenced { |
| 243 | Some(true) => lines.push(trimmed.to_owned()), |
| 244 | Some(false) => {} |
| 245 | None => prose.push(trimmed.to_owned()), |
| 246 | } |
| 247 | } |
| 248 | let prose = prose.join(" "); |
| 249 | lines.extend(prose.split('`').skip(1).step_by(2).map(str::to_owned)); |
| 250 | lines |
| 251 | } |
| 252 | |
| 253 | /// Whether the help `shown` lists `word` among its commands. |
| 254 | fn lists_command(shown: &str, word: &str) -> bool { |
| 255 | shown |
| 256 | .lines() |
| 257 | .skip_while(|line| line.trim() != "Commands:") |
| 258 | .skip(1) |
| 259 | .take_while(|line| line.starts_with(" ")) |
| 260 | .any(|line| line.split_whitespace().next() == Some(word)) |
| 261 | } |
| 262 | |
| 263 | /// Every braid command docs/hub-agents.md, the guide the hub serves at |
| 264 | /// /agents.md, gives exists, with every flag it is given. |
| 265 | #[test] |
| 266 | fn every_braid_command_in_the_hub_guide_exists_with_its_flags() { |
| 267 | let guide = |
| 268 | fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/hub-agents.md")) |
| 269 | .unwrap(); |
| 270 | let mut commands = Vec::new(); |
| 271 | let mut flags = Vec::new(); |
| 272 | for line in command_lines(&guide) { |
| 273 | let line = line.split(" #").next().unwrap(); |
| 274 | for command in line.split(['|', '&', ';']).map(str::trim) { |
| 275 | if command.starts_with("braid ") { |
| 276 | commands.push(command.to_owned()); |
| 277 | } else if command.starts_with("--") { |
| 278 | flags.push(command.split_whitespace().next().unwrap().to_owned()); |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | assert!(commands.len() >= 12, "{commands:?}"); |
| 283 | let help = |path: &[&str]| -> String { |
| 284 | let mut args = path.to_vec(); |
| 285 | args.push("--help"); |
| 286 | let out = Command::new(env!("CARGO_BIN_EXE_braid")) |
| 287 | .args(&args) |
| 288 | .output() |
| 289 | .unwrap(); |
| 290 | assert!( |
| 291 | out.status.success(), |
| 292 | "braid {args:?}: {}", |
| 293 | text(&out.stderr) |
| 294 | ); |
| 295 | text(&out.stdout) |
| 296 | }; |
| 297 | let mut helps = String::new(); |
| 298 | for command in &commands { |
| 299 | let words: Vec<&str> = command.split_whitespace().skip(1).collect(); |
| 300 | if words == ["--version"] { |
| 301 | continue; |
| 302 | } |
| 303 | let mut path = vec![words[0]]; |
| 304 | // Commands with subcommands of their own: the flags are those of |
| 305 | // the subcommand. |
| 306 | if ["hub", "change", "workspace", "git", "op", "agents"].contains(&words[0]) |
| 307 | && words.get(1).is_some_and(|word| !word.starts_with('-')) |
| 308 | { |
| 309 | path.push(words[1]); |
| 310 | } |
| 311 | let mut shown = help(&path); |
| 312 | // A subcommand with commands of its own (`braid hub request |
| 313 | // create`): the flags are those of its command. |
| 314 | if path.len() == 2 |
| 315 | && let Some(&word) = words.get(2) |
| 316 | && lists_command(&shown, word) |
| 317 | { |
| 318 | path.push(word); |
| 319 | shown = help(&path); |
| 320 | } |
| 321 | for word in &words[path.len()..] { |
| 322 | if word.starts_with('-') { |
| 323 | let flag = word.split('=').next().unwrap(); |
| 324 | assert!( |
| 325 | shown.contains(flag), |
| 326 | "{command}: no {flag} in braid {path:?}" |
| 327 | ); |
| 328 | } |
| 329 | } |
| 330 | helps.push_str(&shown); |
| 331 | } |
| 332 | // Flags the guide names on their own belong to the commands it gives. |
| 333 | assert!(flags.len() >= 3, "{flags:?}"); |
| 334 | for flag in &flags { |
| 335 | assert!( |
| 336 | helps.contains(flag.as_str()), |
| 337 | "{flag} is no flag of the guide's commands" |
| 338 | ); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | #[test] |
| 343 | fn a_linked_repository_goes_to_its_hub_unless_kept_local() { |
| 344 | let p = Place::new(); |
| 345 | let url = p.link_to_nowhere(); |
| 346 | let ws = p.workspace_with_a_commit("w1"); |
| 347 | |
| 348 | // Landing goes to the hub, which cannot be reached: nothing moves. |
| 349 | let out = p.braid(&ws, &["land", "--json"], &[]); |
| 350 | fails_with(&out, &format!("cannot reach the hub at {url}")); |
| 351 | let refs = json(&p.braid(&p.root, &["refs", "--json"], &[])); |
| 352 | assert_eq!(refs["refs"]["main"], Value::Null); |
| 353 | |
| 354 | // BRAID_HUB=off and --local land here, as before. |
| 355 | let landed = json(&p.braid(&ws, &["land", "--json"], &[("BRAID_HUB", "off")])); |
| 356 | assert_eq!(landed["outcome"], "fast-forward"); |
| 357 | for key in [ |
| 358 | "branch", |
| 359 | "outcome", |
| 360 | "head_before", |
| 361 | "head", |
| 362 | "landed", |
| 363 | "merged_paths", |
| 364 | "operation", |
| 365 | "change", |
| 366 | "conflicts", |
| 367 | "next", |
| 368 | "base", |
| 369 | "updated_paths", |
| 370 | ] { |
| 371 | assert!(landed.get(key).is_some(), "{key}: {landed}"); |
| 372 | } |
| 373 | p.commit(&ws, "b.txt", "two\n"); |
| 374 | let landed = json(&p.braid(&ws, &["land", "--local", "--json"], &[])); |
| 375 | assert_eq!(landed["outcome"], "fast-forward"); |
| 376 | |
| 377 | // Updating fetches first, and says how to do without. |
| 378 | fails_with(&p.braid(&ws, &["update"], &[]), "--local"); |
| 379 | let updated = json(&p.braid(&ws, &["update", "--local", "--json"], &[])); |
| 380 | assert_eq!(updated["outcome"], "up-to-date"); |
| 381 | let out = p.braid(&ws, &["update"], &[("BRAID_HUB", "off")]); |
| 382 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 383 | |
| 384 | // change create --land too. |
| 385 | let file = p.base.join("c.txt"); |
| 386 | fs::write(&file, "c\n").unwrap(); |
| 387 | let set = format!("c.txt=@{}", file.display()); |
| 388 | let create = [ |
| 389 | "change", "create", "--base", "main", "--set", &set, "-m", "c", "--land", "main", |
| 390 | ]; |
| 391 | fails_with(&p.braid(&p.root, &create, &[]), "cannot reach the hub"); |
| 392 | let mut local = create.to_vec(); |
| 393 | local.push("--local"); |
| 394 | let made = json(&p.braid(&p.root, &local, &[])); |
| 395 | assert_eq!(made["land"]["outcome"], "fast-forward"); |
| 396 | |
| 397 | // A value of BRAID_HUB that means nothing is refused. |
| 398 | fails_with( |
| 399 | &p.braid(&ws, &["land"], &[("BRAID_HUB", "maybe")]), |
| 400 | "BRAID_HUB takes", |
| 401 | ); |
| 402 | |
| 403 | // The hub commands name the hub they cannot reach, and never the |
| 404 | // token they would have sent. |
| 405 | let token = "brd_aaaaaaaa_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; |
| 406 | for args in [&["hub", "fetch"][..], &["hub", "status"]] { |
| 407 | let out = p.braid(&p.root, args, &[("BRAID_TOKEN", token)]); |
| 408 | fails_with(&out, &format!("cannot reach the hub at {url}")); |
| 409 | assert!(!text(&out.stderr).contains("bbbbbbbbbbbbbbbb")); |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn a_damaged_link_is_an_error_that_names_it() { |
| 415 | let p = Place::new(); |
| 416 | fs::write(p.root.join(".braid/hub"), b"{\"url\": \"https://x\"}").unwrap(); |
| 417 | let ws = p.workspace_with_a_commit("w1"); |
| 418 | fails_with(&p.braid(&ws, &["land"], &[]), "is not a valid hub link"); |
| 419 | // --local does not read it. |
| 420 | let out = p.braid(&ws, &["land", "--local"], &[]); |
| 421 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 422 | } |
| 423 | |
| 424 | /// `braid status --json` gives the hub's green and red of the branch as a |
| 425 | /// fetch last recorded them, and null where none was. |
| 426 | #[test] |
| 427 | fn status_gives_the_hubs_green_and_red_as_last_seen() { |
| 428 | let p = Place::new(); |
| 429 | let ws = p.workspace_with_a_commit("w1"); |
| 430 | let landed = json(&p.braid(&ws, &["land", "--local", "--json"], &[])); |
| 431 | let head = landed["head"].as_str().unwrap().to_owned(); |
| 432 | let status = json(&p.braid(&ws, &["status", "--json"], &[])); |
| 433 | assert_eq!( |
| 434 | (&status["hub_green"], &status["hub_red"]), |
| 435 | (&Value::Null, &Value::Null) |
| 436 | ); |
| 437 | for name in ["remote/hub/braid/green/main", "remote/hub/braid/red/main"] { |
| 438 | let out = p.braid(&p.root, &["ref", "set", name, &head], &[]); |
| 439 | assert!(out.status.success(), "{}", text(&out.stderr)); |
| 440 | } |
| 441 | let status = json(&p.braid(&ws, &["status", "--json"], &[])); |
| 442 | assert_eq!(status["hub_green"], head.as_str()); |
| 443 | assert_eq!(status["hub_red"], head.as_str()); |
| 444 | // The local green of `braid verify` is another ref. |
| 445 | assert_eq!(status["green"], Value::Null); |
| 446 | } |
| 447 | |
| 448 | /// A request a stand-in hub read: its request line, its `Idempotency-Key` |
| 449 | /// and its body. |
| 450 | #[derive(Debug, Default, PartialEq, Eq)] |
| 451 | struct Seen { |
| 452 | line: String, |
| 453 | key: Option<String>, |
| 454 | body: String, |
| 455 | } |
| 456 | |
| 457 | /// What `GET /v1` answers on a hub that verifies branches. |
| 458 | const VERIFYING: &str = 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"]}"#; |
| 459 | |
| 460 | /// A stand-in for a hub on this machine: it reads one request per |
| 461 | /// connection and gives each of `answers` in turn, a status and a JSON |
| 462 | /// body, or closes the connection without a word for an empty status, as |
| 463 | /// when an answer is lost. It hands back what it was sent. |
| 464 | fn stand_in(answers: Vec<(&'static str, &'static str)>) -> (String, JoinHandle<Vec<Seen>>) { |
| 465 | let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); |
| 466 | let url = format!("http://{}", listener.local_addr().unwrap()); |
| 467 | let server = std::thread::spawn(move || { |
| 468 | let mut seen = Vec::new(); |
| 469 | for (status, body) in answers { |
| 470 | let (mut stream, _) = listener.accept().unwrap(); |
| 471 | seen.push(read_request(&stream)); |
| 472 | if !status.is_empty() { |
| 473 | write!( |
| 474 | stream, |
| 475 | "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", |
| 476 | body.len() |
| 477 | ) |
| 478 | .unwrap(); |
| 479 | } |
| 480 | } |
| 481 | seen |
| 482 | }); |
| 483 | (url, server) |
| 484 | } |
| 485 | |
| 486 | fn read_request(stream: &TcpStream) -> Seen { |
| 487 | let mut reader = BufReader::new(stream); |
| 488 | let mut seen = Seen::default(); |
| 489 | reader.read_line(&mut seen.line).unwrap(); |
| 490 | seen.line.truncate(seen.line.trim_end().len()); |
| 491 | let mut length = 0; |
| 492 | loop { |
| 493 | let mut line = String::new(); |
| 494 | reader.read_line(&mut line).unwrap(); |
| 495 | let Some((name, value)) = line.trim_end().split_once(':') else { |
| 496 | break; |
| 497 | }; |
| 498 | match name.trim().to_ascii_lowercase().as_str() { |
| 499 | "idempotency-key" => seen.key = Some(value.trim().to_owned()), |
| 500 | "content-length" => length = value.trim().parse().unwrap(), |
| 501 | _ => {} |
| 502 | } |
| 503 | } |
| 504 | let mut body = vec![0; length]; |
| 505 | reader.read_exact(&mut body).unwrap(); |
| 506 | seen.body = String::from_utf8(body).unwrap(); |
| 507 | seen |
| 508 | } |
| 509 | |
| 510 | /// `braid hub verify` and its exit statuses, against a stand-in hub. |
| 511 | #[test] |
| 512 | fn verify_commands_and_their_exit_statuses() { |
| 513 | let p = Place::new(); |
| 514 | let token = "brd_aaaaaaaa_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; |
| 515 | let verify = |url: &str, args: &[&str]| -> Output { |
| 516 | let mut line = vec!["hub", "verify"]; |
| 517 | line.extend(args); |
| 518 | p.braid( |
| 519 | &p.base, |
| 520 | &line, |
| 521 | &[("BRAID_HUB_URL", url), ("BRAID_TOKEN", token)], |
| 522 | ) |
| 523 | }; |
| 524 | let red = r#"{"mode":"report","branch":"main","state":"red","red":null,"later":[1]}"#; |
| 525 | |
| 526 | // Red: 4 with --fail-on-red, and the answer printed whole. |
| 527 | let (url, server) = stand_in(vec![("200 OK", VERIFYING), ("200 OK", red)]); |
| 528 | let out = verify( |
| 529 | &url, |
| 530 | &["status", "-R", "ada/demo", "--fail-on-red", "--json"], |
| 531 | ); |
| 532 | assert_eq!(out.status.code(), Some(4), "{}", text(&out.stderr)); |
| 533 | let printed: Value = serde_json::from_slice(&out.stdout).unwrap(); |
| 534 | assert_eq!(printed, serde_json::from_str::<Value>(red).unwrap()); |
| 535 | let lines: Vec<String> = server |
| 536 | .join() |
| 537 | .unwrap() |
| 538 | .into_iter() |
| 539 | .map(|seen| seen.line) |
| 540 | .collect(); |
| 541 | assert_eq!( |
| 542 | lines, |
| 543 | ["GET /v1 HTTP/1.1", "GET /v1/r/ada/demo/verify HTTP/1.1"] |
| 544 | ); |
| 545 | // Without the flag, 0, and words. |
| 546 | let (url, _server) = stand_in(vec![("200 OK", VERIFYING), ("200 OK", red)]); |
| 547 | let out = verify(&url, &["status", "-R", "ada/demo"]); |
| 548 | assert_eq!(out.status.code(), Some(0), "{}", text(&out.stderr)); |
| 549 | assert!(text(&out.stdout).starts_with("ada/demo main: red")); |
| 550 | |
| 551 | // A hub that does not verify is asked nothing more. |
| 552 | let (url, server) = stand_in(vec![( |
| 553 | "200 OK", |
| 554 | 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}}"#, |
| 555 | )]); |
| 556 | fails_with( |
| 557 | &verify(&url, &["status", "-R", "ada/demo"]), |
| 558 | "does not verify branches", |
| 559 | ); |
| 560 | assert_eq!(server.join().unwrap().len(), 1); |
| 561 | |
| 562 | // A refusal is 1, with the hub's reason. |
| 563 | let (url, _server) = stand_in(vec![ |
| 564 | ("200 OK", VERIFYING), |
| 565 | ( |
| 566 | "403 Forbidden", |
| 567 | r#"{"error":"forbidden","detail":"use a token with read and verify:<glob> only"}"#, |
| 568 | ), |
| 569 | ]); |
| 570 | let out = verify( |
| 571 | &url, |
| 572 | &[ |
| 573 | "report", |
| 574 | "-R", |
| 575 | "ada/demo", |
| 576 | "--outcome", |
| 577 | "pass", |
| 578 | "--git-commit", |
| 579 | &"0a".repeat(20), |
| 580 | "--suite", |
| 581 | "ci", |
| 582 | ], |
| 583 | ); |
| 584 | fails_with(&out, "use a token with read and verify:<glob> only"); |
| 585 | assert!(!text(&out.stderr).contains("bbbbbbbbbbbbbbbb")); |
| 586 | |
| 587 | // A hub out of reach is 3. |
| 588 | let nowhere = { |
| 589 | let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); |
| 590 | format!("http://{}", listener.local_addr().unwrap()) |
| 591 | }; |
| 592 | let out = verify(&nowhere, &["status", "-R", "ada/demo"]); |
| 593 | assert_eq!(out.status.code(), Some(3), "{}", text(&out.stderr)); |
| 594 | assert!(text(&out.stderr).contains("cannot reach the hub")); |
| 595 | |
| 596 | // A report whose answer is lost goes again with the same key, and the |
| 597 | // hub's first answer is printed. |
| 598 | let answer = |
| 599 | r#"{"effect":"green_moved","status":{"mode":"report","branch":"main","state":"green"}}"#; |
| 600 | let (url, server) = stand_in(vec![ |
| 601 | ("200 OK", VERIFYING), |
| 602 | ("", ""), |
| 603 | ("201 Created", answer), |
| 604 | ]); |
| 605 | let commit = "0a".repeat(20); |
| 606 | let out = verify( |
| 607 | &url, |
| 608 | &[ |
| 609 | "report", |
| 610 | "-R", |
| 611 | "ada/demo", |
| 612 | "--outcome", |
| 613 | "pass", |
| 614 | "--git-commit", |
| 615 | &commit, |
| 616 | "--suite", |
| 617 | "ci", |
| 618 | "--json", |
| 619 | ], |
| 620 | ); |
| 621 | assert_eq!(out.status.code(), Some(0), "{}", text(&out.stderr)); |
| 622 | assert_eq!( |
| 623 | serde_json::from_slice::<Value>(&out.stdout).unwrap(), |
| 624 | serde_json::from_str::<Value>(answer).unwrap() |
| 625 | ); |
| 626 | let seen = server.join().unwrap(); |
| 627 | assert_eq!(seen[1], seen[2], "the same request, with the same key"); |
| 628 | assert_eq!(seen[1].line, "POST /v1/r/ada/demo/verify/report HTTP/1.1"); |
| 629 | assert_eq!(seen[1].key.as_ref().map(String::len), Some(32)); |
| 630 | assert_eq!( |
| 631 | serde_json::from_str::<Value>(&seen[1].body).unwrap(), |
| 632 | serde_json::json!({"git_commit": commit, "outcome": "pass", "suite": "ci"}) |
| 633 | ); |
| 634 | |
| 635 | // What the hub would refuse is refused before anything is sent. |
| 636 | fails_with( |
| 637 | &verify( |
| 638 | &nowhere, |
| 639 | &[ |
| 640 | "report", |
| 641 | "-R", |
| 642 | "ada/demo", |
| 643 | "--outcome", |
| 644 | "pass", |
| 645 | "--changeset", |
| 646 | "abc", |
| 647 | "--suite", |
| 648 | "ci", |
| 649 | ], |
| 650 | ), |
| 651 | "64 hex digits", |
| 652 | ); |
| 653 | } |