Skip to main content

bitwarden_organizations/
profile.rs

1use bitwarden_core::{OrganizationId, UserId};
2use bitwarden_crypto::KeyId;
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use uuid::Uuid;
6
7use crate::{
8    MemberDecryptionType, OrganizationUserId, OrganizationUserStatusType, OrganizationUserType,
9    Permissions, ProductTierType, ProviderId, ProviderType,
10};
11
12/// Organization membership details from the user's profile sync.
13///
14/// Contains the full set of entitlements, plan features, and metadata for a single
15/// organization that the current user belongs to.
16#[derive(Default, PartialEq, Serialize, Deserialize, Debug, Clone)]
17#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
18#[bitwarden_ffi::wasm_record]
19#[serde(rename_all = "camelCase")]
20pub struct ProfileOrganization {
21    /// Identity of the organization.
22    pub details: OrganizationDetails,
23    /// The organization's plan or license: tier, limits, and feature entitlements.
24    pub plan: OrganizationPlan,
25    /// The current user's relationship to the organization.
26    pub membership: OrganizationMembership,
27    /// Admin-configured collection management settings.
28    pub collection_management: CollectionManagementSettings,
29    /// The provider managing this organization, if any.
30    pub provider: Option<OrganizationProvider>,
31    /// The organization's SSO and Key Connector settings.
32    pub sso: SsoSettings,
33    /// Families sponsorship state for the current user.
34    pub family_sponsorship: FamilySponsorship,
35}
36
37bitwarden_state::register_repository_item!(OrganizationId => ProfileOrganization, "ProfileOrganization");
38
39/// Basic information about the organization.
40#[derive(PartialEq, Serialize, Deserialize, Debug, Clone)]
41#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
42#[bitwarden_ffi::wasm_record]
43#[serde(rename_all = "camelCase")]
44pub struct OrganizationDetails {
45    /// Unique identifier for the organization.
46    pub id: OrganizationId,
47    /// Display name of the organization.
48    pub name: String,
49    /// Whether the organization is currently enabled.
50    pub enabled: bool,
51    /// Whether the organization has both a public and private key configured.
52    pub has_public_and_private_keys: bool,
53    /// The id of the organization key, as recorded by the server. `None` when the server has not
54    /// recorded one yet.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    #[cfg_attr(feature = "wasm", tsify(optional))]
57    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
58    pub key_id: Option<KeyId>,
59}
60
61impl Default for OrganizationDetails {
62    fn default() -> Self {
63        OrganizationDetails {
64            id: OrganizationId::new(Uuid::nil()),
65            name: String::new(),
66            enabled: true,
67            has_public_and_private_keys: false,
68            key_id: None,
69        }
70    }
71}
72
73/// The organization's plan or license: its tier, limits, and feature entitlements.
74#[derive(PartialEq, Serialize, Deserialize, Debug, Clone)]
75#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
76#[bitwarden_ffi::wasm_record]
77#[serde(rename_all = "camelCase")]
78pub struct OrganizationPlan {
79    /// The subscription tier of the organization.
80    pub product_tier_type: ProductTierType,
81    /// The number of licensed seats for the organization.
82    pub seats: Option<u32>,
83    /// The maximum number of collections the organization can create.
84    pub max_collections: Option<u32>,
85    /// The maximum encrypted storage in gigabytes, if limited.
86    pub max_storage_gb: Option<u32>,
87    /// Whether the organization can create a license file for a self-hosted instance.
88    pub self_host: bool,
89    /// Whether organization members receive premium features.
90    pub users_get_premium: bool,
91    /// Whether the organization has access to policies features.
92    pub use_policies: bool,
93    /// Whether the organization has access to groups features.
94    pub use_groups: bool,
95    /// Whether the organization has access to directory sync features.
96    pub use_directory: bool,
97    /// Whether the organization has access to event logging features.
98    pub use_events: bool,
99    /// Whether the organization can enforce TOTP for members.
100    pub use_totp: bool,
101    /// Whether the organization has access to two-factor authentication features.
102    pub use_2fa: bool,
103    /// Whether the organization has access to the Bitwarden Public API.
104    pub use_api: bool,
105    /// Whether the organization has access to SSO features.
106    pub use_sso: bool,
107    /// Whether the organization can manage verified domains.
108    pub use_organization_domains: bool,
109    /// Whether the organization can use Key Connector for decryption.
110    pub use_key_connector: bool,
111    /// Whether the organization has access to SCIM provisioning.
112    pub use_scim: bool,
113    /// Whether the organization can use the [`OrganizationUserType::Custom`] role.
114    pub use_custom_permissions: bool,
115    /// Whether the organization has access to the account recovery (admin password reset) feature.
116    pub use_reset_password: bool,
117    /// Whether the organization has access to Secrets Manager.
118    pub use_secrets_manager: bool,
119    /// Whether the organization has access to Password Manager.
120    pub use_password_manager: bool,
121    /// Whether the organization has access to Privileged Access Management features.
122    pub use_pam: bool,
123    /// Whether the organization can use the activate autofill policy.
124    pub use_activate_autofill_policy: bool,
125    /// Whether the organization can automatically confirm new members without manual admin
126    /// approval.
127    pub use_automatic_user_confirmation: bool,
128    /// Whether the organization has access to Access Intelligence features.
129    pub use_access_intelligence: bool,
130    /// Whether the organization can sponsor families plans for members (Families For Enterprises).
131    pub use_admin_sponsored_families: bool,
132    /// Whether Secrets Manager ads are disabled for users.
133    #[serde(rename = "useDisableSMAdsForUsers")]
134    pub use_disable_sm_ads_for_users: bool,
135    /// Whether the organization has access to phishing blocker features.
136    pub use_phishing_blocker: bool,
137    /// Whether the organization has access to the My Items collection feature.
138    /// This allows users to store personal items in the organization vault
139    /// if the Centralize Organization Ownership policy is enabled.
140    pub use_my_items: bool,
141    /// Whether the organization can invite members using invite links.
142    pub use_invite_links: bool,
143}
144
145impl Default for OrganizationPlan {
146    fn default() -> Self {
147        OrganizationPlan {
148            product_tier_type: ProductTierType::Free,
149            seats: Some(10),
150            max_collections: None,
151            max_storage_gb: None,
152            self_host: false,
153            users_get_premium: false,
154            use_policies: false,
155            use_groups: false,
156            use_directory: false,
157            use_events: false,
158            use_totp: false,
159            use_2fa: false,
160            use_api: false,
161            use_sso: false,
162            use_organization_domains: false,
163            use_key_connector: false,
164            use_scim: false,
165            use_custom_permissions: false,
166            use_reset_password: false,
167            use_secrets_manager: false,
168            use_password_manager: false,
169            use_pam: false,
170            use_activate_autofill_policy: false,
171            use_automatic_user_confirmation: false,
172            use_access_intelligence: false,
173            use_admin_sponsored_families: false,
174            use_disable_sm_ads_for_users: false,
175            use_phishing_blocker: false,
176            use_my_items: false,
177            use_invite_links: false,
178        }
179    }
180}
181
182/// The current user's relationship to the organization.
183#[derive(PartialEq, Serialize, Deserialize, Debug, Clone)]
184#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
185#[bitwarden_ffi::wasm_record]
186#[serde(rename_all = "camelCase")]
187pub struct OrganizationMembership {
188    /// The user's membership status in the organization.
189    pub status: OrganizationUserStatusType,
190    /// The user's role in the organization.
191    pub r#type: OrganizationUserType,
192    /// The current user's custom permissions, relevant when [`OrganizationUserType::Custom`] is
193    /// the user's `type`.
194    pub permissions: Permissions,
195    /// The current user's personal user ID.
196    pub user_id: UserId,
197    /// The current user's organization membership ID.
198    /// None if the current user has access only through a provider.
199    pub organization_user_id: Option<OrganizationUserId>,
200    /// Whether the current user is a direct member of this organization (as opposed to
201    /// provider-only access).
202    pub is_member: bool,
203    /// Whether the current user accesses this organization through a provider.
204    pub is_provider_user: bool,
205    /// Whether the current user is enrolled in account recovery for this organization.
206    pub reset_password_enrolled: bool,
207    /// Whether the current user's account is linked to this organization via SSO.
208    pub sso_bound: bool,
209    /// Whether the current user's account is claimed by this organization.
210    pub user_is_claimed_by_organization: bool,
211    /// Whether the current user has access to Secrets Manager for this organization.
212    pub access_secrets_manager: bool,
213    /// Whether the current user has access to Privileged Controls for this organization.
214    pub access_pam: bool,
215}
216
217impl Default for OrganizationMembership {
218    fn default() -> Self {
219        OrganizationMembership {
220            status: OrganizationUserStatusType::Confirmed,
221            r#type: OrganizationUserType::User,
222            permissions: Permissions::default(),
223            user_id: UserId::new(Uuid::nil()),
224            organization_user_id: None,
225            is_member: true,
226            is_provider_user: false,
227            reset_password_enrolled: false,
228            sso_bound: false,
229            user_is_claimed_by_organization: false,
230            access_secrets_manager: false,
231            access_pam: false,
232        }
233    }
234}
235
236/// Admin-configured settings controlling who can create, delete, and manage collections and
237/// items.
238#[derive(Default, PartialEq, Serialize, Deserialize, Debug, Clone)]
239#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
240#[bitwarden_ffi::wasm_record]
241#[serde(rename_all = "camelCase")]
242pub struct CollectionManagementSettings {
243    /// Whether collection creation is restricted to owners and admins only.
244    ///
245    /// When `false`, any member can create collections and automatically receives manage
246    /// permissions over collections they create.
247    pub limit_collection_creation: bool,
248    /// Whether collection deletion is restricted to owners and admins only.
249    ///
250    /// When `true`, regular users cannot delete collections that they manage.
251    pub limit_collection_deletion: bool,
252    /// Whether item deletion is restricted to members with the Manage collection permission.
253    ///
254    /// When `false`, members with Edit permission can also delete items within their collections.
255    pub limit_item_deletion: bool,
256    /// Whether owners and admins have implicit manage permissions over all collections.
257    ///
258    /// When `true`, owners and admins can alter items, groups, and permissions across all
259    /// collections without requiring explicit collection assignments.
260    /// When `false`, admins can only access collections where they have been explicitly assigned.
261    pub allow_admin_access_to_all_collection_items: bool,
262}
263
264/// The provider managing an organization.
265#[derive(PartialEq, Serialize, Deserialize, Debug, Clone)]
266#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
267#[bitwarden_ffi::wasm_record]
268#[serde(rename_all = "camelCase")]
269pub struct OrganizationProvider {
270    /// The ID of the provider.
271    pub id: ProviderId,
272    /// The type of provider.
273    pub r#type: ProviderType,
274    /// The name of the provider.
275    /// Should never be None, but server validation is not strict enough to guarantee this.
276    pub name: Option<String>,
277}
278
279/// An organization's SSO and Key Connector settings.
280///
281/// This mirrors the server's fields rather than modelling them as an enum, because the server
282/// does not enforce the relationships between them: for example, a decryption type and Key
283/// Connector URL can be present while SSO is disabled.
284#[derive(Default, PartialEq, Serialize, Deserialize, Debug, Clone)]
285#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
286#[bitwarden_ffi::wasm_record]
287#[serde(rename_all = "camelCase")]
288pub struct SsoSettings {
289    /// Whether SSO login is currently enabled for this organization.
290    pub enabled: bool,
291    /// The organization's SSO identifier.
292    pub identifier: Option<String>,
293    /// The decryption type used for SSO members. `None` when no SSO configuration has been
294    /// saved.
295    pub member_decryption_type: Option<MemberDecryptionType>,
296    /// Whether members decrypt via Key Connector, as computed by the server.
297    pub key_connector_enabled: bool,
298    /// The URL of the Key Connector service. Only meaningful when
299    /// [`key_connector_enabled`](Self::key_connector_enabled) is `true`.
300    pub key_connector_url: Option<String>,
301}
302
303/// Families sponsorship state for the current user in an organization.
304#[derive(Default, PartialEq, Serialize, Deserialize, Debug, Clone)]
305#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
306#[bitwarden_ffi::wasm_record]
307#[serde(rename_all = "camelCase")]
308pub struct FamilySponsorship {
309    /// Whether the organization can sponsor a families plan for the current user. This can be
310    /// `true` while a sponsorship exists.
311    pub available: bool,
312    /// The friendly name of the sponsorship, usually the recipient's email address.
313    /// Should never be None, but server validation is not strict enough to guarantee this.
314    pub friendly_name: Option<String>,
315    /// The date the sponsorship expires. `None` while the sponsorship has been offered but not
316    /// yet redeemed.
317    pub valid_until: Option<DateTime<Utc>>,
318    /// The date the sponsorship was last synced between a self-hosted instance and the cloud.
319    pub last_sync_date: Option<DateTime<Utc>>,
320    /// Whether the sponsorship is scheduled for deletion.
321    pub to_delete: Option<bool>,
322    /// Whether the sponsorship was initiated by an organization admin.
323    pub is_admin_initiated: bool,
324}
325
326#[cfg(test)]
327mod tests {
328    use serde_json::json;
329
330    use super::*;
331
332    /// A record in the nested `ProfileOrganization` shape.
333    fn organization_json() -> serde_json::Value {
334        serde_json::from_str(
335            r#"{
336            "details": {
337                "id": "0b5a2d2c-6b39-4c7e-9f4a-0a1b2c3d4e5f",
338                "name": "Test Org",
339                "enabled": true,
340                "hasPublicAndPrivateKeys": true
341            },
342            "plan": {
343                "productTierType": 3,
344                "seats": 25,
345                "maxCollections": null,
346                "maxStorageGb": 5,
347                "selfHost": false,
348                "usersGetPremium": true,
349                "usePolicies": true,
350                "useGroups": true,
351                "useDirectory": false,
352                "useEvents": true,
353                "useTotp": true,
354                "use2fa": true,
355                "useApi": false,
356                "useSso": true,
357                "useOrganizationDomains": false,
358                "useKeyConnector": false,
359                "useScim": false,
360                "useCustomPermissions": true,
361                "useResetPassword": true,
362                "useSecretsManager": false,
363                "usePasswordManager": true,
364                "usePam": false,
365                "useActivateAutofillPolicy": false,
366                "useAutomaticUserConfirmation": false,
367                "useAccessIntelligence": false,
368                "useAdminSponsoredFamilies": false,
369                "useDisableSMAdsForUsers": false,
370                "usePhishingBlocker": false,
371                "useMyItems": false,
372                "useInviteLinks": true
373            },
374            "membership": {
375                "status": 2,
376                "type": 4,
377                "permissions": {
378                    "accessEventLogs": true,
379                    "accessImportExport": false,
380                    "accessReports": true,
381                    "createNewCollections": false,
382                    "editAnyCollection": false,
383                    "deleteAnyCollection": false,
384                    "manageGroups": true,
385                    "manageSso": false,
386                    "managePolicies": false,
387                    "manageUsers": true,
388                    "manageResetPassword": false,
389                    "manageScim": false,
390                    "manageAccessRules": false,
391                    "manageRotation": false
392                },
393                "userId": "1c6b3e3d-7c4a-4d8f-8a5b-1b2c3d4e5f60",
394                "organizationUserId": "2d7c4f4e-8d5b-4e9a-9b6c-2c3d4e5f6071",
395                "isMember": true,
396                "isProviderUser": false,
397                "resetPasswordEnrolled": true,
398                "ssoBound": false,
399                "userIsClaimedByOrganization": false,
400                "accessSecretsManager": false,
401                "accessPam": false
402            },
403            "collectionManagement": {
404                "limitCollectionCreation": true,
405                "limitCollectionDeletion": true,
406                "limitItemDeletion": false,
407                "allowAdminAccessToAllCollectionItems": true
408            },
409            "provider": null,
410            "sso": {
411                "enabled": true,
412                "identifier": "test-org",
413                "memberDecryptionType": 0,
414                "keyConnectorEnabled": false,
415                "keyConnectorUrl": null
416            },
417            "familySponsorship": {
418                "available": false,
419                "friendlyName": null,
420                "validUntil": null,
421                "lastSyncDate": "2024-01-02T03:04:05Z",
422                "toDelete": null,
423                "isAdminInitiated": false
424            }
425        }"#,
426        )
427        .unwrap()
428    }
429
430    #[test]
431    fn round_trips_organization_json() {
432        let json = organization_json();
433
434        let organization: ProfileOrganization = serde_json::from_value(json.clone()).unwrap();
435        assert_eq!(
436            organization.details.id,
437            OrganizationId::new("0b5a2d2c-6b39-4c7e-9f4a-0a1b2c3d4e5f".parse().unwrap())
438        );
439        assert!(organization.plan.use_invite_links);
440        assert_eq!(organization.membership.r#type, OrganizationUserType::Custom);
441
442        assert_eq!(serde_json::to_value(&organization).unwrap(), json);
443    }
444
445    #[test]
446    fn deserializes_js_iso_date_strings() {
447        let mut json = organization_json();
448        json["familySponsorship"]["lastSyncDate"] = json!("2024-01-02T03:04:05.000Z");
449
450        let organization: ProfileOrganization = serde_json::from_value(json).unwrap();
451        assert_eq!(
452            organization.family_sponsorship.last_sync_date,
453            Some("2024-01-02T03:04:05Z".parse().unwrap())
454        );
455    }
456
457    #[test]
458    fn round_trips_provider_without_name() {
459        let mut json = organization_json();
460        json["provider"] = json!({
461            "id": "3e8d5a5f-9e6c-4fab-8c7d-3d4e5f607182",
462            "type": 2,
463            "name": null
464        });
465
466        let organization: ProfileOrganization = serde_json::from_value(json.clone()).unwrap();
467        assert_eq!(
468            organization.provider,
469            Some(OrganizationProvider {
470                id: "3e8d5a5f-9e6c-4fab-8c7d-3d4e5f607182".parse().unwrap(),
471                r#type: ProviderType::BusinessUnit,
472                name: None,
473            })
474        );
475
476        assert_eq!(serde_json::to_value(&organization).unwrap(), json);
477    }
478
479    #[test]
480    fn round_trips_key_id() {
481        let mut json = organization_json();
482        json["details"]["keyId"] = json!("0123456789abcdef0123456789abcdef");
483
484        let organization: ProfileOrganization = serde_json::from_value(json.clone()).unwrap();
485        assert_eq!(
486            organization.details.key_id,
487            Some("0123456789abcdef0123456789abcdef".parse().unwrap())
488        );
489
490        assert_eq!(serde_json::to_value(&organization).unwrap(), json);
491    }
492
493    #[test]
494    fn deserializes_missing_key_id_as_none() {
495        // Records stored before the key id was synced have no `keyId`, and must not gain one on
496        // the way back out.
497        let json = organization_json();
498        assert!(json["details"].get("keyId").is_none());
499
500        let organization: ProfileOrganization = serde_json::from_value(json.clone()).unwrap();
501        assert_eq!(organization.details.key_id, None);
502
503        assert_eq!(serde_json::to_value(&organization).unwrap(), json);
504    }
505}