openbao 0.15.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
586
587
588
589
590
591
592
593
//! Helpers for building small OpenBao ACL policy documents.
//!
//! The builder intentionally supports a narrow, typed subset of ACL policy HCL:
//! path rules with known OpenBao capabilities. Use [`crate::sys::PolicyWriteRequest`]
//! directly for advanced policy features such as parameter constraints.

use core::fmt;

use crate::{
    Error, Result,
    path::{validate_endpoint_path, validate_mount_path},
};

const MAX_POLICY_RULES: usize = 128;
pub(crate) const MAX_POLICY_BYTES: usize = 16 * 1024;

/// OpenBao ACL capabilities supported by [`AclPolicyBuilder`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AclCapability {
    /// Allows creation when the key does not already exist.
    Create,
    /// Allows reading existing values or metadata.
    Read,
    /// Allows updating existing values.
    Update,
    /// Allows deleting values.
    Delete,
    /// Allows listing path children.
    List,
    /// Allows patch-style partial updates.
    Patch,
    /// Allows privileged system operations on paths that require sudo.
    Sudo,
    /// Denies access. Must not be mixed with other capabilities in one rule.
    Deny,
}

impl AclCapability {
    fn as_str(self) -> &'static str {
        match self {
            Self::Create => "create",
            Self::Read => "read",
            Self::Update => "update",
            Self::Delete => "delete",
            Self::List => "list",
            Self::Patch => "patch",
            Self::Sudo => "sudo",
            Self::Deny => "deny",
        }
    }
}

impl fmt::Display for AclCapability {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct AclRule {
    path: String,
    capabilities: Vec<AclCapability>,
    min_wrapping_ttl: Option<String>,
    max_wrapping_ttl: Option<String>,
}

/// Builder for bounded, typed OpenBao ACL policy documents.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AclPolicyBuilder {
    rules: Vec<AclRule>,
}

impl AclPolicyBuilder {
    /// Creates an empty ACL policy builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a path rule with explicit capabilities.
    ///
    /// The path is validated with the same traversal and URL-injection checks
    /// used by request paths. Wildcard segments such as `*` and `+` are allowed
    /// for ACL policy use.
    pub fn allow_path<I>(&mut self, path: impl AsRef<str>, capabilities: I) -> Result<&mut Self>
    where
        I: IntoIterator<Item = AclCapability>,
    {
        self.push_rule(path.as_ref(), capabilities)
    }

    /// Adds a path rule with response-wrapping TTL constraints.
    ///
    /// `min_wrapping_ttl` and `max_wrapping_ttl` use OpenBao duration syntax
    /// such as `30s`, `5m`, or `1h`. At least one bound must be provided.
    /// Parameter constraints remain outside this builder's scope because safe
    /// generation requires a full HCL value serializer.
    pub fn allow_path_with_wrapping<I>(
        &mut self,
        path: impl AsRef<str>,
        capabilities: I,
        min_wrapping_ttl: Option<&str>,
        max_wrapping_ttl: Option<&str>,
    ) -> Result<&mut Self>
    where
        I: IntoIterator<Item = AclCapability>,
    {
        self.push_rule_with_wrapping(
            path.as_ref(),
            capabilities,
            min_wrapping_ttl,
            max_wrapping_ttl,
        )
    }

    /// Adds a deny rule for a path.
    pub fn deny_path(&mut self, path: impl AsRef<str>) -> Result<&mut Self> {
        self.push_rule(path.as_ref(), [AclCapability::Deny])
    }

    /// Allows KV v2 read/list access below a literal prefix.
    ///
    /// For `mount = "secret"` and `prefix = "app"`, this emits rules for
    /// `secret/data/app/*` and `secret/metadata/app/*`. The metadata rule is
    /// list-only so read-only secret policies do not automatically expose
    /// version history or custom metadata; add an explicit metadata `Read`
    /// rule with [`AclPolicyBuilder::allow_path`] when that is desired.
    pub fn allow_kv2_read_prefix(
        &mut self,
        mount: impl AsRef<str>,
        prefix: impl AsRef<str>,
    ) -> Result<&mut Self> {
        let data_path = prefixed_engine_path(mount.as_ref(), "data", prefix.as_ref())?;
        let metadata_path = prefixed_engine_path(mount.as_ref(), "metadata", prefix.as_ref())?;
        self.push_rule(&data_path, [AclCapability::Read])?;
        self.push_rule(&metadata_path, [AclCapability::List])
    }

    /// Allows KV v2 read/list access below a literal prefix and requires
    /// response wrapping on the data path.
    pub fn allow_kv2_read_prefix_with_required_wrapping(
        &mut self,
        mount: impl AsRef<str>,
        prefix: impl AsRef<str>,
        min_wrapping_ttl: &str,
    ) -> Result<&mut Self> {
        let data_path = prefixed_engine_path(mount.as_ref(), "data", prefix.as_ref())?;
        let metadata_path = prefixed_engine_path(mount.as_ref(), "metadata", prefix.as_ref())?;
        self.push_rule_with_wrapping(
            &data_path,
            [AclCapability::Read],
            Some(min_wrapping_ttl),
            None,
        )?;
        self.push_rule(&metadata_path, [AclCapability::List])
    }

    /// Allows KV v2 read/write/list/delete access below a literal prefix.
    pub fn allow_kv2_read_write_prefix(
        &mut self,
        mount: impl AsRef<str>,
        prefix: impl AsRef<str>,
    ) -> Result<&mut Self> {
        let data_path = prefixed_engine_path(mount.as_ref(), "data", prefix.as_ref())?;
        let metadata_path = prefixed_engine_path(mount.as_ref(), "metadata", prefix.as_ref())?;
        self.push_rule(
            &data_path,
            [
                AclCapability::Create,
                AclCapability::Read,
                AclCapability::Update,
                AclCapability::Patch,
                AclCapability::Delete,
            ],
        )?;
        self.push_rule(
            &metadata_path,
            [
                AclCapability::Read,
                AclCapability::Update,
                AclCapability::Delete,
                AclCapability::List,
            ],
        )
    }

    /// Allows KV v2 read/write/list/delete access below a literal prefix and
    /// requires response wrapping on the data path.
    pub fn allow_kv2_read_write_prefix_with_required_wrapping(
        &mut self,
        mount: impl AsRef<str>,
        prefix: impl AsRef<str>,
        min_wrapping_ttl: &str,
    ) -> Result<&mut Self> {
        let data_path = prefixed_engine_path(mount.as_ref(), "data", prefix.as_ref())?;
        let metadata_path = prefixed_engine_path(mount.as_ref(), "metadata", prefix.as_ref())?;
        self.push_rule_with_wrapping(
            &data_path,
            [
                AclCapability::Create,
                AclCapability::Read,
                AclCapability::Update,
                AclCapability::Patch,
                AclCapability::Delete,
            ],
            Some(min_wrapping_ttl),
            None,
        )?;
        self.push_rule(
            &metadata_path,
            [
                AclCapability::Read,
                AclCapability::Update,
                AclCapability::Delete,
                AclCapability::List,
            ],
        )
    }

    /// Allows Transit encrypt/decrypt access for one key.
    pub fn allow_transit_encrypt_decrypt(
        &mut self,
        mount: impl AsRef<str>,
        key: impl AsRef<str>,
    ) -> Result<&mut Self> {
        self.push_rule(
            &engine_key_path(mount.as_ref(), "encrypt", key.as_ref())?,
            [AclCapability::Update],
        )?;
        self.push_rule(
            &engine_key_path(mount.as_ref(), "decrypt", key.as_ref())?,
            [AclCapability::Update],
        )
    }

    /// Allows Transit encrypt/decrypt access and requires response wrapping.
    pub fn allow_transit_encrypt_decrypt_with_required_wrapping(
        &mut self,
        mount: impl AsRef<str>,
        key: impl AsRef<str>,
        min_wrapping_ttl: &str,
    ) -> Result<&mut Self> {
        self.push_rule_with_wrapping(
            &engine_key_path(mount.as_ref(), "encrypt", key.as_ref())?,
            [AclCapability::Update],
            Some(min_wrapping_ttl),
            None,
        )?;
        self.push_rule_with_wrapping(
            &engine_key_path(mount.as_ref(), "decrypt", key.as_ref())?,
            [AclCapability::Update],
            Some(min_wrapping_ttl),
            None,
        )
    }

    /// Allows Transit sign/verify access for one key.
    pub fn allow_transit_sign_verify(
        &mut self,
        mount: impl AsRef<str>,
        key: impl AsRef<str>,
    ) -> Result<&mut Self> {
        self.push_rule(
            &engine_key_path(mount.as_ref(), "sign", key.as_ref())?,
            [AclCapability::Update],
        )?;
        self.push_rule(
            &engine_key_path(mount.as_ref(), "verify", key.as_ref())?,
            [AclCapability::Update],
        )
    }

    /// Allows Transit sign/verify access and requires response wrapping.
    pub fn allow_transit_sign_verify_with_required_wrapping(
        &mut self,
        mount: impl AsRef<str>,
        key: impl AsRef<str>,
        min_wrapping_ttl: &str,
    ) -> Result<&mut Self> {
        self.push_rule_with_wrapping(
            &engine_key_path(mount.as_ref(), "sign", key.as_ref())?,
            [AclCapability::Update],
            Some(min_wrapping_ttl),
            None,
        )?;
        self.push_rule_with_wrapping(
            &engine_key_path(mount.as_ref(), "verify", key.as_ref())?,
            [AclCapability::Update],
            Some(min_wrapping_ttl),
            None,
        )
    }

    /// Renders the policy document.
    pub fn build(&self) -> Result<String> {
        let mut document = String::new();
        for rule in &self.rules {
            push_rule(&mut document, rule);
            if document.len() > MAX_POLICY_BYTES {
                return Err(Error::InvalidParameter(
                    "ACL policy document exceeds maximum allowed length".into(),
                ));
            }
        }
        Ok(document)
    }

    #[cfg(feature = "sys")]
    /// Renders the policy as a sys policy write request.
    pub fn build_write_request(&self) -> Result<crate::sys::PolicyWriteRequest> {
        Ok(crate::sys::PolicyWriteRequest::new(self.build()?))
    }

    fn push_rule<I>(&mut self, path: &str, capabilities: I) -> Result<&mut Self>
    where
        I: IntoIterator<Item = AclCapability>,
    {
        if self.rules.len() >= MAX_POLICY_RULES {
            return Err(Error::InvalidParameter(
                "ACL policy rule count exceeds maximum allowed length".into(),
            ));
        }
        let capabilities = validate_capabilities(capabilities)?;
        let path = validate_policy_path(path)?;
        self.rules.push(AclRule {
            path,
            capabilities,
            min_wrapping_ttl: None,
            max_wrapping_ttl: None,
        });
        Ok(self)
    }

    fn push_rule_with_wrapping<I>(
        &mut self,
        path: &str,
        capabilities: I,
        min_wrapping_ttl: Option<&str>,
        max_wrapping_ttl: Option<&str>,
    ) -> Result<&mut Self>
    where
        I: IntoIterator<Item = AclCapability>,
    {
        if min_wrapping_ttl.is_none() && max_wrapping_ttl.is_none() {
            return Err(Error::InvalidParameter(
                "ACL wrapping rule must include min_wrapping_ttl or max_wrapping_ttl".into(),
            ));
        }
        if self.rules.len() >= MAX_POLICY_RULES {
            return Err(Error::InvalidParameter(
                "ACL policy rule count exceeds maximum allowed length".into(),
            ));
        }
        let capabilities = validate_capabilities(capabilities)?;
        let path = validate_policy_path(path)?;
        let min_wrapping_ttl = min_wrapping_ttl
            .map(|ttl| validate_wrapping_policy_ttl(ttl, "min_wrapping_ttl"))
            .transpose()?;
        let max_wrapping_ttl = max_wrapping_ttl
            .map(|ttl| validate_wrapping_policy_ttl(ttl, "max_wrapping_ttl"))
            .transpose()?;
        self.rules.push(AclRule {
            path,
            capabilities,
            min_wrapping_ttl,
            max_wrapping_ttl,
        });
        Ok(self)
    }
}

fn validate_capabilities<I>(capabilities: I) -> Result<Vec<AclCapability>>
where
    I: IntoIterator<Item = AclCapability>,
{
    let capabilities = capabilities.into_iter().collect::<Vec<_>>();
    if capabilities.is_empty() {
        return Err(Error::InvalidParameter(
            "ACL policy rule must include at least one capability".into(),
        ));
    }
    if capabilities.contains(&AclCapability::Deny) && capabilities.len() > 1 {
        return Err(Error::InvalidParameter(
            "ACL deny capability must not be mixed with other capabilities".into(),
        ));
    }
    Ok(capabilities)
}

fn validate_wrapping_policy_ttl(ttl: &str, field: &'static str) -> Result<String> {
    crate::validation::validate_duration_parameter(ttl, field)?;
    Ok(ttl.to_owned())
}

fn validate_policy_path(path: &str) -> Result<String> {
    Ok(validate_mount_path(path)?.join("/"))
}

fn validate_literal_path(path: &str) -> Result<Vec<String>> {
    validate_literal_segments(validate_endpoint_path(path)?)
}

fn validate_literal_mount_path(path: &str) -> Result<Vec<String>> {
    validate_literal_segments(validate_mount_path(path)?)
}

fn validate_literal_segments(segments: Vec<String>) -> Result<Vec<String>> {
    if segments
        .iter()
        .any(|segment| segment.contains('*') || segment.contains('+'))
    {
        return Err(Error::InvalidPath(
            "helper-generated ACL paths require literal mount, prefix, and key values".into(),
        ));
    }
    Ok(segments)
}

fn prefixed_engine_path(mount: &str, endpoint: &str, prefix: &str) -> Result<String> {
    let mut segments = validate_literal_mount_path(mount)?;
    segments.push(endpoint.to_owned());
    segments.extend(validate_literal_path(prefix)?);
    segments.push("*".to_owned());
    Ok(segments.join("/"))
}

fn engine_key_path(mount: &str, endpoint: &str, key: &str) -> Result<String> {
    let mut segments = validate_literal_mount_path(mount)?;
    segments.push(endpoint.to_owned());
    segments.extend(validate_literal_mount_path(key)?);
    Ok(segments.join("/"))
}

fn push_rule(document: &mut String, rule: &AclRule) {
    document.push_str("path \"");
    push_hcl_string(document, &rule.path);
    document.push_str("\" {\n  capabilities = [");
    for (index, capability) in rule.capabilities.iter().enumerate() {
        if index > 0 {
            document.push_str(", ");
        }
        document.push('"');
        document.push_str(capability.as_str());
        document.push('"');
    }
    document.push_str("]\n");
    if let Some(ttl) = rule.min_wrapping_ttl.as_ref() {
        document.push_str("  min_wrapping_ttl = \"");
        push_hcl_string(document, ttl);
        document.push_str("\"\n");
    }
    if let Some(ttl) = rule.max_wrapping_ttl.as_ref() {
        document.push_str("  max_wrapping_ttl = \"");
        push_hcl_string(document, ttl);
        document.push_str("\"\n");
    }
    document.push_str("}\n");
}

fn push_hcl_string(output: &mut String, value: &str) {
    let mut characters = value.chars().peekable();
    while let Some(character) = characters.next() {
        match character {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '$' if characters.peek() == Some(&'{') => {
                characters.next();
                output.push_str("$${");
            }
            _ => output.push(character),
        }
    }
}

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

    use super::{AclCapability, AclPolicyBuilder};

    #[test]
    fn builds_kv2_prefix_policy() {
        let mut builder = AclPolicyBuilder::new();
        let result = builder
            .allow_kv2_read_prefix("secret", "app")
            .and_then(|builder| builder.build());
        let policy = match result {
            Ok(policy) => policy,
            Err(error) => panic!("{error}"),
        };

        assert!(policy.contains("path \"secret/data/app/*\""));
        assert!(policy.contains("path \"secret/metadata/app/*\""));
        assert!(policy.contains("capabilities = [\"read\"]"));
        assert!(policy.contains("capabilities = [\"list\"]"));
    }

    #[test]
    fn policy_hcl_strings_escape_template_sequences() {
        let mut builder = AclPolicyBuilder::new();
        let policy = builder
            .allow_path("secret/data/app-${env}", [AclCapability::Read])
            .and_then(|builder| builder.build())
            .unwrap_or_else(|error| panic!("{error}"));

        assert!(policy.contains(r#"secret/data/app-$${env}"#));
    }

    #[test]
    fn rejects_deny_mixed_with_other_capabilities() {
        let mut builder = AclPolicyBuilder::new();
        assert!(
            builder
                .allow_path(
                    "secret/data/app/*",
                    [AclCapability::Deny, AclCapability::Read]
                )
                .is_err()
        );
    }

    #[test]
    fn raw_policy_paths_are_escaped() {
        let mut builder = AclPolicyBuilder::new();
        let result = builder
            .allow_path("secret/data/app\"name", [AclCapability::Read])
            .and_then(|builder| builder.build());
        let policy = match result {
            Ok(policy) => policy,
            Err(error) => panic!("{error}"),
        };

        assert!(policy.contains("path \"secret/data/app\\\"name\""));
    }

    #[test]
    fn helper_paths_reject_wildcard_inputs() {
        let mut builder = AclPolicyBuilder::new();
        assert!(builder.allow_kv2_read_prefix("secret", "app/*").is_err());
    }

    #[test]
    fn builds_path_policy_with_wrapping_ttls() {
        let mut builder = AclPolicyBuilder::new();
        let policy = builder
            .allow_path_with_wrapping(
                "secret/data/app/*",
                [AclCapability::Read],
                Some("30s"),
                Some("5m"),
            )
            .and_then(|builder| builder.build())
            .unwrap_or_else(|error| panic!("{error}"));

        assert!(policy.contains("path \"secret/data/app/*\""));
        assert!(policy.contains("capabilities = [\"read\"]"));
        assert!(policy.contains("min_wrapping_ttl = \"30s\""));
        assert!(policy.contains("max_wrapping_ttl = \"5m\""));
    }

    #[test]
    fn helper_policy_can_require_wrapping() {
        let mut builder = AclPolicyBuilder::new();
        let policy = builder
            .allow_kv2_read_prefix_with_required_wrapping("secret", "app", "1m")
            .and_then(|builder| builder.build())
            .unwrap_or_else(|error| panic!("{error}"));

        assert!(policy.contains("path \"secret/data/app/*\""));
        assert!(policy.contains("min_wrapping_ttl = \"1m\""));
        assert!(policy.contains("path \"secret/metadata/app/*\""));
    }

    #[test]
    fn wrapping_policy_ttls_are_validated() {
        let mut builder = AclPolicyBuilder::new();
        assert!(
            builder
                .allow_path_with_wrapping(
                    "secret/data/app/*",
                    [AclCapability::Read],
                    Some("0s"),
                    None
                )
                .is_err()
        );
        assert!(
            builder
                .allow_path_with_wrapping("secret/data/app/*", [AclCapability::Read], None, None)
                .is_err()
        );
    }
}