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
use super::*;

// // SecretTypeDockerConfigJSON contains a dockercfg file that follows the same format rules as ~/.docker/config.json
// //
// // Required fields:
// // - Secret.Data[".dockerconfigjson"] - a serialized ~/.docker/config.json file
// SecretTypeDockerConfigJSON SecretType = "kubernetes.io/dockerconfigjson"

// // DockerConfigJSONKey is the key of the required data for SecretTypeDockerConfigJson secrets
// DockerConfigJSONKey = ".dockerconfigjson"

const DOCKER_CONFIG_JSON_TYPE: &str = "kubernetes.io/dockerconfigjson";
const DOCKER_CONFIG_JSON_KEY: &str = ".dockerconfigjson";

const BASIC_AUTH_TYPE: &str = "kubernetes.io/basic-auth";
const BASIC_AUTH_USERNAME: &str = "username";
const BASIC_AUTH_PASSWORD: &str = "password";

const SSH_AUTH_TYPE: &str = "kubernetes.io/ssh-auth";
const SSH_AUTH_PRIVATE_KEY: &str = "ssh-privatekey";

pub trait SecretExt: super::ResourceBuilder + Sized {
    fn new(name: impl ToString) -> Self;

    fn immutable(self, yes: bool) -> Self;

    fn r#type(self, r#type: impl ToString) -> Self;

    fn data(self, data: impl IntoIterator<Item = (impl ToString, ByteString)>) -> Self;

    fn string_data(self, data: impl IntoIterator<Item = (impl ToString, impl ToString)>) -> Self;

    /// Creates new image pull secret object
    ///
    fn image_pull_secret(
        name: impl ToString,
        registry: impl ToString,
        username: impl ToString,
        password: impl ToString,
    ) -> Self {
        let registry = registry.to_string();
        let username = username.to_string();
        let password = password.to_string();
        let auth = format!("{username}:{password}");
        let auth = base64::encode(auth);
        let config = format!(
            r#"{{"auths":{{"{registry}":{{"username":"{username}","password":"{password}","auth":"{auth}"}}}}}}"#
        );
        let data = [(DOCKER_CONFIG_JSON_KEY, config)];
        Self::new(name)
            .r#type(DOCKER_CONFIG_JSON_TYPE)
            .string_data(data)
    }

    /// Creates new basic authentication secret object
    ///
    fn basic_auth(name: impl ToString, username: impl ToString, password: impl ToString) -> Self {
        let data = [
            (BASIC_AUTH_USERNAME, username.to_string()),
            (BASIC_AUTH_PASSWORD, password.to_string()),
        ];
        Self::new(name).r#type(BASIC_AUTH_TYPE).string_data(data)
    }

    fn ssh_auth(name: impl ToString, private_key: impl ToString) -> Self {
        let data = [(SSH_AUTH_PRIVATE_KEY, private_key)];
        Self::new(name).r#type(SSH_AUTH_TYPE).string_data(data)
    }
}

pub trait SecretExt2: SecretExt {
    /// Creates new image pull secret object when you already have the .docker/config.json
    /// content extracted from some other source (i.e. secret)
    ///
    fn image_pull_secret(name: impl ToString, data: impl ToString) -> Self {
        let data = [(DOCKER_CONFIG_JSON_KEY, data)];
        Self::new(name)
            .r#type(DOCKER_CONFIG_JSON_TYPE)
            .string_data(data)
    }
}

impl SecretExt for corev1::Secret {
    fn new(name: impl ToString) -> Self {
        let metadata = metadata(name);
        Self {
            metadata,
            // immutable: todo!(),
            // data: todo!(),
            // string_data: todo!(),
            // type_: todo!(),
            ..default()
        }
    }

    fn immutable(self, yes: bool) -> Self {
        let immutable = Some(yes);
        Self { immutable, ..self }
    }

    fn r#type(self, r#type: impl ToString) -> Self {
        let type_ = Some(r#type.to_string());
        Self { type_, ..self }
    }

    fn data(self, data: impl IntoIterator<Item = (impl ToString, ByteString)>) -> Self {
        let data = data
            .into_iter()
            .map(|(key, value)| (key.to_string(), value))
            .collect();
        Self {
            data: Some(data),
            ..self
        }
    }

    fn string_data(self, data: impl IntoIterator<Item = (impl ToString, impl ToString)>) -> Self {
        let data = data
            .into_iter()
            .map(|(key, value)| (key.to_string(), value.to_string()))
            .collect();
        Self {
            string_data: Some(data),
            ..self
        }
    }
}

impl SecretExt2 for corev1::Secret {}

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

    use serde_json as json;

    #[test]
    fn image_pull_secret() {
        let secret = <corev1::Secret as SecretExt>::image_pull_secret(
            "name", "registry", "username", "password",
        );
        // println!("{secret:#?}");
        let string_data = secret.string_data.unwrap_or_default();
        assert_eq!(string_data.len(), 1);
        let config: json::Value = json::from_str(&string_data[DOCKER_CONFIG_JSON_KEY]).unwrap();
        // println!("{config:#?}");
        assert!(config.is_object());
    }

    #[test]
    fn ssh_auth() {
        let secret = corev1::Secret::ssh_auth(
            "name",
            "KGpwKaqlGas+LaAqdwdfAAAEEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIClTFvhvwp1UH25b",
        );
        let string_data = secret.string_data.unwrap_or_default();
        assert_eq!(string_data.len(), 1);
        assert_eq!(string_data[SSH_AUTH_PRIVATE_KEY].len(), 70);
    }
}