| 1 | |
|
| 2 | |
|
| 3 | | use super::ui; |
| 4 | | use anyhow::{bail, Context, Result}; |
| 5 | | use oxy_core::credentials::{hub_of, token_allowed, Credentials, Stored}; |
| 6 | | use oxy_core::protocol::{http_json, RemoteOptions}; |
| 7 | | use oxy_core::repo::Repo; |
| 8 | | use serde_json::Value; |
| 9 | | use std::io::BufRead; |
| 10 | | use std::path::{Path, PathBuf}; |
| 11 | | use std::time::{Duration, Instant}; |
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | | const SCOPES: [&str; 3] = ["repo:read", "repo:write", "user:read"]; |
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | 0× | fn resolve_hub(arg: Option<&str>) -> Result<String> { |
| 20 | 0× | if let Some(a) = arg { |
| 21 | 0× | let url = if a.contains("://") { |
| 22 | 0× | a.to_string() |
| 23 | | } else { |
| 24 | 0× | format!("https://{a}") |
| 25 | | }; |
| 26 | 0× | return hub_of(&url).with_context(|| format!("{a} is not a hub URL")); |
| 27 | 0× | } |
| 28 | 0× | if let Ok(repo) = Repo::open(Path::new(".")) { |
| 29 | 0× | let remotes = &repo.config.remotes; |
| 30 | 0× | let url = remotes.get("origin").or_else(|| { |
| 31 | 0× | (remotes.len() == 1) |
| 32 | 0× | .then(|| remotes.values().next()) |
| 33 | 0× | .flatten() |
| 34 | 0× | }); |
| 35 | 0× | if let Some(hub) = url.and_then(|u| hub_of(u)) { |
| 36 | 0× | return Ok(hub); |
| 37 | 0× | } |
| 38 | 0× | } |
| 39 | 0× | bail!("name the hub, as in: oxy auth login https://oxygenhub.io") |
| 40 | 0× | } |
| 41 | |
|
| 42 | |
|
| 43 | 0× | fn whoami(hub: &str, options: &RemoteOptions) -> Result<std::result::Result<String, String>> { |
| 44 | 0× | let (code, body) = http_json("GET", &format!("{hub}/api/v1/user"), None, options) |
| 45 | 0× | .map_err(|e| anyhow::anyhow!("{e}"))?; |
| 46 | 0× | if code != 200 { |
| 47 | 0× | return Ok(Err(format!("HTTP {code}"))); |
| 48 | 0× | } |
| 49 | 0× | let v: Value = serde_json::from_str(&body).context("the hub's answer about the account")?; |
| 50 | 0× | Ok(v["username"] |
| 51 | 0× | .as_str() |
| 52 | 0× | .map(String::from) |
| 53 | 0× | .ok_or_else(|| "no account in the answer".to_string())) |
| 54 | 0× | } |
| 55 | |
|
| 56 | 0× | fn device_client() -> String { |
| 57 | 0× | let host = std::fs::read_to_string("/etc/hostname") |
| 58 | 0× | .ok() |
| 59 | 0× | .or_else(|| std::env::var("COMPUTERNAME").ok()) |
| 60 | 0× | .map(|h| h.trim().to_string()) |
| 61 | 0× | .filter(|h| !h.is_empty()); |
| 62 | 0× | match host { |
| 63 | 0× | Some(h) => format!("oxy on {h}"), |
| 64 | 0× | None => "oxy".to_string(), |
| 65 | | } |
| 66 | 0× | } |
| 67 | |
|
| 68 | |
|
| 69 | |
|
| 70 | 0× | fn device_sign_in(hub: &str, options: &RemoteOptions) -> Result<String> { |
| 71 | 0× | let request = serde_json::json!({ "client": device_client(), "scopes": SCOPES }).to_string(); |
| 72 | 0× | let (code, body) = http_json( |
| 73 | 0× | "POST", |
| 74 | 0× | &format!("{hub}/api/v1/device/code"), |
| 75 | 0× | Some(&request), |
| 76 | 0× | options, |
| 77 | | ) |
| 78 | 0× | .map_err(|e| anyhow::anyhow!("{e}"))?; |
| 79 | 0× | let v: Value = serde_json::from_str(&body) |
| 80 | 0× | .with_context(|| format!("{hub} did not answer a sign-in request (HTTP {code})"))?; |
| 81 | 0× | if code != 200 { |
| 82 | 0× | bail!( |
| 83 | | "{hub} cannot sign in a device: {}", |
| 84 | 0× | v["error_description"] |
| 85 | 0× | .as_str() |
| 86 | 0× | .or(v["detail"].as_str()) |
| 87 | 0× | .unwrap_or(&body) |
| 88 | | ); |
| 89 | 0× | } |
| 90 | 0× | let device = v["device_code"] |
| 91 | 0× | .as_str() |
| 92 | 0× | .context("no device code")? |
| 93 | 0× | .to_string(); |
| 94 | 0× | let user_code = v["user_code"].as_str().unwrap_or("?"); |
| 95 | 0× | let url = v["verification_uri_complete"] |
| 96 | 0× | .as_str() |
| 97 | 0× | .or(v["verification_uri"].as_str()) |
| 98 | 0× | .unwrap_or(hub); |
| 99 | 0× | let mut interval = v["interval"].as_u64().unwrap_or(5).max(1); |
| 100 | 0× | let deadline = Instant::now() + Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900)); |
| 101 | 0× | eprintln!( |
| 102 | | "Open {} and approve the code {}", |
| 103 | 0× | ui::path(url), |
| 104 | 0× | ui::subject(user_code) |
| 105 | | ); |
| 106 | 0× | eprintln!( |
| 107 | | " {} {}", |
| 108 | 0× | ui::note(), |
| 109 | 0× | ui::dim("approve only a code you started yourself, just now") |
| 110 | | ); |
| 111 | 0× | let sp = ui::spinner("Waiting for approval (Ctrl-C to give up)…"); |
| 112 | 0× | let poll = serde_json::json!({ "device_code": device }).to_string(); |
| 113 | | loop { |
| 114 | 0× | std::thread::sleep(Duration::from_secs(interval)); |
| 115 | 0× | if Instant::now() > deadline { |
| 116 | 0× | sp.clear(); |
| 117 | 0× | bail!("the code expired before it was approved; run oxy auth login again"); |
| 118 | 0× | } |
| 119 | 0× | let (code, body) = http_json( |
| 120 | 0× | "POST", |
| 121 | 0× | &format!("{hub}/api/v1/device/token"), |
| 122 | 0× | Some(&poll), |
| 123 | 0× | options, |
| 124 | | ) |
| 125 | 0× | .map_err(|e| anyhow::anyhow!("{e}"))?; |
| 126 | 0× | let v: Value = serde_json::from_str(&body).unwrap_or_default(); |
| 127 | 0× | if code == 200 { |
| 128 | 0× | sp.clear(); |
| 129 | 0× | return v["access_token"] |
| 130 | 0× | .as_str() |
| 131 | 0× | .map(String::from) |
| 132 | 0× | .context("no token in the hub's answer"); |
| 133 | 0× | } |
| 134 | 0× | match v["error"].as_str() { |
| 135 | 0× | Some("authorization_pending") => {} |
| 136 | 0× | Some("slow_down") => interval += 5, |
| 137 | 0× | Some("access_denied") => { |
| 138 | 0× | sp.clear(); |
| 139 | 0× | bail!("the sign-in was denied on the hub"); |
| 140 | | } |
| 141 | 0× | Some("expired_token") => { |
| 142 | 0× | sp.clear(); |
| 143 | 0× | bail!("the code expired before it was approved; run oxy auth login again"); |
| 144 | | } |
| 145 | | _ => { |
| 146 | 0× | sp.clear(); |
| 147 | 0× | bail!("signing in: HTTP {code}: {}", body.trim()); |
| 148 | | } |
| 149 | | } |
| 150 | | } |
| 151 | 0× | } |
| 152 | |
|
| 153 | 0× | fn where_stored(stored: &Stored) -> String { |
| 154 | 0× | match stored { |
| 155 | 0× | Stored::File(p) => format!("{} (yours only)", p.display()), |
| 156 | 0× | Stored::Helper(h) => format!("credential helper {h}"), |
| 157 | | } |
| 158 | 0× | } |
| 159 | |
|
| 160 | 0× | pub fn login(hub: Option<&str>, with_token: bool, ca: Option<PathBuf>) -> Result<i32> { |
| 161 | 0× | let hub = resolve_hub(hub)?; |
| 162 | 0× | if !token_allowed(&hub) { |
| 163 | 0× | bail!("{hub} is plain http: a token would cross the network unencrypted; sign in to its https address"); |
| 164 | 0× | } |
| 165 | 0× | let store = Credentials::user(); |
| 166 | 0× | let ca = ca |
| 167 | 0× | .map(|c| std::fs::canonicalize(&c).unwrap_or(c)) |
| 168 | 0× | .or_else(|| store.get(&hub).ok().flatten().and_then(|e| e.ca)) |
| 169 | 0× | .or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)); |
| 170 | 0× | let anonymous = RemoteOptions { |
| 171 | 0× | token: None, |
| 172 | 0× | ca: ca.clone(), |
| 173 | 0× | ..RemoteOptions::default() |
| 174 | 0× | }; |
| 175 | 0× | let token = if with_token { |
| 176 | 0× | let mut line = String::new(); |
| 177 | 0× | std::io::stdin() |
| 178 | 0× | .lock() |
| 179 | 0× | .read_line(&mut line) |
| 180 | 0× | .context("reading the token from standard input")?; |
| 181 | 0× | let t = line.trim().to_string(); |
| 182 | 0× | if t.is_empty() { |
| 183 | 0× | bail!("no token on standard input"); |
| 184 | 0× | } |
| 185 | 0× | t |
| 186 | | } else { |
| 187 | 0× | device_sign_in(&hub, &anonymous)? |
| 188 | | }; |
| 189 | 0× | let options = RemoteOptions { |
| 190 | 0× | token: Some(token.clone()), |
| 191 | 0× | ..anonymous |
| 192 | 0× | }; |
| 193 | 0× | let account = match whoami(&hub, &options)? { |
| 194 | 0× | Ok(a) => Some(a), |
| 195 | 0× | Err(why) if with_token => bail!("{hub} did not accept the token ({why})"), |
| 196 | | |
| 197 | 0× | Err(_) => None, |
| 198 | | }; |
| 199 | 0× | let stored = store |
| 200 | 0× | .save(&hub, &token, account.as_deref(), ca.as_deref()) |
| 201 | 0× | .map_err(|e| anyhow::anyhow!("{e}"))?; |
| 202 | 0× | let who = account |
| 203 | 0× | .as_deref() |
| 204 | 0× | .map(|a| format!(" as {}", ui::author(a))) |
| 205 | 0× | .unwrap_or_default(); |
| 206 | 0× | println!("{} to {}{who}", ui::done("Signed in"), ui::path(&hub)); |
| 207 | 0× | println!( |
| 208 | | " {} {}", |
| 209 | 0× | ui::note(), |
| 210 | 0× | ui::dim(format!("token in {}", where_stored(&stored))) |
| 211 | | ); |
| 212 | 0× | Ok(0) |
| 213 | 0× | } |
| 214 | |
|
| 215 | |
|
| 216 | |
|
| 217 | 0× | pub fn grant(hub: Option<&str>) -> Result<i32> { |
| 218 | | use std::io::IsTerminal; |
| 219 | 0× | let hub = resolve_hub(hub)?; |
| 220 | 0× | if !token_allowed(&hub) { |
| 221 | 0× | bail!("{hub} is plain http: a token would cross the network unencrypted; use its https address"); |
| 222 | 0× | } |
| 223 | 0× | if std::io::stdin().is_terminal() { |
| 224 | 0× | eprint!("Agent grant token for {hub}: "); |
| 225 | 0× | } |
| 226 | 0× | let mut line = String::new(); |
| 227 | 0× | std::io::stdin() |
| 228 | 0× | .lock() |
| 229 | 0× | .read_line(&mut line) |
| 230 | 0× | .context("reading the token from standard input")?; |
| 231 | 0× | let token = line.trim(); |
| 232 | 0× | if !token.starts_with("oxyagent_") { |
| 233 | 0× | bail!("that is not an agent grant token (they start oxyagent_; `oh agent grant NAME` makes one)"); |
| 234 | 0× | } |
| 235 | 0× | let stored = Credentials::user() |
| 236 | 0× | .save_grant(&hub, token) |
| 237 | 0× | .map_err(|e| anyhow::anyhow!("{e}"))?; |
| 238 | 0× | println!( |
| 239 | | "{} for {}", |
| 240 | 0× | ui::done("Kept the agent grant"), |
| 241 | 0× | ui::path(&hub) |
| 242 | | ); |
| 243 | 0× | println!( |
| 244 | | " {} {}", |
| 245 | 0× | ui::note(), |
| 246 | 0× | ui::dim(format!( |
| 247 | | "token in {}; sign with it: oxy config author.signer keyless", |
| 248 | 0× | where_stored(&stored) |
| 249 | | )) |
| 250 | | ); |
| 251 | 0× | Ok(0) |
| 252 | 0× | } |
| 253 | |
|
| 254 | |
|
| 255 | 0× | fn masked(token: &str) -> String { |
| 256 | 0× | let shown: String = token.chars().take(10).collect(); |
| 257 | 0× | format!("{shown}…") |
| 258 | 0× | } |
| 259 | |
|
| 260 | 0× | pub fn status() -> Result<i32> { |
| 261 | 0× | let store = Credentials::user(); |
| 262 | 0× | let entries = store.entries().map_err(|e| anyhow::anyhow!("{e}"))?; |
| 263 | 0× | if store.too_open() { |
| 264 | 0× | println!( |
| 265 | 0× | "{} {} {}", |
| 266 | 0× | ui::caution(), |
| 267 | 0× | ui::path(store.path().display()), |
| 268 | 0× | ui::warn("can be read by other users, so oxy ignores it: run chmod 600 on it") |
| 269 | 0× | ); |
| 270 | 0× | } |
| 271 | 0× | if std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty()) { |
| 272 | 0× | println!( |
| 273 | 0× | "{} {}", |
| 274 | 0× | ui::note(), |
| 275 | 0× | ui::dim("OXY_TOKEN is set: it is used ahead of the tokens below, for every hub") |
| 276 | 0× | ); |
| 277 | 0× | } |
| 278 | 0× | if entries.is_empty() { |
| 279 | 0× | println!( |
| 280 | | "{}", |
| 281 | 0× | ui::dim("Not signed in to any hub: run oxy auth login HUB") |
| 282 | | ); |
| 283 | 0× | return Ok(0); |
| 284 | 0× | } |
| 285 | 0× | let helper = store.helper(); |
| 286 | 0× | let mut bad = false; |
| 287 | 0× | for e in entries { |
| 288 | 0× | let full = store.get(&e.hub).map_err(|e| anyhow::anyhow!("{e}"))?; |
| 289 | 0× | let token = full.as_ref().and_then(|f| f.token.clone()); |
| 290 | 0× | println!("{}", ui::section(&e.hub)); |
| 291 | 0× | let Some(token) = token else { |
| 292 | 0× | println!( |
| 293 | | " {}", |
| 294 | 0× | ui::warn("no token stored: run oxy auth login again") |
| 295 | | ); |
| 296 | 0× | bad = true; |
| 297 | 0× | continue; |
| 298 | | }; |
| 299 | 0× | let options = RemoteOptions { |
| 300 | 0× | token: Some(token.clone()), |
| 301 | 0× | ca: e.ca.clone(), |
| 302 | 0× | ..RemoteOptions::default() |
| 303 | 0× | }; |
| 304 | 0× | let check = match whoami(&e.hub, &options) { |
| 305 | 0× | Ok(Ok(a)) => ui::ok(format!("valid, signed in as {a}")), |
| 306 | 0× | Ok(Err(why)) if why == "HTTP 401" => { |
| 307 | 0× | bad = true; |
| 308 | 0× | ui::err("rejected by the hub: expired or revoked; run oxy auth login again") |
| 309 | | } |
| 310 | 0× | Ok(Err(why)) => ui::warn(format!("not checked ({why})")), |
| 311 | 0× | Err(e) => ui::warn(format!("not checked ({e})")), |
| 312 | | }; |
| 313 | 0× | println!( |
| 314 | | "{}", |
| 315 | 0× | ui::kv("token", format!("{} {}", masked(&token), check)) |
| 316 | | ); |
| 317 | 0× | if let Some(a) = &e.account { |
| 318 | 0× | println!("{}", ui::kv("account", ui::author(a))); |
| 319 | 0× | } |
| 320 | 0× | let place = match &helper { |
| 321 | 0× | Some(h) => format!("credential helper {h}"), |
| 322 | 0× | None => store.path().display().to_string(), |
| 323 | | }; |
| 324 | 0× | println!("{}", ui::kv("stored", ui::dim(place))); |
| 325 | 0× | if let Some(ca) = &e.ca { |
| 326 | 0× | println!("{}", ui::kv("ca", ui::path(ca.display()))); |
| 327 | 0× | } |
| 328 | | } |
| 329 | 0× | Ok(if bad { 1 } else { 0 }) |
| 330 | 0× | } |
| 331 | |
|
| 332 | 0× | pub fn logout(hub: Option<&str>) -> Result<i32> { |
| 333 | 0× | let store = Credentials::user(); |
| 334 | 0× | let hub = match hub { |
| 335 | 0× | Some(_) => resolve_hub(hub)?, |
| 336 | | None => { |
| 337 | 0× | let entries = store.entries().map_err(|e| anyhow::anyhow!("{e}"))?; |
| 338 | 0× | match (entries.len(), resolve_hub(None)) { |
| 339 | 0× | (_, Ok(h)) => h, |
| 340 | 0× | (1, Err(_)) => entries[0].hub.clone(), |
| 341 | 0× | _ => bail!("name the hub to sign out of (oxy auth status lists them)"), |
| 342 | | } |
| 343 | | } |
| 344 | | }; |
| 345 | 0× | let Some(entry) = store.remove(&hub).map_err(|e| anyhow::anyhow!("{e}"))? else { |
| 346 | 0× | println!("{}", ui::dim(format!("Not signed in to {hub}"))); |
| 347 | 0× | return Ok(0); |
| 348 | | }; |
| 349 | | |
| 350 | 0× | let revoked = match &entry.token { |
| 351 | 0× | Some(t) => { |
| 352 | 0× | let options = RemoteOptions { |
| 353 | 0× | token: Some(t.clone()), |
| 354 | 0× | ca: entry.ca.clone(), |
| 355 | 0× | ..RemoteOptions::default() |
| 356 | 0× | }; |
| 357 | 0× | matches!( |
| 358 | 0× | http_json( |
| 359 | 0× | "DELETE", |
| 360 | 0× | &format!("{hub}/api/v1/user/token"), |
| 361 | 0× | None, |
| 362 | 0× | &options |
| 363 | 0× | ), |
| 364 | | Ok((200 | 204, _)) |
| 365 | | ) |
| 366 | | } |
| 367 | 0× | None => false, |
| 368 | | }; |
| 369 | 0× | println!("{} of {}", ui::done("Signed out"), ui::path(&hub)); |
| 370 | 0× | if revoked { |
| 371 | 0× | println!( |
| 372 | 0× | " {} {}", |
| 373 | 0× | ui::note(), |
| 374 | 0× | ui::dim("the token was revoked on the hub") |
| 375 | 0× | ); |
| 376 | 0× | } else { |
| 377 | 0× | println!( |
| 378 | 0× | " {} {}", |
| 379 | 0× | ui::caution(), |
| 380 | 0× | ui::warn("the hub did not revoke the token: revoke it under Settings → Tokens") |
| 381 | 0× | ); |
| 382 | 0× | } |
| 383 | 0× | Ok(0) |
| 384 | 0× | } |