OXYGENHUB
◆ v0.5.2 oxygenhub / crates / oh / src / target.rs
11.2 KiB · Rust · last changed oh signs in through oxy's credential store; pin oxygen with oxy auth and remote bookmarks (refs andymccall/oxygen#47, #48) 1 month ago source blame history raw
5c6e92fd Andy McCall ↶ 1
//! Which hub and repository a command talks to, and with which token.
2
//!
3
//! Inside an Oxygen checkout, `oh` uses the checkout's remote (`origin`, or
4
//! the only one, or `--remote NAME`): its URL names the hub and the
5
//! repository, and its token and CA are the ones `oxy` pushes with.
6
//! Elsewhere, `--repo OWNER/NAME` with the hub from `--hub`, `OH_HUB` or
7
//! the one `oh auth login` saved.
8
9
use anyhow::{anyhow, bail, Context, Result};
10
use serde::{Deserialize, Serialize};
11
use std::path::{Path, PathBuf};
12
2bbe88a8 Andy McCall ↶ 13
/// `~/.config/oh/config.toml`: the default hub. Tokens are oxy's: one
14
/// sign-in (`oh auth login` or `oxy auth login`) serves both, kept in
15
/// oxy's credential store (oxygen#47).
5c6e92fd Andy McCall ↶ 16
#[derive(Debug, Default, Serialize, Deserialize)]
17
pub struct Config {
18
    #[serde(default)]
19
    pub default_hub: Option<String>,
20
}
21
2bbe88a8 Andy McCall ↶ 22
/// What oxy's credential store holds for a hub.
23
#[derive(Clone, Debug, Default)]
5c6e92fd Andy McCall ↶ 24
pub struct Host {
25
    pub token: String,
26
    pub ca: Option<PathBuf>,
2bbe88a8 Andy McCall ↶ 27
}
28
29
fn stored(hub: &str) -> Host {
30
    let (token, ca) = oxy_core::credentials::Credentials::user().lookup(hub);
31
    Host { token: token.unwrap_or_default(), ca }
5c6e92fd Andy McCall ↶ 32
}
33
34
pub fn config_path() -> Result<PathBuf> {
35
    if let Some(p) = std::env::var_os("OH_CONFIG") {
36
        return Ok(PathBuf::from(p));
37
    }
38
    let base = match std::env::var_os("XDG_CONFIG_HOME") {
39
        Some(d) => PathBuf::from(d),
bd630386 Andy McCall ↶ 40
        // Windows has no HOME as a rule: the roaming profile's application data.
41
        #[cfg(windows)]
42
        None => PathBuf::from(std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")).context("APPDATA is not set")?),
43
        #[cfg(not(windows))]
5c6e92fd Andy McCall ↶ 44
        None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".config"),
45
    };
46
    Ok(base.join("oh").join("config.toml"))
47
}
48
49
impl Config {
50
    pub fn load() -> Result<Config> {
51
        let p = config_path()?;
52
        match std::fs::read_to_string(&p) {
53
            Ok(t) => toml::from_str(&t).with_context(|| format!("parse {}", p.display())),
54
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
55
            Err(e) => Err(e).with_context(|| format!("read {}", p.display())),
56
        }
57
    }
58
bd630386 Andy McCall ↶ 59
    /// Written owner-only: it holds tokens. (On Windows the file sits in the
60
    /// user's own profile, which only they and administrators can read.)
5c6e92fd Andy McCall ↶ 61
    pub fn save(&self) -> Result<()> {
62
        use std::io::Write;
63
        let p = config_path()?;
64
        std::fs::create_dir_all(p.parent().unwrap())?;
65
        let tmp = p.with_extension("toml.tmp");
bd630386 Andy McCall ↶ 66
        let mut options = std::fs::OpenOptions::new();
67
        options.write(true).create(true).truncate(true);
68
        #[cfg(unix)]
69
        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
70
        let mut f = options.open(&tmp)?;
5c6e92fd Andy McCall ↶ 71
        f.write_all(toml::to_string_pretty(self)?.as_bytes())?;
72
        f.sync_all()?;
73
        std::fs::rename(&tmp, &p)?;
74
        Ok(())
75
    }
76
}
77
78
/// A hub, and a repository on it when the command needs one.
79
#[derive(Clone, Debug)]
80
pub struct Target {
81
    /// `https://host:port`, no trailing slash.
82
    pub hub: String,
83
    pub token: Option<String>,
84
    pub ca: Option<PathBuf>,
85
    pub owner: String,
86
    pub name: String,
87
}
88
89
impl Target {
90
    pub fn repo(&self) -> Result<(&str, &str)> {
91
        if self.owner.is_empty() {
92
            bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME");
93
        }
94
        Ok((&self.owner, &self.name))
95
    }
96
97
    /// `/repos/{owner}/{name}`.
98
    pub fn repo_path(&self) -> Result<String> {
99
        let (o, n) = self.repo()?;
100
        Ok(format!("/repos/{o}/{n}"))
101
    }
102
}
103
104
/// Split `https://host:port/owner/name` into the hub and the repository.
105
pub fn split_url(url: &str) -> Result<(String, String, String)> {
106
    let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?;
107
    let mut parts = rest.trim_end_matches('/').splitn(2, '/');
108
    let host = parts.next().unwrap_or("");
109
    let path = parts.next().unwrap_or("");
110
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
111
    match segs.as_slice() {
112
        [o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())),
113
        _ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"),
114
    }
115
}
116
cefb0ea2 Andy McCall ↶ 117
/// A token and CA for `hub` from the checkout at `dir` or one enclosing
118
/// it (a subrepo's parent): the first remote on that hub that has each.
119
fn checkout_credentials(dir: &Path, hub: &str) -> (Option<String>, Option<PathBuf>) {
120
    let (mut token, mut ca) = (None, None);
121
    let mut at = Some(dir.to_path_buf());
122
    while let Some(d) = at {
123
        let Ok(repo) = oxy_core::repo::Repo::open(&d) else { break };
124
        for (name, url) in &repo.config.remotes {
125
            if split_url(url).is_ok_and(|(h, _, _)| h.eq_ignore_ascii_case(hub)) {
126
                token = token.or_else(|| repo.config.remote_tokens.get(name).cloned());
127
                ca = ca.or_else(|| repo.config.remote_cas.get(name).map(PathBuf::from));
128
            }
129
        }
130
        if token.is_some() && ca.is_some() {
131
            break;
132
        }
133
        at = repo.root().parent().map(Path::to_path_buf);
134
    }
135
    (token, ca)
136
}
137
138
/// The hub of the checkout's remote (the one chosen, `origin`, or the only
139
/// one), for `--repo` without `--hub`.
140
fn checkout_hub(dir: &Path, remote: Option<&str>) -> Option<String> {
141
    let repo = oxy_core::repo::Repo::open(dir).ok()?;
142
    let remotes = &repo.config.remotes;
143
    let url = match remote {
144
        Some(n) => remotes.get(n)?,
145
        None => remotes.get("origin").or_else(|| (remotes.len() == 1).then(|| remotes.values().next()).flatten())?,
146
    };
147
    split_url(url).ok().map(|(hub, _, _)| hub)
148
}
149
5c6e92fd Andy McCall ↶ 150
pub struct Choice<'a> {
151
    pub repo: Option<&'a str>,
152
    pub hub: Option<&'a str>,
153
    pub remote: Option<&'a str>,
154
}
155
156
/// Resolve what to talk to from the flags, the checkout at `dir`, the
157
/// environment and the saved configuration.
158
pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result<Target> {
159
    let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty());
160
    let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from);
2bbe88a8 Andy McCall ↶ 161
    let saved = |hub: &str| Some(stored(hub));
5c6e92fd Andy McCall ↶ 162
    if let Some(r) = choice.repo {
163
        let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?;
cefb0ea2 Andy McCall ↶ 164
        // Inside a checkout, its remote's hub, token and CA serve for
165
        // another repository on the same hub.
5c6e92fd Andy McCall ↶ 166
        let hub = choice
167
            .hub
168
            .map(String::from)
169
            .or_else(|| std::env::var("OH_HUB").ok())
cefb0ea2 Andy McCall ↶ 170
            .or_else(|| checkout_hub(dir, choice.remote))
5c6e92fd Andy McCall ↶ 171
            .or_else(|| cfg.default_hub.clone())
172
            .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?;
173
        let hub = hub.trim_end_matches('/').to_string();
174
        let host = saved(&hub).unwrap_or_default();
cefb0ea2 Andy McCall ↶ 175
        let (co_token, co_ca) = checkout_credentials(dir, &hub);
5c6e92fd Andy McCall ↶ 176
        return Ok(Target {
cefb0ea2 Andy McCall ↶ 177
            token: env_token.or(co_token).or(Some(host.token).filter(|t| !t.is_empty())),
178
            ca: env_ca.or(co_ca).or(host.ca),
5c6e92fd Andy McCall ↶ 179
            hub,
180
            owner: owner.into(),
181
            name: name.into(),
182
        });
183
    }
184
    // The checkout's remote.
185
    if let Ok(repo) = oxy_core::repo::Repo::open(dir) {
186
        let remotes = &repo.config.remotes;
187
        let name = match choice.remote {
188
            Some(n) => n.to_string(),
189
            None if remotes.contains_key("origin") => "origin".into(),
190
            None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(),
191
            None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"),
192
            None => bail!(
193
                "this checkout has several remotes ({}); choose one with --remote",
194
                remotes.keys().cloned().collect::<Vec<_>>().join(", ")
195
            ),
196
        };
197
        let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?;
198
        let (hub, owner, repo_name) = split_url(url)?;
199
        let host = saved(&hub).unwrap_or_default();
cefb0ea2 Andy McCall ↶ 200
        // The remote's own, then a parent checkout's for the same hub (a
201
        // subrepo cloned before it recorded them), then the saved ones.
202
        let (up_token, up_ca) = repo.root().parent().map(|p| checkout_credentials(p, &hub)).unwrap_or_default();
203
        let token =
204
            env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(up_token).or(Some(host.token).filter(|t| !t.is_empty()));
205
        let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(up_ca).or(host.ca);
5c6e92fd Andy McCall ↶ 206
        return Ok(Target { hub, token, ca, owner, name: repo_name });
207
    }
208
    // No repository: commands that need only a hub.
209
    let hub = choice
210
        .hub
211
        .map(String::from)
212
        .or_else(|| std::env::var("OH_HUB").ok())
213
        .or_else(|| cfg.default_hub.clone())
214
        .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?;
215
    let hub = hub.trim_end_matches('/').to_string();
216
    let host = saved(&hub).unwrap_or_default();
217
    Ok(Target {
218
        token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
219
        ca: env_ca.or(host.ca),
220
        hub,
221
        owner: String::new(),
222
        name: String::new(),
223
    })
224
}
225
226
#[cfg(test)]
227
mod tests {
228
    use super::*;
229
230
    #[test]
231
    fn remote_urls_name_the_hub_and_the_repository() {
232
        assert_eq!(
233
            split_url("https://earth.example:7343/andy/oxygen").unwrap(),
234
            ("https://earth.example:7343".into(), "andy".into(), "oxygen".into())
235
        );
236
        assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b");
237
        assert!(split_url("https://hub/only-owner").is_err());
238
        assert!(split_url("not a url").is_err());
cefb0ea2 Andy McCall ↶ 239
    }
240
241
    /// oxygenhub#50, #51: a subrepo checkout whose remote has no token
242
    /// borrows its parent's for the same hub, and --repo inside a checkout
243
    /// takes the checkout's hub and token.
244
    #[test]
245
    fn checkouts_lend_their_hub_and_token() {
246
        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() {
247
            return;
248
        }
249
        let dir = tempfile::tempdir().unwrap();
250
        let parent = dir.path().join("metalgear");
251
        let mut p = oxy_core::repo::Repo::init(&parent).unwrap();
252
        p.config.set("remote.origin.url", "https://hub.example/doomsdayone/metalgear").unwrap();
253
        p.config.set("remote.origin.token", "parent-token").unwrap();
254
        p.save_config().unwrap();
255
        let sub = parent.join("rstar-api");
256
        let mut s = oxy_core::repo::Repo::init(&sub).unwrap();
257
        s.config.set("remote.origin.url", "https://hub.example/doomsdayone/rstar-api").unwrap();
258
        s.save_config().unwrap();
259
        let cfg = Config::default();
260
        let none = Choice { repo: None, hub: None, remote: None };
261
        let t = resolve(&none, &sub, &cfg).unwrap();
262
        assert_eq!((t.name.as_str(), t.token.as_deref()), ("rstar-api", Some("parent-token")));
263
        let other = Choice { repo: Some("doomsdayone/other"), hub: None, remote: None };
264
        let t = resolve(&other, &parent, &cfg).unwrap();
265
        assert_eq!((t.hub.as_str(), t.token.as_deref()), ("https://hub.example", Some("parent-token")));
5c6e92fd Andy McCall ↶ 266
    }
267
}