Skip to main content

bitwarden_pam/rotation/
configs.rs

1use std::sync::Arc;
2
3use bitwarden_api_api::models::{
4    CreateRotationConfigRequestModel, PamRotationConfigDetailResponseModel,
5    PamRotationConfigResponseModel, PamTargetSystemResponseModel, UpdateRotationConfigRequestModel,
6};
7use bitwarden_core::{
8    FromClient, OrganizationId,
9    client::ApiConfigurations,
10    key_management::{KeySlotIds, SymmetricKeySlotId},
11    require,
12};
13use bitwarden_crypto::{
14    CryptoError, Decryptable, EncString, IdentifyKey, KeyStore, KeyStoreContext, safe::DataEnvelope,
15};
16use bitwarden_pam_sealed::{
17    RotationConfigSealedV1, Sealed, seal_rotation_config, unseal_rotation_config,
18};
19use bitwarden_vault::CipherId;
20use chrono::{DateTime, Utc};
21use serde::{Deserialize, Serialize};
22use uuid::Uuid;
23
24use super::{
25    actions::{RotationConfigActions, rotation_config_actions},
26    error::RotationError,
27    models::{RotationJob, TargetSystemMethod, TargetSystemStatus},
28    target_systems::{TargetSystem, TargetSystemView},
29    validate::{RotationValidationError, validate_config_request},
30};
31use crate::{RotationConfigId, TargetSystemId};
32
33/// A rotation config as the server returns it, with its security-relevant fields still sealed.
34#[derive(Debug, Clone, PartialEq)]
35pub(crate) struct RotationConfig {
36    id: RotationConfigId,
37    organization_id: OrganizationId,
38    cipher_id: CipherId,
39    target_system_id: TargetSystemId,
40    target_system_name: String,
41    target_system_method: TargetSystemMethod,
42    sealed_data: Option<String>,
43    wrapped_key: Option<String>,
44    schedule_cron: Option<String>,
45    rotate_on_access_end: bool,
46    enabled: bool,
47    last_rotation_at: Option<DateTime<Utc>>,
48    next_rotation_at: Option<DateTime<Utc>>,
49    has_active_job: bool,
50    last_job_failed: bool,
51    awaiting_manual_rotation: bool,
52    creation_date: DateTime<Utc>,
53    revision_date: DateTime<Utc>,
54}
55
56impl RotationConfig {
57    /// `organization_id` must be the queried id, not `response.organization_id`, or a hostile
58    /// server could pass off another organization's validly-sealed blob.
59    fn from_response(
60        organization_id: OrganizationId,
61        response: PamRotationConfigResponseModel,
62    ) -> Result<Self, RotationError> {
63        let (sealed_data, wrapped_key) = if response.organization_id == Some(organization_id.into())
64        {
65            (response.sealed_data, response.wrapped_key)
66        } else {
67            tracing::debug!("PAM rotation config organization_id mismatch");
68            (None, None)
69        };
70
71        Ok(Self {
72            id: RotationConfigId::new(require!(response.id)),
73            organization_id,
74            cipher_id: CipherId::new(require!(response.cipher_id)),
75            target_system_id: TargetSystemId::new(require!(response.target_system_id)),
76            target_system_name: response.target_system_name.unwrap_or_default(),
77            target_system_method: require!(response.target_system_method).into(),
78            sealed_data,
79            wrapped_key,
80            schedule_cron: response.schedule_cron,
81            rotate_on_access_end: response.rotate_on_access_end.unwrap_or(false),
82            enabled: response.enabled.unwrap_or(true),
83            last_rotation_at: response
84                .last_rotation_at
85                .map(|date| date.parse())
86                .transpose()?,
87            next_rotation_at: response
88                .next_rotation_at
89                .map(|date| date.parse())
90                .transpose()?,
91            has_active_job: response.has_active_job.unwrap_or(false),
92            last_job_failed: response.last_job_failed.unwrap_or(false),
93            awaiting_manual_rotation: response.awaiting_manual_rotation.unwrap_or(false),
94            creation_date: require!(response.creation_date).parse()?,
95            revision_date: require!(response.revision_date).parse()?,
96        })
97    }
98
99    /// Unseals the blob and checks it against this row's `target_system_id` and `cipher_id`. Any
100    /// problem degrades to `None` rather than failing, so one bad blob can't fail a `list`.
101    fn unseal(
102        &self,
103        key: SymmetricKeySlotId,
104        ctx: &mut KeyStoreContext<KeySlotIds>,
105    ) -> Option<RotationConfigSealedFields> {
106        self.try_unseal(key, ctx)
107            .inspect_err(|reason| {
108                tracing::debug!(
109                    config_id = %self.id,
110                    reason,
111                    "PAM rotation config sealed blob rejected"
112                )
113            })
114            .ok()
115    }
116
117    fn try_unseal(
118        &self,
119        key: SymmetricKeySlotId,
120        ctx: &mut KeyStoreContext<KeySlotIds>,
121    ) -> Result<RotationConfigSealedFields, &'static str> {
122        let sealed_data = self.sealed_data.as_deref().ok_or("missing blob")?;
123        let wrapped_key = self.wrapped_key.as_deref().ok_or("missing wrapped key")?;
124        let envelope: DataEnvelope = sealed_data.parse().map_err(|_| "malformed sealed data")?;
125        // Unknown formats parse as `Unparseable` and fail to unseal.
126        let wrapped_key = EncString::from(wrapped_key);
127
128        let unsealed = unseal_rotation_config::<KeySlotIds>(&envelope, &wrapped_key, &key, ctx)
129            .map_err(|_| "unseal failed")?;
130
131        if unsealed.target_system_id != Uuid::from(self.target_system_id) {
132            return Err("target_system_id mismatch");
133        }
134        if unsealed.cipher_id != Uuid::from(self.cipher_id) {
135            return Err("cipher_id mismatch");
136        }
137
138        Ok(RotationConfigSealedFields {
139            account_identity: unsealed.account_identity,
140            terminate_sessions: unsealed.terminate_sessions,
141        })
142    }
143}
144
145impl IdentifyKey<SymmetricKeySlotId> for RotationConfig {
146    fn key_identifier(&self) -> SymmetricKeySlotId {
147        SymmetricKeySlotId::Organization(self.organization_id)
148    }
149}
150
151impl Decryptable<KeySlotIds, SymmetricKeySlotId, RotationConfigView> for RotationConfig {
152    /// Never fails: a blob that can't be verified leaves [`RotationConfigView::sealed`] `None`.
153    fn decrypt(
154        &self,
155        ctx: &mut KeyStoreContext<KeySlotIds>,
156        key: SymmetricKeySlotId,
157    ) -> Result<RotationConfigView, CryptoError> {
158        Ok(RotationConfigView {
159            id: self.id,
160            organization_id: self.organization_id,
161            cipher_id: self.cipher_id,
162            target_system_id: self.target_system_id,
163            target_system_name: self.target_system_name.clone(),
164            target_system_method: self.target_system_method,
165            sealed: self.unseal(key, ctx),
166            schedule_cron: self.schedule_cron.clone(),
167            rotate_on_access_end: self.rotate_on_access_end,
168            enabled: self.enabled,
169            last_rotation_at: self.last_rotation_at,
170            next_rotation_at: self.next_rotation_at,
171            has_active_job: self.has_active_job,
172            last_job_failed: self.last_job_failed,
173            awaiting_manual_rotation: self.awaiting_manual_rotation,
174            creation_date: self.creation_date,
175            revision_date: self.revision_date,
176        })
177    }
178}
179
180/// A managed credential: the link between a vault cipher and the target system its credential is
181/// rotated against, with its sealed fields unsealed.
182#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
183#[bitwarden_ffi::wasm_record]
184#[serde(rename_all = "camelCase")]
185pub struct RotationConfigView {
186    /// The config's unique identifier.
187    pub id: RotationConfigId,
188    /// The organization this config belongs to.
189    pub organization_id: OrganizationId,
190    /// The vault cipher whose credential this config manages. Its name is vault data, so decrypt
191    /// it from the caller's own cipher state.
192    pub cipher_id: CipherId,
193    /// The target system credentials are rotated against.
194    pub target_system_id: TargetSystemId,
195    /// The target system's display name, as of this read.
196    pub target_system_name: String,
197    /// The target system's rotation method, which decides the actions the config offers.
198    pub target_system_method: TargetSystemMethod,
199    /// `None` if the blob is missing, fails to unseal, or disagrees with this row's IDs.
200    pub sealed: Option<RotationConfigSealedFields>,
201    /// The Quartz cron expression driving scheduled rotation, or `None` for no schedule.
202    pub schedule_cron: Option<String>,
203    /// Whether the credential is rotated at the end of an access lease over the cipher.
204    pub rotate_on_access_end: bool,
205    /// False stops new rotation jobs from dispatching; jobs in flight run to completion.
206    pub enabled: bool,
207    /// The most recent completed rotation (UTC), or `None` absent any rotation.
208    pub last_rotation_at: Option<DateTime<Utc>>,
209    /// When the config is next due for rotation (UTC), or `None` when nothing is due.
210    pub next_rotation_at: Option<DateTime<Utc>>,
211    /// Whether the config has a pending or claimed job, or a timed-out one the sweep has not yet
212    /// recorded.
213    pub has_active_job: bool,
214    /// Whether the newest job ended badly: it reported failure, or it is unresolved and its
215    /// timeout has already been recorded by the sweep. Lets a list read resolve the Failed status
216    /// without fetching each config's job history. Mutually exclusive with `has_active_job`.
217    pub last_job_failed: bool,
218    /// Whether a manual-method config is waiting for an operator to record an out-of-band
219    /// rotation.
220    pub awaiting_manual_rotation: bool,
221    /// The config's creation time (UTC).
222    pub creation_date: DateTime<Utc>,
223    /// The config's last-modified time (UTC).
224    pub revision_date: DateTime<Utc>,
225}
226
227/// Security-relevant fields of a rotation config; the server only stores them sealed.
228#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
229#[bitwarden_ffi::wasm_record]
230#[serde(rename_all = "camelCase")]
231pub struct RotationConfigSealedFields {
232    /// The account within the target system, e.g. a username or UPN.
233    pub account_identity: String,
234    /// Whether to terminate the account's sessions after a successful rotation.
235    pub terminate_sessions: bool,
236}
237
238impl RotationConfigView {
239    /// Which actions this config offers, given the status of its target system.
240    ///
241    /// See [`rotation_config_actions`] for how an unloaded target system's `target_status` is
242    /// treated; `PendingSeal` counts as any other non-`Active` status.
243    pub fn actions(&self, target_status: Option<TargetSystemStatus>) -> RotationConfigActions {
244        rotation_config_actions(self, target_status)
245    }
246}
247
248/// A config together with its rotation history, still sealed.
249#[derive(Debug, Clone, PartialEq)]
250pub(crate) struct RotationConfigDetail {
251    config: RotationConfig,
252    jobs: Vec<RotationJob>,
253}
254
255impl RotationConfigDetail {
256    fn from_response(
257        organization_id: OrganizationId,
258        response: PamRotationConfigDetailResponseModel,
259    ) -> Result<Self, RotationError> {
260        let jobs = response
261            .jobs
262            .clone()
263            .unwrap_or_default()
264            .into_iter()
265            .map(RotationJob::try_from)
266            .collect::<Result<Vec<_>, _>>()?;
267
268        // The server flattens the config's own fields onto the detail payload, so the list model is
269        // rebuilt from it.
270        let config = RotationConfig::from_response(
271            organization_id,
272            PamRotationConfigResponseModel {
273                object: response.object,
274                id: response.id,
275                organization_id: response.organization_id,
276                cipher_id: response.cipher_id,
277                target_system_id: response.target_system_id,
278                target_system_name: response.target_system_name,
279                target_system_method: response.target_system_method,
280                sealed_data: response.sealed_data,
281                wrapped_key: response.wrapped_key,
282                schedule_cron: response.schedule_cron,
283                rotate_on_access_end: response.rotate_on_access_end,
284                next_rotation_at: response.next_rotation_at,
285                enabled: response.enabled,
286                last_rotation_at: response.last_rotation_at,
287                has_active_job: response.has_active_job,
288                awaiting_manual_rotation: response.awaiting_manual_rotation,
289                last_job_failed: response.last_job_failed,
290                creation_date: response.creation_date,
291                revision_date: response.revision_date,
292            },
293        )?;
294
295        Ok(Self { config, jobs })
296    }
297}
298
299impl IdentifyKey<SymmetricKeySlotId> for RotationConfigDetail {
300    fn key_identifier(&self) -> SymmetricKeySlotId {
301        self.config.key_identifier()
302    }
303}
304
305impl Decryptable<KeySlotIds, SymmetricKeySlotId, RotationConfigDetailView>
306    for RotationConfigDetail
307{
308    fn decrypt(
309        &self,
310        ctx: &mut KeyStoreContext<KeySlotIds>,
311        key: SymmetricKeySlotId,
312    ) -> Result<RotationConfigDetailView, CryptoError> {
313        Ok(RotationConfigDetailView {
314            config: self.config.decrypt(ctx, key)?,
315            jobs: self.jobs.clone(),
316        })
317    }
318}
319
320/// A config together with its rotation history.
321#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
322#[bitwarden_ffi::wasm_record]
323#[serde(rename_all = "camelCase")]
324pub struct RotationConfigDetailView {
325    /// The config itself.
326    pub config: RotationConfigView,
327    /// The config's rotation jobs, newest first, each carrying its attempts oldest first.
328    pub jobs: Vec<RotationJob>,
329}
330
331/// Request to create or update a rotation config.
332#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
333#[bitwarden_ffi::wasm_record]
334#[serde(rename_all = "camelCase")]
335pub struct RotationConfigCreateRequest {
336    /// The vault cipher whose credential this config will manage.
337    pub cipher_id: CipherId,
338    /// The target system to rotate against.
339    pub target_system_id: TargetSystemId,
340    /// The account within the target system.
341    pub account_identity: String,
342    /// Whether to terminate the account's sessions after a successful rotation. Requires the
343    /// target's sealed `supports_session_termination` to be `true`.
344    pub terminate_sessions: bool,
345    /// A Quartz cron expression, or `None` for no scheduled rotation.
346    pub schedule_cron: Option<String>,
347    /// Whether to rotate at the end of an access lease over the cipher.
348    pub rotate_on_access_end: bool,
349}
350
351/// A [`RotationConfigCreateRequest`] that passed the local checks. Exists so sealing takes only a
352/// validated request, and those checks can't be skipped.
353struct ValidatedRotationConfig(RotationConfigCreateRequest);
354
355impl ValidatedRotationConfig {
356    fn request(&self) -> &RotationConfigCreateRequest {
357        &self.0
358    }
359
360    /// Seals under `key`. Refuses `terminate_sessions` unless `target` supports it, and binds the
361    /// payload to the target and cipher ids.
362    fn seal(
363        &self,
364        target: &TargetSystemView,
365        key: SymmetricKeySlotId,
366        ctx: &mut KeyStoreContext<KeySlotIds>,
367    ) -> Result<Sealed, RotationError> {
368        let request = self.request();
369        // The target is fetched by the config's `target_system_id`, so a mismatch is a bug.
370        debug_assert_eq!(target.id, request.target_system_id);
371
372        let supports_termination = target
373            .sealed
374            .as_ref()
375            .and_then(|sealed| sealed.supports_session_termination);
376        if request.terminate_sessions && supports_termination != Some(true) {
377            return Err(RotationValidationError::SessionTerminationUnsupported.into());
378        }
379
380        if !ctx.has_symmetric_key(key) {
381            return Err(RotationError::MissingOrganizationKey);
382        }
383
384        let data = RotationConfigSealedV1 {
385            target_system_id: request.target_system_id.into(),
386            cipher_id: request.cipher_id.into(),
387            account_identity: request.account_identity.clone(),
388            terminate_sessions: request.terminate_sessions,
389        };
390        Ok(seal_rotation_config::<KeySlotIds>(data, &key, ctx)?)
391    }
392}
393
394impl TryFrom<RotationConfigCreateRequest> for ValidatedRotationConfig {
395    type Error = RotationError;
396
397    fn try_from(request: RotationConfigCreateRequest) -> Result<Self, Self::Error> {
398        validate_config_request(&request)?;
399        Ok(Self(request))
400    }
401}
402
403/// Client for PAM managed-credential (rotation config) operations.
404#[bitwarden_ffi::wasm_object]
405#[derive(FromClient)]
406pub struct RotationConfigsClient {
407    pub(crate) key_store: KeyStore<KeySlotIds>,
408    pub(crate) api_configurations: Arc<ApiConfigurations>,
409}
410
411#[bitwarden_ffi::wasm_export]
412impl RotationConfigsClient {
413    /// Lists the organization's rotation configs.
414    pub async fn list(
415        &self,
416        organization_id: OrganizationId,
417    ) -> Result<Vec<RotationConfigView>, RotationError> {
418        let response = self
419            .api_configurations
420            .api_client
421            .pam_access_connector_rotation_configs_api()
422            .get_all(organization_id.into())
423            .await?;
424
425        let configs = response
426            .data
427            .unwrap_or_default()
428            .into_iter()
429            .map(|item| RotationConfig::from_response(organization_id, item))
430            .collect::<Result<Vec<_>, _>>()?;
431        Ok(self.key_store.decrypt_list(&configs)?)
432    }
433
434    /// Reads one config with its rotation history.
435    pub async fn get(
436        &self,
437        organization_id: OrganizationId,
438        id: RotationConfigId,
439    ) -> Result<RotationConfigDetailView, RotationError> {
440        let response = self
441            .api_configurations
442            .api_client
443            .pam_access_connector_rotation_configs_api()
444            .get(organization_id.into(), id.into())
445            .await?;
446
447        let detail = RotationConfigDetail::from_response(organization_id, response)?;
448        Ok(self.key_store.decrypt(&detail)?)
449    }
450
451    /// Validates, seals, and creates a rotation config.
452    pub async fn create(
453        &self,
454        organization_id: OrganizationId,
455        request: RotationConfigCreateRequest,
456    ) -> Result<RotationConfigDetailView, RotationError> {
457        let config = ValidatedRotationConfig::try_from(request)?;
458        let target = self
459            .verified_target(organization_id, config.request().target_system_id)
460            .await?;
461
462        let sealed = {
463            let mut ctx = self.key_store.context_mut();
464            config.seal(
465                &target,
466                SymmetricKeySlotId::Organization(organization_id),
467                &mut ctx,
468            )?
469        };
470        let request = config.request();
471        let response = self
472            .api_configurations
473            .api_client
474            .pam_access_connector_rotation_configs_api()
475            .post(
476                organization_id.into(),
477                CreateRotationConfigRequestModel {
478                    cipher_id: request.cipher_id.into(),
479                    target_system_id: request.target_system_id.into(),
480                    sealed_data: sealed.envelope.to_string(),
481                    wrapped_key: sealed.wrapped_key.to_string(),
482                    schedule_cron: request.schedule_cron.clone(),
483                    rotate_on_access_end: Some(request.rotate_on_access_end),
484                },
485            )
486            .await?;
487
488        let detail = RotationConfigDetail::from_response(organization_id, response)?;
489        Ok(self.key_store.decrypt(&detail)?)
490    }
491
492    /// Re-seals the whole blob, so every field must be resupplied; `cipher_id` and
493    /// `target_system_id` must match the existing config.
494    pub async fn update(
495        &self,
496        organization_id: OrganizationId,
497        id: RotationConfigId,
498        request: RotationConfigCreateRequest,
499    ) -> Result<RotationConfigDetailView, RotationError> {
500        let config = ValidatedRotationConfig::try_from(request)?;
501
502        let existing = self.get(organization_id, id).await?;
503        if existing.config.cipher_id != config.request().cipher_id
504            || existing.config.target_system_id != config.request().target_system_id
505        {
506            return Err(RotationValidationError::RotationConfigImmutableFieldMismatch.into());
507        }
508
509        let target = self
510            .verified_target(organization_id, config.request().target_system_id)
511            .await?;
512
513        let sealed = {
514            let mut ctx = self.key_store.context_mut();
515            config.seal(
516                &target,
517                SymmetricKeySlotId::Organization(organization_id),
518                &mut ctx,
519            )?
520        };
521        let request = config.request();
522        let response = self
523            .api_configurations
524            .api_client
525            .pam_access_connector_rotation_configs_api()
526            .put(
527                organization_id.into(),
528                id.into(),
529                UpdateRotationConfigRequestModel {
530                    sealed_data: sealed.envelope.to_string(),
531                    wrapped_key: sealed.wrapped_key.to_string(),
532                    schedule_cron: request.schedule_cron.clone(),
533                    rotate_on_access_end: Some(request.rotate_on_access_end),
534                },
535            )
536            .await?;
537
538        let detail = RotationConfigDetail::from_response(organization_id, response)?;
539        Ok(self.key_store.decrypt(&detail)?)
540    }
541
542    /// The target must exist with verified sealed fields, unless still `PendingSeal`.
543    async fn verified_target(
544        &self,
545        organization_id: OrganizationId,
546        target_system_id: TargetSystemId,
547    ) -> Result<TargetSystemView, RotationError> {
548        let response = self
549            .api_configurations
550            .api_client
551            .pam_access_connector_rotation_target_systems_api()
552            .get_all(organization_id.into())
553            .await?;
554
555        let item: PamTargetSystemResponseModel = response
556            .data
557            .unwrap_or_default()
558            .into_iter()
559            .find(|item| item.id == Some(target_system_id.into()))
560            .ok_or(RotationError::TargetSystemNotFound)?;
561
562        let target = self
563            .key_store
564            .decrypt(&TargetSystem::from_response(organization_id, item)?)?;
565
566        if target.status != TargetSystemStatus::PendingSeal && target.sealed.is_none() {
567            return Err(RotationValidationError::TargetSystemSealInvalid.into());
568        }
569
570        Ok(target)
571    }
572
573    /// Pauses a config, so no new rotation jobs are dispatched.
574    pub async fn pause(
575        &self,
576        organization_id: OrganizationId,
577        id: RotationConfigId,
578    ) -> Result<(), RotationError> {
579        self.api_configurations
580            .api_client
581            .pam_access_connector_rotation_configs_api()
582            .pause(organization_id.into(), id.into())
583            .await?;
584
585        Ok(())
586    }
587
588    /// Resumes a paused config.
589    pub async fn resume(
590        &self,
591        organization_id: OrganizationId,
592        id: RotationConfigId,
593    ) -> Result<(), RotationError> {
594        self.api_configurations
595            .api_client
596            .pam_access_connector_rotation_configs_api()
597            .resume(organization_id.into(), id.into())
598            .await?;
599
600        Ok(())
601    }
602
603    /// Dispatches an on-demand rotation now, subject to the server's per-config cooldown.
604    pub async fn rotate_now(
605        &self,
606        organization_id: OrganizationId,
607        id: RotationConfigId,
608    ) -> Result<(), RotationError> {
609        self.api_configurations
610            .api_client
611            .pam_access_connector_rotation_configs_api()
612            .rotate(organization_id.into(), id.into())
613            .await?;
614
615        Ok(())
616    }
617
618    /// Records that an operator rotated a manual-target config's credential out of band, clearing
619    /// its awaiting-manual-rotation state.
620    pub async fn record_manual_rotation(
621        &self,
622        organization_id: OrganizationId,
623        id: RotationConfigId,
624    ) -> Result<(), RotationError> {
625        self.api_configurations
626            .api_client
627            .pam_access_connector_rotation_configs_api()
628            .record_manual(organization_id.into(), id.into())
629            .await?;
630
631        Ok(())
632    }
633
634    /// Deletes a rotation config. The cipher and the target system are untouched; only the link
635    /// between them, and its rotation history, go away.
636    pub async fn delete(
637        &self,
638        organization_id: OrganizationId,
639        id: RotationConfigId,
640    ) -> Result<(), RotationError> {
641        self.api_configurations
642            .api_client
643            .pam_access_connector_rotation_configs_api()
644            .delete(organization_id.into(), id.into())
645            .await?;
646
647        Ok(())
648    }
649
650    /// Which actions a config offers, given the status of its target system. Exposed here because
651    /// a `wasm_record` struct crosses the WASM boundary as plain data, without
652    /// [`RotationConfigView::actions`].
653    pub fn actions(
654        &self,
655        config: RotationConfigView,
656        target_status: Option<TargetSystemStatus>,
657    ) -> RotationConfigActions {
658        config.actions(target_status)
659    }
660}
661
662#[cfg(test)]
663mod tests {
664    use bitwarden_api_api::{
665        apis::ApiClient,
666        models::{
667            PamRotationConfigResponseModelListResponseModel, PamRotationJobResponseModel,
668            PamRotationJobStatus as ApiRotationJobStatus, PamRotationSource as ApiRotationSource,
669            PamTargetSystemMethod as ApiTargetSystemMethod,
670            PamTargetSystemResponseModelListResponseModel,
671            PamTargetSystemStatus as ApiTargetSystemStatus,
672        },
673    };
674    use bitwarden_core::key_management::create_test_crypto_with_user_and_org_key;
675    use bitwarden_crypto::{
676        EncString, SymmetricCryptoKey, SymmetricKeyAlgorithm, safe::DataEnvelope,
677    };
678    use bitwarden_pam_sealed::{
679        RotationConfigSealedV1, SealedPasswordPolicy, SealedTargetSystemKind,
680        SealedTargetSystemMethod, TargetSystemSealedV1, seal_target_system, unseal_rotation_config,
681    };
682    use uuid::{Uuid, uuid};
683
684    use super::*;
685    use crate::rotation::{
686        models::{RotationJobStatus, RotationSource},
687        validate::RotationValidationError,
688    };
689
690    fn organization_id() -> OrganizationId {
691        OrganizationId::new(uuid!("11111111-1111-1111-1111-111111111111"))
692    }
693
694    fn config_id() -> RotationConfigId {
695        RotationConfigId::new(uuid!("22222222-2222-2222-2222-222222222222"))
696    }
697
698    fn cipher_id() -> CipherId {
699        CipherId::new(uuid!("33333333-3333-3333-3333-333333333333"))
700    }
701
702    fn target_system_id() -> TargetSystemId {
703        TargetSystemId::new(uuid!("44444444-4444-4444-4444-444444444444"))
704    }
705
706    fn job_id() -> Uuid {
707        uuid!("55555555-5555-5555-5555-555555555555")
708    }
709
710    fn organization_key() -> SymmetricCryptoKey {
711        SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac)
712    }
713
714    fn client(api_client: ApiClient) -> RotationConfigsClient {
715        client_with_org_key(api_client, organization_key())
716    }
717
718    fn client_with_org_key(
719        api_client: ApiClient,
720        organization_key: SymmetricCryptoKey,
721    ) -> RotationConfigsClient {
722        RotationConfigsClient {
723            key_store: create_test_crypto_with_user_and_org_key(
724                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
725                organization_id(),
726                organization_key,
727            ),
728            api_configurations: Arc::new(ApiConfigurations::from_api_client(api_client)),
729        }
730    }
731
732    fn seal_config_with(
733        organization_key: &SymmetricCryptoKey,
734        data: RotationConfigSealedV1,
735    ) -> Sealed {
736        let store = create_test_crypto_with_user_and_org_key(
737            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
738            organization_id(),
739            organization_key.clone(),
740        );
741        let mut ctx = store.context_mut();
742        seal_rotation_config::<KeySlotIds>(
743            data,
744            &SymmetricKeySlotId::Organization(organization_id()),
745            &mut ctx,
746        )
747        .expect("sealing succeeds")
748    }
749
750    fn seal_target_with(
751        organization_key: &SymmetricCryptoKey,
752        data: TargetSystemSealedV1,
753    ) -> Sealed {
754        let store = create_test_crypto_with_user_and_org_key(
755            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
756            organization_id(),
757            organization_key.clone(),
758        );
759        let mut ctx = store.context_mut();
760        seal_target_system::<KeySlotIds>(
761            data,
762            &SymmetricKeySlotId::Organization(organization_id()),
763            &mut ctx,
764        )
765        .expect("sealing succeeds")
766    }
767
768    fn sample_sealed_data() -> RotationConfigSealedV1 {
769        RotationConfigSealedV1 {
770            target_system_id: target_system_id().into(),
771            cipher_id: cipher_id().into(),
772            account_identity: "svc_rotation".to_string(),
773            terminate_sessions: true,
774        }
775    }
776
777    fn config_view(
778        organization_id: OrganizationId,
779        response: PamRotationConfigResponseModel,
780        ctx: &mut KeyStoreContext<KeySlotIds>,
781    ) -> Result<RotationConfigView, RotationError> {
782        let config = RotationConfig::from_response(organization_id, response)?;
783        let key = config.key_identifier();
784        Ok(config.decrypt(ctx, key)?)
785    }
786
787    fn detail_view(
788        organization_id: OrganizationId,
789        response: PamRotationConfigDetailResponseModel,
790        ctx: &mut KeyStoreContext<KeySlotIds>,
791    ) -> Result<RotationConfigDetailView, RotationError> {
792        let detail = RotationConfigDetail::from_response(organization_id, response)?;
793        let key = detail.key_identifier();
794        Ok(detail.decrypt(ctx, key)?)
795    }
796
797    /// A payload with every optional field populated, so a test that clears one is unambiguous
798    /// about which field it is exercising.
799    fn sample_response(organization_key: &SymmetricCryptoKey) -> PamRotationConfigResponseModel {
800        let payload = seal_config_with(organization_key, sample_sealed_data());
801        PamRotationConfigResponseModel {
802            id: Some(config_id().into()),
803            organization_id: Some(organization_id().into()),
804            cipher_id: Some(cipher_id().into()),
805            target_system_id: Some(target_system_id().into()),
806            target_system_name: Some("Prod SQL".to_string()),
807            target_system_method: Some(ApiTargetSystemMethod::Automatic),
808            sealed_data: Some(payload.envelope.to_string()),
809            wrapped_key: Some(payload.wrapped_key.to_string()),
810            schedule_cron: Some("0 0 0 * * ?".to_string()),
811            rotate_on_access_end: Some(true),
812            next_rotation_at: Some("2026-02-02T00:00:00Z".to_string()),
813            enabled: Some(true),
814            last_rotation_at: Some("2026-02-01T00:00:00Z".to_string()),
815            has_active_job: Some(true),
816            awaiting_manual_rotation: Some(true),
817            creation_date: Some("2026-01-01T00:00:00Z".to_string()),
818            revision_date: Some("2026-01-15T00:00:00Z".to_string()),
819            ..Default::default()
820        }
821    }
822
823    /// The same config as [`sample_response`], as the detail routes return it: the config's own
824    /// fields flattened onto the payload, plus its rotation history.
825    fn sample_detail_response(
826        organization_key: &SymmetricCryptoKey,
827        jobs: Option<Vec<PamRotationJobResponseModel>>,
828    ) -> PamRotationConfigDetailResponseModel {
829        let config = sample_response(organization_key);
830        PamRotationConfigDetailResponseModel {
831            object: config.object,
832            id: config.id,
833            organization_id: config.organization_id,
834            cipher_id: config.cipher_id,
835            target_system_id: config.target_system_id,
836            target_system_name: config.target_system_name,
837            target_system_method: config.target_system_method,
838            sealed_data: config.sealed_data,
839            wrapped_key: config.wrapped_key,
840            schedule_cron: config.schedule_cron,
841            rotate_on_access_end: config.rotate_on_access_end,
842            next_rotation_at: config.next_rotation_at,
843            enabled: config.enabled,
844            last_rotation_at: config.last_rotation_at,
845            has_active_job: config.has_active_job,
846            awaiting_manual_rotation: config.awaiting_manual_rotation,
847            last_job_failed: config.last_job_failed,
848            creation_date: config.creation_date,
849            revision_date: config.revision_date,
850            jobs,
851        }
852    }
853
854    fn sample_job(id: Uuid) -> PamRotationJobResponseModel {
855        PamRotationJobResponseModel {
856            id: Some(id),
857            rotation_config_id: Some(config_id().into()),
858            source: Some(ApiRotationSource::OnDemand),
859            status: Some(ApiRotationJobStatus::Pending),
860            creation_date: Some("2026-01-10T00:00:00Z".to_string()),
861            ..Default::default()
862        }
863    }
864
865    fn create_request() -> RotationConfigCreateRequest {
866        RotationConfigCreateRequest {
867            cipher_id: cipher_id(),
868            target_system_id: target_system_id(),
869            account_identity: "svc_rotation".to_string(),
870            terminate_sessions: true,
871            schedule_cron: Some("0 0 0 * * ?".to_string()),
872            rotate_on_access_end: true,
873        }
874    }
875
876    /// A sealed, active, automatic target supporting session termination.
877    fn terminable_target_response(
878        organization_key: &SymmetricCryptoKey,
879    ) -> PamTargetSystemResponseModel {
880        let payload = seal_target_with(
881            organization_key,
882            TargetSystemSealedV1 {
883                target_system_id: target_system_id().into(),
884                method: SealedTargetSystemMethod::Automatic,
885                kind: Some(SealedTargetSystemKind::CustomScript),
886                password_policy: SealedPasswordPolicy {
887                    min_length: 14,
888                    max_length: 20,
889                    include_uppercase: true,
890                    include_lowercase: true,
891                    include_digits: true,
892                    include_symbols: false,
893                },
894                supports_session_termination: Some(true),
895            },
896        );
897        PamTargetSystemResponseModel {
898            id: Some(target_system_id().into()),
899            organization_id: Some(organization_id().into()),
900            name: Some("Prod SQL".to_string()),
901            method: Some(ApiTargetSystemMethod::Automatic),
902            status: Some(ApiTargetSystemStatus::Active),
903            sealed_data: Some(payload.envelope.to_string()),
904            wrapped_key: Some(payload.wrapped_key.to_string()),
905            creation_date: Some("2026-01-01T00:00:00Z".to_string()),
906            revision_date: Some("2026-01-01T00:00:00Z".to_string()),
907            ..Default::default()
908        }
909    }
910
911    fn target_systems_response(
912        targets: Vec<PamTargetSystemResponseModel>,
913    ) -> PamTargetSystemResponseModelListResponseModel {
914        PamTargetSystemResponseModelListResponseModel {
915            data: Some(targets),
916            ..Default::default()
917        }
918    }
919
920    #[test]
921    fn a_full_payload_maps_every_field() {
922        let organization_key = organization_key();
923        let store = create_test_crypto_with_user_and_org_key(
924            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
925            organization_id(),
926            organization_key.clone(),
927        );
928        let mut ctx = store.context_mut();
929
930        let config = config_view(
931            organization_id(),
932            sample_response(&organization_key),
933            &mut ctx,
934        )
935        .expect("the payload is valid");
936
937        assert_eq!(config.id, config_id());
938        assert_eq!(config.organization_id, organization_id());
939        assert_eq!(config.cipher_id, cipher_id());
940        assert_eq!(config.target_system_id, target_system_id());
941        assert_eq!(config.target_system_name, "Prod SQL");
942        assert_eq!(config.target_system_method, TargetSystemMethod::Automatic);
943        let sealed = config.sealed.expect("the blob is sealed");
944        assert_eq!(sealed.account_identity, "svc_rotation");
945        assert!(sealed.terminate_sessions);
946        assert_eq!(config.schedule_cron.as_deref(), Some("0 0 0 * * ?"));
947        assert!(config.rotate_on_access_end);
948        assert!(config.enabled);
949        assert_eq!(
950            config.last_rotation_at,
951            Some("2026-02-01T00:00:00Z".parse().expect("a valid timestamp"))
952        );
953        assert_eq!(
954            config.next_rotation_at,
955            Some("2026-02-02T00:00:00Z".parse().expect("a valid timestamp"))
956        );
957        assert!(config.has_active_job);
958        assert!(config.awaiting_manual_rotation);
959        assert_eq!(
960            config.creation_date,
961            "2026-01-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap()
962        );
963        assert_eq!(
964            config.revision_date,
965            "2026-01-15T00:00:00Z".parse::<DateTime<Utc>>().unwrap()
966        );
967    }
968
969    /// A blob sealed for a different cipher.
970    #[test]
971    fn an_invalid_blob_degrades_to_no_sealed_fields() {
972        let organization_key = organization_key();
973        let wrong_cipher_blob = seal_config_with(
974            &organization_key,
975            RotationConfigSealedV1 {
976                cipher_id: uuid!("99999999-9999-9999-9999-999999999999"),
977                ..sample_sealed_data()
978            },
979        );
980
981        let sample = sample_response(&organization_key);
982        for (sealed_data, wrapped_key) in [
983            (
984                Some("not a sealed blob".to_string()),
985                sample.wrapped_key.clone(),
986            ),
987            (
988                Some(wrong_cipher_blob.envelope.to_string()),
989                Some(wrong_cipher_blob.wrapped_key.to_string()),
990            ),
991            (None, sample.wrapped_key.clone()),
992            (sample.sealed_data.clone(), None),
993        ] {
994            let store = create_test_crypto_with_user_and_org_key(
995                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
996                organization_id(),
997                organization_key.clone(),
998            );
999            let mut ctx = store.context_mut();
1000
1001            let response = PamRotationConfigResponseModel {
1002                sealed_data,
1003                wrapped_key,
1004                ..sample_response(&organization_key)
1005            };
1006
1007            let config =
1008                config_view(organization_id(), response, &mut ctx).expect("the payload is valid");
1009
1010            assert_eq!(config.sealed, None);
1011        }
1012    }
1013
1014    /// A wrapped key from a different seal of the same data can't open this envelope.
1015    #[test]
1016    fn a_wrapped_key_from_a_different_seal_degrades_to_no_sealed_fields() {
1017        let organization_key = organization_key();
1018        let store = create_test_crypto_with_user_and_org_key(
1019            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1020            organization_id(),
1021            organization_key.clone(),
1022        );
1023        let mut ctx = store.context_mut();
1024
1025        let other = seal_config_with(&organization_key, sample_sealed_data());
1026        let response = PamRotationConfigResponseModel {
1027            wrapped_key: Some(other.wrapped_key.to_string()),
1028            ..sample_response(&organization_key)
1029        };
1030
1031        let config =
1032            config_view(organization_id(), response, &mut ctx).expect("the payload is valid");
1033
1034        assert_eq!(config.sealed, None);
1035    }
1036
1037    /// A hostile server serves org B's item, with org B's validly-sealed blob, in org A's list.
1038    #[test]
1039    fn a_blob_from_a_different_organization_is_not_trusted() {
1040        let org_a = organization_id();
1041        let org_b = OrganizationId::new(uuid!("66666666-6666-6666-6666-666666666666"));
1042        let org_a_key = organization_key();
1043        let org_b_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
1044
1045        // The caller holds both orgs' keys.
1046        let org_b_blob = seal_config_with(&org_b_key, sample_sealed_data());
1047
1048        let store = KeyStore::<KeySlotIds>::default();
1049        {
1050            let mut ctx = store.context_mut();
1051            #[allow(deprecated)]
1052            ctx.set_symmetric_key(SymmetricKeySlotId::Organization(org_a), org_a_key)
1053                .expect("mutable context");
1054            #[allow(deprecated)]
1055            ctx.set_symmetric_key(SymmetricKeySlotId::Organization(org_b), org_b_key)
1056                .expect("mutable context");
1057        }
1058
1059        let response = PamRotationConfigResponseModel {
1060            organization_id: Some(org_b.into()),
1061            sealed_data: Some(org_b_blob.envelope.to_string()),
1062            wrapped_key: Some(org_b_blob.wrapped_key.to_string()),
1063            ..sample_response(&organization_key())
1064        };
1065
1066        let mut ctx = store.context_mut();
1067        let config = config_view(org_a, response, &mut ctx)
1068            .expect("the payload is still structurally valid");
1069
1070        assert_eq!(config.organization_id, org_a);
1071        assert_eq!(config.sealed, None);
1072    }
1073
1074    #[test]
1075    fn an_omitted_enabled_flag_means_the_config_is_active() {
1076        let organization_key = organization_key();
1077        let store = create_test_crypto_with_user_and_org_key(
1078            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1079            organization_id(),
1080            organization_key.clone(),
1081        );
1082        let mut ctx = store.context_mut();
1083
1084        let config = config_view(
1085            organization_id(),
1086            PamRotationConfigResponseModel {
1087                enabled: None,
1088                ..sample_response(&organization_key)
1089            },
1090            &mut ctx,
1091        )
1092        .expect("the payload is valid");
1093
1094        assert!(config.enabled);
1095        assert!(config.actions(Some(TargetSystemStatus::Active)).can_pause);
1096        assert!(!config.actions(Some(TargetSystemStatus::Active)).can_resume);
1097    }
1098
1099    #[test]
1100    fn the_remaining_absent_fields_default_to_not_set() {
1101        let organization_key = organization_key();
1102        let store = create_test_crypto_with_user_and_org_key(
1103            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1104            organization_id(),
1105            organization_key.clone(),
1106        );
1107        let mut ctx = store.context_mut();
1108
1109        let config = config_view(
1110            organization_id(),
1111            PamRotationConfigResponseModel {
1112                target_system_name: None,
1113                schedule_cron: None,
1114                rotate_on_access_end: None,
1115                last_rotation_at: None,
1116                next_rotation_at: None,
1117                has_active_job: None,
1118                awaiting_manual_rotation: None,
1119                ..sample_response(&organization_key)
1120            },
1121            &mut ctx,
1122        )
1123        .expect("the payload is valid");
1124
1125        assert_eq!(config.target_system_name, "");
1126        assert_eq!(config.schedule_cron, None);
1127        assert!(!config.rotate_on_access_end);
1128        assert_eq!(config.last_rotation_at, None);
1129        assert_eq!(config.next_rotation_at, None);
1130        assert!(!config.has_active_job);
1131        assert!(!config.awaiting_manual_rotation);
1132    }
1133
1134    #[test]
1135    fn a_missing_required_field_is_reported_rather_than_defaulted() {
1136        let organization_key = organization_key();
1137        let store = create_test_crypto_with_user_and_org_key(
1138            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1139            organization_id(),
1140            organization_key.clone(),
1141        );
1142        let mut ctx = store.context_mut();
1143
1144        for response in [
1145            PamRotationConfigResponseModel {
1146                id: None,
1147                ..sample_response(&organization_key)
1148            },
1149            // `organization_id: None` degrades instead; see
1150            // `a_blob_from_a_different_organization_is_not_trusted`.
1151            PamRotationConfigResponseModel {
1152                cipher_id: None,
1153                ..sample_response(&organization_key)
1154            },
1155            PamRotationConfigResponseModel {
1156                target_system_id: None,
1157                ..sample_response(&organization_key)
1158            },
1159            PamRotationConfigResponseModel {
1160                target_system_method: None,
1161                ..sample_response(&organization_key)
1162            },
1163            PamRotationConfigResponseModel {
1164                creation_date: None,
1165                ..sample_response(&organization_key)
1166            },
1167            PamRotationConfigResponseModel {
1168                revision_date: None,
1169                ..sample_response(&organization_key)
1170            },
1171        ] {
1172            assert!(matches!(
1173                config_view(organization_id(), response, &mut ctx),
1174                Err(RotationError::MissingField(_))
1175            ));
1176        }
1177    }
1178
1179    #[test]
1180    fn an_unparseable_date_is_reported() {
1181        let organization_key = organization_key();
1182        let store = create_test_crypto_with_user_and_org_key(
1183            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1184            organization_id(),
1185            organization_key.clone(),
1186        );
1187        let mut ctx = store.context_mut();
1188
1189        for response in [
1190            PamRotationConfigResponseModel {
1191                creation_date: Some("not a date".to_string()),
1192                ..sample_response(&organization_key)
1193            },
1194            PamRotationConfigResponseModel {
1195                revision_date: Some("not a date".to_string()),
1196                ..sample_response(&organization_key)
1197            },
1198            PamRotationConfigResponseModel {
1199                last_rotation_at: Some("not a date".to_string()),
1200                ..sample_response(&organization_key)
1201            },
1202            PamRotationConfigResponseModel {
1203                next_rotation_at: Some("not a date".to_string()),
1204                ..sample_response(&organization_key)
1205            },
1206        ] {
1207            assert!(matches!(
1208                config_view(organization_id(), response, &mut ctx),
1209                Err(RotationError::Chrono(_))
1210            ));
1211        }
1212    }
1213
1214    #[test]
1215    fn an_unrecognized_method_degrades_to_unknown() {
1216        let organization_key = organization_key();
1217        let store = create_test_crypto_with_user_and_org_key(
1218            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1219            organization_id(),
1220            organization_key.clone(),
1221        );
1222        let mut ctx = store.context_mut();
1223
1224        let config = config_view(
1225            organization_id(),
1226            PamRotationConfigResponseModel {
1227                target_system_method: Some(ApiTargetSystemMethod::__Unknown(9)),
1228                ..sample_response(&organization_key)
1229            },
1230            &mut ctx,
1231        )
1232        .expect("an unknown method still maps");
1233
1234        assert_eq!(config.target_system_method, TargetSystemMethod::Unknown);
1235    }
1236
1237    /// The detail conversion hand-copies each field of the flattened payload, so a dropped one
1238    /// would silently read as absent.
1239    #[test]
1240    fn the_detail_payload_yields_the_same_config_as_the_list_payload() {
1241        let organization_key = organization_key();
1242        let store = create_test_crypto_with_user_and_org_key(
1243            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1244            organization_id(),
1245            organization_key.clone(),
1246        );
1247        let mut ctx = store.context_mut();
1248
1249        let detail = detail_view(
1250            organization_id(),
1251            sample_detail_response(&organization_key, Some(vec![sample_job(job_id())])),
1252            &mut ctx,
1253        )
1254        .expect("the payload is valid");
1255
1256        assert_eq!(
1257            detail.config,
1258            config_view(
1259                organization_id(),
1260                sample_response(&organization_key),
1261                &mut ctx
1262            )
1263            .expect("the payload is valid")
1264        );
1265    }
1266
1267    #[test]
1268    fn detail_jobs_keep_the_order_the_server_sent() {
1269        let organization_key = organization_key();
1270        let store = create_test_crypto_with_user_and_org_key(
1271            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1272            organization_id(),
1273            organization_key.clone(),
1274        );
1275        let mut ctx = store.context_mut();
1276
1277        let second = uuid!("66666666-6666-6666-6666-666666666666");
1278        let detail = detail_view(
1279            organization_id(),
1280            sample_detail_response(
1281                &organization_key,
1282                Some(vec![sample_job(job_id()), sample_job(second)]),
1283            ),
1284            &mut ctx,
1285        )
1286        .expect("the payload is valid");
1287
1288        let ids: Vec<Uuid> = detail.jobs.iter().map(|job| job.id.into()).collect();
1289        assert_eq!(ids, [job_id(), second]);
1290        assert_eq!(detail.jobs[0].source, RotationSource::OnDemand);
1291        assert_eq!(detail.jobs[0].status, RotationJobStatus::Pending);
1292    }
1293
1294    /// A config that has never rotated has no history, which is not an error.
1295    #[test]
1296    fn a_detail_payload_without_jobs_has_no_jobs() {
1297        let organization_key = organization_key();
1298        let store = create_test_crypto_with_user_and_org_key(
1299            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1300            organization_id(),
1301            organization_key.clone(),
1302        );
1303        let mut ctx = store.context_mut();
1304
1305        let detail = detail_view(
1306            organization_id(),
1307            sample_detail_response(&organization_key, None),
1308            &mut ctx,
1309        )
1310        .expect("no jobs is fine");
1311
1312        assert!(detail.jobs.is_empty());
1313    }
1314
1315    #[test]
1316    fn a_malformed_job_fails_the_whole_detail() {
1317        let organization_key = organization_key();
1318        let store = create_test_crypto_with_user_and_org_key(
1319            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1320            organization_id(),
1321            organization_key.clone(),
1322        );
1323        let mut ctx = store.context_mut();
1324
1325        let malformed = PamRotationJobResponseModel {
1326            rotation_config_id: None,
1327            ..sample_job(job_id())
1328        };
1329
1330        let result = detail_view(
1331            organization_id(),
1332            sample_detail_response(&organization_key, Some(vec![malformed])),
1333            &mut ctx,
1334        );
1335
1336        assert!(matches!(result, Err(RotationError::MissingField(_))));
1337    }
1338
1339    #[tokio::test]
1340    async fn list_maps_the_organizations_configs() {
1341        let organization_key = organization_key();
1342        let api_client = {
1343            let organization_key = organization_key.clone();
1344            ApiClient::new_mocked(move |mock| {
1345                mock.pam_access_connector_rotation_configs_api
1346                    .expect_get_all()
1347                    .withf(|org_id| *org_id == Uuid::from(organization_id()))
1348                    .returning(move |_org_id| {
1349                        Ok(PamRotationConfigResponseModelListResponseModel {
1350                            data: Some(vec![sample_response(&organization_key)]),
1351                            ..Default::default()
1352                        })
1353                    })
1354                    .once();
1355            })
1356        };
1357
1358        let configs = client_with_org_key(api_client, organization_key)
1359            .list(organization_id())
1360            .await
1361            .expect("the list succeeds");
1362
1363        assert_eq!(configs.len(), 1);
1364        assert_eq!(configs[0].id, config_id());
1365        assert!(configs[0].sealed.is_some());
1366    }
1367
1368    #[tokio::test]
1369    async fn an_organization_with_no_configs_lists_empty() {
1370        let api_client = ApiClient::new_mocked(move |mock| {
1371            mock.pam_access_connector_rotation_configs_api
1372                .expect_get_all()
1373                .returning(move |_org_id| {
1374                    Ok(PamRotationConfigResponseModelListResponseModel::default())
1375                })
1376                .once();
1377        });
1378
1379        let configs = client(api_client)
1380            .list(organization_id())
1381            .await
1382            .expect("an absent list is not an error");
1383
1384        assert!(configs.is_empty());
1385    }
1386
1387    #[tokio::test]
1388    async fn list_returns_the_rest_when_one_item_has_an_invalid_blob() {
1389        let organization_key = organization_key();
1390        let api_client = {
1391            let organization_key = organization_key.clone();
1392            ApiClient::new_mocked(move |mock| {
1393                mock.pam_access_connector_rotation_configs_api
1394                    .expect_get_all()
1395                    .returning(move |_org_id| {
1396                        let bad = PamRotationConfigResponseModel {
1397                            id: Some(uuid!("77777777-7777-7777-7777-777777777777")),
1398                            sealed_data: Some("not a sealed blob".to_string()),
1399                            ..sample_response(&organization_key)
1400                        };
1401                        Ok(PamRotationConfigResponseModelListResponseModel {
1402                            data: Some(vec![sample_response(&organization_key), bad]),
1403                            ..Default::default()
1404                        })
1405                    })
1406                    .once();
1407            })
1408        };
1409
1410        let configs = client_with_org_key(api_client, organization_key)
1411            .list(organization_id())
1412            .await
1413            .expect("one invalid item does not fail the list");
1414
1415        assert_eq!(configs.len(), 2);
1416        assert!(configs[0].sealed.is_some());
1417        assert_eq!(configs[1].sealed, None);
1418    }
1419
1420    #[tokio::test]
1421    async fn list_fails_if_a_required_field_is_missing() {
1422        let organization_key = organization_key();
1423        let api_client = {
1424            let organization_key = organization_key.clone();
1425            ApiClient::new_mocked(move |mock| {
1426                mock.pam_access_connector_rotation_configs_api
1427                    .expect_get_all()
1428                    .returning(move |_org_id| {
1429                        Ok(PamRotationConfigResponseModelListResponseModel {
1430                            data: Some(vec![PamRotationConfigResponseModel {
1431                                cipher_id: None,
1432                                ..sample_response(&organization_key)
1433                            }]),
1434                            ..Default::default()
1435                        })
1436                    })
1437                    .once();
1438            })
1439        };
1440
1441        let result = client_with_org_key(api_client, organization_key)
1442            .list(organization_id())
1443            .await;
1444
1445        assert!(matches!(result, Err(RotationError::MissingField(_))));
1446    }
1447
1448    #[tokio::test]
1449    async fn list_surfaces_an_api_error() {
1450        let api_client = ApiClient::new_mocked(move |mock| {
1451            mock.pam_access_connector_rotation_configs_api
1452                .expect_get_all()
1453                .returning(move |_org_id| {
1454                    Err(bitwarden_api_api::apis::Error::Response(
1455                        bitwarden_api_api::apis::ResponseContent {
1456                            status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
1457                            message: String::new(),
1458                        },
1459                    ))
1460                })
1461                .once();
1462        });
1463
1464        let result = client(api_client).list(organization_id()).await;
1465
1466        assert!(matches!(result, Err(RotationError::Api(_))));
1467    }
1468
1469    #[tokio::test]
1470    async fn get_reads_the_requested_config_with_its_history() {
1471        let organization_key = organization_key();
1472        let api_client = {
1473            let organization_key = organization_key.clone();
1474            ApiClient::new_mocked(move |mock| {
1475                mock.pam_access_connector_rotation_configs_api
1476                    .expect_get()
1477                    .withf(|org_id, id| {
1478                        *org_id == Uuid::from(organization_id()) && *id == Uuid::from(config_id())
1479                    })
1480                    .returning(move |_org_id, _id| {
1481                        Ok(sample_detail_response(
1482                            &organization_key,
1483                            Some(vec![sample_job(job_id())]),
1484                        ))
1485                    })
1486                    .once();
1487            })
1488        };
1489
1490        let detail = client_with_org_key(api_client, organization_key)
1491            .get(organization_id(), config_id())
1492            .await
1493            .expect("the read succeeds");
1494
1495        assert_eq!(detail.config.id, config_id());
1496        assert_eq!(detail.jobs.len(), 1);
1497    }
1498
1499    #[tokio::test]
1500    async fn get_surfaces_an_api_error() {
1501        let api_client = ApiClient::new_mocked(move |mock| {
1502            mock.pam_access_connector_rotation_configs_api
1503                .expect_get()
1504                .returning(move |_org_id, _id| {
1505                    Err(bitwarden_api_api::apis::Error::Response(
1506                        bitwarden_api_api::apis::ResponseContent {
1507                            status: reqwest::StatusCode::NOT_FOUND,
1508                            message: String::new(),
1509                        },
1510                    ))
1511                })
1512                .once();
1513        });
1514
1515        let result = client(api_client).get(organization_id(), config_id()).await;
1516
1517        assert!(matches!(result, Err(RotationError::Api(_))));
1518    }
1519
1520    #[tokio::test]
1521    async fn create_validates_the_target_seals_and_sends_the_request() {
1522        let organization_key = organization_key();
1523        let api_client = {
1524            let organization_key = organization_key.clone();
1525            ApiClient::new_mocked(move |mock| {
1526                let target_key = organization_key.clone();
1527                mock.pam_access_connector_rotation_target_systems_api
1528                    .expect_get_all()
1529                    .returning(move |_org_id| {
1530                        Ok(target_systems_response(vec![terminable_target_response(
1531                            &target_key,
1532                        )]))
1533                    })
1534                    .once();
1535
1536                let config_key = organization_key.clone();
1537                mock.pam_access_connector_rotation_configs_api
1538                    .expect_post()
1539                    .withf(move |org_id, request| {
1540                        if *org_id != Uuid::from(organization_id())
1541                            || request.cipher_id != Uuid::from(cipher_id())
1542                            || request.target_system_id != Uuid::from(target_system_id())
1543                            || request.schedule_cron.as_deref() != Some("0 0 0 * * ?")
1544                        {
1545                            return false;
1546                        }
1547
1548                        let store = create_test_crypto_with_user_and_org_key(
1549                            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1550                            organization_id(),
1551                            config_key.clone(),
1552                        );
1553                        let mut ctx = store.context_mut();
1554                        let unsealed = unseal_rotation_config::<KeySlotIds>(
1555                            &request
1556                                .sealed_data
1557                                .parse::<DataEnvelope>()
1558                                .expect("sealedData is well-formed"),
1559                            &request
1560                                .wrapped_key
1561                                .parse::<EncString>()
1562                                .expect("wrappedKey is well-formed"),
1563                            &SymmetricKeySlotId::Organization(organization_id()),
1564                            &mut ctx,
1565                        )
1566                        .expect("the blob unseals under the organization key");
1567
1568                        unsealed.target_system_id == Uuid::from(target_system_id())
1569                            && unsealed.cipher_id == Uuid::from(cipher_id())
1570                            && unsealed.account_identity == "svc_rotation"
1571                            && unsealed.terminate_sessions
1572                    })
1573                    .returning(move |_org_id, _request| {
1574                        Ok(sample_detail_response(&organization_key, None))
1575                    })
1576                    .once();
1577            })
1578        };
1579
1580        let detail = client_with_org_key(api_client, organization_key)
1581            .create(organization_id(), create_request())
1582            .await
1583            .expect("creation succeeds");
1584
1585        assert_eq!(detail.config.id, config_id());
1586    }
1587
1588    /// The mock has no expectations, so any call to the server fails the test.
1589    #[tokio::test]
1590    async fn create_rejects_an_invalid_request_before_calling_the_server() {
1591        for (request, expected) in [
1592            (
1593                RotationConfigCreateRequest {
1594                    account_identity: "   ".to_string(),
1595                    ..create_request()
1596                },
1597                RotationValidationError::InvalidAccountIdentity,
1598            ),
1599            (
1600                RotationConfigCreateRequest {
1601                    // A 5-field UNIX cron, which Quartz would misread field by field.
1602                    schedule_cron: Some("0 0 * * *".to_string()),
1603                    ..create_request()
1604                },
1605                RotationValidationError::InvalidCron,
1606            ),
1607        ] {
1608            let result = client(ApiClient::new_mocked(|_| {}))
1609                .create(organization_id(), request)
1610                .await;
1611
1612            assert!(
1613                matches!(result, Err(RotationError::Validation(ref actual)) if *actual == expected),
1614                "expected {expected:?}, got {result:?}"
1615            );
1616        }
1617    }
1618
1619    /// Rejected after fetching the target but before writing anything.
1620    #[tokio::test]
1621    async fn create_rejects_terminate_sessions_on_an_unsupported_target() {
1622        let organization_key = organization_key();
1623        let api_client = {
1624            let target_key = organization_key.clone();
1625            ApiClient::new_mocked(move |mock| {
1626                mock.pam_access_connector_rotation_target_systems_api
1627                    .expect_get_all()
1628                    .returning(move |_org_id| {
1629                        let sealed = seal_target_with(
1630                            &target_key,
1631                            TargetSystemSealedV1 {
1632                                target_system_id: target_system_id().into(),
1633                                method: SealedTargetSystemMethod::Automatic,
1634                                kind: Some(SealedTargetSystemKind::CustomScript),
1635                                password_policy: SealedPasswordPolicy {
1636                                    min_length: 14,
1637                                    max_length: 20,
1638                                    include_uppercase: true,
1639                                    include_lowercase: true,
1640                                    include_digits: true,
1641                                    include_symbols: false,
1642                                },
1643                                supports_session_termination: Some(false),
1644                            },
1645                        );
1646                        let response = PamTargetSystemResponseModel {
1647                            sealed_data: Some(sealed.envelope.to_string()),
1648                            wrapped_key: Some(sealed.wrapped_key.to_string()),
1649                            ..terminable_target_response(&target_key)
1650                        };
1651                        Ok(target_systems_response(vec![response]))
1652                    })
1653                    .once();
1654            })
1655        };
1656
1657        let result = client_with_org_key(api_client, organization_key)
1658            .create(organization_id(), create_request())
1659            .await;
1660
1661        assert!(matches!(
1662            result,
1663            Err(RotationError::Validation(
1664                RotationValidationError::SessionTerminationUnsupported
1665            ))
1666        ));
1667    }
1668
1669    /// An unknown capability counts as unsupported.
1670    #[tokio::test]
1671    async fn create_rejects_terminate_sessions_on_a_pending_seal_target() {
1672        let api_client = ApiClient::new_mocked(move |mock| {
1673            mock.pam_access_connector_rotation_target_systems_api
1674                .expect_get_all()
1675                .returning(move |_org_id| {
1676                    Ok(target_systems_response(vec![
1677                        PamTargetSystemResponseModel {
1678                            id: Some(target_system_id().into()),
1679                            organization_id: Some(organization_id().into()),
1680                            name: Some("Prod SQL".to_string()),
1681                            method: Some(ApiTargetSystemMethod::Automatic),
1682                            status: Some(ApiTargetSystemStatus::PendingSeal),
1683                            sealed_data: None,
1684                            creation_date: Some("2026-01-01T00:00:00Z".to_string()),
1685                            revision_date: Some("2026-01-01T00:00:00Z".to_string()),
1686                            ..Default::default()
1687                        },
1688                    ]))
1689                })
1690                .once();
1691        });
1692
1693        let result = client(api_client)
1694            .create(organization_id(), create_request())
1695            .await;
1696
1697        assert!(matches!(
1698            result,
1699            Err(RotationError::Validation(
1700                RotationValidationError::SessionTerminationUnsupported
1701            ))
1702        ));
1703    }
1704
1705    /// `seal` itself refuses `terminate_sessions` against a target that doesn't confirm support.
1706    #[test]
1707    fn seal_rejects_terminate_sessions_without_confirmed_support() {
1708        let target = TargetSystemView {
1709            id: target_system_id(),
1710            organization_id: organization_id(),
1711            name: "Prod SQL".to_string(),
1712            method: TargetSystemMethod::Automatic,
1713            status: TargetSystemStatus::PendingSeal,
1714            sealed: None,
1715            creation_date: "2026-01-01T00:00:00Z".parse().unwrap(),
1716            revision_date: "2026-01-01T00:00:00Z".parse().unwrap(),
1717        };
1718        let config = ValidatedRotationConfig::try_from(create_request()).expect("a valid request");
1719
1720        let client = client(ApiClient::new_mocked(|_| {}));
1721        let result = config.seal(
1722            &target,
1723            SymmetricKeySlotId::Organization(organization_id()),
1724            &mut client.key_store.context_mut(),
1725        );
1726
1727        assert!(matches!(
1728            result,
1729            Err(RotationError::Validation(
1730                RotationValidationError::SessionTerminationUnsupported
1731            ))
1732        ));
1733    }
1734
1735    #[tokio::test]
1736    async fn create_fails_when_the_target_system_does_not_exist() {
1737        let api_client = ApiClient::new_mocked(move |mock| {
1738            mock.pam_access_connector_rotation_target_systems_api
1739                .expect_get_all()
1740                .returning(move |_org_id| Ok(target_systems_response(vec![])))
1741                .once();
1742        });
1743
1744        let result = client(api_client)
1745            .create(organization_id(), create_request())
1746            .await;
1747
1748        assert!(matches!(result, Err(RotationError::TargetSystemNotFound)));
1749    }
1750
1751    #[tokio::test]
1752    async fn create_fails_when_the_target_systems_seal_is_invalid() {
1753        let api_client = ApiClient::new_mocked(move |mock| {
1754            mock.pam_access_connector_rotation_target_systems_api
1755                .expect_get_all()
1756                .returning(move |_org_id| {
1757                    Ok(target_systems_response(vec![
1758                        PamTargetSystemResponseModel {
1759                            id: Some(target_system_id().into()),
1760                            organization_id: Some(organization_id().into()),
1761                            name: Some("Prod SQL".to_string()),
1762                            method: Some(ApiTargetSystemMethod::Automatic),
1763                            status: Some(ApiTargetSystemStatus::Active),
1764                            sealed_data: Some("not a sealed blob".to_string()),
1765                            creation_date: Some("2026-01-01T00:00:00Z".to_string()),
1766                            revision_date: Some("2026-01-01T00:00:00Z".to_string()),
1767                            ..Default::default()
1768                        },
1769                    ]))
1770                })
1771                .once();
1772        });
1773
1774        let result = client(api_client)
1775            .create(organization_id(), create_request())
1776            .await;
1777
1778        assert!(matches!(
1779            result,
1780            Err(RotationError::Validation(
1781                RotationValidationError::TargetSystemSealInvalid
1782            ))
1783        ));
1784    }
1785
1786    #[tokio::test]
1787    async fn update_seals_and_sends_the_request_to_the_requested_config() {
1788        let organization_key = organization_key();
1789        let api_client = {
1790            let target_key = organization_key.clone();
1791            let config_key = organization_key.clone();
1792            let response_key = organization_key.clone();
1793            let existing_key = organization_key.clone();
1794            ApiClient::new_mocked(move |mock| {
1795                mock.pam_access_connector_rotation_configs_api
1796                    .expect_get()
1797                    .returning(move |_org_id, _id| Ok(sample_detail_response(&existing_key, None)))
1798                    .once();
1799
1800                mock.pam_access_connector_rotation_target_systems_api
1801                    .expect_get_all()
1802                    .returning(move |_org_id| {
1803                        Ok(target_systems_response(vec![terminable_target_response(
1804                            &target_key,
1805                        )]))
1806                    })
1807                    .once();
1808
1809                mock.pam_access_connector_rotation_configs_api
1810                    .expect_put()
1811                    .withf(move |org_id, id, request| {
1812                        if *org_id != Uuid::from(organization_id())
1813                            || *id != Uuid::from(config_id())
1814                            || request.rotate_on_access_end != Some(true)
1815                        {
1816                            return false;
1817                        }
1818
1819                        let store = create_test_crypto_with_user_and_org_key(
1820                            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
1821                            organization_id(),
1822                            config_key.clone(),
1823                        );
1824                        let mut ctx = store.context_mut();
1825                        let unsealed = unseal_rotation_config::<KeySlotIds>(
1826                            &request
1827                                .sealed_data
1828                                .parse::<DataEnvelope>()
1829                                .expect("sealedData is well-formed"),
1830                            &request
1831                                .wrapped_key
1832                                .parse::<EncString>()
1833                                .expect("wrappedKey is well-formed"),
1834                            &SymmetricKeySlotId::Organization(organization_id()),
1835                            &mut ctx,
1836                        )
1837                        .expect("the blob unseals under the organization key");
1838
1839                        unsealed.account_identity == "svc_rotation"
1840                    })
1841                    .returning(move |_org_id, _id, _request| {
1842                        Ok(sample_detail_response(&response_key, None))
1843                    })
1844                    .once();
1845            })
1846        };
1847
1848        let detail = client_with_org_key(api_client, organization_key)
1849            .update(organization_id(), config_id(), create_request())
1850            .await
1851            .expect("the update succeeds");
1852
1853        assert_eq!(detail.config.id, config_id());
1854    }
1855
1856    #[tokio::test]
1857    async fn update_rejects_an_invalid_request_before_calling_the_server() {
1858        let result = client(ApiClient::new_mocked(|_| {}))
1859            .update(
1860                organization_id(),
1861                config_id(),
1862                RotationConfigCreateRequest {
1863                    account_identity: String::new(),
1864                    ..create_request()
1865                },
1866            )
1867            .await;
1868
1869        assert!(matches!(
1870            result,
1871            Err(RotationError::Validation(
1872                RotationValidationError::InvalidAccountIdentity
1873            ))
1874        ));
1875    }
1876
1877    /// The mock has no target-system or `put` expectation, so reaching either fails the test.
1878    #[tokio::test]
1879    async fn update_rejects_a_target_system_id_different_from_the_existing_config() {
1880        let organization_key = organization_key();
1881        let api_client = {
1882            let organization_key = organization_key.clone();
1883            ApiClient::new_mocked(move |mock| {
1884                mock.pam_access_connector_rotation_configs_api
1885                    .expect_get()
1886                    .returning(move |_org_id, _id| {
1887                        // Existing config names `target_system_id()`.
1888                        Ok(sample_detail_response(&organization_key, None))
1889                    })
1890                    .once();
1891            })
1892        };
1893
1894        let result = client_with_org_key(api_client, organization_key)
1895            .update(
1896                organization_id(),
1897                config_id(),
1898                RotationConfigCreateRequest {
1899                    // Request names a different target system.
1900                    target_system_id: TargetSystemId::new(uuid!(
1901                        "88888888-8888-8888-8888-888888888888"
1902                    )),
1903                    ..create_request()
1904                },
1905            )
1906            .await;
1907
1908        assert!(matches!(
1909            result,
1910            Err(RotationError::Validation(
1911                RotationValidationError::RotationConfigImmutableFieldMismatch
1912            ))
1913        ));
1914    }
1915
1916    /// Same guard, for `cipher_id` instead of `target_system_id`.
1917    #[tokio::test]
1918    async fn update_rejects_a_cipher_id_different_from_the_existing_config() {
1919        let organization_key = organization_key();
1920        let api_client = {
1921            let organization_key = organization_key.clone();
1922            ApiClient::new_mocked(move |mock| {
1923                mock.pam_access_connector_rotation_configs_api
1924                    .expect_get()
1925                    .returning(move |_org_id, _id| {
1926                        // Existing config names `cipher_id()`.
1927                        Ok(sample_detail_response(&organization_key, None))
1928                    })
1929                    .once();
1930            })
1931        };
1932
1933        let result = client_with_org_key(api_client, organization_key)
1934            .update(
1935                organization_id(),
1936                config_id(),
1937                RotationConfigCreateRequest {
1938                    // Request names a different cipher.
1939                    cipher_id: CipherId::new(uuid!("99999999-9999-9999-9999-999999999999")),
1940                    ..create_request()
1941                },
1942            )
1943            .await;
1944
1945        assert!(matches!(
1946            result,
1947            Err(RotationError::Validation(
1948                RotationValidationError::RotationConfigImmutableFieldMismatch
1949            ))
1950        ));
1951    }
1952
1953    #[tokio::test]
1954    async fn pause_targets_the_requested_config() {
1955        let api_client = ApiClient::new_mocked(move |mock| {
1956            mock.pam_access_connector_rotation_configs_api
1957                .expect_pause()
1958                .withf(|org_id, id| {
1959                    *org_id == Uuid::from(organization_id()) && *id == Uuid::from(config_id())
1960                })
1961                .returning(move |_org_id, _id| Ok(()))
1962                .once();
1963        });
1964
1965        client(api_client)
1966            .pause(organization_id(), config_id())
1967            .await
1968            .expect("pausing succeeds");
1969    }
1970
1971    #[tokio::test]
1972    async fn resume_targets_the_requested_config() {
1973        let api_client = ApiClient::new_mocked(move |mock| {
1974            mock.pam_access_connector_rotation_configs_api
1975                .expect_resume()
1976                .withf(|org_id, id| {
1977                    *org_id == Uuid::from(organization_id()) && *id == Uuid::from(config_id())
1978                })
1979                .returning(move |_org_id, _id| Ok(()))
1980                .once();
1981        });
1982
1983        client(api_client)
1984            .resume(organization_id(), config_id())
1985            .await
1986            .expect("resuming succeeds");
1987    }
1988
1989    /// The unit-returning actions differ only in the route they hit, so each test pins its own.
1990    #[tokio::test]
1991    async fn rotate_now_dispatches_an_on_demand_rotation() {
1992        let api_client = ApiClient::new_mocked(move |mock| {
1993            mock.pam_access_connector_rotation_configs_api
1994                .expect_rotate()
1995                .withf(|org_id, id| {
1996                    *org_id == Uuid::from(organization_id()) && *id == Uuid::from(config_id())
1997                })
1998                .returning(move |_org_id, _id| Ok(()))
1999                .once();
2000        });
2001
2002        client(api_client)
2003            .rotate_now(organization_id(), config_id())
2004            .await
2005            .expect("dispatching succeeds");
2006    }
2007
2008    #[tokio::test]
2009    async fn record_manual_rotation_records_against_the_requested_config() {
2010        let api_client = ApiClient::new_mocked(move |mock| {
2011            mock.pam_access_connector_rotation_configs_api
2012                .expect_record_manual()
2013                .withf(|org_id, id| {
2014                    *org_id == Uuid::from(organization_id()) && *id == Uuid::from(config_id())
2015                })
2016                .returning(move |_org_id, _id| Ok(()))
2017                .once();
2018        });
2019
2020        client(api_client)
2021            .record_manual_rotation(organization_id(), config_id())
2022            .await
2023            .expect("recording succeeds");
2024    }
2025
2026    #[tokio::test]
2027    async fn delete_targets_the_requested_config() {
2028        let api_client = ApiClient::new_mocked(move |mock| {
2029            mock.pam_access_connector_rotation_configs_api
2030                .expect_delete()
2031                .withf(|org_id, id| {
2032                    *org_id == Uuid::from(organization_id()) && *id == Uuid::from(config_id())
2033                })
2034                .returning(move |_org_id, _id| Ok(()))
2035                .once();
2036        });
2037
2038        client(api_client)
2039            .delete(organization_id(), config_id())
2040            .await
2041            .expect("deleting succeeds");
2042    }
2043
2044    /// The server's cooldown refusal is the expected failure on this route, so it has to reach the
2045    /// caller rather than read as a dispatched rotation.
2046    #[tokio::test]
2047    async fn rotate_now_surfaces_an_api_error() {
2048        let api_client = ApiClient::new_mocked(move |mock| {
2049            mock.pam_access_connector_rotation_configs_api
2050                .expect_rotate()
2051                .returning(move |_org_id, _id| {
2052                    Err(bitwarden_api_api::apis::Error::Response(
2053                        bitwarden_api_api::apis::ResponseContent {
2054                            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
2055                            message: String::new(),
2056                        },
2057                    ))
2058                })
2059                .once();
2060        });
2061
2062        let result = client(api_client)
2063            .rotate_now(organization_id(), config_id())
2064            .await;
2065
2066        assert!(matches!(result, Err(RotationError::Api(_))));
2067    }
2068
2069    /// The client method exists so non-Rust callers reach the same predicates the Rust API has on
2070    /// [`RotationConfigView::actions`]; it must not drift from them.
2071    #[test]
2072    fn the_client_derives_the_same_actions_as_the_config() {
2073        let organization_key = organization_key();
2074        let store = create_test_crypto_with_user_and_org_key(
2075            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
2076            organization_id(),
2077            organization_key.clone(),
2078        );
2079        let mut ctx = store.context_mut();
2080        let config = config_view(
2081            organization_id(),
2082            sample_response(&organization_key),
2083            &mut ctx,
2084        )
2085        .expect("the payload is valid");
2086
2087        for status in [
2088            None,
2089            Some(TargetSystemStatus::Active),
2090            Some(TargetSystemStatus::Disabled),
2091            Some(TargetSystemStatus::Unknown),
2092        ] {
2093            assert_eq!(
2094                client(ApiClient::new_mocked(|_| {})).actions(config.clone(), status),
2095                config.actions(status),
2096                "for {status:?}"
2097            );
2098        }
2099    }
2100}