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
//! Token auth method lifecycle helpers.

use std::collections::BTreeMap;

use reqwest::Method;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};

use crate::{
    Authenticated, Client, Error, Result,
    response::{
        Empty, ResponseEnvelope, deserialize_bounded_secret_string_vec,
        deserialize_bounded_string_map_or_default, deserialize_bounded_string_vec,
    },
};

/// Handle for the built-in token auth method.
#[derive(Debug)]
pub struct Token<'a> {
    client: &'a Client<Authenticated>,
}

/// Options for creating a child token.
#[derive(Clone, Default, Serialize)]
pub struct TokenCreateRequest {
    /// Policies attached to the token.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub policies: Vec<String>,
    /// Metadata stored with the token.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub meta: BTreeMap<String, String>,
    /// Human-readable display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Requested TTL such as `30m`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,
    /// Explicit max TTL such as `2h`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub explicit_max_ttl: Option<String>,
    /// Periodic token period such as `1h`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<String>,
    /// Maximum number of uses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_uses: Option<u64>,
    /// Whether the token is renewable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub renewable: Option<bool>,
    /// Create an orphan token without a parent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_parent: Option<bool>,
    /// Do not attach the default policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_default_policy: Option<bool>,
    /// OpenBao token type, such as `service` or `batch`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_type: Option<String>,
}

impl TokenCreateRequest {
    /// Sets the policies attached to the created token.
    #[must_use]
    pub fn with_policies<I, P>(mut self, policies: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<String>,
    {
        self.policies = policies.into_iter().map(Into::into).collect();
        self
    }

    /// Omits OpenBao's default policy from the created token.
    #[must_use]
    pub fn without_default_policy(mut self) -> Self {
        self.no_default_policy = Some(true);
        self
    }

    /// Sets the requested token TTL after validating OpenBao duration syntax.
    pub fn with_ttl(mut self, ttl: impl Into<String>) -> Result<Self> {
        let ttl = ttl.into();
        crate::validation::validate_duration_parameter(&ttl, "token ttl")?;
        self.ttl = Some(ttl);
        Ok(self)
    }

    /// Sets the requested explicit maximum TTL after validating duration syntax.
    pub fn with_explicit_max_ttl(mut self, explicit_max_ttl: impl Into<String>) -> Result<Self> {
        let explicit_max_ttl = explicit_max_ttl.into();
        crate::validation::validate_duration_parameter(
            &explicit_max_ttl,
            "token explicit_max_ttl",
        )?;
        self.explicit_max_ttl = Some(explicit_max_ttl);
        Ok(self)
    }

    /// Sets the requested periodic token period after validating duration syntax.
    pub fn with_period(mut self, period: impl Into<String>) -> Result<Self> {
        let period = period.into();
        crate::validation::validate_duration_parameter(&period, "token period")?;
        self.period = Some(period);
        Ok(self)
    }

    fn validate(&self) -> Result<()> {
        if let Some(ttl) = &self.ttl {
            crate::validation::validate_duration_parameter(ttl, "token ttl")?;
        }
        if let Some(explicit_max_ttl) = &self.explicit_max_ttl {
            crate::validation::validate_duration_parameter(
                explicit_max_ttl,
                "token explicit_max_ttl",
            )?;
        }
        if let Some(period) = &self.period {
            crate::validation::validate_duration_parameter(period, "token period")?;
        }
        Ok(())
    }
}

/// Result of creating or renewing a token.
#[derive(Debug, Deserialize)]
pub struct TokenAuth {
    /// Client token returned by OpenBao.
    pub client_token: SecretString,
    /// Token accessor returned by OpenBao.
    pub accessor: SecretString,
    /// Policies attached to the token.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub policies: Vec<String>,
    /// Token policies attached to the token.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub token_policies: Vec<String>,
    /// Token metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    pub metadata: BTreeMap<String, String>,
    /// Lease duration in seconds.
    #[serde(default)]
    pub lease_duration: u64,
    /// Whether the token is renewable.
    #[serde(default)]
    pub renewable: bool,
    /// Entity identifier, when present.
    #[serde(default)]
    pub entity_id: Option<String>,
    /// Token type, when present.
    #[serde(default)]
    pub token_type: Option<String>,
    /// Whether the token is orphaned.
    #[serde(default)]
    pub orphan: bool,
}

/// Token lookup metadata returned by OpenBao.
#[derive(Clone, Debug, Deserialize)]
pub struct TokenInfo {
    /// Token accessor, treated as secret material.
    #[serde(default)]
    pub accessor: Option<SecretString>,
    /// Token ID, when OpenBao returns one.
    #[serde(default)]
    pub id: Option<SecretString>,
    /// Display name.
    #[serde(default)]
    pub display_name: Option<String>,
    /// Entity identifier.
    #[serde(default)]
    pub entity_id: Option<String>,
    /// Creation path.
    #[serde(default)]
    pub path: Option<String>,
    /// Creation time as a Unix timestamp.
    #[serde(default)]
    pub creation_time: Option<u64>,
    /// Creation TTL in seconds.
    #[serde(default)]
    pub creation_ttl: Option<u64>,
    /// Current TTL in seconds.
    #[serde(default)]
    pub ttl: Option<u64>,
    /// Expiration time, when present.
    #[serde(default)]
    pub expire_time: Option<String>,
    /// Explicit max TTL in seconds.
    #[serde(default)]
    pub explicit_max_ttl: Option<u64>,
    /// Number of uses remaining.
    #[serde(default)]
    pub num_uses: Option<u64>,
    /// Whether the token is orphaned.
    #[serde(default)]
    pub orphan: bool,
    /// Whether the token is renewable.
    #[serde(default)]
    pub renewable: bool,
    /// Attached policies.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub policies: Vec<String>,
    /// Identity policies.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub identity_policies: Vec<String>,
    /// Token metadata.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    pub meta: BTreeMap<String, String>,
    /// Token type.
    #[serde(default)]
    pub token_type: Option<String>,
}

/// Token accessor list response.
#[derive(Clone, Debug, Deserialize)]
pub struct TokenAccessorList {
    /// Token accessors. Accessors can revoke tokens, so keep them secret.
    #[serde(default, deserialize_with = "deserialize_bounded_secret_string_vec")]
    pub keys: Vec<SecretString>,
}

#[derive(Deserialize)]
struct TokenAuthEnvelope {
    auth: Option<TokenAuth>,
}

#[derive(Serialize)]
struct TokenPayload<'a> {
    token: &'a str,
}

#[derive(Serialize)]
struct AccessorPayload<'a> {
    accessor: &'a str,
}

#[derive(Serialize)]
struct RenewPayload<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    token: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    increment: Option<&'a str>,
}

impl Client<Authenticated> {
    /// Accesses token lifecycle helpers.
    pub fn token(&self) -> Token<'_> {
        Token { client: self }
    }
}

impl Token<'_> {
    /// Creates a child token.
    pub async fn create(&self, request: &TokenCreateRequest) -> Result<TokenAuth> {
        self.create_at(None, request).await
    }

    /// Creates a token using an OpenBao token role.
    pub async fn create_at(
        &self,
        role_name: Option<&str>,
        request: &TokenCreateRequest,
    ) -> Result<TokenAuth> {
        request.validate()?;
        let path = match role_name {
            Some(role_name) => {
                let role_name = crate::path::validate_mount_path(role_name)?.join("/");
                format!("auth/token/create/{role_name}")
            }
            None => "auth/token/create".to_owned(),
        };
        let envelope: TokenAuthEnvelope = self
            .client
            .request_json(Method::POST, &path, Some(request))
            .await?;
        envelope.auth.ok_or(Error::MissingField("auth"))
    }

    /// Looks up the caller's token.
    pub async fn lookup_self(&self) -> Result<TokenInfo> {
        let envelope: ResponseEnvelope<TokenInfo> = self
            .client
            .request_json(
                Method::POST,
                "auth/token/lookup-self",
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Looks up a token value.
    pub async fn lookup(&self, token: &SecretString) -> Result<TokenInfo> {
        let payload = TokenPayload {
            token: token.expose_secret(),
        };
        let envelope: ResponseEnvelope<TokenInfo> = self
            .client
            .request_json(Method::POST, "auth/token/lookup", Some(&payload))
            .await?;
        Ok(envelope.data)
    }

    /// Looks up a token accessor.
    pub async fn lookup_accessor(&self, accessor: &SecretString) -> Result<TokenInfo> {
        let payload = AccessorPayload {
            accessor: accessor.expose_secret(),
        };
        let envelope: ResponseEnvelope<TokenInfo> = self
            .client
            .request_json(Method::POST, "auth/token/lookup-accessor", Some(&payload))
            .await?;
        Ok(envelope.data)
    }

    /// Lists token accessors. This requires tightly controlled sudo capability.
    pub async fn list_accessors(&self) -> Result<TokenAccessorList> {
        let method =
            Method::from_bytes(b"LIST").map_err(|error| Error::InvalidHeader(error.to_string()))?;
        let envelope: ResponseEnvelope<TokenAccessorList> = self
            .client
            .request_json(method, "auth/token/accessors", Option::<&Empty>::None)
            .await?;
        Ok(envelope.data)
    }

    /// Renews the caller's token.
    pub async fn renew_self(&self, increment: Option<&str>) -> Result<TokenAuth> {
        validate_renew_increment(increment)?;
        let payload = RenewPayload {
            token: None,
            increment,
        };
        let envelope: TokenAuthEnvelope = self
            .client
            .request_json(Method::POST, "auth/token/renew-self", Some(&payload))
            .await?;
        envelope.auth.ok_or(Error::MissingField("auth"))
    }

    /// Renews a token value.
    pub async fn renew(&self, token: &SecretString, increment: Option<&str>) -> Result<TokenAuth> {
        validate_renew_increment(increment)?;
        let payload = RenewPayload {
            token: Some(token.expose_secret()),
            increment,
        };
        let envelope: TokenAuthEnvelope = self
            .client
            .request_json(Method::POST, "auth/token/renew", Some(&payload))
            .await?;
        envelope.auth.ok_or(Error::MissingField("auth"))
    }

    /// Revokes a token and its child tokens.
    pub async fn revoke(&self, token: &SecretString) -> Result<Empty> {
        let payload = TokenPayload {
            token: token.expose_secret(),
        };
        self.client
            .request_json(Method::POST, "auth/token/revoke", Some(&payload))
            .await
    }

    /// Revokes the caller's token and its child tokens.
    pub async fn revoke_self(&self) -> Result<Empty> {
        self.client
            .request_json(
                Method::POST,
                "auth/token/revoke-self",
                Option::<&Empty>::None,
            )
            .await
    }

    /// Revokes the token associated with an accessor.
    pub async fn revoke_accessor(&self, accessor: &SecretString) -> Result<Empty> {
        let payload = AccessorPayload {
            accessor: accessor.expose_secret(),
        };
        self.client
            .request_json(Method::POST, "auth/token/revoke-accessor", Some(&payload))
            .await
    }
}

fn validate_renew_increment(increment: Option<&str>) -> Result<()> {
    if let Some(increment) = increment {
        crate::validation::validate_duration_parameter(increment, "token renewal increment")?;
    }
    Ok(())
}

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

    use crate::response::ResponseEnvelope;

    use super::{TokenAccessorList, TokenCreateRequest, TokenInfo, validate_renew_increment};

    #[test]
    fn token_ttl_rejects_negative_values() {
        let error = match serde_json::from_str::<ResponseEnvelope<TokenInfo>>(
            r#"{"data":{"ttl":-1,"policies":[]}}"#,
        ) {
            Ok(_) => panic!("negative ttl unexpectedly decoded"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("invalid value"));
    }

    #[test]
    fn token_create_duration_fields_are_validated() {
        let request = TokenCreateRequest::default()
            .with_policies(["app-read", "infra-common"])
            .without_default_policy()
            .with_ttl("30m")
            .unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(request.policies, ["app-read", "infra-common"]);
        assert_eq!(request.no_default_policy, Some(true));
        assert!(TokenCreateRequest::default().with_ttl("never").is_err());
        assert!(TokenCreateRequest::default().with_ttl("1h\r\nbad").is_err());
        assert!(
            TokenCreateRequest::default()
                .with_explicit_max_ttl("1h")
                .is_ok()
        );
        assert!(TokenCreateRequest::default().with_period("60s").is_ok());
        assert!(validate_renew_increment(Some("30m")).is_ok());
        assert!(validate_renew_increment(Some("1 hour")).is_err());
    }

    #[test]
    fn token_accessor_list_is_bounded() {
        let mut keys = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            keys.push(format!("accessor-{index}"));
        }
        let value = serde_json::json!({ "keys": keys });
        let error = match serde_json::from_value::<TokenAccessorList>(value) {
            Ok(_) => panic!("oversized accessor list unexpectedly decoded"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("exceeds item limit"));
    }
}