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
use core::fmt;
use std::{convert::TryFrom, path::PathBuf};
use yup_oauth2::ServiceAccountKey;
#[derive(PartialEq, Eq, Clone)]
pub enum AuthMethod {
None,
ServiceAccountKey(Vec<u8>),
WorkloadIdentity(Option<String>),
}
impl From<Vec<u8>> for AuthMethod {
fn from(service_account_key: Vec<u8>) -> Self {
if service_account_key.is_empty() {
return AuthMethod::WorkloadIdentity(None);
}
AuthMethod::ServiceAccountKey(service_account_key)
}
}
impl TryFrom<PathBuf> for AuthMethod {
type Error = std::io::Error;
fn try_from(service_account_key_file: PathBuf) -> Result<Self, Self::Error> {
match std::fs::read(service_account_key_file) {
Err(e) => Err(e),
Ok(v) => Ok(v.into()),
}
}
}
impl TryFrom<Option<PathBuf>> for AuthMethod {
type Error = std::io::Error;
fn try_from(service_account_key_file: Option<PathBuf>) -> Result<Self, Self::Error> {
match service_account_key_file {
Some(p) => AuthMethod::try_from(p),
None => Ok(AuthMethod::WorkloadIdentity(None)),
}
}
}
impl AuthMethod {
pub(super) fn to_service_account_key(&self) -> std::io::Result<ServiceAccountKey> {
match self {
AuthMethod::WorkloadIdentity(_) | AuthMethod::None => {
Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "service account key not chosen as option"))
}
AuthMethod::ServiceAccountKey(key) => {
serde_json::from_slice(key).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bad service account key: {}", e)))
}
}
}
}
impl fmt::Display for AuthMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AuthMethod::WorkloadIdentity(None) => write!(f, "Workload Identity"),
AuthMethod::WorkloadIdentity(Some(s)) => write!(f, "Workload Identity with service account {}", s),
AuthMethod::ServiceAccountKey(_) => write!(f, "Service Account Key"),
AuthMethod::None => write!(f, "None"),
}
}
}
impl fmt::Debug for AuthMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AuthMethod::WorkloadIdentity(None) => write!(f, "WorkloadIdentity(None)"),
AuthMethod::WorkloadIdentity(Some(s)) => write!(f, "WorkloadIdentity(Some({}))", s),
AuthMethod::ServiceAccountKey(_) => write!(f, "ServiceAccountKey(*******)"),
AuthMethod::None => write!(f, "None"),
}
}
}