use serde::{Deserialize, Serialize};
use super::RemoteTransport;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum HttpsAuth {
System {
#[serde(default, skip_serializing_if = "Option::is_none")]
username: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
ignore_repo_helpers: bool,
},
Integration {
integration: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
username: Option<String>,
},
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>,
},
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>,
#[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>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum SshAuth {
System,
KeyFile {
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
known_hosts: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
strict_host_key: bool,
},
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
}
#[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 {
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))
}
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(", "))
}
}
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";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IdentityVia {
Token,
Username,
CredentialHelper,
TokenCommand,
HelpersIgnored,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HttpsIdentity {
pub via: IdentityVia,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SshIdentity {
pub name: String,
#[serde(default, skip_serializing_if = "is_false")]
pub of_account: bool,
}
#[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>,
#[serde(default, skip_serializing_if = "is_false")]
pub integration: bool,
}
impl RepoAuthProfile {
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)
}
}
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 {
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,
}
}
}
fn file_name_of(path: &str) -> &str {
path.rsplit(['/', '\\'])
.find(|s| !s.is_empty())
.unwrap_or(path)
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepoAuthSetArgs {
pub profile: RepoAuthProfile,
#[serde(default)]
pub confirm: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepoAuthTestArgs {
#[serde(default)]
pub remote: Option<String>,
#[serde(default)]
pub push: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemoteIdentity {
pub remote: String,
pub url: String,
pub transport: RemoteTransport,
pub identity: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthOverride {
pub key: String,
pub value: String,
pub scope: String,
pub origin: String,
pub overridden: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HttpsOrigin {
#[default]
System,
Repository,
IntegrationDefault,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepoAuthView {
pub configured: bool,
pub profile: RepoAuthProfile,
pub summary: Option<String>,
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unavailable: Option<String>,
#[serde(default)]
pub https_source: HttpsOrigin,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub integration_default: Option<String>,
#[serde(default)]
pub https_source_text: 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")
);
}
}