videosdk-server-sdk 0.1.0

Rust server SDK for the VideoSDK v2 REST 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
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Token minting, decoding and verification.
//!
//! The VideoSDK API authenticates server requests with a JWT that is HS256-signed
//! with the project secret and carries the public API key in its payload. Tokens
//! are signed locally — there is no network call — and are sent as
//! `Authorization: <token>`, a **raw JWT with no `Bearer` prefix**.

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use hmac::{Hmac, Mac};
use serde_json::{json, Map, Value};
use sha2::Sha256;

use crate::error::{Error, Result};

/// The token lifetime used when none is specified.
pub const DEFAULT_TOKEN_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// The fixed JWT header. Written literally so the encoded bytes match the other
/// VideoSDK SDKs exactly.
const JWT_HEADER: &str = r#"{"alg":"HS256","typ":"JWT"}"#;

type HmacSha256 = Hmac<Sha256>;

/// Configures [`generate_token`].
#[derive(Debug, Clone, Default)]
pub struct GenerateTokenParams {
    /// The project API key (public). Embedded in the payload as `apikey`. Required.
    pub api_key: String,
    /// The project secret (private). HS256-signs the token; never transmitted. Required.
    pub secret_key: String,
    /// Permission claims. Defaults to `["allow_join", "allow_mod"]`.
    pub permissions: Option<Vec<String>>,
    /// Role claims. Defaults to `["crawler"]`, which the v2 REST APIs require for
    /// management requests.
    pub roles: Option<Vec<String>>,
    /// The token version. Defaults to `2`, which the v2 REST APIs require.
    pub version: Option<i64>,
    /// The token lifetime. Defaults to [`DEFAULT_TOKEN_TTL`].
    pub expires_in: Option<Duration>,
    /// Extra custom claims merged into the payload, e.g. `participantId`, `roomId`.
    ///
    /// Custom claims may shadow `apikey`, `permissions`, `version` and `roles`,
    /// but never `iat` or `exp`.
    pub claims: Map<String, Value>,
}

/// A decoded view of a token payload.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct TokenClaims {
    /// The `apikey` claim.
    pub api_key: Option<String>,
    /// The `permissions` claim.
    pub permissions: Vec<String>,
    /// The `roles` claim.
    pub roles: Vec<String>,
    /// The `version` claim.
    pub version: Option<i64>,
    /// The `iat` claim, in Unix seconds.
    pub issued_at: Option<i64>,
    /// The `exp` claim, in Unix seconds.
    pub expires_at: Option<i64>,
    /// Every claim as decoded from JSON, including custom ones.
    pub raw: Map<String, Value>,
}

/// A participant permission claim — an entry in the token's `permissions`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Grant {
    /// Lets the participant join the meeting directly.
    AllowJoin,
    /// Requires the participant to request to join; a host admits them.
    AskJoin,
    /// Lets the participant moderate: remove participants, control recordings, and so on.
    AllowMod,
}

impl Grant {
    /// The wire representation of this grant.
    pub fn as_str(self) -> &'static str {
        match self {
            Grant::AllowJoin => "allow_join",
            Grant::AskJoin => "ask_join",
            Grant::AllowMod => "allow_mod",
        }
    }
}

fn unix_now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

fn invalid_expires_in(value: &str) -> Error {
    Error::validation(format!(
        "invalid expiresIn {value:?}: use a number of seconds or a string like \"24h\", \"7d\""
    ))
}

/// Converts a duration string such as `"30s"`, `"10m"`, `"24h"`, `"7d"`, `"2w"`
/// or `"1y"` into a [`Duration`]. A bare number is interpreted as seconds.
pub fn parse_expires_in(value: &str) -> Result<Duration> {
    let s = value.trim();
    let digits_end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
    if digits_end == 0 {
        return Err(invalid_expires_in(value));
    }
    let amount: u64 = s[..digits_end]
        .parse()
        .map_err(|_| invalid_expires_in(value))?;
    let seconds_per_unit = match s[digits_end..].trim_start() {
        "" | "s" => 1,
        "m" => 60,
        "h" => 3_600,
        "d" => 86_400,
        "w" => 604_800,
        "y" => 31_536_000,
        _ => return Err(invalid_expires_in(value)),
    };
    amount
        .checked_mul(seconds_per_unit)
        .map(Duration::from_secs)
        .ok_or_else(|| invalid_expires_in(value))
}

fn new_mac(secret: &str) -> HmacSha256 {
    <HmacSha256 as Mac>::new_from_slice(secret.as_bytes()).expect("HMAC accepts keys of any length")
}

fn sign_hs256(signing_input: &str, secret: &str) -> String {
    let mut mac = new_mac(secret);
    mac.update(signing_input.as_bytes());
    URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())
}

/// Decodes a base64url JWT segment, tolerating padding and the standard base64
/// alphabet that some producers emit.
fn decode_segment(segment: &str) -> std::result::Result<Vec<u8>, base64::DecodeError> {
    let normalized: String = segment
        .trim_end_matches('=')
        .chars()
        .map(|c| match c {
            '+' => '-',
            '/' => '_',
            other => other,
        })
        .collect();
    URL_SAFE_NO_PAD.decode(normalized)
}

/// Signs a JWT for authenticating against the VideoSDK v2 REST APIs.
///
/// Send it as `Authorization: <token>` — a raw JWT, with no `Bearer` prefix.
pub fn generate_token(params: &GenerateTokenParams) -> Result<String> {
    if params.api_key.is_empty() {
        return Err(Error::config("generate_token: api_key is required"));
    }
    if params.secret_key.is_empty() {
        return Err(Error::config("generate_token: secret_key is required"));
    }

    let ttl = params
        .expires_in
        .filter(|d| !d.is_zero())
        .unwrap_or(DEFAULT_TOKEN_TTL);
    let iat = unix_now();
    let exp = iat + ttl.as_secs() as i64;

    let permissions = params
        .permissions
        .clone()
        .unwrap_or_else(|| vec!["allow_join".to_string(), "allow_mod".to_string()]);
    let roles = params
        .roles
        .clone()
        .unwrap_or_else(|| vec!["crawler".to_string()]);

    let mut payload = Map::new();
    payload.insert("apikey".into(), json!(params.api_key));
    payload.insert("permissions".into(), json!(permissions));
    payload.insert("version".into(), json!(params.version.unwrap_or(2)));
    payload.insert("roles".into(), json!(roles));
    // Custom claims may shadow the four claims above...
    for (key, value) in &params.claims {
        payload.insert(key.clone(), value.clone());
    }
    // ...but never `iat`/`exp`, which are written last.
    payload.insert("iat".into(), json!(iat));
    payload.insert("exp".into(), json!(exp));

    let payload_json = serde_json::to_vec(&payload).map_err(|e| Error::Encode { source: e })?;
    let signing_input = format!(
        "{}.{}",
        URL_SAFE_NO_PAD.encode(JWT_HEADER),
        URL_SAFE_NO_PAD.encode(payload_json)
    );
    let signature = sign_hs256(&signing_input, &params.secret_key);
    Ok(format!("{signing_input}.{signature}"))
}

fn string_vec(value: Option<&Value>) -> Vec<String> {
    value
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

fn claims_from_map(map: Map<String, Value>) -> TokenClaims {
    TokenClaims {
        api_key: map
            .get("apikey")
            .and_then(Value::as_str)
            .map(str::to_string),
        permissions: string_vec(map.get("permissions")),
        roles: string_vec(map.get("roles")),
        version: map.get("version").and_then(Value::as_i64),
        issued_at: map.get("iat").and_then(Value::as_i64),
        expires_at: map.get("exp").and_then(Value::as_i64),
        raw: map,
    }
}

/// Decodes a token's payload **without verifying its signature**.
///
/// Useful for reading `exp` to decide whether a cached token needs regenerating.
pub fn decode_token(token: &str) -> Result<TokenClaims> {
    let mut parts = token.split('.');
    let (_header, payload) = (parts.next(), parts.next());
    let payload = payload
        .filter(|p| !p.is_empty())
        .ok_or_else(|| Error::validation("malformed token: expected at least a 2-part JWT"))?;
    let raw = decode_segment(payload)
        .map_err(|e| Error::validation(format!("malformed token payload: {e}")))?;
    let map: Map<String, Value> = serde_json::from_slice(&raw)
        .map_err(|e| Error::validation(format!("malformed token payload: {e}")))?;
    Ok(claims_from_map(map))
}

/// Verifies an HS256 JWT against `secret` and returns its claims.
///
/// Fails if the token is malformed, the signature doesn't match, or it has expired.
pub fn verify_token(token: &str, secret: &str) -> Result<TokenClaims> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() != 3 || parts.iter().any(|p| p.is_empty()) {
        return Err(Error::auth("malformed token: expected a 3-part JWT"));
    }
    let signature = decode_segment(parts[2]).map_err(|_| Error::auth("invalid token signature"))?;

    let mut mac = new_mac(secret);
    mac.update(format!("{}.{}", parts[0], parts[1]).as_bytes());
    // Constant-time comparison.
    mac.verify_slice(&signature)
        .map_err(|_| Error::auth("invalid token signature"))?;

    let claims = decode_token(token).map_err(|_| Error::auth("malformed token payload"))?;
    if let Some(exp) = claims.expires_at {
        if unix_now() >= exp {
            return Err(Error::auth("token has expired"));
        }
    }
    Ok(claims)
}

/// Fluently builds a VideoSDK access token.
///
/// Defaults to a **participant** token (`roles: ["rtc"]`, `version: 2`). Call
/// [`AccessTokenBuilder::for_api`] for a management token (`roles: ["crawler"]`).
/// Obtain one from [`Client::access_token`](crate::Client::access_token).
///
/// ```no_run
/// # use videosdk::{AccessTokenBuilder, Grant};
/// # use std::time::Duration;
/// let jwt = AccessTokenBuilder::new("key", "secret")
///     .set_participant("participant-1")
///     .grant(Grant::AllowJoin)
///     .grant(Grant::AllowMod)
///     .for_room("room-1")
///     .expires_in(Duration::from_secs(2 * 60 * 60))
///     .to_jwt()?;
/// # Ok::<(), videosdk::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct AccessTokenBuilder {
    api_key: String,
    secret: String,
    participant_id: Option<String>,
    room_id: Option<String>,
    grants: Vec<Grant>,
    roles: Vec<String>,
    ttl: Option<Duration>,
    claims: Map<String, Value>,
}

impl AccessTokenBuilder {
    /// Starts a builder for a participant token.
    pub fn new(api_key: impl Into<String>, secret: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            secret: secret.into(),
            participant_id: None,
            room_id: None,
            grants: Vec::new(),
            roles: vec!["rtc".to_string()],
            ttl: None,
            claims: Map::new(),
        }
    }

    /// Sets the `participantId` claim.
    pub fn set_participant(mut self, participant_id: impl Into<String>) -> Self {
        self.participant_id = Some(participant_id.into());
        self
    }

    /// Adds a permission grant. Duplicates are ignored; insertion order is kept.
    pub fn grant(mut self, grant: Grant) -> Self {
        if !self.grants.contains(&grant) {
            self.grants.push(grant);
        }
        self
    }

    /// Adds several permission grants at once.
    pub fn grants(mut self, grants: impl IntoIterator<Item = Grant>) -> Self {
        for grant in grants {
            self = self.grant(grant);
        }
        self
    }

    /// Scopes the token to a specific room, via the `roomId` claim.
    pub fn for_room(mut self, room_id: impl Into<String>) -> Self {
        self.room_id = Some(room_id.into());
        self
    }

    /// Builds a management token (`roles: ["crawler"]`) instead of a participant token.
    pub fn for_api(mut self) -> Self {
        self.roles = vec!["crawler".to_string()];
        self
    }

    /// Sets the token lifetime.
    pub fn expires_in(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Attaches an arbitrary custom claim.
    pub fn set_claim(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.claims.insert(key.into(), value.into());
        self
    }

    /// Signs and returns the token.
    pub fn to_jwt(&self) -> Result<String> {
        if self.api_key.is_empty() || self.secret.is_empty() {
            return Err(Error::config("access_token requires an api_key and secret"));
        }
        let mut claims = self.claims.clone();
        if let Some(participant_id) = &self.participant_id {
            claims.insert("participantId".into(), json!(participant_id));
        }
        if let Some(room_id) = &self.room_id {
            claims.insert("roomId".into(), json!(room_id));
        }
        // No grants means no `permissions` claim, which lets `generate_token`
        // apply its own default of ["allow_join", "allow_mod"].
        let permissions = (!self.grants.is_empty())
            .then(|| self.grants.iter().map(|g| g.as_str().to_string()).collect());

        generate_token(&GenerateTokenParams {
            api_key: self.api_key.clone(),
            secret_key: self.secret.clone(),
            permissions,
            roles: Some(self.roles.clone()),
            version: Some(2),
            expires_in: self.ttl,
            claims,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn params() -> GenerateTokenParams {
        GenerateTokenParams {
            api_key: "test-key".into(),
            secret_key: "test-secret".into(),
            ..Default::default()
        }
    }

    #[test]
    fn parses_duration_strings() {
        assert_eq!(parse_expires_in("30").unwrap(), Duration::from_secs(30));
        assert_eq!(parse_expires_in("30s").unwrap(), Duration::from_secs(30));
        assert_eq!(parse_expires_in("10m").unwrap(), Duration::from_secs(600));
        assert_eq!(
            parse_expires_in("24h").unwrap(),
            Duration::from_secs(86_400)
        );
        assert_eq!(
            parse_expires_in("7d").unwrap(),
            Duration::from_secs(604_800)
        );
        assert_eq!(
            parse_expires_in("2w").unwrap(),
            Duration::from_secs(1_209_600)
        );
        assert_eq!(
            parse_expires_in("1y").unwrap(),
            Duration::from_secs(31_536_000)
        );
        // The reference SDKs allow whitespace between the amount and the unit.
        assert_eq!(
            parse_expires_in(" 15 m ").unwrap(),
            Duration::from_secs(900)
        );
    }

    #[test]
    fn rejects_bad_duration_strings() {
        for bad in ["", "abc", "h", "-5s", "10x", "1.5h"] {
            assert!(parse_expires_in(bad).is_err(), "expected {bad:?} to fail");
        }
    }

    #[test]
    fn generated_token_has_three_segments_and_expected_header() {
        let token = generate_token(&params()).unwrap();
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
        let header = decode_segment(parts[0]).unwrap();
        assert_eq!(String::from_utf8(header).unwrap(), JWT_HEADER);
    }

    #[test]
    fn applies_documented_defaults() {
        let claims = decode_token(&generate_token(&params()).unwrap()).unwrap();
        assert_eq!(claims.api_key.as_deref(), Some("test-key"));
        assert_eq!(claims.permissions, ["allow_join", "allow_mod"]);
        assert_eq!(claims.roles, ["crawler"]);
        assert_eq!(claims.version, Some(2));
        let (iat, exp) = (claims.issued_at.unwrap(), claims.expires_at.unwrap());
        assert_eq!(exp - iat, DEFAULT_TOKEN_TTL.as_secs() as i64);
    }

    #[test]
    fn custom_claims_may_shadow_roles_but_never_iat_or_exp() {
        let mut p = params();
        p.claims.insert("roles".into(), json!(["custom"]));
        p.claims.insert("exp".into(), json!(1));
        p.claims.insert("iat".into(), json!(1));
        p.claims.insert("participantId".into(), json!("p-1"));

        let claims = decode_token(&generate_token(&p).unwrap()).unwrap();
        assert_eq!(claims.roles, ["custom"], "custom claims shadow roles");
        assert_eq!(
            claims.raw.get("participantId").unwrap().as_str(),
            Some("p-1")
        );
        assert_ne!(claims.expires_at, Some(1), "exp must not be overridable");
        assert_ne!(claims.issued_at, Some(1), "iat must not be overridable");
    }

    #[test]
    fn verify_round_trips_a_generated_token() {
        let token = generate_token(&params()).unwrap();
        let claims = verify_token(&token, "test-secret").unwrap();
        assert_eq!(claims.api_key.as_deref(), Some("test-key"));
    }

    #[test]
    fn verify_rejects_a_wrong_secret() {
        let token = generate_token(&params()).unwrap();
        let err = verify_token(&token, "not-the-secret").unwrap_err();
        assert!(err.is_authentication());
        assert!(err.to_string().contains("invalid token signature"));
    }

    #[test]
    fn verify_rejects_a_tampered_payload() {
        let token = generate_token(&params()).unwrap();
        let mut parts: Vec<&str> = token.split('.').collect();
        let forged = URL_SAFE_NO_PAD.encode(br#"{"apikey":"attacker"}"#);
        parts[1] = &forged;
        let tampered = parts.join(".");
        assert!(verify_token(&tampered, "test-secret").is_err());
    }

    #[test]
    fn verify_rejects_malformed_and_expired_tokens() {
        assert!(verify_token("a.b", "s").unwrap_err().is_authentication());
        assert!(verify_token("a..c", "s").unwrap_err().is_authentication());

        let mut p = params();
        p.expires_in = Some(Duration::from_secs(1));
        let mut token_params = p.clone();
        // Mint a token that expired an hour ago by back-dating via a custom claim
        // is impossible (exp always wins), so sign one by hand instead.
        token_params.claims.clear();
        let payload = json!({"apikey": "k", "exp": unix_now() - 3600});
        let signing_input = format!(
            "{}.{}",
            URL_SAFE_NO_PAD.encode(JWT_HEADER),
            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap())
        );
        let expired = format!("{signing_input}.{}", sign_hs256(&signing_input, "s"));
        let err = verify_token(&expired, "s").unwrap_err();
        assert!(err.to_string().contains("token has expired"));
    }

    #[test]
    fn decode_does_not_verify() {
        let signing_input = format!(
            "{}.{}",
            URL_SAFE_NO_PAD.encode(JWT_HEADER),
            URL_SAFE_NO_PAD.encode(br#"{"apikey":"k"}"#)
        );
        let unsigned = format!("{signing_input}.garbage");
        assert_eq!(
            decode_token(&unsigned).unwrap().api_key.as_deref(),
            Some("k")
        );
        assert!(verify_token(&unsigned, "s").is_err());
    }

    #[test]
    fn decode_rejects_malformed_tokens() {
        assert!(decode_token("only-one-part").is_err());
        assert!(decode_token("header.").is_err());
        assert!(decode_token("header.!!!not-base64!!!").is_err());
    }

    #[test]
    fn access_token_defaults_to_a_participant_token() {
        let jwt = AccessTokenBuilder::new("k", "s").to_jwt().unwrap();
        let claims = decode_token(&jwt).unwrap();
        assert_eq!(claims.roles, ["rtc"]);
        // No grants set, so `generate_token` supplies the default permissions.
        assert_eq!(claims.permissions, ["allow_join", "allow_mod"]);
        assert_eq!(claims.version, Some(2));
    }

    #[test]
    fn for_api_switches_to_the_management_role() {
        let jwt = AccessTokenBuilder::new("k", "s")
            .for_api()
            .to_jwt()
            .unwrap();
        assert_eq!(decode_token(&jwt).unwrap().roles, ["crawler"]);
    }

    #[test]
    fn grants_are_deduplicated_and_ordered() {
        let jwt = AccessTokenBuilder::new("k", "s")
            .grant(Grant::AllowMod)
            .grant(Grant::AllowJoin)
            .grant(Grant::AllowMod)
            .to_jwt()
            .unwrap();
        assert_eq!(
            decode_token(&jwt).unwrap().permissions,
            ["allow_mod", "allow_join"]
        );
    }

    #[test]
    fn participant_and_room_become_claims() {
        let jwt = AccessTokenBuilder::new("k", "s")
            .set_participant("p-1")
            .for_room("r-1")
            .set_claim("custom", "v")
            .to_jwt()
            .unwrap();
        let raw = decode_token(&jwt).unwrap().raw;
        assert_eq!(raw.get("participantId").unwrap().as_str(), Some("p-1"));
        assert_eq!(raw.get("roomId").unwrap().as_str(), Some("r-1"));
        assert_eq!(raw.get("custom").unwrap().as_str(), Some("v"));
    }

    #[test]
    fn generate_token_requires_credentials() {
        let mut p = params();
        p.api_key = String::new();
        assert!(generate_token(&p)
            .unwrap_err()
            .to_string()
            .contains("api_key"));

        let mut p = params();
        p.secret_key = String::new();
        assert!(generate_token(&p)
            .unwrap_err()
            .to_string()
            .contains("secret_key"));
    }

    #[test]
    fn decode_segment_tolerates_standard_base64_alphabet() {
        // `+` and `/` should be normalized to `-` and `_`.
        let raw = [0xfb_u8, 0xff, 0xbf];
        let standard = base64::engine::general_purpose::STANDARD.encode(raw);
        assert!(standard.contains('+') || standard.contains('/'));
        assert_eq!(decode_segment(&standard).unwrap(), raw);
    }
}