openbao 0.8.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
//! Shared OpenBao response envelopes.

use core::fmt;

use secrecy::SecretString;
use serde::de::Error as DeError;
use serde::{
    Deserialize, Deserializer, Serialize,
    de::{IgnoredAny, MapAccess, SeqAccess, Visitor},
};

use std::collections::BTreeMap;

const MAX_API_ERRORS: usize = 16;
pub(crate) const MAX_RESPONSE_STRINGS: usize = 4096;

/// Empty JSON payload used for endpoints that do not require a body.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
pub struct Empty {}

/// Shared accessor trait for OpenBao list responses.
///
/// OpenBao commonly returns list endpoints as a primary `keys`, `policies`,
/// or `roles` string array. Concrete response structs keep their documented
/// field names; this trait provides common read-only ergonomics across them.
pub trait ListEntries {
    /// Returns the primary list entries.
    fn entries(&self) -> &[String];

    /// Returns an iterator over the primary list entries.
    fn iter(&self) -> core::slice::Iter<'_, String> {
        self.entries().iter()
    }

    /// Returns the number of primary entries.
    fn len(&self) -> usize {
        self.entries().len()
    }

    /// Returns true when the primary entry list is empty.
    fn is_empty(&self) -> bool {
        self.entries().is_empty()
    }

    /// Returns true when the primary entry list contains `entry`.
    fn contains(&self, entry: &str) -> bool {
        self.entries().iter().any(|candidate| candidate == entry)
    }
}

/// Standard OpenBao response envelope for endpoints that return `data`.
#[derive(Clone, Deserialize)]
pub struct ResponseEnvelope<T> {
    /// Endpoint-specific response data.
    pub data: T,
    /// Lease identifier, when the endpoint returns one.
    #[serde(default = "empty_secret")]
    pub lease_id: SecretString,
    /// Lease duration in seconds.
    #[serde(default)]
    pub lease_duration: u64,
    /// Whether the lease is renewable.
    #[serde(default)]
    pub renewable: bool,
    /// Warnings emitted by OpenBao.
    #[serde(default, deserialize_with = "deserialize_optional_bounded_string_vec")]
    pub warnings: Option<Vec<String>>,
    /// Response wrapping metadata, when OpenBao returns a wrapped response.
    #[serde(default)]
    pub wrap_info: Option<WrapInfo>,
}

impl<T: fmt::Debug> fmt::Debug for ResponseEnvelope<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResponseEnvelope")
            .field("data", &self.data)
            .field("lease_id", &"<redacted>")
            .field("lease_duration", &self.lease_duration)
            .field("renewable", &self.renewable)
            .field("warnings", &self.warnings)
            .field("wrap_info", &self.wrap_info)
            .finish()
    }
}

/// Metadata for a response-wrapping token.
#[derive(Clone, Deserialize)]
pub struct WrapInfo {
    /// Wrapping token. Treat as secret material.
    pub token: SecretString,
    /// Token accessor, when returned. Treat as secret material.
    #[serde(default)]
    pub accessor: Option<SecretString>,
    /// Wrapping token TTL in seconds.
    #[serde(default)]
    pub ttl: u64,
    /// Wrapped response creation time.
    #[serde(default)]
    pub creation_time: Option<String>,
    /// Wrapped response creation path.
    #[serde(default)]
    pub creation_path: Option<String>,
}

impl fmt::Debug for WrapInfo {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WrapInfo")
            .field("token", &"<redacted>")
            .field("accessor", &self.accessor.as_ref().map(|_| "<redacted>"))
            .field("ttl", &self.ttl)
            .field("creation_time", &self.creation_time)
            .field("creation_path", &self.creation_path)
            .finish()
    }
}

fn empty_secret() -> SecretString {
    SecretString::from(String::new())
}

pub(crate) fn deserialize_bounded_string_vec<'de, D>(
    deserializer: D,
) -> core::result::Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_seq(BoundedStringListVisitor::<MAX_RESPONSE_STRINGS>)
}

pub(crate) fn deserialize_optional_bounded_string_vec<'de, D>(
    deserializer: D,
) -> core::result::Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    Option::<BoundedStringList>::deserialize(deserializer).map(|value| value.map(|value| value.0))
}

#[allow(dead_code)]
pub(crate) fn deserialize_bounded_string_map<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, String>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_map(BoundedStringMapVisitor::<MAX_RESPONSE_STRINGS>)
}

#[allow(dead_code)]
pub(crate) fn deserialize_optional_bounded_string_map<'de, D>(
    deserializer: D,
) -> core::result::Result<Option<BTreeMap<String, String>>, D::Error>
where
    D: Deserializer<'de>,
{
    Option::<BoundedStringMap>::deserialize(deserializer).map(|value| value.map(|value| value.0))
}

#[allow(dead_code)]
pub(crate) fn deserialize_bounded_string_map_or_default<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, String>, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Option::<BoundedStringMap>::deserialize(deserializer)?
        .map(|value| value.0)
        .unwrap_or_default())
}

#[derive(Deserialize)]
struct BoundedStringList(#[serde(deserialize_with = "deserialize_bounded_string_vec")] Vec<String>);

#[derive(Deserialize)]
#[allow(dead_code)]
struct BoundedStringMap(
    #[serde(deserialize_with = "deserialize_bounded_string_map")] BTreeMap<String, String>,
);

#[allow(dead_code)]
pub(crate) fn deserialize_bounded_secret_string_vec<'de, D>(
    deserializer: D,
) -> core::result::Result<Vec<SecretString>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_seq(BoundedSecretStringListVisitor::<MAX_RESPONSE_STRINGS>)
}

struct BoundedStringListVisitor<const MAX: usize>;

impl<'de, const MAX: usize> Visitor<'de> for BoundedStringListVisitor<MAX> {
    type Value = Vec<String>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "a list of at most {MAX} strings")
    }

    fn visit_seq<A>(self, mut seq: A) -> core::result::Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut values = Vec::new();
        while values.len() < MAX {
            let Some(value) = seq.next_element::<String>()? else {
                return Ok(values);
            };
            values.push(value);
        }
        if seq.next_element::<IgnoredAny>()?.is_some() {
            return Err(A::Error::custom("OpenBao string list exceeds item limit"));
        }
        Ok(values)
    }
}

#[allow(dead_code)]
struct BoundedStringMapVisitor<const MAX: usize>;

impl<'de, const MAX: usize> Visitor<'de> for BoundedStringMapVisitor<MAX> {
    type Value = BTreeMap<String, String>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "a map of at most {MAX} string pairs")
    }

    fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut values = BTreeMap::new();
        while values.len() < MAX {
            let Some((key, value)) = map.next_entry::<String, String>()? else {
                return Ok(values);
            };
            values.insert(key, value);
        }
        if map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {
            return Err(A::Error::custom("OpenBao string map exceeds item limit"));
        }
        Ok(values)
    }
}

#[allow(dead_code)]
struct BoundedSecretStringListVisitor<const MAX: usize>;

impl<'de, const MAX: usize> Visitor<'de> for BoundedSecretStringListVisitor<MAX> {
    type Value = Vec<SecretString>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "a list of at most {MAX} secret strings")
    }

    fn visit_seq<A>(self, mut seq: A) -> core::result::Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut values = Vec::new();
        while values.len() < MAX {
            let Some(value) = seq.next_element::<String>()? else {
                return Ok(values);
            };
            values.push(SecretString::from(value));
        }
        if seq.next_element::<IgnoredAny>()?.is_some() {
            return Err(A::Error::custom(
                "OpenBao secret string list exceeds item limit",
            ));
        }
        Ok(values)
    }
}

#[derive(Debug, Deserialize)]
pub(crate) struct ErrorEnvelope {
    #[serde(default, deserialize_with = "deserialize_error_list")]
    pub(crate) errors: Vec<String>,
}

fn deserialize_error_list<'de, D>(deserializer: D) -> core::result::Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_seq(ErrorListVisitor)
}

struct ErrorListVisitor;

impl<'de> Visitor<'de> for ErrorListVisitor {
    type Value = Vec<String>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a bounded list of OpenBao API errors")
    }

    fn visit_seq<A>(self, mut seq: A) -> core::result::Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut errors = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(MAX_API_ERRORS));
        while errors.len() < MAX_API_ERRORS {
            let Some(error) = seq.next_element::<String>()? else {
                return Ok(errors);
            };
            errors.push(error);
        }
        while seq.next_element::<IgnoredAny>()?.is_some() {}
        Ok(errors)
    }
}

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

    use secrecy::SecretString;

    use super::{ListEntries, ResponseEnvelope};

    #[test]
    fn response_debug_redacts_lease_id() {
        let envelope = ResponseEnvelope {
            data: "ok",
            lease_id: SecretString::from("secret-lease"),
            lease_duration: 30,
            renewable: true,
            warnings: None,
            wrap_info: None,
        };

        let debug = format!("{envelope:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("secret-lease"));
    }

    #[test]
    fn response_debug_redacts_wrap_info() {
        let envelope = ResponseEnvelope {
            data: "ok",
            lease_id: SecretString::from(""),
            lease_duration: 0,
            renewable: false,
            warnings: None,
            wrap_info: Some(super::WrapInfo {
                token: SecretString::from("wrap-token"),
                accessor: Some(SecretString::from("wrap-accessor")),
                ttl: 60,
                creation_time: None,
                creation_path: None,
            }),
        };

        let debug = format!("{envelope:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("wrap-token"));
        assert!(!debug.contains("wrap-accessor"));
    }

    #[test]
    fn error_envelope_caps_error_count() {
        let json = format!(
            r#"{{"errors":[{}]}}"#,
            (0..32)
                .map(|index| format!(r#""error-{index}""#))
                .collect::<Vec<_>>()
                .join(",")
        );

        let envelope: super::ErrorEnvelope =
            serde_json::from_str(&json).unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(envelope.errors.len(), 16);
        assert_eq!(envelope.errors[15], "error-15");
    }

    #[test]
    fn response_warnings_are_bounded() {
        let mut warnings = Vec::new();
        for index in 0..=super::MAX_RESPONSE_STRINGS {
            warnings.push(format!("warning-{index}"));
        }
        let value = serde_json::json!({ "data": "ok", "warnings": warnings });
        let error = match serde_json::from_value::<ResponseEnvelope<String>>(value) {
            Ok(_) => panic!("oversized warning list unexpectedly decoded"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("exceeds item limit"));
    }

    #[test]
    #[cfg(all(feature = "kv2", feature = "ssh", feature = "sys"))]
    fn list_entries_trait_covers_common_primary_fields() {
        let kv = crate::secrets::kv2::Kv2List {
            keys: vec!["app/".to_owned(), "db".to_owned()],
        };
        let ssh = crate::secrets::ssh::SshRoleList {
            roles: vec!["admin".to_owned()],
        };
        let policies = crate::sys::PolicyList {
            policies: vec!["default".to_owned()],
        };

        assert_eq!(kv.len(), 2);
        assert!(kv.contains("db"));
        assert_eq!(ssh.entries(), ["admin"]);
        assert_eq!(policies.iter().next().map(String::as_str), Some("default"));
    }
}