draupnir 0.1.5

Draupnir — the nordisk boot/provisioning library: fire up a runtime from one BootSpec across three backends (KVM via tunnr · OCI container · Redfish bare-metal virtual-media) and drive its power lifecycle. Odin's ring that drips eight identical copies → boot a fleet of identical machines from one ISO.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! **Redfish backend** — provision **bare metal** out-of-band through a BMC.
//!
//! This is the capability Draupnir uniquely owns. A bare-metal node is booted
//! *without* touching its OS: through the node's BMC (iLO / iDRAC / OpenBMC)
//! DMTF **Redfish** REST API we
//!
//! 1. **insert** a bootable ISO as **virtual media** ([`VirtualMedia::insert_media`]),
//! 2. **set the one-time boot override** to that media ([`VirtualMedia::set_boot_override`]),
//! 3. **power the node on** ([`Lifecycle::power_on`], via `ComputerSystem.Reset`).
//!
//! Draupnir does not hand-roll a heavyweight client: the transport is **`ureq`**
//! over **rustls** (pure Rust — no openssl/native-tls, per the charter), driving the
//! handful of Redfish endpoints we need. It sits behind the `backend-redfish`
//! feature so the default build stays pure-std and offline-green.
//!
//! ## Testability
//!
//! The **request shaping** — the resource URLs and the JSON action bodies — is
//! pure and [fixture-tested](tests) with no BMC. Only the actual HTTP send needs a
//! live endpoint; unit tests never touch the network. BMCs almost always ship
//! self-signed certs, so [`RedfishBoot::insecure`] installs a rustls config that
//! skips verification (opt-in).

use crate::{
    Boot, BmcEndpoint, BootSpec, BootTarget, Error, ImageSource, Lifecycle, Machine, PowerState,
    Result, VirtualMedia,
};

/// The default Redfish `VirtualMedia` resource id an ISO is inserted into (the
/// virtual CD/DVD slot). Overridable via [`RedfishBoot::media_id`].
pub const DEFAULT_MEDIA_ID: &str = "CD";

/// The Redfish bare-metal boot backend.
///
/// Constructed either bare ([`new`](Self::new), then [`with_password`](Self::with_password))
/// or bound to a node ([`for_node`](Self::for_node)). The BMC secret is supplied
/// here **at drive time** — it is deliberately never a field on [`BootSpec`].
#[derive(Debug, Default, Clone)]
pub struct RedfishBoot {
    /// The BMC account password, supplied at drive time (never in a [`BootSpec`]).
    password: String,
    /// Skip TLS certificate verification — BMCs ship self-signed certs. Opt-in.
    insecure: bool,
    /// The `VirtualMedia` slot id (defaults to [`DEFAULT_MEDIA_ID`]).
    media_id: Option<String>,
    /// The node this backend drives, for the [`Lifecycle`] methods (which only get
    /// a [`Machine`], not a [`BmcEndpoint`]). `boot()` uses the spec's BMC directly.
    #[cfg_attr(not(feature = "backend-redfish"), allow(dead_code))]
    endpoint: Option<BmcEndpoint>,
}

impl RedfishBoot {
    /// Construct the Redfish backend (no credential/endpoint yet).
    pub fn new() -> Self {
        Self::default()
    }

    /// Bind the backend to a node + its BMC password so the [`Lifecycle`] methods
    /// (which receive only a [`Machine`]) can address it.
    pub fn for_node(bmc: BmcEndpoint, password: impl Into<String>) -> Self {
        Self {
            password: password.into(),
            insecure: false,
            media_id: None,
            endpoint: Some(bmc),
        }
    }

    /// Set the BMC account password (builder style).
    pub fn with_password(mut self, password: impl Into<String>) -> Self {
        self.password = password.into();
        self
    }

    /// Skip TLS certificate verification (BMCs ship self-signed certs). Opt-in.
    pub fn insecure(mut self, insecure: bool) -> Self {
        self.insecure = insecure;
        self
    }

    /// Override the `VirtualMedia` slot id (default [`DEFAULT_MEDIA_ID`]).
    pub fn media_id(mut self, id: impl Into<String>) -> Self {
        self.media_id = Some(id.into());
        self
    }

    /// The virtual-media slot this backend inserts into.
    #[cfg_attr(not(feature = "backend-redfish"), allow(dead_code))]
    fn slot(&self) -> &str {
        self.media_id.as_deref().unwrap_or(DEFAULT_MEDIA_ID)
    }

    /// The BMC endpoint + ISO a Redfish spec targets (both required).
    fn target<'a>(&self, spec: &'a BootSpec) -> Result<(&'a BmcEndpoint, &'a str)> {
        let bmc = spec
            .bmc
            .as_ref()
            .ok_or_else(|| Error::Spec("Redfish boot needs a BMC endpoint".into()))?;
        match &spec.image {
            ImageSource::Iso(iso) => Ok((bmc, iso.as_str())),
            other => Err(Error::Spec(format!(
                "Redfish backend boots an ISO, got {other:?}"
            ))),
        }
    }

    /// The node the [`Lifecycle`] methods act on (the one bound via
    /// [`for_node`](Self::for_node)).
    #[cfg_attr(not(feature = "backend-redfish"), allow(dead_code))]
    fn bound(&self) -> Result<&BmcEndpoint> {
        self.endpoint.as_ref().ok_or_else(|| {
            Error::Backend(
                "no BMC endpoint bound: construct with RedfishBoot::for_node(bmc, password)".into(),
            )
        })
    }
}

impl Boot for RedfishBoot {
    fn boot(&self, spec: &BootSpec) -> Result<Machine> {
        spec.validate()?;
        let (bmc, iso) = self.target(spec)?;
        #[cfg(feature = "backend-redfish")]
        {
            // The full bare-metal boot sequence: insert the ISO, override next boot
            // to it, power the node on — each an out-of-band Redfish action.
            self.insert_media(bmc, iso)?;
            self.set_boot_override(bmc, BootTarget::Cd)?;
            self.reset(bmc, "On")?;
            Ok(Machine::started(&bmc.system_id, spec))
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            let _ = (bmc, iso);
            Err(Error::Unsupported(
                "redfish backend needs the `backend-redfish` feature (pure-Rust ureq/rustls Redfish client)"
                    .into(),
            ))
        }
    }
}

impl VirtualMedia for RedfishBoot {
    fn insert_media(&self, node: &BmcEndpoint, iso: &str) -> Result<()> {
        #[cfg(feature = "backend-redfish")]
        {
            let url = virtual_media_action_url(node, self.slot(), "InsertMedia");
            self.post(node, &url, &insert_media_body(iso))
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            let _ = (node, iso);
            Err(unsupported())
        }
    }

    fn eject_media(&self, node: &BmcEndpoint) -> Result<()> {
        #[cfg(feature = "backend-redfish")]
        {
            let url = virtual_media_action_url(node, self.slot(), "EjectMedia");
            self.post(node, &url, &serde_json::json!({}))
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            let _ = node;
            Err(unsupported())
        }
    }

    fn set_boot_override(&self, node: &BmcEndpoint, target: BootTarget) -> Result<()> {
        #[cfg(feature = "backend-redfish")]
        {
            self.patch(node, &system_url(node), &boot_override_body(target))
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            let _ = (node, target);
            Err(unsupported())
        }
    }
}

impl Lifecycle for RedfishBoot {
    fn power_on(&self, machine: &Machine) -> Result<()> {
        let _ = machine;
        #[cfg(feature = "backend-redfish")]
        {
            self.reset(self.bound()?, "On")
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            Err(unsupported())
        }
    }

    fn power_off(&self, machine: &Machine) -> Result<()> {
        let _ = machine;
        #[cfg(feature = "backend-redfish")]
        {
            self.reset(self.bound()?, "ForceOff")
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            Err(unsupported())
        }
    }

    fn status(&self, machine: &Machine) -> Result<PowerState> {
        let _ = machine;
        #[cfg(feature = "backend-redfish")]
        {
            self.query_power(self.bound()?)
        }
        #[cfg(not(feature = "backend-redfish"))]
        {
            Err(unsupported())
        }
    }
}

/// The honest "feature not compiled in" error for the un-gated trait methods.
#[cfg(not(feature = "backend-redfish"))]
fn unsupported() -> Error {
    Error::Unsupported(
        "redfish backend needs the `backend-redfish` feature (pure-Rust ureq/rustls Redfish client)"
            .into(),
    )
}

// ---------------------------------------------------------------------------
// Request shaping — PURE: resource URLs + JSON action bodies. Fixture-tested.
// ---------------------------------------------------------------------------

/// The trailing-slash-trimmed Redfish service base for `bmc`.
#[cfg(feature = "backend-redfish")]
fn base(bmc: &BmcEndpoint) -> &str {
    bmc.host.trim_end_matches('/')
}

/// The `ComputerSystem` resource URL: `{host}/redfish/v1/Systems/{system_id}`.
#[cfg(feature = "backend-redfish")]
pub(crate) fn system_url(bmc: &BmcEndpoint) -> String {
    format!("{}/redfish/v1/Systems/{}", base(bmc), bmc.system_id)
}

/// A `VirtualMedia` action URL, e.g.
/// `{host}/redfish/v1/Systems/{system_id}/VirtualMedia/{slot}/Actions/VirtualMedia.{action}`.
#[cfg(feature = "backend-redfish")]
pub(crate) fn virtual_media_action_url(bmc: &BmcEndpoint, slot: &str, action: &str) -> String {
    format!(
        "{}/redfish/v1/Systems/{}/VirtualMedia/{}/Actions/VirtualMedia.{}",
        base(bmc),
        bmc.system_id,
        slot,
        action
    )
}

/// The `ComputerSystem.Reset` action URL.
#[cfg(feature = "backend-redfish")]
pub(crate) fn reset_url(bmc: &BmcEndpoint) -> String {
    format!(
        "{}/redfish/v1/Systems/{}/Actions/ComputerSystem.Reset",
        base(bmc),
        bmc.system_id
    )
}

/// The `VirtualMedia.InsertMedia` request body — mount `iso` read-only.
#[cfg(feature = "backend-redfish")]
pub(crate) fn insert_media_body(iso: &str) -> serde_json::Value {
    serde_json::json!({ "Image": iso, "Inserted": true, "WriteProtected": true })
}

/// The one-time `Boot` override PATCH body for `target`.
#[cfg(feature = "backend-redfish")]
pub(crate) fn boot_override_body(target: BootTarget) -> serde_json::Value {
    serde_json::json!({
        "Boot": {
            "BootSourceOverrideEnabled": "Once",
            "BootSourceOverrideTarget": target_str(target),
        }
    })
}

/// The `ComputerSystem.Reset` body for a Redfish `ResetType` (`On` / `ForceOff` / …).
#[cfg(feature = "backend-redfish")]
pub(crate) fn reset_body(reset_type: &str) -> serde_json::Value {
    serde_json::json!({ "ResetType": reset_type })
}

/// Map a [`BootTarget`] onto its Redfish `BootSourceOverrideTarget` token.
#[cfg(feature = "backend-redfish")]
pub(crate) fn target_str(target: BootTarget) -> &'static str {
    match target {
        BootTarget::Cd => "Cd",
        BootTarget::Pxe => "Pxe",
        BootTarget::Hdd => "Hdd",
        BootTarget::BiosSetup => "BiosSetup",
    }
}

// ---------------------------------------------------------------------------
// Transport — ureq/rustls (feature `backend-redfish`).
// ---------------------------------------------------------------------------

#[cfg(feature = "backend-redfish")]
impl RedfishBoot {
    /// Build a ureq agent, optionally skipping cert verification for the
    /// self-signed certs BMCs ship (pure rustls — no openssl/native-tls).
    fn agent(&self) -> ureq::Agent {
        if self.insecure {
            use ureq::tls::TlsConfig;
            ureq::config::Config::builder()
                .tls_config(TlsConfig::builder().disable_verification(true).build())
                .build()
                .into()
        } else {
            ureq::Agent::new_with_defaults()
        }
    }

    /// The HTTP Basic `Authorization` header value for `bmc` + the drive-time secret.
    fn auth(&self, bmc: &BmcEndpoint) -> String {
        format!("Basic {}", base64(format!("{}:{}", bmc.username, self.password).as_bytes()))
    }

    /// POST a Redfish action body to `url`.
    fn post(&self, bmc: &BmcEndpoint, url: &str, body: &serde_json::Value) -> Result<()> {
        self.agent()
            .post(url)
            .header("Authorization", &self.auth(bmc))
            .send_json(body)
            .map_err(|e| Error::Backend(format!("redfish POST {url}: {e}")))?;
        Ok(())
    }

    /// PATCH a Redfish resource at `url`.
    fn patch(&self, bmc: &BmcEndpoint, url: &str, body: &serde_json::Value) -> Result<()> {
        self.agent()
            .patch(url)
            .header("Authorization", &self.auth(bmc))
            .send_json(body)
            .map_err(|e| Error::Backend(format!("redfish PATCH {url}: {e}")))?;
        Ok(())
    }

    /// Drive a `ComputerSystem.Reset` with `reset_type` (`On`/`ForceOff`/…).
    fn reset(&self, bmc: &BmcEndpoint, reset_type: &str) -> Result<()> {
        self.post(bmc, &reset_url(bmc), &reset_body(reset_type))
    }

    /// GET the `ComputerSystem` and map its `PowerState` onto [`PowerState`].
    fn query_power(&self, bmc: &BmcEndpoint) -> Result<PowerState> {
        let url = system_url(bmc);
        let mut resp = self
            .agent()
            .get(&url)
            .header("Authorization", &self.auth(bmc))
            .call()
            .map_err(|e| Error::Backend(format!("redfish GET {url}: {e}")))?;
        let v: serde_json::Value = resp
            .body_mut()
            .read_json()
            .map_err(|e| Error::Backend(format!("redfish decode {url}: {e}")))?;
        Ok(match v.get("PowerState").and_then(|p| p.as_str()) {
            Some("On") => PowerState::On,
            Some("Off") => PowerState::Off,
            _ => PowerState::Unknown,
        })
    }
}

/// Minimal std-only base64 (standard alphabet, padded) for the Basic-auth header —
/// avoids pulling a crate for four bytes of encoding.
#[cfg(feature = "backend-redfish")]
fn base64(input: &[u8]) -> String {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0];
        let b1 = *chunk.get(1).unwrap_or(&0);
        let b2 = *chunk.get(2).unwrap_or(&0);
        let n = ((b0 as u32) << 16) | ((b1 as u32) << 8) | (b2 as u32);
        out.push(T[((n >> 18) & 63) as usize] as char);
        out.push(T[((n >> 12) & 63) as usize] as char);
        out.push(if chunk.len() > 1 { T[((n >> 6) & 63) as usize] as char } else { '=' });
        out.push(if chunk.len() > 2 { T[(n & 63) as usize] as char } else { '=' });
    }
    out
}

#[cfg(all(test, feature = "backend-redfish"))]
mod tests {
    use super::*;

    fn bmc() -> BmcEndpoint {
        BmcEndpoint {
            host: "https://bmc-42.dc.example/".into(), // trailing slash to prove trim
            username: "admin".into(),
            system_id: "System.Embedded.1".into(),
        }
    }

    #[test]
    fn system_and_reset_urls_are_well_formed() {
        let b = bmc();
        assert_eq!(
            system_url(&b),
            "https://bmc-42.dc.example/redfish/v1/Systems/System.Embedded.1"
        );
        assert_eq!(
            reset_url(&b),
            "https://bmc-42.dc.example/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
        );
    }

    #[test]
    fn virtual_media_insert_url_targets_the_cd_slot() {
        assert_eq!(
            virtual_media_action_url(&bmc(), "CD", "InsertMedia"),
            "https://bmc-42.dc.example/redfish/v1/Systems/System.Embedded.1/VirtualMedia/CD/Actions/VirtualMedia.InsertMedia"
        );
    }

    #[test]
    fn insert_media_body_mounts_the_iso_read_only() {
        let body = insert_media_body("http://srv/installer.iso");
        assert_eq!(body["Image"], "http://srv/installer.iso");
        assert_eq!(body["Inserted"], true);
        assert_eq!(body["WriteProtected"], true);
    }

    #[test]
    fn boot_override_body_is_one_time_to_cd() {
        let body = boot_override_body(BootTarget::Cd);
        assert_eq!(body["Boot"]["BootSourceOverrideEnabled"], "Once");
        assert_eq!(body["Boot"]["BootSourceOverrideTarget"], "Cd");
    }

    #[test]
    fn boot_targets_map_to_redfish_tokens() {
        assert_eq!(target_str(BootTarget::Cd), "Cd");
        assert_eq!(target_str(BootTarget::Pxe), "Pxe");
        assert_eq!(target_str(BootTarget::Hdd), "Hdd");
        assert_eq!(target_str(BootTarget::BiosSetup), "BiosSetup");
    }

    #[test]
    fn reset_body_carries_the_reset_type() {
        assert_eq!(reset_body("On")["ResetType"], "On");
        assert_eq!(reset_body("ForceOff")["ResetType"], "ForceOff");
    }

    #[test]
    fn base64_matches_known_vectors() {
        assert_eq!(base64(b""), "");
        assert_eq!(base64(b"f"), "Zg==");
        assert_eq!(base64(b"fo"), "Zm8=");
        assert_eq!(base64(b"foo"), "Zm9v");
        assert_eq!(base64(b"admin:secret"), "YWRtaW46c2VjcmV0");
    }

    #[test]
    fn auth_header_is_basic_base64_of_user_colon_password() {
        let rf = RedfishBoot::new().with_password("secret");
        assert_eq!(rf.auth(&bmc()), "Basic YWRtaW46c2VjcmV0");
    }

    #[test]
    fn lifecycle_without_a_bound_node_is_an_honest_error() {
        let rf = RedfishBoot::new().with_password("x");
        let m = Machine {
            id: "System.Embedded.1".into(),
            spec_name: "n".into(),
            backend: crate::Backend::Redfish,
            power: PowerState::Unknown,
        };
        assert!(matches!(rf.power_on(&m), Err(Error::Backend(_))));
    }
}