trellis-rs 0.10.7

Curated public Rust facade for Trellis clients and services.
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
use super::{
    AdminSessionState, AuthRequestsValidateRequest, AuthRequestsValidateResponse,
    AuthenticatedUser, IdentityGrantEntryRecord, ListIdentityGrantsRequest,
    RevokeIdentityGrantRequest, TrellisAuthError,
};
use crate::client::{RpcDescriptor, TrellisClient, UserConnectOptions};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::collections::BTreeMap;

use super::protocol::LogoutResponse;
use crate::sdk::auth::{
    rpc::{
        AuthCapabilitiesListRpc, AuthCapabilityGroupsListRpc, AuthDeploymentsCreateRpc,
        AuthDeploymentsDisableRpc, AuthDeploymentsEnableRpc, AuthDeploymentsListRpc,
        AuthDeploymentsRemoveRpc, AuthIdentityGrantsListRpc, AuthIdentityGrantsRevokeRpc,
        AuthSessionsListRpc, AuthSessionsMeRpc, AuthUsersCreateRpc, AuthUsersGetRpc,
        AuthUsersListRpc, AuthUsersPasswordResetCreateRpc, AuthUsersUpdateRpc, Empty,
    },
    types::{
        AuthCapabilitiesListRequest, AuthCapabilitiesListResponseEntriesItem,
        AuthCapabilityGroupsListRequest, AuthCapabilityGroupsListResponseEntriesItem,
        AuthDeploymentsCreateRequest, AuthDeploymentsDisableRequest, AuthDeploymentsEnableRequest,
        AuthDeploymentsListRequest, AuthDeploymentsRemoveRequest, AuthSessionsListRequest,
        AuthUsersCreateRequest, AuthUsersCreateResponseUser, AuthUsersGetRequest,
        AuthUsersGetResponseUser, AuthUsersListRequest, AuthUsersListResponseEntriesItem,
        AuthUsersPasswordResetCreateRequest, AuthUsersPasswordResetCreateResponse,
        AuthUsersUpdateRequest,
    },
};

const AUTH_CLIENT_LIST_LIMIT: i64 = 500;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ServiceDeploymentRecord {
    pub kind: String,
    pub deployment_id: String,
    pub namespaces: Vec<String>,
    pub disabled: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeviceDeploymentRecord {
    pub kind: String,
    pub deployment_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub review_mode: Option<serde_json::Value>,
    pub disabled: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct DeviceDeploymentCreateRequest<'a> {
    kind: &'static str,
    deployment_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    review_mode: Option<&'a str>,
}

/// Connect an authenticated admin client from the stored session state.
pub async fn connect_admin_client_async(
    state: &AdminSessionState,
) -> Result<TrellisClient, TrellisAuthError> {
    Ok(TrellisClient::connect_user(UserConnectOptions {
        servers: &state.nats_servers,
        sentinel_jwt: &state.sentinel_jwt,
        sentinel_seed: &state.sentinel_seed,
        session_key_seed_base64url: &state.session_seed,
        contract_digest: &state.contract_digest,
        timeout_ms: 5_000,
    })
    .await?)
}

/// Thin typed client for Trellis auth/admin RPCs used by the CLI.
pub struct AuthClient<'a> {
    inner: &'a TrellisClient,
}

/// Options for removing a device deployment.
#[derive(Debug, Clone, Copy, Default)]
pub struct RemoveDeviceDeploymentOptions {
    /// Also remove dependent device instances and activation records.
    pub cascade: Option<bool>,
    /// Garbage-collect deployment contract records that are no longer referenced.
    pub purge_unused_contracts: Option<bool>,
}

/// Options for removing a service deployment.
#[derive(Debug, Clone, Copy, Default)]
pub struct RemoveServiceDeploymentOptions {
    /// Also remove dependent service instances and activation records.
    pub cascade: Option<bool>,
    /// Delete service-owned physical resource bindings before durable removal.
    pub purge_unused_contracts: Option<bool>,
}

impl<'a> AuthClient<'a> {
    /// Wrap an already-connected low-level Trellis client.
    pub fn new(inner: &'a TrellisClient) -> Self {
        Self { inner }
    }

    async fn call<Input, Output>(
        &self,
        subject: &str,
        input: &Input,
    ) -> Result<Output, TrellisAuthError>
    where
        Input: Serialize,
        Output: DeserializeOwned,
    {
        let request = serde_json::to_value(input)?;
        let response = self.inner.request_json_value(subject, &request).await?;
        Ok(serde_json::from_value(response)?)
    }

    async fn call_rpc<R>(&self, input: &R::Input) -> Result<R::Output, TrellisAuthError>
    where
        R: RpcDescriptor,
    {
        self.call(R::SUBJECT, input).await
    }

    /// Return the currently authenticated user.
    pub async fn me(&self) -> Result<AuthenticatedUser, TrellisAuthError> {
        let response = self.call_rpc::<AuthSessionsMeRpc>(&Empty {}).await?;
        let participant_kind = response
            .participant_kind
            .as_str()
            .unwrap_or("none")
            .to_string();

        match participant_kind.as_str() {
            "app" | "agent" if !response.user.is_null() => {
                Ok(serde_json::from_value(response.user)?)
            }
            _ => Err(TrellisAuthError::NotUserSession(participant_kind)),
        }
    }

    /// List delegated identity grants.
    pub async fn list_identity_grants(
        &self,
        user: Option<&str>,
        digest: Option<&str>,
    ) -> Result<Vec<IdentityGrantEntryRecord>, TrellisAuthError> {
        let request = ListIdentityGrantsRequest {
            limit: AUTH_CLIENT_LIST_LIMIT,
            offset: None,
            user: user.map(ToOwned::to_owned),
        };
        let identity_grants = self
            .call_rpc::<AuthIdentityGrantsListRpc>(&request)
            .await?
            .entries;
        Ok(match digest {
            Some(digest) => identity_grants
                .into_iter()
                .filter(|entry| entry.contract_evidence.contract_digest == digest)
                .collect(),
            None => identity_grants,
        })
    }

    /// Revoke one delegated identity grant.
    pub async fn revoke_identity_grant(
        &self,
        identity_grant_id: &str,
        user: Option<&str>,
    ) -> Result<bool, TrellisAuthError> {
        let request = RevokeIdentityGrantRequest {
            identity_grant_id: identity_grant_id.to_string(),
            user: user.map(ToOwned::to_owned),
        };
        Ok(self
            .call_rpc::<AuthIdentityGrantsRevokeRpc>(&request)
            .await?
            .success)
    }

    /// List Trellis users.
    pub async fn list_users(
        &self,
        limit: i64,
        offset: Option<i64>,
    ) -> Result<Vec<AuthUsersListResponseEntriesItem>, TrellisAuthError> {
        Ok(self
            .call_rpc::<AuthUsersListRpc>(&AuthUsersListRequest { limit, offset })
            .await?
            .entries)
    }

    /// Get one Trellis user by user ID.
    pub async fn get_user(
        &self,
        user_id: &str,
    ) -> Result<AuthUsersGetResponseUser, TrellisAuthError> {
        Ok(self
            .call_rpc::<AuthUsersGetRpc>(&AuthUsersGetRequest {
                user_id: user_id.to_string(),
            })
            .await?
            .user)
    }

    /// Create one Trellis user.
    pub async fn create_user(
        &self,
        input: &AuthUsersCreateRequest,
    ) -> Result<AuthUsersCreateResponseUser, TrellisAuthError> {
        Ok(self.call_rpc::<AuthUsersCreateRpc>(input).await?.user)
    }

    /// Update one Trellis user.
    pub async fn update_user(
        &self,
        input: &AuthUsersUpdateRequest,
    ) -> Result<bool, TrellisAuthError> {
        Ok(self.call_rpc::<AuthUsersUpdateRpc>(input).await?.success)
    }

    /// List auth sessions.
    pub async fn list_sessions(
        &self,
        limit: i64,
        offset: Option<i64>,
        user: Option<&str>,
    ) -> Result<Vec<serde_json::Value>, TrellisAuthError> {
        Ok(self
            .call_rpc::<AuthSessionsListRpc>(&AuthSessionsListRequest {
                limit,
                offset,
                user: user.map(ToOwned::to_owned),
            })
            .await?
            .entries)
    }

    /// List available auth capabilities.
    pub async fn list_capabilities(
        &self,
        limit: i64,
        offset: Option<i64>,
    ) -> Result<Vec<AuthCapabilitiesListResponseEntriesItem>, TrellisAuthError> {
        Ok(self
            .call_rpc::<AuthCapabilitiesListRpc>(&AuthCapabilitiesListRequest { limit, offset })
            .await?
            .entries)
    }

    /// List auth capability groups.
    pub async fn list_capability_groups(
        &self,
        limit: i64,
        offset: Option<i64>,
    ) -> Result<Vec<AuthCapabilityGroupsListResponseEntriesItem>, TrellisAuthError> {
        Ok(self
            .call_rpc::<AuthCapabilityGroupsListRpc>(&AuthCapabilityGroupsListRequest {
                limit,
                offset,
            })
            .await?
            .entries)
    }

    /// Create a local password reset flow for one Trellis user.
    pub async fn create_password_reset_flow(
        &self,
        input: &AuthUsersPasswordResetCreateRequest,
    ) -> Result<AuthUsersPasswordResetCreateResponse, TrellisAuthError> {
        self.call_rpc::<AuthUsersPasswordResetCreateRpc>(input)
            .await
    }

    /// List device deployments.
    pub async fn list_device_deployments(
        &self,
        disabled: bool,
    ) -> Result<Vec<DeviceDeploymentRecord>, TrellisAuthError> {
        let deployments = self
            .call_rpc::<AuthDeploymentsListRpc>(&AuthDeploymentsListRequest {
                disabled: if disabled { Some(true) } else { None },
                kind: Some("device".to_string()),
                limit: AUTH_CLIENT_LIST_LIMIT,
                offset: None,
            })
            .await?
            .entries;

        deployments
            .into_iter()
            .map(serde_json::from_value)
            .collect::<Result<Vec<_>, _>>()
            .map_err(Into::into)
    }

    /// Create a device deployment.
    pub async fn create_device_deployment(
        &self,
        deployment_id: &str,
        review_mode: Option<&str>,
    ) -> Result<DeviceDeploymentRecord, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsCreateRpc>(&AuthDeploymentsCreateRequest(
                serde_json::to_value(DeviceDeploymentCreateRequest {
                    kind: "device",
                    deployment_id,
                    review_mode,
                })?,
            ))
            .await?;

        Ok(serde_json::from_value(response.deployment)?)
    }

    /// Disable a device deployment.
    pub async fn disable_device_deployment(
        &self,
        deployment_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsDisableRpc>(&AuthDeploymentsDisableRequest {
                deployment_id: deployment_id.to_string(),
                kind: "device".to_string(),
            })
            .await?;
        let deployment: DeviceDeploymentRecord = serde_json::from_value(response.deployment)?;
        Ok(deployment.disabled)
    }

    /// Enable a device deployment.
    pub async fn enable_device_deployment(
        &self,
        deployment_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsEnableRpc>(&AuthDeploymentsEnableRequest {
                deployment_id: deployment_id.to_string(),
                kind: "device".to_string(),
            })
            .await?;
        let deployment: DeviceDeploymentRecord = serde_json::from_value(response.deployment)?;
        Ok(!deployment.disabled)
    }

    /// Remove a device deployment.
    pub async fn remove_device_deployment(
        &self,
        deployment_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        self.remove_device_deployment_with_options(deployment_id, None)
            .await
    }

    /// Remove a device deployment with explicit remove options.
    pub async fn remove_device_deployment_with_options(
        &self,
        deployment_id: &str,
        cascade: Option<bool>,
    ) -> Result<bool, TrellisAuthError> {
        self.remove_device_deployment_with_remove_options(
            deployment_id,
            RemoveDeviceDeploymentOptions {
                cascade,
                purge_unused_contracts: None,
            },
        )
        .await
    }

    /// Remove a device deployment with explicit remove options.
    pub async fn remove_device_deployment_with_remove_options(
        &self,
        deployment_id: &str,
        options: RemoveDeviceDeploymentOptions,
    ) -> Result<bool, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsRemoveRpc>(&AuthDeploymentsRemoveRequest {
                cascade: options.cascade,
                deployment_id: deployment_id.to_string(),
                kind: "device".to_string(),
                purge_unused_contracts: options.purge_unused_contracts,
            })
            .await?;
        Ok(response.success)
    }

    /// Provision a device instance.
    pub async fn provision_device_instance(
        &self,
        deployment_id: &str,
        public_identity_key: &str,
        activation_key: &str,
        metadata: Option<BTreeMap<String, String>>,
    ) -> Result<crate::sdk::auth::AuthDevicesProvisionResponseInstance, TrellisAuthError> {
        Ok(self
            .call::<_, crate::sdk::auth::AuthDevicesProvisionResponse>(
                "rpc.v1.Auth.Devices.Provision",
                &crate::sdk::auth::AuthDevicesProvisionRequest {
                    deployment_id: deployment_id.to_string(),
                    public_identity_key: public_identity_key.to_string(),
                    activation_key: activation_key.to_string(),
                    metadata,
                },
            )
            .await?
            .instance)
    }

    /// List device instances.
    pub async fn list_device_instances(
        &self,
        deployment_id: Option<&str>,
        state: Option<&str>,
    ) -> Result<Vec<crate::sdk::auth::AuthDevicesListResponseEntriesItem>, TrellisAuthError> {
        Ok(self
            .call::<_, crate::sdk::auth::AuthDevicesListResponse>(
                "rpc.v1.Auth.Devices.List",
                &crate::sdk::auth::AuthDevicesListRequest {
                    deployment_id: deployment_id.map(ToOwned::to_owned),
                    limit: AUTH_CLIENT_LIST_LIMIT,
                    offset: None,
                    state: state.map(ToOwned::to_owned),
                },
            )
            .await?
            .entries)
    }

    /// Disable a device instance.
    pub async fn disable_device_instance(
        &self,
        instance_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        let response = self
            .call::<_, crate::sdk::auth::AuthDevicesDisableResponse>(
                "rpc.v1.Auth.Devices.Disable",
                &crate::sdk::auth::AuthDevicesDisableRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?;
        Ok(response.instance.state == "disabled")
    }

    /// Enable a device instance.
    pub async fn enable_device_instance(
        &self,
        instance_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        let response = self
            .call::<_, crate::sdk::auth::AuthDevicesEnableResponse>(
                "rpc.v1.Auth.Devices.Enable",
                &crate::sdk::auth::AuthDevicesEnableRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?;
        Ok(response.instance.state != "disabled")
    }

    /// Remove a device instance.
    pub async fn remove_device_instance(
        &self,
        instance_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        let response = self
            .call::<_, crate::sdk::auth::AuthDevicesRemoveResponse>(
                "rpc.v1.Auth.Devices.Remove",
                &crate::sdk::auth::AuthDevicesRemoveRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?;
        Ok(response.success)
    }

    /// List device activations.
    pub async fn list_device_activations(
        &self,
        instance_id: Option<&str>,
        deployment_id: Option<&str>,
        state: Option<&str>,
    ) -> Result<
        Vec<crate::sdk::auth::AuthDeviceUserAuthoritiesListResponseEntriesItem>,
        TrellisAuthError,
    > {
        Ok(self
            .call::<_, crate::sdk::auth::AuthDeviceUserAuthoritiesListResponse>(
                "rpc.v1.Auth.DeviceUserAuthorities.List",
                &crate::sdk::auth::AuthDeviceUserAuthoritiesListRequest {
                    instance_id: instance_id.map(ToOwned::to_owned),
                    deployment_id: deployment_id.map(ToOwned::to_owned),
                    limit: AUTH_CLIENT_LIST_LIMIT,
                    offset: None,
                    state: state.map(ToOwned::to_owned),
                },
            )
            .await?
            .entries)
    }

    /// Revoke a device activation.
    pub async fn revoke_device_activation(
        &self,
        instance_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        Ok(self
            .call::<_, crate::sdk::auth::AuthDeviceUserAuthoritiesRevokeResponse>(
                "rpc.v1.Auth.DeviceUserAuthorities.Revoke",
                &crate::sdk::auth::AuthDeviceUserAuthoritiesRevokeRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?
            .success)
    }

    /// List device activation reviews.
    pub async fn list_device_activation_reviews(
        &self,
        instance_id: Option<&str>,
        deployment_id: Option<&str>,
        state: Option<&str>,
    ) -> Result<
        Vec<crate::sdk::auth::AuthDeviceUserAuthoritiesReviewsListResponseEntriesItem>,
        TrellisAuthError,
    > {
        Ok(self
            .call::<_, crate::sdk::auth::AuthDeviceUserAuthoritiesReviewsListResponse>(
                "rpc.v1.Auth.DeviceUserAuthorities.Reviews.List",
                &crate::sdk::auth::AuthDeviceUserAuthoritiesReviewsListRequest {
                    instance_id: instance_id.map(ToOwned::to_owned),
                    deployment_id: deployment_id.map(ToOwned::to_owned),
                    limit: AUTH_CLIENT_LIST_LIMIT,
                    offset: None,
                    state: state.map(ToOwned::to_owned),
                },
            )
            .await?
            .entries)
    }

    /// Decide one device activation review.
    pub async fn decide_device_activation_review(
        &self,
        review_id: &str,
        decision: &str,
        reason: Option<&str>,
    ) -> Result<crate::sdk::auth::AuthDeviceUserAuthoritiesReviewsDecideResponse, TrellisAuthError>
    {
        self.call(
            "rpc.v1.Auth.DeviceUserAuthorities.Reviews.Decide",
            &crate::sdk::auth::AuthDeviceUserAuthoritiesReviewsDecideRequest {
                review_id: review_id.to_string(),
                decision: decision.to_string(),
                reason: reason.map(ToOwned::to_owned),
            },
        )
        .await
    }

    /// Create one service deployment.
    pub async fn create_service_deployment(
        &self,
        deployment_id: &str,
        namespaces: Vec<String>,
    ) -> Result<ServiceDeploymentRecord, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsCreateRpc>(&AuthDeploymentsCreateRequest(
                serde_json::json!({
                    "kind": "service",
                    "deploymentId": deployment_id,
                    "namespaces": namespaces,
                }),
            ))
            .await?;
        Ok(serde_json::from_value(response.deployment)?)
    }

    /// List service deployments.
    pub async fn list_service_deployments(
        &self,
        disabled: bool,
    ) -> Result<Vec<ServiceDeploymentRecord>, TrellisAuthError> {
        self.call_rpc::<AuthDeploymentsListRpc>(&AuthDeploymentsListRequest {
            disabled: if disabled { Some(true) } else { None },
            kind: Some("service".to_string()),
            limit: AUTH_CLIENT_LIST_LIMIT,
            offset: None,
        })
        .await?
        .entries
        .into_iter()
        .map(serde_json::from_value)
        .collect::<Result<Vec<_>, _>>()
        .map_err(Into::into)
    }

    /// Disable one service deployment.
    pub async fn disable_service_deployment(
        &self,
        deployment_id: &str,
    ) -> Result<ServiceDeploymentRecord, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsDisableRpc>(&AuthDeploymentsDisableRequest {
                deployment_id: deployment_id.to_string(),
                kind: "service".to_string(),
            })
            .await?;
        Ok(serde_json::from_value(response.deployment)?)
    }

    /// Enable one service deployment.
    pub async fn enable_service_deployment(
        &self,
        deployment_id: &str,
    ) -> Result<ServiceDeploymentRecord, TrellisAuthError> {
        let response = self
            .call_rpc::<AuthDeploymentsEnableRpc>(&AuthDeploymentsEnableRequest {
                deployment_id: deployment_id.to_string(),
                kind: "service".to_string(),
            })
            .await?;
        Ok(serde_json::from_value(response.deployment)?)
    }

    /// Remove one service deployment.
    pub async fn remove_service_deployment(
        &self,
        deployment_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        self.remove_service_deployment_with_options(deployment_id, None)
            .await
    }

    /// Remove one service deployment with explicit remove options.
    pub async fn remove_service_deployment_with_options(
        &self,
        deployment_id: &str,
        cascade: Option<bool>,
    ) -> Result<bool, TrellisAuthError> {
        self.remove_service_deployment_with_remove_options(
            deployment_id,
            RemoveServiceDeploymentOptions {
                cascade,
                purge_unused_contracts: None,
            },
        )
        .await
    }

    /// Remove one service deployment with explicit remove options.
    pub async fn remove_service_deployment_with_remove_options(
        &self,
        deployment_id: &str,
        options: RemoveServiceDeploymentOptions,
    ) -> Result<bool, TrellisAuthError> {
        Ok(self
            .call_rpc::<AuthDeploymentsRemoveRpc>(&AuthDeploymentsRemoveRequest {
                cascade: options.cascade,
                deployment_id: deployment_id.to_string(),
                kind: "service".to_string(),
                purge_unused_contracts: options.purge_unused_contracts,
            })
            .await?
            .success)
    }

    /// Provision one service instance.
    pub async fn provision_service_instance(
        &self,
        input: &crate::sdk::auth::AuthServiceInstancesProvisionRequest,
    ) -> Result<crate::sdk::auth::AuthServiceInstancesProvisionResponseInstance, TrellisAuthError>
    {
        Ok(self
            .call::<_, crate::sdk::auth::AuthServiceInstancesProvisionResponse>(
                "rpc.v1.Auth.ServiceInstances.Provision",
                input,
            )
            .await?
            .instance)
    }

    /// List service instances.
    pub async fn list_service_instances(
        &self,
        deployment_id: Option<&str>,
        disabled: Option<bool>,
    ) -> Result<Vec<crate::sdk::auth::AuthServiceInstancesListResponseEntriesItem>, TrellisAuthError>
    {
        Ok(self
            .call::<_, crate::sdk::auth::AuthServiceInstancesListResponse>(
                "rpc.v1.Auth.ServiceInstances.List",
                &crate::sdk::auth::AuthServiceInstancesListRequest {
                    deployment_id: deployment_id.map(ToOwned::to_owned),
                    disabled,
                    limit: AUTH_CLIENT_LIST_LIMIT,
                    offset: None,
                },
            )
            .await?
            .entries)
    }

    /// Disable one service instance.
    pub async fn disable_service_instance(
        &self,
        instance_id: &str,
    ) -> Result<crate::sdk::auth::AuthServiceInstancesDisableResponseInstance, TrellisAuthError>
    {
        Ok(self
            .call::<_, crate::sdk::auth::AuthServiceInstancesDisableResponse>(
                "rpc.v1.Auth.ServiceInstances.Disable",
                &crate::sdk::auth::AuthServiceInstancesDisableRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?
            .instance)
    }

    /// Enable one service instance.
    pub async fn enable_service_instance(
        &self,
        instance_id: &str,
    ) -> Result<crate::sdk::auth::AuthServiceInstancesEnableResponseInstance, TrellisAuthError>
    {
        Ok(self
            .call::<_, crate::sdk::auth::AuthServiceInstancesEnableResponse>(
                "rpc.v1.Auth.ServiceInstances.Enable",
                &crate::sdk::auth::AuthServiceInstancesEnableRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?
            .instance)
    }

    /// Remove one service instance.
    pub async fn remove_service_instance(
        &self,
        instance_id: &str,
    ) -> Result<bool, TrellisAuthError> {
        Ok(self
            .call::<_, crate::sdk::auth::AuthServiceInstancesRemoveResponse>(
                "rpc.v1.Auth.ServiceInstances.Remove",
                &crate::sdk::auth::AuthServiceInstancesRemoveRequest {
                    instance_id: instance_id.to_string(),
                },
            )
            .await?
            .success)
    }

    /// Validate one request payload.
    pub async fn validate_request(
        &self,
        input: &AuthRequestsValidateRequest,
    ) -> Result<AuthRequestsValidateResponse, TrellisAuthError> {
        self.call("rpc.v1.Auth.Requests.Validate", input).await
    }

    /// List service deployments.
    pub async fn list_services(&self) -> Result<Vec<ServiceDeploymentRecord>, TrellisAuthError> {
        self.list_service_deployments(false).await
    }

    /// Log out the current admin session remotely.
    pub async fn logout(&self) -> Result<bool, TrellisAuthError> {
        Ok(self
            .call::<_, LogoutResponse>("rpc.v1.Auth.Sessions.Logout", &Empty {})
            .await?
            .success)
    }
}

#[cfg(test)]
mod tests {
    use crate::sdk::auth::types::AuthSessionsMeResponse;
    use serde_json::json;

    use super::{AuthenticatedUser, DeviceDeploymentCreateRequest, DeviceDeploymentRecord};

    #[test]
    fn sessions_me_response_user_value_deserializes_account_first_shape() {
        let response: AuthSessionsMeResponse = serde_json::from_value(json!({
            "participantKind": "agent",
            "user": {
                "userId": "usr_123",
                "active": true,
                "name": "Ada",
                "email": "ada@example.com",
                "identity": {
                    "identityId": "idn_github_123",
                    "provider": "github",
                    "subject": "123"
                },
                "capabilities": ["admin"]
            },
            "device": null,
            "service": null
        }))
        .expect("deserialize generated response");

        assert_eq!(response.participant_kind.as_str(), Some("agent"));
        let user: AuthenticatedUser =
            serde_json::from_value(response.user).expect("deserialize authenticated user");
        assert_eq!(user.user_id, "usr_123");
        assert_eq!(user.identity.identity_id, "idn_github_123");
        assert_eq!(user.identity.provider, "github");
        assert_eq!(user.identity.subject, "123");
    }

    #[test]
    fn device_deployment_requests_omit_absent_review_mode() {
        let without_review_mode = serde_json::to_value(DeviceDeploymentCreateRequest {
            kind: "device",
            deployment_id: "reader",
            review_mode: None,
        })
        .expect("serialize device deployment create request");
        assert_eq!(
            without_review_mode,
            json!({ "kind": "device", "deploymentId": "reader" })
        );
        assert!(!without_review_mode
            .as_object()
            .expect("request object")
            .contains_key("reviewMode"));

        let with_review_mode = serde_json::to_value(DeviceDeploymentCreateRequest {
            kind: "device",
            deployment_id: "reader",
            review_mode: Some("required"),
        })
        .expect("serialize device deployment create request with review mode");
        assert_eq!(
            with_review_mode,
            json!({ "kind": "device", "deploymentId": "reader", "reviewMode": "required" })
        );
    }

    #[test]
    fn device_deployment_records_omit_absent_review_mode() {
        let record = serde_json::to_value(DeviceDeploymentRecord {
            kind: "device".to_string(),
            deployment_id: "reader".to_string(),
            review_mode: None,
            disabled: false,
        })
        .expect("serialize device deployment record");

        assert_eq!(
            record,
            json!({ "kind": "device", "deploymentId": "reader", "disabled": false })
        );
        assert!(!record
            .as_object()
            .expect("record object")
            .contains_key("reviewMode"));
    }

    #[test]
    fn remove_deployment_requests_serialize_optional_cascade() {
        let service_without_cascade =
            serde_json::to_value(crate::sdk::auth::AuthDeploymentsRemoveRequest {
                cascade: None,
                deployment_id: "api".to_string(),
                kind: "service".to_string(),
                purge_unused_contracts: None,
            })
            .expect("serialize service remove request");
        assert_eq!(
            service_without_cascade,
            json!({ "deploymentId": "api", "kind": "service" })
        );

        let service_with_cascade =
            serde_json::to_value(crate::sdk::auth::AuthDeploymentsRemoveRequest {
                cascade: Some(true),
                deployment_id: "api".to_string(),
                kind: "service".to_string(),
                purge_unused_contracts: None,
            })
            .expect("serialize service cascade remove request");
        assert_eq!(
            service_with_cascade,
            json!({ "cascade": true, "deploymentId": "api", "kind": "service" })
        );

        let device_with_cascade =
            serde_json::to_value(crate::sdk::auth::AuthDeploymentsRemoveRequest {
                cascade: Some(true),
                deployment_id: "reader".to_string(),
                kind: "device".to_string(),
                purge_unused_contracts: None,
            })
            .expect("serialize device cascade remove request");
        assert_eq!(
            device_with_cascade,
            json!({ "cascade": true, "deploymentId": "reader", "kind": "device" })
        );

        let service_with_purge =
            serde_json::to_value(crate::sdk::auth::AuthDeploymentsRemoveRequest {
                cascade: Some(true),
                deployment_id: "api".to_string(),
                kind: "service".to_string(),
                purge_unused_contracts: Some(true),
            })
            .expect("serialize service purge remove request");
        assert_eq!(
            service_with_purge,
            json!({
                "cascade": true,
                "deploymentId": "api",
                "kind": "service",
                "purgeUnusedContracts": true
            })
        );

        let device_with_purge =
            serde_json::to_value(crate::sdk::auth::AuthDeploymentsRemoveRequest {
                cascade: Some(true),
                deployment_id: "reader".to_string(),
                kind: "device".to_string(),
                purge_unused_contracts: Some(true),
            })
            .expect("serialize device purge remove request");
        assert_eq!(
            device_with_purge,
            json!({
                "cascade": true,
                "deploymentId": "reader",
                "kind": "device",
                "purgeUnusedContracts": true
            })
        );
    }
}