delopay 0.20.0

Official Rust SDK for the DeloPay payments API
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! The `api_keys` resource: create and manage a merchant's API keys.
//!
//! Two families of endpoints live here:
//!
//! - merchant-wide keys under `/api-keys/{merchant_id}` — [`ApiKeys::create`],
//!   [`ApiKeys::retrieve`], [`ApiKeys::update`], [`ApiKeys::revoke`],
//!   [`ApiKeys::list`];
//! - shop-scoped (business profile) keys under
//!   `/account/{merchant_id}/profile/api-keys` — [`ApiKeys::rotate_by_profile`].
//!   The shop is taken from the caller's JWT, never from the request, so a
//!   shop-scoped user can only rotate keys pinned to their own shop.
//!
//! The plaintext key value is returned **once**, at creation time, in
//! [`ApiKeyCreateResponse::api_key`]. Every other endpoint returns only the
//! prefix. Because that field is a live credential,
//! [`ApiKeyCreateResponse`] has a hand-written [`Debug`] that redacts it.

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `api_keys` resource, obtained via [`crate::Delopay::api_keys`].
#[derive(Debug, Clone)]
pub struct ApiKeys {
    inner: Arc<Inner>,
}

impl ApiKeys {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Create a new merchant-wide API key.
    ///
    /// The response carries the plaintext key in
    /// [`ApiKeyCreateResponse::api_key`]; it is shown only once.
    pub async fn create(
        &self,
        merchant_id: &str,
        params: &ApiKeyCreateRequest,
    ) -> Result<ApiKeyCreateResponse> {
        params.validate()?;
        let path = format!("/api-keys/{}", encode_segment(merchant_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Retrieve an API key's metadata. Never returns the plaintext key.
    pub async fn retrieve(&self, merchant_id: &str, key_id: &str) -> Result<ApiKeyResponse> {
        let path = format!(
            "/api-keys/{}/{}",
            encode_segment(merchant_id),
            encode_segment(key_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update an API key's name, description, or expiry.
    pub async fn update(
        &self,
        merchant_id: &str,
        key_id: &str,
        params: &ApiKeyUpdateRequest,
    ) -> Result<ApiKeyResponse> {
        params.validate()?;
        let path = format!(
            "/api-keys/{}/{}",
            encode_segment(merchant_id),
            encode_segment(key_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Revoke an API key, invalidating it immediately.
    pub async fn revoke(&self, merchant_id: &str, key_id: &str) -> Result<ApiKeyRevokeResponse> {
        let path = format!(
            "/api-keys/{}/{}",
            encode_segment(merchant_id),
            encode_segment(key_id)
        );
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// Rotate a merchant-wide API key: the key keeps its ID and metadata and
    /// gets a new secret. `POST /api-keys/{merchant_id}/{key_id}/rotate`
    ///
    /// The response carries the new plaintext key in
    /// [`ApiKeyCreateResponse::api_key`]; it is shown only once. The API
    /// refuses a rotation while partial authentication is enabled; create a
    /// new key and revoke this one instead.
    pub async fn rotate(&self, merchant_id: &str, key_id: &str) -> Result<ApiKeyCreateResponse> {
        let path = format!(
            "/api-keys/{}/{}/rotate",
            encode_segment(merchant_id),
            encode_segment(key_id)
        );
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, None, None)
            .await
    }

    /// List every API key on the merchant account.
    pub async fn list(&self, merchant_id: &str) -> Result<Vec<ApiKeyResponse>> {
        let path = format!("/api-keys/{}/list", encode_segment(merchant_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Rotate a shop-pinned API key: the key keeps its ID and metadata and
    /// gets a new secret.
    /// `POST /account/{merchant_id}/profile/api-keys/{key_id}/rotate`
    ///
    /// The new plaintext key is returned once, as with
    /// [`rotate`](Self::rotate).
    pub async fn rotate_by_profile(
        &self,
        merchant_id: &str,
        key_id: &str,
    ) -> Result<ApiKeyCreateResponse> {
        let path = format!(
            "/account/{}/profile/api-keys/{}/rotate",
            encode_segment(merchant_id),
            encode_segment(key_id)
        );
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, None, None)
            .await
    }
}

/// Parameters for [`ApiKeys::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ApiKeyCreateRequest {
    /// Human-readable name for the key.
    pub name: String,
    /// Expiry: `"never"`, or an ISO 8601 timestamp.
    pub expiration: String,
    /// Optional description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// `"full"`, `"statistics_read"` or `"restricted"`. Left out, the key is
    /// `full` only when the caller's role covers everything, else
    /// `restricted` to the caller's permissions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// The permission groups of a `restricted` key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_groups: Option<Vec<String>>,
    /// The shops the key may act on; `None` is the whole account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_ids: Option<Vec<String>>,
    /// Browser origins the key may be used from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_origins: Option<Vec<String>>,
    /// The most requests the key may make per minute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate_limit_per_minute: Option<i32>,
    /// Any additional create fields not modeled above, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `ApiKeyCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const API_KEY_CREATE_REQUEST_NAMED: &[&str] = &[
    "name",
    "expiration",
    "description",
    "scope",
    "permission_groups",
    "profile_ids",
    "allowed_origins",
    "rate_limit_per_minute",
];

impl ValidateRequest for ApiKeyCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if API_KEY_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on ApiKeyCreateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl ApiKeyCreateRequest {
    /// A request creating a key with the given name and expiry (`"never"`, or
    /// an ISO 8601 timestamp).
    pub fn new(name: impl Into<String>, expiration: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            expiration: expiration.into(),
            ..Default::default()
        }
    }

    /// Set the key's description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the key's scope.
    #[must_use]
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }

    /// Restrict the key to these permission groups.
    #[must_use]
    pub fn permission_groups(mut self, groups: Vec<String>) -> Self {
        self.permission_groups = Some(groups);
        self
    }

    /// Restrict the key to these shops.
    #[must_use]
    pub fn profile_ids(mut self, profile_ids: Vec<String>) -> Self {
        self.profile_ids = Some(profile_ids);
        self
    }

    /// Allow the key from these browser origins.
    #[must_use]
    pub fn allowed_origins(mut self, origins: Vec<String>) -> Self {
        self.allowed_origins = Some(origins);
        self
    }

    /// Limit the key's requests per minute.
    #[must_use]
    pub fn rate_limit_per_minute(mut self, limit: i32) -> Self {
        self.rate_limit_per_minute = Some(limit);
        self
    }
}

/// Parameters for [`ApiKeys::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ApiKeyUpdateRequest {
    /// New name for the key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// New description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// New expiry: `"never"`, or an ISO 8601 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration: Option<String>,
    /// The permission groups of a `restricted` key. Making the key `full`
    /// again is not expressible here.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_groups: Option<Vec<String>>,
    /// The shops the key may act on; `None` is the whole account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_ids: Option<Vec<String>>,
    /// Browser origins the key may be used from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_origins: Option<Vec<String>>,
    /// The most requests the key may make per minute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate_limit_per_minute: Option<i32>,
    /// Any additional update fields not modeled above, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `ApiKeyUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const API_KEY_UPDATE_REQUEST_NAMED: &[&str] = &[
    "name",
    "description",
    "expiration",
    "permission_groups",
    "profile_ids",
    "allowed_origins",
    "rate_limit_per_minute",
];

impl ValidateRequest for ApiKeyUpdateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if API_KEY_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on ApiKeyUpdateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl ApiKeyUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the key's new name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the key's new description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the key's new expiry (`"never"`, or an ISO 8601 timestamp).
    #[must_use]
    pub fn expiration(mut self, expiration: impl Into<String>) -> Self {
        self.expiration = Some(expiration.into());
        self
    }
}

/// The response to [`ApiKeys::create`] — the only place the plaintext key is
/// ever returned.
///
/// [`Debug`] is hand-written and redacts the key; see the impl.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ApiKeyCreateResponse {
    /// Unique ID of the key.
    pub key_id: String,
    /// Merchant account the key belongs to.
    pub merchant_id: String,
    /// Human-readable name.
    pub name: String,
    /// **The plaintext API key.** Shown once, at creation. Store it
    /// somewhere safe: it cannot be retrieved again.
    pub api_key: String,
    /// Creation timestamp.
    pub created: String,
    /// Expiry: `"never"`, or an ISO 8601 timestamp.
    pub expiration: String,
    /// Description, if one was set.
    #[serde(default)]
    pub description: Option<String>,
    /// The shop (business profile) the key is pinned to, or `None` for
    /// merchant-wide keys. Absent on backends without profile-scoped keys.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// `"full"`, `"statistics_read"` or `"restricted"`.
    #[serde(default)]
    pub scope: Option<String>,
    /// Browser origins the key may be used from.
    #[serde(default)]
    pub allowed_origins: Option<Vec<String>>,
    /// The most requests the key may make per minute.
    #[serde(default)]
    pub rate_limit_per_minute: Option<i32>,
    /// The permission groups of a `restricted` key.
    #[serde(default)]
    pub permission_groups: Option<Vec<String>>,
    /// The shops the key may act on; `None` is the whole account.
    #[serde(default)]
    pub profile_ids: Option<Vec<String>>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `api_key` is a live credential, and a
// `{:?}` on a create response is exactly what ends up in a log line or an
// error report. `extra` is printed as key names only — a backend that starts
// returning the secret under some new name would otherwise leak it through
// the catch-all map.
impl std::fmt::Debug for ApiKeyCreateResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let extra_keys: Vec<&str> = self.extra.keys().map(String::as_str).collect();
        f.debug_struct("ApiKeyCreateResponse")
            .field("key_id", &self.key_id)
            .field("merchant_id", &self.merchant_id)
            .field("name", &self.name)
            .field("api_key", &"[redacted]")
            .field("created", &self.created)
            .field("expiration", &self.expiration)
            .field("description", &self.description)
            .field("profile_id", &self.profile_id)
            .field("scope", &self.scope)
            .field("allowed_origins", &self.allowed_origins)
            .field("rate_limit_per_minute", &self.rate_limit_per_minute)
            .field("permission_groups", &self.permission_groups)
            .field("profile_ids", &self.profile_ids)
            .field("extra_keys", &extra_keys)
            .finish_non_exhaustive()
    }
}

/// API key metadata, as returned by every endpoint other than create. Carries
/// only the key's prefix, never the plaintext key.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ApiKeyResponse {
    /// Unique ID of the key.
    pub key_id: String,
    /// Merchant account the key belongs to.
    pub merchant_id: String,
    /// Human-readable name.
    pub name: String,
    /// Leading characters of the key, for identifying it in a list.
    pub prefix: String,
    /// Creation timestamp.
    pub created: String,
    /// Expiry: `"never"`, or an ISO 8601 timestamp.
    pub expiration: String,
    /// Description, if one was set.
    #[serde(default)]
    pub description: Option<String>,
    /// The shop (business profile) the key is pinned to, or `None` for
    /// merchant-wide keys. Absent on backends without profile-scoped keys.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// `"full"`, `"statistics_read"` or `"restricted"`.
    #[serde(default)]
    pub scope: Option<String>,
    /// Browser origins the key may be used from.
    #[serde(default)]
    pub allowed_origins: Option<Vec<String>>,
    /// The most requests the key may make per minute.
    #[serde(default)]
    pub rate_limit_per_minute: Option<i32>,
    /// The permission groups of a `restricted` key.
    #[serde(default)]
    pub permission_groups: Option<Vec<String>>,
    /// The shops the key may act on; `None` is the whole account.
    #[serde(default)]
    pub profile_ids: Option<Vec<String>>,
    /// ISO 8601 time the key was last used.
    #[serde(default)]
    pub last_used: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The response to [`ApiKeys::revoke`].
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ApiKeyRevokeResponse {
    /// Merchant account the key belonged to.
    pub merchant_id: String,
    /// ID of the revoked key.
    pub key_id: String,
    /// Whether the key is now revoked.
    pub revoked: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with, client_with_retries};
    use serde_json::json;

    const CREATE_JSON: &str = r#"{
        "key_id": "key_1", "merchant_id": "merch_1", "name": "Production key",
        "api_key": "snd_supersecretvalue", "created": "2026-01-01T00:00:00Z",
        "expiration": "never"
    }"#;
    const KEY_JSON: &str = r#"{
        "key_id": "key_1", "merchant_id": "merch_1", "name": "Production key",
        "prefix": "snd_abcd", "created": "2026-01-01T00:00:00Z",
        "expiration": "never", "scope": "restricted",
        "permission_groups": ["OperationsView"], "profile_ids": ["pro_1"],
        "allowed_origins": ["https://shop.test"], "rate_limit_per_minute": 60,
        "last_used": "2026-02-01T00:00:00Z"
    }"#;
    const REVOKE_JSON: &str = r#"{"merchant_id":"merch_1","key_id":"key_1","revoked":true}"#;

    #[tokio::test]
    async fn create_posts_to_the_merchant_key_path() {
        let (client, mock) = client_with(vec![Step::ok(CREATE_JSON)]);
        let out = client
            .api_keys()
            .create(
                "merch/1",
                &ApiKeyCreateRequest::new("Production key", "never").description("main"),
            )
            .await
            .unwrap();
        assert_eq!(out.api_key, "snd_supersecretvalue");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/api-keys/merch%2F1");
        let body = seen[0].body_json();
        assert_eq!(body["name"], "Production key");
        assert_eq!(body["expiration"], "never");
        assert_eq!(body["description"], "main");
    }

    #[tokio::test]
    async fn retrieve_update_revoke_share_the_key_path() {
        let (client, mock) = client_with(vec![
            Step::ok(KEY_JSON),
            Step::ok(KEY_JSON),
            Step::ok(REVOKE_JSON),
        ]);
        let keys = client.api_keys();
        let got = keys.retrieve("merch_1", "key/1").await.unwrap();
        assert_eq!(got.prefix, "snd_abcd");
        assert_eq!(got.scope.as_deref(), Some("restricted"));
        assert_eq!(got.rate_limit_per_minute, Some(60));
        assert_eq!(got.last_used.as_deref(), Some("2026-02-01T00:00:00Z"));
        assert_eq!(got.profile_ids.as_deref(), Some(&["pro_1".to_string()][..]));
        keys.update(
            "merch_1",
            "key/1",
            &ApiKeyUpdateRequest::new()
                .name("Renamed")
                .expiration("never"),
        )
        .await
        .unwrap();
        let revoked = keys.revoke("merch_1", "key/1").await.unwrap();
        assert!(revoked.revoked);

        let seen = mock.seen.lock().unwrap();
        for step in seen.iter() {
            assert_eq!(step.url, "https://api.test/api-keys/merch_1/key%2F1");
        }
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[1].method, "POST");
        assert_eq!(seen[1].body_json()["name"], "Renamed");
        assert_eq!(seen[1].body_json()["expiration"], "never");
        assert_eq!(seen[2].method, "DELETE");
    }

    #[tokio::test]
    async fn list_gets_the_list_suffix() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{KEY_JSON}]"))]);
        let out = client.api_keys().list("merch_1").await.unwrap();
        assert_eq!(out[0].key_id, "key_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/api-keys/merch_1/list");
    }

    #[tokio::test]
    async fn rotate_posts_to_the_rotate_suffix_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "key_id": "key_1", "merchant_id": "merch_1", "name": "Production key",
                "api_key": "snd_rotatedvalue", "created": "2026-01-01T00:00:00Z",
                "expiration": "never", "rotated_from": "snd_abcd"
            }"#,
        )]);
        let out = client.api_keys().rotate("merch/1", "key/1").await.unwrap();
        assert_eq!(out.api_key, "snd_rotatedvalue");
        assert_eq!(out.extra["rotated_from"], "snd_abcd");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/api-keys/merch%2F1/key%2F1/rotate"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn rotate_by_profile_posts_to_the_account_profile_rotate_suffix() {
        let (client, mock) = client_with(vec![Step::ok(CREATE_JSON)]);
        let out = client
            .api_keys()
            .rotate_by_profile("merch/1", "key/1")
            .await
            .unwrap();
        assert_eq!(out.key_id, "key_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/merch%2F1/profile/api-keys/key%2F1/rotate"
        );
        assert!(seen[0].body.is_none());
    }

    /// The plaintext key must never reach a `{:?}`; a derived `Debug` on
    /// `ApiKeyCreateResponse` makes this fail.
    #[test]
    fn create_response_debug_redacts_the_plaintext_key() {
        let created: ApiKeyCreateResponse = serde_json::from_str(CREATE_JSON).unwrap();
        let printed = format!("{created:?}");
        assert!(
            !printed.contains("snd_supersecretvalue"),
            "plaintext api_key leaked into Debug output: {printed}"
        );
        assert!(printed.contains("[redacted]"));
        // The non-secret metadata is still useful for debugging.
        assert!(printed.contains("key_1"));
    }

    /// A backend that returned the secret under an unmodeled name would land
    /// in `extra`; only its key names may be printed.
    #[test]
    fn create_response_debug_hides_extra_values() {
        let mut created: ApiKeyCreateResponse = serde_json::from_str(CREATE_JSON).unwrap();
        created
            .extra
            .insert("key_value".to_string(), json!("another_secret"));
        let printed = format!("{created:?}");
        assert!(
            !printed.contains("another_secret"),
            "an unmodeled secret leaked through `extra`: {printed}"
        );
        assert!(printed.contains("key_value"));
    }

    /// Drift guard for `API_KEY_CREATE_REQUEST_NAMED`.
    #[test]
    fn api_key_create_request_named_fields_are_complete() {
        let req = ApiKeyCreateRequest::new("Production key", "never")
            .description("main")
            .scope("restricted")
            .permission_groups(vec!["OperationsView".to_string()])
            .profile_ids(vec!["pro_1".to_string()])
            .allowed_origins(vec!["https://shop.test".to_string()])
            .rate_limit_per_minute(60);
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                API_KEY_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "API_KEY_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `API_KEY_UPDATE_REQUEST_NAMED`.
    #[test]
    fn api_key_update_request_named_fields_are_complete() {
        let req = ApiKeyUpdateRequest {
            name: Some("Renamed".to_string()),
            description: Some("main".to_string()),
            expiration: Some("never".to_string()),
            permission_groups: Some(vec!["OperationsView".to_string()]),
            profile_ids: Some(vec!["pro_1".to_string()]),
            allowed_origins: Some(vec!["https://shop.test".to_string()]),
            rate_limit_per_minute: Some(60),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                API_KEY_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "API_KEY_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_keys_colliding_with_named_fields() {
        let mut create = ApiKeyCreateRequest::new("k", "never");
        create
            .extra
            .insert("expiration".to_string(), json!("never"));
        match create.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("expiration")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut update = ApiKeyUpdateRequest::new();
        update.extra.insert("name".to_string(), json!("collide"));
        match update.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// A rotation never carries an idempotency key, not even the
    /// client-wide one, so a 5xx is not replayed. Mutation: switch a call
    /// site back to `request(.., None)` — the header appears and the call
    /// count grows.
    #[tokio::test]
    async fn rotations_ignore_the_client_wide_idempotency_key() {
        for by_profile in [false, true] {
            let (client, mock) =
                client_with_retries(vec![Step::status(503, "{}"), Step::ok(CREATE_JSON)], 2);
            let keys = client.with_idempotency_key("client-key").api_keys();
            let out = if by_profile {
                keys.rotate_by_profile("merch_1", "key_1").await
            } else {
                keys.rotate("merch_1", "key_1").await
            };
            assert!(out.is_err());
            assert_eq!(mock.call_count(), 1);
            assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
        }
    }
}