gitpoulpi-core 1.1.0

GitPoulpi domain model, GitBackend and trait. No I/O-framework dependencies.
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! A repository's authentication profile (ADR-0010): which identity its
//! network git processes use, chosen per repository and stored in
//! GitPoulpi's private directory, never in the repository or in git's config.
//! These are the wire and file types; the storage is `gitpoulpi-session`'s
//! `repo_auth`, the resolution into a [`crate::domain::NetworkAuth`] is the
//! daemon's.

use serde::{Deserialize, Serialize};

use super::RemoteTransport;

/// How HTTPS remotes authenticate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum HttpsAuth {
    /// git's own helpers (the machine's identity), with two optional extras.
    System {
        /// `credential.username`: lets a credential manager pick one of
        /// several stored accounts for the host.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        username: Option<String>,
        /// Drop the credential helpers this repository sets itself (its
        /// `.git/config`, files that includes, a worktree config) and keep
        /// the system and global ones.
        #[serde(default, skip_serializing_if = "is_false")]
        ignore_repo_helpers: bool,
    },
    /// A GitPoulpi integration account's token.
    Integration {
        integration: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        username: Option<String>,
    },
    /// One credential helper command, run by git. Stored only when confirmed.
    Helper {
        helper: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        username: Option<String>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        hosts: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        confirmed_sha256: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        script_sha256: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        confirmed_at: Option<i64>,
    },
    /// A command that prints a token, run by the daemon. Stored only when
    /// confirmed.
    TokenCommand {
        argv: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        username: Option<String>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        hosts: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_minutes: Option<u32>,
        /// Also the token of this repository's hosting API calls (issues,
        /// pull requests), instead of the personal token. Pairs with a
        /// GitHub App installation token.
        #[serde(default, skip_serializing_if = "is_false")]
        use_for_hosting: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        confirmed_sha256: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        script_sha256: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        confirmed_at: Option<i64>,
    },
}

/// How SSH remotes authenticate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum SshAuth {
    /// ssh's own configuration, the agent and the global key.
    System,
    /// A key file, offered with `IdentitiesOnly`.
    KeyFile {
        key: String,
        /// `UserKnownHostsFile`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        known_hosts: Option<String>,
        /// `StrictHostKeyChecking=yes`.
        #[serde(default, skip_serializing_if = "is_false")]
        strict_host_key: bool,
    },
    /// The key of a GitPoulpi integration profile (`IntegrationSsh`),
    /// resolved live at each transfer.
    IntegrationKey {
        integration: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        known_hosts: Option<String>,
        #[serde(default, skip_serializing_if = "is_false")]
        strict_host_key: bool,
    },
}

fn is_false(b: &bool) -> bool {
    !*b
}

/// What a repository authenticates with. `None` for a protocol means "the
/// default" (the machine's own identity, as without a profile).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepoAuthProfile {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub https: Option<HttpsAuth>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssh: Option<SshAuth>,
}

impl RepoAuthProfile {
    /// Whether this profile changes nothing against having none: no source,
    /// or only default ones.
    pub fn is_default(&self) -> bool {
        let https_default = match &self.https {
            None => true,
            Some(HttpsAuth::System {
                username,
                ignore_repo_helpers,
            }) => username.as_deref().is_none_or(str::is_empty) && !ignore_repo_helpers,
            Some(_) => false,
        };
        https_default && matches!(self.ssh, None | Some(SshAuth::System))
    }

    /// A short label for the push indicator (`None` when everything is
    /// default). Never contains a secret: an account id, a key's file name.
    pub fn summary(&self) -> Option<String> {
        if self.is_default() {
            return None;
        }
        let mut parts = Vec::new();
        match &self.https {
            None => {}
            Some(HttpsAuth::System {
                username,
                ignore_repo_helpers,
            }) => {
                let user = username.as_deref().filter(|u| !u.is_empty());
                match (user, ignore_repo_helpers) {
                    (Some(u), true) => parts.push(format!("HTTPS: {u}, repo helpers ignored")),
                    (Some(u), false) => parts.push(format!("HTTPS: {u}")),
                    (None, true) => parts.push("HTTPS: repo helpers ignored".to_string()),
                    (None, false) => {}
                }
            }
            Some(HttpsAuth::Integration { integration, .. }) => {
                parts.push(format!("HTTPS: {integration}"))
            }
            Some(HttpsAuth::Helper { .. }) => parts.push("HTTPS: credential helper".to_string()),
            Some(HttpsAuth::TokenCommand { .. }) => parts.push("HTTPS: token command".to_string()),
        }
        match &self.ssh {
            None | Some(SshAuth::System) => {}
            Some(SshAuth::KeyFile { key, .. }) => {
                parts.push(format!("SSH key: {}", file_name_of(key)))
            }
            Some(SshAuth::IntegrationKey { integration, .. }) => {
                parts.push(format!("SSH key of {integration}"))
            }
        }
        Some(parts.join(", "))
    }
}

/// The prompt of the `NeedsConfirmation` a credential helper or token command
/// gets when it is sent without a person's confirmation. A frontend that
/// recognizes it words it in its own language and points at the page where the
/// person confirms.
pub const COMMAND_NEEDS_PERSON: &str =
    "a credential helper or token command is stored only when a person confirms it: \
     ask the person to set it in GitPoulpi";

/// How the HTTPS identity of a profile is reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IdentityVia {
    /// The token of a GitPoulpi account; the name is the account id.
    Token,
    /// Only a git username on the system helpers; the name is the user.
    Username,
    /// This repository's own credential helper command.
    CredentialHelper,
    /// This repository's token command.
    TokenCommand,
    /// The system helpers, with the repository's own ones ignored.
    HelpersIgnored,
}

/// Who a repository's HTTPS remotes sign in as.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HttpsIdentity {
    pub via: IdentityVia,
    /// An account id or a user name; empty when `via` has none.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub name: String,
}

/// Who a repository's SSH remotes sign in as.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SshIdentity {
    /// A key file's name, or the account id for an account's key.
    pub name: String,
    /// `name` is an account id (the key of that integration).
    #[serde(default, skip_serializing_if = "is_false")]
    pub of_account: bool,
}

/// What the status payload says about a repository whose profile is not all
/// default (the push line and the Activity Log entries of fetch, pull and
/// push). Never a secret. The wording is the UI's.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveIdentity {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub https: Option<HttpsIdentity>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssh: Option<SshIdentity>,
    /// An integration account is the source of the HTTPS or SSH identity.
    #[serde(default, skip_serializing_if = "is_false")]
    pub integration: bool,
}

impl RepoAuthProfile {
    /// The identity this profile gives, `None` when everything is default.
    pub fn identity(&self) -> Option<ActiveIdentity> {
        if self.is_default() {
            return None;
        }
        let mut id = ActiveIdentity::default();
        id.https = match &self.https {
            None => None,
            Some(HttpsAuth::System {
                username,
                ignore_repo_helpers,
            }) => match (
                username.as_deref().filter(|u| !u.is_empty()),
                ignore_repo_helpers,
            ) {
                (Some(u), _) => Some(HttpsIdentity {
                    via: IdentityVia::Username,
                    name: u.to_string(),
                }),
                (None, true) => Some(HttpsIdentity {
                    via: IdentityVia::HelpersIgnored,
                    name: String::new(),
                }),
                (None, false) => None,
            },
            Some(HttpsAuth::Integration { integration, .. }) => {
                id.integration = true;
                Some(HttpsIdentity {
                    via: IdentityVia::Token,
                    name: integration.clone(),
                })
            }
            Some(HttpsAuth::Helper { .. }) => Some(HttpsIdentity {
                via: IdentityVia::CredentialHelper,
                name: String::new(),
            }),
            Some(HttpsAuth::TokenCommand { .. }) => Some(HttpsIdentity {
                via: IdentityVia::TokenCommand,
                name: String::new(),
            }),
        };
        id.ssh = match &self.ssh {
            None | Some(SshAuth::System) => None,
            Some(SshAuth::KeyFile { key, .. }) => Some(SshIdentity {
                name: file_name_of(key).to_string(),
                of_account: false,
            }),
            Some(SshAuth::IntegrationKey { integration, .. }) => {
                id.integration = true;
                Some(SshIdentity {
                    name: integration.clone(),
                    of_account: true,
                })
            }
        };
        Some(id)
    }
}

/// The SHA-256 (lower-case hex) of a command-running source's command: the
/// helper string, or the arguments of a token command joined by NUL. What a
/// person confirms is shown with this hash.
pub fn command_sha256(parts: &[&str]) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(parts.join("\0").as_bytes());
    digest.iter().map(|b| format!("{b:02x}")).collect()
}

impl HttpsAuth {
    /// The hash of the command of a helper or token-command source, `None`
    /// for the others.
    pub fn command_sha256(&self) -> Option<String> {
        match self {
            HttpsAuth::Helper { helper, .. } => Some(command_sha256(&[helper])),
            HttpsAuth::TokenCommand { argv, .. } => {
                let parts: Vec<&str> = argv.iter().map(String::as_str).collect();
                Some(command_sha256(&parts))
            }
            _ => None,
        }
    }
}

/// The last component of a path written with either separator.
fn file_name_of(path: &str) -> &str {
    path.rsplit(['/', '\\'])
        .find(|s| !s.is_empty())
        .unwrap_or(path)
}

/// `RepoAuthSet` arguments.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepoAuthSetArgs {
    pub profile: RepoAuthProfile,
    /// The requester confirms a command-running source (helper, token
    /// command). Only a person may: the CLI sends it only from a session that
    /// may trust, the TUI after its dialog, MCP never. Without it a command
    /// is stored only when it is the one already confirmed.
    #[serde(default)]
    pub confirm: bool,
}

/// `RepoAuthTest` arguments: one remote, or every remote of the repository.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepoAuthTestArgs {
    #[serde(default)]
    pub remote: Option<String>,
    #[serde(default)]
    pub push: bool,
}

/// Which identity one remote will authenticate with.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemoteIdentity {
    pub remote: String,
    /// The fetch URL without userinfo.
    pub url: String,
    pub transport: RemoteTransport,
    /// Plain words, never a secret: "system git", "system git (user alice)",
    /// "ssh key work_ed25519".
    pub identity: String,
}

/// A repository setting that the profile overrides or that competes with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthOverride {
    /// `core.sshCommand` or `credential.helper`.
    pub key: String,
    pub value: String,
    /// `local`, `worktree`, `global`, `system`...
    pub scope: String,
    /// The file it comes from.
    pub origin: String,
    /// Whether the profile ignores it (it does not apply to this
    /// repository's transfers).
    pub overridden: bool,
}

/// `RepoAuthGet`'s answer. Carries no secret: a command-running source's
/// command is blanked.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepoAuthView {
    /// Whether the repository has a stored profile at all.
    pub configured: bool,
    pub profile: RepoAuthProfile,
    pub summary: Option<String>,
    /// The common git directory recorded when the profile was saved.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_common_dir: Option<String>,
    pub remotes: Vec<RemoteIdentity>,
    pub overrides: Vec<AuthOverride>,
    pub warnings: Vec<String>,
    /// Why the profile cannot be used for a transfer right now, if so (the
    /// transfer would be refused with `RepoAuthUnavailable`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unavailable: Option<String>,
}

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

    #[test]
    fn the_identity_names_the_account_or_the_key_and_is_absent_by_default() {
        assert_eq!(RepoAuthProfile::default().identity(), None);
        let p = RepoAuthProfile {
            https: Some(HttpsAuth::Integration {
                integration: "github-corp".into(),
                username: None,
            }),
            ssh: Some(SshAuth::KeyFile {
                key: "C:\\Users\\me\\.ssh\\work_ed25519".into(),
                known_hosts: None,
                strict_host_key: false,
            }),
        };
        let id = p.identity().expect("not default");
        assert_eq!(id.https.unwrap().name, "github-corp");
        assert_eq!(id.ssh.unwrap().name, "work_ed25519");
        assert!(id.integration);
    }

    #[test]
    fn a_profile_with_only_defaults_has_no_summary() {
        assert_eq!(RepoAuthProfile::default().summary(), None);
        let p = RepoAuthProfile {
            https: Some(HttpsAuth::System {
                username: Some(String::new()),
                ignore_repo_helpers: false,
            }),
            ssh: Some(SshAuth::System),
        };
        assert!(p.is_default());
        assert_eq!(p.summary(), None);
    }

    #[test]
    fn the_summary_names_the_choice_without_a_path_or_secret() {
        let p = RepoAuthProfile {
            https: Some(HttpsAuth::System {
                username: None,
                ignore_repo_helpers: true,
            }),
            ssh: Some(SshAuth::KeyFile {
                key: r"C:\Users\me\.ssh\work_ed25519".into(),
                known_hosts: None,
                strict_host_key: false,
            }),
        };
        assert_eq!(
            p.summary().as_deref(),
            Some("HTTPS: repo helpers ignored, SSH key: work_ed25519")
        );
    }
}