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
use nkeys::error::Error as NKeysError;
use snafu::{ResultExt, Snafu};
use vector_lib::configurable::configurable_component;
use vector_lib::sensitive_string::SensitiveString;

use crate::tls::TlsEnableableConfig;

#[derive(Debug, Snafu)]
pub enum NatsConfigError {
    #[snafu(display("NATS Auth Config Error: {}", source))]
    AuthConfigError { source: NKeysError },
    #[snafu(display("NATS TLS Config Error: missing key"))]
    TlsMissingKey,
    #[snafu(display("NATS TLS Config Error: missing cert"))]
    TlsMissingCert,
    #[snafu(display("NATS Credentials file error"))]
    CredentialsFileError { source: std::io::Error },
}

/// Configuration of the authentication strategy when interacting with NATS.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(rename_all = "snake_case", tag = "strategy")]
#[configurable(metadata(
    docs::enum_tag_description = "The strategy used to authenticate with the NATS server.

More information on NATS authentication, and the various authentication strategies, can be found in the
NATS [documentation][nats_auth_docs]. For TLS client certificate authentication specifically, see the
`tls` settings.

[nats_auth_docs]: https://docs.nats.io/running-a-nats-service/configuration/securing_nats/auth_intro"
))]
pub(crate) enum NatsAuthConfig {
    /// Username/password authentication.
    UserPassword {
        #[configurable(derived)]
        user_password: NatsAuthUserPassword,
    },

    /// Token authentication.
    Token {
        #[configurable(derived)]
        token: NatsAuthToken,
    },

    /// Credentials file authentication. (JWT-based)
    CredentialsFile {
        #[configurable(derived)]
        credentials_file: NatsAuthCredentialsFile,
    },

    /// NKey authentication.
    Nkey {
        #[configurable(derived)]
        nkey: NatsAuthNKey,
    },
}

impl std::fmt::Display for NatsAuthConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use NatsAuthConfig::*;
        let word = match self {
            UserPassword { .. } => "user_password",
            Token { .. } => "token",
            CredentialsFile { .. } => "credentials_file",
            Nkey { .. } => "nkey",
        };
        write!(f, "{}", word)
    }
}

/// Username and password configuration.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct NatsAuthUserPassword {
    /// Username.
    pub(crate) user: String,

    /// Password.
    pub(crate) password: SensitiveString,
}

/// Token configuration.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct NatsAuthToken {
    /// Token.
    pub(crate) value: SensitiveString,
}

/// Credentials file configuration.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct NatsAuthCredentialsFile {
    /// Path to credentials file.
    #[configurable(metadata(docs::examples = "/etc/nats/nats.creds"))]
    pub(crate) path: String,
}

/// NKeys configuration.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct NatsAuthNKey {
    /// User.
    ///
    /// Conceptually, this is equivalent to a public key.
    pub(crate) nkey: String,

    /// Seed.
    ///
    /// Conceptually, this is equivalent to a private key.
    pub(crate) seed: String,
}

impl NatsAuthConfig {
    pub(crate) fn to_nats_options(&self) -> Result<async_nats::ConnectOptions, NatsConfigError> {
        match self {
            NatsAuthConfig::UserPassword { user_password } => {
                Ok(async_nats::ConnectOptions::with_user_and_password(
                    user_password.user.clone(),
                    user_password.password.inner().to_string(),
                ))
            }
            NatsAuthConfig::CredentialsFile { credentials_file } => {
                async_nats::ConnectOptions::with_credentials(
                    &std::fs::read_to_string(credentials_file.path.clone())
                        .context(CredentialsFileSnafu)?,
                )
                .context(CredentialsFileSnafu)
            }
            NatsAuthConfig::Nkey { nkey } => {
                Ok(async_nats::ConnectOptions::with_nkey(nkey.seed.clone()))
            }
            NatsAuthConfig::Token { token } => Ok(async_nats::ConnectOptions::with_token(
                token.value.inner().to_string(),
            )),
        }
    }
}

pub(crate) fn from_tls_auth_config(
    connection_name: &str,
    auth_config: &Option<NatsAuthConfig>,
    tls_config: &Option<TlsEnableableConfig>,
) -> Result<async_nats::ConnectOptions, NatsConfigError> {
    let nats_options = match &auth_config {
        None => async_nats::ConnectOptions::new(),
        Some(auth) => auth.to_nats_options()?,
    };

    let nats_options = nats_options.name(connection_name);

    match tls_config {
        None => Ok(nats_options),
        Some(tls_config) => {
            let tls_enabled = tls_config.enabled.unwrap_or(false);
            let nats_options = nats_options.require_tls(tls_enabled);
            if !tls_enabled {
                return Ok(nats_options);
            }

            let nats_options = match &tls_config.options.ca_file {
                None => nats_options,
                Some(ca_file) => nats_options.add_root_certificates(ca_file.clone()),
            };

            let nats_options = match (&tls_config.options.crt_file, &tls_config.options.key_file) {
                (None, None) => nats_options,
                (Some(crt_file), Some(key_file)) => {
                    nats_options.add_client_certificate(crt_file.clone(), key_file.clone())
                }
                (Some(_crt_file), None) => return Err(NatsConfigError::TlsMissingKey),
                (None, Some(_key_file)) => return Err(NatsConfigError::TlsMissingCert),
            };
            Ok(nats_options)
        }
    }
}

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

    fn parse_auth(s: &str) -> Result<async_nats::ConnectOptions, crate::Error> {
        toml::from_str(s)
            .map_err(Into::into)
            .and_then(|config: NatsAuthConfig| config.to_nats_options().map_err(Into::into))
    }

    #[test]
    fn auth_user_password_ok() {
        parse_auth(
            r#"
            strategy = "user_password"
            user_password.user = "username"
            user_password.password = "password"
        "#,
        )
        .unwrap();
    }

    #[test]
    fn auth_user_password_missing_user() {
        parse_auth(
            r#"
            strategy = "user_password"
            user_password.password = "password"
        "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_user_password_missing_password() {
        parse_auth(
            r#"
            strategy = "user_password"
            user_password.user = "username"
        "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_user_password_missing_all() {
        parse_auth(
            r#"
            strategy = "user_password"
            token.value = "foobar"
            "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_token_ok() {
        parse_auth(
            r#"
            strategy = "token"
            token.value = "token"
        "#,
        )
        .unwrap();
    }

    #[test]
    fn auth_token_missing() {
        parse_auth(
            r#"
            strategy = "token"
            user_password.user = "foobar"
            "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_credentials_file_ok() {
        parse_auth(
            r#"
            strategy = "credentials_file"
            credentials_file.path = "tests/data/nats/nats.creds"
        "#,
        )
        .unwrap();
    }

    #[test]
    fn auth_credentials_file_missing() {
        parse_auth(
            r#"
            strategy = "credentials_file"
            token.value = "foobar"
            "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_nkey_ok() {
        parse_auth(
            r#"
            strategy = "nkey"
            nkey.nkey = "UC435ZYS52HF72E2VMQF4GO6CUJOCHDUUPEBU7XDXW5AQLIC6JZ46PO5"
            nkey.seed = "SUAAEZYNLTEA2MDTG7L5X7QODZXYHPOI2LT2KH5I4GD6YVP24SE766EGPA"
        "#,
        )
        .unwrap();
    }

    #[test]
    fn auth_nkey_missing_nkey() {
        parse_auth(
            r#"
            strategy = "nkey"
            nkey.seed = "SUAAEZYNLTEA2MDTG7L5X7QODZXYHPOI2LT2KH5I4GD6YVP24SE766EGPA"
        "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_nkey_missing_seed() {
        parse_auth(
            r#"
            strategy = "nkey"
            nkey.nkey = "UC435ZYS52HF72E2VMQF4GO6CUJOCHDUUPEBU7XDXW5AQLIC6JZ46PO5"
        "#,
        )
        .unwrap_err();
    }

    #[test]
    fn auth_nkey_missing_both() {
        parse_auth(
            r#"
            strategy = "nkey"
            user_password.user = "foobar"
            "#,
        )
        .unwrap_err();
    }
}