oa_gateway/
tls.rs

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
//! Reads the TLS material named in the config before any adapter listens.
//!
//! Doing this here, once, keeps a missing file or a mismatched cert/key pair
//! from being discovered only once a client tries to connect.

use oa_gateway_adapter::tls::{client_tls, server_tls, ClientTls, ServerTls};

use crate::addr::host_part;
use crate::config::Config;

/// TLS material the host built before any adapter touched a socket.
#[derive(Debug)]
pub(crate) struct HostTls {
    pub(crate) owp: Option<ServerTls>,
    pub(crate) stomp: Option<ClientTls>,
}

/// Reads the certificates and keys named in `config`, if any.
///
/// A disabled adapter's TLS settings are not read, matching how
/// [`crate::adapters::start`] only resolves addresses for enabled adapters.
///
/// # Errors
///
/// Returns an error if `owp.tls_cert`/`owp.tls_key` is set without its
/// pair, if `owp.tls_client_ca` is set without both of those, if
/// `stomp.tls_client_cert`/`stomp.tls_client_key` is set without
/// `stomp.tls = true`, if a cert/key/CA file cannot be read, if a
/// certificate does not parse or does not match its key, or if
/// `stomp.tls_server_name` (or the host part of `stomp.broker`, when that
/// is empty) is not a usable DNS name or IP address.
pub(crate) fn load(config: &Config) -> Result<HostTls, String> {
    let owp = if config.owp.enabled {
        let cert = non_empty_path(&config.owp.tls_cert);
        let key = non_empty_path(&config.owp.tls_key);
        let client_ca = non_empty_path(&config.owp.tls_client_ca);
        server_tls("owp.tls", cert, key, client_ca)?
    } else {
        None
    };
    let stomp = if config.stomp.enabled {
        if config.stomp.tls {
            let ca = non_empty_path(&config.stomp.tls_ca);
            let name = if config.stomp.tls_server_name.is_empty() {
                host_part(&config.stomp.broker)
            } else {
                &config.stomp.tls_server_name
            };
            let client_cert = non_empty_path(&config.stomp.tls_client_cert);
            let client_key = non_empty_path(&config.stomp.tls_client_key);
            Some(client_tls("stomp.tls", ca, name, client_cert, client_key)?)
        } else if !config.stomp.tls_client_cert.is_empty() {
            return Err(
                "stomp.tls_client_cert is set but stomp.tls is not. A client certificate \
                 needs stomp.tls = true to matter."
                    .into(),
            );
        } else if !config.stomp.tls_client_key.is_empty() {
            return Err(
                "stomp.tls_client_key is set but stomp.tls is not. A client certificate \
                 needs stomp.tls = true to matter."
                    .into(),
            );
        } else {
            None
        }
    } else {
        None
    };
    Ok(HostTls { owp, stomp })
}

fn non_empty_path(value: &str) -> Option<&std::path::Path> {
    if value.is_empty() {
        None
    } else {
        Some(std::path::Path::new(value))
    }
}

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

    #[test]
    fn no_tls_configured_leaves_owp_plaintext() {
        let config: Config = toml::from_str("[owp]\nenabled = true\n").unwrap();
        assert!(load(&config).unwrap().owp.is_none());
    }

    #[test]
    fn a_disabled_owp_adapter_is_not_checked_for_tls() {
        // enabled = false with only tls_cert set would otherwise be refused;
        // a disabled adapter's TLS settings should not even be read.
        let config: Config =
            toml::from_str("[owp]\nenabled = false\ntls_cert = \"definitely/not/here.pem\"\n")
                .unwrap();
        assert!(load(&config).unwrap().owp.is_none());
    }

    #[test]
    fn a_cert_without_a_key_is_refused_at_startup() {
        let config: Config =
            toml::from_str("[owp]\nenabled = true\ntls_cert = \"definitely/not/here.pem\"\n")
                .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("owp.tls_key"), "{err}");
    }

    #[test]
    fn an_unreadable_cert_path_names_the_file() {
        let config: Config = toml::from_str(
            "[owp]\nenabled = true\ntls_cert = \"definitely/not/here.pem\"\ntls_key = \"definitely/not/here-key.pem\"\n",
        )
        .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("definitely/not/here.pem"), "{err}");
    }

    #[test]
    fn a_matching_cert_and_key_are_loaded() {
        let rcgen::CertifiedKey { cert, key_pair } =
            rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();

        let dir = std::env::temp_dir().join("oa-gateway-tls-test");
        std::fs::create_dir_all(&dir).unwrap();
        let cert_path = dir.join("cert.pem");
        let key_path = dir.join("key.pem");
        std::fs::write(&cert_path, cert.pem()).unwrap();
        std::fs::write(&key_path, key_pair.serialize_pem()).unwrap();

        let config: Config = toml::from_str(&format!(
            "[owp]\nenabled = true\ntls_cert = {:?}\ntls_key = {:?}\n",
            cert_path.display().to_string(),
            key_path.display().to_string(),
        ))
        .unwrap();
        assert!(load(&config).unwrap().owp.is_some());

        std::fs::remove_file(&cert_path).ok();
        std::fs::remove_file(&key_path).ok();
    }

    #[test]
    fn a_client_ca_without_a_cert_or_key_is_refused_at_startup() {
        let config: Config =
            toml::from_str("[owp]\nenabled = true\ntls_client_ca = \"definitely/not/here.pem\"\n")
                .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("owp.tls_client_ca"), "{err}");
    }

    #[test]
    fn a_cert_key_and_client_ca_load_together() {
        let rcgen::CertifiedKey { cert, key_pair } =
            rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();

        let dir = std::env::temp_dir().join("oa-gateway-mtls-test");
        std::fs::create_dir_all(&dir).unwrap();
        let cert_path = dir.join("cert.pem");
        let key_path = dir.join("key.pem");
        let client_ca_path = dir.join("client-ca.pem");
        std::fs::write(&cert_path, cert.pem()).unwrap();
        std::fs::write(&key_path, key_pair.serialize_pem()).unwrap();
        // The server's own cert doubles as the "trusted CA" bundle here —
        // this test only checks that the wiring reaches server_tls, not
        // that a particular chain verifies.
        std::fs::write(&client_ca_path, cert.pem()).unwrap();

        let config: Config = toml::from_str(&format!(
            "[owp]\nenabled = true\ntls_cert = {:?}\ntls_key = {:?}\ntls_client_ca = {:?}\n",
            cert_path.display().to_string(),
            key_path.display().to_string(),
            client_ca_path.display().to_string(),
        ))
        .unwrap();
        assert!(load(&config).unwrap().owp.is_some());

        std::fs::remove_file(&cert_path).ok();
        std::fs::remove_file(&key_path).ok();
        std::fs::remove_file(&client_ca_path).ok();
    }

    #[test]
    fn no_stomp_tls_configured_leaves_it_plaintext() {
        let config: Config = toml::from_str("[stomp]\nenabled = true\n").unwrap();
        assert!(load(&config).unwrap().stomp.is_none());
    }

    #[test]
    fn a_disabled_stomp_adapter_is_not_checked_for_tls() {
        let config: Config = toml::from_str(
            "[stomp]\nenabled = false\ntls = true\ntls_ca = \"definitely/not/here.pem\"\n",
        )
        .unwrap();
        assert!(load(&config).unwrap().stomp.is_none());
    }

    #[test]
    fn stomp_tls_off_ignores_a_configured_ca() {
        // tls = false is the switch; a leftover tls_ca must not be checked.
        let config: Config = toml::from_str(
            "[stomp]\nenabled = true\ntls = false\ntls_ca = \"definitely/not/here.pem\"\n",
        )
        .unwrap();
        assert!(load(&config).unwrap().stomp.is_none());
    }

    #[test]
    fn an_unreadable_stomp_ca_path_names_the_file() {
        let config: Config = toml::from_str(
            "[stomp]\nenabled = true\ntls = true\ntls_ca = \"definitely/not/here.pem\"\n",
        )
        .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("stomp.tls_ca"), "{err}");
        assert!(err.contains("definitely/not/here.pem"), "{err}");
    }

    #[test]
    fn stomp_tls_server_name_defaults_to_the_broker_host_not_the_stomp_host_header() {
        // An unparseable broker host surfaces in the error, proving it is
        // what got used as the default server name — and `host = "/"`
        // (the STOMP protocol header, not a hostname) is set alongside it
        // to confirm that is not what was parsed instead.
        let config: Config = toml::from_str(
            "[stomp]\nenabled = true\ntls = true\nbroker = \"not a hostname!:61612\"\nhost = \"/\"\n",
        )
        .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("not a hostname!"), "{err}");
    }

    #[test]
    fn an_explicit_stomp_server_name_overrides_the_broker_host() {
        let config: Config = toml::from_str(
            "[stomp]\nenabled = true\ntls = true\nbroker = \"127.0.0.1:61612\"\ntls_server_name = \"not a hostname!\"\n",
        )
        .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("stomp.tls_server_name"), "{err}");
    }

    #[test]
    fn a_stomp_client_cert_without_tls_is_refused_at_startup() {
        let config: Config = toml::from_str(
            "[stomp]\nenabled = true\ntls = false\ntls_client_cert = \"definitely/not/here.pem\"\n",
        )
        .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("stomp.tls_client_cert"), "{err}");
        assert!(err.contains("stomp.tls"), "{err}");
    }

    #[test]
    fn a_stomp_client_key_without_tls_is_refused_at_startup() {
        let config: Config = toml::from_str(
            "[stomp]\nenabled = true\ntls = false\ntls_client_key = \"definitely/not/here.pem\"\n",
        )
        .unwrap();
        let err = load(&config).unwrap_err();
        assert!(err.contains("stomp.tls_client_key"), "{err}");
        assert!(err.contains("stomp.tls"), "{err}");
    }

    #[test]
    fn a_disabled_stomp_adapter_is_not_checked_for_a_client_cert() {
        let config: Config = toml::from_str(
            "[stomp]\nenabled = false\ntls_client_cert = \"definitely/not/here.pem\"\n",
        )
        .unwrap();
        assert!(load(&config).unwrap().stomp.is_none());
    }

    #[test]
    fn a_stomp_client_cert_and_key_load_with_tls_on() {
        let rcgen::CertifiedKey { cert, key_pair } =
            rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_string()]).unwrap();

        let dir = std::env::temp_dir().join("oa-gateway-stomp-mtls-test");
        std::fs::create_dir_all(&dir).unwrap();
        let cert_path = dir.join("client-cert.pem");
        let key_path = dir.join("client-key.pem");
        std::fs::write(&cert_path, cert.pem()).unwrap();
        std::fs::write(&key_path, key_pair.serialize_pem()).unwrap();

        let config: Config = toml::from_str(&format!(
            "[stomp]\nenabled = true\ntls = true\nbroker = \"127.0.0.1:61612\"\ntls_client_cert = {:?}\ntls_client_key = {:?}\n",
            cert_path.display().to_string(),
            key_path.display().to_string(),
        ))
        .unwrap();
        assert!(load(&config).unwrap().stomp.is_some());

        std::fs::remove_file(&cert_path).ok();
        std::fs::remove_file(&key_path).ok();
    }
}