//! Which hub and repository a command talks to, and with which token. //! //! Inside an Oxygen checkout, `oh` uses the checkout's remote (`origin`, or //! the only one, or `--remote NAME`): its URL names the hub and the //! repository, and its token and CA are the ones `oxy` pushes with. //! Elsewhere, `--repo OWNER/NAME` with the hub from `--hub`, `OH_HUB` or //! the one `oh auth login` saved. use anyhow::{anyhow, bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; /// `~/.config/oh/config.toml`: the default hub. Tokens are oxy's: one /// sign-in (`oh auth login` or `oxy auth login`) serves both, kept in /// oxy's credential store (oxygen#47). #[derive(Debug, Default, Serialize, Deserialize)] pub struct Config { #[serde(default)] pub default_hub: Option, } /// What oxy's credential store holds for a hub. #[derive(Clone, Debug, Default)] pub struct Host { pub token: String, pub ca: Option, } fn stored(hub: &str) -> Host { let (token, ca) = oxy_core::credentials::Credentials::user().lookup(hub); Host { token: token.unwrap_or_default(), ca } } pub fn config_path() -> Result { if let Some(p) = std::env::var_os("OH_CONFIG") { return Ok(PathBuf::from(p)); } let base = match std::env::var_os("XDG_CONFIG_HOME") { Some(d) => PathBuf::from(d), // Windows has no HOME as a rule: the roaming profile's application data. #[cfg(windows)] None => PathBuf::from(std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")).context("APPDATA is not set")?), #[cfg(not(windows))] None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".config"), }; Ok(base.join("oh").join("config.toml")) } impl Config { pub fn load() -> Result { let p = config_path()?; match std::fs::read_to_string(&p) { Ok(t) => toml::from_str(&t).with_context(|| format!("parse {}", p.display())), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()), Err(e) => Err(e).with_context(|| format!("read {}", p.display())), } } /// Written owner-only: it holds tokens. (On Windows the file sits in the /// user's own profile, which only they and administrators can read.) pub fn save(&self) -> Result<()> { use std::io::Write; let p = config_path()?; std::fs::create_dir_all(p.parent().unwrap())?; let tmp = p.with_extension("toml.tmp"); let mut options = std::fs::OpenOptions::new(); options.write(true).create(true).truncate(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); let mut f = options.open(&tmp)?; f.write_all(toml::to_string_pretty(self)?.as_bytes())?; f.sync_all()?; std::fs::rename(&tmp, &p)?; Ok(()) } } /// A hub, and a repository on it when the command needs one. #[derive(Clone, Debug)] pub struct Target { /// `https://host:port`, no trailing slash. pub hub: String, pub token: Option, pub ca: Option, pub owner: String, pub name: String, } impl Target { pub fn repo(&self) -> Result<(&str, &str)> { if self.owner.is_empty() { bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME"); } Ok((&self.owner, &self.name)) } /// `/repos/{owner}/{name}`. pub fn repo_path(&self) -> Result { let (o, n) = self.repo()?; Ok(format!("/repos/{o}/{n}")) } } /// Split `https://host:port/owner/name` into the hub and the repository. pub fn split_url(url: &str) -> Result<(String, String, String)> { let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?; let mut parts = rest.trim_end_matches('/').splitn(2, '/'); let host = parts.next().unwrap_or(""); let path = parts.next().unwrap_or(""); let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); match segs.as_slice() { [o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())), // A drop's clone (oxygenhub#279): `https://hub/OWNER/drops/ID`. [o, "drops", id] => Ok((format!("{scheme}://{host}"), o.to_string(), format!("drops/{id}"))), _ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"), } } /// A token and CA for `hub` from the checkout at `dir` or one enclosing /// it (a subrepo's parent): the first remote on that hub that has each. fn checkout_credentials(dir: &Path, hub: &str) -> (Option, Option) { let (mut token, mut ca) = (None, None); let mut at = Some(dir.to_path_buf()); while let Some(d) = at { let Ok(repo) = oxy_core::repo::Repo::open(&d) else { break }; for (name, url) in &repo.config.remotes { if split_url(url).is_ok_and(|(h, _, _)| h.eq_ignore_ascii_case(hub)) { token = token.or_else(|| repo.config.remote_tokens.get(name).cloned()); ca = ca.or_else(|| repo.config.remote_cas.get(name).map(PathBuf::from)); } } if token.is_some() && ca.is_some() { break; } at = repo.root().parent().map(Path::to_path_buf); } (token, ca) } /// The hub of the checkout's remote (the one chosen, `origin`, or the only /// one), for `--repo` without `--hub`. fn checkout_hub(dir: &Path, remote: Option<&str>) -> Option { let repo = oxy_core::repo::Repo::open(dir).ok()?; let remotes = &repo.config.remotes; let url = match remote { Some(n) => remotes.get(n)?, None => remotes.get("origin").or_else(|| (remotes.len() == 1).then(|| remotes.values().next()).flatten())?, }; split_url(url).ok().map(|(hub, _, _)| hub) } pub struct Choice<'a> { pub repo: Option<&'a str>, pub hub: Option<&'a str>, pub remote: Option<&'a str>, } /// Resolve what to talk to from the flags, the checkout at `dir`, the /// environment and the saved configuration. pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result { let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty()); let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from); let saved = |hub: &str| Some(stored(hub)); if let Some(r) = choice.repo { let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?; // Inside a checkout, its remote's hub, token and CA serve for // another repository on the same hub. let hub = choice .hub .map(String::from) .or_else(|| std::env::var("OH_HUB").ok()) .or_else(|| checkout_hub(dir, choice.remote)) .or_else(|| cfg.default_hub.clone()) .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?; let hub = hub.trim_end_matches('/').to_string(); let host = saved(&hub).unwrap_or_default(); let (co_token, co_ca) = checkout_credentials(dir, &hub); return Ok(Target { token: env_token.or(co_token).or(Some(host.token).filter(|t| !t.is_empty())), ca: env_ca.or(co_ca).or(host.ca), hub, owner: owner.into(), name: name.into(), }); } // The checkout's remote. if let Ok(repo) = oxy_core::repo::Repo::open(dir) { let remotes = &repo.config.remotes; let name = match choice.remote { Some(n) => n.to_string(), None if remotes.contains_key("origin") => "origin".into(), None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(), None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"), None => bail!( "this checkout has several remotes ({}); choose one with --remote", remotes.keys().cloned().collect::>().join(", ") ), }; let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?; let (hub, owner, repo_name) = split_url(url)?; let host = saved(&hub).unwrap_or_default(); // The remote's own, then a parent checkout's for the same hub (a // subrepo cloned before it recorded them), then the saved ones. let (up_token, up_ca) = repo.root().parent().map(|p| checkout_credentials(p, &hub)).unwrap_or_default(); let token = env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(up_token).or(Some(host.token).filter(|t| !t.is_empty())); let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(up_ca).or(host.ca); return Ok(Target { hub, token, ca, owner, name: repo_name }); } // No repository: commands that need only a hub. let hub = choice .hub .map(String::from) .or_else(|| std::env::var("OH_HUB").ok()) .or_else(|| cfg.default_hub.clone()) .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?; let hub = hub.trim_end_matches('/').to_string(); let host = saved(&hub).unwrap_or_default(); Ok(Target { token: env_token.or(Some(host.token).filter(|t| !t.is_empty())), ca: env_ca.or(host.ca), hub, owner: String::new(), name: String::new(), }) } #[cfg(test)] mod tests { use super::*; #[test] fn remote_urls_name_the_hub_and_the_repository() { assert_eq!( split_url("https://earth.example:7343/andy/oxygen").unwrap(), ("https://earth.example:7343".into(), "andy".into(), "oxygen".into()) ); assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b"); // A drop's clone names its hub, so `oh drop` works inside it. assert_eq!( split_url("https://hub/andy/drops/0123456789abcdef01234567").unwrap(), ("https://hub".into(), "andy".into(), "drops/0123456789abcdef01234567".into()) ); assert!(split_url("https://hub/a/b/c").is_err()); assert!(split_url("https://hub/only-owner").is_err()); assert!(split_url("not a url").is_err()); } /// oxygenhub#50, #51: a subrepo checkout whose remote has no token /// borrows its parent's for the same hub, and --repo inside a checkout /// takes the checkout's hub and token. #[test] fn checkouts_lend_their_hub_and_token() { if std::env::var_os("OH_TOKEN").is_some() || std::env::var_os("OXY_TOKEN").is_some() || std::env::var_os("OH_HUB").is_some() { return; } let dir = tempfile::tempdir().unwrap(); let parent = dir.path().join("metalgear"); let mut p = oxy_core::repo::Repo::init(&parent).unwrap(); p.config.set("remote.origin.url", "https://hub.example/doomsdayone/metalgear").unwrap(); p.config.set("remote.origin.token", "parent-token").unwrap(); p.save_config().unwrap(); let sub = parent.join("rstar-api"); let mut s = oxy_core::repo::Repo::init(&sub).unwrap(); s.config.set("remote.origin.url", "https://hub.example/doomsdayone/rstar-api").unwrap(); s.save_config().unwrap(); let cfg = Config::default(); let none = Choice { repo: None, hub: None, remote: None }; let t = resolve(&none, &sub, &cfg).unwrap(); assert_eq!((t.name.as_str(), t.token.as_deref()), ("rstar-api", Some("parent-token"))); let other = Choice { repo: Some("doomsdayone/other"), hub: None, remote: None }; let t = resolve(&other, &parent, &cfg).unwrap(); assert_eq!((t.hub.as_str(), t.token.as_deref()), ("https://hub.example", Some("parent-token"))); } }