Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 27.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Credentials for hubs.
5//!
6//! `braid login` saves a token in `hub.json`, in braid's configuration
7//! directory: `$XDG_CONFIG_HOME/braid`, or `$HOME/.config/braid` when
8//! `XDG_CONFIG_HOME` is unset or not absolute. The directory has mode 0700
9//! and the file 0600, and the file holds:
10//!
11//! ```json
12//! {"default": "<url>", "hubs": {"<url>": {"token": "brd_…", "login": "…", "expires": "…"}},
13//! "autopublish": true}
14//! ```
15//!
16//! `default` is the hub signed in to last, and `autopublish` the answer of
17//! `braid hub autopublish on|off`, for every hub (absent until answered).
18//! The environment takes precedence over the file: `BRAID_HUB_URL` names
19//! the hub, and `BRAID_TOKEN` is the token for it; when `BRAID_HUB_URL` is
20//! unset, for the hub used by default (the one signed in to last, or the
21//! public hub), and for no other: a `.braid/hub` that came with a checkout
22//! or an archive never gets it.
23//!
24//! A hub's URL is `https://`, or `http://` to this machine only, so that a
25//! token never crosses a network in clear. The token itself only ever goes
26//! in an `Authorization` header: never in a URL, an argument, a log or an
27//! error message. A file that other users can open is used, with a warning.
28
29use std::collections::BTreeMap;
30use std::fmt;
31use std::fs::{self, File, OpenOptions};
32use std::io::{self, Write};
33use std::net::IpAddr;
34use std::path::{Path, PathBuf};
35
36use anyhow::{Context, Result, anyhow, bail};
37use braid_hubproto::{DEFAULT_HUB_URL, Token, limits};
38use serde::{Deserialize, Serialize};
39
40/// The file, in braid's configuration directory.
41pub(crate) const FILE: &str = "hub.json";
42
43/// The smallest request body `BRAID_HUB_MAX_BODY` may ask for.
44pub(crate) const MIN_BODY: u64 = 1024;
45
46/// What the environment says about hubs, read once, so that the rules below
47/// can be tested without touching the process's environment.
48#[derive(Clone, Default)]
49pub(crate) struct HubEnv {
50 /// `BRAID_TOKEN`.
51 pub(crate) token: Option<String>,
52 /// `BRAID_HUB_URL`.
53 pub(crate) url: Option<String>,
54 /// `BRAID_HUB`: `off` keeps landing and updating local.
55 pub(crate) mode: Option<String>,
56 /// `BRAID_HUB_MAX_BODY`: the largest upload request, in bytes.
57 pub(crate) max_body: Option<String>,
58 /// `XDG_CONFIG_HOME`.
59 pub(crate) config_home: Option<PathBuf>,
60 /// `HOME`.
61 pub(crate) home: Option<PathBuf>,
62}
63
64impl HubEnv {
65 /// The process's environment. An empty variable counts as unset.
66 pub(crate) fn from_process() -> HubEnv {
67 let text = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty());
68 let path = |name: &str| {
69 std::env::var_os(name)
70 .filter(|value| !value.is_empty())
71 .map(PathBuf::from)
72 };
73 HubEnv {
74 token: text("BRAID_TOKEN"),
75 url: text("BRAID_HUB_URL"),
76 mode: text("BRAID_HUB"),
77 max_body: text("BRAID_HUB_MAX_BODY"),
78 config_home: path("XDG_CONFIG_HOME"),
79 home: path("HOME").or_else(|| path("USERPROFILE")),
80 }
81 }
82
83 /// The largest body an upload request may have: the protocol's 256 MiB,
84 /// or less when `BRAID_HUB_MAX_BODY` says so, for a hub behind a proxy
85 /// that takes less.
86 pub(crate) fn max_body(&self) -> Result<u64> {
87 let Some(text) = &self.max_body else {
88 return Ok(limits::MAX_BODY);
89 };
90 match text.trim().parse::<u64>() {
91 Ok(bytes) if (MIN_BODY..=limits::MAX_BODY).contains(&bytes) => Ok(bytes),
92 _ => bail!(
93 "BRAID_HUB_MAX_BODY takes a number of bytes from {MIN_BODY} to {}, not {text:?}",
94 limits::MAX_BODY
95 ),
96 }
97 }
98
99 /// Where the credentials file is.
100 pub(crate) fn credentials_path(&self) -> Result<PathBuf> {
101 let base = match (&self.config_home, &self.home) {
102 (Some(dir), _) if dir.is_absolute() => dir.clone(),
103 (_, Some(home)) => home.join(".config"),
104 _ => bail!(
105 "cannot find braid's configuration directory for hub credentials: set HOME or XDG_CONFIG_HOME"
106 ),
107 };
108 Ok(base.join("braid").join(FILE))
109 }
110
111 /// The saved credentials, or none when there is no file or nowhere to
112 /// look for one.
113 pub(crate) fn credentials(&self) -> Result<Credentials> {
114 match self.credentials_path() {
115 Ok(path) => Credentials::load(&path),
116 Err(_) => Ok(Credentials::default()),
117 }
118 }
119
120 /// Whether `BRAID_HUB` turns the hub off: `off` keeps `land`, `update`
121 /// and `change create --land` local in a linked repository; `on`, or
122 /// nothing, lets the link decide.
123 pub(crate) fn hub_off(&self) -> Result<bool> {
124 match self.mode.as_deref().map(str::to_ascii_lowercase).as_deref() {
125 None | Some("on") => Ok(false),
126 Some("off") => Ok(true),
127 Some(other) => bail!("BRAID_HUB takes `off` or `on`, not {other:?}"),
128 }
129 }
130}
131
132/// The credentials file.
133#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
134pub(crate) struct Credentials {
135 /// The hub signed in to last.
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub(crate) default: Option<String>,
138 /// A token for each hub, by URL.
139 #[serde(default)]
140 pub(crate) hubs: BTreeMap<String, Saved>,
141 /// Whether coding agents publish the new projects they start to the
142 /// hub: `braid hub autopublish`. `None` until answered.
143 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub(crate) autopublish: Option<bool>,
145}
146
147/// A token saved for one hub.
148#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
149pub(crate) struct Saved {
150 /// The token: `brd_<id>_<secret>`.
151 pub(crate) token: String,
152 /// The account's GitHub login.
153 #[serde(default)]
154 pub(crate) login: String,
155 /// When the token expires, as the hub said it.
156 #[serde(default)]
157 pub(crate) expires: String,
158}
159
160impl fmt::Debug for Saved {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 // The secret never reaches a debug print.
163 let shown = Token::parse(&self.token)
164 .map_or_else(|_| "(not a token)".to_owned(), |t| format!("{t:?}"));
165 f.debug_struct("Saved")
166 .field("token", &shown)
167 .field("login", &self.login)
168 .field("expires", &self.expires)
169 .finish()
170 }
171}
172
173impl Credentials {
174 /// Reads the file at `path`; no file holds no credentials. A damaged
175 /// file is an error that says where it is damaged, but never quotes
176 /// what it found there, which may be a token.
177 pub(crate) fn load(path: &Path) -> Result<Credentials> {
178 match fs::read(path) {
179 Ok(bytes) => {
180 warn_if_open(path);
181 Credentials::decode(path, &bytes)
182 }
183 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Credentials::default()),
184 Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())),
185 }
186 }
187
188 /// The credentials in `bytes`, read from `path`.
189 fn decode(path: &Path, bytes: &[u8]) -> Result<Credentials> {
190 let creds: Credentials = serde_json::from_slice(bytes).map_err(|err| {
191 let what = match err.classify() {
192 serde_json::error::Category::Eof => "it is cut short",
193 serde_json::error::Category::Syntax => "it is not JSON",
194 serde_json::error::Category::Data => "a value has the wrong type",
195 serde_json::error::Category::Io => "it cannot be read",
196 };
197 anyhow!(
198 "{} is not a valid credentials file ({what}, at line {} column {}): fix it, or remove it and sign in again",
199 path.display(),
200 err.line(),
201 err.column()
202 )
203 })?;
204 if let Some(default) = &creds.default
205 && normalize_url(default).is_err()
206 {
207 bail!(
208 "{} is not a valid credentials file (its default hub is not a hub URL): fix it, or remove it and sign in again",
209 path.display()
210 );
211 }
212 Ok(creds)
213 }
214
215 /// Writes the file at `path`, mode 0600, through a scratch file and a
216 /// rename, in a directory of mode 0700.
217 pub(crate) fn save(&self, path: &Path) -> Result<()> {
218 let dir = path
219 .parent()
220 .with_context(|| format!("{} has no directory", path.display()))?;
221 private_dir(dir).with_context(|| format!("cannot create {}", dir.display()))?;
222 let mut text = serde_json::to_vec_pretty(self)?;
223 text.push(b'\n');
224 let scratch = dir.join(format!(".{FILE}.{}.tmp", std::process::id()));
225 let _ = fs::remove_file(&scratch);
226 let written = private_file(&scratch).and_then(|mut file| {
227 file.write_all(&text)?;
228 file.sync_all()
229 });
230 if let Err(err) = written.and_then(|()| fs::rename(&scratch, path)) {
231 let _ = fs::remove_file(&scratch);
232 return Err(err).with_context(|| format!("cannot write {}", path.display()));
233 }
234 Ok(())
235 }
236}
237
238/// Warns, on standard error, when the credentials file is open to other
239/// users, or its directory can be written by them: the token in it is
240/// theirs to read, or to replace. The command goes on; saving the file
241/// closes both again.
242#[cfg(unix)]
243fn warn_if_open(path: &Path) {
244 use std::os::unix::fs::PermissionsExt;
245 let mode = |path: &Path| {
246 fs::metadata(path)
247 .ok()
248 .map(|meta| meta.permissions().mode() & 0o777)
249 };
250 if let Some(mode) = mode(path)
251 && mode & 0o077 != 0
252 {
253 eprintln!(
254 "braid: warning: {} is open to other users (mode {mode:03o}), and it holds tokens: run `chmod 600 {}`",
255 path.display(),
256 path.display()
257 );
258 }
259 if let Some(dir) = path.parent()
260 && let Some(mode) = mode(dir)
261 && mode & 0o022 != 0
262 {
263 eprintln!(
264 "braid: warning: other users can write in {} (mode {mode:03o}), which holds the hub tokens: run `chmod 700 {}`",
265 dir.display(),
266 dir.display()
267 );
268 }
269}
270
271#[cfg(not(unix))]
272fn warn_if_open(_path: &Path) {}
273
274/// Creates `dir` with mode 0700, and gives it that mode if it exists: it
275/// holds tokens.
276#[cfg(unix)]
277fn private_dir(dir: &Path) -> io::Result<()> {
278 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
279 if let Some(parent) = dir.parent() {
280 fs::create_dir_all(parent)?;
281 }
282 match fs::DirBuilder::new().mode(0o700).create(dir) {
283 Ok(()) => Ok(()),
284 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
285 fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
286 }
287 Err(err) => Err(err),
288 }
289}
290
291#[cfg(not(unix))]
292fn private_dir(dir: &Path) -> io::Result<()> {
293 fs::create_dir_all(dir)
294}
295
296/// Creates a new file that only its owner can read and write.
297#[cfg(unix)]
298fn private_file(path: &Path) -> io::Result<File> {
299 use std::os::unix::fs::OpenOptionsExt;
300 OpenOptions::new()
301 .write(true)
302 .create_new(true)
303 .mode(0o600)
304 .open(path)
305}
306
307#[cfg(not(unix))]
308fn private_file(path: &Path) -> io::Result<File> {
309 OpenOptions::new().write(true).create_new(true).open(path)
310}
311
312/// Where a command's token came from.
313#[derive(Clone, Copy, Debug, PartialEq, Eq)]
314pub(crate) enum TokenSource {
315 /// `BRAID_TOKEN`.
316 Environment,
317 /// The credentials file.
318 File,
319 /// Nowhere: the command goes without one.
320 None,
321}
322
323impl TokenSource {
324 /// How JSON output names it.
325 pub(crate) fn code(self) -> Option<&'static str> {
326 match self {
327 TokenSource::Environment => Some("environment"),
328 TokenSource::File => Some("file"),
329 TokenSource::None => None,
330 }
331 }
332}
333
334/// The hub a command talks to when no linked repository names one: `given`
335/// (`--hub`), then `BRAID_HUB_URL`, then the hub signed in to last, then the
336/// public hub.
337pub(crate) fn hub_url(env: &HubEnv, creds: &Credentials, given: Option<&str>) -> Result<String> {
338 let url = given
339 .map(str::to_owned)
340 .or_else(|| env.url.clone())
341 .or_else(|| creds.default.clone())
342 .unwrap_or_else(|| DEFAULT_HUB_URL.to_owned());
343 normalize_url(&url)
344}
345
346/// The token for the hub at `url` (normalized): `BRAID_TOKEN` for the hub
347/// it is meant for, the one [`hub_url`] gives without `--hub`; else the one
348/// saved for `url`; else none. A linked repository's `.braid/hub` may come
349/// from anywhere, so BRAID_TOKEN never goes to a hub only it names.
350pub(crate) fn token_for(
351 env: &HubEnv,
352 creds: &Credentials,
353 url: &str,
354) -> Result<(Option<Token>, TokenSource)> {
355 if let Some(text) = &env.token
356 && hub_url(env, creds, None)? == url
357 {
358 // The message never repeats the variable's value.
359 let token = Token::parse(text.trim()).map_err(|_| {
360 anyhow!(
361 "BRAID_TOKEN is not a braid hub token: expected brd_ then an 8-character id, _ and a 52-character secret"
362 )
363 })?;
364 return Ok((Some(token), TokenSource::Environment));
365 }
366 match creds.hubs.get(url) {
367 Some(saved) => {
368 let token = Token::parse(&saved.token).map_err(|_| {
369 anyhow!(
370 "the token saved for {url} is not a braid hub token: sign in again with `braid login --hub {url}`"
371 )
372 })?;
373 Ok((Some(token), TokenSource::File))
374 }
375 None => Ok((None, TokenSource::None)),
376 }
377}
378
379/// The hub `BRAID_TOKEN` is meant for, when it is set and that is not
380/// `url`: what a command that sends no token to `url` says.
381pub(crate) fn withheld_for(env: &HubEnv, creds: &Credentials, url: &str) -> Option<String> {
382 env.token.as_ref()?;
383 hub_url(env, creds, None).ok().filter(|meant| meant != url)
384}
385
386/// A hub's URL in the one form braid keeps it in: the scheme and the host
387/// lowercase, without a trailing `/`. Only `https://` is taken, and
388/// `http://` to this machine, which tests use; a URL with a
389/// user name or password, a query or a fragment is refused.
390pub(crate) fn normalize_url(text: &str) -> Result<String> {
391 let text = text.trim();
392 let invalid = |why: &str| {
393 if redact(text) == text {
394 anyhow!("{text:?} is not a hub URL: {why}")
395 } else {
396 // Never repeated: a token put where the URL goes, as when the
397 // two variables are swapped.
398 anyhow!(
399 "that is not a hub URL: it holds a braid hub token, which goes in BRAID_TOKEN and never in a URL"
400 )
401 }
402 };
403 let (scheme, rest) = text
404 .split_once("://")
405 .ok_or_else(|| invalid("expected https:// and a host"))?;
406 if text.contains(['?', '#']) || text.chars().any(|c| c.is_whitespace() || c.is_control()) {
407 return Err(invalid("it holds a query, a fragment or a space"));
408 }
409 let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
410 if authority.is_empty() {
411 return Err(invalid("it has no host"));
412 }
413 if authority.contains('@') {
414 return Err(invalid(
415 "it holds a user name or password: braid sends the token in a header",
416 ));
417 }
418 let scheme = scheme.to_ascii_lowercase();
419 let authority = authority.to_ascii_lowercase();
420 match scheme.as_str() {
421 "https" => {}
422 "http" if is_loopback(&authority) => {}
423 "http" => {
424 return Err(invalid(
425 "http:// would send the token in clear: use https:// (http:// is taken only for an address on this machine)",
426 ));
427 }
428 _ => return Err(invalid("expected https://")),
429 }
430 Ok(format!(
431 "{scheme}://{authority}{}",
432 path.trim_end_matches('/')
433 ))
434}
435
436/// `text` with the secret of every braid token in it, whole or cut short,
437/// left out: `brd_<id>_...`. For what a hub, or a proxy in front of it,
438/// says, which may echo the token a request carried.
439pub(crate) fn redact(text: &str) -> std::borrow::Cow<'_, str> {
440 const PREFIX: &str = "brd_";
441 if !text.contains(PREFIX) {
442 return std::borrow::Cow::Borrowed(text);
443 }
444 let base32 = |byte: u8| byte.is_ascii_lowercase() || (b'2'..=b'7').contains(&byte);
445 let bytes = text.as_bytes();
446 let mut out = String::with_capacity(text.len());
447 let mut copied = 0;
448 let mut at = 0;
449 while let Some(found) = text[at..].find(PREFIX) {
450 let id = at + found + PREFIX.len();
451 let underscore = id + 8;
452 if underscore < bytes.len()
453 && bytes[id..underscore].iter().all(|&byte| base32(byte))
454 && bytes[underscore] == b'_'
455 {
456 let secret = underscore + 1;
457 let mut end = secret;
458 while end < bytes.len() && base32(bytes[end]) {
459 end += 1;
460 }
461 if end > secret {
462 out.push_str(&text[copied..secret]);
463 out.push_str("...");
464 copied = end;
465 }
466 at = end;
467 } else {
468 at = id;
469 }
470 }
471 out.push_str(&text[copied..]);
472 std::borrow::Cow::Owned(out)
473}
474
475/// The `host[:port]` of a normalized URL.
476pub(crate) fn authority(url: &str) -> &str {
477 let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
478 &rest[..rest.find('/').unwrap_or(rest.len())]
479}
480
481/// Whether `authority` (`host[:port]`) names this machine: `localhost`, or
482/// a loopback address.
483pub(crate) fn is_loopback(authority: &str) -> bool {
484 let host = match authority.strip_prefix('[') {
485 Some(rest) => rest.split(']').next().unwrap_or(""),
486 None => authority
487 .rsplit_once(':')
488 .map_or(authority, |(host, _)| host),
489 };
490 host == "localhost" || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 fn token(n: u8) -> Token {
498 Token::from_random([n; 5], [n; 32])
499 }
500
501 fn env_in(dir: &Path) -> HubEnv {
502 HubEnv {
503 home: Some(dir.to_path_buf()),
504 ..HubEnv::default()
505 }
506 }
507
508 #[test]
509 fn urls() {
510 let good = [
511 (
512 "https://braidhub.elffuss.com",
513 "https://braidhub.elffuss.com",
514 ),
515 (
516 "https://BraidHub.Example.ORG/",
517 "https://braidhub.example.org",
518 ),
519 (
520 "HTTPS://hub.example.org/base/",
521 "https://hub.example.org/base",
522 ),
523 ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
524 ("http://localhost:3000/", "http://localhost:3000"),
525 ("http://[::1]:9000", "http://[::1]:9000"),
526 ];
527 for (given, normal) in good {
528 assert_eq!(normalize_url(given).unwrap(), normal, "{given}");
529 }
530 for bad in [
531 "braidhub.elffuss.com",
532 "http://hub.example.org",
533 "http://10.0.0.1:8080",
534 "ftp://hub.example.org",
535 "https://user:secret@hub.example.org",
536 "https://hub.example.org/?token=x",
537 "https://hub.example.org/#x",
538 "https://",
539 "https://hub example.org",
540 ] {
541 let err = normalize_url(bad).unwrap_err().to_string();
542 assert!(err.contains("is not a hub URL"), "{bad}: {err}");
543 }
544 assert_eq!(authority("https://hub.example.org/base"), "hub.example.org");
545 assert!(is_loopback("127.0.0.1:1") && is_loopback("[::1]:1"));
546 assert!(!is_loopback("hub.example.org:443") && !is_loopback("192.168.1.2"));
547 }
548
549 #[test]
550 fn where_the_file_is() {
551 let base = std::env::temp_dir();
552 let xdg = base.join("xdg");
553 let home = base.join("home");
554 let env = HubEnv {
555 config_home: Some(xdg.clone()),
556 home: Some(home.clone()),
557 ..HubEnv::default()
558 };
559 assert_eq!(env.credentials_path().unwrap(), xdg.join("braid/hub.json"));
560 // A relative XDG_CONFIG_HOME is ignored, as the specification says.
561 let env = HubEnv {
562 config_home: Some(PathBuf::from("relative")),
563 home: Some(home.clone()),
564 ..HubEnv::default()
565 };
566 assert_eq!(
567 env.credentials_path().unwrap(),
568 home.join(".config/braid/hub.json")
569 );
570 assert!(HubEnv::default().credentials_path().is_err());
571 assert_eq!(
572 HubEnv::default().credentials().unwrap(),
573 Credentials::default()
574 );
575 }
576
577 #[test]
578 fn saved_privately_and_read_back() {
579 let dir = tempfile::tempdir().unwrap();
580 let env = env_in(dir.path());
581 let path = env.credentials_path().unwrap();
582 assert_eq!(Credentials::load(&path).unwrap(), Credentials::default());
583 let mut creds = Credentials {
584 default: Some("https://hub.example.org".to_owned()),
585 ..Credentials::default()
586 };
587 creds.hubs.insert(
588 "https://hub.example.org".to_owned(),
589 Saved {
590 token: token(1).expose(),
591 login: "ada".to_owned(),
592 expires: "2027-01-01T00:00:00Z".to_owned(),
593 },
594 );
595 creds.save(&path).unwrap();
596 assert_eq!(Credentials::load(&path).unwrap(), creds);
597 // Saving again replaces the file.
598 creds.hubs.clear();
599 creds.save(&path).unwrap();
600 assert_eq!(Credentials::load(&path).unwrap(), creds);
601 #[cfg(unix)]
602 {
603 use std::os::unix::fs::PermissionsExt;
604 let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
605 assert_eq!(mode(&path), 0o600);
606 assert_eq!(mode(path.parent().unwrap()), 0o700);
607 // A directory made by someone else is closed too.
608 fs::set_permissions(path.parent().unwrap(), fs::Permissions::from_mode(0o755)).unwrap();
609 creds.save(&path).unwrap();
610 assert_eq!(mode(path.parent().unwrap()), 0o700);
611 }
612 // No scratch file is left behind.
613 let names: Vec<_> = fs::read_dir(path.parent().unwrap())
614 .unwrap()
615 .map(|entry| entry.unwrap().file_name())
616 .collect();
617 assert_eq!(names, [FILE]);
618 // A damaged file is an error that names it.
619 fs::write(&path, b"{not json").unwrap();
620 let err = format!("{:#}", Credentials::load(&path).unwrap_err());
621 assert!(err.contains("not a valid credentials file"), "{err}");
622 }
623
624 #[test]
625 fn the_environment_comes_first() {
626 let saved_url = "https://hub.example.org";
627 let mut creds = Credentials {
628 default: Some(saved_url.to_owned()),
629 ..Credentials::default()
630 };
631 creds.hubs.insert(
632 saved_url.to_owned(),
633 Saved {
634 token: token(1).expose(),
635 login: "ada".to_owned(),
636 expires: String::new(),
637 },
638 );
639 // The hub: --hub, then BRAID_HUB_URL, then the default, then the
640 // public hub.
641 let none = HubEnv::default();
642 assert_eq!(hub_url(&none, &creds, None).unwrap(), saved_url);
643 assert_eq!(
644 hub_url(&none, &Credentials::default(), None).unwrap(),
645 DEFAULT_HUB_URL
646 );
647 let env = HubEnv {
648 url: Some("https://other.example.org/".to_owned()),
649 ..HubEnv::default()
650 };
651 assert_eq!(
652 hub_url(&env, &creds, None).unwrap(),
653 "https://other.example.org"
654 );
655 assert_eq!(
656 hub_url(&env, &creds, Some("http://localhost:1")).unwrap(),
657 "http://localhost:1"
658 );
659
660 // The token: the saved one, unless BRAID_TOKEN is set.
661 assert_eq!(
662 token_for(&none, &creds, saved_url).unwrap(),
663 (Some(token(1)), TokenSource::File)
664 );
665 assert_eq!(
666 token_for(&none, &creds, "https://unknown.example.org").unwrap(),
667 (None, TokenSource::None)
668 );
669 let env = HubEnv {
670 token: Some(token(2).expose()),
671 ..HubEnv::default()
672 };
673 assert_eq!(
674 token_for(&env, &creds, saved_url).unwrap(),
675 (Some(token(2)), TokenSource::Environment)
676 );
677 // BRAID_TOKEN belongs to the hub BRAID_HUB_URL names, and to no
678 // other.
679 let env = HubEnv {
680 token: Some(token(2).expose()),
681 url: Some("https://other.example.org".to_owned()),
682 ..HubEnv::default()
683 };
684 assert_eq!(
685 token_for(&env, &creds, "https://other.example.org").unwrap(),
686 (Some(token(2)), TokenSource::Environment)
687 );
688 assert_eq!(
689 token_for(&env, &creds, saved_url).unwrap(),
690 (Some(token(1)), TokenSource::File)
691 );
692 // A malformed BRAID_TOKEN is refused without being repeated.
693 let secret = "brd_notavalidtokenatall_with-a-secret-inside";
694 let env = HubEnv {
695 token: Some(secret.to_owned()),
696 ..HubEnv::default()
697 };
698 let err = token_for(&env, &creds, saved_url).unwrap_err().to_string();
699 assert!(
700 err.contains("BRAID_TOKEN") && !err.contains("secret-inside"),
701 "{err}"
702 );
703 }
704
705 #[test]
706 fn the_autopublish_answer_lives_next_to_the_tokens() {
707 let dir = tempfile::tempdir().unwrap();
708 let path = env_in(dir.path()).credentials_path().unwrap();
709 let mut creds = Credentials::default();
710 creds.hubs.insert(
711 "https://hub.example.org".to_owned(),
712 Saved {
713 token: token(1).expose(),
714 login: "ada".to_owned(),
715 expires: String::new(),
716 },
717 );
718 creds.autopublish = Some(false);
719 creds.save(&path).unwrap();
720 let text = fs::read_to_string(&path).unwrap();
721 assert!(text.contains("\"autopublish\": false"), "{text}");
722 assert_eq!(Credentials::load(&path).unwrap(), creds);
723 // A file from before the question reads as unanswered, and an
724 // unanswered question writes nothing.
725 fs::write(&path, br#"{"hubs": {}}"#).unwrap();
726 let creds = Credentials::load(&path).unwrap();
727 assert_eq!(creds.autopublish, None);
728 creds.save(&path).unwrap();
729 assert!(!fs::read_to_string(&path).unwrap().contains("autopublish"));
730 }
731
732 #[test]
733 fn the_largest_upload() {
734 let env = |value: Option<&str>| HubEnv {
735 max_body: value.map(str::to_owned),
736 ..HubEnv::default()
737 };
738 assert_eq!(env(None).max_body().unwrap(), limits::MAX_BODY);
739 assert_eq!(env(Some("65536")).max_body().unwrap(), 65536);
740 assert_eq!(env(Some(" 1024 ")).max_body().unwrap(), MIN_BODY);
741 for bad in ["0", "1023", "268435457", "64k", "-1"] {
742 let err = env(Some(bad)).max_body().unwrap_err().to_string();
743 assert!(err.contains("BRAID_HUB_MAX_BODY takes"), "{bad}: {err}");
744 }
745 }
746
747 #[test]
748 fn braid_hub_off() {
749 let mode = |value: Option<&str>| HubEnv {
750 mode: value.map(str::to_owned),
751 ..HubEnv::default()
752 };
753 assert!(!mode(None).hub_off().unwrap());
754 assert!(!mode(Some("on")).hub_off().unwrap());
755 assert!(mode(Some("off")).hub_off().unwrap());
756 assert!(mode(Some("OFF")).hub_off().unwrap());
757 assert!(mode(Some("nope")).hub_off().is_err());
758 }
759
760 #[test]
761 fn debug_never_shows_a_secret() {
762 let secret = token(3).expose();
763 let saved = Saved {
764 token: secret.clone(),
765 login: "ada".to_owned(),
766 expires: String::new(),
767 };
768 let shown = format!("{saved:?}");
769 assert!(!shown.contains(&secret[13..]), "{shown}");
770 let mut creds = Credentials::default();
771 creds
772 .hubs
773 .insert("https://hub.example.org".to_owned(), saved);
774 assert!(!format!("{creds:?}").contains(&secret[13..]));
775 }
776}