mapepire 0.4.0

Async Rust client for Mapepire — Db2 for IBM i over secure WebSockets
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Daemon connection configuration.

use crate::password::Password;

/// TLS verification mode for the connection to the Mapepire daemon.
///
/// Mapepire is **always** TLS — there is no plaintext path. This enum only
/// chooses how the certificate is validated.
///
/// The variants exist at the type level in v0.1. Their runtime semantics
/// land with the transport layer in v0.2 — the active TLS backend is
/// selected at compile time via the `rustls-tls` (default) and
/// `native-tls` Cargo features.
#[derive(Debug, Clone, Default)]
pub enum TlsConfig {
    /// Verify the server certificate against system / `webpki` roots (default).
    ///
    /// In v0.2 this requires the `rustls-tls` or `native-tls` feature; v0.1
    /// only declares the type.
    #[default]
    Verified,

    /// Pin a specific CA certificate (DER-encoded bytes).
    ///
    /// In v0.2, use this with the bytes returned by
    /// `DaemonServer::fetch_certificate` to bootstrap trust on a self-signed
    /// daemon. v0.1 only declares the variant.
    Ca(Vec<u8>),

    /// Skip server-cert verification entirely. Available only when the crate
    /// is built with the `insecure-tls` feature (the runtime gate lands with
    /// the transport layer in v0.2).
    ///
    /// **Never** use this in production.
    Insecure,
}

/// Connection settings for a Mapepire daemon.
///
/// Construct via [`DaemonServer::builder`]. The struct is intentionally
/// **not** `Clone` because [`Password`] is not `Clone`. Wrap in
/// [`std::sync::Arc`] to share across multiple pools.
#[derive(Debug)]
pub struct DaemonServer {
    /// Hostname or IP of the IBM i system.
    pub host: String,
    /// TCP port; default `8076`.
    pub port: u16,
    /// IBM i user profile.
    pub user: String,
    /// IBM i user password.
    pub password: Password,
    /// TLS verification mode.
    pub tls: TlsConfig,
}

impl DaemonServer {
    /// Default Mapepire daemon TCP port.
    pub const DEFAULT_PORT: u16 = 8076;

    /// Begin building a [`DaemonServer`] with required fields collected
    /// fluently.
    #[must_use]
    pub fn builder() -> DaemonServerBuilder {
        DaemonServerBuilder::default()
    }
}

/// TLS certificate bootstrap methods.
#[cfg(feature = "insecure-tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "insecure-tls")))]
impl DaemonServer {
    /// Connect to the daemon with TLS verification disabled and return the
    /// server's leaf certificate as DER bytes. Pin the bytes via
    /// [`TlsConfig::Ca`] for subsequent verified connections — the canonical
    /// bootstrap workflow for self-signed daemons.
    ///
    /// **Never** use this in production without immediately pinning the
    /// returned cert. The connection that returns the bytes is itself
    /// unverified, so a man-in-the-middle attacker could substitute their own
    /// cert. Verify the returned bytes out-of-band before trusting them.
    /// Concretely: compute the SHA-256 fingerprint of the returned DER bytes
    /// (e.g., `openssl x509 -in <der> -inform DER -fingerprint -sha256 -noout`)
    /// and compare against the value the daemon admin reports out-of-band.
    ///
    /// This is an associated function (no `&self`) because callers are
    /// bootstrapping — they don't have a fully-built [`DaemonServer`] yet.
    ///
    /// Requires the `insecure-tls` Cargo feature.
    ///
    /// # Errors
    ///
    /// - [`crate::error::Error::Transport`] for TCP / TLS failures.
    /// - [`crate::error::Error::Internal`] if the server presents no certificate or an empty chain.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> mapepire::Result<()> {
    /// use mapepire::{DaemonServer, TlsConfig};
    ///
    /// // Bootstrap: fetch the daemon's self-signed cert (UNVERIFIED).
    /// let der = DaemonServer::fetch_certificate("daemon.example.com", 8076).await?;
    ///
    /// // Pin it for subsequent verified connections.
    /// let server = DaemonServer::builder()
    ///     .host("daemon.example.com")
    ///     .port(8076)
    ///     .user("USER")
    ///     .password("…".to_string())
    ///     .tls(TlsConfig::Ca(der))
    ///     .build()
    ///     .expect("all fields set");
    /// # Ok(()) }
    /// ```
    pub async fn fetch_certificate(host: &str, port: u16) -> crate::Result<Vec<u8>> {
        crate::transport::tls::fetch_certificate(host, port).await
    }
}

/// Fluent builder for [`DaemonServer`].
#[derive(Debug, Default)]
pub struct DaemonServerBuilder {
    host: Option<String>,
    port: Option<u16>,
    user: Option<String>,
    password: Option<Password>,
    tls: Option<TlsConfig>,
}

impl DaemonServerBuilder {
    /// Set the hostname or IP.
    #[must_use]
    pub fn host(mut self, host: impl Into<String>) -> Self {
        self.host = Some(host.into());
        self
    }

    /// Override the default port (8076).
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Set the IBM i user profile.
    #[must_use]
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Set the password. Takes ownership; the original `String` heap
    /// buffer moves into a zeroizing buffer on construction.
    #[must_use]
    pub fn password(mut self, password: String) -> Self {
        self.password = Some(Password::new(password));
        self
    }

    /// Override the default TLS configuration ([`TlsConfig::Verified`]).
    #[must_use]
    pub fn tls(mut self, tls: TlsConfig) -> Self {
        self.tls = Some(tls);
        self
    }

    /// Finalize the builder.
    ///
    /// # Errors
    ///
    /// Returns [`BuilderError`] if any required field (`host`, `user`,
    /// `password`) is missing.
    pub fn build(self) -> Result<DaemonServer, BuilderError> {
        Ok(DaemonServer {
            host: self.host.ok_or(BuilderError::MissingField("host"))?,
            port: self.port.unwrap_or(DaemonServer::DEFAULT_PORT),
            user: self.user.ok_or(BuilderError::MissingField("user"))?,
            password: self
                .password
                .ok_or(BuilderError::MissingField("password"))?,
            tls: self.tls.unwrap_or_default(),
        })
    }
}

/// Errors returned by [`DaemonServerBuilder::build`].
#[derive(Debug, thiserror::Error)]
pub enum BuilderError {
    /// A required field was not set before calling `build()`.
    #[error("missing required field: {0}")]
    MissingField(&'static str),
}

// NOTE: `From<DaemonServer> for Arc<DaemonServer>` is provided by the
// standard library's blanket `impl<T> From<T> for Arc<T>` (stable since
// Rust 1.21). An explicit impl would conflict (E0119). Callers can use
// `Arc::new(server)` or `Into::<Arc<DaemonServer>>::into(server)` directly.

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;

    #[test]
    fn default_is_verified() {
        assert!(matches!(TlsConfig::default(), TlsConfig::Verified));
    }

    #[test]
    fn ca_holds_bytes() {
        let bytes = vec![0xAA, 0xBB, 0xCC];
        let cfg = TlsConfig::Ca(bytes.clone());
        match cfg {
            TlsConfig::Ca(b) => assert_eq!(b, bytes),
            _ => panic!("expected Ca variant"),
        }
    }

    #[test]
    fn builder_defaults_port_and_tls() {
        let s = DaemonServer::builder()
            .host("ibmi.example.com")
            .user("DCURTIS")
            .password("hunter2".to_string())
            .build()
            .expect("DaemonServer builds with all required fields set");

        assert_eq!(s.host, "ibmi.example.com");
        assert_eq!(s.port, DaemonServer::DEFAULT_PORT);
        assert_eq!(s.user, "DCURTIS");
        assert!(matches!(s.tls, TlsConfig::Verified));
    }

    #[test]
    fn builder_missing_host_is_error() {
        let err = DaemonServer::builder()
            .user("DCURTIS")
            .password("x".to_string())
            .build()
            .unwrap_err();
        assert!(matches!(err, BuilderError::MissingField("host")));
    }

    #[test]
    fn builder_missing_user_is_error() {
        let err = DaemonServer::builder()
            .host("h")
            .password("x".to_string())
            .build()
            .unwrap_err();
        assert!(matches!(err, BuilderError::MissingField("user")));
    }

    #[test]
    fn builder_missing_password_is_error() {
        let err = DaemonServer::builder()
            .host("h")
            .user("u")
            .build()
            .unwrap_err();
        assert!(matches!(err, BuilderError::MissingField("password")));
    }

    #[test]
    fn into_arc_works() {
        let s = DaemonServer::builder()
            .host("h")
            .user("u")
            .password("p".to_string())
            .build()
            .unwrap();
        let a: Arc<DaemonServer> = s.into();
        assert_eq!(a.host, "h");
    }

    #[test]
    fn builder_overrides_port_and_tls() {
        let s = DaemonServer::builder()
            .host("h")
            .user("u")
            .password("p".to_string())
            .port(9999)
            .tls(TlsConfig::Insecure)
            .build()
            .expect("DaemonServer builds with all required fields set");
        assert_eq!(s.port, 9999);
        assert!(matches!(s.tls, TlsConfig::Insecure));
    }
}

/// Serializable counterpart to [`DaemonServer`] for loading config from files.
///
/// Available only with the `serde-config` feature. Convert into the runtime
/// type via [`DaemonServerSpec::try_into_server`].
#[cfg(feature = "serde-config")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-config")))]
#[derive(Debug, serde::Deserialize)]
pub struct DaemonServerSpec {
    /// Hostname or IP of the IBM i system.
    pub host: String,
    /// TCP port; defaults to [`DaemonServer::DEFAULT_PORT`] when absent.
    #[serde(default)]
    pub port: Option<u16>,
    /// IBM i user profile.
    pub user: String,
    /// IBM i user password (plain text in config — handle the file accordingly).
    pub password: String,
    /// TLS mode. `"verified"`, `"insecure"`, or `{ "ca": "<base64-DER>" }`
    /// in the config file.
    #[serde(default)]
    pub tls: TlsConfigSpec,
}

/// TLS configuration as it appears in serialized config.
#[cfg(feature = "serde-config")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-config")))]
#[derive(Debug, Default, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TlsConfigSpec {
    /// Verify against system roots.
    #[default]
    Verified,
    /// Pin a CA from the given DER bytes (base64-encoded in the config).
    Ca(String),
    /// Skip verification.
    Insecure,
}

#[cfg(feature = "serde-config")]
impl DaemonServerSpec {
    /// Convert into a runtime [`DaemonServer`].
    ///
    /// # Errors
    ///
    /// Returns a [`SpecError`] if the TLS CA bytes fail to decode from base64.
    pub fn try_into_server(self) -> Result<DaemonServer, SpecError> {
        use base64::Engine;
        let tls = match self.tls {
            TlsConfigSpec::Verified => TlsConfig::Verified,
            TlsConfigSpec::Insecure => TlsConfig::Insecure,
            TlsConfigSpec::Ca(b64) => {
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(&b64)
                    .map_err(SpecError::InvalidCaBase64)?;
                TlsConfig::Ca(bytes)
            }
        };
        Ok(DaemonServer {
            host: self.host,
            port: self.port.unwrap_or(DaemonServer::DEFAULT_PORT),
            user: self.user,
            password: Password::new(self.password),
            tls,
        })
    }
}

/// Errors returned by [`DaemonServerSpec::try_into_server`].
#[cfg(feature = "serde-config")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-config")))]
#[derive(Debug, thiserror::Error)]
pub enum SpecError {
    /// The base64-encoded CA bytes failed to decode.
    #[error("invalid base64 in tls.ca: {0}")]
    InvalidCaBase64(#[source] base64::DecodeError),
}

#[cfg(all(test, feature = "serde-config"))]
mod spec_tests {
    //! Tests use JSON via `serde_json` (already in `[dependencies]`) rather
    //! than introducing a TOML parser as a dev-dep — the `toml` 0.9 crate
    //! pulls `winnow` 1.x and conflicts with the `winnow` 0.7.x already in
    //! the tree via `insta`/`toml_edit`, which trips
    //! `multiple-versions = "deny"` in `deny.toml`. The serde derives are
    //! format-agnostic, so JSON exercises the same code path.

    use super::*;

    #[test]
    fn parses_minimal_json() {
        let json = r#"{
            "host": "ibmi.example.com",
            "user": "DCURTIS",
            "password": "hunter2"
        }"#;
        let spec: DaemonServerSpec =
            serde_json::from_str(json).expect("DaemonServerSpec parses from JSON");
        let server = spec
            .try_into_server()
            .expect("DaemonServerSpec converts to DaemonServer");
        assert_eq!(server.host, "ibmi.example.com");
        assert_eq!(server.port, DaemonServer::DEFAULT_PORT);
    }

    #[test]
    fn parses_with_explicit_port_and_insecure_tls() {
        let json = r#"{
            "host": "h",
            "port": 9000,
            "user": "u",
            "password": "p",
            "tls": "insecure"
        }"#;
        let spec: DaemonServerSpec =
            serde_json::from_str(json).expect("DaemonServerSpec parses from JSON");
        let server = spec
            .try_into_server()
            .expect("DaemonServerSpec converts to DaemonServer");
        assert_eq!(server.port, 9000);
        assert!(matches!(server.tls, TlsConfig::Insecure));
    }
}