Browse Source

Merge 3de2eaff56 into 4051a4d3a6

pull/7971/merge
Mathijs van Veluw 4 hours ago
committed by GitHub
parent
commit
32fbab73d7
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      .pre-commit-config.yaml
  2. 923
      Cargo.lock
  3. 43
      Cargo.toml
  4. 7
      build.rs
  5. 8
      docker/Dockerfile.alpine
  6. 2
      docker/Dockerfile.debian
  7. 2
      macros/Cargo.toml
  8. 2
      macros/src/lib.rs
  9. 2
      rust-toolchain.toml
  10. 97
      src/api/admin.rs
  11. 12
      src/api/core/accounts.rs
  12. 23
      src/api/core/ciphers.rs
  13. 3
      src/api/core/emergency_access.rs
  14. 10
      src/api/core/events.rs
  15. 43
      src/api/core/organizations.rs
  16. 4
      src/api/core/public.rs
  17. 18
      src/api/core/sends.rs
  18. 7
      src/api/core/two_factor/authenticator.rs
  19. 4
      src/api/core/two_factor/duo.rs
  20. 21
      src/api/core/two_factor/duo_oidc.rs
  21. 59
      src/api/core/two_factor/email.rs
  22. 12
      src/api/core/two_factor/webauthn.rs
  23. 61
      src/api/icons.rs
  24. 34
      src/api/identity.rs
  25. 2
      src/api/mod.rs
  26. 13
      src/api/notifications.rs
  27. 56
      src/auth.rs
  28. 8
      src/auth/send.rs
  29. 47
      src/config.rs
  30. 19
      src/db/mod.rs
  31. 2
      src/db/models/attachment.rs
  32. 44
      src/db/models/cipher.rs
  33. 2
      src/db/models/collection.rs
  34. 62
      src/db/models/device.rs
  35. 6
      src/db/models/emergency_access.rs
  36. 8
      src/db/models/event.rs
  37. 8
      src/db/models/group.rs
  38. 13
      src/db/models/org_policy.rs
  39. 98
      src/db/models/organization.rs
  40. 16
      src/db/models/send.rs
  41. 2
      src/db/models/sso_auth.rs
  42. 4
      src/db/models/two_factor.rs
  43. 12
      src/db/models/user.rs
  44. 30
      src/http_client.rs
  45. 21
      src/mail.rs
  46. 15
      src/main.rs
  47. 12
      src/sso.rs
  48. 20
      src/sso_client.rs
  49. 3
      src/storage.rs
  50. 145
      src/util.rs

4
.pre-commit-config.yaml

@ -38,7 +38,7 @@ repos:
description: Test the package for errors.
entry: cargo test
language: system
args: [ "--features", "sqlite,mysql,postgresql", "--" ]
args: [ "--features", "sqlite,mysql,postgresql,enable_mimalloc,s3,unsafe_test_mode", "--" ]
types_or: [ rust, toml ] # Cargo.lock matches toml type which is intended
pass_filenames: false
- id: cargo-clippy
@ -46,7 +46,7 @@ repos:
description: Lint Rust sources
entry: cargo clippy
language: system
args: [ "--features", "sqlite,mysql,postgresql", "--", "-D", "warnings" ]
args: [ "--features", "sqlite,mysql,postgresql,enable_mimalloc,s3,unsafe_test_mode", "--", "-D", "warnings" ]
types_or: [ rust, toml ] # Cargo.lock matches toml type which is intended
pass_filenames: false
- id: check-docker-templates

923
Cargo.lock

File diff suppressed because it is too large

43
Cargo.toml

@ -1,6 +1,6 @@
[workspace.package]
edition = "2024"
rust-version = "1.97.1"
rust-version = "1.98.1"
license = "AGPL-3.0-only"
repository = "https://github.com/dani-garcia/vaultwarden"
publish = false
@ -44,7 +44,6 @@ s3 = [
"dep:aws-config",
"dep:aws-credential-types",
"dep:aws-smithy-runtime-api",
"dep:http",
"dep:reqsign-aws-v4",
"dep:reqsign-core",
]
@ -61,7 +60,7 @@ unstable = []
unsafe_test_mode = ["dep:serde_cbor_2"]
[target."cfg(unix)".dependencies]
nix = { version = "0.31.3", features = ["fs"] }
nix = { version = "0.32.0", features = ["fs"] }
# Logging
syslog = "7.0.0"
@ -126,18 +125,17 @@ diesel-derive-newtype = "2.1.3"
libsqlite3-sys = { version = "0.38.2", optional = true }
# Crypto-related libraries
rand = "0.10.3"
rand = "0.10.4"
ring = "0.17.14"
rustls = { version = "0.23.46", features = ["ring", "std"], default-features = false }
subtle = "2.6.1"
# UUID generation
uuid = { version = "1.29.0", features = ["v4"] }
uuid = { version = "1.29.2", features = ["v4"] }
# Date and time libraries
chrono = { version = "0.4.45", default-features = false, features = ["clock", "serde"] }
chrono-tz = "0.10.4"
time = "0.3.55"
# Job scheduler
job_scheduler_ng = "2.5.0"
@ -146,7 +144,7 @@ job_scheduler_ng = "2.5.0"
data-encoding = "2.11.1"
# JWT library
jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto", "use_pem"] }
jsonwebtoken = { version = "12.0.0", default-features = false, features = ["rust_crypto", "use_pem"] }
# TOTP library
totp-lite = "2.0.1"
@ -208,7 +206,7 @@ reqwest = { version = "0.13.5", default-features = false, features = [
hickory-resolver = "0.26.3"
# Favicon extraction libraries
html5gum = "0.9.0"
html5gum = "0.9.1"
regex = { version = "1.13.1", default-features = false, features = [
"perf",
"std",
@ -218,15 +216,12 @@ data-url = "0.3.2"
bytes = "1.12.1"
svg-hush = "0.9.7"
# Cache function results (Used for version check and favicon fetching)
cached = { version = "4.1.0", features = ["async"] }
# Used for custom short lived cookie jar during favicon extraction
cookie = "0.18.2"
cookie_store = "0.22.1"
# Used by U2F, JWT and PostgreSQL
openssl = "0.10.81"
openssl = "0.10.82"
# CLI argument parsing
pico-args = "0.5.0"
@ -240,6 +235,8 @@ ipnet = "2.12.2"
# OIDC for SSO
openidconnect = { version = "4.1.0", default-features = false }
# Used for caching for ODIC/SSO and Admin version check
moka = { version = "0.12.16", features = ["future"] }
# Check client versions for specific features.
@ -255,7 +252,7 @@ which = "8.0.6"
argon2 = "0.6.0"
# Reading a password from the cli for generating the Argon2id ADMIN_TOKEN
rpassword = "7.5.4"
rpassword = "7.5.5"
# Loading a dynamic CSS Stylesheet
grass_compiler = { version = "0.13.4", default-features = false }
@ -265,15 +262,14 @@ opendal = { version = "0.59.5", default-features = false, features = ["services-
opendal-http-transport-reqwest = { version = "0.59.5", default-features = false, features = ["rustls-no-provider"], optional = true }
# For retrieving AWS credentials, including temporary SSO credentials
aws-config = { version = "1.13.0", optional = true, default-features = false, features = [
aws-config = { version = "1.13.2", optional = true, default-features = false, features = [
"behavior-version-latest",
"credentials-process",
"rt-tokio",
"sso",
] }
aws-credential-types = { version = "1.3.1", optional = true }
aws-smithy-runtime-api = { version = "1.19.2", optional = true }
http = { version = "1.5.0", optional = true }
aws-smithy-runtime-api = { version = "1.21.0", optional = true }
reqsign-aws-v4 = { version = "3.3.1", optional = true }
reqsign-core = { version = "3.3.2", optional = true }
@ -330,6 +326,14 @@ opt-level = 3
# Linting config
# https://doc.rust-lang.org/rustc/lints/groups.html
[workspace.lints.rust]
# Features
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(sqlite)',
'cfg(mysql)',
'cfg(postgresql)',
'cfg(s3)',
] }
# Forbid
unsafe_code = "forbid"
non_ascii_idents = "forbid"
@ -359,6 +363,7 @@ unused_import_braces = "deny"
unused_lifetimes = "deny"
unused_qualifications = "deny"
variant_size_differences = "deny"
redundant_imports = "deny"
# https://rust-lang.github.io/rust-clippy/stable/index.html
[workspace.lints.clippy]
@ -386,11 +391,15 @@ iter_on_empty_collections = "deny"
iter_on_single_items = "deny"
mem_forget = "deny"
needless_collect = "deny"
needless_pass_by_ref_mut = "deny"
or_fun_call = "deny"
redundant_clone = "deny"
significant_drop_in_scrutinee = "deny"
str_to_string = "deny"
unnecessary_self_imports = "deny"
use_self = "deny"
useless_let_if_seq = "deny"
verbose_file_reads = "deny"
str_to_string = "deny"
# Pedantic Opt-Outs
inline_always = "allow" # We use this sparsely

7
build.rs

@ -16,13 +16,6 @@ fn main() {
#[cfg(feature = "s3")]
println!("cargo:rustc-cfg=s3");
// Use check-cfg to let cargo know which cfg's we define,
// and avoid warnings when they are used in the code.
println!("cargo::rustc-check-cfg=cfg(sqlite)");
println!("cargo::rustc-check-cfg=cfg(mysql)");
println!("cargo::rustc-check-cfg=cfg(postgresql)");
println!("cargo::rustc-check-cfg=cfg(s3)");
// Rerun when these paths are changed.
// Someone could have checked-out a tag or specific commit, but no other files changed.
println!("cargo:rerun-if-changed=.git");

8
docker/Dockerfile.alpine

@ -32,10 +32,10 @@ FROM --platform=linux/amd64 docker.io/vaultwarden/web-vault@sha256:7baaa7d534974
########################## ALPINE BUILD IMAGES ##########################
## NOTE: The Alpine Base Images do not support other platforms then linux/amd64 and linux/arm64
## And for Alpine we define all build images here, they will only be loaded when actually used
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:x86_64-musl-stable-1.99.1 AS build_amd64
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:aarch64-musl-stable-1.99.1 AS build_arm64
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:armv7-musleabihf-stable-1.99.1 AS build_armv7
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:arm-musleabi-stable-1.99.1 AS build_armv6
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:x86_64-musl-stable-1.100.0 AS build_amd64
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:aarch64-musl-stable-1.100.0 AS build_arm64
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:armv7-musleabihf-stable-1.100.0 AS build_armv7
FROM --platform=$BUILDPLATFORM ghcr.io/blackdex/rust-musl:arm-musleabi-stable-1.100.0 AS build_armv6
########################## BUILD IMAGE ##########################
# hadolint ignore=DL3006

2
docker/Dockerfile.debian

@ -36,7 +36,7 @@ FROM --platform=linux/amd64 docker.io/tonistiigi/xx@sha256:40fe21f44bb8cddf1eb12
########################## BUILD IMAGE ##########################
# hadolint ignore=DL3006
FROM --platform=$BUILDPLATFORM docker.io/library/rust:1.99.1-slim-trixie AS build
FROM --platform=$BUILDPLATFORM docker.io/library/rust:1.100.0-slim-trixie AS build
# hadolint ignore=DL3067
COPY --from=xx / /
ARG TARGETARCH

2
macros/Cargo.toml

@ -14,7 +14,7 @@ proc-macro = true
[dependencies]
quote = "1.0.47"
syn = "3.0.9"
syn = "3.0.10"
[lints]
workspace = true

2
macros/src/lib.rs

@ -18,7 +18,7 @@ fn impl_derive_uuid_macro(ast: &DeriveInput) -> TokenStream {
#[inline(always)]
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
if uuid::Uuid::parse_str(param).is_ok() {
if uuid::Uuid::try_parse(param).is_ok() {
Ok(Self(param.to_string()))
} else {
Err(())

2
rust-toolchain.toml

@ -1,4 +1,4 @@
[toolchain]
channel = "1.99.1"
channel = "1.100.0"
components = [ "rustfmt", "clippy" ]
profile = "minimal"

97
src/api/admin.rs

@ -125,15 +125,15 @@ impl<'r> FromRequest<'r> for IpHeader {
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
if req.headers().get_one(&CONFIG.ip_header()).is_some() {
Outcome::Success(IpHeader(Some(CONFIG.ip_header())))
Outcome::Success(Self(Some(CONFIG.ip_header())))
} else if req.headers().get_one("X-Client-IP").is_some() {
Outcome::Success(IpHeader(Some(String::from("X-Client-IP"))))
Outcome::Success(Self(Some(String::from("X-Client-IP"))))
} else if req.headers().get_one("X-Real-IP").is_some() {
Outcome::Success(IpHeader(Some(String::from("X-Real-IP"))))
Outcome::Success(Self(Some(String::from("X-Real-IP"))))
} else if req.headers().get_one("X-Forwarded-For").is_some() {
Outcome::Success(IpHeader(Some(String::from("X-Forwarded-For"))))
Outcome::Success(Self(Some(String::from("X-Forwarded-For"))))
} else {
Outcome::Success(IpHeader(None))
Outcome::Success(Self(None))
}
}
}
@ -210,7 +210,7 @@ fn post_admin_login(
let cookie = Cookie::build((COOKIE_NAME, jwt))
.path(admin_path())
.max_age(time::Duration::minutes(i64::from(CONFIG.admin_session_lifetime())))
.max_age(rocket::time::Duration::minutes(i64::from(CONFIG.admin_session_lifetime())))
.same_site(SameSite::Strict)
.http_only(true)
.secure(secure.https);
@ -391,7 +391,7 @@ async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<Stri
None => json!("Never"),
};
usr["sso_identifier"] = json!(sso_u.map_or(String::new(), |u| u.identifier.to_string()));
usr["sso_identifier"] = json!(sso_u.map_or_default(|u| u.identifier.to_string()));
// The clients are shown a Manager as a Custom member, but the admin panel tells the two roles apart
let roles: HashMap<String, i32> = Membership::find_confirmed_by_user(&u.uuid, &conn)
@ -677,46 +677,55 @@ async fn has_http_access() -> bool {
let Ok(req) = make_http_request(Method::HEAD, "https://github.com/dani-garcia/vaultwarden") else {
return false;
};
match req.send().await {
Ok(r) => r.status().is_success(),
_ => false,
}
req.send().await.is_ok_and(|r| r.status().is_success())
}
use cached::macros::cached;
/// Cache this function to prevent API call rate limit. Github only allows 60 requests per hour, and we use 3 here already
/// It will cache this function for 600 seconds (10 minutes) which should prevent the exhaustion of the rate limit
/// Any cache will be lost if Vaultwarden is restarted
#[cached(ttl_secs = 600, sync_writes = "default")]
async fn get_release_info(has_http_access: bool) -> (String, String, String) {
// If the HTTP Check failed, do not even attempt to check for new versions since we were not able to connect with github.com anyway.
if has_http_access {
(
match get_json_api::<GitRelease>("https://api.github.com/repos/dani-garcia/vaultwarden/releases/latest")
.await
{
Ok(r) => r.tag_name,
_ => "-".to_owned(),
},
match get_json_api::<GitCommit>("https://api.github.com/repos/dani-garcia/vaultwarden/commits/main").await {
Ok(mut c) => {
c.sha.truncate(8);
c.sha
}
_ => "-".to_owned(),
},
// Do not fetch the web-vault version when running within a container
// The web-vault version is embedded within the container it self, and should not be updated manually
match get_json_api::<GitRelease>("https://api.github.com/repos/dani-garcia/bw_web_builds/releases/latest")
.await
{
Ok(r) => r.tag_name.trim_start_matches('v').to_owned(),
_ => "-".to_owned(),
},
)
} else {
("-".to_owned(), "-".to_owned(), "-".to_owned())
}
// Cache this function to prevent API call rate limit. Github only allows 60 requests per hour, and we use 3 here already
// It will cache this function for 600 seconds (10 minutes) which should prevent the exhaustion of the rate limit
// Any cache will be lost if Vaultwarden is restarted
static CACHE: LazyLock<moka::future::Cache<bool, (String, String, String)>> = LazyLock::new(|| {
moka::future::Cache::builder().max_capacity(2).time_to_live(std::time::Duration::from_mins(10)).build()
});
CACHE
.get_with(has_http_access, async {
// If the HTTP Check failed, do not even attempt to check for new versions since we were not able to connect with github.com anyway.
if has_http_access {
(
match get_json_api::<GitRelease>(
"https://api.github.com/repos/dani-garcia/vaultwarden/releases/latest",
)
.await
{
Ok(r) => r.tag_name,
_ => "-".to_owned(),
},
match get_json_api::<GitCommit>("https://api.github.com/repos/dani-garcia/vaultwarden/commits/main")
.await
{
Ok(mut c) => {
c.sha.truncate(8);
c.sha
}
_ => "-".to_owned(),
},
// Do not fetch the web-vault version when running within a container
// The web-vault version is embedded within the container it self, and should not be updated manually
match get_json_api::<GitRelease>(
"https://api.github.com/repos/dani-garcia/bw_web_builds/releases/latest",
)
.await
{
Ok(r) => r.tag_name.trim_start_matches('v').to_owned(),
_ => "-".to_owned(),
},
)
} else {
("-".to_owned(), "-".to_owned(), "-".to_owned())
}
})
.await
}
async fn get_ntp_time(has_http_access: bool) -> String {

12
src/api/core/accounts.rs

@ -166,8 +166,8 @@ impl RegisterDataCompat {
fcu: impl FnOnce(&'a RegisterDataCur) -> &'a T,
) -> &'a T {
match self {
RegisterDataCompat::RegisterDataOld(rdc) => fct(rdc),
RegisterDataCompat::RegisterDataCur(rdcu) => fcu(rdcu),
Self::RegisterDataOld(rdc) => fct(rdc),
Self::RegisterDataCur(rdcu) => fcu(rdcu),
}
}
@ -186,8 +186,8 @@ impl RegisterDataCompat {
/// The id of the user key, which only the current format carries.
fn key_id(&self) -> Option<KeyId> {
match self {
RegisterDataCompat::RegisterDataOld(_) => None,
RegisterDataCompat::RegisterDataCur(rdcu) => rdcu.master_password_unlock.contained_key_id.clone(),
Self::RegisterDataOld(_) => None,
Self::RegisterDataCur(rdcu) => rdcu.master_password_unlock.contained_key_id.clone(),
}
}
@ -2194,7 +2194,7 @@ async fn password_hint(data: Json<PasswordHintData>, ip: ClientIp, conn: DbConn)
use rand::{RngExt, rngs::SmallRng};
let mut rng: SmallRng = rand::make_rng();
let sleep_ms: u64 = rng.random_range(900..=1100);
tokio::time::sleep(tokio::time::Duration::from_millis(sleep_ms)).await;
tokio::time::sleep(std::time::Duration::from_millis(sleep_ms)).await;
Ok(())
} else {
err!(NO_HINT);
@ -2371,7 +2371,7 @@ impl<'r> FromRequest<'r> for KnownDevice {
return Outcome::Error((Status::BadRequest, "X-Device-Identifier value is required"));
};
Outcome::Success(KnownDevice {
Outcome::Success(Self {
email,
uuid,
})

23
src/api/core/ciphers.rs

@ -1,7 +1,6 @@
use std::collections::{HashMap, HashSet};
use chrono::{NaiveDateTime, Utc};
use num_traits::ToPrimitive;
use rocket::{
Route,
form::{Form, FromForm},
@ -129,12 +128,10 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
let mut ciphers = Cipher::find_by_user_visible(&headers.user.uuid, &conn).await;
// Filter out SSH keys if the client version is less than 2024.12.0
let show_ssh_keys = if let Some(client_version) = client_version {
let show_ssh_keys = client_version.is_some_and(|v| {
let ver_match = semver::VersionReq::parse(">=2024.12.0").unwrap();
ver_match.matches(&client_version.0)
} else {
false
};
ver_match.matches(&v.0)
});
if !show_ssh_keys {
ciphers.retain(|c| c.atype != 5);
}
@ -287,7 +284,7 @@ async fn cipher_json_for_scope(
}
}
#[derive(Debug, Deserialize)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CipherData {
// Id is optional as it is included only in bulk share
@ -341,8 +338,7 @@ pub struct CipherData {
pub password_history: Option<Value>,
// These are used during key rotation
// 'Attachments' is unused, contains map of {id: filename}
#[allow(dead_code)]
#[cfg_attr(not(feature = "unsafe_test_mode"), expect(unused, reason = "Only read by the unsafe test seeder"))]
attachments: Option<Value>,
attachments2: Option<HashMap<AttachmentId, Attachments2Data>>,
@ -553,7 +549,7 @@ async fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn, nt
///
/// Ref: https://bitwarden.com/help/article/policies/#personal-ownership
async fn enforce_personal_ownership_policy(data: Option<&CipherData>, headers: &Headers, conn: &DbConn) -> EmptyResult {
if data.is_none() || data.unwrap().organization_id.is_none() {
if data.is_none_or(|d| d.organization_id.is_none()) {
let user_id = &headers.user.uuid;
let policy_type = OrgPolicyType::PersonalOwnership;
if OrgPolicy::is_applicable_to_user(user_id, policy_type, None, conn).await {
@ -1744,7 +1740,7 @@ async fn save_attachment(
) -> Result<(Cipher, DbConn), crate::error::Error> {
let data = data.into_inner();
let Some(size) = data.data.len().to_i64() else {
let Ok(size) = i64::try_from(data.data.len()) else {
err!("Attachment data size overflow");
};
if size < 0 {
@ -2844,10 +2840,7 @@ mod custom_role_tests {
use crate::{
api::notifications::{WS_USERS, WebSocketUsers},
auth::ClientIp,
db::{
models::{CustomPermission, Device, User},
test_db,
},
db::{models::Device, test_db},
};
use chrono::Datelike;
use diesel::connection::SimpleConnection;

3
src/api/core/emergency_access.rs

@ -793,8 +793,7 @@ fn is_valid_request(
requesting_user_id: &UserId,
requested_access_type: EmergencyAccessType,
) -> bool {
emergency_access.grantee_uuid.is_some()
&& emergency_access.grantee_uuid.as_ref().unwrap() == requesting_user_id
emergency_access.grantee_uuid.as_ref().is_some_and(|u| u == requesting_user_id)
&& emergency_access.status == EmergencyAccessStatus::RecoveryApproved as i32
&& emergency_access.atype == requested_access_type as i32
}

10
src/api/core/events.rs

@ -140,12 +140,10 @@ fn get_continuation_token(events_json: &[Value]) -> Option<&str> {
// When the length of the vec equals the max page_size there probably is more data
// When it is less, then all events are loaded.
#[expect(clippy::cast_possible_truncation, reason = "PAGE_SIZE fits within usize")]
if events_json.len() == Event::PAGE_SIZE as usize {
if let Some(last_event) = events_json.last() {
last_event["date"].as_str()
} else {
None
}
if events_json.len() == Event::PAGE_SIZE as usize
&& let Some(last_event) = events_json.last()
{
last_event["date"].as_str()
} else {
None
}

43
src/api/core/organizations.rs

@ -116,8 +116,8 @@ struct OrgData {
key: String,
name: String,
keys: Option<OrgKeyData>,
#[allow(dead_code)]
plan_type: NumberOrString, // Ignored, always use the same plan
#[expect(unused, reason = "Ignored, always use the same plan")]
plan_type: NumberOrString,
}
#[derive(Deserialize, Debug)]
@ -1317,7 +1317,7 @@ async fn send_invite(
if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() {
err!("Group not found in Organization")
}
let mut group_entry = GroupUser::new(group_id.clone(), new_member.uuid.clone());
let group_entry = GroupUser::new(group_id.clone(), new_member.uuid.clone());
group_entry.save(&conn).await?;
}
}
@ -1797,7 +1797,7 @@ async fn edit_member(
if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() {
err!("Group not found in Organization")
}
let mut group_entry = GroupUser::new(group_id.clone(), member_to_edit.uuid.clone());
let group_entry = GroupUser::new(group_id.clone(), member_to_edit.uuid.clone());
group_entry.save(&conn).await?;
}
@ -2279,13 +2279,7 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
};
let user_collections: HashMap<CollectionId, Collection> = collections
.into_iter()
.filter_map(|c| {
if data.collection_ids.contains(&c.uuid) {
Some((c.uuid.clone(), c))
} else {
None
}
})
.filter_map(|c| data.collection_ids.contains(&c.uuid).then(|| (c.uuid.clone(), c)))
.collect();
// Verify if all the collections requested exists and are writable for the user, else abort
@ -2396,10 +2390,9 @@ async fn get_policy(org_id: OrganizationId, pol_type: i32, headers: ManagePolici
err!("Invalid or unsupported policy type")
};
let policy = match OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn).await {
Some(p) => p,
None => OrgPolicy::new(org_id.clone(), pol_type_enum, false, "null".to_owned()),
};
let policy = OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn)
.await
.unwrap_or_else(|| OrgPolicy::new(org_id.clone(), pol_type_enum, false, "null".to_owned()));
Ok(Json(policy.to_json()))
}
@ -2466,11 +2459,9 @@ async fn put_policy(
// 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 =
match OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn).await {
Some(p) => p.enabled,
None => false,
};
let single_org_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn)
.await
.is_some_and(|p| p.enabled);
if !single_org_policy_enabled {
err!("Single Organization policy is not enabled. It is mandatory for this policy to be enabled.")
@ -2479,11 +2470,9 @@ async fn put_policy(
// Also prevent the Single Org Policy to be disabled if the Reset Password policy is enabled
if pol_type_enum == OrgPolicyType::SingleOrg && !data.enabled {
let reset_pw_policy_enabled =
match OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::ResetPassword, &conn).await {
Some(p) => p.enabled,
None => false,
};
let reset_pw_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::ResetPassword, &conn)
.await
.is_some_and(|p| p.enabled);
if reset_pw_policy_enabled {
err!("Account recovery policy is enabled. It is not allowed to disable this policy.")
@ -3097,12 +3086,12 @@ async fn add_update_group(
group.save(conn).await?;
for col_selection in collections {
let mut collection_group = col_selection.to_collection_group(group.uuid.clone());
let collection_group = col_selection.to_collection_group(group.uuid.clone());
collection_group.save(&org_id, conn).await?;
}
for assigned_member in members {
let mut user_entry = GroupUser::new(group.uuid.clone(), assigned_member.clone());
let user_entry = GroupUser::new(group.uuid.clone(), assigned_member.clone());
user_entry.save(conn).await?;
log_event(

4
src/api/core/public.rs

@ -156,7 +156,7 @@ async fn ldap_import(data: Json<OrgImportData>, token: PublicToken, conn: DbConn
for ext_id in &group_data.member_external_ids {
if let Some(member) = Membership::find_by_external_id_and_org(ext_id, &org_id, &conn).await {
let mut group_user = GroupUser::new(group_uuid.clone(), member.uuid.clone());
let group_user = GroupUser::new(group_uuid.clone(), member.uuid.clone());
group_user.save(&conn).await?;
}
}
@ -237,6 +237,6 @@ impl<'r> FromRequest<'r> for PublicToken {
err_handler!("Token not issued for this client");
}
Outcome::Success(PublicToken(claims.client_sub))
Outcome::Success(Self(claims.client_sub))
}
}

18
src/api/core/sends.rs

@ -1,7 +1,6 @@
use std::{path::Path, sync::LazyLock, time::Duration};
use chrono::{DateTime, TimeDelta, Utc};
use num_traits::ToPrimitive;
use rocket::{
form::Form,
fs::{NamedFile, TempFile},
@ -172,10 +171,7 @@ fn create_send(data: SendData, user_id: UserId) -> ApiResult<Send> {
let mut send = Send::new(data.r#type, data.name, data_str, data.key, data.deletion_date.naive_utc());
send.user_uuid = Some(user_id);
send.notes = data.notes;
send.max_access_count = match data.max_access_count {
Some(m) => Some(m.into_i32()?),
_ => None,
};
send.max_access_count = data.max_access_count.map(|m| m.into_i32()).transpose()?;
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
send.disabled = data.disabled;
send.hide_email = data.hide_email;
@ -303,7 +299,7 @@ async fn post_send_file_v2(data: Json<SendData>, headers: Headers, conn: DbConn)
}
#[derive(Deserialize)]
#[allow(non_snake_case)]
#[expect(non_snake_case, reason = "Bitwarden clients use this format")]
pub struct SendFileData {
id: SendFileId,
size: u64,
@ -357,10 +353,7 @@ async fn post_send_file_v2_data(
err!("Send file does not match send data.", format!("Expected id {} got {file_id}", send_data.id));
}
let Some(size) = data.data.len().to_u64() else {
err!("Send file size overflow.");
};
let size = data.data.len();
if size != send_data.size {
err!("Send file size does not match.", format!("Expected a file size of {} got {size}", send_data.size));
}
@ -538,10 +531,7 @@ async fn update_send_from_data(
send.akey = data.key;
send.deletion_date = data.deletion_date.naive_utc();
send.notes = data.notes;
send.max_access_count = match data.max_access_count {
Some(m) => Some(m.into_i32()?),
_ => None,
};
send.max_access_count = data.max_access_count.map(|m| m.into_i32()).transpose()?;
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
send.hide_email = data.hide_email;
send.disabled = data.disabled;

7
src/api/core/two_factor/authenticator.rs

@ -116,10 +116,9 @@ pub async fn validate_totp_code(
err!("Invalid TOTP secret")
};
let mut twofactor = match TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn).await {
Some(tf) => tf,
_ => TwoFactor::new(user_id.clone(), TwoFactorType::Authenticator, secret.to_owned()),
};
let mut twofactor = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn)
.await
.unwrap_or_else(|| TwoFactor::new(user_id.clone(), TwoFactorType::Authenticator, secret.to_owned()));
// The amount of steps back and forward in time
// Also check if we need to disable time drifted TOTP codes.

4
src/api/core/two_factor/duo.rs

@ -32,8 +32,8 @@ enum DuoStatus {
impl DuoStatus {
fn data(self) -> Option<DuoData> {
match self {
DuoStatus::Global(data) | DuoStatus::User(data) => Some(data),
DuoStatus::Disabled(_) => None,
Self::Global(data) | Self::User(data) => Some(data),
Self::Disabled(_) => None,
}
}
}

21
src/api/core/two_factor/duo_oidc.rs

@ -108,8 +108,8 @@ struct DuoClient {
impl DuoClient {
// Construct a new DuoClient
fn new(client_id: String, client_secret: String, api_host: String, redirect_uri: String) -> DuoClient {
DuoClient {
fn new(client_id: String, client_secret: String, api_host: String, redirect_uri: String) -> Self {
Self {
client_id,
client_secret,
api_host,
@ -137,7 +137,7 @@ impl DuoClient {
match jsonwebtoken::encode(
&Header::new(JWT_SIGNATURE_ALG),
&jwt_payload,
&EncodingKey::from_secret(self.client_secret.as_bytes()),
&EncodingKey::from_secret(self.client_secret.as_bytes())?,
) {
Ok(token) => Ok(token),
Err(e) => err!(format!("Error encoding Duo JWT: {e:?}")),
@ -157,10 +157,7 @@ impl DuoClient {
Err(e) => return Err(e),
};
let mut post_body = HashMap::new();
post_body.insert("client_assertion", token);
post_body.insert("client_id", self.client_id.clone());
let post_body = HashMap::from([("client_assertion", token), ("client_id", self.client_id.clone())]);
let res = match make_http_request(reqwest::Method::POST, &health_check_url)?
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
.form(&post_body)
@ -291,7 +288,7 @@ impl DuoClient {
let token_data = match jsonwebtoken::decode::<IdTokenClaims>(
&response.id_token,
&DecodingKey::from_secret(self.client_secret.as_bytes()),
&DecodingKey::from_secret(self.client_secret.as_bytes())?,
&validation,
) {
Ok(c) => c,
@ -422,18 +419,14 @@ pub async fn validate_duo_login(
conn: &DbConn,
) -> EmptyResult {
// Result supplied to us by clients in the form "<authz code>|<state>"
let split: Vec<&str> = two_factor_token.split('|').collect();
if split.len() != 2 {
let Some((code, state)) = two_factor_token.split_once('|').filter(|(_, state)| !state.contains('|')) else {
err!(
"Invalid response length",
ErrorEvent {
event: EventType::UserFailedLogIn2fa
}
);
}
let code = split[0];
let state = split[1];
};
let (ik, sk, host) = get_duo_keys_email(email, conn).await?;

59
src/api/core/two_factor/email.rs

@ -349,8 +349,8 @@ pub struct EmailTokenData {
}
impl EmailTokenData {
pub fn new(email: String, token: Option<String>) -> EmailTokenData {
EmailTokenData {
pub fn new(email: String, token: Option<String>) -> Self {
Self {
email,
last_token: token,
token_sent: Utc::now().timestamp(),
@ -376,8 +376,8 @@ impl EmailTokenData {
serde_json::to_string(&self).unwrap()
}
pub fn from_json(string: &str) -> Result<EmailTokenData, Error> {
let res: Result<EmailTokenData, serde_json::Error> = serde_json::from_str(string);
pub fn from_json(string: &str) -> Result<Self, Error> {
let res: Result<Self, serde_json::Error> = serde_json::from_str(string);
if let Ok(x) = res {
Ok(x)
} else {
@ -398,22 +398,21 @@ pub async fn activate_email_2fa(user: &User, conn: &DbConn) -> EmptyResult {
/// Takes an email address and obscures it by replacing it with asterisks except two characters.
pub fn obscure_email(email: &str) -> String {
let split: Vec<&str> = email.rsplitn(2, '@').collect();
let mut name = split[1].to_owned();
let domain = &split[0];
let name_size = name.chars().count();
let Some((name, domain)) = email.rsplit_once('@') else {
return "*".repeat(email.chars().count());
};
let new_name = if let 1..=3 = name_size {
"*".repeat(name_size)
let len = name.chars().count();
let keep = if len > 3 {
2
} else {
let stars = "*".repeat(name_size - 2);
name.truncate(2);
format!("{name}{stars}")
0
};
format!("{new_name}@{domain}")
// Byte offset after the first `keep` chars (UTF-8 safe).
let end = name.char_indices().nth(keep).map_or(name.len(), |(i, _)| i);
format!("{}{}@{domain}", &name[..end], "*".repeat(len - keep))
}
pub async fn find_and_activate_email_2fa(user_id: &UserId, conn: &DbConn) -> EmptyResult {
@ -431,7 +430,6 @@ mod tests {
#[test]
fn test_obscure_email_long() {
let email = "bytes@example.ext";
let result = obscure_email(email);
// Only first two characters should be visible.
@ -441,10 +439,37 @@ mod tests {
#[test]
fn test_obscure_email_short() {
let email = "byt@example.ext";
let result = obscure_email(email);
// If it's smaller than 3 characters it should only show asterisks.
assert_eq!(result, "***@example.ext");
}
// Test unicode email address, as that might cut a unicode char in half and cause a panic
#[test]
fn test_obscure_email_unicode_long() {
let email = "bɏtes@example.ext";
let result = obscure_email(email);
// Only first two characters should be visible.
assert_eq!(result, "bɏ***@example.ext");
}
#[test]
fn test_obscure_email_unicode_short() {
let email = "bɏt@example.ext";
let result = obscure_email(email);
// If it's smaller than 3 characters it should only show asterisks.
assert_eq!(result, "***@example.ext");
}
#[test]
fn test_missing_at() {
let email = "bɏt_at_example.ext";
let result = obscure_email(email);
// If it's smaller than 3 characters it should only show asterisks.
assert_eq!(result, "******************");
}
}

12
src/api/core/two_factor/webauthn.rs

@ -35,7 +35,7 @@ use crate::{
static WEBAUTHN: LazyLock<Webauthn> = LazyLock::new(|| {
let domain = CONFIG.domain();
let domain_origin = CONFIG.domain_origin();
let rp_id = Url::parse(&domain).map(|u| u.domain().map(str::to_owned)).ok().flatten().unwrap_or_default();
let rp_id = Url::parse(&domain).map_or_default(|u| u.domain().map_or_default(str::to_owned));
let rp_origin = Url::parse(&domain_origin).unwrap();
let webauthn = WebauthnBuilder::new(&rp_id, &rp_origin)
@ -355,13 +355,9 @@ async fn inner_delete_webauthns(
let mut removed: HashSet<Vec<u8>> = HashSet::new();
let mut migrated = false;
keys.retain(|key| {
let retained = retain(key);
if !retained {
removed.insert(key.credential.cred_id().to_vec());
migrated = migrated || key.migrated;
}
retained
keys.extract_if(.., |key| !retain(key)).for_each(|key| {
removed.insert(key.credential.cred_id().to_vec());
migrated |= key.migrated;
});
if removed.is_empty() {

61
src/api/icons.rs

@ -76,9 +76,6 @@ static CLIENT: LazyLock<Client> = LazyLock::new(|| {
.expect("Failed to build client")
});
// Build Regex only once since this takes a lot of time.
static ICON_SIZE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?x)(\d+)\D*(\d+)").unwrap());
// The function name `icon_external` is checked in the `on_response` function in `AppHeaders`
// It is used to prevent sending a specific header which breaks icon downloads.
// If this function needs to be renamed, also adjust the code in `util.rs`
@ -263,7 +260,7 @@ fn get_favicons_node(dom: Tokenizer<StringReader<'_>, FaviconEmitter>, icons: &m
}
TAG_BASE => {
base_url = if let Some(href) = token.tag.attributes.get(ATTR_HREF) {
let href = std::str::from_utf8(href).unwrap_or_default();
let href = str::from_utf8(href).unwrap_or_default();
debug!("Found base href: {}", href.escape_debug());
match base_url.join(href) {
Ok(inner_url) => inner_url,
@ -282,13 +279,9 @@ fn get_favicons_node(dom: Tokenizer<StringReader<'_>, FaviconEmitter>, icons: &m
for icon_tag in icon_tags {
if let Some(icon_href) = icon_tag.attributes.get(ATTR_HREF)
&& let Ok(full_href) = base_url.join(std::str::from_utf8(icon_href).unwrap_or_default())
&& let Ok(full_href) = base_url.join(str::from_utf8(icon_href).unwrap_or_default())
{
let sizes = if let Some(v) = icon_tag.attributes.get(ATTR_SIZES) {
std::str::from_utf8(v).unwrap_or_default()
} else {
""
};
let sizes = icon_tag.attributes.get(ATTR_SIZES).map_or_default(|v| str::from_utf8(v).unwrap_or_default());
let priority = get_icon_priority(full_href.as_str(), sizes);
icons.push(Icon::new(priority, full_href.to_string()));
}
@ -443,7 +436,7 @@ async fn get_page_with_referer(url: &str, referer: &str) -> Result<Response, Err
/// ```
fn get_icon_priority(href: &str, sizes: &str) -> u8 {
static PRIORITY_MAP: LazyLock<HashMap<&'static str, u8>> =
LazyLock::new(|| [(".png", 10), (".jpg", 20), (".jpeg", 20)].into_iter().collect());
LazyLock::new(|| HashMap::from([("png", 10), ("jpg", 20), ("jpeg", 20)]));
// Check if there is a dimension set
let (width, height) = parse_sizes(sizes);
@ -489,20 +482,12 @@ fn get_icon_priority(href: &str, sizes: &str) -> u8 {
/// let (width, height) = parse_sizes("32"); // (0, 0)
/// ```
fn parse_sizes(sizes: &str) -> (u16, u16) {
let mut width: u16 = 0;
let mut height: u16 = 0;
if !sizes.is_empty() {
match ICON_SIZE_REGEX.captures(sizes.trim()) {
Some(dimensions) if dimensions.len() >= 3 => {
width = dimensions[1].parse::<u16>().unwrap_or_default();
height = dimensions[2].parse::<u16>().unwrap_or_default();
}
_ => {}
}
}
static ICON_SIZE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\d+)\D+(\d+)").unwrap());
(width, height)
ICON_SIZE_REGEX
.captures(sizes)
.and_then(|c| Some((c[1].parse::<u16>().ok()?, c[2].parse::<u16>().ok()?)))
.unwrap_or((0, 0))
}
async fn download_icon(domain: &str) -> Result<(Bytes, Option<&str>), Error> {
@ -602,12 +587,10 @@ async fn save_icon(path: &str, icon: Vec<u8>) {
fn get_icon_type(bytes: &[u8]) -> Option<&'static str> {
fn check_svg_after_xml_declaration(bytes: &[u8]) -> Option<&'static str> {
// Look for SVG tag within the first 1KB
if let Ok(content) = std::str::from_utf8(&bytes[..bytes.len().min(1024)])
&& (content.contains("<svg") || content.contains("<SVG"))
{
return Some("svg+xml");
}
None
const SVG_MATCH: &[u8; 4] = b"<svg";
let content = &bytes[..bytes.len().min(1024)];
// Even though XML is case-sensitive we will do a case insensitive match
content.windows(SVG_MATCH.len()).any(|w| w.eq_ignore_ascii_case(SVG_MATCH)).then_some("svg+xml")
}
// Some details can be found here:
@ -659,8 +642,7 @@ pub struct Jar(std::sync::RwLock<CookieStore>);
impl reqwest::cookie::CookieStore for Jar {
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
use cookie::{Cookie as RawCookie, ParseError as RawCookieParseError};
use time::Duration;
use cookie::{Cookie as RawCookie, ParseError as RawCookieParseError, time::Duration};
let mut cookie_store = self.0.write().unwrap();
@ -675,7 +657,7 @@ impl reqwest::cookie::CookieStore for Jar {
}
let cookies = cookie_headers.filter_map(|val| {
std::str::from_utf8(val.as_bytes())
str::from_utf8(val.as_bytes())
.map_err(RawCookieParseError::from)
.and_then(RawCookie::parse)
.map(|mut c| {
@ -746,8 +728,7 @@ impl FaviconEmitter {
if let Some(ref mut token) = self.current_token {
let tag_name: &[u8] = &token.tag.name;
if self.current_attribute.is_some() && (tag_name == TAG_BASE || tag_name == TAG_LINK) {
let (k, v) = self.current_attribute.take().unwrap();
if let Some((k, v)) = self.current_attribute.take_if(|_| tag_name == TAG_BASE || tag_name == TAG_LINK) {
token.tag.attributes.entry(k).and_modify(|_| {}).or_insert(v);
}
@ -756,8 +737,7 @@ impl FaviconEmitter {
TAG_HEAD if token.closing => self.emit_token = true,
TAG_BASE if tag_attr.contains_key(ATTR_HREF) => self.emit_token = true,
TAG_LINK if emit_current_tag && tag_attr.contains_key(ATTR_REL) && tag_attr.contains_key(ATTR_HREF) => {
let rel_value =
std::str::from_utf8(token.tag.attributes.get(ATTR_REL).unwrap()).unwrap_or_default();
let rel_value = str::from_utf8(token.tag.attributes.get(ATTR_REL).unwrap()).unwrap_or_default();
if rel_value.contains("icon") && !rel_value.contains("mask-icon") {
self.emit_token = true;
}
@ -843,10 +823,9 @@ impl Emitter for FaviconEmitter {
}
fn current_is_appropriate_end_tag_token(&mut self) -> bool {
match &self.current_token {
Some(token) if token.closing => !self.last_start_tag.is_empty() && self.last_start_tag == token.tag.name,
_ => false,
}
self.current_token
.as_ref()
.is_some_and(|t| t.closing && (!self.last_start_tag.is_empty() && self.last_start_tag == t.tag.name))
}
// We do not want and need these parts of the HTML document

34
src/api/identity.rs

@ -467,9 +467,9 @@ async fn password_login(
let now = Utc::now().naive_utc();
if user.verified_at.is_none() && CONFIG.mail_enabled() && CONFIG.signups_verify() {
if user.last_verifying_at.is_none()
|| now.signed_duration_since(user.last_verifying_at.unwrap()).num_seconds()
> i64::from(CONFIG.signups_verify_resend_time())
if user
.last_verifying_at
.is_none_or(|d| now.signed_duration_since(d).num_seconds() > i64::from(CONFIG.signups_verify_resend_time()))
{
let resend_limit = i32::from(CONFIG.signups_verify_resend_limit());
if resend_limit == 0 || user.login_verify_count < resend_limit {
@ -1155,7 +1155,7 @@ async fn register_verification_email(
use rand::{RngExt, rngs::SmallRng};
let mut rng: SmallRng = rand::make_rng();
let sleep_ms: u64 = rng.random_range(900..=1100);
tokio::time::sleep(tokio::time::Duration::from_millis(sleep_ms)).await;
tokio::time::sleep(std::time::Duration::from_millis(sleep_ms)).await;
} else {
mail::send_register_verify_email(&data.email, &token).await?;
}
@ -1233,10 +1233,10 @@ struct ConnectData {
#[field(name = uncased("device_type"))]
#[field(name = uncased("devicetype"))]
device_type: Option<String>,
#[allow(unused)]
#[expect(unused, reason = "Unused, mobile device push not yet supported")]
#[field(name = uncased("device_push_token"))]
#[field(name = uncased("devicepushtoken"))]
_device_push_token: Option<String>, // Unused; mobile device push not yet supported.
device_push_token: Option<String>,
// Needed for two-factor auth
#[field(name = uncased("two_factor_provider"))]
@ -1283,8 +1283,8 @@ fn prevalidate() -> JsonResult {
const SSO_BINDING_COOKIE: &str = "VW_SSO_BINDING";
#[get("/connect/oidc-signin?<code>&<state>", rank = 1)]
async fn oidcsignin(code: OIDCCode, state: String, cookies: &CookieJar<'_>, mut conn: DbConn) -> ApiResult<Redirect> {
oidcsignin_redirect(state, code, None, cookies, &mut conn).await
async fn oidcsignin(code: OIDCCode, state: String, cookies: &CookieJar<'_>, conn: DbConn) -> ApiResult<Redirect> {
oidcsignin_redirect(state, code, None, cookies, &conn).await
}
// Bitwarden client appear to only care for code and state
@ -1296,7 +1296,7 @@ async fn oidcsignin_error(
error: String,
error_description: Option<String>,
cookies: &CookieJar<'_>,
mut conn: DbConn,
conn: DbConn,
) -> ApiResult<Redirect> {
oidcsignin_redirect(
state.clone(),
@ -1306,7 +1306,7 @@ async fn oidcsignin_error(
error_description,
}),
cookies,
&mut conn,
&conn,
)
.await
}
@ -1319,7 +1319,7 @@ async fn oidcsignin_redirect(
code: OIDCCode,
error: Option<OIDCCodeResponseError>,
cookies: &CookieJar<'_>,
conn: &mut DbConn,
conn: &DbConn,
) -> ApiResult<Redirect> {
let state = sso::decode_state(&base64_state)?;
@ -1367,18 +1367,18 @@ struct AuthorizeData {
#[field(name = uncased("redirect_uri"))]
#[field(name = uncased("redirecturi"))]
redirect_uri: String,
#[allow(unused)]
#[expect(unused)]
response_type: Option<String>,
#[allow(unused)]
#[expect(unused)]
scope: Option<String>,
state: OIDCState,
code_challenge: OIDCCodeChallenge,
code_challenge_method: String,
#[allow(unused)]
#[expect(unused)]
response_mode: Option<String>,
#[allow(unused)]
#[expect(unused)]
domain_hint: Option<String>,
#[allow(unused)]
#[expect(unused)]
#[field(name = uncased("ssoToken"))]
sso_token: Option<String>,
}
@ -1410,7 +1410,7 @@ async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure,
cookies.add(
Cookie::build((SSO_BINDING_COOKIE, binding_token))
.path(format!("{}/identity/connect/", CONFIG.domain_path()))
.max_age(time::Duration::seconds(sso::SSO_AUTH_EXPIRATION.num_seconds()))
.max_age(rocket::time::Duration::seconds(sso::SSO_AUTH_EXPIRATION.num_seconds()))
.same_site(SameSite::Lax) // Lax is needed because the IdP runs on a different FQDN
.http_only(true)
.secure(secure.https)

2
src/api/mod.rs

@ -120,7 +120,7 @@ async fn master_password_policy(user: &User, conn: &DbConn) -> Value {
}
}))
} else if CONFIG.sso_enabled() {
CONFIG.sso_master_password_policy_value().unwrap_or(json!({}))
CONFIG.sso_master_password_policy_value().unwrap_or_else(|| json!({}))
} else {
json!({})
};

13
src/api/notifications.rs

@ -615,12 +615,11 @@ impl AnonymousWebSocketSubscriptions {
/// Releases a slot taken by `try_reserve`.
fn release(&self, addr: IpAddr) {
let empty = if let Some(mut count) = self.connections.get_mut(&addr) {
*count = count.saturating_sub(1);
*count == 0
} else {
false
};
let empty = self.connections.get_mut(&addr).is_some_and(|mut c| {
*c = c.saturating_sub(1);
*c == 0
});
// Only remove once the guard above is dropped, otherwise this deadlocks.
if empty {
self.connections.remove_if(&addr, |_, count| *count == 0);
@ -629,7 +628,7 @@ impl AnonymousWebSocketSubscriptions {
async fn send_update(&self, token: &str, data: &[u8]) {
// Clone the senders so the map isn't kept locked while sending.
let senders = self.map.get(token).map(|v| v.clone()).unwrap_or_default();
let senders = self.map.get(token).map_or_default(|v| v.clone());
for (_, sender) in senders {
if let Err(e) = sender.send(Message::binary(data)).await {
error!("Error sending WS update {e}");

56
src/auth.rs

@ -43,12 +43,12 @@ use crate::{
const JWT_ALGORITHM: Algorithm = Algorithm::RS256;
// Limit when BitWarden consider the token as expired
pub static BW_EXPIRATION: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_minutes(5).unwrap());
// Limit when Bitwarden consider the token as expired
pub static BW_EXPIRATION: TimeDelta = TimeDelta::try_minutes(5).unwrap();
pub static DEFAULT_REFRESH_VALIDITY: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_days(30).unwrap());
pub static MOBILE_REFRESH_VALIDITY: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_days(90).unwrap());
pub static DEFAULT_ACCESS_VALIDITY: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_hours(2).unwrap());
pub static DEFAULT_REFRESH_VALIDITY: TimeDelta = TimeDelta::try_days(30).unwrap();
pub static MOBILE_REFRESH_VALIDITY: TimeDelta = TimeDelta::try_days(90).unwrap();
pub static DEFAULT_ACCESS_VALIDITY: TimeDelta = TimeDelta::try_hours(2).unwrap();
static JWT_HEADER: LazyLock<Header> = LazyLock::new(|| Header::new(JWT_ALGORITHM));
pub static JWT_LOGIN_ISSUER: LazyLock<String> = LazyLock::new(|| format!("{}|login", CONFIG.domain_origin()));
@ -258,7 +258,7 @@ impl LoginJwtClaims {
// let orguser: Vec<_> = orgs.iter().filter(|o| o.atype == 2).map(|o| o.org_uuid.clone()).collect();
// let orgmanager: Vec<_> = orgs.iter().filter(|o| o.atype == 3).map(|o| o.org_uuid.clone()).collect();
if exp <= (now + *BW_EXPIRATION).timestamp() {
if exp <= (now + BW_EXPIRATION).timestamp() {
warn!("Raise access_token lifetime to more than 5min.");
}
@ -286,7 +286,7 @@ impl LoginJwtClaims {
sstamp: user.security_stamp.clone(),
device: device.uuid.clone(),
devicetype: DeviceType::from_i32(device.atype).to_string(),
client_id: client_id.unwrap_or("undefined".to_owned()),
client_id: client_id.unwrap_or_else(|| "undefined".to_owned()),
scope,
amr: vec!["Application".into()],
}
@ -298,7 +298,7 @@ impl LoginJwtClaims {
device,
user,
time_now.timestamp(),
(time_now + *DEFAULT_ACCESS_VALIDITY).timestamp(),
(time_now + DEFAULT_ACCESS_VALIDITY).timestamp(),
auth_method.scope_vec(),
client_id,
time_now,
@ -623,7 +623,7 @@ impl<'r> FromRequest<'r> for Host {
format!("{protocol}://{host}")
};
Outcome::Success(Host {
Outcome::Success(Self {
host,
})
}
@ -654,7 +654,7 @@ impl<'r> FromRequest<'r> for ClientHeaders {
let client_version =
request.headers().get_one("Bitwarden-Client-Version").and_then(|v| semver::Version::parse(v).ok());
Outcome::Success(ClientHeaders {
Outcome::Success(Self {
device_type,
ip,
client_version,
@ -723,7 +723,7 @@ impl<'r> FromRequest<'r> for Headers {
}
}
Outcome::Success(Headers {
Outcome::Success(Self {
host,
device,
user,
@ -789,7 +789,7 @@ impl<'r> FromRequest<'r> for OrgIdGuard {
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match get_org_id(request) {
Some(_) => Outcome::Success(OrgIdGuard),
Some(_) => Outcome::Success(Self),
None => Outcome::Forward(rocket::http::Status::NotFound),
}
}
@ -1065,8 +1065,8 @@ macro_rules! collection_headers {
}
impl From<$name> for Headers {
fn from(h: $name) -> Headers {
Headers {
fn from(h: $name) -> Self {
Self {
host: h.host,
device: h.device,
user: h.user,
@ -1132,8 +1132,8 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose {
}
impl From<ManagerHeadersLoose> for Headers {
fn from(h: ManagerHeadersLoose) -> Headers {
Headers {
fn from(h: ManagerHeadersLoose) -> Self {
Self {
host: h.host,
device: h.device,
user: h.user,
@ -1147,7 +1147,7 @@ impl CollectionDeleteHeaders {
h: ManagerHeadersLoose,
collections: &Vec<CollectionId>,
conn: &DbConn,
) -> Result<CollectionDeleteHeaders, Error> {
) -> Result<Self, Error> {
let is_custom = h.membership.has_type(MembershipType::Custom) && custom_roles_enabled();
for col_id in collections {
if uuid::Uuid::parse_str(col_id.as_ref()).is_err() {
@ -1164,7 +1164,7 @@ impl CollectionDeleteHeaders {
}
}
Ok(CollectionDeleteHeaders {
Ok(Self {
host: h.host,
device: h.device,
user: h.user,
@ -1229,8 +1229,8 @@ impl<'r> FromRequest<'r> for OrgMemberHeaders {
}
impl From<OrgMemberHeaders> for Headers {
fn from(h: OrgMemberHeaders) -> Headers {
Headers {
fn from(h: OrgMemberHeaders) -> Self {
Self {
host: h.host,
device: h.device,
user: h.user,
@ -1322,7 +1322,7 @@ impl<'r> FromRequest<'r> for ClientIp {
let ip = ip.or(remote).unwrap_or_else(|| "0.0.0.0".parse().unwrap());
Outcome::Success(ClientIp {
Outcome::Success(Self {
ip,
})
}
@ -1352,7 +1352,7 @@ impl<'r> FromRequest<'r> for Secure {
}
};
Outcome::Success(Secure {
Outcome::Success(Self {
https: protocol == "https",
})
}
@ -1398,7 +1398,7 @@ impl<'r> FromRequest<'r> for ClientVersion {
err_handler!("Invalid Bitwarden-Client-Version header provided")
};
Outcome::Success(ClientVersion(version))
Outcome::Success(Self(version))
}
}
@ -1414,9 +1414,9 @@ pub enum AuthMethod {
impl AuthMethod {
pub fn scope(&self) -> String {
match self {
AuthMethod::OrgApiKey => "api.organization".to_owned(),
AuthMethod::UserApiKey => "api".to_owned(),
AuthMethod::Password | AuthMethod::Sso => "api offline_access".to_owned(),
Self::OrgApiKey => "api.organization".to_owned(),
Self::UserApiKey => "api".to_owned(),
Self::Password | Self::Sso => "api offline_access".to_owned(),
}
}
@ -1486,9 +1486,9 @@ impl AuthTokens {
let access_claims = LoginJwtClaims::default(device, user, &sub, client_id);
let validity = if device.is_mobile() {
*MOBILE_REFRESH_VALIDITY
MOBILE_REFRESH_VALIDITY
} else {
*DEFAULT_REFRESH_VALIDITY
DEFAULT_REFRESH_VALIDITY
};
let refresh_claims = RefreshJwtClaims {

8
src/auth/send.rs

@ -45,7 +45,7 @@ impl SendTokens {
})
}
fn expected_error(msg: &str, error_type: &str) -> ApiResult<SendTokens> {
fn expected_error(msg: &str, error_type: &str) -> ApiResult<Self> {
let err = json!({
"kind": "expected_server",
"error": "invalid_request",
@ -55,7 +55,7 @@ impl SendTokens {
Err(Error::new_msg(msg).with_kind(ErrorKind::Json(err)).silent())
}
fn invalid_error(msg: &str, error_type: &str, silent: bool) -> ApiResult<SendTokens> {
fn invalid_error(msg: &str, error_type: &str, silent: bool) -> ApiResult<Self> {
let err = json!({
"kind": "expected_server",
"error": "invalid_grant",
@ -70,7 +70,7 @@ impl SendTokens {
password: Option<String>,
ip: &ClientIp,
conn: &DbConn,
) -> ApiResult<SendTokens> {
) -> ApiResult<Self> {
let Some(send_id) = Self::as_send_id(access_id) else {
return Self::invalid_error(
&format!("Can't convert {}", access_id.escape_debug()),
@ -140,7 +140,7 @@ impl<'r> FromRequest<'r> for SendHeaders {
err_handler!("Invalid claim")
};
Outcome::Success(SendHeaders {
Outcome::Success(Self {
send_id: claims.sub.into(),
})
}

47
src/config.rs

@ -129,7 +129,7 @@ macro_rules! make_config {
)+)+
];
#[allow(non_camel_case_types)]
#[expect(non_camel_case_types, reason="ConfigBuilder uses different case types")]
enum Field {
$($(
$name,
@ -362,7 +362,6 @@ macro_rules! make_config {
elements: Vec<ElementData>,
}
#[allow(unused)]
impl Config {
$($(
$(#[doc = $doc])+
@ -479,13 +478,11 @@ macro_rules! make_config {
let mut json = serde_json::Map::new();
$($(
json.insert(String::from(stringify!($name)), make_config! { @supportstr $name, cfg.$name, $ty, $none_action });
)+)+;
)+)+
// Loop through all privacy sensitive keys and mask them
for mask_key in PRIVACY_CONFIG {
if let Some(value) = json.get_mut(*mask_key) {
if let Some(s) = value.as_str() {
*value = privacy_mask(s).into();
}
if let Some(value) = json.get_mut(*mask_key) && let Some(s) = value.as_str() {
*value = privacy_mask(s).into();
}
}
json
@ -693,7 +690,7 @@ make_config! {
/// Set to the string "none" (without quotes), to disable any headers and just use the remote IP
ip_header: String, true, def, "X-Real-IP".to_owned();
/// Internal IP header property, used to avoid recomputing each time
_ip_header_enabled: bool, false, generated, |c| &c.ip_header.trim().to_lowercase() != "none";
_ip_header_enabled: bool, false, generated, |c| !c.ip_header.trim().eq_ignore_ascii_case("none");
/// Trusted proxies |> Which addresses the client IP header is accepted from. Requests from any
/// other address use the remote IP instead, so a client can't spoof the header.
/// Either the string "local" (the default, any non-global address, which covers a reverse proxy
@ -1422,13 +1419,7 @@ fn extract_url_origin(url: &str) -> String {
/// Extracts the path from a URL.
/// All trailing '/' chars are trimmed, even if the path is a lone '/'.
fn extract_url_path(url: &str) -> String {
match Url::parse(url) {
Ok(u) => u.path().trim_end_matches('/').to_owned(),
Err(_) => {
// We already print it in the method above, no need to do it again
String::new()
}
}
Url::parse(url).map_or_default(|u| u.path().trim_end_matches('/').to_owned())
}
fn generate_smtp_img_src(embed_images: bool, domain: &str) -> String {
@ -1463,10 +1454,7 @@ fn generate_icon_service_url(icon_service: &str) -> String {
fn generate_icon_service_csp(icon_service: &str, icon_service_url: &str) -> String {
// We split on the first '{', since that is the variable delimiter for an icon service URL.
// Everything up until the first '{' should be fixed and can be used as an CSP string.
let csp_string = match icon_service_url.split_once('{') {
Some((c, _)) => c.to_owned(),
None => String::new(),
};
let csp_string = icon_service_url.split_once('{').map_or_default(|(c, _)| c.to_owned());
// Because Google does a second redirect to there gstatic.com domain, we need to add an extra csp string.
match icon_service {
@ -1480,9 +1468,9 @@ fn smtp_convert_deprecated_ssl_options(smtp_ssl: Option<bool>, smtp_explicit_tls
if smtp_explicit_tls.is_some() || smtp_ssl.is_some() {
println!("[DEPRECATED]: `SMTP_SSL` or `SMTP_EXPLICIT_TLS` is set. Please use `SMTP_SECURITY` instead.");
}
if smtp_explicit_tls.is_some() && smtp_explicit_tls.unwrap() {
if smtp_explicit_tls.is_some_and(|b| b) {
return "force_tls".to_owned();
} else if smtp_ssl.is_some() && !smtp_ssl.unwrap() {
} else if smtp_ssl.is_some_and(|b| !b) {
return "off".to_owned();
}
// Return the default `starttls` in all other cases
@ -1566,7 +1554,7 @@ impl Config {
validate_config(&config, false)?;
}
Ok(Config {
Ok(Self {
inner: RwLock::new(Inner {
rocket_shutdown_handle: None,
templates: load_templates(&config.templates_folder),
@ -1625,15 +1613,17 @@ impl Config {
/// is in signups_domains_whitelist, or if no whitelist is set (so there
/// are no domain restrictions in effect).
pub fn is_email_domain_allowed(&self, email: &str) -> bool {
let e: Vec<&str> = email.rsplitn(2, '@').collect();
if e.len() != 2 || e[0].is_empty() || e[1].is_empty() {
let Some((_, domain)) = email.rsplit_once('@').filter(|(name, domain)| !name.is_empty() && !domain.is_empty())
else {
warn!("Failed to parse email address '{}'", email.escape_debug());
return false;
}
let email_domain = e[0].to_lowercase();
};
let domain = &domain.to_lowercase();
let whitelist = self.signups_domains_whitelist();
let whitelist = whitelist.trim();
whitelist.is_empty() || whitelist.split(',').any(|d| d.trim() == email_domain)
whitelist.is_empty() || whitelist.split(',').any(|d| d.trim() == domain)
}
/// Tests whether signup is allowed for an email address, taking into
@ -1724,8 +1714,7 @@ impl Config {
/// Tests whether the admin token is set to a non-empty value.
pub fn is_admin_token_set(&self) -> bool {
let token = self.admin_token();
token.is_some() && !token.unwrap().trim().is_empty()
token.is_some_and(|t| !t.trim().is_empty())
}
pub fn opendal_operator_for_path_type(&self, path_type: &PathType) -> Result<opendal::Operator, Error> {

19
src/db/mod.rs

@ -1,7 +1,6 @@
mod query_logger;
use std::{
future::Future,
sync::{
Arc, OnceLock,
atomic::{AtomicBool, Ordering},
@ -237,7 +236,7 @@ impl DbPool {
error!("Tried to set the active database connection type more than once.");
}
Ok(DbPool {
Ok(Self {
pool: Some(pool),
semaphore: Arc::new(Semaphore::new(max_conns as usize)),
})
@ -268,25 +267,25 @@ impl DbPool {
impl DbConnType {
pub fn from_url(url: &str) -> Result<Self, Error> {
// Mysql
if url.len() > 6 && &url[..6] == "mysql:" {
if url.starts_with("mysql:") {
#[cfg(mysql)]
return Ok(DbConnType::Mysql);
return Ok(Self::Mysql);
#[cfg(not(mysql))]
err!("`DATABASE_URL` is a MySQL URL, but the 'mysql' feature is not enabled")
// Postgresql
} else if url.len() > 11 && (&url[..11] == "postgresql:" || &url[..9] == "postgres:") {
} else if url.starts_with("postgresql:") || url.starts_with("postgres:") {
#[cfg(postgresql)]
return Ok(DbConnType::Postgresql);
return Ok(Self::Postgresql);
#[cfg(not(postgresql))]
err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled")
// Sqlite (explicit)
} else if url.len() > 7 && &url[..7] == "sqlite:" {
} else if url.starts_with("sqlite:") {
#[cfg(sqlite)]
return Ok(DbConnType::Sqlite);
return Ok(Self::Sqlite);
#[cfg(not(sqlite))]
err!("`DATABASE_URL` is a SQLite URL, but the 'sqlite' feature is not enabled")
@ -297,7 +296,7 @@ impl DbConnType {
#[cfg(sqlite)]
{
if std::path::Path::new(url).exists() {
return Ok(DbConnType::Sqlite);
return Ok(Self::Sqlite);
}
err!(format!(
"`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://) \
@ -438,8 +437,6 @@ pub mod models;
/// MySQL/MariaDB and PostgreSQL are not supported.
#[cfg(sqlite)]
pub fn backup_sqlite() -> Result<String, Error> {
use diesel::Connection;
let db_url = CONFIG.database_url();
if DbConnType::from_url(&CONFIG.database_url()).is_ok_and(|t| t == DbConnType::Sqlite) {
// Strip the sqlite:// prefix if present to get the raw file path

2
src/db/models/attachment.rs

@ -146,7 +146,7 @@ impl Attachment {
}
pub async fn delete_all_by_cipher(cipher_uuid: &CipherId, conn: &DbConn) -> EmptyResult {
for attachment in Attachment::find_by_cipher(cipher_uuid, conn).await {
for attachment in Self::find_by_cipher(cipher_uuid, conn).await {
attachment.delete(conn).await?;
}
Ok(())

44
src/db/models/cipher.rs

@ -97,8 +97,8 @@ impl CipherAccessScope {
/// Whether `member` reaches every cipher of their organization with this access.
fn reaches_all_ciphers(self, member: &Membership) -> bool {
match self {
CipherAccessScope::User => member.has_full_access(),
CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(),
Self::User => member.has_full_access(),
Self::OrganizationAdmin => member.can_edit_any_collection(),
}
}
@ -106,18 +106,18 @@ impl CipherAccessScope {
/// administrative one still needs a member who may edit any collection.
pub fn requested(admin_request: Option<bool>) -> Self {
if admin_request == Some(true) {
CipherAccessScope::OrganizationAdmin
Self::OrganizationAdmin
} else {
CipherAccessScope::User
Self::User
}
}
/// The access for a route that does not tell which one it is, from the member's own membership.
pub fn for_member(member: Option<&Membership>) -> Self {
if member.is_some_and(Membership::can_edit_any_collection) {
CipherAccessScope::OrganizationAdmin
Self::OrganizationAdmin
} else {
CipherAccessScope::User
Self::User
}
}
}
@ -306,7 +306,7 @@ impl Cipher {
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
.ok()
})
.map(|d| {
.map_or_default(|d| {
d.into_iter()
.map(|mut f| {
// Check if the `type` key is a number, strings break some clients
@ -326,8 +326,7 @@ impl Cipher {
f.data
})
.collect()
})
.unwrap_or_default();
});
let password_history_json: Vec<_> = self
.password_history
@ -337,7 +336,7 @@ impl Cipher {
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
.ok()
})
.map(|d| {
.map_or_default(|d| {
// Check every password history item if they are valid and return it.
// If a password field has the type `null` skip it, it breaks newer Bitwarden clients
// A second check is done to verify the lastUsedDate exists and is a valid DateTime string, if not the epoch start time will be used
@ -356,19 +355,14 @@ impl Cipher {
d
})
.collect()
})
.unwrap_or_default();
});
// Like upstream, fields and password history stored as NULL are sent as null, not `[]`
let fields_json = self.fields.is_some().then_some(fields_json);
let password_history_json = self.password_history.is_some().then_some(password_history_json);
let collection_ids = if let Some(cipher_sync_data) = cipher_sync_data {
if let Some(cipher_collections) = cipher_sync_data.cipher_collections.get(&self.uuid) {
Cow::from(cipher_collections)
} else {
Cow::from(Vec::new())
}
cipher_sync_data.cipher_collections.get(&self.uuid).map_or_default(Cow::from)
} else {
Cow::from(self.get_admin_collections(user_uuid.clone(), scope, conn).await)
};
@ -688,7 +682,7 @@ impl Cipher {
/// Returns whether this cipher is directly owned by the user.
pub fn is_owned_by_user(&self, user_uuid: &UserId) -> bool {
self.user_uuid.is_some() && self.user_uuid.as_ref().unwrap() == user_uuid
self.user_uuid.as_ref().is_some_and(|u| u == user_uuid)
}
/// Returns whether this cipher is owned by an org in which the user reaches every cipher with `scope`.
@ -875,10 +869,9 @@ impl Cipher {
scope: CipherAccessScope,
conn: &DbConn,
) -> bool {
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
Some((read_only, _hide_passwords, manage)) => !read_only || manage,
None => false,
}
self.get_access_restrictions(user_uuid, scope, None, conn)
.await
.is_some_and(|(read_only, _hide_passwords, manage)| !read_only || manage)
}
// used for checking if collection can be edited (only if user has access to a collection they
@ -889,10 +882,9 @@ impl Cipher {
scope: CipherAccessScope,
conn: &DbConn,
) -> bool {
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
Some((read_only, hide_passwords, manage)) => (!read_only && !hide_passwords) || manage,
None => false,
}
self.get_access_restrictions(user_uuid, scope, None, conn)
.await
.is_some_and(|(read_only, hide_passwords, manage)| (!read_only && !hide_passwords) || manage)
}
pub async fn is_accessible_to_user(&self, user_uuid: &UserId, scope: CipherAccessScope, conn: &DbConn) -> bool {

2
src/db/models/collection.rs

@ -878,7 +878,7 @@ impl CollectionUser {
}
pub async fn delete_all_by_collection(collection_uuid: &CollectionId, conn: &DbConn) -> EmptyResult {
for collection in &CollectionUser::find_by_collection(collection_uuid, conn).await {
for collection in &Self::find_by_collection(collection_uuid, conn).await {
User::update_uuid_revision(&collection.user_uuid, conn).await;
}

62
src/db/models/device.rs

@ -51,7 +51,7 @@ impl Device {
push_uuid: Some(PushId(get_uuid())),
push_token: None,
refresh_token: Device::generate_refresh_token(),
refresh_token: Self::generate_refresh_token(),
twofactor_remember: None,
}
}
@ -268,7 +268,7 @@ impl Device {
// We cannot do a single UPDATE with one value because each device needs a unique token.
let devices = Self::find_by_user(user_uuid, conn).await;
for mut device in devices {
device.refresh_token = Device::generate_refresh_token();
device.refresh_token = Self::generate_refresh_token();
device.twofactor_remember = None;
device.save(false, conn).await?;
}
@ -347,36 +347,36 @@ pub enum DeviceType {
impl DeviceType {
#[expect(clippy::match_same_arms, reason = "Specifically define 14 and have a fallback for new types")]
pub fn from_i32(value: i32) -> DeviceType {
pub fn from_i32(value: i32) -> Self {
match value {
0 => DeviceType::Android,
1 => DeviceType::Ios,
2 => DeviceType::ChromeExtension,
3 => DeviceType::FirefoxExtension,
4 => DeviceType::OperaExtension,
5 => DeviceType::EdgeExtension,
6 => DeviceType::WindowsDesktop,
7 => DeviceType::MacOsDesktop,
8 => DeviceType::LinuxDesktop,
9 => DeviceType::ChromeBrowser,
10 => DeviceType::FirefoxBrowser,
11 => DeviceType::OperaBrowser,
12 => DeviceType::EdgeBrowser,
13 => DeviceType::IEBrowser,
14 => DeviceType::UnknownBrowser,
15 => DeviceType::AndroidAmazon,
16 => DeviceType::Uwp,
17 => DeviceType::SafariBrowser,
18 => DeviceType::VivaldiBrowser,
19 => DeviceType::VivaldiExtension,
20 => DeviceType::SafariExtension,
21 => DeviceType::Sdk,
22 => DeviceType::Server,
23 => DeviceType::WindowsCLI,
24 => DeviceType::MacOsCLI,
25 => DeviceType::LinuxCLI,
26 => DeviceType::DuckDuckGoBrowser,
_ => DeviceType::UnknownBrowser,
0 => Self::Android,
1 => Self::Ios,
2 => Self::ChromeExtension,
3 => Self::FirefoxExtension,
4 => Self::OperaExtension,
5 => Self::EdgeExtension,
6 => Self::WindowsDesktop,
7 => Self::MacOsDesktop,
8 => Self::LinuxDesktop,
9 => Self::ChromeBrowser,
10 => Self::FirefoxBrowser,
11 => Self::OperaBrowser,
12 => Self::EdgeBrowser,
13 => Self::IEBrowser,
14 => Self::UnknownBrowser,
15 => Self::AndroidAmazon,
16 => Self::Uwp,
17 => Self::SafariBrowser,
18 => Self::VivaldiBrowser,
19 => Self::VivaldiExtension,
20 => Self::SafariExtension,
21 => Self::Sdk,
22 => Self::Server,
23 => Self::WindowsCLI,
24 => Self::MacOsCLI,
25 => Self::LinuxCLI,
26 => Self::DuckDuckGoBrowser,
_ => Self::UnknownBrowser,
}
}
}

6
src/db/models/emergency_access.rs

@ -141,8 +141,8 @@ pub enum EmergencyAccessType {
impl EmergencyAccessType {
pub fn from_str(s: &str) -> Option<Self> {
match s {
"0" | "View" => Some(EmergencyAccessType::View),
"1" | "Takeover" => Some(EmergencyAccessType::Takeover),
"0" | "View" => Some(Self::View),
"1" | "Takeover" => Some(Self::Takeover),
_ => None,
}
}
@ -397,7 +397,7 @@ impl EmergencyAccess {
}
pub async fn accept_invite(&mut self, grantee_uuid: &UserId, grantee_email: &str, conn: &DbConn) -> EmptyResult {
if self.email.is_none() || self.email.as_ref().unwrap() != grantee_email {
if self.email.as_ref().is_none_or(|e| e != grantee_email) {
err!("User email does not match invite.");
}

8
src/db/models/event.rs

@ -151,11 +151,7 @@ pub enum EventType {
/// Local methods
impl Event {
pub fn new(event_type: i32, event_date: Option<NaiveDateTime>) -> Self {
let event_date = match event_date {
Some(d) => d,
None => Utc::now().naive_utc(),
};
let event_date = event_date.unwrap_or_else(|| Utc::now().naive_utc());
Self {
uuid: EventId(crate::util::get_uuid()),
event_type,
@ -230,7 +226,7 @@ impl Event {
}
}
pub async fn save_user_event(events: Vec<Event>, conn: &DbConn) -> EmptyResult {
pub async fn save_user_event(events: Vec<Self>, conn: &DbConn) -> EmptyResult {
// Special save function which is able to handle multiple events.
// SQLite doesn't support the DEFAULT argument, and does not support inserting multiple values at the same time.
// MySQL and PostgreSQL do.

8
src/db/models/group.rs

@ -315,7 +315,7 @@ impl Group {
}
impl CollectionGroup {
pub async fn save(&mut self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
pub async fn save(&self, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
let group_users = GroupUser::find_by_group(&self.groups_uuid, org_uuid, conn).await;
for group_user in group_users {
group_user.update_user_revision(conn).await;
@ -448,7 +448,7 @@ impl CollectionGroup {
org_uuid: &OrganizationId,
conn: &DbConn,
) -> EmptyResult {
let collection_assigned_to_groups = CollectionGroup::find_by_collection(collection_uuid, conn).await;
let collection_assigned_to_groups = Self::find_by_collection(collection_uuid, conn).await;
for collection_assigned_to_group in collection_assigned_to_groups {
let group_users = GroupUser::find_by_group(&collection_assigned_to_group.groups_uuid, org_uuid, conn).await;
for group_user in group_users {
@ -467,7 +467,7 @@ impl CollectionGroup {
}
impl GroupUser {
pub async fn save(&mut self, conn: &DbConn) -> EmptyResult {
pub async fn save(&self, conn: &DbConn) -> EmptyResult {
self.update_user_revision(conn).await;
let values = (
@ -574,7 +574,7 @@ impl GroupUser {
}
pub async fn delete_all_by_group(group_uuid: &GroupId, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
let group_users = GroupUser::find_by_group(group_uuid, org_uuid, conn).await;
let group_users = Self::find_by_group(group_uuid, org_uuid, conn).await;
for group_user in group_users {
group_user.update_user_revision(conn).await;
}

13
src/db/models/org_policy.rs

@ -301,11 +301,9 @@ impl OrgPolicy {
exclude_org_uuid: Option<&OrganizationId>,
conn: &DbConn,
) -> bool {
for policy in
OrgPolicy::find_accepted_and_confirmed_by_user_and_active_policy(user_uuid, policy_type, conn).await
{
for policy in Self::find_accepted_and_confirmed_by_user_and_active_policy(user_uuid, policy_type, conn).await {
// Check if we need to skip this organization.
if exclude_org_uuid.is_some() && *exclude_org_uuid.unwrap() == policy.org_uuid {
if exclude_org_uuid.is_some_and(|u| u == &policy.org_uuid) {
continue;
}
@ -370,7 +368,7 @@ impl OrgPolicy {
return false;
}
match OrgPolicy::find_by_org_and_type(org_uuid, OrgPolicyType::ResetPassword, conn).await {
match Self::find_by_org_and_type(org_uuid, OrgPolicyType::ResetPassword, conn).await {
Some(policy) => match serde_json::from_str::<ResetPasswordDataModel>(&policy.data) {
Ok(opts) => {
return policy.enabled && opts.auto_enroll_enabled;
@ -386,8 +384,7 @@ impl OrgPolicy {
/// Returns true if the user belongs to an org that has enabled the `DisableHideEmail`
/// option of the `Send Options` policy, and the user is not an owner or admin of that org.
pub async fn is_hide_email_disabled(user_uuid: &UserId, conn: &DbConn) -> bool {
for policy in
OrgPolicy::find_confirmed_by_user_and_active_policy(user_uuid, OrgPolicyType::SendOptions, conn).await
for policy in Self::find_confirmed_by_user_and_active_policy(user_uuid, OrgPolicyType::SendOptions, conn).await
{
if let Some(user) = Membership::find_confirmed_by_user_and_org(user_uuid, &policy.org_uuid, conn).await
&& user.atype < MembershipType::Admin
@ -407,7 +404,7 @@ impl OrgPolicy {
pub async fn is_enabled_for_member(member_uuid: &MembershipId, policy_type: OrgPolicyType, conn: &DbConn) -> bool {
if let Some(member) = Membership::find_by_uuid(member_uuid, conn).await
&& let Some(policy) = OrgPolicy::find_by_org_and_type(&member.org_uuid, policy_type, conn).await
&& let Some(policy) = Self::find_by_org_and_type(&member.org_uuid, policy_type, conn).await
{
return policy.enabled;
}

98
src/db/models/organization.rs

@ -134,11 +134,11 @@ pub enum MembershipType {
impl MembershipType {
pub fn from_str(s: &str) -> Option<Self> {
match s {
"0" | "Owner" => Some(MembershipType::Owner),
"1" | "Admin" => Some(MembershipType::Admin),
"2" | "User" => Some(MembershipType::User),
"3" | "Manager" => Some(MembershipType::Manager),
"4" | "Custom" => Some(MembershipType::Custom),
"0" | "Owner" => Some(Self::Owner),
"1" | "Admin" => Some(Self::Admin),
"2" | "User" => Some(Self::User),
"3" | "Manager" => Some(Self::Manager),
"4" | "Custom" => Some(Self::Custom),
_ => None,
}
}
@ -152,23 +152,23 @@ impl MembershipType {
/// keeps their role when the request repeats it, so an unrelated edit never turns one into the other. A
/// Manager only becomes a Custom member when the permissions they are shown with are changed.
pub fn requested(
requested: MembershipType,
requested: Self,
current: Option<&Membership>,
custom_permissions: Option<&HashSet<CustomPermission>>,
) -> MembershipType {
if requested != MembershipType::Custom {
) -> Self {
if requested != Self::Custom {
return requested;
}
match (current, custom_permissions) {
(Some(member), _) if member.has_type(MembershipType::Custom) => MembershipType::Custom,
(Some(member), _) if member.has_type(Self::Custom) => Self::Custom,
(Some(member), Some(permissions))
if member.has_type(MembershipType::Manager) && *permissions != member.legacy_manager_permissions() =>
if member.has_type(Self::Manager) && *permissions != member.legacy_manager_permissions() =>
{
MembershipType::Custom
Self::Custom
}
(Some(member), _) if member.has_type(MembershipType::Manager) => MembershipType::Manager,
(_, Some(_)) => MembershipType::Custom,
(_, None) => MembershipType::Manager,
(Some(member), _) if member.has_type(Self::Manager) => Self::Manager,
(_, Some(_)) => Self::Custom,
(_, None) => Self::Manager,
}
}
@ -176,23 +176,23 @@ impl MembershipType {
/// its permissions, never from its role, so the role itself ranks right above User and below Manager.
const fn rank(self) -> u8 {
match self {
MembershipType::User => 0,
MembershipType::Custom => 1,
MembershipType::Manager => 2,
MembershipType::Admin => 3,
MembershipType::Owner => 4,
Self::User => 0,
Self::Custom => 1,
Self::Manager => 2,
Self::Admin => 3,
Self::Owner => 4,
}
}
}
impl Ord for MembershipType {
fn cmp(&self, other: &MembershipType) -> Ordering {
fn cmp(&self, other: &Self) -> Ordering {
self.rank().cmp(&other.rank())
}
}
impl PartialOrd for MembershipType {
fn partial_cmp(&self, other: &MembershipType) -> Option<Ordering> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
@ -222,7 +222,7 @@ impl PartialOrd<i32> for MembershipType {
impl PartialEq<MembershipType> for i32 {
fn eq(&self, other: &MembershipType) -> bool {
*self == *other as i32
*self == *other as Self
}
}
@ -275,32 +275,32 @@ const SUPPORTED_CUSTOM_PERMISSIONS: &[CustomPermission] = &[
];
impl CustomPermission {
pub const ALL: [CustomPermission; 10] = [
CustomPermission::ManageUsers,
CustomPermission::ManageGroups,
CustomPermission::ManagePolicies,
CustomPermission::CreateNewCollections,
CustomPermission::EditAnyCollection,
CustomPermission::DeleteAnyCollection,
CustomPermission::AccessEventLogs,
CustomPermission::AccessImportExport,
CustomPermission::AccessReports,
CustomPermission::ManageResetPassword,
pub const ALL: [Self; 10] = [
Self::ManageUsers,
Self::ManageGroups,
Self::ManagePolicies,
Self::CreateNewCollections,
Self::EditAnyCollection,
Self::DeleteAnyCollection,
Self::AccessEventLogs,
Self::AccessImportExport,
Self::AccessReports,
Self::ManageResetPassword,
];
/// The key of the permission in the `permissions` object of the Bitwarden clients.
pub const fn json_key(self) -> &'static str {
match self {
CustomPermission::ManageUsers => "manageUsers",
CustomPermission::ManageGroups => "manageGroups",
CustomPermission::ManagePolicies => "managePolicies",
CustomPermission::CreateNewCollections => "createNewCollections",
CustomPermission::EditAnyCollection => "editAnyCollection",
CustomPermission::DeleteAnyCollection => "deleteAnyCollection",
CustomPermission::AccessEventLogs => "accessEventLogs",
CustomPermission::AccessImportExport => "accessImportExport",
CustomPermission::AccessReports => "accessReports",
CustomPermission::ManageResetPassword => "manageResetPassword",
Self::ManageUsers => "manageUsers",
Self::ManageGroups => "manageGroups",
Self::ManagePolicies => "managePolicies",
Self::CreateNewCollections => "createNewCollections",
Self::EditAnyCollection => "editAnyCollection",
Self::DeleteAnyCollection => "deleteAnyCollection",
Self::AccessEventLogs => "accessEventLogs",
Self::AccessImportExport => "accessImportExport",
Self::AccessReports => "accessReports",
Self::ManageResetPassword => "manageResetPassword",
}
}
@ -314,9 +314,9 @@ impl CustomPermission {
/// replaces the member's permissions, so a malformed value must not silently remove one. Granting a
/// permission this version does not enforce is rejected as well. The clients also send permissions
/// Vaultwarden does not know at all, like `manageSso`, those are ignored.
pub fn requested(permissions: &HashMap<String, Value>) -> Result<HashSet<CustomPermission>, Error> {
pub fn requested(permissions: &HashMap<String, Value>) -> Result<HashSet<Self>, Error> {
let mut granted = HashSet::new();
for permission in CustomPermission::ALL {
for permission in Self::ALL {
match permissions.get(permission.json_key()) {
None | Some(Value::Bool(false)) => {}
Some(Value::Bool(true)) if permission.is_supported() => {
@ -581,7 +581,7 @@ impl Membership {
/// Whether this member may act with every Custom role permission stored for `other`, as Bitwarden's
/// `Permissions.Includes`.
pub fn has_custom_permissions_of(&self, other: &Membership) -> bool {
pub fn has_custom_permissions_of(&self, other: &Self) -> bool {
CustomPermission::ALL.into_iter().all(|p| !other.custom_permission(p) || self.has_custom_permission(p))
}
@ -928,7 +928,7 @@ impl Membership {
json!({
"id": self.uuid,
"userId": self.user_uuid,
"name": if self.get_unrevoked_status() >= MembershipStatus::Accepted as i32 { Some(user.name) } else { None },
"name": (self.get_unrevoked_status() >= MembershipStatus::Accepted as i32).then_some(user.name),
"email": user.email,
"externalId": self.external_id,
"avatarColor": user.avatar_color,
@ -1081,9 +1081,9 @@ impl Membership {
Ok(())
}
pub async fn find_by_email_and_org(email: &str, org_uuid: &OrganizationId, conn: &DbConn) -> Option<Membership> {
pub async fn find_by_email_and_org(email: &str, org_uuid: &OrganizationId, conn: &DbConn) -> Option<Self> {
if let Some(user) = User::find_by_mail(email, conn).await
&& let Some(member) = Membership::find_by_user_and_org(&user.uuid, org_uuid, conn).await
&& let Some(member) = Self::find_by_user_and_org(&user.uuid, org_uuid, conn).await
{
return Some(member);
}

16
src/db/models/send.rs

@ -58,9 +58,9 @@ pub enum SendType {
}
enum SendAuthType {
#[allow(dead_code)]
#[expect(unused, reason = "Not yet supported")]
// Send requires email OTP verification
Email = 0, // Not yet supported by Vaultwarden
Email = 0,
// Send requires a password
Password = 1,
// Send requires no auth
@ -145,7 +145,7 @@ impl Send {
}
pub fn to_json(&self) -> Value {
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map(|d| d.data).unwrap_or_default();
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map_or_default(|d| d.data);
// Mobile clients expect size to be a string instead of a number
if let Some(size) = data.get("size").and_then(Value::as_i64) {
@ -159,8 +159,8 @@ impl Send {
"name": self.name,
"notes": self.notes,
"text": if self.atype == SendType::Text as i32 { Some(&data) } else { None },
"file": if self.atype == SendType::File as i32 { Some(&data) } else { None },
"text": (self.atype == SendType::Text as i32).then_some(&data),
"file": (self.atype == SendType::File as i32).then_some(&data),
"key": self.akey,
"maxAccessCount": self.max_access_count,
@ -178,7 +178,7 @@ impl Send {
}
pub async fn to_json_access(&self, conn: &DbConn) -> Value {
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map(|d| d.data).unwrap_or_default();
let mut data = serde_json::from_str::<LowerCase<Value>>(&self.data).map_or_default(|d| d.data);
// Mobile clients expect size to be a string instead of a number
if let Some(size) = data.get("size").and_then(Value::as_i64) {
@ -190,8 +190,8 @@ impl Send {
"type": self.atype,
"name": self.name,
"text": if self.atype == SendType::Text as i32 { Some(&data) } else { None },
"file": if self.atype == SendType::File as i32 { Some(&data) } else { None },
"text": (self.atype == SendType::Text as i32).then_some(&data),
"file": (self.atype == SendType::File as i32).then_some(&data),
"expirationDate": self.expiration_date.as_ref().map(format_date),
"creatorIdentifier": self.creator_identifier(conn).await,

2
src/db/models/sso_auth.rs

@ -67,7 +67,7 @@ impl SsoAuth {
) -> Self {
let now = Utc::now().naive_utc();
SsoAuth {
Self {
state,
client_challenge,
nonce,

4
src/db/models/two_factor.rs

@ -227,7 +227,7 @@ impl TwoFactor {
u2f.data = serde_json::to_string(&regs)?;
u2f.save(conn).await?;
TwoFactor::new(u2f.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(&webauthn_regs)?)
Self::new(u2f.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(&webauthn_regs)?)
.save(conn)
.await?;
}
@ -254,7 +254,7 @@ impl TwoFactor {
let regs = regs.into_iter().map(Into::into).collect::<Vec<WebauthnRegistration>>();
TwoFactor::new(webauthn_factor.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(&regs)?)
Self::new(webauthn_factor.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(&regs)?)
.save(conn)
.await?;
}

12
src/db/models/user.rs

@ -147,7 +147,7 @@ impl User {
verified_at: None,
last_verifying_at: None,
login_verify_count: 0,
name: name.unwrap_or(email.clone()),
name: name.unwrap_or_else(|| email.clone()),
email,
akey: String::new(),
email_new: None,
@ -222,15 +222,11 @@ impl User {
}
pub fn check_valid_recovery_code(&self, recovery_code: &str) -> bool {
if let Some(ref totp_recover) = self.totp_recover {
crypto::ct_eq(recovery_code, totp_recover.to_lowercase())
} else {
false
}
self.totp_recover.as_ref().is_some_and(|c| crypto::ct_eq(recovery_code, c.to_lowercase()))
}
pub fn check_valid_api_key(&self, key: &str) -> bool {
matches!(self.api_key, Some(ref api_key) if crypto::ct_eq(api_key, key))
self.api_key.as_ref().is_some_and(|k| crypto::ct_eq(key, k))
}
/// Set the password hash generated
@ -290,7 +286,7 @@ impl User {
grace.push(UserStampException {
routes: None,
security_stamp: previous_stamp,
expire: (Utc::now() + *DEFAULT_ACCESS_VALIDITY).timestamp(),
expire: (Utc::now() + DEFAULT_ACCESS_VALIDITY).timestamp(),
});
let mut exceptions = self.stamp_exceptions();
exceptions.extend(grace);

30
src/http_client.rs

@ -161,13 +161,9 @@ pub fn should_block_host<S: AsRef<str>>(host: &Host<S>) -> Result<(), CustomHttp
});
}
if should_block_address_regex(&host_str) {
return Err(CustomHttpClientError::Blocked {
domain: host_str,
});
}
Ok(())
(!should_block_address_regex(&host_str)).ok_or(CustomHttpClientError::Blocked {
domain: host_str,
})
}
#[derive(Debug, Clone)]
@ -211,7 +207,7 @@ impl CustomHttpClientError {
while let Some(err) = source {
source = err.source();
if let Some(err) = err.downcast_ref::<CustomHttpClientError>() {
if let Some(err) = err.downcast_ref::<Self>() {
return Some(err);
}
}
@ -258,7 +254,7 @@ impl CustomDns {
fn instance(enforce_block: bool) -> Self {
static INSTANCE: LazyLock<Arc<CustomDnsResolver>> = LazyLock::new(CustomDnsResolver::new);
CustomDns {
Self {
enforce_block,
resolver: Arc::clone(&*INSTANCE),
}
@ -409,7 +405,7 @@ pub(crate) mod aws {
Ok(HttpResponse::new(status, bytes.into()))
};
HttpConnectorFuture::new(Box::pin(future))
HttpConnectorFuture::new(future)
}
}
@ -419,7 +415,7 @@ pub(crate) mod aws {
_settings: &HttpConnectorSettings,
_components: &RuntimeComponents,
) -> SharedHttpConnector {
SharedHttpConnector::new(AwsReqwestConnector {
SharedHttpConnector::new(Self {
client: self.client.clone(),
})
}
@ -430,8 +426,10 @@ pub(crate) mod aws {
mod tests {
use super::*;
use crate::util::is_global_hardcoded;
use std::net::{Ipv4Addr, Ipv6Addr};
use url::Host;
use std::{
assert_matches,
net::{Ipv4Addr, Ipv6Addr},
};
// ===
// IPv4 numeric-format normalization
@ -535,19 +533,19 @@ mod tests {
#[test]
fn get_valid_host_normalizes_decimal_int() {
let h = get_valid_host("2130706433").expect("valid");
assert!(matches!(h, Host::Ipv4(ip) if ip == Ipv4Addr::LOCALHOST));
assert_matches!(h, Host::Ipv4(ip) if ip == Ipv4Addr::LOCALHOST);
}
#[test]
fn get_valid_host_normalizes_hex() {
let h = get_valid_host("0x7f000001").expect("valid");
assert!(matches!(h, Host::Ipv4(ip) if ip == Ipv4Addr::LOCALHOST));
assert_matches!(h, Host::Ipv4(ip) if ip == Ipv4Addr::LOCALHOST);
}
#[test]
fn get_valid_host_normalizes_octal() {
let h = get_valid_host("017700000001").expect("valid");
assert!(matches!(h, Host::Ipv4(ip) if ip == Ipv4Addr::LOCALHOST));
assert_matches!(h, Host::Ipv4(ip) if ip == Ipv4Addr::LOCALHOST);
}
// ===

21
src/mail.rs

@ -74,8 +74,8 @@ fn smtp_transport() -> AsyncSmtpTransport<Tokio1Executor> {
let mut selected_mechanisms = vec![];
for wanted_mechanism in mechanism.split(',') {
for m in &allowed_mechanisms {
if m.to_string().to_lowercase()
== wanted_mechanism.trim_matches(|c| c == '"' || c == '\'' || c == ' ').to_lowercase()
if m.to_string()
.eq_ignore_ascii_case(wanted_mechanism.trim_matches(|c| c == '"' || c == '\'' || c == ' '))
{
selected_mechanisms.push(*m);
}
@ -127,26 +127,17 @@ fn get_text(template_name: &'static str, data: serde_json::Value) -> Result<(Str
}
fn get_template(template_name: &str, data: &serde_json::Value) -> Result<(String, String), Error> {
const DELIMITER: &str = "<!---------------->";
let text = CONFIG.render_template(template_name, data)?;
let mut text_split = text.split("<!---------------->");
let subject = if let Some(s) = text_split.next() {
s.trim().to_owned()
} else {
err!("Template doesn't contain subject")
};
let body = if let Some(s) = text_split.next() {
s.trim().to_owned()
} else {
let Some((subject, body)) = text.split_once(DELIMITER) else {
err!("Template doesn't contain body")
};
if text_split.next().is_some() {
if body.contains(DELIMITER) {
err!("Template contains more than one body");
}
Ok((subject, body))
Ok((subject.trim().to_owned(), body.trim().to_owned()))
}
pub async fn send_password_hint(address: &str, hint: Option<String>) -> EmptyResult {

15
src/main.rs

@ -243,7 +243,7 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
let level = caps
.get(1)
.and_then(|m| log::LevelFilter::from_str(m.as_str()).ok())
.ok_or(Error::new("Failed to parse global log level".to_owned(), ""))?;
.ok_or_else(|| Error::new("Failed to parse global log level".to_owned(), ""))?;
let levels_override: Vec<(&str, log::LevelFilter)> = caps
.get(2)
@ -258,7 +258,7 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
})
.collect()
})
.ok_or(Error::new("Failed to parse overrides".to_owned(), ""))?;
.ok_or_else(|| Error::new("Failed to parse overrides".to_owned(), ""))?;
(level, levels_override)
} else {
@ -394,14 +394,7 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
let thread = thread::current();
let thread = thread.name().unwrap_or("unnamed");
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match info.payload().downcast_ref::<String>() {
Some(s) => &**s,
None => "Box<Any>",
},
};
let msg = info.payload_as_str().unwrap_or("Box<Any>");
let backtrace = std::backtrace::Backtrace::force_capture();
match info.location() {
@ -764,7 +757,7 @@ fn schedule_jobs(pool: db::DbPool) {
// tick, the one that was added earlier will run first.
loop {
sched.tick();
runtime.block_on(tokio::time::sleep(tokio::time::Duration::from_millis(u64::from(
runtime.block_on(tokio::time::sleep(std::time::Duration::from_millis(u64::from(
CONFIG.job_poll_interval_ms(),
))));
}

12
src/sso.rs

@ -236,7 +236,7 @@ pub struct OIDCIdentifier(String);
impl OIDCIdentifier {
fn new(issuer: &str, subject: &str) -> Self {
OIDCIdentifier(format!("{issuer}/{subject}"))
Self(format!("{issuer}/{subject}"))
}
}
@ -283,14 +283,14 @@ pub async fn exchange_code(
let user_info = client.user_info(token_response.access_token().to_owned()).await?;
let email = match id_claims.email().or(user_info.email()) {
let email = match id_claims.email().or_else(|| user_info.email()) {
None => err!("Neither id token nor userinfo contained an email"),
Some(e) => e.to_string().to_lowercase(),
};
let email_verified = id_claims.email_verified().or(user_info.email_verified());
let email_verified = id_claims.email_verified().or_else(|| user_info.email_verified());
let user_name = id_claims.preferred_username().or(user_info.preferred_username()).map(|un| un.to_string());
let user_name = id_claims.preferred_username().or_else(|| user_info.preferred_username()).map(|un| un.to_string());
let refresh_token = token_response.refresh_token().map(openidconnect::RefreshToken::secret);
if refresh_token.is_none() && CONFIG.sso_scopes_vec().contains(&"offline_access".to_owned()) {
@ -398,7 +398,7 @@ fn create_auth_tokens_impl(
match decode_token_claims("refresh_token", &rt) {
Err(_) => {
let time_now = Utc::now();
let exp = (time_now + *DEFAULT_REFRESH_VALIDITY).timestamp();
let exp = (time_now + DEFAULT_REFRESH_VALIDITY).timestamp();
debug!("Non jwt refresh_token (expiration set to {exp})");
(time_now.timestamp(), exp, TokenWrapper::Refresh(rt))
}
@ -454,7 +454,7 @@ pub async fn exchange_refresh_token(
}
Some(TokenWrapper::Access(access_token)) => {
let now = Utc::now();
let exp_limit = (now + *BW_EXPIRATION).timestamp();
let exp_limit = (now + BW_EXPIRATION).timestamp();
if exp < exp_limit {
err_silent!("Access token is close to expiration but we have no refresh token")

20
src/sso_client.rs

@ -1,4 +1,4 @@
use std::{borrow::Cow, collections::HashSet, future::Future, pin::Pin, sync::LazyLock, time::Duration};
use std::{borrow::Cow, collections::HashSet, pin::Pin, sync::LazyLock, time::Duration};
use openidconnect::{
AccessToken, AsyncHttpClient, AuthDisplay, AuthPrompt, AuthType, AuthenticationFlow, AuthorizationCode,
@ -12,7 +12,7 @@ use openidconnect::{
CoreProviderMetadata, CoreResponseType, CoreRevocableToken, CoreRevocationErrorResponse,
CoreTokenIntrospectionResponse, CoreTokenResponse, CoreTokenType, CoreUserInfoClaims,
},
http, url,
http,
};
use regex::Regex;
use url::Url;
@ -25,8 +25,8 @@ use crate::{
sso::{OIDCCode, OIDCCodeChallenge, OIDCCodeVerifier, OIDCState},
};
static CLIENT_CACHE_KEY: LazyLock<String> = LazyLock::new(|| "sso-client".to_owned());
static CLIENT_CACHE: LazyLock<moka::sync::Cache<String, Client>> = LazyLock::new(|| {
const CLIENT_CACHE_KEY: &str = "sso-client";
static CLIENT_CACHE: LazyLock<moka::sync::Cache<&'static str, Client>> = LazyLock::new(|| {
moka::sync::Cache::builder()
.max_capacity(1)
.time_to_live(Duration::from_secs(u64::from(CONFIG.sso_client_cache_expiration())))
@ -154,7 +154,7 @@ impl Client {
.set_token_uri(token_uri)
.set_user_info_url(user_info_url);
Ok(Client {
Ok(Self {
http_client,
core_client,
})
@ -163,11 +163,11 @@ impl Client {
// Simple cache to prevent recalling the discovery endpoint each time
pub async fn cached() -> ApiResult<Self> {
if CONFIG.sso_client_cache_expiration() > 0 {
match CLIENT_CACHE.get(&*CLIENT_CACHE_KEY) {
match CLIENT_CACHE.get(CLIENT_CACHE_KEY) {
Some(client) => Ok(client),
None => Self::get_client().await.inspect(|client| {
debug!("Inserting new client in cache");
CLIENT_CACHE.insert(CLIENT_CACHE_KEY.clone(), client.clone());
CLIENT_CACHE.insert(CLIENT_CACHE_KEY, client.clone());
}),
}
} else {
@ -177,7 +177,7 @@ impl Client {
pub fn invalidate() {
if CONFIG.sso_client_cache_expiration() > 0 {
CLIENT_CACHE.invalidate(&*CLIENT_CACHE_KEY);
CLIENT_CACHE.invalidate(CLIENT_CACHE_KEY);
}
}
@ -287,7 +287,7 @@ impl Client {
}
pub async fn check_validity(access_token: String) -> EmptyResult {
let client = Client::cached().await?;
let client = Self::cached().await?;
match client.user_info(AccessToken::new(access_token)).await {
Err(err) => {
err_silent!(format!("Failed to retrieve user info, token has probably been invalidated: {err}"))
@ -312,7 +312,7 @@ impl Client {
}
pub async fn exchange_refresh_token(refresh_token: String) -> ApiResult<RefreshTokenResponse> {
let client = Client::cached().await?;
let client = Self::cached().await?;
REFRESH_CACHE
.get_with(refresh_token.clone(), async move { client.exchange_refresh_token_impl(refresh_token).await })

3
src/storage.rs

@ -147,8 +147,7 @@ mod s3 {
fn path_segments(url: &Url) -> Vec<String> {
url.path_segments()
.map(|segments| segments.filter(|segment| !segment.is_empty()).map(str::to_owned).collect())
.unwrap_or_default()
.map_or_default(|segments| segments.filter(|segment| !segment.is_empty()).map(str::to_owned).collect())
}
fn set_path_segments(url: &mut Url, segments: &[String]) {

145
src/util.rs

@ -151,16 +151,13 @@ pub struct Cors();
impl Cors {
fn get_header(headers: &HeaderMap<'_>, name: &str) -> String {
match headers.get_one(name) {
Some(h) => h.to_owned(),
_ => String::new(),
}
headers.get_one(name).map_or_default(ToOwned::to_owned)
}
// 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<String> {
let origin = Cors::get_header(headers, "Origin");
let origin = Self::get_header(headers, "Origin");
let safari_extension_origin = "file://";
let desktop_custom_file_origin = "bw-desktop-file://bundle";
@ -188,14 +185,14 @@ impl Fairing for Cors {
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
let req_headers = request.headers();
if let Some(origin) = Cors::get_allowed_origin(req_headers) {
if let Some(origin) = Self::get_allowed_origin(req_headers) {
response.set_header(Header::new("Access-Control-Allow-Origin", origin));
}
// Preflight request
if request.method() == Method::Options {
let req_allow_headers = Cors::get_header(req_headers, "Access-Control-Request-Headers");
let req_allow_method = Cors::get_header(req_headers, "Access-Control-Request-Method");
let req_allow_headers = Self::get_header(req_headers, "Access-Control-Request-Headers");
let req_allow_method = Self::get_header(req_headers, "Access-Control-Request-Method");
response.set_header(Header::new("Access-Control-Allow-Methods", req_allow_method));
response.set_header(Header::new("Access-Control-Allow-Headers", req_allow_headers));
@ -214,7 +211,7 @@ pub struct Cached<R> {
}
impl<R> Cached<R> {
pub fn long(response: R, is_immutable: bool) -> Cached<R> {
pub fn long(response: R, is_immutable: bool) -> Self {
Self {
response,
is_immutable,
@ -222,7 +219,7 @@ impl<R> Cached<R> {
}
}
pub fn short(response: R, is_immutable: bool) -> Cached<R> {
pub fn short(response: R, is_immutable: bool) -> Self {
Self {
response,
is_immutable,
@ -230,7 +227,7 @@ impl<R> Cached<R> {
}
}
pub fn ttl(response: R, ttl: u32, is_immutable: bool) -> Cached<R> {
pub fn ttl(response: R, ttl: u32, is_immutable: bool) -> Self {
Self {
response,
is_immutable,
@ -447,19 +444,19 @@ pub fn get_uuid() -> String {
#[inline]
pub fn upcase_first(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
c.next().map_or_default(|f| f.to_uppercase().collect::<String>() + c.as_str())
}
#[inline]
pub fn lcase_first(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),
pub fn lcase_first(mut s: String) -> String {
// get_mut(0..1) is None if empty or if the first char is multi-byte
if let Some(first) = s.get_mut(0..1) {
first.make_ascii_lowercase();
} else if let Some(c) = s.chars().next() {
let lc: String = c.to_lowercase().collect();
s.replace_range(..c.len_utf8(), &lc);
}
s
}
pub fn try_parse_string<S, T>(string: Option<S>) -> Option<T>
@ -467,11 +464,7 @@ where
S: AsRef<str>,
T: FromStr,
{
if let Some(Ok(value)) = string.map(|s| s.as_ref().parse::<T>()) {
Some(value)
} else {
None
}
string.and_then(|s| s.as_ref().parse::<T>().ok())
}
//
@ -513,15 +506,15 @@ pub fn get_env_bool(key: &'static str) -> Option<bool> {
const TRUE_VALUES: &[&str] = &["true", "t", "yes", "y", "1"];
const FALSE_VALUES: &[&str] = &["false", "f", "no", "n", "0"];
match get_env_str_value(key) {
Some(val) if TRUE_VALUES.contains(&val.to_lowercase().as_ref()) => Some(true),
Some(val) if FALSE_VALUES.contains(&val.to_lowercase().as_ref()) => Some(false),
Some(_) => {
println!("[ERROR] `{key}` contains an invalid boolean value and is ignored, the default is used instead.");
INVALID_ENV_VARS.lock().unwrap().push(key);
None
}
_ => None,
let val = get_env_str_value(key)?;
if TRUE_VALUES.iter().any(|v| val.eq_ignore_ascii_case(v)) {
Some(true)
} else if FALSE_VALUES.iter().any(|v| val.eq_ignore_ascii_case(v)) {
Some(false)
} else {
println!("[ERROR] `{key}` contains an invalid boolean value and is ignored, the default is used instead.");
INVALID_ENV_VARS.lock().unwrap().push(key);
None
}
}
@ -715,10 +708,12 @@ impl<'de> Visitor<'de> for LowerCaseVisitor {
// Inner function to handle a special case for the 'ssn' key.
// This key is part of the Identity Cipher (Social Security Number)
fn process_json_key(key: &str) -> String {
match key.to_lowercase().as_ref() {
"ssn" => "ssn".into(),
_ => lcase_first(key),
fn process_json_key(mut key: String) -> String {
if key.eq_ignore_ascii_case("ssn") {
key.make_ascii_lowercase();
key
} else {
lcase_first(key)
}
}
@ -747,8 +742,8 @@ pub enum NumberOrString {
impl NumberOrString {
pub fn into_string(self) -> String {
match self {
NumberOrString::Number(n) => n.to_string(),
NumberOrString::String(s) => s,
Self::Number(n) => n.to_string(),
Self::String(s) => s,
}
}
@ -756,16 +751,14 @@ impl NumberOrString {
pub fn into_i32(&self) -> Result<i32, crate::Error> {
use std::num::ParseIntError as PIE;
match self {
NumberOrString::Number(n) => {
if let Some(n) = n.to_i32() {
Self::Number(n) => {
if let Ok(n) = i32::try_from(*n) {
Ok(n)
} else {
err!("Number does not fit in i32")
}
}
NumberOrString::String(s) => {
s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string()))
}
Self::String(s) => s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string())),
}
}
@ -773,10 +766,8 @@ impl NumberOrString {
pub fn into_i64(&self) -> Result<i64, crate::Error> {
use std::num::ParseIntError as PIE;
match self {
NumberOrString::Number(n) => Ok(*n),
NumberOrString::String(s) => {
s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string()))
}
Self::Number(n) => Ok(*n),
Self::String(s) => s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string())),
}
}
}
@ -833,50 +824,25 @@ where
pub fn convert_json_key_lcase_first(src_json: Value) -> Value {
match src_json {
Value::Array(elm) => {
let mut new_array: Vec<Value> = Vec::with_capacity(elm.len());
for obj in elm {
new_array.push(convert_json_key_lcase_first(obj));
Value::Array(mut elm) => {
for obj in &mut elm {
*obj = convert_json_key_lcase_first(obj.take());
}
Value::Array(new_array)
Value::Array(elm)
}
Value::Object(obj) => {
let mut json_map = JsonMap::new();
for (key, value) in obj {
match (key, value) {
(key, Value::Object(elm)) => {
let inner_value = convert_json_key_lcase_first(Value::Object(elm));
json_map.insert(process_json_key(&key), inner_value);
}
(key, Value::Array(elm)) => {
let mut inner_array: Vec<Value> = Vec::with_capacity(elm.len());
for inner_obj in elm {
inner_array.push(convert_json_key_lcase_first(inner_obj));
}
json_map.insert(process_json_key(&key), Value::Array(inner_array));
}
(key, value) => {
json_map.insert(process_json_key(&key), value);
}
}
json_map.insert(process_json_key(key), convert_json_key_lcase_first(value));
}
Value::Object(json_map)
}
value => value,
}
}
pub enum FeatureFlagFilter {
#[allow(dead_code)]
Unfiltered,
ValidOnly,
InvalidOnly,
}
@ -891,7 +857,6 @@ pub fn parse_experimental_client_feature_flags(
.map(str::trim)
.filter(|flag| !flag.is_empty())
.filter(|flag| match filter_mode {
FeatureFlagFilter::Unfiltered => true,
FeatureFlagFilter::ValidOnly => SUPPORTED_FEATURE_FLAGS.contains(flag),
FeatureFlagFilter::InvalidOnly => !SUPPORTED_FEATURE_FLAGS.contains(flag),
})
@ -911,9 +876,9 @@ pub fn is_client_feature_flag_enabled(flag: &str) -> bool {
// #[expect(clippy::nonminimal_bool, reason = "Mostly copy/paste from std, keep as-is")]
#[expect(clippy::decimal_bitwise_operands, reason = "Mostly copy/paste from std, keep as-is")]
#[cfg(any(not(feature = "unstable"), test))]
pub fn is_global_hardcoded(ip: std::net::IpAddr) -> bool {
pub fn is_global_hardcoded(ip: core::net::IpAddr) -> bool {
match ip {
std::net::IpAddr::V4(ip) => {
core::net::IpAddr::V4(ip) => {
!(ip.octets()[0] == 0 // "This network"
|| ip.is_private()
|| (ip.octets()[0] == 100 && (ip.octets()[1] & 0b1100_0000 == 0b0100_0000)) // ip.is_shared()
@ -925,12 +890,14 @@ pub fn is_global_hardcoded(ip: std::net::IpAddr) -> bool {
ip.octets()[0] == 192 && ip.octets()[1] == 0 && ip.octets()[2] == 0
&& ip.octets()[3] != 9 && ip.octets()[3] != 10
)
// 6a44-relay anycast address (`192.88.99.2/32`)
|| matches!(ip.octets(), [192, 88, 99, 2])
|| ip.is_documentation()
|| (ip.octets()[0] == 198 && (ip.octets()[1] & 0xfe) == 18) // ip.is_benchmarking()
|| (ip.octets()[0] & 240 == 240 && !ip.is_broadcast()) // ip.is_reserved()
|| ip.is_broadcast())
}
std::net::IpAddr::V6(ip) => {
core::net::IpAddr::V6(ip) => {
!(ip.is_unspecified()
|| ip.is_loopback()
// IPv4-mapped Address (`::ffff:0:0/96`)
@ -939,6 +906,8 @@ pub fn is_global_hardcoded(ip: std::net::IpAddr) -> bool {
|| matches!(ip.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
// Discard-Only Address Block (`100::/64`)
|| matches!(ip.segments(), [0x100, 0, 0, 0, _, _, _, _])
// Dummy IPv6 Prefix (100:0:0:1::/64)
|| matches!(ip.segments(), [0x100, 0, 0, 1, _, _, _, _])
// IETF Protocol Assignments (`2001::/23`)
|| (matches!(ip.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
&& !(
@ -946,6 +915,8 @@ pub fn is_global_hardcoded(ip: std::net::IpAddr) -> bool {
u128::from_be_bytes(ip.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
// Traversal Using Relays around NAT Anycast (`2001:1::2`)
|| u128::from_be_bytes(ip.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
// DNS-SD Service Registration Protocol Anycast (`2001:1::3`)
|| u128::from_be_bytes(ip.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0003
// AMT (`2001:3::/32`)
|| matches!(ip.segments(), [0x2001, 3, _, _, _, _, _, _])
// AS112-v6 (`2001:4:112::/48`)
@ -1027,11 +998,11 @@ mod tests {
#[test]
#[ignore = "exhaustive IPv4 check is too slow for the regular test suite"]
fn test_ipv4_global() {
for a in 0..u8::MAX {
for a in 0..=u8::MAX {
println!("Iter: {a}/255");
for b in 0..u8::MAX {
for c in 0..u8::MAX {
for d in 0..u8::MAX {
for b in 0..=u8::MAX {
for c in 0..=u8::MAX {
for d in 0..=u8::MAX {
let ip = IpAddr::V4(std::net::Ipv4Addr::new(a, b, c, d));
assert_eq!(ip.is_global(), is_global_hardcoded(ip), "IP mismatch: {ip}");
}

Loading…
Cancel
Save