| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
|
| 24 | | use crate::protocol::RemoteOptions; |
| 25 | | use std::collections::{BTreeMap, HashMap}; |
| 26 | | use std::io::Write; |
| 27 | | use std::path::{Path, PathBuf}; |
| 28 | | use std::process::{Command, Stdio}; |
| 29 | | use std::sync::{Mutex, OnceLock}; |
| 30 | |
|
| 31 | |
|
| 32 | |
|
| 33 | | const HELPER_USER: &str = "oxy-token"; |
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | 2798× | pub fn hub_of(url: &str) -> Option<String> { |
| 38 | 2798× | let (scheme, rest) = url.split_once("://")?; |
| 39 | 502× | let scheme = scheme.to_ascii_lowercase(); |
| 40 | 502× | if scheme != "http" && scheme != "https" { |
| 41 | 114× | return None; |
| 42 | 388× | } |
| 43 | 388× | let host = rest.split(['/', '?', '#']).next()?; |
| 44 | | |
| 45 | 388× | let host = host.rsplit('@').next()?; |
| 46 | 388× | if host.is_empty() { |
| 47 | 0× | return None; |
| 48 | 388× | } |
| 49 | 388× | Some(format!("{scheme}://{}", host.to_ascii_lowercase())) |
| 50 | 2798× | } |
| 51 | |
|
| 52 | |
|
| 53 | |
|
| 54 | 15× | pub fn token_allowed(url: &str) -> bool { |
| 55 | 15× | let Some(hub) = hub_of(url) else { |
| 56 | 0× | return true; |
| 57 | | }; |
| 58 | 15× | match hub.split_once("://") { |
| 59 | 15× | Some(("https", _)) => true, |
| 60 | 14× | Some((_, host)) => { |
| 61 | 14× | let name = match host.strip_prefix('[') { |
| 62 | 1× | Some(v6) => v6.split(']').next().unwrap_or(""), |
| 63 | 13× | None => host.rsplit_once(':').map_or(host, |(h, _)| h), |
| 64 | | }; |
| 65 | 14× | name == "localhost" |
| 66 | 13× | || name == "::1" |
| 67 | 12× | || name |
| 68 | 12× | .parse::<std::net::Ipv4Addr>() |
| 69 | 12× | .is_ok_and(|a| a.is_loopback()) |
| 70 | | } |
| 71 | 0× | None => false, |
| 72 | | } |
| 73 | 15× | } |
| 74 | |
|
| 75 | |
|
| 76 | | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 77 | | pub struct HubEntry { |
| 78 | | |
| 79 | | pub hub: String, |
| 80 | | |
| 81 | | pub account: Option<String>, |
| 82 | | |
| 83 | | pub token: Option<String>, |
| 84 | | |
| 85 | | pub ca: Option<PathBuf>, |
| 86 | | |
| 87 | | |
| 88 | | pub grant: Option<String>, |
| 89 | | } |
| 90 | |
|
| 91 | |
|
| 92 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 93 | | pub enum Stored { |
| 94 | | |
| 95 | | File(PathBuf), |
| 96 | | |
| 97 | | Helper(String), |
| 98 | | } |
| 99 | |
|
| 100 | |
|
| 101 | | #[derive(Clone, Debug)] |
| 102 | | pub struct Credentials { |
| 103 | | home: PathBuf, |
| 104 | | } |
| 105 | |
|
| 106 | | impl Credentials { |
| 107 | | |
| 108 | 1325× | pub fn at(home: impl Into<PathBuf>) -> Credentials { |
| 109 | 1325× | Credentials { home: home.into() } |
| 110 | 1325× | } |
| 111 | |
|
| 112 | | |
| 113 | 252× | pub fn user() -> Credentials { |
| 114 | 252× | Credentials::at(crate::repo::default_home()) |
| 115 | 252× | } |
| 116 | |
|
| 117 | | |
| 118 | 117× | pub fn path(&self) -> PathBuf { |
| 119 | 117× | self.home.join("credentials.toml") |
| 120 | 117× | } |
| 121 | |
|
| 122 | | |
| 123 | 54× | pub fn helper(&self) -> Option<String> { |
| 124 | 54× | crate::repo::read_config_file(&self.home.join("config.toml")) |
| 125 | 54× | .ok()? |
| 126 | 54× | .remove("auth.helper") |
| 127 | 54× | .filter(|h| !h.trim().is_empty()) |
| 128 | 54× | } |
| 129 | |
|
| 130 | | |
| 131 | 1× | pub fn entries(&self) -> Result<Vec<HubEntry>, String> { |
| 132 | 1× | Ok(self.read()?.into_values().collect()) |
| 133 | 1× | } |
| 134 | |
|
| 135 | | |
| 136 | | |
| 137 | 37× | pub fn too_open(&self) -> bool { |
| 138 | | #[cfg(unix)] |
| 139 | | { |
| 140 | | use std::os::unix::fs::PermissionsExt; |
| 141 | 37× | if let Ok(m) = std::fs::metadata(self.path()) { |
| 142 | 12× | return m.permissions().mode() & 0o077 != 0; |
| 143 | 25× | } |
| 144 | | } |
| 145 | 25× | false |
| 146 | 37× | } |
| 147 | |
|
| 148 | | |
| 149 | 41× | pub fn get(&self, hub: &str) -> Result<Option<HubEntry>, String> { |
| 150 | 41× | let entry = self.read()?.remove(hub); |
| 151 | 41× | let helper = self.helper(); |
| 152 | 41× | let mut entry = match (entry, &helper) { |
| 153 | 11× | (Some(e), _) => e, |
| 154 | | |
| 155 | 0× | (None, Some(_)) => HubEntry { |
| 156 | 0× | hub: hub.to_string(), |
| 157 | 0× | ..HubEntry::default() |
| 158 | 0× | }, |
| 159 | 30× | (None, None) => return Ok(None), |
| 160 | | }; |
| 161 | 11× | if entry.token.is_none() { |
| 162 | 4× | if let Some(h) = &helper { |
| 163 | 2× | entry.token = run_helper(h, "get", hub, None)?; |
| 164 | 2× | } |
| 165 | 7× | } |
| 166 | 11× | if entry.token.is_none() |
| 167 | 2× | && entry.account.is_none() |
| 168 | 2× | && entry.ca.is_none() |
| 169 | 2× | && entry.grant.is_none() |
| 170 | | { |
| 171 | 0× | return Ok(None); |
| 172 | 11× | } |
| 173 | 11× | Ok(Some(entry)) |
| 174 | 41× | } |
| 175 | |
|
| 176 | | |
| 177 | 7× | pub fn save( |
| 178 | 7× | &self, |
| 179 | 7× | hub: &str, |
| 180 | 7× | token: &str, |
| 181 | 7× | account: Option<&str>, |
| 182 | 7× | ca: Option<&Path>, |
| 183 | 7× | ) -> Result<Stored, String> { |
| 184 | 7× | let mut all = self.read()?; |
| 185 | 7× | let helper = self.helper(); |
| 186 | 7× | let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry { |
| 187 | 7× | hub: hub.to_string(), |
| 188 | 7× | ..HubEntry::default() |
| 189 | 7× | }); |
| 190 | 7× | entry.account = account.map(String::from).or(entry.account.take()); |
| 191 | 7× | if let Some(ca) = ca { |
| 192 | 1× | entry.ca = Some(ca.to_path_buf()); |
| 193 | 6× | } |
| 194 | 7× | let stored = match &helper { |
| 195 | 1× | Some(h) => { |
| 196 | 1× | run_helper(h, "store", hub, Some(token))?; |
| 197 | 1× | entry.token = None; |
| 198 | 1× | Stored::Helper(h.clone()) |
| 199 | | } |
| 200 | | None => { |
| 201 | 6× | entry.token = Some(token.to_string()); |
| 202 | 6× | Stored::File(self.path()) |
| 203 | | } |
| 204 | | }; |
| 205 | 7× | self.write(&all)?; |
| 206 | 7× | forget_cached(); |
| 207 | 7× | Ok(stored) |
| 208 | 7× | } |
| 209 | |
|
| 210 | | |
| 211 | | |
| 212 | 2× | pub fn save_grant(&self, hub: &str, token: &str) -> Result<Stored, String> { |
| 213 | 2× | let mut all = self.read()?; |
| 214 | 2× | let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry { |
| 215 | 1× | hub: hub.to_string(), |
| 216 | 1× | ..HubEntry::default() |
| 217 | 1× | }); |
| 218 | 2× | let stored = match self.helper() { |
| 219 | 0× | Some(h) => { |
| 220 | 0× | run_helper_as(&h, "store", hub, GRANT_USER, Some(token))?; |
| 221 | 0× | entry.grant = None; |
| 222 | 0× | Stored::Helper(h) |
| 223 | | } |
| 224 | | None => { |
| 225 | 2× | entry.grant = Some(token.to_string()); |
| 226 | 2× | Stored::File(self.path()) |
| 227 | | } |
| 228 | | }; |
| 229 | 2× | self.write(&all)?; |
| 230 | 2× | Ok(stored) |
| 231 | 2× | } |
| 232 | |
|
| 233 | | |
| 234 | 2× | pub fn grant(&self, hub: &str) -> Result<Option<String>, String> { |
| 235 | 2× | if let Some(g) = self.read()?.get(hub).and_then(|e| e.grant.clone()) { |
| 236 | 1× | return Ok(Some(g)); |
| 237 | 1× | } |
| 238 | 1× | match self.helper() { |
| 239 | 0× | Some(h) => run_helper_as(&h, "get", hub, GRANT_USER, None), |
| 240 | 1× | None => Ok(None), |
| 241 | | } |
| 242 | 2× | } |
| 243 | |
|
| 244 | | |
| 245 | | |
| 246 | 2× | pub fn remove(&self, hub: &str) -> Result<Option<HubEntry>, String> { |
| 247 | 2× | let found = self.get(hub)?; |
| 248 | 2× | let mut all = self.read()?; |
| 249 | 2× | if all.remove(hub).is_some() { |
| 250 | 2× | self.write(&all)?; |
| 251 | 0× | } |
| 252 | 2× | if let Some(h) = self.helper() { |
| 253 | 1× | run_helper(&h, "erase", hub, None)?; |
| 254 | 1× | } |
| 255 | 2× | forget_cached(); |
| 256 | 2× | Ok(found) |
| 257 | 2× | } |
| 258 | |
|
| 259 | 55× | fn read(&self) -> Result<BTreeMap<String, HubEntry>, String> { |
| 260 | 55× | let path = self.path(); |
| 261 | 55× | let text = match std::fs::read_to_string(&path) { |
| 262 | 22× | Ok(t) => t, |
| 263 | 33× | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()), |
| 264 | 0× | Err(e) => return Err(format!("reading {}: {e}", path.display())), |
| 265 | | }; |
| 266 | 22× | let mut out = BTreeMap::new(); |
| 267 | 22× | let mut current: Option<HubEntry> = None; |
| 268 | 150× | for (n, line) in text.lines().enumerate() { |
| 269 | 150× | let line = line.trim(); |
| 270 | 150× | if line.is_empty() || line.starts_with('#') { |
| 271 | 54× | continue; |
| 272 | 96× | } |
| 273 | 96× | if let Some(hub) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { |
| 274 | 32× | if let Some(e) = current.take() { |
| 275 | 10× | out.insert(e.hub.clone(), e); |
| 276 | 22× | } |
| 277 | 32× | current = Some(HubEntry { |
| 278 | 32× | hub: hub.trim().to_string(), |
| 279 | 32× | ..HubEntry::default() |
| 280 | 32× | }); |
| 281 | 32× | continue; |
| 282 | 64× | } |
| 283 | 64× | let bad = || { |
| 284 | 0× | format!( |
| 285 | | "{} line {}: expected key = \"value\"", |
| 286 | 0× | path.display(), |
| 287 | 0× | n + 1 |
| 288 | | ) |
| 289 | 0× | }; |
| 290 | 64× | let (k, v) = line.split_once('=').ok_or_else(bad)?; |
| 291 | 64× | let v = unquote(v.trim()).ok_or_else(bad)?; |
| 292 | 64× | let Some(e) = current.as_mut() else { |
| 293 | 0× | return Err(format!( |
| 294 | 0× | "{} line {}: a key before any [hub] section", |
| 295 | 0× | path.display(), |
| 296 | 0× | n + 1 |
| 297 | 0× | )); |
| 298 | | }; |
| 299 | 64× | match k.trim() { |
| 300 | 64× | "account" => e.account = Some(v), |
| 301 | 44× | "token" => e.token = Some(v), |
| 302 | 18× | "ca" => e.ca = Some(PathBuf::from(v)), |
| 303 | 9× | "grant" => e.grant = Some(v), |
| 304 | | |
| 305 | 0× | _ => {} |
| 306 | | } |
| 307 | | } |
| 308 | 22× | if let Some(e) = current { |
| 309 | 22× | out.insert(e.hub.clone(), e); |
| 310 | 22× | } |
| 311 | 22× | Ok(out) |
| 312 | 55× | } |
| 313 | |
|
| 314 | 11× | fn write(&self, all: &BTreeMap<String, HubEntry>) -> Result<(), String> { |
| 315 | 11× | let mut text = |
| 316 | 11× | String::from("# oxy credentials: a token for each hub. Keep this file private.\n"); |
| 317 | 12× | for e in all.values() { |
| 318 | 12× | text.push_str(&format!("\n[{}]\n", e.hub)); |
| 319 | 12× | if let Some(a) = &e.account { |
| 320 | 8× | text.push_str(&format!("account = {}\n", quote(a))); |
| 321 | 8× | } |
| 322 | 12× | if let Some(t) = &e.token { |
| 323 | 10× | text.push_str(&format!("token = {}\n", quote(t))); |
| 324 | 10× | } |
| 325 | 12× | if let Some(c) = &e.ca { |
| 326 | 2× | text.push_str(&format!("ca = {}\n", quote(&c.to_string_lossy()))); |
| 327 | 10× | } |
| 328 | 12× | if let Some(g) = &e.grant { |
| 329 | 3× | text.push_str(&format!("grant = {}\n", quote(g))); |
| 330 | 9× | } |
| 331 | | } |
| 332 | 11× | let path = self.path(); |
| 333 | 11× | std::fs::create_dir_all(&self.home) |
| 334 | 11× | .map_err(|e| format!("creating {}: {e}", self.home.display()))?; |
| 335 | 11× | crate::durable::write_atomic_private(&path, text.as_bytes()) |
| 336 | 11× | .map_err(|e| format!("writing {}: {e}", path.display())) |
| 337 | 11× | } |
| 338 | |
|
| 339 | | |
| 340 | | |
| 341 | | |
| 342 | 1327× | pub fn lookup(&self, url: &str) -> (Option<String>, Option<PathBuf>) { |
| 343 | 1327× | let Some(hub) = hub_of(url) else { |
| 344 | 1154× | return (None, None); |
| 345 | | }; |
| 346 | 173× | let key = (self.home.clone(), hub.clone()); |
| 347 | 173× | if let Some(hit) = cache().lock().unwrap().get(&key) { |
| 348 | 138× | return hit.clone(); |
| 349 | 35× | } |
| 350 | 35× | let found = if self.too_open() { |
| 351 | 1× | warn_once(&format!( |
| 352 | 1× | "warning: {} can be read by other users, so oxy ignores it; run chmod 600 on it", |
| 353 | 1× | self.path().display() |
| 354 | 1× | )); |
| 355 | 1× | (None, None) |
| 356 | | } else { |
| 357 | 34× | match self.get(&hub) { |
| 358 | | |
| 359 | | |
| 360 | | |
| 361 | 5× | Ok(Some(e)) => ( |
| 362 | 5× | e.token |
| 363 | 5× | .or(e.grant) |
| 364 | 5× | .or_else(|| self.grant(&hub).ok().flatten()), |
| 365 | 5× | e.ca, |
| 366 | | ), |
| 367 | 29× | Ok(None) => (None, None), |
| 368 | 0× | Err(e) => { |
| 369 | 0× | warn_once(&format!("warning: credentials for {hub}: {e}")); |
| 370 | 0× | (None, None) |
| 371 | | } |
| 372 | | } |
| 373 | | }; |
| 374 | 35× | cache().lock().unwrap().insert(key, found.clone()); |
| 375 | 35× | found |
| 376 | 1327× | } |
| 377 | |
|
| 378 | | |
| 379 | | |
| 380 | 1319× | pub fn options_for(&self, url: &str) -> RemoteOptions { |
| 381 | 1319× | let env_token = std::env::var("OXY_TOKEN").ok().filter(|t| !t.is_empty()); |
| 382 | 1319× | let env_ca = std::env::var("OXY_CA").ok().map(PathBuf::from); |
| 383 | 1319× | let (token, ca) = match (&env_token, &env_ca) { |
| 384 | 0× | (Some(_), Some(_)) => (None, None), |
| 385 | 1319× | _ => self.lookup(url), |
| 386 | | }; |
| 387 | 1319× | RemoteOptions { |
| 388 | 1319× | token: env_token.or(token), |
| 389 | 1319× | ca: env_ca.or(ca), |
| 390 | 1319× | ..RemoteOptions::default() |
| 391 | 1319× | } |
| 392 | 1319× | } |
| 393 | | } |
| 394 | |
|
| 395 | | type Cache = Mutex<HashMap<(PathBuf, String), (Option<String>, Option<PathBuf>)>>; |
| 396 | |
|
| 397 | 217× | fn cache() -> &'static Cache { |
| 398 | | static CACHE: OnceLock<Cache> = OnceLock::new(); |
| 399 | 217× | CACHE.get_or_init(Default::default) |
| 400 | 217× | } |
| 401 | |
|
| 402 | 9× | fn forget_cached() { |
| 403 | 9× | cache().lock().unwrap().clear(); |
| 404 | 9× | } |
| 405 | |
|
| 406 | 2× | pub(crate) fn warn_once(message: &str) { |
| 407 | | static SEEN: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new(); |
| 408 | 2× | if SEEN |
| 409 | 2× | .get_or_init(Default::default) |
| 410 | 2× | .lock() |
| 411 | 2× | .unwrap() |
| 412 | 2× | .insert(message.to_string()) |
| 413 | 2× | { |
| 414 | 2× | eprintln!("{message}"); |
| 415 | 2× | } |
| 416 | 2× | } |
| 417 | |
|
| 418 | 23× | fn quote(v: &str) -> String { |
| 419 | 23× | let mut out = String::from('"'); |
| 420 | 134× | for c in v.chars() { |
| 421 | 134× | match c { |
| 422 | 2× | '"' => out.push_str("\\\""), |
| 423 | 0× | '\\' => out.push_str("\\\\"), |
| 424 | 0× | '\n' => out.push_str("\\n"), |
| 425 | 132× | c => out.push(c), |
| 426 | | } |
| 427 | | } |
| 428 | 23× | out.push('"'); |
| 429 | 23× | out |
| 430 | 23× | } |
| 431 | |
|
| 432 | 64× | fn unquote(v: &str) -> Option<String> { |
| 433 | 64× | let inner = v.strip_prefix('"')?.strip_suffix('"')?; |
| 434 | 64× | let mut out = String::new(); |
| 435 | 64× | let mut chars = inner.chars(); |
| 436 | 457× | while let Some(c) = chars.next() { |
| 437 | 393× | if c == '\\' { |
| 438 | 8× | match chars.next()? { |
| 439 | 0× | 'n' => out.push('\n'), |
| 440 | 8× | c => out.push(c), |
| 441 | | } |
| 442 | 385× | } else { |
| 443 | 385× | out.push(c); |
| 444 | 385× | } |
| 445 | | } |
| 446 | 64× | Some(out) |
| 447 | 64× | } |
| 448 | |
|
| 449 | |
|
| 450 | |
|
| 451 | |
|
| 452 | |
|
| 453 | |
|
| 454 | 4× | fn run_helper( |
| 455 | 4× | helper: &str, |
| 456 | 4× | action: &str, |
| 457 | 4× | hub: &str, |
| 458 | 4× | token: Option<&str>, |
| 459 | 4× | ) -> Result<Option<String>, String> { |
| 460 | 4× | run_helper_as(helper, action, hub, HELPER_USER, token) |
| 461 | 4× | } |
| 462 | |
|
| 463 | |
|
| 464 | |
|
| 465 | | const GRANT_USER: &str = "oxy-agent-grant"; |
| 466 | |
|
| 467 | 4× | fn run_helper_as( |
| 468 | 4× | helper: &str, |
| 469 | 4× | action: &str, |
| 470 | 4× | hub: &str, |
| 471 | 4× | user: &str, |
| 472 | 4× | token: Option<&str>, |
| 473 | 4× | ) -> Result<Option<String>, String> { |
| 474 | 4× | let (protocol, host) = hub |
| 475 | 4× | .split_once("://") |
| 476 | 4× | .ok_or_else(|| format!("{hub} is not a hub URL"))?; |
| 477 | 4× | let mut cmd = if let Some(shell) = helper.strip_prefix('!') { |
| 478 | 4× | let mut c = Command::new("sh"); |
| 479 | 4× | c.arg("-c").arg(format!("{shell} {action}")); |
| 480 | 4× | c |
| 481 | 0× | } else if Path::new(helper).is_absolute() { |
| 482 | 0× | let mut c = Command::new(helper); |
| 483 | 0× | c.arg(action); |
| 484 | 0× | c |
| 485 | | } else { |
| 486 | 0× | let mut c = Command::new("git"); |
| 487 | 0× | c.arg(format!("credential-{helper}")).arg(action); |
| 488 | 0× | c |
| 489 | | }; |
| 490 | 4× | let mut input = format!("protocol={protocol}\nhost={host}\nusername={user}\n"); |
| 491 | 4× | if let Some(t) = token { |
| 492 | 1× | input.push_str(&format!("password={t}\n")); |
| 493 | 3× | } |
| 494 | 4× | input.push('\n'); |
| 495 | 4× | let mut child = cmd |
| 496 | 4× | .stdin(Stdio::piped()) |
| 497 | 4× | .stdout(Stdio::piped()) |
| 498 | 4× | .stderr(Stdio::inherit()) |
| 499 | 4× | .spawn() |
| 500 | 4× | .map_err(|e| format!("running credential helper {helper:?}: {e}"))?; |
| 501 | | |
| 502 | | |
| 503 | | |
| 504 | 4× | match child |
| 505 | 4× | .stdin |
| 506 | 4× | .take() |
| 507 | 4× | .expect("piped") |
| 508 | 4× | .write_all(input.as_bytes()) |
| 509 | | { |
| 510 | 0× | Err(e) if e.kind() != std::io::ErrorKind::BrokenPipe => { |
| 511 | 0× | return Err(format!("credential helper {helper:?}: {e}")); |
| 512 | | } |
| 513 | 4× | _ => {} |
| 514 | | } |
| 515 | 4× | let out = child |
| 516 | 4× | .wait_with_output() |
| 517 | 4× | .map_err(|e| format!("credential helper {helper:?}: {e}"))?; |
| 518 | 4× | if !out.status.success() { |
| 519 | 0× | return Err(format!("credential helper {helper:?} {action} failed")); |
| 520 | 4× | } |
| 521 | 4× | if action != "get" { |
| 522 | 2× | return Ok(None); |
| 523 | 2× | } |
| 524 | 2× | Ok(String::from_utf8_lossy(&out.stdout) |
| 525 | 2× | .lines() |
| 526 | 2× | .find_map(|l| l.strip_prefix("password=")) |
| 527 | 2× | .map(String::from) |
| 528 | 2× | .filter(|p| !p.is_empty())) |
| 529 | 4× | } |
| 530 | |
|
| 531 | | #[cfg(test)] |
| 532 | | mod tests { |
| 533 | | use super::*; |
| 534 | |
|
| 535 | | |
| 536 | | |
| 537 | | #[test] |
| 538 | 1× | fn a_grant_token_is_kept_beside_the_hub_token() { |
| 539 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 540 | 1× | let store = Credentials::at(dir.path()); |
| 541 | 1× | let hub = "https://oxygenhub.io"; |
| 542 | 1× | assert_eq!(store.grant(hub).unwrap(), None); |
| 543 | 1× | store.save(hub, "oxyhub_t", Some("andy"), None).unwrap(); |
| 544 | 1× | store.save_grant(hub, "oxyagent_g").unwrap(); |
| 545 | 1× | assert_eq!(store.grant(hub).unwrap().as_deref(), Some("oxyagent_g")); |
| 546 | 1× | let e = store.get(hub).unwrap().unwrap(); |
| 547 | 1× | assert_eq!(e.token.as_deref(), Some("oxyhub_t")); |
| 548 | 1× | assert_eq!(e.account.as_deref(), Some("andy")); |
| 549 | | |
| 550 | 1× | store |
| 551 | 1× | .save_grant("https://elsewhere.example", "oxyagent_h") |
| 552 | 1× | .unwrap(); |
| 553 | 1× | assert!(store.get("https://elsewhere.example").unwrap().is_some()); |
| 554 | | |
| 555 | | |
| 556 | 1× | assert_eq!( |
| 557 | 1× | store.lookup("https://elsewhere.example/a/b").0.as_deref(), |
| 558 | | Some("oxyagent_h") |
| 559 | | ); |
| 560 | 1× | assert_eq!( |
| 561 | 1× | store.lookup("https://oxygenhub.io/a/b").0.as_deref(), |
| 562 | | Some("oxyhub_t") |
| 563 | | ); |
| 564 | | #[cfg(unix)] |
| 565 | | { |
| 566 | | use std::os::unix::fs::PermissionsExt; |
| 567 | 1× | let mode = std::fs::metadata(store.path()) |
| 568 | 1× | .unwrap() |
| 569 | 1× | .permissions() |
| 570 | 1× | .mode(); |
| 571 | 1× | assert_eq!(mode & 0o077, 0, "owner only"); |
| 572 | | } |
| 573 | 1× | } |
| 574 | |
|
| 575 | | #[test] |
| 576 | 1× | fn hubs_are_scheme_host_and_port() { |
| 577 | 1× | assert_eq!( |
| 578 | 1× | hub_of("https://OxygenHub.io/doomsdayone/metalgear").as_deref(), |
| 579 | | Some("https://oxygenhub.io") |
| 580 | | ); |
| 581 | 1× | assert_eq!( |
| 582 | 1× | hub_of("http://127.0.0.1:7300/a/b").as_deref(), |
| 583 | | Some("http://127.0.0.1:7300") |
| 584 | | ); |
| 585 | 1× | assert_eq!( |
| 586 | 1× | hub_of("https://user:[email protected]/x").as_deref(), |
| 587 | | Some("https://hub.example") |
| 588 | | ); |
| 589 | 1× | assert_eq!(hub_of("/srv/repo"), None); |
| 590 | 1× | assert_eq!(hub_of("file:///srv/repo"), None); |
| 591 | 1× | } |
| 592 | |
|
| 593 | | #[test] |
| 594 | 1× | fn tokens_go_over_https_or_to_this_machine() { |
| 595 | 1× | assert!(token_allowed("https://oxygenhub.io/a/b")); |
| 596 | 1× | assert!(token_allowed("http://127.0.0.1:7300/a/b")); |
| 597 | 1× | assert!(token_allowed("http://localhost/a")); |
| 598 | 1× | assert!(token_allowed("http://[::1]:8080/a")); |
| 599 | 1× | assert!(!token_allowed("http://oxygenhub.io/a/b")); |
| 600 | 1× | assert!(!token_allowed("http://10.0.0.1/a")); |
| 601 | 1× | assert!(!token_allowed("http://127.0.0.1.evil.example/a")); |
| 602 | 1× | } |
| 603 | |
|
| 604 | | #[test] |
| 605 | 1× | fn save_get_and_remove_round_trip_privately() { |
| 606 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 607 | 1× | let store = Credentials::at(dir.path()); |
| 608 | 1× | assert_eq!(store.get("https://hub.example").unwrap(), None); |
| 609 | 1× | let stored = store |
| 610 | 1× | .save("https://hub.example", "tok\"en", Some("andy"), None) |
| 611 | 1× | .unwrap(); |
| 612 | 1× | assert_eq!(stored, Stored::File(store.path())); |
| 613 | 1× | store |
| 614 | 1× | .save( |
| 615 | 1× | "http://127.0.0.1:7300", |
| 616 | 1× | "local", |
| 617 | 1× | None, |
| 618 | 1× | Some(Path::new("/ca.pem")), |
| 619 | | ) |
| 620 | 1× | .unwrap(); |
| 621 | 1× | let e = store.get("https://hub.example").unwrap().unwrap(); |
| 622 | 1× | assert_eq!(e.token.as_deref(), Some("tok\"en")); |
| 623 | 1× | assert_eq!(e.account.as_deref(), Some("andy")); |
| 624 | 1× | assert!(!store.too_open()); |
| 625 | 1× | assert_eq!( |
| 626 | 1× | store.lookup("https://hub.example/o/r"), |
| 627 | 1× | (Some("tok\"en".into()), None) |
| 628 | | ); |
| 629 | | |
| 630 | 1× | assert_eq!(store.lookup("https://other.example/o/r"), (None, None)); |
| 631 | 1× | assert_eq!(store.lookup("http://hub.example/o/r"), (None, None)); |
| 632 | 1× | assert_eq!(store.lookup("https://hub.example:8443/o/r"), (None, None)); |
| 633 | 1× | let gone = store.remove("https://hub.example").unwrap().unwrap(); |
| 634 | 1× | assert_eq!(gone.token.as_deref(), Some("tok\"en")); |
| 635 | 1× | assert_eq!(store.lookup("https://hub.example/o/r"), (None, None)); |
| 636 | 1× | assert_eq!(store.entries().unwrap().len(), 1); |
| 637 | 1× | } |
| 638 | |
|
| 639 | | #[cfg(unix)] |
| 640 | | #[test] |
| 641 | 1× | fn a_file_others_can_read_is_ignored() { |
| 642 | | use std::os::unix::fs::PermissionsExt; |
| 643 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 644 | 1× | let store = Credentials::at(dir.path()); |
| 645 | 1× | store.save("https://open.example", "t", None, None).unwrap(); |
| 646 | 1× | let mode = std::fs::metadata(store.path()) |
| 647 | 1× | .unwrap() |
| 648 | 1× | .permissions() |
| 649 | 1× | .mode(); |
| 650 | 1× | assert_eq!(mode & 0o777, 0o600); |
| 651 | 1× | std::fs::set_permissions(store.path(), std::fs::Permissions::from_mode(0o644)).unwrap(); |
| 652 | 1× | assert!(store.too_open()); |
| 653 | 1× | assert_eq!(store.lookup("https://open.example/o/r"), (None, None)); |
| 654 | 1× | } |
| 655 | |
|
| 656 | | #[cfg(unix)] |
| 657 | | #[test] |
| 658 | 1× | fn a_helper_keeps_the_token_out_of_the_file() { |
| 659 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 660 | 1× | let vault = dir.path().join("vault"); |
| 661 | | |
| 662 | 1× | let helper = format!( |
| 663 | | "!f() {{ case $1 in get) [ -f {v} ] && echo password=$(cat {v});; store) sed -n 's/^password=//p' > {v};; erase) rm -f {v};; esac; }}; f", |
| 664 | 1× | v = vault.display() |
| 665 | | ); |
| 666 | 1× | std::fs::write( |
| 667 | 1× | dir.path().join("config.toml"), |
| 668 | 1× | format!("auth.helper = \"{helper}\"\n"), |
| 669 | | ) |
| 670 | 1× | .unwrap(); |
| 671 | 1× | let store = Credentials::at(dir.path()); |
| 672 | 1× | assert!(store.helper().is_some()); |
| 673 | 1× | let stored = store |
| 674 | 1× | .save("https://hub.example", "secret", Some("andy"), None) |
| 675 | 1× | .unwrap(); |
| 676 | 1× | assert!(matches!(stored, Stored::Helper(_))); |
| 677 | 1× | let text = std::fs::read_to_string(store.path()).unwrap(); |
| 678 | 1× | assert!(!text.contains("secret"), "{text}"); |
| 679 | 1× | assert_eq!( |
| 680 | 1× | store |
| 681 | 1× | .get("https://hub.example") |
| 682 | 1× | .unwrap() |
| 683 | 1× | .unwrap() |
| 684 | 1× | .token |
| 685 | 1× | .as_deref(), |
| 686 | | Some("secret") |
| 687 | | ); |
| 688 | 1× | store.remove("https://hub.example").unwrap(); |
| 689 | 1× | assert!(!vault.exists()); |
| 690 | 1× | } |
| 691 | | } |