Modernize Rust code and Fixes (#7971)

* Modernize Rust code and fix input handling

- Adopt newer std APIs, reduce allocations, and consolidate caching on Moka.
- Update the Rust toolchain and most dependencies, tighten lints, and expand test coverage.
- Fix favicon ranking for URLs with query strings or fragments, and try the next icon when SVG sanitization fails.
- Prevent panics when masking 2FA email addresses containing Unicode or missing an @.
- Prevent panics on Unicode database paths and recognize short postgres: URLs.
- Treat whitespace-only collection and member external IDs as absent and avoid redundant membership updates.
- Align stable builds’ global IP classification with Rust’s standard library.

Signed-off-by: BlackDex <black.dex@gmail.com>

* Update crates and some fixes

- Bump Rocket, rocket_ws, Diesel, SQLite bindings, and html5gum.
- Reuse WebSocket payload buffers and detect upgrades from the response.
- Match favicon rel tokens case-insensitively, honor the first base href,
  and stop scanning at the end of the head or the start of the body.

Signed-off-by: BlackDex <black.dex@gmail.com>

---------

Signed-off-by: BlackDex <black.dex@gmail.com>
This commit is contained in:
Mathijs van Veluw authored and GitHub committed 2026-11-18 22:33:23 +01:00
1 parent 4051a4d3a6
commit 4a0acc3314
51 files changed
+1156 -1506

No files matched your search

+2 -2
View File
@@ -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
Generated
+352 -624
View File
File diff suppressed because it is too large. Load diff
+35 -26
View File
@@ -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"
@@ -83,8 +82,8 @@ num-derive = "0.5.1"
bigdecimal = "0.4.11"
# Web framework
rocket = { version = "0.5.2", default-features = false, features = ["json", "tls"] }
rocket_ws = { version = "0.1.1" }
rocket = { version = "0.5.3", default-features = false, features = ["json", "tls"] }
rocket_ws = { version = "0.2.0" }
# WebSockets libraries
rmpv = "1.3.1" # MessagePack library
@@ -110,8 +109,8 @@ serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
# A safe, extensible ORM and Query builder
diesel = { version = "2.3.14", features = ["chrono", "r2d2", "numeric", "64-column-tables"] }
diesel_migrations = "2.3.2"
diesel = { version = "2.4.0", features = ["chrono", "r2d2", "numeric", "64-column-tables"] }
diesel_migrations = "2.4.0"
derive_more = { version = "2.1.1", features = [
"as_ref",
@@ -123,21 +122,20 @@ derive_more = { version = "2.1.1", features = [
diesel-derive-newtype = "2.1.3"
# SQLite, statically bundled unless the `sqlite_system` feature is enabled
libsqlite3-sys = { version = "0.38.2", optional = true }
libsqlite3-sys = { version = "0.40.0", 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.3", 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"
@@ -166,7 +164,7 @@ serde_cbor_2 = { version = "0.13.0", optional = true }
url = "2.5.8"
# Email libraries
lettre = { version = "0.11.23", default-features = false, features = [
lettre = { version = "0.11.24", default-features = false, features = [
# Misc
"tracing",
"serde",
@@ -181,7 +179,7 @@ lettre = { version = "0.11.23", default-features = false, features = [
"sendmail-transport",
] }
percent-encoding = "2.3.2" # URL encoding library used for URL's in the emails
email_address = "0.2.9"
email_address = "0.2.10"
# HTML Template library
handlebars = { version = "6.4.4", features = ["dir_source"] }
@@ -208,25 +206,22 @@ reqwest = { version = "0.13.5", default-features = false, features = [
hickory-resolver = "0.26.3"
# Favicon extraction libraries
html5gum = "0.9.0"
regex = { version = "1.13.1", default-features = false, features = [
html5gum = "0.9.2"
regex = { version = "1.13.2", default-features = false, features = [
"perf",
"std",
"unicode-perl",
] }
data-url = "0.3.2"
bytes = "1.12.1"
bytes = "1.12.2"
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.3", 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.22.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
View File
@@ -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");
+4 -4
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -14,7 +14,7 @@ proc-macro = true
[dependencies]
quote = "1.0.47"
syn = "3.0.9"
syn = "3.0.10"
[lints]
workspace = true
+1 -1
View File
@@ -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(())
+1 -1
View File
@@ -1,4 +1,4 @@
[toolchain]
channel = "1.99.1"
channel = "1.100.0"
components = [ "rustfmt", "clippy" ]
profile = "minimal"
+29 -21
View File
@@ -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,28 +677,33 @@ 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) {
// 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")
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 {
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
@@ -707,7 +712,9 @@ async fn get_release_info(has_http_access: bool) -> (String, String, String) {
},
// 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")
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(),
@@ -717,6 +724,8 @@ async fn get_release_info(has_http_access: bool) -> (String, String, String) {
} else {
("-".to_owned(), "-".to_owned(), "-".to_owned())
}
})
.await
}
async fn get_ntp_time(has_http_access: bool) -> String {
@@ -917,8 +926,7 @@ impl<'r> FromRequest<'r> for AdminToken {
let access_token = if let Some(cookie) = cookies.get(COOKIE_NAME) {
cookie.value()
} else {
let requested_page =
request.segments::<std::path::PathBuf>(0..).unwrap_or_default().display().to_string();
let requested_page = request.segments::<std::path::PathBuf>(0..).unwrap_or_default();
// When the requested page is empty, it is `/admin`, in that case, Forward, so it will render the login page
// Else, return a 401 failure, which will be caught
if requested_page.is_empty() {
+15 -22
View File
@@ -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(),
}
}
@@ -299,7 +299,7 @@ impl AccountKeysData {
}
if let Some(security_state) = &self.security_state {
required(Some(security_state.security_state.clone()), "SecurityState")?;
if security_state.security_state.encode_utf16().count() > 10_000 {
if security_state.security_state.encode_utf16().nth(10_000).is_some() {
err!("The field SecurityState must be a string with a maximum length of 10000.")
}
}
@@ -709,7 +709,7 @@ async fn post_set_password(data: Json<Value>, headers: Headers, conn: DbConn) ->
let Ok(data) = serde_json::from_value::<SetPasswordData>(data) else {
err_code!("Unexpected SetPasswordData format", Status::UnprocessableEntity.code)
};
if data.master_password_hint.as_ref().is_some_and(|h| h.encode_utf16().count() > 50) {
if data.master_password_hint.as_ref().is_some_and(|h| h.encode_utf16().nth(50).is_some()) {
err!("The field MasterPasswordHint must be a string with a maximum length of 50.")
}
let mut user = headers.user;
@@ -1373,7 +1373,6 @@ fn validate_rotation_data(
existing_sends: &[Send],
) -> EmptyResult {
// Check that we're correctly rotating all the user's ciphers
let existing_cipher_ids = existing_ciphers.iter().map(|c| &c.uuid).collect::<HashSet<&CipherId>>();
let provided_cipher_ids = data
.account_data
.ciphers
@@ -1381,44 +1380,38 @@ fn validate_rotation_data(
.filter(|c| c.organization_id.is_none())
.filter_map(|c| c.id.as_ref())
.collect::<HashSet<&CipherId>>();
if !provided_cipher_ids.is_superset(&existing_cipher_ids) {
if existing_ciphers.iter().any(|c| !provided_cipher_ids.contains(&c.uuid)) {
err!("All existing ciphers must be included in the rotation")
}
// Check that we're correctly rotating all the user's folders
let existing_folder_ids = existing_folders.iter().map(|f| &f.uuid).collect::<HashSet<&FolderId>>();
let provided_folder_ids =
data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
if !provided_folder_ids.is_superset(&existing_folder_ids) {
if existing_folders.iter().any(|f| !provided_folder_ids.contains(&f.uuid)) {
err!("All existing folders must be included in the rotation")
}
// Check that we're correctly rotating all the user's emergency access keys
let existing_emergency_access_ids =
existing_emergency_access.iter().map(|ea| &ea.uuid).collect::<HashSet<&EmergencyAccessId>>();
let provided_emergency_access_ids =
data.unlock_data.emergency_access_unlock_data.iter().map(|ea| &ea.id).collect::<HashSet<&EmergencyAccessId>>();
if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) {
if existing_emergency_access.iter().any(|ea| !provided_emergency_access_ids.contains(&ea.uuid)) {
err!("All existing emergency access keys must be included in the rotation")
}
// Check that we're correctly rotating all the user's reset password keys
let existing_reset_password_ids =
existing_memberships.iter().map(|m| &m.org_uuid).collect::<HashSet<&OrganizationId>>();
let provided_reset_password_ids = data
.unlock_data
.organization_account_recovery_unlock_data
.iter()
.map(|rp| &rp.organization_id)
.collect::<HashSet<&OrganizationId>>();
if !provided_reset_password_ids.is_superset(&existing_reset_password_ids) {
if existing_memberships.iter().any(|m| !provided_reset_password_ids.contains(&m.org_uuid)) {
err!("All existing reset password keys must be included in the rotation")
}
// Check that we're correctly rotating all the user's sends
let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>();
let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
if !provided_send_ids.is_superset(&existing_send_ids) {
if existing_sends.iter().any(|s| !provided_send_ids.contains(&s.uuid)) {
err!("All existing sends must be included in the rotation")
}
@@ -1503,7 +1496,7 @@ struct RotateData {
/// Upstream's `[StringLength(max)]`, which counts UTF-16 code units.
fn validate_max_length(value: &str, max: usize, field: &str) -> EmptyResult {
if value.encode_utf16().count() > max {
if value.encode_utf16().nth(max).is_some() {
err!(format!("The field {field} must be a string with a maximum length of {max}."))
}
Ok(())
@@ -1544,7 +1537,7 @@ impl MasterPasswordUnlockData {
if let Some(hint) = &self.master_password_hint {
validate_max_length(hint, 50, "MasterPasswordHint")?;
}
if self.master_password_salt.as_ref().is_some_and(|salt| salt.encode_utf16().count() > 256) {
if self.master_password_salt.as_ref().is_some_and(|salt| salt.encode_utf16().nth(256).is_some()) {
err!("The field MasterPasswordSalt must be a string or array type with a maximum length of '256'.")
}
Ok(())
@@ -2194,7 +2187,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 +2364,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,
})
+10 -18
View File
@@ -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 {
@@ -1382,7 +1378,7 @@ async fn put_cipher_share_selected(
if data.ciphers.iter().any(|c| c.id.is_none() || c.organization_id.is_none()) {
err!("All Ciphers must have an Id and OrganizationId.")
}
if data.ciphers.iter().map(|c| &c.organization_id).collect::<HashSet<_>>().len() != 1 {
if data.ciphers.array_windows::<2>().any(|[a, b]| a.organization_id != b.organization_id) {
err!("All ciphers must be for the same organization.")
}
if data.collection_ids.is_empty() {
@@ -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 {
@@ -1791,7 +1787,7 @@ async fn save_attachment(
err!("Invalid attachment size min")
};
if min_size <= size && size <= max_size {
if (min_size..=max_size).contains(&size) {
if size != attachment.file_size {
// Update the attachment with the actual file size.
attachment.file_size = size;
@@ -1799,7 +1795,6 @@ async fn save_attachment(
}
} else {
attachment.delete(&conn).await.ok();
err!(format!("Attachment size mismatch (expected within [{min_size}, {max_size}], got {size})"));
}
} else {
@@ -2844,10 +2839,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;
+2 -3
View File
@@ -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
}
@@ -911,7 +910,7 @@ pub async fn emergency_notification_reminder_job(pool: DbPool) {
};
// Only send reminders during the last 24 hours, else continue
if now < final_reminder_at || now >= deadline_at {
if !(final_reminder_at..deadline_at).contains(&now) {
continue;
}
+3 -5
View File
@@ -140,15 +140,13 @@ 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() {
if events_json.len() == Event::PAGE_SIZE as usize
&& let Some(last_event) = events_json.last()
{
last_event["date"].as_str()
} else {
None
}
} else {
None
}
}
/// ###############################################################################################################
+23 -42
View File
@@ -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)]
@@ -592,11 +592,12 @@ async fn post_bulk_access_collections(
// As in Bitwarden, missing, repeated or unmanageable collections are Not Found. Invalid groups and members are
// checked after them and are a Bad Request.
if data.collection_ids.is_empty()
|| data.collection_ids.iter().collect::<HashSet<_>>().len() != data.collection_ids.len()
{
let mut seen = HashSet::new();
if data.collection_ids.is_empty() || data.collection_ids.iter().any(|id| !seen.insert(id)) {
err_code!("One or more collections not found.", Status::NotFound.code)
}
}
let mut collections = Vec::with_capacity(data.collection_ids.len());
for col_id in &data.collection_ids {
@@ -694,11 +695,7 @@ async fn put_organization_collection_update(
};
collection.name = data.name;
collection.external_id = match data.external_id {
Some(external_id) if !external_id.trim().is_empty() => Some(external_id),
_ => None,
};
collection.external_id = data.external_id.filter(|e| !e.trim().is_empty());
collection.save(&conn).await?;
log_event(
@@ -1317,7 +1314,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 +1794,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 +2276,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 +2387,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 +2456,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 +2467,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 +3083,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(
@@ -3251,8 +3237,8 @@ async fn get_group_members(
let group_members: Vec<MembershipId> = GroupUser::find_by_group(&group_id, &org_id, &conn)
.await
.iter()
.map(|entry| entry.users_organizations_uuid.clone())
.into_iter()
.map(|entry| entry.users_organizations_uuid)
.collect();
Ok(Json(json!(group_members)))
@@ -3731,12 +3717,7 @@ async fn put_reset_password_enrollment(
let reset_request = data.into_inner();
let reset_password_key = match reset_request.reset_password_key {
None => None,
Some(ref key) if key.is_empty() => None,
Some(key) => Some(key),
};
let reset_password_key = reset_request.reset_password_key.filter(|k| !k.is_empty());
if reset_password_key.is_none() && OrgPolicy::org_is_reset_password_auto_enroll(&org_id, &conn).await {
err!("Reset password can't be withdrawn due to an enterprise policy");
}
+2 -2
View File
@@ -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))
}
}
+4 -14
View File
@@ -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;
+3 -4
View File
@@ -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.
+2 -2
View File
@@ -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,
}
}
}
+14 -23
View File
@@ -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)
@@ -253,16 +250,14 @@ impl DuoClient {
Err(e) => return Err(e),
};
let mut post_body = HashMap::new();
post_body.insert("grant_type", String::from("authorization_code"));
post_body.insert("code", String::from(duo_code));
let post_body = HashMap::from([
("grant_type", String::from("authorization_code")),
("code", String::from(duo_code)),
// Must be the same URL that was supplied in the authorization request for the supplied duo_code
post_body.insert("redirect_uri", self.redirect_uri.clone());
post_body
.insert("client_assertion_type", String::from("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
post_body.insert("client_assertion", token);
("redirect_uri", self.redirect_uri.clone()),
("client_assertion_type", String::from("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")),
("client_assertion", token),
]);
let res = match make_http_request(reqwest::Method::POST, &token_url)?
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
@@ -291,7 +286,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 +417,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?;
+48 -32
View File
@@ -54,18 +54,9 @@ async fn send_email_login(data: Json<SendEmailLoginData>, client_headers: Client
crate::ratelimit::check_limit_login(&client_headers.ip.ip)?;
// Get the user
let email = match &data.email {
Some(email) if !email.is_empty() => Some(email),
_ => None,
};
let master_password_hash = match &data.master_password_hash {
Some(password_hash) if !password_hash.is_empty() => Some(password_hash),
_ => None,
};
let auth_request_id = match &data.auth_request_id {
Some(auth_request_id) if !auth_request_id.is_empty() => Some(auth_request_id),
_ => None,
};
let email = data.email.as_ref().filter(|e| !e.is_empty());
let master_password_hash = data.master_password_hash.as_ref().filter(|h| !h.is_empty());
let auth_request_id = data.auth_request_id.as_ref().filter(|a| !a.is_empty());
let user = if let Some(email) = email {
let Some(user) = User::find_by_mail(email, &conn).await else {
@@ -349,8 +340,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 +367,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 +389,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 new_name = if let 1..=3 = name_size {
"*".repeat(name_size)
} else {
let stars = "*".repeat(name_size - 2);
name.truncate(2);
format!("{name}{stars}")
let Some((name, domain)) = email.rsplit_once('@') else {
return "*".repeat(email.chars().count());
};
format!("{new_name}@{domain}")
let len = name.chars().count();
let keep = if len > 3 {
2
} else {
0
};
// 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 +421,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 +430,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);
// With a missing `@` the whole string should show asterisks
assert_eq!(result, "******************");
}
}
+3 -7
View File
@@ -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 {
keys.extract_if(.., |key| !retain(key)).for_each(|key| {
removed.insert(key.credential.cred_id().to_vec());
migrated = migrated || key.migrated;
}
retained
migrated |= key.migrated;
});
if removed.is_empty() {
+129 -155
View File
@@ -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`
@@ -253,43 +250,34 @@ fn get_favicons_node(dom: Tokenizer<StringReader<'_>, FaviconEmitter>, icons: &m
const ATTR_HREF: &[u8] = b"href";
const ATTR_SIZES: &[u8] = b"sizes";
let mut base_url = url.clone();
let mut icon_tags: Vec<Tag> = Vec::new();
for Ok(token) in dom {
let tag_name: &[u8] = &token.tag.name;
match tag_name {
TAG_LINK => {
icon_tags.push(token.tag);
}
TAG_BASE => {
base_url = if let Some(href) = token.tag.attributes.get(ATTR_HREF) {
let href = std::str::from_utf8(href).unwrap_or_default();
debug!("Found base href: {}", href.escape_debug());
match base_url.join(href) {
Ok(inner_url) => inner_url,
_ => continue,
}
} else {
continue;
};
}
TAG_HEAD if token.closing => {
break;
let mut base_href = None;
let mut icon_tags = Vec::new();
for Ok(mut token) in dom {
match token.tag.name.as_slice() {
TAG_LINK => icon_tags.push(token.tag),
TAG_BASE if base_href.is_none() => {
base_href = token.tag.attributes.remove(ATTR_HREF);
}
TAG_HEAD if token.closing => break,
b"body" | b"frameset" if !token.closing => break,
_ => {}
}
}
let parsed_base = base_href.as_ref().and_then(|value| {
let href = str::from_utf8(value).ok()?;
debug!("Found base href: {}", href.escape_debug());
url.join(href).ok().filter(|base| !matches!(base.scheme(), "data" | "javascript"))
});
let base_url = parsed_base.as_ref().unwrap_or(url);
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 priority = get_icon_priority(full_href.as_str(), sizes);
let sizes = icon_tag.attributes.get(ATTR_SIZES).map_or_default(|v| str::from_utf8(v).unwrap_or_default());
// Only check the full_href path during priority checks so query strings like `/path/to/icon.png?v=xxx` will be ignored
let priority = get_icon_priority(full_href.path(), sizes);
icons.push(Icon::new(priority, full_href.to_string()));
}
}
@@ -323,25 +311,18 @@ async fn get_icon_url(domain: &str) -> Result<IconUrlResult, Error> {
// If we get an error that is not caused by the blacklist, we retry with HTTP
match get_page(&httpdomain).await {
mut sub_resp @ Err(_) => {
// When the domain is not an IP, and has more then one dot, remove all subdomains.
let is_ip = domain.parse::<IpAddr>();
if is_ip.is_err() && domain.matches('.').count() > 1 {
let mut domain_parts = domain.split('.');
let base_domain = format!(
"{base}.{tld}",
tld = domain_parts.next_back().unwrap(),
base = domain_parts.next_back().unwrap()
);
if get_valid_host(&base_domain).is_ok() {
if domain.parse::<IpAddr>().is_err() {
if let Some((dot, _)) = domain.rmatch_indices('.').nth(1) {
// Use the last two labels when the domain has at least two dots.
let base_domain = &domain[dot + 1..];
if get_valid_host(base_domain).is_ok() {
let sslbase = format!("https://{base_domain}");
let httpbase = format!("http://{base_domain}");
debug!("[get_icon_url]: Trying without subdomains '{base_domain}'");
sub_resp = get_page(&sslbase).or_else(|_| get_page(&httpbase)).await;
}
// When the domain is not an IP, and has less then 2 dots, try to add www. infront of it.
} else if is_ip.is_err() && domain.matches('.').count() < 2 {
} else {
let www_domain = format!("www.{domain}");
if get_valid_host(&www_domain).is_ok() {
let sslwww = format!("https://{www_domain}");
@@ -351,6 +332,7 @@ async fn get_icon_url(domain: &str) -> Result<IconUrlResult, Error> {
sub_resp = get_page(&sslwww).or_else(|_| get_page(&httpwww)).await;
}
}
}
sub_resp
}
res => res,
@@ -378,9 +360,8 @@ async fn get_icon_url(domain: &str) -> Result<IconUrlResult, Error> {
iconlist.push(Icon::new(40, String::from(url.join("/apple-touch-icon.png").unwrap())));
// 384KB should be more than enough for the HTML, though as we only really need the HTML header.
let limited_reader = stream_to_bytes_limit(content, 384 * 1024).await?.to_vec();
let dom = Tokenizer::new_with_emitter(limited_reader.to_reader(), FaviconEmitter::default());
let limited_reader = stream_to_bytes_limit(content, 384 * 1024).await?;
let dom = Tokenizer::new_with_emitter(limited_reader.as_ref().to_reader(), FaviconEmitter::default());
get_favicons_node(dom, &mut iconlist, &url);
} else {
// Add the default favicon.ico to the list with just the given domain
@@ -443,7 +424,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,100 +470,76 @@ 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;
static ICON_SIZE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\d+)\D+(\d+)").unwrap());
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();
}
_ => {}
}
}
(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> {
let icon_result = get_icon_url(domain).await?;
let mut buffer = Bytes::new();
let mut icon_type: Option<&str> = None;
let mut icons = icon_result.iconlist.iter().take(5).peekable();
while let Some(icon) = icons.next() {
if icon.href.starts_with("data:image") {
let mut buffer = if icon.href.starts_with("data:image") {
let Ok(datauri) = data_url::DataUrl::process(&icon.href) else {
continue;
};
// Check if we are able to decode the data uri
let mut body = BytesMut::new();
match datauri.decode::<_, ()>(|bytes| {
if datauri
.decode::<_, ()>(|bytes| {
body.extend_from_slice(bytes);
Ok(())
}) {
Ok(_) => {
// Also check if the size is at least 67 bytes, which seems to be the smallest png I could create
if body.len() >= 67 {
// Check if the icon type is allowed, else try an icon from the list.
icon_type = get_icon_type(&body);
if icon_type.is_none() {
debug!("Icon from {domain} data:image uri, is not a valid image type");
})
.is_err()
{
debug!("Extracted icon from data:image uri is invalid");
continue;
}
info!("Extracted icon from data:image uri for {domain}");
buffer = body.freeze();
break;
}
}
_ => debug!("Extracted icon from data:image uri is invalid"),
// Preserve the minimum size required for data URI icons.
if body.len() < 67 {
continue;
}
body.freeze()
} else {
debug!("Trying {}", icon.href);
// Make sure all icons are checked before returning error
let res = match get_page_with_referer(&icon.href, &icon_result.referer).await {
Ok(r) => r,
Err(e) if icons.peek().is_none() => return Err(e),
Err(e) if CustomHttpClientError::downcast_ref(&e).is_some() => return Err(e), // If blacklisted stop immediately instead of checking the rest of the icons. see explanation and actual handling inside get_icon()
// If blacklisted stop immediately instead of checking the rest of the icons. see explanation and actual handling inside get_icon()
Err(e) if CustomHttpClientError::downcast_ref(&e).is_some() => return Err(e),
Err(e) => {
warn!("Unable to download icon: {e:?}");
// Continue to next icon
continue;
}
};
stream_to_bytes_limit(res, 5120 * 1024).await?
};
buffer = stream_to_bytes_limit(res, 5120 * 1024).await?; // 5120KB/5MB for each icon max (Same as icons.bitwarden.net)
// Check if the icon type is allowed, else try another icon from the list.
icon_type = get_icon_type(&buffer);
if icon_type.is_none() {
buffer.clear();
debug!("Icon from {}, is not a valid image type", icon.href);
let Some(icon_type) = get_icon_type(&buffer) else {
debug!("Icon candidate for {domain} is not a valid image type");
continue;
}
info!("Downloaded icon from {}", icon.href);
break;
}
}
};
if buffer.is_empty() {
err_silent!("Empty response or unable find a valid icon", domain);
} else if icon_type == Some("svg+xml") {
// Validate SVG format early incase it is invalid, it will continue to the next icon in the list
if icon_type == "svg+xml" {
let mut svg_filter = Filter::new();
svg_filter.set_data_url_filter(data_url_filter::allow_standard_images);
let mut sanitized_svg = Vec::new();
if svg_filter.filter(&*buffer, &mut sanitized_svg).is_err() {
icon_type = None;
buffer.clear();
} else {
if svg_filter.filter(&*buffer, &mut sanitized_svg).is_err() || sanitized_svg.is_empty() {
debug!("SVG icon candidate for {domain} could not be sanitized");
continue;
}
buffer = sanitized_svg.into();
}
info!("Found valid icon for {domain}");
return Ok((buffer, Some(icon_type)));
}
Ok((buffer, icon_type))
err_silent!("Empty response or unable find a valid icon", domain);
}
async fn save_icon(path: &str, icon: Vec<u8>) {
@@ -602,12 +559,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 +614,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 +629,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| {
@@ -690,11 +644,15 @@ impl reqwest::cookie::CookieStore for Jar {
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
let cookie_store = self.0.read().unwrap();
let s = cookie_store
.get_request_values(url)
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>()
.join("; ");
let mut s = String::new();
for (name, value) in cookie_store.get_request_values(url) {
if !s.is_empty() {
s.push_str("; ");
}
s.push_str(name);
s.push('=');
s.push_str(value);
}
if s.is_empty() {
return None;
@@ -736,34 +694,48 @@ struct FaviconEmitter {
}
impl FaviconEmitter {
fn flush_current_attribute(&mut self, emit_current_tag: bool) {
const ATTR_HREF: &[u8] = b"href";
const ATTR_REL: &[u8] = b"rel";
const TAG_LINK: &[u8] = b"link";
const TAG_BASE: &[u8] = b"base";
const TAG_HEAD: &[u8] = b"head";
fn is_icon_rel(rel: &[u8]) -> bool {
let mut has_icon = false;
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();
token.tag.attributes.entry(k).and_modify(|_| {}).or_insert(v);
for keyword in rel.split(u8::is_ascii_whitespace) {
if keyword.eq_ignore_ascii_case(b"mask-icon") {
return false;
}
if keyword.eq_ignore_ascii_case(b"icon")
|| keyword.eq_ignore_ascii_case(b"favicon")
|| keyword.eq_ignore_ascii_case(b"fluid-icon")
|| keyword.eq_ignore_ascii_case(b"apple-touch-icon")
|| keyword.eq_ignore_ascii_case(b"apple-touch-icon-precomposed")
{
has_icon = true;
}
}
let tag_attr = &token.tag.attributes;
match tag_name {
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();
if rel_value.contains("icon") && !rel_value.contains("mask-icon") {
self.emit_token = true;
has_icon
}
fn flush_current_attribute(&mut self, tag_complete: bool) {
let Some(token) = &mut self.current_token else {
return;
};
if let Some((name, value)) = self.current_attribute.take() {
token.tag.attributes.entry(name).or_insert(value);
}
_ => (),
if tag_complete {
let attrs = &token.tag.attributes;
let href: &[u8] = b"href";
let rel: &[u8] = b"rel";
self.emit_token = match (token.closing, token.tag.name.as_slice()) {
(true, b"head") | (false, b"body" | b"frameset") => true,
(false, b"base") => attrs.contains_key(href),
(false, b"link") => {
attrs.contains_key(href) && attrs.get(rel).is_some_and(|value| Self::is_icon_rel(value))
}
_ => false,
};
}
}
}
@@ -818,16 +790,11 @@ impl Emitter for FaviconEmitter {
fn init_attribute(&mut self) {
self.flush_current_attribute(false);
self.current_attribute = match &self.current_token {
Some(token) => {
let tag_name: &[u8] = &token.tag.name;
match tag_name {
b"link" | b"head" | b"base" => Some(Default::default()),
_ => None,
}
}
_ => None,
};
self.current_attribute = self
.current_token
.as_ref()
.filter(|token| !token.closing && matches!(token.tag.name.as_slice(), b"link" | b"base"))
.map(|_| Default::default());
}
fn push_attribute_name(&mut self, s: &[u8]) {
@@ -843,25 +810,32 @@ 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))
}
fn should_emit_errors(&mut self) -> bool {
false
}
// We do not want and need these parts of the HTML document
// These will be skipped and ignored during the tokenization and iteration.
fn emit_current_comment(&mut self) {}
fn emit_current_doctype(&mut self) {}
fn emit_current_processing_instruction(&mut self) {}
fn emit_eof(&mut self) {}
fn emit_error(&mut self, _: html5gum::Error) {}
fn emit_string(&mut self, _: &[u8]) {}
fn init_comment(&mut self) {}
fn init_doctype(&mut self) {}
fn init_processing_instruction(&mut self) {}
fn push_comment(&mut self, _: &[u8]) {}
fn push_doctype_name(&mut self, _: &[u8]) {}
fn push_doctype_public_identifier(&mut self, _: &[u8]) {}
fn push_doctype_system_identifier(&mut self, _: &[u8]) {}
fn push_processing_instruction_data(&mut self, _: &[u8]) {}
fn push_processing_instruction_target(&mut self, _: &[u8]) {}
fn set_doctype_public_identifier(&mut self, _: &[u8]) {}
fn set_doctype_system_identifier(&mut self, _: &[u8]) {}
fn set_force_quirks(&mut self) {}
+18 -23
View File
@@ -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 {
@@ -996,12 +996,7 @@ async fn twofactor_auth(
TwoFactorIncomplete::mark_complete(&user.uuid, &device.uuid, conn).await?;
let remember = data.two_factor_remember.unwrap_or(0);
let two_factor = if !CONFIG.disable_2fa_remember() && remember == 1 {
Some(device.refresh_twofactor_remember())
} else {
None
};
Ok(two_factor)
Ok((!CONFIG.disable_2fa_remember() && remember == 1).then(|| device.refresh_twofactor_remember()))
}
fn selected_data(tf: Option<TwoFactor>) -> ApiResult<String> {
@@ -1155,7 +1150,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 +1228,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 +1278,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 +1291,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 +1301,7 @@ async fn oidcsignin_error(
error_description,
}),
cookies,
&mut conn,
&conn,
)
.await
}
@@ -1319,7 +1314,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 +1362,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 +1405,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)
+1 -1
View File
@@ -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!({})
};
+24 -25
View File
@@ -4,6 +4,7 @@ use std::{
time::{Duration, Instant},
};
use bytes::Bytes;
use chrono::{NaiveDateTime, Utc};
use rmpv::Value;
use rocket::{Route, futures::StreamExt};
@@ -212,7 +213,7 @@ fn websockets_hub<'r>(
if last_received.elapsed() > WS_CLIENT_TIMEOUT {
break;
}
yield Message::Ping(PING.to_vec());
yield Message::Ping(PING);
}
}
}
@@ -295,7 +296,7 @@ fn anonymous_websockets_hub<'r>(ws: WebSocket, token: String, ip: ClientIp) -> R
if last_received.elapsed() > WS_CLIENT_TIMEOUT {
break;
}
yield Message::Ping(PING.to_vec());
yield Message::Ping(PING);
}
}
}
@@ -307,7 +308,7 @@ fn anonymous_websockets_hub<'r>(ws: WebSocket, token: String, ip: ClientIp) -> R
// Websockets server
//
fn serialize(val: &Value) -> Vec<u8> {
fn serialize(val: &Value) -> Bytes {
use rmpv::encode::write_value;
let mut buf = Vec::new();
@@ -335,7 +336,7 @@ fn serialize(val: &Value) -> Vec<u8> {
}
len_buf.append(&mut buf);
len_buf
len_buf.into()
}
fn serialize_date(date: NaiveDateTime) -> Value {
@@ -358,8 +359,8 @@ fn convert_option<T: Into<Value>>(option: Option<T>) -> Value {
}
const RECORD_SEPARATOR: u8 = 0x1e;
const INITIAL_RESPONSE: [u8; 3] = [0x7b, 0x7d, RECORD_SEPARATOR]; // {, }, <RS>
const PING: [u8; 3] = [0x02, 0x91, 0x06];
const INITIAL_RESPONSE: Bytes = Bytes::from_static(&[0x7b, 0x7d, RECORD_SEPARATOR]); // {, }, <RS>
const PING: Bytes = Bytes::from_static(&[0x02, 0x91, 0x06]);
#[derive(Deserialize, Copy, Clone, Eq, PartialEq)]
struct InitialMessage<'a> {
@@ -380,10 +381,10 @@ pub struct WebSocketUsers {
}
impl WebSocketUsers {
async fn send_update(&self, user_id: &UserId, data: &[u8]) {
async fn send_update(&self, user_id: &UserId, data: &Bytes) {
if let Some(user) = self.map.get(user_id.as_ref()).map(|v| v.clone()) {
for (_, sender) in &user {
if let Err(e) = sender.send(Message::binary(data)).await {
if let Err(e) = sender.send(Message::binary(data.clone())).await {
error!("Error sending WS update {e}");
}
}
@@ -427,13 +428,12 @@ impl WebSocketUsers {
if *NOTIFICATIONS_DISABLED {
return;
}
let acting_device_id = acting_device.map(|d| d.uuid.clone());
let mut payload =
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))];
if let Some(reason) = reason {
payload.push(("Reason".into(), (reason as i32).into()));
}
let data = create_update(payload, UpdateType::LogOut, acting_device_id);
let data = create_update(payload, UpdateType::LogOut, acting_device.map(|d| &d.uuid));
if CONFIG.enable_websocket() {
self.send_update(&user.uuid, &data).await;
@@ -456,7 +456,7 @@ impl WebSocketUsers {
("RevisionDate".into(), serialize_date(folder.updated_at)),
],
ut,
Some(device.uuid.clone()),
Some(&device.uuid),
);
if CONFIG.enable_websocket() {
@@ -503,7 +503,7 @@ impl WebSocketUsers {
("RevisionDate".into(), revision_date),
],
ut,
Some(device.uuid.clone()), // Acting device id (unique device/app uuid)
Some(&device.uuid), // Acting device id (unique device/app uuid)
);
if CONFIG.enable_websocket() {
@@ -559,7 +559,7 @@ impl WebSocketUsers {
let data = create_update(
vec![("Id".into(), auth_request_uuid.to_owned().into()), ("UserId".into(), user_id.to_string().into())],
UpdateType::AuthRequest,
Some(device.uuid.clone()),
Some(&device.uuid),
);
if CONFIG.enable_websocket() {
self.send_update(user_id, &data).await;
@@ -584,7 +584,7 @@ impl WebSocketUsers {
let data = create_update(
vec![("Id".into(), auth_request_id.to_string().into()), ("UserId".into(), user_id.to_string().into())],
UpdateType::AuthRequestResponse,
Some(device.uuid.clone()),
Some(&device.uuid),
);
if CONFIG.enable_websocket() {
self.send_update(user_id, &data).await;
@@ -615,23 +615,22 @@ 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);
}
}
async fn send_update(&self, token: &str, data: &[u8]) {
async fn send_update(&self, token: &str, data: &Bytes) {
// 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 {
if let Err(e) = sender.send(Message::binary(data.clone())).await {
error!("Error sending WS update {e}");
}
}
@@ -665,7 +664,7 @@ impl AnonymousWebSocketSubscriptions {
]
]
*/
fn create_update(payload: Vec<(Value, Value)>, ut: UpdateType, acting_device_id: Option<DeviceId>) -> Vec<u8> {
fn create_update(payload: Vec<(Value, Value)>, ut: UpdateType, acting_device_id: Option<&DeviceId>) -> Bytes {
use rmpv::Value as V;
let value = V::Array(vec![
@@ -683,7 +682,7 @@ fn create_update(payload: Vec<(Value, Value)>, ut: UpdateType, acting_device_id:
serialize(&value)
}
fn create_anonymous_update(payload: Vec<(Value, Value)>, ut: UpdateType, user_id: &UserId) -> Vec<u8> {
fn create_anonymous_update(payload: Vec<(Value, Value)>, ut: UpdateType, user_id: &UserId) -> Bytes {
use rmpv::Value as V;
let value = V::Array(vec![
+32 -31
View File
@@ -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()));
@@ -86,7 +86,8 @@ pub async fn initialize_keys() -> Result<(), Error> {
};
let (priv_key, priv_key_buffer) = if let Some(priv_key_buffer) = priv_key_buffer {
(Rsa::private_key_from_pem(priv_key_buffer.to_vec().as_slice())?, priv_key_buffer.to_vec())
let pem = priv_key_buffer.to_vec();
(Rsa::private_key_from_pem(&pem)?, pem)
} else {
let rsa_key = Rsa::generate(2048)?;
let priv_key_buffer = rsa_key.private_key_to_pem()?;
@@ -258,7 +259,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 +287,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 +299,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 +624,7 @@ impl<'r> FromRequest<'r> for Host {
format!("{protocol}://{host}")
};
Outcome::Success(Host {
Outcome::Success(Self {
host,
})
}
@@ -654,7 +655,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 +724,7 @@ impl<'r> FromRequest<'r> for Headers {
}
}
Outcome::Success(Headers {
Outcome::Success(Self {
host,
device,
user,
@@ -789,7 +790,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 +1066,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 +1133,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 +1148,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 +1165,7 @@ impl CollectionDeleteHeaders {
}
}
Ok(CollectionDeleteHeaders {
Ok(Self {
host: h.host,
device: h.device,
user: h.user,
@@ -1229,8 +1230,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,
@@ -1286,10 +1287,10 @@ fn client_ip_from_header(req: &Request<'_>, header: &str, is_trusted: impl Fn(Ip
}
fn client_ip_from_header_values(values: &[&str], header: &str, is_trusted: impl Fn(IpAddr) -> bool) -> Option<IpAddr> {
let entries: Vec<&str> = values.iter().flat_map(|value| value.split(',')).map(str::trim).collect();
let entries = values.iter().flat_map(|value| value.split(',')).rev().map(str::trim);
let mut client_ip = None;
for entry in entries.into_iter().rev() {
for entry in entries {
let Ok(ip) = entry.parse() else {
warn!("'{header}' header is malformed: {entry}");
break;
@@ -1322,7 +1323,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 +1353,7 @@ impl<'r> FromRequest<'r> for Secure {
}
};
Outcome::Success(Secure {
Outcome::Success(Self {
https: protocol == "https",
})
}
@@ -1398,7 +1399,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 +1415,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 +1487,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 {
+4 -4
View File
@@ -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(),
})
}
+20 -31
View File
@@ -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,15 +478,13 @@ 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() {
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
@@ -1003,11 +1000,11 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
}
let limit = 256;
if cfg.database_max_conns < 1 || cfg.database_max_conns > limit {
if !(1..=limit).contains(&cfg.database_max_conns) {
err!(format!("`DATABASE_MAX_CONNS` contains an invalid value. Ensure it is between 1 and {limit}.",));
}
if cfg.database_min_conns < 1 || cfg.database_min_conns > limit {
if !(1..=limit).contains(&cfg.database_min_conns) {
err!(format!("`DATABASE_MIN_CONNS` contains an invalid value. Ensure it is between 1 and {limit}.",));
}
@@ -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 whitelist = self.signups_domains_whitelist();
};
whitelist.is_empty() || whitelist.split(',').any(|d| d.trim() == email_domain)
let domain = &domain.to_lowercase();
let whitelist = self.signups_domains_whitelist();
let whitelist = whitelist.trim();
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> {
+17 -11
View File
@@ -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
@@ -614,6 +611,15 @@ pub mod test_db {
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
.env("DATABASE_URL", "sqlite://:memory:")
// Keep a local `.env` out of the tests, such as SMTP settings that would send mail
.env(
"ENV_FILE",
if cfg!(windows) {
"NUL"
} else {
"/dev/null"
},
)
.output()
.unwrap();
assert!(
+1 -1
View File
@@ -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(())
+19 -27
View File
@@ -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 {
@@ -1373,7 +1365,7 @@ impl Cipher {
return (assigned, Vec::new());
}
let listed: HashSet<CipherId> = assigned.iter().map(|cipher| cipher.uuid.clone()).collect();
let listed: HashSet<&CipherId> = assigned.iter().map(|cipher| &cipher.uuid).collect();
let in_collections: HashSet<CipherId> =
Self::get_collections_with_cipher_by_organization(&member.org_uuid, conn)
.await
+3 -13
View File
@@ -82,18 +82,8 @@ impl Collection {
}
pub fn set_external_id(&mut self, external_id: Option<String>) {
//Check if external id is empty. We don't want to have
//empty strings in the database
match external_id {
Some(external_id) => {
if external_id.is_empty() {
self.external_id = None;
} else {
self.external_id = Some(external_id);
}
}
None => self.external_id = None,
}
// Check if external id is empty. We don't want to have empty strings in the database
self.external_id = external_id.filter(|e| !e.trim().is_empty());
}
pub async fn to_json_details(
@@ -878,7 +868,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;
}
+31 -31
View File
@@ -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,
}
}
}
+3 -3
View File
@@ -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.");
}
+2 -6
View File
@@ -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.
+5 -8
View File
@@ -112,10 +112,7 @@ impl Group {
pub fn set_external_id(&mut self, external_id: Option<String>) {
// Check if external_id is empty. We do not want to have empty strings in the database
self.external_id = match external_id {
Some(external_id) if !external_id.trim().is_empty() => Some(external_id),
_ => None,
};
self.external_id = external_id.filter(|e| !e.trim().is_empty());
}
}
@@ -315,7 +312,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 +445,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 +464,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 +571,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;
}
+5 -8
View File
@@ -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;
}
+151 -70
View File
@@ -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))
}
}
@@ -212,17 +212,17 @@ impl PartialOrd<i32> for MembershipType {
}
fn gt(&self, other: &i32) -> bool {
matches!(self.partial_cmp(other), Some(Ordering::Greater))
self.partial_cmp(other).is_some_and(Ordering::is_gt)
}
fn ge(&self, other: &i32) -> bool {
matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
self.partial_cmp(other).is_some_and(Ordering::is_ge)
}
}
impl PartialEq<MembershipType> for i32 {
fn eq(&self, other: &MembershipType) -> bool {
*self == *other as i32
*self == *other as Self
}
}
@@ -235,11 +235,11 @@ impl PartialOrd<MembershipType> for i32 {
}
fn lt(&self, other: &MembershipType) -> bool {
matches!(self.partial_cmp(other), Some(Ordering::Less) | None)
self.partial_cmp(other).is_none_or(Ordering::is_lt)
}
fn le(&self, other: &MembershipType) -> bool {
matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal) | None)
self.partial_cmp(other).is_none_or(Ordering::is_le)
}
}
@@ -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))
}
@@ -644,16 +644,15 @@ impl Membership {
}
pub fn set_external_id(&mut self, external_id: Option<String>) -> bool {
//Check if external id is empty. We don't want to have
//empty strings in the database
if self.external_id != external_id {
self.external_id = match external_id {
Some(external_id) if !external_id.is_empty() => Some(external_id),
_ => None,
};
return true;
// Check if external id is empty. We don't want to have empty strings in the database
let external_id = external_id.filter(|e| !e.trim().is_empty());
if self.external_id == external_id {
return false;
}
false
self.external_id = external_id;
true
}
/// HACK: Convert the manager type to a custom type
@@ -882,7 +881,7 @@ impl Membership {
let twofactor_enabled = !TwoFactor::find_by_user(&user.uuid, conn).await.is_empty();
let groups: Vec<GroupId> = if include_groups && CONFIG.org_groups_enabled() {
GroupUser::find_by_member(&self.uuid, conn).await.iter().map(|gu| gu.groups_uuid.clone()).collect()
GroupUser::find_by_member(&self.uuid, conn).await.into_iter().map(|gu| gu.groups_uuid).collect()
} else {
// The Bitwarden clients seem to call this API regardless of whether groups are enabled,
// so just act as if there are no groups.
@@ -928,7 +927,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 +1080,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);
}
@@ -1285,9 +1284,7 @@ impl Membership {
.filter(users_organizations::org_uuid.eq(org_uuid))
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
.filter(
users_organizations::atype
.eq_any(vec![MembershipType::Owner as i32, MembershipType::Admin as i32])
.or(users_organizations::atype
users_organizations::atype.eq_any(ORG_ADMIN_ATYPES).or(users_organizations::atype
.eq(MembershipType::Manager as i32)
.and(users_organizations::access_all.eq(true))),
)
@@ -1669,6 +1666,18 @@ mod tests {
use CustomPermission::*;
use MembershipType::{Admin, Custom, Manager, Owner, User};
/// Every role, from the least to the most authority.
const AUTHORITY: [MembershipType; 5] = [User, Custom, Manager, Admin, Owner];
/// Stored roles no `MembershipType` exists for, like one written by a newer version.
const UNKNOWN_ROLES: [i32; 5] = [i32::MIN, -1, 5, 99, i32::MAX];
/// `[<, <=, >, >=, ==, !=]`, through the trait methods those operators call for `A` and `B`.
fn compare<A: PartialOrd<B>, B>(a: &A, b: &B) -> [bool; 6] {
[a.lt(b), a.le(b), a.gt(b), a.ge(b), a.eq(b), a.ne(b)]
}
fn expected(ordering: Ordering) -> [bool; 6] {
[ordering.is_lt(), ordering.is_le(), ordering.is_gt(), ordering.is_ge(), ordering.is_eq(), ordering.is_ne()]
}
fn member(role: MembershipType) -> Membership {
let mut member = Membership::new("user".into(), "org".into(), None);
member.atype = role as i32;
@@ -1678,22 +1687,94 @@ mod tests {
#[test]
fn membership_type_authority() {
assert!(Owner > Admin && Admin > Manager && Manager > Custom && Custom > User);
assert!((Custom as i32) >= User && (Custom as i32) < Manager && (Custom as i32) < Admin);
for raw in [99, -1] {
assert_eq!((raw >= User, raw >= Manager, raw >= Admin, raw < Admin), (false, false, false, true));
// Roles compare by authority, never by their stored number, whichever side the raw `i32` is on
for (i, role) in AUTHORITY.into_iter().enumerate() {
for (j, other) in AUTHORITY.into_iter().enumerate() {
let ordering = i.cmp(&j);
let (raw, raw_other) = (role as i32, other as i32);
assert_eq!(role.cmp(&other), ordering, "{role:?} {other:?}");
assert_eq!(role.partial_cmp(&raw_other), Some(ordering), "{role:?} {raw_other}");
assert_eq!(raw.partial_cmp(&other), Some(ordering), "{raw} {other:?}");
assert_eq!(compare(&role, &other), expected(ordering), "{role:?} {other:?}");
assert_eq!(compare(&role, &raw_other), expected(ordering), "{role:?} {raw_other}");
assert_eq!(compare(&raw, &other), expected(ordering), "{raw} {other:?}");
}
}
for (value, expected) in [
("0", Some(Owner)),
("Owner", Some(Owner)),
("1", Some(Admin)),
("Admin", Some(Admin)),
("2", Some(User)),
("User", Some(User)),
("3", Some(Manager)),
("Manager", Some(Manager)),
("4", Some(Custom)),
("Custom", Some(Custom)),
("5", None),
("Invalid", None),
] {
assert_eq!(MembershipType::from_str(value), expected);
}
}
#[test]
fn unknown_raw_roles_fail_closed() {
for raw in UNKNOWN_ROLES {
assert_eq!(MembershipType::from_i32(raw), None);
for role in AUTHORITY {
// An unknown stored role ranks below every role, so it never passes an authority check and every
// `atype < Admin` restriction applies to it
assert_eq!(raw.partial_cmp(&role), None);
assert_eq!(compare(&raw, &role), [true, true, false, false, false, true], "{raw} {role:?}");
// The other way around nothing holds, which no check relies on
assert_eq!(role.partial_cmp(&raw), None);
assert_eq!(compare(&role, &raw), [false, false, false, false, false, true], "{role:?} {raw}");
}
let mut unknown = member(User);
unknown.atype = raw;
assert!(!unknown.has_full_access());
assert!(AUTHORITY.into_iter().all(|role| !unknown.has_type(role)));
}
}
#[test]
fn revoke_and_restore_round_trip() {
// The revoked statuses are stored and queried for, so they are pinned rather than derived
for (status, revoked) in
[(MembershipStatus::Invited, -128), (MembershipStatus::Accepted, -127), (MembershipStatus::Confirmed, -126)]
{
let status = status as i32;
for role in AUTHORITY {
let mut m = member(role);
m.status = status;
let full_access = m.has_full_access();
assert_eq!(full_access, role >= Admin && status == MembershipStatus::Confirmed as i32);
assert!(!m.restore(), "{role:?} {status}: only a revoked member can be restored");
assert_eq!((m.status, m.get_unrevoked_status()), (status, status));
assert!(m.revoke(), "{role:?} {status}");
assert_eq!((m.status, m.get_unrevoked_status()), (revoked, status));
assert!(MembershipStatus::from_i32(m.status).is_none());
assert!(!m.has_status(MembershipStatus::Confirmed) && !m.has_full_access());
assert!(m.has_type(role));
assert_eq!(m.atype.partial_cmp(&role), Some(Ordering::Equal));
assert!(!m.revoke(), "{role:?} {status}: a revoked member can't be revoked again");
assert_eq!(m.status, revoked);
assert!(m.restore(), "{role:?} {status}");
assert_eq!((m.status, m.get_unrevoked_status()), (status, status));
assert_eq!((m.atype, m.has_full_access()), (role as i32, full_access));
assert!(!m.restore(), "{role:?} {status}: a restored member can't be restored again");
assert_eq!(m.status, status);
}
}
}
#[test]
fn requested_membership_type() {
let none = HashSet::new();
+8 -8
View File
@@ -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,
+1 -1
View File
@@ -67,7 +67,7 @@ impl SsoAuth {
) -> Self {
let now = Utc::now().naive_utc();
SsoAuth {
Self {
state,
client_challenge,
nonce,
+3 -3
View File
@@ -174,7 +174,7 @@ impl TwoFactor {
for mut u2f in u2f_factors {
let mut regs: Vec<U2FRegistration> = serde_json::from_str(&u2f.data)?;
// If there are no registrations or they are migrated (we do the migration in batch so we can consider them all migrated when the first one is)
if regs.is_empty() || regs[0].migrated == Some(true) {
if regs.first().is_none_or(|reg| reg.migrated == Some(true)) {
continue;
}
@@ -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?;
}
+13 -8
View File
@@ -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);
@@ -773,6 +769,15 @@ mod tests {
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
.env("DATABASE_URL", "sqlite://:memory:")
// Keep a local `.env` out of the tests, such as SMTP settings that would send mail.
.env(
"ENV_FILE",
if cfg!(windows) {
"NUL"
} else {
"/dev/null"
},
)
.output()
.unwrap();
assert!(
+1 -2
View File
@@ -238,8 +238,7 @@ impl Serialize for ApiErrorResponse<'_> {
state.serialize_field("message", self.0.message)?;
let mut validation_errors = std::collections::HashMap::with_capacity(1);
validation_errors.insert("", vec![self.0.message]);
let validation_errors = std::collections::HashMap::from([("", vec![self.0.message])]);
state.serialize_field("validationErrors", &validation_errors)?;
let error_model = ErrorModel {
+13 -15
View File
@@ -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 {
(!should_block_address_regex(&host_str)).ok_or(CustomHttpClientError::Blocked {
domain: host_str,
});
}
Ok(())
})
}
#[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);
}
// ===
+7 -16
View File
@@ -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 {
@@ -358,7 +349,7 @@ pub async fn send_emergency_access_invite(
{
let mut query_params = query.query_pairs_mut();
query_params
.append_pair("id", &emer_id.to_string())
.append_pair("id", emer_id.as_str())
.append_pair("name", grantor_name)
.append_pair("email", address)
.append_pair("token", &encode_jwt(&claims));
+9 -19
View File
@@ -243,22 +243,20 @@ 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)
.map(|m| {
m.as_str()
.split(',')
.collect::<Vec<&str>>()
.into_iter()
.filter_map(|s| match s.split_once('=') {
Some((log, lvl_str)) => log::LevelFilter::from_str(lvl_str).ok().map(|lvl| (log, lvl)),
_ => None,
})
.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 {
@@ -366,16 +364,15 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
}
if let Some(log_file) = CONFIG.log_file() {
#[cfg(windows)]
{
logger = logger.chain(fern::log_file(log_file)?);
}
#[cfg(unix)]
{
std::cfg_select! {
windows => { logger = logger.chain(fern::log_file(log_file)?); }
unix => {
const SIGHUP: i32 = SignalKind::hangup().as_raw_value();
let path = Path::new(&log_file);
logger = logger.chain(fern::log_reopen1(path, [SIGHUP])?);
}
_ => {}
}
}
#[cfg(unix)]
@@ -394,14 +391,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 +754,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(),
))));
}
+6 -6
View File
@@ -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")
+17 -15
View File
@@ -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())))
@@ -83,10 +83,12 @@ impl<'c> AsyncHttpClient<'c> for OidcHttpClient {
fn call(&'c self, request: HttpRequest) -> Self::Future {
Box::pin(async move {
let response = self.client.execute(request.try_into().map_err(Box::new)?).await.map_err(|e| {
debug!("Request failed {e:?}");
Box::new(e)
})?;
let response = self
.client
.execute(request.try_into().map_err(Box::new)?)
.await
.inspect_err(|e| debug!("Request failed {e:?}"))
.map_err(Box::new)?;
let mut builder = http::Response::builder().status(response.status()).version(response.version());
@@ -154,7 +156,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 +165,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 +179,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);
}
}
@@ -189,7 +191,7 @@ impl Client {
binding_hash: Option<String>,
) -> ApiResult<(Url, SsoAuth)> {
let scopes = CONFIG.sso_scopes_vec().into_iter().map(Scope::new);
let base64_state = data_encoding::BASE64.encode(state.to_string().as_bytes());
let base64_state = data_encoding::BASE64.encode(state.as_bytes());
let client = Self::cached().await?;
let mut auth_req = client
@@ -287,7 +289,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 +314,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 })
+1 -2
View File
@@ -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]) {
+57 -101
View File
@@ -38,24 +38,15 @@ impl Fairing for AppHeaders {
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
let req_uri_path = req.uri().path();
let req_headers = req.headers();
// Check if this connection is an Upgrade/WebSocket connection and return early
// We do not want add any extra headers, this could cause issues with reverse proxies or CloudFlare
if req_uri_path.ends_with("notifications/hub") || req_uri_path.ends_with("notifications/anonymous-hub") {
match (req_headers.get_one("connection"), req_headers.get_one("upgrade")) {
(Some(c), Some(u))
if c.to_lowercase().contains("upgrade") && u.to_lowercase().contains("websocket") =>
{
// Remove headers which could cause websocket connection issues
if res.upgrade("websocket").is_some() {
res.remove_header("X-Frame-Options");
res.remove_header("X-Content-Type-Options");
res.remove_header("Permissions-Policy");
return;
}
(_, _) => (),
}
}
// NOTE: When modifying or adding security headers be sure to also update the diagnostic checks in `src/static/scripts/admin_diagnostics.js` in `checkSecurityHeaders`
res.set_raw_header("Permissions-Policy", "accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()");
@@ -151,16 +142,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 +176,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 +202,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 +210,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 +218,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 +435,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 +455,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,16 +497,16 @@ 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(_) => {
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
}
_ => None,
}
}
//
@@ -715,10 +699,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)
}
}
@@ -728,13 +714,7 @@ where
T: From<String>,
{
use serde::Deserialize;
Ok(Option::<String>::deserialize(deserializer)?.and_then(|s| {
if s.is_empty() {
None
} else {
Some(T::from(s))
}
}))
Ok(Option::<String>::deserialize(deserializer)?.filter(|s| !s.is_empty()).map(T::from))
}
#[derive(Clone, Debug, Deserialize)]
@@ -747,8 +727,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 +736,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 +751,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 +809,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);
json_map.insert(process_json_key(key), convert_json_key_lcase_first(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);
}
}
}
Value::Object(json_map)
}
value => value,
}
}
pub enum FeatureFlagFilter {
#[allow(dead_code)]
Unfiltered,
ValidOnly,
InvalidOnly,
}
@@ -891,7 +842,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 +861,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 +875,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 +891,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 +900,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 +983,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}");
}