From b12874bd83b7fc4c96611bfb8f6976313904a598 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa?= Date: Tue, 24 Nov 2026 01:53:04 +0100 Subject: [PATCH] Align several API responses and request checks with upstream (#8001) --- .env.template | 5 +- THREAT_MODEL.md | 1 + playwright/tests/organization.smtp.spec.ts | 10 ++- src/api/core/accounts.rs | 94 ++++------------------ src/api/core/ciphers.rs | 41 +++++----- src/api/core/organizations.rs | 37 +++++++-- src/config.rs | 6 +- src/db/models/auth_request.rs | 21 ++++- src/db/models/collection.rs | 6 +- src/db/models/organization.rs | 6 +- src/sso_client.rs | 5 +- src/util.rs | 8 +- 12 files changed, 119 insertions(+), 121 deletions(-) diff --git a/.env.template b/.env.template index 47c2feaf..501df3e2 100644 --- a/.env.template +++ b/.env.template @@ -338,6 +338,8 @@ ## "local" accepts it from any non global address, which covers a reverse proxy running on the same ## host or container network. Use "all" to accept it from anywhere, or list the addresses of your ## proxy as IPs and CIDR ranges if it connects from a public address. +## Non global addresses include the 6to4, Teredo and local-use NAT64 ranges, which can carry clients from anywhere: +## if those can reach Vaultwarden, list your proxy instead of using "local", or those clients can set the header. ## For a list header like X-Forwarded-For, the client IP is the rightmost address that isn't one of ## these proxies, so with several proxies in a row (a CDN in front of nginx, for example) list all of them. # IP_HEADER_TRUSTED_PROXIES=local @@ -383,6 +385,7 @@ ## Enabling this will cause the internal HTTP client to refuse to connect to any non-global IP address. ## Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block +## Requests through an outbound proxy (HTTP_PROXY, HTTPS_PROXY or ALL_PROXY) aren't checked, because the proxy resolves the names. # HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS=true ## Client Settings @@ -524,7 +527,7 @@ ## Enforce that the Single Org policy is enabled before setting the Reset Password policy ## Bitwarden enforces this by default. In Vaultwarden we encouraged to use multiple organizations because groups were not available. ## Setting this to true will enforce the Single Org Policy to be enabled before you can enable the Reset Password policy. -# ENFORCE_SINGLE_ORG_WITH_RESET_PW_POLICY=false +# ENFORCE_SINGLE_ORG_WITH_RESET_PW_POLICY=true ## Prefer IPv6 (AAAA) resolving ## This settings configures the DNS resolver to resolve IPv6 first, and if not available try IPv4 diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 524c4dce..30878a80 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -81,6 +81,7 @@ These are intended behavior or outside this model. Several match upstream Bitwar - Attacks that need a missing or misconfigured reverse proxy, such as one not sending `X-Forwarded-Proto` (it decides the admin cookie's `Secure` flag). - Attacks that need another component to break its own specification, such as a NAT64 translator that forwards the `64:ff9b::/96` prefix to private addresses, against RFC 6052. - Outbound requests to the SSO provider, Yubico server or S3 endpoint the operator configures, which skip the outbound filter and can be on the internal network. +- Requests sent through an outbound proxy (`HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`). The proxy resolves names itself, so `HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS` can't check where they go. Configure the proxy so it can't reach anything sensitive, or so it blocks internal addresses. - File permissions in the data folder. Host security belongs to the operator. - Attacks that need physical access to a user's device. - Self-exploitation, where someone can only affect their own account, such as self-XSS or weak KDF settings they choose. diff --git a/playwright/tests/organization.smtp.spec.ts b/playwright/tests/organization.smtp.spec.ts index 1e97ed5d..f45b2f52 100644 --- a/playwright/tests/organization.smtp.spec.ts +++ b/playwright/tests/organization.smtp.spec.ts @@ -42,9 +42,17 @@ test('Invite users', async ({ page }) => { await createAccount(test, page, users.user1, mail1Buffer); await orgs.create(test, page, 'Test'); + await orgs.policies(test, page, 'Test'); + + // Account recovery requires the Single organisation policy (ENFORCE_SINGLE_ORG_WITH_RESET_PW_POLICY) + await test.step(`Set single organisation`, async () => { + await page.getByRole('button', { name: 'Single organisation' }).click(); + await page.getByRole('checkbox', { name: 'Turn on' }).or(page.getByRole('switch', { name: 'Enable policy' })).check({ force: true }); + await page.getByRole('button', { name: 'Save' }).click(); + await utils.checkNotification(page, 'Edited policy Single organisation'); + }); await test.step(`Set account recovery`, async () => { - await orgs.policies(test, page, 'Test'); await page.getByRole('button', { name: 'Account recovery' }).click(); await page.getByRole('checkbox', { name: 'Turn on' }).check(); await page.getByRole('checkbox', { name: 'Automatically enroll new' }).check(); diff --git a/src/api/core/accounts.rs b/src/api/core/accounts.rs index b36d24c2..8de601ef 100644 --- a/src/api/core/accounts.rs +++ b/src/api/core/accounts.rs @@ -21,10 +21,10 @@ use crate::{ db::{ DbConn, DbPool, models::{ - AuthRequest, AuthRequestId, Cipher, CipherId, Device, DeviceId, DeviceType, DeviceWithAuthRequest, - EmergencyAccess, EmergencyAccessId, EventType, Folder, FolderId, Invitation, KeyId, Membership, - MembershipId, OrgPolicy, OrgPolicyType, Organization, OrganizationId, Send, SendId, SignatureAlgorithm, - User, UserId, UserKdfType, UserSignatureKeyPair, + AuthRequest, AuthRequestId, Cipher, CipherId, Device, DeviceId, DeviceWithAuthRequest, EmergencyAccess, + EmergencyAccessId, EventType, Folder, FolderId, Invitation, KeyId, Membership, MembershipId, OrgPolicy, + OrgPolicyType, Organization, OrganizationId, Send, SendId, SignatureAlgorithm, User, UserId, UserKdfType, + UserSignatureKeyPair, }, }, mail, @@ -909,7 +909,9 @@ async fn get_keys(headers: Headers, conn: DbConn) -> JsonResult { #[serde(rename_all = "camelCase")] struct PostKeysData { // Required like upstream, even next to `accountKeys` + #[serde(alias = "PublicKey")] public_key: Option, + #[serde(alias = "EncryptedPrivateKey")] encrypted_private_key: Option, account_keys: Option, // The id of the user key these account keys belong to, only honored for v2 `accountKeys` @@ -2507,19 +2509,7 @@ async fn post_auth_request( ) .await; - Ok(Json(json!({ - "id": auth_request.uuid, - "publicKey": auth_request.public_key, - "requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(), - "requestIpAddress": auth_request.request_ip, - "key": null, - "masterPasswordHash": null, - "creationDate": format_date(&auth_request.creation_date), - "responseDate": null, - "requestApproved": false, - "origin": CONFIG.domain_origin(), - "object": "auth-request" - }))) + Ok(Json(auth_request.to_json())) } #[get("/auth-requests/")] @@ -2529,21 +2519,7 @@ async fn get_auth_request(auth_request_id: AuthRequestId, headers: Headers, conn err!("AuthRequest doesn't exist", "Record not found or user uuid does not match") }; - let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date)); - - Ok(Json(json!({ - "id": &auth_request_id, - "publicKey": auth_request.public_key, - "requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(), - "requestIpAddress": auth_request.request_ip, - "key": auth_request.enc_key, - "masterPasswordHash": auth_request.master_password_hash, - "creationDate": format_date(&auth_request.creation_date), - "responseDate": response_date_utc, - "requestApproved": auth_request.approved, - "origin": CONFIG.domain_origin(), - "object":"auth-request" - }))) + Ok(Json(auth_request.to_json())) } #[derive(Debug, Deserialize)] @@ -2578,15 +2554,14 @@ async fn put_auth_request( err!("An authentication request with the same device already exists") } - let response_date = Utc::now().naive_utc(); - let response_date_utc = format_date(&response_date); + // Set the date now so that the response returns it + auth_request.response_date = Some(Utc::now().naive_utc()); if data.request_approved { auth_request.approved = Some(data.request_approved); auth_request.enc_key = Some(data.key); auth_request.master_password_hash = data.master_password_hash; auth_request.response_device_id = Some(data.device_identifier.clone()); - auth_request.response_date = Some(response_date); auth_request.save(&conn).await?; ant.send_auth_response(&auth_request.user_uuid, &auth_request.uuid).await; @@ -2613,19 +2588,7 @@ async fn put_auth_request( .await; } - Ok(Json(json!({ - "id": &auth_request_id, - "publicKey": auth_request.public_key, - "requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(), - "requestIpAddress": auth_request.request_ip, - "key": auth_request.enc_key, - "masterPasswordHash": auth_request.master_password_hash, - "creationDate": format_date(&auth_request.creation_date), - "responseDate": response_date_utc, - "requestApproved": auth_request.approved, - "origin": CONFIG.domain_origin(), - "object":"auth-request" - }))) + Ok(Json(auth_request.to_json())) } #[get("/auth-requests//response?")] @@ -2648,21 +2611,7 @@ async fn get_auth_request_response( err!("AuthRequest doesn't exist", "Invalid device, IP or code") } - let response_date_utc = auth_request.response_date.map(|response_date| format_date(&response_date)); - - Ok(Json(json!({ - "id": &auth_request_id, - "publicKey": auth_request.public_key, - "requestDeviceType": DeviceType::from_i32(auth_request.device_type).to_string(), - "requestIpAddress": auth_request.request_ip, - "key": auth_request.enc_key, - "masterPasswordHash": auth_request.master_password_hash, - "creationDate": format_date(&auth_request.creation_date), - "responseDate": response_date_utc, - "requestApproved": auth_request.approved, - "origin": CONFIG.domain_origin(), - "object":"auth-request" - }))) + Ok(Json(auth_request.to_json())) } // Now unused but not yet removed @@ -2680,23 +2629,8 @@ async fn get_auth_requests_pending(headers: Headers, conn: DbConn) -> JsonResult "data": auth_requests .iter() .filter(|request| request.approved.is_none()) - .map(|request| { - let response_date_utc = request.response_date.map(|response_date| format_date(&response_date)); - - json!({ - "id": request.uuid, - "publicKey": request.public_key, - "requestDeviceType": DeviceType::from_i32(request.device_type).to_string(), - "requestIpAddress": request.request_ip, - "key": request.enc_key, - "masterPasswordHash": request.master_password_hash, - "creationDate": format_date(&request.creation_date), - "responseDate": response_date_utc, - "requestApproved": request.approved, - "origin": CONFIG.domain_origin(), - "object":"auth-request" - }) - }).collect::>(), + .map(AuthRequest::to_json) + .collect::>(), "continuationToken": null, "object": "list" }))) diff --git a/src/api/core/ciphers.rs b/src/api/core/ciphers.rs index 32b4fcb1..b6c9d5cd 100644 --- a/src/api/core/ciphers.rs +++ b/src/api/core/ciphers.rs @@ -1,6 +1,7 @@ use std::collections::{HashMap, HashSet}; use chrono::{NaiveDateTime, Utc}; + use rocket::{ Route, form::{Form, FromForm}, @@ -12,7 +13,7 @@ use serde_json::Value; use crate::{ CONFIG, - api::{self, ApiResult, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType, core::log_event}, + api::{self, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType, core::log_event}, auth::ClientVersion, auth::{Headers, OrgIdGuard, OwnerHeaders}, config::PathType, @@ -842,7 +843,7 @@ pub async fn seed_cipher( user_id: &UserId, folder_ids: &HashMap, conn: &DbConn, -) -> ApiResult { +) -> api::ApiResult { // Not in the request model, but a trashed cipher has to stay trashed let deleted_at = encrypted.get("deletedDate").and_then(Value::as_str).map(parse_seed_date).transpose()?; let mut data: CipherData = serde_json::from_value(encrypted)?; @@ -889,7 +890,7 @@ pub async fn seed_cipher( } #[cfg(feature = "unsafe_test_mode")] -fn parse_seed_date(date: &str) -> ApiResult { +fn parse_seed_date(date: &str) -> api::ApiResult { match chrono::DateTime::parse_from_rfc3339(date) { Ok(date) => Ok(date.naive_utc()), Err(e) => err!(format!("Invalid date {}: {e}", date.escape_debug())), @@ -1518,6 +1519,13 @@ async fn share_cipher_by_uuid( false, ) .await?; + // The moved attachments now count against the organization's limit + if transfer_cipher { + let moved: i64 = Attachment::find_by_cipher(&cipher.uuid, conn).await.iter().map(|a| a.file_size).sum(); + if moved > 0 { + check_attachment_space(&cipher, moved, moved, conn).await?; + } + } for col_id in &shared_to_collections { CollectionCipher::save(&cipher.uuid, col_id, conn).await?; } @@ -1619,17 +1627,17 @@ enum FileUploadType { // Azure = 1, // only used upstream } -/// Remaining attachment storage in bytes for the cipher's owner, `None` when unlimited. -/// `size_adjust` credits a v2 attachment whose record already counts as used. -async fn attachment_size_limit(cipher: &Cipher, size_adjust: i64, conn: &DbConn) -> ApiResult> { +/// Fails when `size` more bytes don't fit in the attachment storage of the cipher's owner. +/// `size_adjust` credits bytes already counted as used, such as a v2 attachment's reserved record. +async fn check_attachment_space(cipher: &Cipher, size: i64, size_adjust: i64, conn: &DbConn) -> EmptyResult { let (limit_kb, already_used) = if let Some(ref user_id) = cipher.user_uuid { let Some(limit_kb) = CONFIG.user_attachment_limit() else { - return Ok(None); + return Ok(()); }; (limit_kb, Attachment::size_by_user(user_id, conn).await) } else if let Some(ref org_id) = cipher.organization_uuid { let Some(limit_kb) = CONFIG.org_attachment_limit() else { - return Ok(None); + return Ok(()); }; (limit_kb, Attachment::size_by_org(org_id, conn).await) } else { @@ -1649,8 +1657,11 @@ async fn attachment_size_limit(cipher: &Cipher, size_adjust: i64, conn: &DbConn) if left <= 0 { err!("Attachment storage limit reached! Delete some attachments to free up space") } + if size > left { + err!("Attachment storage limit exceeded with this file"); + } - Ok(Some(left)) + Ok(()) } /// v2 API for creating an attachment associated with a cipher. @@ -1688,11 +1699,7 @@ async fn post_attachment_v2( err!("Max file size is 525 MB.") } - if let Some(size_limit) = attachment_size_limit(&cipher, 0, &conn).await? - && file_size > size_limit - { - err!("Attachment storage limit exceeded with this file"); - } + check_attachment_space(&cipher, file_size, 0, &conn).await?; let attachment_id = crypto::generate_attachment_id(); let attachment = @@ -1762,11 +1769,7 @@ async fn save_attachment( Some(a) => a.file_size, // v2 API }; - if let Some(size_limit) = attachment_size_limit(&cipher, size_adjust, &conn).await? - && size > size_limit - { - err!("Attachment storage limit exceeded with this file"); - } + check_attachment_space(&cipher, size, size_adjust, &conn).await?; let file_id = match &attachment { Some(attachment) => attachment.id.clone(), // v2 API diff --git a/src/api/core/organizations.rs b/src/api/core/organizations.rs index a25306c3..84edd850 100644 --- a/src/api/core/organizations.rs +++ b/src/api/core/organizations.rs @@ -120,11 +120,12 @@ struct OrgData { plan_type: NumberOrString, } -#[derive(Deserialize, Debug)] +#[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct OrganizationUpdateData { billing_email: String, name: String, + keys: Option, } #[derive(Deserialize)] @@ -160,18 +161,24 @@ impl FullCollectionData { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct CollectionGroupData { + #[serde(default)] hide_passwords: bool, id: GroupId, + #[serde(default)] read_only: bool, + #[serde(default)] manage: bool, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct CollectionMembershipData { + #[serde(default)] hide_passwords: bool, id: MembershipId, + #[serde(default)] read_only: bool, + #[serde(default)] manage: bool, } @@ -309,6 +316,16 @@ async fn put_organization( org.name = data.name; org.billing_email = data.billing_email.to_lowercase(); + if let Some(keys) = data.keys + && !keys.public_key.trim().is_empty() + && !keys.encrypted_private_key.trim().is_empty() + && org.public_key.as_deref().is_none_or(|k| k.trim().is_empty()) + && org.private_key.as_deref().is_none_or(|k| k.trim().is_empty()) + { + org.public_key = Some(keys.public_key); + org.private_key = Some(keys.encrypted_private_key); + } + org.save(&conn).await?; log_event( @@ -2294,7 +2311,9 @@ async fn post_bulk_collections(data: Json, headers: Headers // Only act on existing cipher uuid's // Do not abort the operation just ignore it, it could be a cipher was just deleted for example if let Some(cipher) = Cipher::find_by_uuid_and_org(cipher_id, &data.organization_id, &conn).await - && cipher.is_write_accessible_to_user(&headers.user.uuid, CipherAccessScope::OrganizationAdmin, &conn).await + && cipher + .is_in_editable_collection_by_user(&headers.user.uuid, CipherAccessScope::OrganizationAdmin, &conn) + .await { // When selecting a specific collection from the left filter list, and use the bulk option, you can remove an item from that collection // In these cases the client will call this endpoint twice, once for adding the new collections and a second for deleting. @@ -2344,9 +2363,15 @@ async fn list_policies_token(org_id: OrganizationId, token: &str, conn: DbConn) return Ok(Json(json!({}))); } - // TODO: We receive the invite token as ?token=<>, validate it contains the org id + let Some(member) = Membership::find_by_uuid_and_org(&invite.member_id, &org_id, &conn).await else { + err!("Organization not found", "The invited membership no longer exists") + }; + if member.user_uuid != invite.sub || member.status != MembershipStatus::Invited as i32 { + err!("Organization not found", "The membership is not a pending invitation of this user") + } + let policies = OrgPolicy::find_by_org(&org_id, &conn).await; - let policies_json: Vec = policies.iter().map(OrgPolicy::to_json).collect(); + let policies_json: Vec = policies.iter().filter(|p| p.enabled).map(OrgPolicy::to_json).collect(); Ok(Json(json!({ "data": policies_json, @@ -2462,7 +2487,6 @@ async fn put_policy( // Vaultwarden encouraged to use multiple orgs instead of groups because groups were not available in the past // Now that groups are available we can enforce this option when wanted. // We put this behind a config option to prevent breaking current installation. - // Maybe we want to enable this by default in the future, but currently it is disabled by default. if CONFIG.enforce_single_org_with_reset_pw_policy() { if pol_type_enum == OrgPolicyType::ResetPassword && data.enabled { let single_org_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn) @@ -3000,8 +3024,11 @@ impl GroupRequest { #[serde(rename_all = "camelCase")] struct CollectionData { id: CollectionId, + #[serde(default)] read_only: bool, + #[serde(default)] hide_passwords: bool, + #[serde(default)] manage: bool, } diff --git a/src/config.rs b/src/config.rs index 185921c7..35a58589 100644 --- a/src/config.rs +++ b/src/config.rs @@ -736,6 +736,7 @@ make_config! { /// running on the same host or container network), the string "all" to accept it from anywhere, /// or a comma separated list of IPs and CIDR ranges. For a list header like X-Forwarded-For, the /// client IP is the rightmost address that isn't a trusted proxy, so list every proxy in the chain. + /// "local" also trusts 6to4, Teredo and local-use NAT64 addresses, which can carry clients from anywhere. ip_header_trusted_proxies: String, true, def, "local".to_owned(); /// Icon service |> The predefined icon services are: internal, bitwarden, duckduckgo, google. /// To specify a custom icon service, set a URL template with exactly one instance of `{}`, @@ -770,7 +771,8 @@ make_config! { /// Useful to hide other servers in the local network. Check the WIKI for more details http_request_block_regex: String, true, option; /// Block non global IPs |> Enabling this will cause the internal HTTP client to refuse to connect to any non global IP address. - /// Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block + /// Useful to secure your internal environment: See https://en.wikipedia.org/wiki/Reserved_IP_addresses for a list of IPs which it will block. + /// Requests through an outbound proxy (HTTP_PROXY, HTTPS_PROXY or ALL_PROXY) aren't checked, because the proxy resolves the names. http_request_block_non_global_ips: bool, true, auto, |c| c.icon_blacklist_non_global_ips; /// Disable Two-Factor remember |> Enabling this would force the users to use a second factor to login every time. @@ -870,7 +872,7 @@ make_config! { /// Enforce Single Org with Reset Password Policy |> Enforce that the Single Org policy is enabled before setting the Reset Password policy /// Bitwarden enforces this by default. In Vaultwarden we encouraged to use multiple organizations because groups were not available. /// Setting this to true will enforce the Single Org Policy to be enabled before you can enable the Reset Password policy. - enforce_single_org_with_reset_pw_policy: bool, false, def, false; + enforce_single_org_with_reset_pw_policy: bool, false, def, true; /// Prefer IPv6 (AAAA) resolving |> This settings configures the DNS resolver to resolve IPv6 first, and if not available try IPv4 /// This could be useful in IPv6 only environments. diff --git a/src/db/models/auth_request.rs b/src/db/models/auth_request.rs index f2b0ecdc..221b78f7 100644 --- a/src/db/models/auth_request.rs +++ b/src/db/models/auth_request.rs @@ -4,6 +4,7 @@ use diesel::prelude::*; use serde_json::Value; use crate::{ + CONFIG, api::{ApiResult, EmptyResult}, crypto::ct_eq, db::{DbConn, schema::auth_requests}, @@ -12,7 +13,7 @@ use crate::{ }; use macros::UuidFromParam; -use super::{DeviceId, OrganizationId, UserId}; +use super::{DeviceId, DeviceType, OrganizationId, UserId}; #[derive(Identifiable, Queryable, Insertable, AsChangeset, Deserialize, Serialize)] #[diesel(table_name = auth_requests)] @@ -73,6 +74,24 @@ impl AuthRequest { } } + pub fn to_json(&self) -> Value { + json!({ + "id": self.uuid, + "publicKey": self.public_key, + "requestDeviceIdentifier": self.request_device_identifier, + "requestDeviceTypeValue": self.device_type, + "requestDeviceType": DeviceType::from_i32(self.device_type).to_string(), + "requestIpAddress": self.request_ip, + "key": self.enc_key, + "masterPasswordHash": self.master_password_hash, + "creationDate": format_date(&self.creation_date), + "responseDate": self.response_date.as_ref().map(format_date), + "requestApproved": self.approved.unwrap_or(false), + "origin": CONFIG.domain_origin(), + "object": "auth-request" + }) + } + pub fn to_json_for_pending_device(&self) -> Value { json!({ "id": self.uuid, diff --git a/src/db/models/collection.rs b/src/db/models/collection.rs index 0c0367ea..651c94ff 100644 --- a/src/db/models/collection.rs +++ b/src/db/models/collection.rs @@ -995,11 +995,7 @@ impl CollectionMembership { "id": self.membership_uuid, "readOnly": self.read_only, "hidePasswords": self.hide_passwords, - "manage": membership_type >= MembershipType::Admin - || self.manage - || (membership_type == MembershipType::Manager - && !self.read_only - && !self.hide_passwords), + "manage": membership_type >= MembershipType::Admin || self.manage, }) } } diff --git a/src/db/models/organization.rs b/src/db/models/organization.rs index 37ce8a15..b28c00e1 100644 --- a/src/db/models/organization.rs +++ b/src/db/models/organization.rs @@ -811,6 +811,7 @@ impl Membership { "useResetPassword": CONFIG.mail_enabled(), "ssoBound": false, // Not supported "useSso": false, // Not supported + "ssoEnabled": false, "useKeyConnector": false, "useSecretsManager": false, // Not supported (Not AGPLv3 Licensed) "usePasswordManager": true, @@ -824,6 +825,7 @@ impl Membership { "useOrganizationDomains": false, // Not supported (Linked to SSO) "usePam": false, // Not supported "usePhishingBlocker": false, + "useAutomaticUserConfirmation": false, "organizationUserId": self.uuid, "providerId": null, @@ -831,6 +833,7 @@ impl Membership { "providerType": null, "familySponsorshipFriendlyName": null, "familySponsorshipAvailable": false, + "isAdminInitiated": false, "productTierType": 3, // Enterprise tier "keyConnectorEnabled": false, "keyConnectorUrl": null, @@ -838,6 +841,7 @@ impl Membership { "familySponsorshipValidUntil": null, "familySponsorshipToDelete": null, "accessSecretsManager": false, + "accessPam": false, // limit collection creation to managers with access_all permission to prevent issues "limitCollectionCreation": self.atype < MembershipType::Manager || !self.access_all, "limitCollectionDeletion": true, @@ -905,7 +909,7 @@ impl Membership { "id": cu.collection_uuid, "readOnly": cu.read_only, "hidePasswords": cu.hide_passwords, - "manage": cu.manage || (self.atype == MembershipType::Manager && !cu.read_only && !cu.hide_passwords), + "manage": cu.manage, }) }) .collect() diff --git a/src/sso_client.rs b/src/sso_client.rs index 37442ae2..7051f77f 100644 --- a/src/sso_client.rs +++ b/src/sso_client.rs @@ -246,14 +246,13 @@ impl Client { let mut exchange = self.core_client.exchange_code(oidc_code); + Self::check_client_verifier(&client_verifier, sso_auth)?; if CONFIG.sso_pkce() { exchange = exchange.set_pkce_verifier(PkceCodeVerifier::new(client_verifier.into())); - } else { - Self::check_client_verifier(&client_verifier, sso_auth)?; } match exchange.request_async(&self.http_client).await { - Err(err) => err!(format!("Failed to contact token endpoint: {:?}", err)), + Err(err) => err!(format!("Failed to contact token endpoint: {err}")), Ok(token_response) => { let oidc_nonce = Nonce::new(sso_auth.nonce.clone()); diff --git a/src/util.rs b/src/util.rs index 9a4a329b..a7513eb9 100644 --- a/src/util.rs +++ b/src/util.rs @@ -147,7 +147,7 @@ impl Cors { // Check a request's `Origin` header against the list of allowed origins. // If a match exists, return it. Otherwise, return None. - fn get_allowed_origin(headers: &HeaderMap<'_>) -> Option { + fn get_allowed_origin(headers: &HeaderMap<'_>, allow_sso: bool) -> Option { let origin = Self::get_header(headers, "Origin"); let safari_extension_origin = "file://"; let desktop_custom_file_origin = "bw-desktop-file://bundle"; @@ -155,7 +155,7 @@ impl Cors { if origin == CONFIG.domain_origin() || origin == safari_extension_origin || origin == desktop_custom_file_origin - || (CONFIG.sso_enabled() && origin == CONFIG.sso_authority()) + || (allow_sso && CONFIG.sso_enabled() && origin == CONFIG.sso_authority()) { Some(origin) } else { @@ -175,8 +175,10 @@ impl Fairing for Cors { async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) { let req_headers = request.headers(); + // The admin panel authenticates with a cookie, so the SSO provider's pages must not reach it + let allow_sso = !request.uri().path().as_str().starts_with(&format!("{}/admin", CONFIG.domain_path())); - if let Some(origin) = Self::get_allowed_origin(req_headers) { + if let Some(origin) = Self::get_allowed_origin(req_headers, allow_sso) { response.set_header(Header::new("Access-Control-Allow-Origin", origin)); }