openbao 0.6.0

Secure, typed, async Rust SDK for OpenBao
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Idempotent administration bootstrap helpers.
//!
//! This module builds on typed `sys`, KV v2, Transit, and token helpers. It is
//! meant for already-initialized OpenBao clusters. It does not initialize,
//! unseal, rekey, or rotate production seal material.

use core::fmt;
use std::collections::BTreeMap;

use secrecy::{ExposeSecret, SecretString};
use subtle::ConstantTimeEq;

use crate::{
    AclPolicyBuilder, Authenticated, Client, Error, Result,
    auth::token::{TokenAuth, TokenCreateRequest},
    path::{validate_mount_path, validate_secret_path},
    secrets::transit::TransitCreateKeyRequest,
    sys::{MountEnableRequest, PolicyWriteRequest},
};

const MAX_BOOTSTRAP_OPERATIONS: usize = 512;

/// Builder for a small, idempotent OpenBao admin bootstrap plan.
#[derive(Clone, Debug, Default)]
pub struct AdminBootstrap {
    operations: Vec<BootstrapOperation>,
}

#[derive(Clone)]
enum BootstrapOperation {
    Kv2Mount {
        path: String,
        description: Option<String>,
    },
    TransitMount {
        path: String,
        description: Option<String>,
    },
    TransitKey {
        mount: String,
        name: String,
        request: TransitCreateKeyRequest,
    },
    Policy {
        name: String,
        policy: String,
    },
    Kv2SecretValues {
        mount: String,
        path: String,
        values: BTreeMap<String, SecretString>,
    },
    ServiceToken {
        name: String,
        request: TokenCreateRequest,
    },
}

/// Result of running an [`AdminBootstrap`] plan.
#[derive(Debug, Default)]
pub struct BootstrapReport {
    /// Per-operation status entries.
    pub steps: Vec<BootstrapStepReport>,
    /// Tokens explicitly issued by the plan.
    pub issued_tokens: Vec<BootstrapIssuedToken>,
}

/// Per-operation bootstrap status.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BootstrapStepStatus {
    /// The target already matched the desired state.
    Unchanged,
    /// The target was created.
    Created,
    /// The target existed but was updated.
    Updated,
    /// A new credential was issued. This is intentionally not idempotent.
    Issued,
}

/// Per-operation bootstrap report entry.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BootstrapStepReport {
    /// Bootstrap target type.
    pub target_type: &'static str,
    /// Bootstrap target name or path.
    pub target: String,
    /// Operation status.
    pub status: BootstrapStepStatus,
}

impl BootstrapStepReport {
    fn new(
        target_type: &'static str,
        target: impl Into<String>,
        status: BootstrapStepStatus,
    ) -> Self {
        Self {
            target_type,
            target: target.into(),
            status,
        }
    }
}

/// Token material issued by a bootstrap plan.
pub struct BootstrapIssuedToken {
    /// Logical token name from the bootstrap plan.
    pub name: String,
    /// Token auth response. Contains secret token and accessor material.
    pub auth: TokenAuth,
}

impl fmt::Debug for BootstrapIssuedToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("BootstrapIssuedToken")
            .field("name", &self.name)
            .field("auth", &"<redacted>")
            .finish()
    }
}

impl fmt::Debug for BootstrapOperation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Kv2Mount { path, description } => formatter
                .debug_struct("Kv2Mount")
                .field("path", path)
                .field("description", description)
                .finish(),
            Self::TransitMount { path, description } => formatter
                .debug_struct("TransitMount")
                .field("path", path)
                .field("description", description)
                .finish(),
            Self::TransitKey { mount, name, .. } => formatter
                .debug_struct("TransitKey")
                .field("mount", mount)
                .field("name", name)
                .field("request", &"<redacted>")
                .finish(),
            Self::Policy { name, .. } => formatter
                .debug_struct("Policy")
                .field("name", name)
                .field("policy", &"<redacted>")
                .finish(),
            Self::Kv2SecretValues { mount, path, .. } => formatter
                .debug_struct("Kv2SecretValues")
                .field("mount", mount)
                .field("path", path)
                .field("values", &"<redacted>")
                .finish(),
            Self::ServiceToken { name, .. } => formatter
                .debug_struct("ServiceToken")
                .field("name", name)
                .field("request", &"<redacted>")
                .finish(),
        }
    }
}

impl AdminBootstrap {
    /// Creates an empty admin bootstrap plan.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Ensures a KV v2 mount exists at `path`.
    pub fn ensure_kv2_mount(
        &mut self,
        path: impl AsRef<str>,
        description: Option<&str>,
    ) -> Result<&mut Self> {
        let path = validate_mount_path(path.as_ref())?.join("/");
        self.push_operation(BootstrapOperation::Kv2Mount {
            path,
            description: description.map(str::to_owned),
        })
    }

    /// Ensures a Transit mount exists at `path`.
    pub fn ensure_transit_mount(
        &mut self,
        path: impl AsRef<str>,
        description: Option<&str>,
    ) -> Result<&mut Self> {
        let path = validate_mount_path(path.as_ref())?.join("/");
        self.push_operation(BootstrapOperation::TransitMount {
            path,
            description: description.map(str::to_owned),
        })
    }

    /// Ensures a Transit key exists.
    pub fn ensure_transit_key(
        &mut self,
        mount: impl AsRef<str>,
        name: impl AsRef<str>,
        request: TransitCreateKeyRequest,
    ) -> Result<&mut Self> {
        let mount = validate_mount_path(mount.as_ref())?.join("/");
        let name = validate_mount_path(name.as_ref())?.join("/");
        self.push_operation(BootstrapOperation::TransitKey {
            mount,
            name,
            request,
        })
    }

    /// Ensures an ACL policy exists and matches the builder output.
    pub fn ensure_policy(
        &mut self,
        name: impl AsRef<str>,
        policy: &AclPolicyBuilder,
    ) -> Result<&mut Self> {
        self.ensure_policy_document(name, policy.build()?)
    }

    /// Ensures an ACL policy exists and matches an explicit policy document.
    pub fn ensure_policy_document(
        &mut self,
        name: impl AsRef<str>,
        policy: impl Into<String>,
    ) -> Result<&mut Self> {
        let name = validate_mount_path(name.as_ref())?.join("/");
        self.push_operation(BootstrapOperation::Policy {
            name,
            policy: policy.into(),
        })
    }

    /// Ensures a KV v2 secret contains the provided string values.
    ///
    /// Existing extra keys are preserved. The secret is patched only when one
    /// of the requested values is missing or different.
    pub fn ensure_kv2_secret_values(
        &mut self,
        mount: impl AsRef<str>,
        path: impl AsRef<str>,
        values: BTreeMap<String, SecretString>,
    ) -> Result<&mut Self> {
        let mount = validate_mount_path(mount.as_ref())?.join("/");
        let path = validate_secret_path(path.as_ref())?.join("/");
        self.push_operation(BootstrapOperation::Kv2SecretValues {
            mount,
            path,
            values,
        })
    }

    /// Issues a scoped service token at the end of the plan.
    ///
    /// Token issuance always creates a new credential. This method is explicit
    /// so callers can separate idempotent state convergence from credential
    /// handoff.
    pub fn issue_service_token(
        &mut self,
        name: impl AsRef<str>,
        request: TokenCreateRequest,
    ) -> Result<&mut Self> {
        let name = validate_mount_path(name.as_ref())?.join("/");
        self.push_operation(BootstrapOperation::ServiceToken { name, request })
    }

    fn push_operation(&mut self, operation: BootstrapOperation) -> Result<&mut Self> {
        if self.operations.len() >= MAX_BOOTSTRAP_OPERATIONS {
            return Err(Error::InvalidParameter(
                "bootstrap plan exceeds maximum allowed operation count".into(),
            ));
        }
        self.operations.push(operation);
        Ok(self)
    }

    /// Runs the bootstrap plan.
    pub async fn run(&self, client: &Client<Authenticated>) -> Result<BootstrapReport> {
        let mut report = BootstrapReport::default();
        for operation in &self.operations {
            match operation {
                BootstrapOperation::Kv2Mount { path, description } => {
                    let status = ensure_mount(client, path, "kv", Some(("version", "2")), || {
                        MountEnableRequest::kv2().with_optional_description(description)
                    })
                    .await?;
                    report
                        .steps
                        .push(BootstrapStepReport::new("kv2_mount", path, status));
                }
                BootstrapOperation::TransitMount { path, description } => {
                    let status = ensure_mount(client, path, "transit", None, || {
                        MountEnableRequest::new("transit").with_optional_description(description)
                    })
                    .await?;
                    report
                        .steps
                        .push(BootstrapStepReport::new("transit_mount", path, status));
                }
                BootstrapOperation::TransitKey {
                    mount,
                    name,
                    request,
                } => {
                    let status = match client.transit(mount)?.read_key(name).await {
                        Ok(_) => BootstrapStepStatus::Unchanged,
                        Err(error) if error.is_not_found() => {
                            match client.transit(mount)?.create_key(name, request).await {
                                Ok(_) => BootstrapStepStatus::Created,
                                Err(error) if is_already_exists_error(&error) => {
                                    BootstrapStepStatus::Unchanged
                                }
                                Err(error) => return Err(error),
                            }
                        }
                        Err(error) => return Err(error),
                    };
                    report.steps.push(BootstrapStepReport::new(
                        "transit_key",
                        format!("{mount}/{name}"),
                        status,
                    ));
                }
                BootstrapOperation::Policy { name, policy } => {
                    let status = match client.sys().read_policy(name).await {
                        Ok(existing) if existing.rules == *policy => BootstrapStepStatus::Unchanged,
                        Ok(_) => {
                            client
                                .sys()
                                .write_policy(name, &PolicyWriteRequest::new(policy.clone()))
                                .await?;
                            BootstrapStepStatus::Updated
                        }
                        Err(error) if error.is_not_found() => {
                            client
                                .sys()
                                .write_policy(name, &PolicyWriteRequest::new(policy.clone()))
                                .await?;
                            BootstrapStepStatus::Created
                        }
                        Err(error) => return Err(error),
                    };
                    report
                        .steps
                        .push(BootstrapStepReport::new("policy", name, status));
                }
                BootstrapOperation::Kv2SecretValues {
                    mount,
                    path,
                    values,
                } => {
                    let kv = client.kv2(mount)?;
                    let current = match kv.read_service_config(path).await {
                        Ok(config) => Some(config),
                        Err(error) if error.is_not_found() => None,
                        Err(error) => return Err(error),
                    };
                    let needs_patch = current.as_ref().is_none_or(|config| {
                        values.iter().any(|(key, value)| {
                            config.get(key).is_none_or(|current| {
                                !secret_values_equal(current.expose_secret(), value.expose_secret())
                            })
                        })
                    });
                    let status = if needs_patch {
                        kv.patch(path, secret_patch_payload(values)).await?;
                        if current.is_some() {
                            BootstrapStepStatus::Updated
                        } else {
                            BootstrapStepStatus::Created
                        }
                    } else {
                        BootstrapStepStatus::Unchanged
                    };
                    report.steps.push(BootstrapStepReport::new(
                        "kv2_secret",
                        format!("{mount}/{path}"),
                        status,
                    ));
                }
                BootstrapOperation::ServiceToken { name, request } => {
                    let auth = client.token().create(request).await?;
                    report.steps.push(BootstrapStepReport::new(
                        "service_token",
                        name,
                        BootstrapStepStatus::Issued,
                    ));
                    report.issued_tokens.push(BootstrapIssuedToken {
                        name: name.clone(),
                        auth,
                    });
                }
            }
        }
        Ok(report)
    }
}

trait MountDescriptionExt {
    fn with_optional_description(self, description: &Option<String>) -> Self;
}

impl MountDescriptionExt for MountEnableRequest {
    fn with_optional_description(mut self, description: &Option<String>) -> Self {
        self.description.clone_from(description);
        self
    }
}

async fn ensure_mount<F>(
    client: &Client<Authenticated>,
    path: &str,
    expected_type: &str,
    expected_option: Option<(&str, &str)>,
    request: F,
) -> Result<BootstrapStepStatus>
where
    F: FnOnce() -> MountEnableRequest,
{
    match client.sys().read_mount(path).await {
        Ok(mount) => {
            if mount.backend_type != expected_type {
                return Err(Error::InvalidParameter(format!(
                    "mount `{path}` exists with type `{}` instead of `{expected_type}`",
                    mount.backend_type
                )));
            }
            if let Some((key, value)) = expected_option
                && mount
                    .options
                    .as_ref()
                    .and_then(|options| options.get(key))
                    .map(String::as_str)
                    != Some(value)
            {
                return Err(Error::InvalidParameter(format!(
                    "mount `{path}` exists without required option `{key}={value}`"
                )));
            }
            Ok(BootstrapStepStatus::Unchanged)
        }
        Err(error) if error.is_not_found() => {
            match client.sys().enable_mount(path, &request()).await {
                Ok(_) => Ok(BootstrapStepStatus::Created),
                Err(error) if is_already_exists_error(&error) => Ok(BootstrapStepStatus::Unchanged),
                Err(error) => Err(error),
            }
        }
        Err(error) => Err(error),
    }
}

fn is_already_exists_error(error: &Error) -> bool {
    error.is_conflict()
}

fn secret_values_equal(current: &str, desired: &str) -> bool {
    current.as_bytes().ct_eq(desired.as_bytes()).into()
}

fn secret_patch_payload(values: &BTreeMap<String, SecretString>) -> BTreeMap<String, &str> {
    values
        .iter()
        .map(|(key, value)| (key.clone(), value.expose_secret()))
        .collect()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]
    #![allow(deprecated)]

    use std::collections::BTreeMap;

    use secrecy::SecretString;

    use crate::{
        AclCapability, AclPolicyBuilder, Authenticated, Client, Error, OpenBaoConfig,
        auth::token::TokenCreateRequest,
        bootstrap::{
            AdminBootstrap, BootstrapStepStatus, MAX_BOOTSTRAP_OPERATIONS, is_already_exists_error,
            secret_values_equal,
        },
        secrets::transit::TransitCreateKeyRequest,
    };
    use reqwest::StatusCode;

    #[test]
    fn bootstrap_validates_paths_when_building_plan() {
        let mut bootstrap = AdminBootstrap::new();
        assert!(bootstrap.ensure_kv2_mount("../secret", None).is_err());
        assert!(
            bootstrap
                .ensure_transit_key("transit", "../key", TransitCreateKeyRequest::default())
                .is_err()
        );
    }

    #[test]
    fn issued_token_debug_redacts_auth() {
        let config = OpenBaoConfig::new("http://127.0.0.1:8200")
            .and_then(OpenBaoConfig::allow_localhost_http)
            .unwrap_or_else(|error| panic!("{error}"));
        let client: Client<Authenticated> = Client::from_config(config)
            .unwrap_or_else(|error| panic!("{error}"))
            .with_token(SecretString::from("token"));

        let mut policy = AclPolicyBuilder::new();
        policy
            .allow_path("secret/data/app", [AclCapability::Read])
            .unwrap_or_else(|error| panic!("{error}"));

        let mut values = BTreeMap::new();
        let sensitive_value = ["sensitive-", "value"].concat();
        values.insert(
            "API_KEY".to_owned(),
            SecretString::from(sensitive_value.clone()),
        );

        let mut bootstrap = AdminBootstrap::new();
        bootstrap
            .ensure_policy("app-read", &policy)
            .and_then(|builder| builder.ensure_kv2_secret_values("secret", "app", values))
            .and_then(|builder| {
                builder.issue_service_token(
                    "app",
                    TokenCreateRequest {
                        policies: vec!["app-read".to_owned()],
                        no_default_policy: Some(true),
                        ..TokenCreateRequest::default()
                    },
                )
            })
            .unwrap_or_else(|error| panic!("{error}"));

        let report = format!("{:?}", bootstrap.operations);
        assert!(!report.contains(&sensitive_value));
        let _client = client;
    }

    #[test]
    fn bootstrap_statuses_are_stable_values() {
        assert_eq!(BootstrapStepStatus::Created, BootstrapStepStatus::Created);
        assert_ne!(BootstrapStepStatus::Created, BootstrapStepStatus::Unchanged);
    }

    #[test]
    fn bootstrap_plan_operation_count_is_bounded() {
        let mut bootstrap = AdminBootstrap::new();
        for index in 0..MAX_BOOTSTRAP_OPERATIONS {
            bootstrap
                .ensure_policy_document(
                    format!("policy-{index}"),
                    "path \"secret/data/app\" { capabilities = [\"read\"] }",
                )
                .unwrap_or_else(|error| panic!("{error}"));
        }
        assert!(
            bootstrap
                .ensure_policy_document(
                    "one-too-many",
                    "path \"secret/data/app\" { capabilities = [\"read\"] }",
                )
                .is_err()
        );
    }

    #[test]
    fn bootstrap_secret_comparison_and_race_errors_are_handled() {
        assert!(secret_values_equal("same-secret", "same-secret"));
        assert!(!secret_values_equal("same-secret", "other-secret"));

        let duplicate = Error::Api {
            status: StatusCode::BAD_REQUEST,
            errors: vec!["path is already in use".to_owned()],
        };
        assert!(is_already_exists_error(&duplicate));

        let unrelated = Error::Api {
            status: StatusCode::BAD_REQUEST,
            errors: vec!["permission denied".to_owned()],
        };
        assert!(!is_already_exists_error(&unrelated));
    }
}