deepgram 0.13.0

Community Rust SDK for Deepgram's automated speech recognition APIs.
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
//! Response types for the self-hosted distribution credentials endpoints.

use std::fmt;

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::Scope;

/// Success message.
///
/// Returned by
/// [`SelfHosted::delete_distribution_credentials`](super::SelfHosted::delete_distribution_credentials).
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Message {
    /// The server's confirmation text, for example
    /// `"Successfully deleted the distribution credentials!"`. Intended for
    /// humans; do not match on it.
    pub message: String,
}

/// A list of distribution credentials for a project.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DistributionCredentialsList {
    /// The distribution credentials, each with its associated member.
    #[serde(default)]
    pub distribution_credentials: Vec<DistributionCredentialsEntry>,
}

/// A single set of distribution credentials together with the member that owns
/// them.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DistributionCredentialsEntry {
    /// The project member who created the credentials, and to whom the API
    /// attributes them.
    pub member: Member,

    /// The credentials themselves, without the registry `username` and
    /// `secret` — those are returned only once, by
    /// [`SelfHosted::create_distribution_credentials`](super::SelfHosted::create_distribution_credentials).
    pub distribution_credentials: DistributionCredentials,
}

/// The member associated with a set of distribution credentials.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Member {
    /// The member's id within the project, the same value the
    /// [`members`](crate::manage::members) endpoints use.
    pub member_id: Uuid,

    /// The email address the member signs in with.
    pub email: String,
}

/// A set of self-hosted distribution credentials, as returned by the list and
/// get endpoints.
///
/// The registry `username` and `secret` are only ever returned by the create
/// endpoint (see [`CreatedDistributionCredentials`]); they cannot be retrieved
/// again afterwards.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DistributionCredentials {
    /// Identifies this set of credentials. Pass it to
    /// [`SelfHosted::get_distribution_credentials`](super::SelfHosted::get_distribution_credentials)
    /// or
    /// [`SelfHosted::delete_distribution_credentials`](super::SelfHosted::delete_distribution_credentials).
    pub distribution_credentials_id: Uuid,

    /// The provider of the distribution service (e.g. `quay`).
    pub provider: String,

    /// A comment describing the credentials.
    pub comment: Option<String>,

    /// The permission scopes granted to the credentials, deciding which
    /// container images they may pull. Each scope is listed under both its
    /// `self-hosted:` and `onprem:` prefixes, so each named variant typically
    /// appears twice (see [`Scope`]). A scope this version of the SDK does
    /// not name arrives as [`Scope::Unknown`].
    #[serde(default)]
    pub scopes: Vec<Scope>,

    /// Tags attached to the credentials. The server omits this field when it
    /// is empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,

    /// The timestamp when the credentials were created.
    pub created: String,
}

/// A freshly created set of self-hosted distribution credentials.
///
/// Returned by
/// [`SelfHosted::create_distribution_credentials`](super::SelfHosted::create_distribution_credentials).
/// Unlike the list and get responses, this is a bare credentials object (no
/// `member` wrapper) and it carries the registry `username` and `secret`.
///
/// **The `secret` is shown exactly once.** It cannot be retrieved again through
/// the API or the Console, so store it securely as soon as it is returned. The
/// secret is wrapped in a [`SecretString`], whose `Debug` output is redacted;
/// read it with [`SecretString::expose_secret`].
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CreatedDistributionCredentials {
    /// Identifies this set of credentials. Pass it to
    /// [`SelfHosted::get_distribution_credentials`](super::SelfHosted::get_distribution_credentials)
    /// or
    /// [`SelfHosted::delete_distribution_credentials`](super::SelfHosted::delete_distribution_credentials).
    pub distribution_credentials_id: Uuid,

    /// The provider of the distribution service (e.g. `quay`).
    pub provider: String,

    /// The registry username to log in with (for example `deepgram+<id>`).
    /// Only returned on create.
    pub username: String,

    /// The registry password to log in with. Only returned on create, and
    /// never retrievable again.
    pub secret: SecretString,

    /// A comment describing the credentials.
    pub comment: Option<String>,

    /// The permission scopes granted to the credentials, deciding which
    /// container images they may pull. This is the expanded list the server
    /// granted, not the request as sent: [`Scope::Products`] never appears,
    /// and each scope is listed under both its `self-hosted:` and `onprem:`
    /// prefixes, so each named variant typically appears twice (see
    /// [`Scope`]). A scope this version of the SDK does not name arrives as
    /// [`Scope::Unknown`].
    #[serde(default)]
    pub scopes: Vec<Scope>,

    /// Tags attached to the credentials. The server omits this field when it
    /// is empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,

    /// The timestamp when the credentials were created.
    pub created: String,
}

/// A string that holds a secret and redacts itself when formatted with
/// `Debug`, so that a `{:?}` of a response (for example in a `tracing` field)
/// never writes the secret to a log.
///
/// Read the value explicitly with [`expose_secret`](Self::expose_secret).
/// `Serialize` writes the real value, so the secret survives a round-trip
/// through `serde_json` for callers who persist it deliberately.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SecretString(String);

impl SecretString {
    /// Wrap a secret.
    pub fn new(secret: impl Into<String>) -> Self {
        Self(secret.into())
    }

    /// Return the wrapped secret.
    pub fn expose_secret(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper and return the wrapped secret.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl fmt::Debug for SecretString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("***")
    }
}

impl From<String> for SecretString {
    fn from(secret: String) -> Self {
        Self(secret)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CreatedDistributionCredentials, DistributionCredentialsEntry, DistributionCredentialsList,
        Message, Scope, SecretString,
    };

    #[test]
    fn deserializes_documented_response() {
        // Shape from the Deepgram Self-Hosted API docs.
        let json = serde_json::json!({
            "distribution_credentials": [{
                "member": {
                    "member_id": "3376abcd-8e5e-49d3-92d4-876d3a4f0363",
                    "email": "email@example.com"
                },
                "distribution_credentials": {
                    "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
                    "provider": "quay",
                    "scopes": ["self-hosted:product:api", "self-hosted:product:engine"],
                    "created": "2023-06-28T15:36:59.609841Z",
                    "comment": "My Self-Hosted Distribution Credentials"
                }
            }]
        });

        let list: DistributionCredentialsList = serde_json::from_value(json).unwrap();
        assert_eq!(list.distribution_credentials.len(), 1);
        let entry = &list.distribution_credentials[0];
        assert_eq!(entry.member.email, "email@example.com");
        assert_eq!(entry.distribution_credentials.provider, "quay");
        assert_eq!(
            entry.distribution_credentials.scopes,
            [Scope::Api, Scope::Engine]
        );
        assert_eq!(
            entry.distribution_credentials.comment.as_deref(),
            Some("My Self-Hosted Distribution Credentials")
        );
        // `tags` is omitted by the server when empty.
        assert!(entry.distribution_credentials.tags.is_empty());
    }

    #[test]
    fn deserializes_single_entry_response() {
        // `get` returns one `{ member, distribution_credentials }` entry.
        let json = serde_json::json!({
            "member": {
                "member_id": "3376abcd-8e5e-49d3-92d4-876d3a4f0363",
                "email": "email@example.com"
            },
            "distribution_credentials": {
                "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
                "provider": "quay",
                "scopes": ["self-hosted:product:api"],
                "tags": ["prod", "us-east"],
                "created": "2023-06-28T15:36:59.609841Z",
                "comment": "primary"
            }
        });

        let entry: DistributionCredentialsEntry = serde_json::from_value(json).unwrap();
        assert_eq!(entry.member.email, "email@example.com");
        assert_eq!(
            entry
                .distribution_credentials
                .distribution_credentials_id
                .to_string(),
            "8b36cfd0-472f-4a21-833f-2d6343c3a2f3"
        );
        assert_eq!(
            entry.distribution_credentials.comment.as_deref(),
            Some("primary")
        );
        assert_eq!(entry.distribution_credentials.tags, ["prod", "us-east"]);
    }

    #[test]
    fn deserializes_response_without_comment() {
        // `comment` is optional.
        let json = serde_json::json!({
            "distribution_credentials": [{
                "member": { "member_id": "3376abcd-8e5e-49d3-92d4-876d3a4f0363", "email": "e@x.com" },
                "distribution_credentials": {
                    "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
                    "provider": "quay",
                    "scopes": [],
                    "created": "2023-06-28T15:36:59.609841Z"
                }
            }]
        });
        let list: DistributionCredentialsList = serde_json::from_value(json).unwrap();
        assert!(list.distribution_credentials[0]
            .distribution_credentials
            .comment
            .is_none());
    }

    #[test]
    fn deserializes_create_response_with_one_time_secret() {
        // The API server answers `create` with a bare credentials object (no
        // `member` wrapper) that carries the one-time `username` / `secret`.
        let json = serde_json::json!({
            "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
            "provider": "quay",
            "username": "deepgram+8b36cfd0",
            "secret": "s3cr3t-registry-password",
            "comment": "created from the rust sdk",
            "scopes": ["self-hosted:product:api", "onprem:product:api"],
            "created": "2023-06-28T15:36:59.609841Z"
        });

        let created: CreatedDistributionCredentials = serde_json::from_value(json).unwrap();
        assert_eq!(
            created.distribution_credentials_id.to_string(),
            "8b36cfd0-472f-4a21-833f-2d6343c3a2f3"
        );
        assert_eq!(created.provider, "quay");
        assert_eq!(created.username, "deepgram+8b36cfd0");
        assert_eq!(created.secret.expose_secret(), "s3cr3t-registry-password");
        assert_eq!(
            created.comment.as_deref(),
            Some("created from the rust sdk")
        );
        assert_eq!(created.scopes, [Scope::Api, Scope::Api]);
        assert!(created.tags.is_empty());

        // The secret must never reach Debug output.
        let debug = format!("{created:?}");
        assert!(
            !debug.contains("s3cr3t-registry-password"),
            "secret leaked into Debug: {debug}"
        );
        assert!(debug.contains("***"), "{debug}");

        // ...but it does survive a deliberate serialization round-trip.
        let json = serde_json::to_value(&created).unwrap();
        assert_eq!(json["secret"], "s3cr3t-registry-password");
        assert!(json.get("tags").is_none(), "empty tags are omitted");
    }

    #[test]
    fn deserializes_create_response_with_tags() {
        let json = serde_json::json!({
            "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
            "provider": "quay",
            "username": "u",
            "secret": "s",
            "comment": "",
            "scopes": ["self-hosted:product:api", "self-hosted:product:engine"],
            "tags": ["staging"],
            "created": "2023-06-28T15:36:59.609841Z"
        });
        let created: CreatedDistributionCredentials = serde_json::from_value(json).unwrap();
        assert_eq!(created.tags, ["staging"]);
        assert_eq!(created.scopes, [Scope::Api, Scope::Engine]);
    }

    #[test]
    fn deserializes_create_response_for_the_products_shorthand() {
        // A create that sends `["self-hosted:products"]` from an account
        // holding every product scope. The server stores the expanded grant,
        // emitting each product under the `self-hosted:` and then the
        // `onprem:` prefix, and omits `tags` when there are none.
        let products = [
            "api",
            "engine",
            "license-proxy",
            "billing",
            "dgtools",
            "hotpepper",
            "metrics-server",
        ];
        let scopes: Vec<String> = products
            .iter()
            .flat_map(|p| {
                [
                    format!("self-hosted:product:{p}"),
                    format!("onprem:product:{p}"),
                ]
            })
            .collect();
        let json = serde_json::json!({
            "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
            "provider": "quay",
            "username": "deepgram+8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
            "secret": "s3cr3t",
            "comment": "every product",
            "scopes": scopes,
            "created": "2023-06-28T15:36:59.609841Z"
        });

        let created: CreatedDistributionCredentials = serde_json::from_value(json).unwrap();
        assert_eq!(created.scopes.len(), 14);
        assert!(
            !created
                .scopes
                .iter()
                .any(|s| matches!(s, Scope::Unknown(_) | Scope::Products)),
            "every expanded scope resolves to a named product variant: {:?}",
            created.scopes
        );
        for scope in [
            Scope::Api,
            Scope::Engine,
            Scope::LicenseProxy,
            Scope::Billing,
            Scope::Dgtools,
            Scope::Hotpepper,
            Scope::MetricsServer,
        ] {
            assert_eq!(created.scopes.iter().filter(|s| **s == scope).count(), 2);
        }
    }

    #[test]
    fn create_response_without_a_secret_is_an_error() {
        // The server always returns `username` and `secret` on create; a body
        // without them is not a create response.
        let json = serde_json::json!({
            "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
            "provider": "quay",
            "comment": "",
            "scopes": [],
            "created": "2023-06-28T15:36:59.609841Z"
        });
        assert!(serde_json::from_value::<CreatedDistributionCredentials>(json).is_err());
    }

    #[test]
    fn deserializes_response_with_an_unknown_scope() {
        // A scope the SDK does not name must not fail the whole response, and
        // must re-serialize to exactly the string it arrived as.
        let json = serde_json::json!({
            "member": { "member_id": "3376abcd-8e5e-49d3-92d4-876d3a4f0363", "email": "e@x.com" },
            "distribution_credentials": {
                "distribution_credentials_id": "8b36cfd0-472f-4a21-833f-2d6343c3a2f3",
                "provider": "quay",
                "scopes": ["self-hosted:products", "self-hosted:product:not-invented-yet"],
                "created": "2023-06-28T15:36:59.609841Z"
            }
        });

        let entry: DistributionCredentialsEntry = serde_json::from_value(json).unwrap();
        assert_eq!(
            entry.distribution_credentials.scopes,
            [
                Scope::Products,
                Scope::Unknown("self-hosted:product:not-invented-yet".to_string())
            ]
        );

        let round_tripped = serde_json::to_value(&entry).unwrap();
        assert_eq!(
            round_tripped["distribution_credentials"]["scopes"],
            serde_json::json!([
                "self-hosted:products",
                "self-hosted:product:not-invented-yet"
            ])
        );
    }

    #[test]
    fn deserializes_delete_message() {
        // The API server answers `delete` with a message, not the entry.
        let json = serde_json::json!({
            "message": "Successfully deleted the distribution credentials!"
        });
        let message: Message = serde_json::from_value(json).unwrap();
        assert_eq!(
            message.message,
            "Successfully deleted the distribution credentials!"
        );
    }

    #[test]
    fn secret_string_redacts_debug() {
        let secret = SecretString::new("hunter2");
        assert_eq!(format!("{secret:?}"), "***");
        assert_eq!(secret.expose_secret(), "hunter2");
        assert_eq!(secret.clone().into_inner(), "hunter2");
        assert_eq!(SecretString::from("hunter2".to_string()), secret);
    }
}