gitaway 0.1.0

Reach your self-hosted git server from anywhere, with a tunnel only gitaway uses
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Decide which profile applies to a command.
//!
//! The first rule that applies wins:
//!
//! 1. `--profile <name>`
//! 2. the `GITAWAY_PROFILE` environment variable
//! 3. `git config gitaway.profile` (repo, then global, then `includeIf`)
//! 4. the one profile whose `[hosts]` handles any of the command's URLs
//!    (a push can go to several)
//! 5. `default_profile` in `config.toml`
//!
//! If several profiles handle those URLs in step 4, each one's home check
//! runs. If exactly one passes, you're at that home and it's used. Otherwise
//! the default is used if it's one of them (say, one server set up twice,
//! for ssh and for https): that's a choice you made, not a guess. Otherwise
//! it's an error: away from home the candidates can't be told apart, and
//! gitaway never guesses.
//!
//! [`resolve`] is pure. The caller gathers the inputs (flags, environment,
//! git config, profiles) and passes the home check in as a function, so every
//! rule can be tested without a network, git or files.

use std::collections::BTreeMap;

use crate::git::remote_url::RemoteUrl;

use super::name::ProfileName;
use super::profile::Profile;

/// Everything that can name a profile, gathered by the caller.
#[derive(Debug, Clone, Copy, Default)]
pub struct Inputs<'a> {
    /// From `--profile`.
    pub flag: Option<&'a ProfileName>,
    /// From `GITAWAY_PROFILE`.
    pub env: Option<&'a ProfileName>,
    /// From `git config gitaway.profile`.
    pub git_config: Option<&'a ProfileName>,
    /// Every network URL the command may contact; empty if none could be
    /// worked out.
    pub remotes: &'a [RemoteUrl],
    /// From `default_profile` in `config.toml`.
    pub default: Option<&'a ProfileName>,
}

/// Which rule chose the profile. Used in messages, so a user can see why a
/// profile was picked.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Source {
    /// `--profile`.
    Flag,
    /// `GITAWAY_PROFILE`.
    Env,
    /// `git config gitaway.profile`.
    GitConfig,
    /// The remote's host matched one profile's `[hosts]`.
    HostMatch,
    /// The remote's host matched several profiles, and only this one's home
    /// check passed.
    VerifiedHome,
    /// `default_profile`.
    Default,
}

/// The chosen profile and why it was chosen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Resolved<'a> {
    /// The profile's name.
    pub name: &'a ProfileName,
    /// The profile.
    pub profile: &'a Profile,
    /// The rule that chose it.
    pub source: Source,
}

/// No profile could be chosen safely.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ResolveError {
    /// A profile was named explicitly but doesn't exist.
    #[error("profile `{name}` (from {origin}) doesn't exist; see `gitaway profile list`")]
    NotFound {
        /// The missing profile.
        name: ProfileName,
        /// Where the name came from, for the message.
        origin: &'static str,
    },
    /// Several profiles handle the remote, and their home checks couldn't
    /// tell them apart.
    #[error(
        "profiles {} all handle this command's remotes and none is verifiably home; pick one with `gitaway use <profile>` in a repository, or `--profile <profile>` before the command",
        .0.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ")
    )]
    Ambiguous(Vec<ProfileName>),
}

/// Picks the profile for a command. `Ok(None)` means no rule applies, and the
/// command runs as plain git.
///
/// `is_home` runs a profile's home check. It's only called when several
/// profiles handle the remote.
pub fn resolve<'a>(
    inputs: Inputs<'_>,
    profiles: &'a BTreeMap<ProfileName, Profile>,
    mut is_home: impl FnMut(&ProfileName, &Profile) -> bool,
) -> Result<Option<Resolved<'a>>, ResolveError> {
    let named = [
        (inputs.flag, Source::Flag, "--profile"),
        (inputs.env, Source::Env, "GITAWAY_PROFILE"),
        (
            inputs.git_config,
            Source::GitConfig,
            "git config gitaway.profile",
        ),
    ];
    for (name, source, label) in named {
        if let Some(name) = name {
            return lookup(profiles, name, source, label).map(Some);
        }
    }

    let candidates: Vec<_> = profiles
        .iter()
        .filter(|(_, profile)| inputs.remotes.iter().any(|r| profile.hosts.handles(r)))
        .collect();
    match candidates.as_slice() {
        [] => {}
        [(name, profile)] => {
            return Ok(Some(Resolved {
                name,
                profile,
                source: Source::HostMatch,
            }));
        }
        several => {
            let mut home = several
                .iter()
                .filter(|(name, profile)| is_home(name, profile));
            if let (Some((name, profile)), None) = (home.next(), home.next()) {
                return Ok(Some(Resolved {
                    name,
                    profile,
                    source: Source::VerifiedHome,
                }));
            }
            // The default is an explicit choice, not a guess, so it settles
            // a tie among the profiles that handle the remote.
            if let Some(default) = inputs.default
                && several.iter().any(|(name, _)| *name == default)
            {
                return lookup(profiles, default, Source::Default, "default_profile").map(Some);
            }
            return Err(ResolveError::Ambiguous(
                several.iter().map(|(name, _)| (*name).clone()).collect(),
            ));
        }
    }

    match inputs.default {
        Some(name) => lookup(profiles, name, Source::Default, "default_profile").map(Some),
        None => Ok(None),
    }
}

fn lookup<'a>(
    profiles: &'a BTreeMap<ProfileName, Profile>,
    name: &ProfileName,
    source: Source,
    label: &'static str,
) -> Result<Resolved<'a>, ResolveError> {
    let (name, profile) = profiles
        .get_key_value(name)
        .ok_or_else(|| ResolveError::NotFound {
            name: name.clone(),
            origin: label,
        })?;
    Ok(Resolved {
        name,
        profile,
        source,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::remote_url;

    fn profile(hosts: &[&str]) -> Profile {
        let hosts: String = hosts
            .iter()
            .map(|host| format!("\"{host}\" = \"10.0.0.1\"\n"))
            .collect();
        Profile::from_toml(&format!(
            r#"
            [transport.wireguard]
            endpoint = "vpn.example.net:51820"
            server_public_key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
            [hosts]
            {hosts}
            "#
        ))
        .unwrap()
    }

    fn name(s: &str) -> ProfileName {
        s.parse().unwrap()
    }

    /// home and cabin both handle 192.0.2.10; office handles 198.51.100.5.
    fn profiles() -> BTreeMap<ProfileName, Profile> {
        BTreeMap::from([
            (name("home"), profile(&["192.0.2.10"])),
            (name("cabin"), profile(&["192.0.2.10"])),
            (name("office"), profile(&["198.51.100.5"])),
        ])
    }

    fn never_home(_: &ProfileName, _: &Profile) -> bool {
        panic!("home check should not run")
    }

    fn resolved_name(
        inputs: Inputs<'_>,
        is_home: impl FnMut(&ProfileName, &Profile) -> bool,
    ) -> Result<Option<String>, ResolveError> {
        let profiles = profiles();
        resolve(inputs, &profiles, is_home).map(|r| r.map(|r| r.name.to_string()))
    }

    #[test]
    fn explicit_sources_win_in_order() {
        let (flag, env, git, default) = (name("office"), name("home"), name("cabin"), name("home"));
        let all = Inputs {
            flag: Some(&flag),
            env: Some(&env),
            git_config: Some(&git),
            remotes: &[],
            default: Some(&default),
        };
        assert_eq!(resolved_name(all, never_home), Ok(Some("office".into())));

        let no_flag = Inputs { flag: None, ..all };
        assert_eq!(resolved_name(no_flag, never_home), Ok(Some("home".into())));

        let only_git = Inputs {
            env: None,
            ..no_flag
        };
        assert_eq!(
            resolved_name(only_git, never_home),
            Ok(Some("cabin".into()))
        );
    }

    #[test]
    fn explicit_source_beats_host_match() {
        let remote = remote_url::parse("ssh://git@198.51.100.5/app.git").unwrap();
        let git = name("home");
        let inputs = Inputs {
            git_config: Some(&git),
            remotes: std::slice::from_ref(&remote),
            ..Inputs::default()
        };
        assert_eq!(resolved_name(inputs, never_home), Ok(Some("home".into())));
    }

    #[test]
    fn unique_host_match_wins_over_default() {
        let remote = remote_url::parse("ssh://git@198.51.100.5/app.git").unwrap();
        let default = name("home");
        let inputs = Inputs {
            remotes: std::slice::from_ref(&remote),
            default: Some(&default),
            ..Inputs::default()
        };
        let profiles = profiles();
        let resolved = resolve(inputs, &profiles, never_home).unwrap().unwrap();
        assert_eq!(resolved.name.as_str(), "office");
        assert_eq!(resolved.source, Source::HostMatch);
    }

    #[test]
    fn several_matches_use_the_one_verified_home() {
        let remote = remote_url::parse("git@192.0.2.10:app.git").unwrap();
        let inputs = Inputs {
            remotes: std::slice::from_ref(&remote),
            ..Inputs::default()
        };
        let profiles = profiles();
        let resolved = resolve(inputs, &profiles, |name, _| name.as_str() == "cabin")
            .unwrap()
            .unwrap();
        assert_eq!(resolved.name.as_str(), "cabin");
        assert_eq!(resolved.source, Source::VerifiedHome);
    }

    #[test]
    fn several_matches_without_one_verified_home_is_an_error() {
        let remote = remote_url::parse("git@192.0.2.10:app.git").unwrap();
        let default = name("office");
        let inputs = Inputs {
            remotes: std::slice::from_ref(&remote),
            default: Some(&default),
            ..Inputs::default()
        };
        let expected = Err(ResolveError::Ambiguous(vec![name("cabin"), name("home")]));
        assert_eq!(resolved_name(inputs, |_, _| false), expected, "none home");
        assert_eq!(resolved_name(inputs, |_, _| true), expected, "both home");
    }

    /// Two profiles for the same server (say, one set up for ssh and one for
    /// https): if the home checks can't tell them apart, the default is used
    /// when it's one of them. A verified home still wins over the default.
    #[test]
    fn several_matches_fall_back_to_the_default_when_it_is_one_of_them() {
        let remote = remote_url::parse("git@192.0.2.10:app.git").unwrap();
        let default = name("home");
        let inputs = Inputs {
            remotes: std::slice::from_ref(&remote),
            default: Some(&default),
            ..Inputs::default()
        };
        let profiles = profiles();
        for is_home in [
            |_: &ProfileName, _: &Profile| false,
            |_: &ProfileName, _: &Profile| true,
        ] {
            let resolved = resolve(inputs, &profiles, is_home).unwrap().unwrap();
            assert_eq!(resolved.name.as_str(), "home");
            assert_eq!(resolved.source, Source::Default);
        }
        let resolved = resolve(inputs, &profiles, |name, _| name.as_str() == "cabin")
            .unwrap()
            .unwrap();
        assert_eq!(
            resolved.name.as_str(),
            "cabin",
            "a verified home beats the default"
        );
    }

    /// A push to GitHub and to home: the home URL picks the profile, even
    /// though it isn't first.
    #[test]
    fn any_of_the_commands_urls_can_match_a_profile() {
        let remotes = [
            remote_url::parse("git@github.com:alice/app.git").unwrap(),
            remote_url::parse("ssh://git@198.51.100.5/app.git").unwrap(),
        ];
        let inputs = Inputs {
            remotes: &remotes,
            ..Inputs::default()
        };
        assert_eq!(resolved_name(inputs, never_home), Ok(Some("office".into())));
    }

    #[test]
    fn unmatched_remote_falls_back_to_default() {
        let remote = remote_url::parse("git@github.com:alice/app.git").unwrap();
        let default = name("office");
        let inputs = Inputs {
            remotes: std::slice::from_ref(&remote),
            default: Some(&default),
            ..Inputs::default()
        };
        assert_eq!(resolved_name(inputs, never_home), Ok(Some("office".into())));
    }

    #[test]
    fn nothing_applies_means_plain_git() {
        let remote = remote_url::parse("git@github.com:alice/app.git").unwrap();
        let inputs = Inputs {
            remotes: std::slice::from_ref(&remote),
            ..Inputs::default()
        };
        assert_eq!(resolved_name(inputs, never_home), Ok(None));
        assert_eq!(resolved_name(Inputs::default(), never_home), Ok(None));
    }

    #[test]
    fn named_profile_that_does_not_exist_is_an_error() {
        let missing = name("missing");
        for inputs in [
            Inputs {
                flag: Some(&missing),
                ..Inputs::default()
            },
            Inputs {
                env: Some(&missing),
                ..Inputs::default()
            },
            Inputs {
                git_config: Some(&missing),
                ..Inputs::default()
            },
            Inputs {
                default: Some(&missing),
                ..Inputs::default()
            },
        ] {
            assert!(matches!(
                resolved_name(inputs, never_home),
                Err(ResolveError::NotFound { .. })
            ));
        }
    }
}