bibby 0.2.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
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
//! Client and types for **Bytebury Vault** (`https://api.bytebury.com/vault/v1`).
//!
//! Store encrypted project secrets by environment, import and export `.env`
//! files, inspect and restore secret versions, and create burn-after-reading
//! one-time share links.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::client::Bibby;
use crate::error::Result;
use crate::pagination::{Page, PageParams};

const PRODUCT: &str = "vault";

/// Client for **Bytebury Vault**.
///
/// Obtained via [`Bibby::vault`].
#[derive(Debug, Clone, Copy)]
pub struct VaultClient<'a> {
    client: &'a Bibby,
}

impl<'a> VaultClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    // -------------------------------------------------------------------------
    // Projects
    // -------------------------------------------------------------------------

    /// Lists Vault projects in your account.
    ///
    /// Calls `GET /vault/v1/projects`.
    pub async fn list_projects(&self, params: &PageParams) -> Result<Page<VaultProject>> {
        self.client
            .get_json_query(PRODUCT, "projects", params)
            .await
    }

    /// Creates a new Vault project.
    ///
    /// Calls `POST /vault/v1/projects`.
    pub async fn create_project(&self, request: &CreateProjectRequest) -> Result<VaultProject> {
        self.client.post_json(PRODUCT, "projects", request).await
    }

    /// Fetches a Vault project by ID.
    ///
    /// Calls `GET /vault/v1/projects/{id}`.
    pub async fn get_project(&self, id: i64) -> Result<VaultProject> {
        self.client
            .get_json(PRODUCT, &format!("projects/{id}"))
            .await
    }

    /// Updates a Vault project's name or description.
    ///
    /// Calls `PATCH /vault/v1/projects/{id}`.
    pub async fn update_project(
        &self,
        id: i64,
        changes: &UpdateProjectRequest,
    ) -> Result<VaultProject> {
        self.client
            .patch_json(PRODUCT, &format!("projects/{id}"), changes)
            .await
    }

    /// Permanently deletes a Vault project and all of its secrets.
    ///
    /// Calls `DELETE /vault/v1/projects/{id}`.
    pub async fn delete_project(&self, id: i64) -> Result<()> {
        self.client
            .delete_unit(PRODUCT, &format!("projects/{id}"))
            .await
    }

    /// Lists environment names present in a project (e.g. `["development", "production"]`).
    ///
    /// Calls `GET /vault/v1/projects/{id}/environments`.
    pub async fn list_environments(&self, project_id: i64) -> Result<Vec<String>> {
        self.client
            .get_json(PRODUCT, &format!("projects/{project_id}/environments"))
            .await
    }

    // -------------------------------------------------------------------------
    // Secrets, Versions, Import & Export
    // -------------------------------------------------------------------------

    /// Lists secret metadata (never plaintext values) in a project.
    ///
    /// Calls `GET /vault/v1/projects/{project_id}/secrets`.
    pub async fn list_secrets(
        &self,
        project_id: i64,
        params: &ListSecretsParams,
    ) -> Result<Page<SecretMeta>> {
        self.client
            .get_json_query(PRODUCT, &format!("projects/{project_id}/secrets"), params)
            .await
    }

    /// Creates or updates (upserts) a secret in an environment, incrementing its version.
    ///
    /// Calls `POST /vault/v1/projects/{project_id}/secrets`.
    pub async fn set_secret(
        &self,
        project_id: i64,
        request: &SetSecretRequest,
    ) -> Result<SecretMeta> {
        self.client
            .post_json(PRODUCT, &format!("projects/{project_id}/secrets"), request)
            .await
    }

    /// Bulk-imports secrets from `.env` formatted text into an environment.
    ///
    /// Calls `POST /vault/v1/projects/{project_id}/secrets/import`.
    pub async fn import_dotenv(
        &self,
        project_id: i64,
        environment: &str,
        dotenv: &str,
    ) -> Result<ImportSummary> {
        #[derive(Serialize)]
        struct Body<'a> {
            environment: &'a str,
            dotenv: &'a str,
        }
        self.client
            .post_json(
                PRODUCT,
                &format!("projects/{project_id}/secrets/import"),
                &Body {
                    environment,
                    dotenv,
                },
            )
            .await
    }

    /// Exports all secrets for an environment as raw `.env` text.
    ///
    /// Calls `GET /vault/v1/projects/{project_id}/export?environment=...&format=dotenv`.
    pub async fn export_dotenv(
        &self,
        project_id: i64,
        environment: Option<&str>,
    ) -> Result<String> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            environment: Option<&'a str>,
            format: &'static str,
        }
        self.client
            .get_text_query(
                PRODUCT,
                &format!("projects/{project_id}/export"),
                &Query {
                    environment,
                    format: "dotenv",
                },
            )
            .await
    }

    /// Exports all secrets for an environment as structured JSON (including a
    /// `BTreeMap<String, String>` and `.env` string).
    ///
    /// Calls `GET /vault/v1/projects/{project_id}/export?environment=...&format=json`.
    pub async fn export_json(
        &self,
        project_id: i64,
        environment: Option<&str>,
    ) -> Result<ExportedSecrets> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            environment: Option<&'a str>,
            format: &'static str,
        }
        self.client
            .get_json_query(
                PRODUCT,
                &format!("projects/{project_id}/export"),
                &Query {
                    environment,
                    format: "json",
                },
            )
            .await
    }

    /// Decrypts and returns a secret's plaintext value.
    ///
    /// Calls `GET /vault/v1/projects/{project_id}/secrets/{secret_id}/reveal`.
    pub async fn reveal_secret(&self, project_id: i64, secret_id: i64) -> Result<RevealedSecret> {
        self.client
            .get_json(
                PRODUCT,
                &format!("projects/{project_id}/secrets/{secret_id}/reveal"),
            )
            .await
    }

    /// Lists historical version metadata for a secret.
    ///
    /// Calls `GET /vault/v1/projects/{project_id}/secrets/{secret_id}/versions`.
    pub async fn list_versions(
        &self,
        project_id: i64,
        secret_id: i64,
    ) -> Result<Vec<SecretVersion>> {
        self.client
            .get_json(
                PRODUCT,
                &format!("projects/{project_id}/secrets/{secret_id}/versions"),
            )
            .await
    }

    /// Restores a previous version of a secret as the new latest version.
    ///
    /// Calls `POST /vault/v1/projects/{project_id}/secrets/{secret_id}/versions/{version}/restore`.
    pub async fn restore_version(
        &self,
        project_id: i64,
        secret_id: i64,
        version: i32,
    ) -> Result<SecretMeta> {
        self.client
            .post_empty(
                PRODUCT,
                &format!("projects/{project_id}/secrets/{secret_id}/versions/{version}/restore"),
            )
            .await
    }

    /// Permanently deletes a secret from a project.
    ///
    /// Calls `DELETE /vault/v1/projects/{project_id}/secrets/{secret_id}`.
    pub async fn delete_secret(&self, project_id: i64, secret_id: i64) -> Result<()> {
        self.client
            .delete_unit(
                PRODUCT,
                &format!("projects/{project_id}/secrets/{secret_id}"),
            )
            .await
    }

    // -------------------------------------------------------------------------
    // Burn-After-Reading Share Links
    // -------------------------------------------------------------------------

    /// Lists active burn-after-reading share links in your account.
    ///
    /// Calls `GET /vault/v1/shares`.
    pub async fn list_shares(&self, params: &PageParams) -> Result<Page<ShareMeta>> {
        self.client.get_json_query(PRODUCT, "shares", params).await
    }

    /// Creates a new burn-after-reading encrypted share link.
    ///
    /// Calls `POST /vault/v1/shares`.
    pub async fn create_share(&self, request: &CreateShareRequest) -> Result<ShareMeta> {
        self.client.post_json(PRODUCT, "shares", request).await
    }

    /// Revokes and deletes a share link immediately.
    ///
    /// Calls `DELETE /vault/v1/shares/{id}`.
    pub async fn delete_share(&self, id: i64) -> Result<()> {
        self.client
            .delete_unit(PRODUCT, &format!("shares/{id}"))
            .await
    }
}

/// Request body for [`VaultClient::create_project`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateProjectRequest {
    /// Project name.
    pub name: String,
    /// Optional project description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl CreateProjectRequest {
    /// Creates a new project request with the given `name`.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
        }
    }

    /// Sets an optional description.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Request body for [`VaultClient::update_project`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateProjectRequest {
    /// Updated project name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Updated description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// A Bytebury Vault project.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VaultProject {
    /// Project ID.
    pub id: i64,
    /// Project name.
    pub name: String,
    /// Optional description.
    pub description: Option<String>,
    /// Total number of secrets across all environments.
    pub secret_count: i64,
    /// RFC 3339 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
}

/// Query parameters for [`VaultClient::list_secrets`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListSecretsParams {
    /// Filter by environment name (e.g. `"production"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    /// Substring search filter on secret key names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// Request body for [`VaultClient::set_secret`].
#[derive(Debug, Clone, Serialize)]
pub struct SetSecretRequest {
    /// Target environment (e.g. `"production"`, `"staging"`, `"development"`).
    pub environment: String,
    /// Secret key name (e.g. `"DATABASE_URL"`).
    pub key: String,
    /// Secret plaintext value (encrypted at rest by Vault).
    pub value: String,
}

impl SetSecretRequest {
    /// Creates a new upsert-secret request.
    pub fn new(
        environment: impl Into<String>,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        Self {
            environment: environment.into(),
            key: key.into(),
            value: value.into(),
        }
    }
}

/// Metadata for a stored secret (never includes the plaintext value).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecretMeta {
    /// Secret ID.
    pub id: i64,
    /// Parent project ID.
    pub project_id: i64,
    /// Environment name.
    #[serde(default)]
    pub environment: String,
    /// Secret key name.
    pub key: String,
    /// Current version number.
    pub version: i32,
    /// RFC 3339 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
}

/// Decrypted secret returned by [`VaultClient::reveal_secret`].
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RevealedSecret {
    /// Secret ID.
    #[serde(default)]
    pub id: i64,
    /// Parent project ID.
    pub project_id: i64,
    /// Environment name.
    pub environment: String,
    /// Secret key name.
    pub key: String,
    /// Decrypted plaintext value.
    pub value: String,
    /// Version number.
    pub version: i32,
    /// RFC 3339 last-update timestamp.
    #[serde(default)]
    pub updated_at: Option<String>,
}

impl std::fmt::Debug for RevealedSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RevealedSecret")
            .field("id", &self.id)
            .field("project_id", &self.project_id)
            .field("environment", &self.environment)
            .field("key", &self.key)
            .field("value", &"***")
            .field("version", &self.version)
            .field("updated_at", &self.updated_at)
            .finish()
    }
}

/// Version metadata entry returned by [`VaultClient::list_versions`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecretVersion {
    /// Version row ID.
    #[serde(default)]
    pub id: i64,
    /// Parent secret ID.
    #[serde(default)]
    pub secret_id: i64,
    /// Version number.
    pub version: i32,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
}

/// Result of [`VaultClient::import_dotenv`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportSummary {
    /// Target environment.
    pub environment: String,
    /// Total number of secrets imported.
    pub imported: usize,
    /// Number of newly created secrets.
    pub created: usize,
    /// Number of existing secrets updated.
    pub updated: usize,
}

/// Structured export returned by [`VaultClient::export_json`].
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExportedSecrets {
    /// Project ID.
    pub project_id: i64,
    /// Project name.
    pub project_name: String,
    /// Exported environment name.
    pub environment: String,
    /// Export format (`"json"`).
    pub format: String,
    /// Rendered `.env` text.
    pub dotenv: String,
    /// Key-value map of decrypted secrets.
    pub secrets: BTreeMap<String, String>,
}

impl std::fmt::Debug for ExportedSecrets {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExportedSecrets")
            .field("project_id", &self.project_id)
            .field("project_name", &self.project_name)
            .field("environment", &self.environment)
            .field("secret_count", &self.secrets.len())
            .finish()
    }
}

/// Request body for [`VaultClient::create_share`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateShareRequest {
    /// Secret text to encrypt and share.
    pub secret: String,
    /// Optional human-readable label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Optional passphrase required to reveal the share.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub passphrase: Option<String>,
    /// Maximum views before burning (`1..=10`, default `1`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_views: Option<i32>,
    /// Expiration time-to-live in minutes (`5..=10080`, default `1440`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl_minutes: Option<i64>,
}

impl CreateShareRequest {
    /// Creates a burn-after-reading share request for `secret`.
    pub fn new(secret: impl Into<String>) -> Self {
        Self {
            secret: secret.into(),
            label: None,
            passphrase: None,
            max_views: None,
            ttl_minutes: None,
        }
    }

    /// Sets a display label.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Requires a passphrase to reveal the share.
    pub fn passphrase(mut self, passphrase: impl Into<String>) -> Self {
        self.passphrase = Some(passphrase.into());
        self
    }

    /// Sets maximum view count (`1..=10`).
    pub fn max_views(mut self, max_views: i32) -> Self {
        self.max_views = Some(max_views);
        self
    }

    /// Sets expiration TTL in minutes (`5..=10080`).
    pub fn ttl_minutes(mut self, minutes: i64) -> Self {
        self.ttl_minutes = Some(minutes);
        self
    }
}

/// Metadata for a burn-after-reading share link.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareMeta {
    /// Share ID.
    pub id: i64,
    /// Public share token.
    pub token: String,
    /// Optional display label.
    pub label: Option<String>,
    /// Whether a passphrase is required to reveal it.
    pub has_passphrase: bool,
    /// Maximum allowed views.
    pub max_views: i32,
    /// Number of views used so far.
    pub view_count: i32,
    /// RFC 3339 expiration timestamp.
    pub expires_at: String,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
    /// RFC 3339 timestamp of the last view, if any.
    #[serde(default)]
    pub last_viewed_at: Option<String>,
}

impl ShareMeta {
    /// Returns the public share URL (`https://bytebury.com/vault/s/{token}`).
    pub fn share_url(&self) -> String {
        format!("https://bytebury.com/vault/s/{}", self.token)
    }
}