mirror of
https://github.com/dani-garcia/vaultwarden.wiki.git
synced 2026-11-19 01:05:57 +02:00
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:
1 parent
4051a4d3a6
commit
4a0acc3314
51 files changed
+1219
-1569
No files matched your search
@@ -38,7 +38,7 @@ repos:
|
|||||||
description: Test the package for errors.
|
description: Test the package for errors.
|
||||||
entry: cargo test
|
entry: cargo test
|
||||||
language: system
|
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
|
types_or: [ rust, toml ] # Cargo.lock matches toml type which is intended
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
- id: cargo-clippy
|
- id: cargo-clippy
|
||||||
@@ -46,7 +46,7 @@ repos:
|
|||||||
description: Lint Rust sources
|
description: Lint Rust sources
|
||||||
entry: cargo clippy
|
entry: cargo clippy
|
||||||
language: system
|
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
|
types_or: [ rust, toml ] # Cargo.lock matches toml type which is intended
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
- id: check-docker-templates
|
- id: check-docker-templates
|
||||||
|
|||||||
Generated
+352
-624
File diff suppressed because it is too large.
Load diff
+35
-26
@@ -1,6 +1,6 @@
|
|||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.97.1"
|
rust-version = "1.98.1"
|
||||||
license = "AGPL-3.0-only"
|
license = "AGPL-3.0-only"
|
||||||
repository = "https://github.com/dani-garcia/vaultwarden"
|
repository = "https://github.com/dani-garcia/vaultwarden"
|
||||||
publish = false
|
publish = false
|
||||||
@@ -44,7 +44,6 @@ s3 = [
|
|||||||
"dep:aws-config",
|
"dep:aws-config",
|
||||||
"dep:aws-credential-types",
|
"dep:aws-credential-types",
|
||||||
"dep:aws-smithy-runtime-api",
|
"dep:aws-smithy-runtime-api",
|
||||||
"dep:http",
|
|
||||||
"dep:reqsign-aws-v4",
|
"dep:reqsign-aws-v4",
|
||||||
"dep:reqsign-core",
|
"dep:reqsign-core",
|
||||||
]
|
]
|
||||||
@@ -61,7 +60,7 @@ unstable = []
|
|||||||
unsafe_test_mode = ["dep:serde_cbor_2"]
|
unsafe_test_mode = ["dep:serde_cbor_2"]
|
||||||
|
|
||||||
[target."cfg(unix)".dependencies]
|
[target."cfg(unix)".dependencies]
|
||||||
nix = { version = "0.31.3", features = ["fs"] }
|
nix = { version = "0.32.0", features = ["fs"] }
|
||||||
# Logging
|
# Logging
|
||||||
syslog = "7.0.0"
|
syslog = "7.0.0"
|
||||||
|
|
||||||
@@ -83,8 +82,8 @@ num-derive = "0.5.1"
|
|||||||
bigdecimal = "0.4.11"
|
bigdecimal = "0.4.11"
|
||||||
|
|
||||||
# Web framework
|
# Web framework
|
||||||
rocket = { version = "0.5.2", default-features = false, features = ["json", "tls"] }
|
rocket = { version = "0.5.3", default-features = false, features = ["json", "tls"] }
|
||||||
rocket_ws = { version = "0.1.1" }
|
rocket_ws = { version = "0.2.0" }
|
||||||
|
|
||||||
# WebSockets libraries
|
# WebSockets libraries
|
||||||
rmpv = "1.3.1" # MessagePack library
|
rmpv = "1.3.1" # MessagePack library
|
||||||
@@ -110,8 +109,8 @@ serde = { version = "1.0.229", features = ["derive"] }
|
|||||||
serde_json = "1.0.154"
|
serde_json = "1.0.154"
|
||||||
|
|
||||||
# A safe, extensible ORM and Query builder
|
# A safe, extensible ORM and Query builder
|
||||||
diesel = { version = "2.3.14", features = ["chrono", "r2d2", "numeric", "64-column-tables"] }
|
diesel = { version = "2.4.0", features = ["chrono", "r2d2", "numeric", "64-column-tables"] }
|
||||||
diesel_migrations = "2.3.2"
|
diesel_migrations = "2.4.0"
|
||||||
|
|
||||||
derive_more = { version = "2.1.1", features = [
|
derive_more = { version = "2.1.1", features = [
|
||||||
"as_ref",
|
"as_ref",
|
||||||
@@ -123,21 +122,20 @@ derive_more = { version = "2.1.1", features = [
|
|||||||
diesel-derive-newtype = "2.1.3"
|
diesel-derive-newtype = "2.1.3"
|
||||||
|
|
||||||
# SQLite, statically bundled unless the `sqlite_system` feature is enabled
|
# 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
|
# Crypto-related libraries
|
||||||
rand = "0.10.3"
|
rand = "0.10.4"
|
||||||
ring = "0.17.14"
|
ring = "0.17.14"
|
||||||
rustls = { version = "0.23.46", features = ["ring", "std"], default-features = false }
|
rustls = { version = "0.23.46", features = ["ring", "std"], default-features = false }
|
||||||
subtle = "2.6.1"
|
subtle = "2.6.1"
|
||||||
|
|
||||||
# UUID generation
|
# UUID generation
|
||||||
uuid = { version = "1.29.0", features = ["v4"] }
|
uuid = { version = "1.29.3", features = ["v4"] }
|
||||||
|
|
||||||
# Date and time libraries
|
# Date and time libraries
|
||||||
chrono = { version = "0.4.45", default-features = false, features = ["clock", "serde"] }
|
chrono = { version = "0.4.45", default-features = false, features = ["clock", "serde"] }
|
||||||
chrono-tz = "0.10.4"
|
chrono-tz = "0.10.4"
|
||||||
time = "0.3.55"
|
|
||||||
|
|
||||||
# Job scheduler
|
# Job scheduler
|
||||||
job_scheduler_ng = "2.5.0"
|
job_scheduler_ng = "2.5.0"
|
||||||
@@ -146,7 +144,7 @@ job_scheduler_ng = "2.5.0"
|
|||||||
data-encoding = "2.11.1"
|
data-encoding = "2.11.1"
|
||||||
|
|
||||||
# JWT library
|
# 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 library
|
||||||
totp-lite = "2.0.1"
|
totp-lite = "2.0.1"
|
||||||
@@ -166,7 +164,7 @@ serde_cbor_2 = { version = "0.13.0", optional = true }
|
|||||||
url = "2.5.8"
|
url = "2.5.8"
|
||||||
|
|
||||||
# Email libraries
|
# Email libraries
|
||||||
lettre = { version = "0.11.23", default-features = false, features = [
|
lettre = { version = "0.11.24", default-features = false, features = [
|
||||||
# Misc
|
# Misc
|
||||||
"tracing",
|
"tracing",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -181,7 +179,7 @@ lettre = { version = "0.11.23", default-features = false, features = [
|
|||||||
"sendmail-transport",
|
"sendmail-transport",
|
||||||
] }
|
] }
|
||||||
percent-encoding = "2.3.2" # URL encoding library used for URL's in the emails
|
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
|
# HTML Template library
|
||||||
handlebars = { version = "6.4.4", features = ["dir_source"] }
|
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"
|
hickory-resolver = "0.26.3"
|
||||||
|
|
||||||
# Favicon extraction libraries
|
# Favicon extraction libraries
|
||||||
html5gum = "0.9.0"
|
html5gum = "0.9.2"
|
||||||
regex = { version = "1.13.1", default-features = false, features = [
|
regex = { version = "1.13.2", default-features = false, features = [
|
||||||
"perf",
|
"perf",
|
||||||
"std",
|
"std",
|
||||||
"unicode-perl",
|
"unicode-perl",
|
||||||
] }
|
] }
|
||||||
data-url = "0.3.2"
|
data-url = "0.3.2"
|
||||||
bytes = "1.12.1"
|
bytes = "1.12.2"
|
||||||
svg-hush = "0.9.7"
|
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
|
# Used for custom short lived cookie jar during favicon extraction
|
||||||
cookie = "0.18.2"
|
cookie = "0.18.2"
|
||||||
cookie_store = "0.22.1"
|
cookie_store = "0.22.1"
|
||||||
|
|
||||||
# Used by U2F, JWT and PostgreSQL
|
# Used by U2F, JWT and PostgreSQL
|
||||||
openssl = "0.10.81"
|
openssl = "0.10.82"
|
||||||
|
|
||||||
# CLI argument parsing
|
# CLI argument parsing
|
||||||
pico-args = "0.5.0"
|
pico-args = "0.5.0"
|
||||||
@@ -240,6 +235,8 @@ ipnet = "2.12.2"
|
|||||||
|
|
||||||
# OIDC for SSO
|
# OIDC for SSO
|
||||||
openidconnect = { version = "4.1.0", default-features = false }
|
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"] }
|
moka = { version = "0.12.16", features = ["future"] }
|
||||||
|
|
||||||
# Check client versions for specific features.
|
# Check client versions for specific features.
|
||||||
@@ -255,7 +252,7 @@ which = "8.0.6"
|
|||||||
argon2 = "0.6.0"
|
argon2 = "0.6.0"
|
||||||
|
|
||||||
# Reading a password from the cli for generating the Argon2id ADMIN_TOKEN
|
# 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
|
# Loading a dynamic CSS Stylesheet
|
||||||
grass_compiler = { version = "0.13.4", default-features = false }
|
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 }
|
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
|
# 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",
|
"behavior-version-latest",
|
||||||
"credentials-process",
|
"credentials-process",
|
||||||
"rt-tokio",
|
"rt-tokio",
|
||||||
"sso",
|
"sso",
|
||||||
] }
|
] }
|
||||||
aws-credential-types = { version = "1.3.1", optional = true }
|
aws-credential-types = { version = "1.3.1", optional = true }
|
||||||
aws-smithy-runtime-api = { version = "1.19.2", optional = true }
|
aws-smithy-runtime-api = { version = "1.22.0", optional = true }
|
||||||
http = { version = "1.5.0", optional = true }
|
|
||||||
reqsign-aws-v4 = { version = "3.3.1", optional = true }
|
reqsign-aws-v4 = { version = "3.3.1", optional = true }
|
||||||
reqsign-core = { version = "3.3.2", optional = true }
|
reqsign-core = { version = "3.3.2", optional = true }
|
||||||
|
|
||||||
@@ -330,6 +326,14 @@ opt-level = 3
|
|||||||
# Linting config
|
# Linting config
|
||||||
# https://doc.rust-lang.org/rustc/lints/groups.html
|
# https://doc.rust-lang.org/rustc/lints/groups.html
|
||||||
[workspace.lints.rust]
|
[workspace.lints.rust]
|
||||||
|
# Features
|
||||||
|
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||||
|
'cfg(sqlite)',
|
||||||
|
'cfg(mysql)',
|
||||||
|
'cfg(postgresql)',
|
||||||
|
'cfg(s3)',
|
||||||
|
] }
|
||||||
|
|
||||||
# Forbid
|
# Forbid
|
||||||
unsafe_code = "forbid"
|
unsafe_code = "forbid"
|
||||||
non_ascii_idents = "forbid"
|
non_ascii_idents = "forbid"
|
||||||
@@ -359,6 +363,7 @@ unused_import_braces = "deny"
|
|||||||
unused_lifetimes = "deny"
|
unused_lifetimes = "deny"
|
||||||
unused_qualifications = "deny"
|
unused_qualifications = "deny"
|
||||||
variant_size_differences = "deny"
|
variant_size_differences = "deny"
|
||||||
|
redundant_imports = "deny"
|
||||||
|
|
||||||
# https://rust-lang.github.io/rust-clippy/stable/index.html
|
# https://rust-lang.github.io/rust-clippy/stable/index.html
|
||||||
[workspace.lints.clippy]
|
[workspace.lints.clippy]
|
||||||
@@ -386,11 +391,15 @@ iter_on_empty_collections = "deny"
|
|||||||
iter_on_single_items = "deny"
|
iter_on_single_items = "deny"
|
||||||
mem_forget = "deny"
|
mem_forget = "deny"
|
||||||
needless_collect = "deny"
|
needless_collect = "deny"
|
||||||
|
needless_pass_by_ref_mut = "deny"
|
||||||
|
or_fun_call = "deny"
|
||||||
redundant_clone = "deny"
|
redundant_clone = "deny"
|
||||||
|
significant_drop_in_scrutinee = "deny"
|
||||||
|
str_to_string = "deny"
|
||||||
unnecessary_self_imports = "deny"
|
unnecessary_self_imports = "deny"
|
||||||
|
use_self = "deny"
|
||||||
useless_let_if_seq = "deny"
|
useless_let_if_seq = "deny"
|
||||||
verbose_file_reads = "deny"
|
verbose_file_reads = "deny"
|
||||||
str_to_string = "deny"
|
|
||||||
|
|
||||||
# Pedantic Opt-Outs
|
# Pedantic Opt-Outs
|
||||||
inline_always = "allow" # We use this sparsely
|
inline_always = "allow" # We use this sparsely
|
||||||
|
|||||||
@@ -16,13 +16,6 @@ fn main() {
|
|||||||
#[cfg(feature = "s3")]
|
#[cfg(feature = "s3")]
|
||||||
println!("cargo:rustc-cfg=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.
|
// Rerun when these paths are changed.
|
||||||
// Someone could have checked-out a tag or specific commit, but no other files changed.
|
// Someone could have checked-out a tag or specific commit, but no other files changed.
|
||||||
println!("cargo:rerun-if-changed=.git");
|
println!("cargo:rerun-if-changed=.git");
|
||||||
|
|||||||
@@ -32,10 +32,10 @@ FROM --platform=linux/amd64 docker.io/vaultwarden/web-vault@sha256:7baaa7d534974
|
|||||||
########################## ALPINE BUILD IMAGES ##########################
|
########################## ALPINE BUILD IMAGES ##########################
|
||||||
## NOTE: The Alpine Base Images do not support other platforms then linux/amd64 and linux/arm64
|
## 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
|
## 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:x86_64-musl-stable-1.100.0 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:aarch64-musl-stable-1.100.0 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:armv7-musleabihf-stable-1.100.0 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:arm-musleabi-stable-1.100.0 AS build_armv6
|
||||||
|
|
||||||
########################## BUILD IMAGE ##########################
|
########################## BUILD IMAGE ##########################
|
||||||
# hadolint ignore=DL3006
|
# hadolint ignore=DL3006
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ FROM --platform=linux/amd64 docker.io/tonistiigi/xx@sha256:40fe21f44bb8cddf1eb12
|
|||||||
|
|
||||||
########################## BUILD IMAGE ##########################
|
########################## BUILD IMAGE ##########################
|
||||||
# hadolint ignore=DL3006
|
# 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
|
# hadolint ignore=DL3067
|
||||||
COPY --from=xx / /
|
COPY --from=xx / /
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ proc-macro = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
quote = "1.0.47"
|
quote = "1.0.47"
|
||||||
syn = "3.0.9"
|
syn = "3.0.10"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
+1
-1
@@ -18,7 +18,7 @@ fn impl_derive_uuid_macro(ast: &DeriveInput) -> TokenStream {
|
|||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
|
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()))
|
Ok(Self(param.to_string()))
|
||||||
} else {
|
} else {
|
||||||
Err(())
|
Err(())
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "1.99.1"
|
channel = "1.100.0"
|
||||||
components = [ "rustfmt", "clippy" ]
|
components = [ "rustfmt", "clippy" ]
|
||||||
profile = "minimal"
|
profile = "minimal"
|
||||||
+54
-46
@@ -125,15 +125,15 @@ impl<'r> FromRequest<'r> for IpHeader {
|
|||||||
|
|
||||||
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||||
if req.headers().get_one(&CONFIG.ip_header()).is_some() {
|
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() {
|
} 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() {
|
} 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() {
|
} 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 {
|
} else {
|
||||||
Outcome::Success(IpHeader(None))
|
Outcome::Success(Self(None))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -210,7 +210,7 @@ fn post_admin_login(
|
|||||||
|
|
||||||
let cookie = Cookie::build((COOKIE_NAME, jwt))
|
let cookie = Cookie::build((COOKIE_NAME, jwt))
|
||||||
.path(admin_path())
|
.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)
|
.same_site(SameSite::Strict)
|
||||||
.http_only(true)
|
.http_only(true)
|
||||||
.secure(secure.https);
|
.secure(secure.https);
|
||||||
@@ -391,7 +391,7 @@ async fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<Stri
|
|||||||
None => json!("Never"),
|
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
|
// 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)
|
let roles: HashMap<String, i32> = Membership::find_confirmed_by_user(&u.uuid, &conn)
|
||||||
@@ -677,46 +677,55 @@ async fn has_http_access() -> bool {
|
|||||||
let Ok(req) = make_http_request(Method::HEAD, "https://github.com/dani-garcia/vaultwarden") else {
|
let Ok(req) = make_http_request(Method::HEAD, "https://github.com/dani-garcia/vaultwarden") else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
match req.send().await {
|
req.send().await.is_ok_and(|r| r.status().is_success())
|
||||||
Ok(r) => r.status().is_success(),
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
async fn get_release_info(has_http_access: bool) -> (String, String, String) {
|
||||||
// If the HTTP Check failed, do not even attempt to check for new versions since we were not able to connect with github.com anyway.
|
// Cache this function to prevent API call rate limit. Github only allows 60 requests per hour, and we use 3 here already
|
||||||
if has_http_access {
|
// 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
|
||||||
match get_json_api::<GitRelease>("https://api.github.com/repos/dani-garcia/vaultwarden/releases/latest")
|
static CACHE: LazyLock<moka::future::Cache<bool, (String, String, String)>> = LazyLock::new(|| {
|
||||||
.await
|
moka::future::Cache::builder().max_capacity(2).time_to_live(std::time::Duration::from_mins(10)).build()
|
||||||
{
|
});
|
||||||
Ok(r) => r.tag_name,
|
|
||||||
_ => "-".to_owned(),
|
CACHE
|
||||||
},
|
.get_with(has_http_access, async {
|
||||||
match get_json_api::<GitCommit>("https://api.github.com/repos/dani-garcia/vaultwarden/commits/main").await {
|
// 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.
|
||||||
Ok(mut c) => {
|
if has_http_access {
|
||||||
c.sha.truncate(8);
|
(
|
||||||
c.sha
|
match get_json_api::<GitRelease>(
|
||||||
}
|
"https://api.github.com/repos/dani-garcia/vaultwarden/releases/latest",
|
||||||
_ => "-".to_owned(),
|
)
|
||||||
},
|
.await
|
||||||
// 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
|
Ok(r) => r.tag_name,
|
||||||
match get_json_api::<GitRelease>("https://api.github.com/repos/dani-garcia/bw_web_builds/releases/latest")
|
_ => "-".to_owned(),
|
||||||
.await
|
},
|
||||||
{
|
match get_json_api::<GitCommit>("https://api.github.com/repos/dani-garcia/vaultwarden/commits/main")
|
||||||
Ok(r) => r.tag_name.trim_start_matches('v').to_owned(),
|
.await
|
||||||
_ => "-".to_owned(),
|
{
|
||||||
},
|
Ok(mut c) => {
|
||||||
)
|
c.sha.truncate(8);
|
||||||
} else {
|
c.sha
|
||||||
("-".to_owned(), "-".to_owned(), "-".to_owned())
|
}
|
||||||
}
|
_ => "-".to_owned(),
|
||||||
|
},
|
||||||
|
// Do not fetch the web-vault version when running within a container
|
||||||
|
// The web-vault version is embedded within the container it self, and should not be updated manually
|
||||||
|
match get_json_api::<GitRelease>(
|
||||||
|
"https://api.github.com/repos/dani-garcia/bw_web_builds/releases/latest",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(r) => r.tag_name.trim_start_matches('v').to_owned(),
|
||||||
|
_ => "-".to_owned(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
("-".to_owned(), "-".to_owned(), "-".to_owned())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_ntp_time(has_http_access: bool) -> String {
|
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) {
|
let access_token = if let Some(cookie) = cookies.get(COOKIE_NAME) {
|
||||||
cookie.value()
|
cookie.value()
|
||||||
} else {
|
} else {
|
||||||
let requested_page =
|
let requested_page = request.segments::<std::path::PathBuf>(0..).unwrap_or_default();
|
||||||
request.segments::<std::path::PathBuf>(0..).unwrap_or_default().display().to_string();
|
|
||||||
// When the requested page is empty, it is `/admin`, in that case, Forward, so it will render the login page
|
// 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
|
// Else, return a 401 failure, which will be caught
|
||||||
if requested_page.is_empty() {
|
if requested_page.is_empty() {
|
||||||
|
|||||||
+15
-22
@@ -166,8 +166,8 @@ impl RegisterDataCompat {
|
|||||||
fcu: impl FnOnce(&'a RegisterDataCur) -> &'a T,
|
fcu: impl FnOnce(&'a RegisterDataCur) -> &'a T,
|
||||||
) -> &'a T {
|
) -> &'a T {
|
||||||
match self {
|
match self {
|
||||||
RegisterDataCompat::RegisterDataOld(rdc) => fct(rdc),
|
Self::RegisterDataOld(rdc) => fct(rdc),
|
||||||
RegisterDataCompat::RegisterDataCur(rdcu) => fcu(rdcu),
|
Self::RegisterDataCur(rdcu) => fcu(rdcu),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,8 +186,8 @@ impl RegisterDataCompat {
|
|||||||
/// The id of the user key, which only the current format carries.
|
/// The id of the user key, which only the current format carries.
|
||||||
fn key_id(&self) -> Option<KeyId> {
|
fn key_id(&self) -> Option<KeyId> {
|
||||||
match self {
|
match self {
|
||||||
RegisterDataCompat::RegisterDataOld(_) => None,
|
Self::RegisterDataOld(_) => None,
|
||||||
RegisterDataCompat::RegisterDataCur(rdcu) => rdcu.master_password_unlock.contained_key_id.clone(),
|
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 {
|
if let Some(security_state) = &self.security_state {
|
||||||
required(Some(security_state.security_state.clone()), "SecurityState")?;
|
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.")
|
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 {
|
let Ok(data) = serde_json::from_value::<SetPasswordData>(data) else {
|
||||||
err_code!("Unexpected SetPasswordData format", Status::UnprocessableEntity.code)
|
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.")
|
err!("The field MasterPasswordHint must be a string with a maximum length of 50.")
|
||||||
}
|
}
|
||||||
let mut user = headers.user;
|
let mut user = headers.user;
|
||||||
@@ -1373,7 +1373,6 @@ fn validate_rotation_data(
|
|||||||
existing_sends: &[Send],
|
existing_sends: &[Send],
|
||||||
) -> EmptyResult {
|
) -> EmptyResult {
|
||||||
// Check that we're correctly rotating all the user's ciphers
|
// 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
|
let provided_cipher_ids = data
|
||||||
.account_data
|
.account_data
|
||||||
.ciphers
|
.ciphers
|
||||||
@@ -1381,44 +1380,38 @@ fn validate_rotation_data(
|
|||||||
.filter(|c| c.organization_id.is_none())
|
.filter(|c| c.organization_id.is_none())
|
||||||
.filter_map(|c| c.id.as_ref())
|
.filter_map(|c| c.id.as_ref())
|
||||||
.collect::<HashSet<&CipherId>>();
|
.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")
|
err!("All existing ciphers must be included in the rotation")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that we're correctly rotating all the user's folders
|
// 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 =
|
let provided_folder_ids =
|
||||||
data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
|
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")
|
err!("All existing folders must be included in the rotation")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that we're correctly rotating all the user's emergency access keys
|
// 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 =
|
let provided_emergency_access_ids =
|
||||||
data.unlock_data.emergency_access_unlock_data.iter().map(|ea| &ea.id).collect::<HashSet<&EmergencyAccessId>>();
|
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")
|
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
|
// 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
|
let provided_reset_password_ids = data
|
||||||
.unlock_data
|
.unlock_data
|
||||||
.organization_account_recovery_unlock_data
|
.organization_account_recovery_unlock_data
|
||||||
.iter()
|
.iter()
|
||||||
.map(|rp| &rp.organization_id)
|
.map(|rp| &rp.organization_id)
|
||||||
.collect::<HashSet<&OrganizationId>>();
|
.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")
|
err!("All existing reset password keys must be included in the rotation")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that we're correctly rotating all the user's sends
|
// 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>>();
|
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")
|
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.
|
/// Upstream's `[StringLength(max)]`, which counts UTF-16 code units.
|
||||||
fn validate_max_length(value: &str, max: usize, field: &str) -> EmptyResult {
|
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}."))
|
err!(format!("The field {field} must be a string with a maximum length of {max}."))
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -1544,7 +1537,7 @@ impl MasterPasswordUnlockData {
|
|||||||
if let Some(hint) = &self.master_password_hint {
|
if let Some(hint) = &self.master_password_hint {
|
||||||
validate_max_length(hint, 50, "MasterPasswordHint")?;
|
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'.")
|
err!("The field MasterPasswordSalt must be a string or array type with a maximum length of '256'.")
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -2194,7 +2187,7 @@ async fn password_hint(data: Json<PasswordHintData>, ip: ClientIp, conn: DbConn)
|
|||||||
use rand::{RngExt, rngs::SmallRng};
|
use rand::{RngExt, rngs::SmallRng};
|
||||||
let mut rng: SmallRng = rand::make_rng();
|
let mut rng: SmallRng = rand::make_rng();
|
||||||
let sleep_ms: u64 = rng.random_range(900..=1100);
|
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(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
err!(NO_HINT);
|
err!(NO_HINT);
|
||||||
@@ -2371,7 +2364,7 @@ impl<'r> FromRequest<'r> for KnownDevice {
|
|||||||
return Outcome::Error((Status::BadRequest, "X-Device-Identifier value is required"));
|
return Outcome::Error((Status::BadRequest, "X-Device-Identifier value is required"));
|
||||||
};
|
};
|
||||||
|
|
||||||
Outcome::Success(KnownDevice {
|
Outcome::Success(Self {
|
||||||
email,
|
email,
|
||||||
uuid,
|
uuid,
|
||||||
})
|
})
|
||||||
|
|||||||
+10
-18
@@ -1,7 +1,6 @@
|
|||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
use chrono::{NaiveDateTime, Utc};
|
use chrono::{NaiveDateTime, Utc};
|
||||||
use num_traits::ToPrimitive;
|
|
||||||
use rocket::{
|
use rocket::{
|
||||||
Route,
|
Route,
|
||||||
form::{Form, FromForm},
|
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;
|
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
|
// 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();
|
let ver_match = semver::VersionReq::parse(">=2024.12.0").unwrap();
|
||||||
ver_match.matches(&client_version.0)
|
ver_match.matches(&v.0)
|
||||||
} else {
|
});
|
||||||
false
|
|
||||||
};
|
|
||||||
if !show_ssh_keys {
|
if !show_ssh_keys {
|
||||||
ciphers.retain(|c| c.atype != 5);
|
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")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct CipherData {
|
pub struct CipherData {
|
||||||
// Id is optional as it is included only in bulk share
|
// Id is optional as it is included only in bulk share
|
||||||
@@ -341,8 +338,7 @@ pub struct CipherData {
|
|||||||
pub password_history: Option<Value>,
|
pub password_history: Option<Value>,
|
||||||
|
|
||||||
// These are used during key rotation
|
// These are used during key rotation
|
||||||
// 'Attachments' is unused, contains map of {id: filename}
|
#[cfg_attr(not(feature = "unsafe_test_mode"), expect(unused, reason = "Only read by the unsafe test seeder"))]
|
||||||
#[allow(dead_code)]
|
|
||||||
attachments: Option<Value>,
|
attachments: Option<Value>,
|
||||||
attachments2: Option<HashMap<AttachmentId, Attachments2Data>>,
|
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
|
/// Ref: https://bitwarden.com/help/article/policies/#personal-ownership
|
||||||
async fn enforce_personal_ownership_policy(data: Option<&CipherData>, headers: &Headers, conn: &DbConn) -> EmptyResult {
|
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 user_id = &headers.user.uuid;
|
||||||
let policy_type = OrgPolicyType::PersonalOwnership;
|
let policy_type = OrgPolicyType::PersonalOwnership;
|
||||||
if OrgPolicy::is_applicable_to_user(user_id, policy_type, None, conn).await {
|
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()) {
|
if data.ciphers.iter().any(|c| c.id.is_none() || c.organization_id.is_none()) {
|
||||||
err!("All Ciphers must have an Id and OrganizationId.")
|
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.")
|
err!("All ciphers must be for the same organization.")
|
||||||
}
|
}
|
||||||
if data.collection_ids.is_empty() {
|
if data.collection_ids.is_empty() {
|
||||||
@@ -1744,7 +1740,7 @@ async fn save_attachment(
|
|||||||
) -> Result<(Cipher, DbConn), crate::error::Error> {
|
) -> Result<(Cipher, DbConn), crate::error::Error> {
|
||||||
let data = data.into_inner();
|
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");
|
err!("Attachment data size overflow");
|
||||||
};
|
};
|
||||||
if size < 0 {
|
if size < 0 {
|
||||||
@@ -1791,7 +1787,7 @@ async fn save_attachment(
|
|||||||
err!("Invalid attachment size min")
|
err!("Invalid attachment size min")
|
||||||
};
|
};
|
||||||
|
|
||||||
if min_size <= size && size <= max_size {
|
if (min_size..=max_size).contains(&size) {
|
||||||
if size != attachment.file_size {
|
if size != attachment.file_size {
|
||||||
// Update the attachment with the actual file size.
|
// Update the attachment with the actual file size.
|
||||||
attachment.file_size = size;
|
attachment.file_size = size;
|
||||||
@@ -1799,7 +1795,6 @@ async fn save_attachment(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
attachment.delete(&conn).await.ok();
|
attachment.delete(&conn).await.ok();
|
||||||
|
|
||||||
err!(format!("Attachment size mismatch (expected within [{min_size}, {max_size}], got {size})"));
|
err!(format!("Attachment size mismatch (expected within [{min_size}, {max_size}], got {size})"));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -2844,10 +2839,7 @@ mod custom_role_tests {
|
|||||||
use crate::{
|
use crate::{
|
||||||
api::notifications::{WS_USERS, WebSocketUsers},
|
api::notifications::{WS_USERS, WebSocketUsers},
|
||||||
auth::ClientIp,
|
auth::ClientIp,
|
||||||
db::{
|
db::{models::Device, test_db},
|
||||||
models::{CustomPermission, Device, User},
|
|
||||||
test_db,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
use chrono::Datelike;
|
use chrono::Datelike;
|
||||||
use diesel::connection::SimpleConnection;
|
use diesel::connection::SimpleConnection;
|
||||||
|
|||||||
@@ -793,8 +793,7 @@ fn is_valid_request(
|
|||||||
requesting_user_id: &UserId,
|
requesting_user_id: &UserId,
|
||||||
requested_access_type: EmergencyAccessType,
|
requested_access_type: EmergencyAccessType,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
emergency_access.grantee_uuid.is_some()
|
emergency_access.grantee_uuid.as_ref().is_some_and(|u| u == requesting_user_id)
|
||||||
&& emergency_access.grantee_uuid.as_ref().unwrap() == requesting_user_id
|
|
||||||
&& emergency_access.status == EmergencyAccessStatus::RecoveryApproved as i32
|
&& emergency_access.status == EmergencyAccessStatus::RecoveryApproved as i32
|
||||||
&& emergency_access.atype == requested_access_type 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
|
// 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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -140,12 +140,10 @@ fn get_continuation_token(events_json: &[Value]) -> Option<&str> {
|
|||||||
// When the length of the vec equals the max page_size there probably is more data
|
// When the length of the vec equals the max page_size there probably is more data
|
||||||
// When it is less, then all events are loaded.
|
// When it is less, then all events are loaded.
|
||||||
#[expect(clippy::cast_possible_truncation, reason = "PAGE_SIZE fits within usize")]
|
#[expect(clippy::cast_possible_truncation, reason = "PAGE_SIZE fits within usize")]
|
||||||
if events_json.len() == Event::PAGE_SIZE as usize {
|
if events_json.len() == Event::PAGE_SIZE as usize
|
||||||
if let Some(last_event) = events_json.last() {
|
&& let Some(last_event) = events_json.last()
|
||||||
last_event["date"].as_str()
|
{
|
||||||
} else {
|
last_event["date"].as_str()
|
||||||
None
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -116,8 +116,8 @@ struct OrgData {
|
|||||||
key: String,
|
key: String,
|
||||||
name: String,
|
name: String,
|
||||||
keys: Option<OrgKeyData>,
|
keys: Option<OrgKeyData>,
|
||||||
#[allow(dead_code)]
|
#[expect(unused, reason = "Ignored, always use the same plan")]
|
||||||
plan_type: NumberOrString, // Ignored, always use the same plan
|
plan_type: NumberOrString,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
@@ -592,10 +592,11 @@ async fn post_bulk_access_collections(
|
|||||||
|
|
||||||
// As in Bitwarden, missing, repeated or unmanageable collections are Not Found. Invalid groups and members are
|
// As in Bitwarden, missing, repeated or unmanageable collections are Not Found. Invalid groups and members are
|
||||||
// checked after them and are a Bad Request.
|
// 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()
|
|
||||||
{
|
{
|
||||||
err_code!("One or more collections not found.", Status::NotFound.code)
|
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());
|
let mut collections = Vec::with_capacity(data.collection_ids.len());
|
||||||
@@ -694,11 +695,7 @@ async fn put_organization_collection_update(
|
|||||||
};
|
};
|
||||||
|
|
||||||
collection.name = data.name;
|
collection.name = data.name;
|
||||||
collection.external_id = match data.external_id {
|
collection.external_id = data.external_id.filter(|e| !e.trim().is_empty());
|
||||||
Some(external_id) if !external_id.trim().is_empty() => Some(external_id),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
collection.save(&conn).await?;
|
collection.save(&conn).await?;
|
||||||
|
|
||||||
log_event(
|
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() {
|
if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() {
|
||||||
err!("Group not found in Organization")
|
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?;
|
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() {
|
if Group::find_by_uuid_and_org(group_id, &org_id, &conn).await.is_none() {
|
||||||
err!("Group not found in Organization")
|
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?;
|
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
|
let user_collections: HashMap<CollectionId, Collection> = collections
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|c| {
|
.filter_map(|c| data.collection_ids.contains(&c.uuid).then(|| (c.uuid.clone(), c)))
|
||||||
if data.collection_ids.contains(&c.uuid) {
|
|
||||||
Some((c.uuid.clone(), c))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// Verify if all the collections requested exists and are writable for the user, else abort
|
// 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")
|
err!("Invalid or unsupported policy type")
|
||||||
};
|
};
|
||||||
|
|
||||||
let policy = match OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn).await {
|
let policy = OrgPolicy::find_by_org_and_type(&org_id, pol_type_enum, &conn)
|
||||||
Some(p) => p,
|
.await
|
||||||
None => OrgPolicy::new(org_id.clone(), pol_type_enum, false, "null".to_owned()),
|
.unwrap_or_else(|| OrgPolicy::new(org_id.clone(), pol_type_enum, false, "null".to_owned()));
|
||||||
};
|
|
||||||
|
|
||||||
Ok(Json(policy.to_json()))
|
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.
|
// 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 CONFIG.enforce_single_org_with_reset_pw_policy() {
|
||||||
if pol_type_enum == OrgPolicyType::ResetPassword && data.enabled {
|
if pol_type_enum == OrgPolicyType::ResetPassword && data.enabled {
|
||||||
let single_org_policy_enabled =
|
let single_org_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn)
|
||||||
match OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::SingleOrg, &conn).await {
|
.await
|
||||||
Some(p) => p.enabled,
|
.is_some_and(|p| p.enabled);
|
||||||
None => false,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !single_org_policy_enabled {
|
if !single_org_policy_enabled {
|
||||||
err!("Single Organization policy is not enabled. It is mandatory for this policy to be 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
|
// Also prevent the Single Org Policy to be disabled if the Reset Password policy is enabled
|
||||||
if pol_type_enum == OrgPolicyType::SingleOrg && !data.enabled {
|
if pol_type_enum == OrgPolicyType::SingleOrg && !data.enabled {
|
||||||
let reset_pw_policy_enabled =
|
let reset_pw_policy_enabled = OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::ResetPassword, &conn)
|
||||||
match OrgPolicy::find_by_org_and_type(&org_id, OrgPolicyType::ResetPassword, &conn).await {
|
.await
|
||||||
Some(p) => p.enabled,
|
.is_some_and(|p| p.enabled);
|
||||||
None => false,
|
|
||||||
};
|
|
||||||
|
|
||||||
if reset_pw_policy_enabled {
|
if reset_pw_policy_enabled {
|
||||||
err!("Account recovery policy is enabled. It is not allowed to disable this policy.")
|
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?;
|
group.save(conn).await?;
|
||||||
|
|
||||||
for col_selection in collections {
|
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?;
|
collection_group.save(&org_id, conn).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
for assigned_member in members {
|
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?;
|
user_entry.save(conn).await?;
|
||||||
|
|
||||||
log_event(
|
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)
|
let group_members: Vec<MembershipId> = GroupUser::find_by_group(&group_id, &org_id, &conn)
|
||||||
.await
|
.await
|
||||||
.iter()
|
.into_iter()
|
||||||
.map(|entry| entry.users_organizations_uuid.clone())
|
.map(|entry| entry.users_organizations_uuid)
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
Ok(Json(json!(group_members)))
|
Ok(Json(json!(group_members)))
|
||||||
@@ -3731,12 +3717,7 @@ async fn put_reset_password_enrollment(
|
|||||||
|
|
||||||
let reset_request = data.into_inner();
|
let reset_request = data.into_inner();
|
||||||
|
|
||||||
let reset_password_key = match reset_request.reset_password_key {
|
let reset_password_key = reset_request.reset_password_key.filter(|k| !k.is_empty());
|
||||||
None => None,
|
|
||||||
Some(ref key) if key.is_empty() => None,
|
|
||||||
Some(key) => Some(key),
|
|
||||||
};
|
|
||||||
|
|
||||||
if reset_password_key.is_none() && OrgPolicy::org_is_reset_password_auto_enroll(&org_id, &conn).await {
|
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");
|
err!("Reset password can't be withdrawn due to an enterprise policy");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ async fn ldap_import(data: Json<OrgImportData>, token: PublicToken, conn: DbConn
|
|||||||
|
|
||||||
for ext_id in &group_data.member_external_ids {
|
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 {
|
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?;
|
group_user.save(&conn).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,6 +237,6 @@ impl<'r> FromRequest<'r> for PublicToken {
|
|||||||
err_handler!("Token not issued for this client");
|
err_handler!("Token not issued for this client");
|
||||||
}
|
}
|
||||||
|
|
||||||
Outcome::Success(PublicToken(claims.client_sub))
|
Outcome::Success(Self(claims.client_sub))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+4
-14
@@ -1,7 +1,6 @@
|
|||||||
use std::{path::Path, sync::LazyLock, time::Duration};
|
use std::{path::Path, sync::LazyLock, time::Duration};
|
||||||
|
|
||||||
use chrono::{DateTime, TimeDelta, Utc};
|
use chrono::{DateTime, TimeDelta, Utc};
|
||||||
use num_traits::ToPrimitive;
|
|
||||||
use rocket::{
|
use rocket::{
|
||||||
form::Form,
|
form::Form,
|
||||||
fs::{NamedFile, TempFile},
|
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());
|
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.user_uuid = Some(user_id);
|
||||||
send.notes = data.notes;
|
send.notes = data.notes;
|
||||||
send.max_access_count = match data.max_access_count {
|
send.max_access_count = data.max_access_count.map(|m| m.into_i32()).transpose()?;
|
||||||
Some(m) => Some(m.into_i32()?),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
|
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
|
||||||
send.disabled = data.disabled;
|
send.disabled = data.disabled;
|
||||||
send.hide_email = data.hide_email;
|
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)]
|
#[derive(Deserialize)]
|
||||||
#[allow(non_snake_case)]
|
#[expect(non_snake_case, reason = "Bitwarden clients use this format")]
|
||||||
pub struct SendFileData {
|
pub struct SendFileData {
|
||||||
id: SendFileId,
|
id: SendFileId,
|
||||||
size: u64,
|
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));
|
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 {
|
let size = data.data.len();
|
||||||
err!("Send file size overflow.");
|
|
||||||
};
|
|
||||||
|
|
||||||
if size != send_data.size {
|
if size != send_data.size {
|
||||||
err!("Send file size does not match.", format!("Expected a file size of {} got {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.akey = data.key;
|
||||||
send.deletion_date = data.deletion_date.naive_utc();
|
send.deletion_date = data.deletion_date.naive_utc();
|
||||||
send.notes = data.notes;
|
send.notes = data.notes;
|
||||||
send.max_access_count = match data.max_access_count {
|
send.max_access_count = data.max_access_count.map(|m| m.into_i32()).transpose()?;
|
||||||
Some(m) => Some(m.into_i32()?),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
|
send.expiration_date = data.expiration_date.map(|d| d.naive_utc());
|
||||||
send.hide_email = data.hide_email;
|
send.hide_email = data.hide_email;
|
||||||
send.disabled = data.disabled;
|
send.disabled = data.disabled;
|
||||||
|
|||||||
@@ -116,10 +116,9 @@ pub async fn validate_totp_code(
|
|||||||
err!("Invalid TOTP secret")
|
err!("Invalid TOTP secret")
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut twofactor = match TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn).await {
|
let mut twofactor = TwoFactor::find_by_user_and_type(user_id, TwoFactorType::Authenticator, conn)
|
||||||
Some(tf) => tf,
|
.await
|
||||||
_ => TwoFactor::new(user_id.clone(), TwoFactorType::Authenticator, secret.to_owned()),
|
.unwrap_or_else(|| TwoFactor::new(user_id.clone(), TwoFactorType::Authenticator, secret.to_owned()));
|
||||||
};
|
|
||||||
|
|
||||||
// The amount of steps back and forward in time
|
// The amount of steps back and forward in time
|
||||||
// Also check if we need to disable time drifted TOTP codes.
|
// Also check if we need to disable time drifted TOTP codes.
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ enum DuoStatus {
|
|||||||
impl DuoStatus {
|
impl DuoStatus {
|
||||||
fn data(self) -> Option<DuoData> {
|
fn data(self) -> Option<DuoData> {
|
||||||
match self {
|
match self {
|
||||||
DuoStatus::Global(data) | DuoStatus::User(data) => Some(data),
|
Self::Global(data) | Self::User(data) => Some(data),
|
||||||
DuoStatus::Disabled(_) => None,
|
Self::Disabled(_) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -108,8 +108,8 @@ struct DuoClient {
|
|||||||
|
|
||||||
impl DuoClient {
|
impl DuoClient {
|
||||||
// Construct a new DuoClient
|
// Construct a new DuoClient
|
||||||
fn new(client_id: String, client_secret: String, api_host: String, redirect_uri: String) -> DuoClient {
|
fn new(client_id: String, client_secret: String, api_host: String, redirect_uri: String) -> Self {
|
||||||
DuoClient {
|
Self {
|
||||||
client_id,
|
client_id,
|
||||||
client_secret,
|
client_secret,
|
||||||
api_host,
|
api_host,
|
||||||
@@ -137,7 +137,7 @@ impl DuoClient {
|
|||||||
match jsonwebtoken::encode(
|
match jsonwebtoken::encode(
|
||||||
&Header::new(JWT_SIGNATURE_ALG),
|
&Header::new(JWT_SIGNATURE_ALG),
|
||||||
&jwt_payload,
|
&jwt_payload,
|
||||||
&EncodingKey::from_secret(self.client_secret.as_bytes()),
|
&EncodingKey::from_secret(self.client_secret.as_bytes())?,
|
||||||
) {
|
) {
|
||||||
Ok(token) => Ok(token),
|
Ok(token) => Ok(token),
|
||||||
Err(e) => err!(format!("Error encoding Duo JWT: {e:?}")),
|
Err(e) => err!(format!("Error encoding Duo JWT: {e:?}")),
|
||||||
@@ -157,10 +157,7 @@ impl DuoClient {
|
|||||||
Err(e) => return Err(e),
|
Err(e) => return Err(e),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut post_body = HashMap::new();
|
let post_body = HashMap::from([("client_assertion", token), ("client_id", self.client_id.clone())]);
|
||||||
post_body.insert("client_assertion", token);
|
|
||||||
post_body.insert("client_id", self.client_id.clone());
|
|
||||||
|
|
||||||
let res = match make_http_request(reqwest::Method::POST, &health_check_url)?
|
let res = match make_http_request(reqwest::Method::POST, &health_check_url)?
|
||||||
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
|
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
|
||||||
.form(&post_body)
|
.form(&post_body)
|
||||||
@@ -253,16 +250,14 @@ impl DuoClient {
|
|||||||
Err(e) => return Err(e),
|
Err(e) => return Err(e),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut post_body = HashMap::new();
|
let post_body = HashMap::from([
|
||||||
post_body.insert("grant_type", String::from("authorization_code"));
|
("grant_type", String::from("authorization_code")),
|
||||||
post_body.insert("code", String::from(duo_code));
|
("code", String::from(duo_code)),
|
||||||
|
// Must be the same URL that was supplied in the authorization request for the supplied duo_code
|
||||||
// Must be the same URL that was supplied in the authorization request for the supplied duo_code
|
("redirect_uri", self.redirect_uri.clone()),
|
||||||
post_body.insert("redirect_uri", self.redirect_uri.clone());
|
("client_assertion_type", String::from("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")),
|
||||||
|
("client_assertion", token),
|
||||||
post_body
|
]);
|
||||||
.insert("client_assertion_type", String::from("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
|
|
||||||
post_body.insert("client_assertion", token);
|
|
||||||
|
|
||||||
let res = match make_http_request(reqwest::Method::POST, &token_url)?
|
let res = match make_http_request(reqwest::Method::POST, &token_url)?
|
||||||
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
|
.header(header::USER_AGENT, "vaultwarden:Duo/2.0 (Rust)")
|
||||||
@@ -291,7 +286,7 @@ impl DuoClient {
|
|||||||
|
|
||||||
let token_data = match jsonwebtoken::decode::<IdTokenClaims>(
|
let token_data = match jsonwebtoken::decode::<IdTokenClaims>(
|
||||||
&response.id_token,
|
&response.id_token,
|
||||||
&DecodingKey::from_secret(self.client_secret.as_bytes()),
|
&DecodingKey::from_secret(self.client_secret.as_bytes())?,
|
||||||
&validation,
|
&validation,
|
||||||
) {
|
) {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
@@ -422,18 +417,14 @@ pub async fn validate_duo_login(
|
|||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> EmptyResult {
|
) -> EmptyResult {
|
||||||
// Result supplied to us by clients in the form "<authz code>|<state>"
|
// Result supplied to us by clients in the form "<authz code>|<state>"
|
||||||
let split: Vec<&str> = two_factor_token.split('|').collect();
|
let Some((code, state)) = two_factor_token.split_once('|').filter(|(_, state)| !state.contains('|')) else {
|
||||||
if split.len() != 2 {
|
|
||||||
err!(
|
err!(
|
||||||
"Invalid response length",
|
"Invalid response length",
|
||||||
ErrorEvent {
|
ErrorEvent {
|
||||||
event: EventType::UserFailedLogIn2fa
|
event: EventType::UserFailedLogIn2fa
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
let code = split[0];
|
|
||||||
let state = split[1];
|
|
||||||
|
|
||||||
let (ik, sk, host) = get_duo_keys_email(email, conn).await?;
|
let (ik, sk, host) = get_duo_keys_email(email, conn).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -54,18 +54,9 @@ async fn send_email_login(data: Json<SendEmailLoginData>, client_headers: Client
|
|||||||
crate::ratelimit::check_limit_login(&client_headers.ip.ip)?;
|
crate::ratelimit::check_limit_login(&client_headers.ip.ip)?;
|
||||||
|
|
||||||
// Get the user
|
// Get the user
|
||||||
let email = match &data.email {
|
let email = data.email.as_ref().filter(|e| !e.is_empty());
|
||||||
Some(email) if !email.is_empty() => Some(email),
|
let master_password_hash = data.master_password_hash.as_ref().filter(|h| !h.is_empty());
|
||||||
_ => None,
|
let auth_request_id = data.auth_request_id.as_ref().filter(|a| !a.is_empty());
|
||||||
};
|
|
||||||
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 user = if let Some(email) = email {
|
let user = if let Some(email) = email {
|
||||||
let Some(user) = User::find_by_mail(email, &conn).await else {
|
let Some(user) = User::find_by_mail(email, &conn).await else {
|
||||||
@@ -349,8 +340,8 @@ pub struct EmailTokenData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EmailTokenData {
|
impl EmailTokenData {
|
||||||
pub fn new(email: String, token: Option<String>) -> EmailTokenData {
|
pub fn new(email: String, token: Option<String>) -> Self {
|
||||||
EmailTokenData {
|
Self {
|
||||||
email,
|
email,
|
||||||
last_token: token,
|
last_token: token,
|
||||||
token_sent: Utc::now().timestamp(),
|
token_sent: Utc::now().timestamp(),
|
||||||
@@ -376,8 +367,8 @@ impl EmailTokenData {
|
|||||||
serde_json::to_string(&self).unwrap()
|
serde_json::to_string(&self).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_json(string: &str) -> Result<EmailTokenData, Error> {
|
pub fn from_json(string: &str) -> Result<Self, Error> {
|
||||||
let res: Result<EmailTokenData, serde_json::Error> = serde_json::from_str(string);
|
let res: Result<Self, serde_json::Error> = serde_json::from_str(string);
|
||||||
if let Ok(x) = res {
|
if let Ok(x) = res {
|
||||||
Ok(x)
|
Ok(x)
|
||||||
} else {
|
} 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.
|
/// Takes an email address and obscures it by replacing it with asterisks except two characters.
|
||||||
pub fn obscure_email(email: &str) -> String {
|
pub fn obscure_email(email: &str) -> String {
|
||||||
let split: Vec<&str> = email.rsplitn(2, '@').collect();
|
let Some((name, domain)) = email.rsplit_once('@') else {
|
||||||
|
return "*".repeat(email.chars().count());
|
||||||
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}")
|
|
||||||
};
|
};
|
||||||
|
|
||||||
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 {
|
pub async fn find_and_activate_email_2fa(user_id: &UserId, conn: &DbConn) -> EmptyResult {
|
||||||
@@ -431,7 +421,6 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_obscure_email_long() {
|
fn test_obscure_email_long() {
|
||||||
let email = "bytes@example.ext";
|
let email = "bytes@example.ext";
|
||||||
|
|
||||||
let result = obscure_email(email);
|
let result = obscure_email(email);
|
||||||
|
|
||||||
// Only first two characters should be visible.
|
// Only first two characters should be visible.
|
||||||
@@ -441,10 +430,37 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_obscure_email_short() {
|
fn test_obscure_email_short() {
|
||||||
let email = "byt@example.ext";
|
let email = "byt@example.ext";
|
||||||
|
|
||||||
let result = obscure_email(email);
|
let result = obscure_email(email);
|
||||||
|
|
||||||
// If it's smaller than 3 characters it should only show asterisks.
|
// If it's smaller than 3 characters it should only show asterisks.
|
||||||
assert_eq!(result, "***@example.ext");
|
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, "******************");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ use crate::{
|
|||||||
static WEBAUTHN: LazyLock<Webauthn> = LazyLock::new(|| {
|
static WEBAUTHN: LazyLock<Webauthn> = LazyLock::new(|| {
|
||||||
let domain = CONFIG.domain();
|
let domain = CONFIG.domain();
|
||||||
let domain_origin = CONFIG.domain_origin();
|
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 rp_origin = Url::parse(&domain_origin).unwrap();
|
||||||
|
|
||||||
let webauthn = WebauthnBuilder::new(&rp_id, &rp_origin)
|
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 removed: HashSet<Vec<u8>> = HashSet::new();
|
||||||
let mut migrated = false;
|
let mut migrated = false;
|
||||||
|
|
||||||
keys.retain(|key| {
|
keys.extract_if(.., |key| !retain(key)).for_each(|key| {
|
||||||
let retained = retain(key);
|
removed.insert(key.credential.cred_id().to_vec());
|
||||||
if !retained {
|
migrated |= key.migrated;
|
||||||
removed.insert(key.credential.cred_id().to_vec());
|
|
||||||
migrated = migrated || key.migrated;
|
|
||||||
}
|
|
||||||
retained
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if removed.is_empty() {
|
if removed.is_empty() {
|
||||||
|
|||||||
+149
-175
@@ -76,9 +76,6 @@ static CLIENT: LazyLock<Client> = LazyLock::new(|| {
|
|||||||
.expect("Failed to build client")
|
.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`
|
// 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.
|
// 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`
|
// 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_HREF: &[u8] = b"href";
|
||||||
const ATTR_SIZES: &[u8] = b"sizes";
|
const ATTR_SIZES: &[u8] = b"sizes";
|
||||||
|
|
||||||
let mut base_url = url.clone();
|
let mut base_href = None;
|
||||||
let mut icon_tags: Vec<Tag> = Vec::new();
|
let mut icon_tags = Vec::new();
|
||||||
for Ok(token) in dom {
|
for Ok(mut token) in dom {
|
||||||
let tag_name: &[u8] = &token.tag.name;
|
match token.tag.name.as_slice() {
|
||||||
match tag_name {
|
TAG_LINK => icon_tags.push(token.tag),
|
||||||
TAG_LINK => {
|
TAG_BASE if base_href.is_none() => {
|
||||||
icon_tags.push(token.tag);
|
base_href = token.tag.attributes.remove(ATTR_HREF);
|
||||||
}
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
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 {
|
for icon_tag in icon_tags {
|
||||||
if let Some(icon_href) = icon_tag.attributes.get(ATTR_HREF)
|
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) {
|
let sizes = icon_tag.attributes.get(ATTR_SIZES).map_or_default(|v| str::from_utf8(v).unwrap_or_default());
|
||||||
std::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
|
||||||
} else {
|
let priority = get_icon_priority(full_href.path(), sizes);
|
||||||
""
|
|
||||||
};
|
|
||||||
let priority = get_icon_priority(full_href.as_str(), sizes);
|
|
||||||
icons.push(Icon::new(priority, full_href.to_string()));
|
icons.push(Icon::new(priority, full_href.to_string()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -323,32 +311,26 @@ 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
|
// If we get an error that is not caused by the blacklist, we retry with HTTP
|
||||||
match get_page(&httpdomain).await {
|
match get_page(&httpdomain).await {
|
||||||
mut sub_resp @ Err(_) => {
|
mut sub_resp @ Err(_) => {
|
||||||
// When the domain is not an IP, and has more then one dot, remove all subdomains.
|
if domain.parse::<IpAddr>().is_err() {
|
||||||
let is_ip = domain.parse::<IpAddr>();
|
if let Some((dot, _)) = domain.rmatch_indices('.').nth(1) {
|
||||||
if is_ip.is_err() && domain.matches('.').count() > 1 {
|
// Use the last two labels when the domain has at least two dots.
|
||||||
let mut domain_parts = domain.split('.');
|
let base_domain = &domain[dot + 1..];
|
||||||
let base_domain = format!(
|
if get_valid_host(base_domain).is_ok() {
|
||||||
"{base}.{tld}",
|
let sslbase = format!("https://{base_domain}");
|
||||||
tld = domain_parts.next_back().unwrap(),
|
let httpbase = format!("http://{base_domain}");
|
||||||
base = domain_parts.next_back().unwrap()
|
debug!("[get_icon_url]: Trying without subdomains '{base_domain}'");
|
||||||
);
|
|
||||||
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;
|
sub_resp = get_page(&sslbase).or_else(|_| get_page(&httpbase)).await;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
let www_domain = format!("www.{domain}");
|
||||||
|
if get_valid_host(&www_domain).is_ok() {
|
||||||
|
let sslwww = format!("https://{www_domain}");
|
||||||
|
let httpwww = format!("http://{www_domain}");
|
||||||
|
debug!("[get_icon_url]: Trying with www. prefix '{www_domain}'");
|
||||||
|
|
||||||
// When the domain is not an IP, and has less then 2 dots, try to add www. infront of it.
|
sub_resp = get_page(&sslwww).or_else(|_| get_page(&httpwww)).await;
|
||||||
} else if is_ip.is_err() && domain.matches('.').count() < 2 {
|
}
|
||||||
let www_domain = format!("www.{domain}");
|
|
||||||
if get_valid_host(&www_domain).is_ok() {
|
|
||||||
let sslwww = format!("https://{www_domain}");
|
|
||||||
let httpwww = format!("http://{www_domain}");
|
|
||||||
debug!("[get_icon_url]: Trying with www. prefix '{www_domain}'");
|
|
||||||
|
|
||||||
sub_resp = get_page(&sslwww).or_else(|_| get_page(&httpwww)).await;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sub_resp
|
sub_resp
|
||||||
@@ -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())));
|
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.
|
// 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 limited_reader = stream_to_bytes_limit(content, 384 * 1024).await?;
|
||||||
|
let dom = Tokenizer::new_with_emitter(limited_reader.as_ref().to_reader(), FaviconEmitter::default());
|
||||||
let dom = Tokenizer::new_with_emitter(limited_reader.to_reader(), FaviconEmitter::default());
|
|
||||||
get_favicons_node(dom, &mut iconlist, &url);
|
get_favicons_node(dom, &mut iconlist, &url);
|
||||||
} else {
|
} else {
|
||||||
// Add the default favicon.ico to the list with just the given domain
|
// 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 {
|
fn get_icon_priority(href: &str, sizes: &str) -> u8 {
|
||||||
static PRIORITY_MAP: LazyLock<HashMap<&'static 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
|
// Check if there is a dimension set
|
||||||
let (width, height) = parse_sizes(sizes);
|
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)
|
/// let (width, height) = parse_sizes("32"); // (0, 0)
|
||||||
/// ```
|
/// ```
|
||||||
fn parse_sizes(sizes: &str) -> (u16, u16) {
|
fn parse_sizes(sizes: &str) -> (u16, u16) {
|
||||||
let mut width: u16 = 0;
|
static ICON_SIZE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(\d+)\D+(\d+)").unwrap());
|
||||||
let mut height: u16 = 0;
|
|
||||||
|
|
||||||
if !sizes.is_empty() {
|
ICON_SIZE_REGEX
|
||||||
match ICON_SIZE_REGEX.captures(sizes.trim()) {
|
.captures(sizes)
|
||||||
Some(dimensions) if dimensions.len() >= 3 => {
|
.and_then(|c| Some((c[1].parse::<u16>().ok()?, c[2].parse::<u16>().ok()?)))
|
||||||
width = dimensions[1].parse::<u16>().unwrap_or_default();
|
.unwrap_or((0, 0))
|
||||||
height = dimensions[2].parse::<u16>().unwrap_or_default();
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(width, height)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn download_icon(domain: &str) -> Result<(Bytes, Option<&str>), Error> {
|
async fn download_icon(domain: &str) -> Result<(Bytes, Option<&str>), Error> {
|
||||||
let icon_result = get_icon_url(domain).await?;
|
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();
|
let mut icons = icon_result.iconlist.iter().take(5).peekable();
|
||||||
while let Some(icon) = icons.next() {
|
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 {
|
let Ok(datauri) = data_url::DataUrl::process(&icon.href) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
// Check if we are able to decode the data uri
|
|
||||||
let mut body = BytesMut::new();
|
let mut body = BytesMut::new();
|
||||||
match datauri.decode::<_, ()>(|bytes| {
|
if datauri
|
||||||
body.extend_from_slice(bytes);
|
.decode::<_, ()>(|bytes| {
|
||||||
Ok(())
|
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
|
.is_err()
|
||||||
if body.len() >= 67 {
|
{
|
||||||
// Check if the icon type is allowed, else try an icon from the list.
|
debug!("Extracted icon from data:image uri is invalid");
|
||||||
icon_type = get_icon_type(&body);
|
continue;
|
||||||
if icon_type.is_none() {
|
|
||||||
debug!("Icon from {domain} data:image uri, is not a valid image type");
|
|
||||||
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 {
|
} else {
|
||||||
debug!("Trying {}", icon.href);
|
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 {
|
let res = match get_page_with_referer(&icon.href, &icon_result.referer).await {
|
||||||
Ok(r) => r,
|
Ok(r) => r,
|
||||||
Err(e) if icons.peek().is_none() => return Err(e),
|
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) => {
|
Err(e) => {
|
||||||
warn!("Unable to download icon: {e:?}");
|
warn!("Unable to download icon: {e:?}");
|
||||||
|
|
||||||
// Continue to next icon
|
|
||||||
continue;
|
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)
|
let Some(icon_type) = get_icon_type(&buffer) else {
|
||||||
|
debug!("Icon candidate for {domain} is not a valid image type");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
// Check if the icon type is allowed, else try another icon from the list.
|
// Validate SVG format early incase it is invalid, it will continue to the next icon in the list
|
||||||
icon_type = get_icon_type(&buffer);
|
if icon_type == "svg+xml" {
|
||||||
if icon_type.is_none() {
|
let mut svg_filter = Filter::new();
|
||||||
buffer.clear();
|
svg_filter.set_data_url_filter(data_url_filter::allow_standard_images);
|
||||||
debug!("Icon from {}, is not a valid image type", icon.href);
|
let mut sanitized_svg = Vec::new();
|
||||||
|
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;
|
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") {
|
|
||||||
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 {
|
|
||||||
buffer = sanitized_svg.into();
|
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>) {
|
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 get_icon_type(bytes: &[u8]) -> Option<&'static str> {
|
||||||
fn check_svg_after_xml_declaration(bytes: &[u8]) -> Option<&'static str> {
|
fn check_svg_after_xml_declaration(bytes: &[u8]) -> Option<&'static str> {
|
||||||
// Look for SVG tag within the first 1KB
|
// Look for SVG tag within the first 1KB
|
||||||
if let Ok(content) = std::str::from_utf8(&bytes[..bytes.len().min(1024)])
|
const SVG_MATCH: &[u8; 4] = b"<svg";
|
||||||
&& (content.contains("<svg") || content.contains("<SVG"))
|
let content = &bytes[..bytes.len().min(1024)];
|
||||||
{
|
// Even though XML is case-sensitive we will do a case insensitive match
|
||||||
return Some("svg+xml");
|
content.windows(SVG_MATCH.len()).any(|w| w.eq_ignore_ascii_case(SVG_MATCH)).then_some("svg+xml")
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Some details can be found here:
|
// Some details can be found here:
|
||||||
@@ -659,8 +614,7 @@ pub struct Jar(std::sync::RwLock<CookieStore>);
|
|||||||
|
|
||||||
impl reqwest::cookie::CookieStore for Jar {
|
impl reqwest::cookie::CookieStore for Jar {
|
||||||
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
|
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
|
||||||
use cookie::{Cookie as RawCookie, ParseError as RawCookieParseError};
|
use cookie::{Cookie as RawCookie, ParseError as RawCookieParseError, time::Duration};
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
let mut cookie_store = self.0.write().unwrap();
|
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| {
|
let cookies = cookie_headers.filter_map(|val| {
|
||||||
std::str::from_utf8(val.as_bytes())
|
str::from_utf8(val.as_bytes())
|
||||||
.map_err(RawCookieParseError::from)
|
.map_err(RawCookieParseError::from)
|
||||||
.and_then(RawCookie::parse)
|
.and_then(RawCookie::parse)
|
||||||
.map(|mut c| {
|
.map(|mut c| {
|
||||||
@@ -690,11 +644,15 @@ impl reqwest::cookie::CookieStore for Jar {
|
|||||||
|
|
||||||
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
|
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
|
||||||
let cookie_store = self.0.read().unwrap();
|
let cookie_store = self.0.read().unwrap();
|
||||||
let s = cookie_store
|
let mut s = String::new();
|
||||||
.get_request_values(url)
|
for (name, value) in cookie_store.get_request_values(url) {
|
||||||
.map(|(name, value)| format!("{name}={value}"))
|
if !s.is_empty() {
|
||||||
.collect::<Vec<_>>()
|
s.push_str("; ");
|
||||||
.join("; ");
|
}
|
||||||
|
s.push_str(name);
|
||||||
|
s.push('=');
|
||||||
|
s.push_str(value);
|
||||||
|
}
|
||||||
|
|
||||||
if s.is_empty() {
|
if s.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
@@ -736,34 +694,48 @@ struct FaviconEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FaviconEmitter {
|
impl FaviconEmitter {
|
||||||
fn flush_current_attribute(&mut self, emit_current_tag: bool) {
|
fn is_icon_rel(rel: &[u8]) -> bool {
|
||||||
const ATTR_HREF: &[u8] = b"href";
|
let mut has_icon = false;
|
||||||
const ATTR_REL: &[u8] = b"rel";
|
|
||||||
const TAG_LINK: &[u8] = b"link";
|
|
||||||
const TAG_BASE: &[u8] = b"base";
|
|
||||||
const TAG_HEAD: &[u8] = b"head";
|
|
||||||
|
|
||||||
if let Some(ref mut token) = self.current_token {
|
for keyword in rel.split(u8::is_ascii_whitespace) {
|
||||||
let tag_name: &[u8] = &token.tag.name;
|
if keyword.eq_ignore_ascii_case(b"mask-icon") {
|
||||||
|
return false;
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
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;
|
has_icon
|
||||||
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,
|
fn flush_current_attribute(&mut self, tag_complete: bool) {
|
||||||
TAG_LINK if emit_current_tag && tag_attr.contains_key(ATTR_REL) && tag_attr.contains_key(ATTR_HREF) => {
|
let Some(token) = &mut self.current_token else {
|
||||||
let rel_value =
|
return;
|
||||||
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;
|
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) {
|
fn init_attribute(&mut self) {
|
||||||
self.flush_current_attribute(false);
|
self.flush_current_attribute(false);
|
||||||
self.current_attribute = match &self.current_token {
|
self.current_attribute = self
|
||||||
Some(token) => {
|
.current_token
|
||||||
let tag_name: &[u8] = &token.tag.name;
|
.as_ref()
|
||||||
match tag_name {
|
.filter(|token| !token.closing && matches!(token.tag.name.as_slice(), b"link" | b"base"))
|
||||||
b"link" | b"head" | b"base" => Some(Default::default()),
|
.map(|_| Default::default());
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn push_attribute_name(&mut self, s: &[u8]) {
|
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 {
|
fn current_is_appropriate_end_tag_token(&mut self) -> bool {
|
||||||
match &self.current_token {
|
self.current_token
|
||||||
Some(token) if token.closing => !self.last_start_tag.is_empty() && self.last_start_tag == token.tag.name,
|
.as_ref()
|
||||||
_ => false,
|
.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
|
// We do not want and need these parts of the HTML document
|
||||||
// These will be skipped and ignored during the tokenization and iteration.
|
// These will be skipped and ignored during the tokenization and iteration.
|
||||||
fn emit_current_comment(&mut self) {}
|
fn emit_current_comment(&mut self) {}
|
||||||
fn emit_current_doctype(&mut self) {}
|
fn emit_current_doctype(&mut self) {}
|
||||||
|
fn emit_current_processing_instruction(&mut self) {}
|
||||||
fn emit_eof(&mut self) {}
|
fn emit_eof(&mut self) {}
|
||||||
fn emit_error(&mut self, _: html5gum::Error) {}
|
fn emit_error(&mut self, _: html5gum::Error) {}
|
||||||
fn emit_string(&mut self, _: &[u8]) {}
|
fn emit_string(&mut self, _: &[u8]) {}
|
||||||
fn init_comment(&mut self) {}
|
fn init_comment(&mut self) {}
|
||||||
fn init_doctype(&mut self) {}
|
fn init_doctype(&mut self) {}
|
||||||
|
fn init_processing_instruction(&mut self) {}
|
||||||
fn push_comment(&mut self, _: &[u8]) {}
|
fn push_comment(&mut self, _: &[u8]) {}
|
||||||
fn push_doctype_name(&mut self, _: &[u8]) {}
|
fn push_doctype_name(&mut self, _: &[u8]) {}
|
||||||
fn push_doctype_public_identifier(&mut self, _: &[u8]) {}
|
fn push_doctype_public_identifier(&mut self, _: &[u8]) {}
|
||||||
fn push_doctype_system_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_public_identifier(&mut self, _: &[u8]) {}
|
||||||
fn set_doctype_system_identifier(&mut self, _: &[u8]) {}
|
fn set_doctype_system_identifier(&mut self, _: &[u8]) {}
|
||||||
fn set_force_quirks(&mut self) {}
|
fn set_force_quirks(&mut self) {}
|
||||||
|
|||||||
+18
-23
@@ -467,9 +467,9 @@ async fn password_login(
|
|||||||
let now = Utc::now().naive_utc();
|
let now = Utc::now().naive_utc();
|
||||||
|
|
||||||
if user.verified_at.is_none() && CONFIG.mail_enabled() && CONFIG.signups_verify() {
|
if user.verified_at.is_none() && CONFIG.mail_enabled() && CONFIG.signups_verify() {
|
||||||
if user.last_verifying_at.is_none()
|
if user
|
||||||
|| now.signed_duration_since(user.last_verifying_at.unwrap()).num_seconds()
|
.last_verifying_at
|
||||||
> i64::from(CONFIG.signups_verify_resend_time())
|
.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());
|
let resend_limit = i32::from(CONFIG.signups_verify_resend_limit());
|
||||||
if resend_limit == 0 || user.login_verify_count < 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?;
|
TwoFactorIncomplete::mark_complete(&user.uuid, &device.uuid, conn).await?;
|
||||||
|
|
||||||
let remember = data.two_factor_remember.unwrap_or(0);
|
let remember = data.two_factor_remember.unwrap_or(0);
|
||||||
let two_factor = if !CONFIG.disable_2fa_remember() && remember == 1 {
|
Ok((!CONFIG.disable_2fa_remember() && remember == 1).then(|| device.refresh_twofactor_remember()))
|
||||||
Some(device.refresh_twofactor_remember())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
Ok(two_factor)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn selected_data(tf: Option<TwoFactor>) -> ApiResult<String> {
|
fn selected_data(tf: Option<TwoFactor>) -> ApiResult<String> {
|
||||||
@@ -1155,7 +1150,7 @@ async fn register_verification_email(
|
|||||||
use rand::{RngExt, rngs::SmallRng};
|
use rand::{RngExt, rngs::SmallRng};
|
||||||
let mut rng: SmallRng = rand::make_rng();
|
let mut rng: SmallRng = rand::make_rng();
|
||||||
let sleep_ms: u64 = rng.random_range(900..=1100);
|
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 {
|
} else {
|
||||||
mail::send_register_verify_email(&data.email, &token).await?;
|
mail::send_register_verify_email(&data.email, &token).await?;
|
||||||
}
|
}
|
||||||
@@ -1233,10 +1228,10 @@ struct ConnectData {
|
|||||||
#[field(name = uncased("device_type"))]
|
#[field(name = uncased("device_type"))]
|
||||||
#[field(name = uncased("devicetype"))]
|
#[field(name = uncased("devicetype"))]
|
||||||
device_type: Option<String>,
|
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("device_push_token"))]
|
||||||
#[field(name = uncased("devicepushtoken"))]
|
#[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
|
// Needed for two-factor auth
|
||||||
#[field(name = uncased("two_factor_provider"))]
|
#[field(name = uncased("two_factor_provider"))]
|
||||||
@@ -1283,8 +1278,8 @@ fn prevalidate() -> JsonResult {
|
|||||||
const SSO_BINDING_COOKIE: &str = "VW_SSO_BINDING";
|
const SSO_BINDING_COOKIE: &str = "VW_SSO_BINDING";
|
||||||
|
|
||||||
#[get("/connect/oidc-signin?<code>&<state>", rank = 1)]
|
#[get("/connect/oidc-signin?<code>&<state>", rank = 1)]
|
||||||
async fn oidcsignin(code: OIDCCode, state: String, cookies: &CookieJar<'_>, mut conn: DbConn) -> ApiResult<Redirect> {
|
async fn oidcsignin(code: OIDCCode, state: String, cookies: &CookieJar<'_>, conn: DbConn) -> ApiResult<Redirect> {
|
||||||
oidcsignin_redirect(state, code, None, cookies, &mut conn).await
|
oidcsignin_redirect(state, code, None, cookies, &conn).await
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bitwarden client appear to only care for code and state
|
// Bitwarden client appear to only care for code and state
|
||||||
@@ -1296,7 +1291,7 @@ async fn oidcsignin_error(
|
|||||||
error: String,
|
error: String,
|
||||||
error_description: Option<String>,
|
error_description: Option<String>,
|
||||||
cookies: &CookieJar<'_>,
|
cookies: &CookieJar<'_>,
|
||||||
mut conn: DbConn,
|
conn: DbConn,
|
||||||
) -> ApiResult<Redirect> {
|
) -> ApiResult<Redirect> {
|
||||||
oidcsignin_redirect(
|
oidcsignin_redirect(
|
||||||
state.clone(),
|
state.clone(),
|
||||||
@@ -1306,7 +1301,7 @@ async fn oidcsignin_error(
|
|||||||
error_description,
|
error_description,
|
||||||
}),
|
}),
|
||||||
cookies,
|
cookies,
|
||||||
&mut conn,
|
&conn,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -1319,7 +1314,7 @@ async fn oidcsignin_redirect(
|
|||||||
code: OIDCCode,
|
code: OIDCCode,
|
||||||
error: Option<OIDCCodeResponseError>,
|
error: Option<OIDCCodeResponseError>,
|
||||||
cookies: &CookieJar<'_>,
|
cookies: &CookieJar<'_>,
|
||||||
conn: &mut DbConn,
|
conn: &DbConn,
|
||||||
) -> ApiResult<Redirect> {
|
) -> ApiResult<Redirect> {
|
||||||
let state = sso::decode_state(&base64_state)?;
|
let state = sso::decode_state(&base64_state)?;
|
||||||
|
|
||||||
@@ -1367,18 +1362,18 @@ struct AuthorizeData {
|
|||||||
#[field(name = uncased("redirect_uri"))]
|
#[field(name = uncased("redirect_uri"))]
|
||||||
#[field(name = uncased("redirecturi"))]
|
#[field(name = uncased("redirecturi"))]
|
||||||
redirect_uri: String,
|
redirect_uri: String,
|
||||||
#[allow(unused)]
|
#[expect(unused)]
|
||||||
response_type: Option<String>,
|
response_type: Option<String>,
|
||||||
#[allow(unused)]
|
#[expect(unused)]
|
||||||
scope: Option<String>,
|
scope: Option<String>,
|
||||||
state: OIDCState,
|
state: OIDCState,
|
||||||
code_challenge: OIDCCodeChallenge,
|
code_challenge: OIDCCodeChallenge,
|
||||||
code_challenge_method: String,
|
code_challenge_method: String,
|
||||||
#[allow(unused)]
|
#[expect(unused)]
|
||||||
response_mode: Option<String>,
|
response_mode: Option<String>,
|
||||||
#[allow(unused)]
|
#[expect(unused)]
|
||||||
domain_hint: Option<String>,
|
domain_hint: Option<String>,
|
||||||
#[allow(unused)]
|
#[expect(unused)]
|
||||||
#[field(name = uncased("ssoToken"))]
|
#[field(name = uncased("ssoToken"))]
|
||||||
sso_token: Option<String>,
|
sso_token: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -1410,7 +1405,7 @@ async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure,
|
|||||||
cookies.add(
|
cookies.add(
|
||||||
Cookie::build((SSO_BINDING_COOKIE, binding_token))
|
Cookie::build((SSO_BINDING_COOKIE, binding_token))
|
||||||
.path(format!("{}/identity/connect/", CONFIG.domain_path()))
|
.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
|
.same_site(SameSite::Lax) // Lax is needed because the IdP runs on a different FQDN
|
||||||
.http_only(true)
|
.http_only(true)
|
||||||
.secure(secure.https)
|
.secure(secure.https)
|
||||||
|
|||||||
+1
-1
@@ -120,7 +120,7 @@ async fn master_password_policy(user: &User, conn: &DbConn) -> Value {
|
|||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
} else if CONFIG.sso_enabled() {
|
} 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 {
|
} else {
|
||||||
json!({})
|
json!({})
|
||||||
};
|
};
|
||||||
|
|||||||
+24
-25
@@ -4,6 +4,7 @@ use std::{
|
|||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
use chrono::{NaiveDateTime, Utc};
|
use chrono::{NaiveDateTime, Utc};
|
||||||
use rmpv::Value;
|
use rmpv::Value;
|
||||||
use rocket::{Route, futures::StreamExt};
|
use rocket::{Route, futures::StreamExt};
|
||||||
@@ -212,7 +213,7 @@ fn websockets_hub<'r>(
|
|||||||
if last_received.elapsed() > WS_CLIENT_TIMEOUT {
|
if last_received.elapsed() > WS_CLIENT_TIMEOUT {
|
||||||
break;
|
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 {
|
if last_received.elapsed() > WS_CLIENT_TIMEOUT {
|
||||||
break;
|
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
|
// Websockets server
|
||||||
//
|
//
|
||||||
|
|
||||||
fn serialize(val: &Value) -> Vec<u8> {
|
fn serialize(val: &Value) -> Bytes {
|
||||||
use rmpv::encode::write_value;
|
use rmpv::encode::write_value;
|
||||||
|
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
@@ -335,7 +336,7 @@ fn serialize(val: &Value) -> Vec<u8> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
len_buf.append(&mut buf);
|
len_buf.append(&mut buf);
|
||||||
len_buf
|
len_buf.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_date(date: NaiveDateTime) -> Value {
|
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 RECORD_SEPARATOR: u8 = 0x1e;
|
||||||
const INITIAL_RESPONSE: [u8; 3] = [0x7b, 0x7d, RECORD_SEPARATOR]; // {, }, <RS>
|
const INITIAL_RESPONSE: Bytes = Bytes::from_static(&[0x7b, 0x7d, RECORD_SEPARATOR]); // {, }, <RS>
|
||||||
const PING: [u8; 3] = [0x02, 0x91, 0x06];
|
const PING: Bytes = Bytes::from_static(&[0x02, 0x91, 0x06]);
|
||||||
|
|
||||||
#[derive(Deserialize, Copy, Clone, Eq, PartialEq)]
|
#[derive(Deserialize, Copy, Clone, Eq, PartialEq)]
|
||||||
struct InitialMessage<'a> {
|
struct InitialMessage<'a> {
|
||||||
@@ -380,10 +381,10 @@ pub struct WebSocketUsers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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()) {
|
if let Some(user) = self.map.get(user_id.as_ref()).map(|v| v.clone()) {
|
||||||
for (_, sender) in &user {
|
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}");
|
error!("Error sending WS update {e}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -427,13 +428,12 @@ impl WebSocketUsers {
|
|||||||
if *NOTIFICATIONS_DISABLED {
|
if *NOTIFICATIONS_DISABLED {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let acting_device_id = acting_device.map(|d| d.uuid.clone());
|
|
||||||
let mut payload =
|
let mut payload =
|
||||||
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))];
|
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))];
|
||||||
if let Some(reason) = reason {
|
if let Some(reason) = reason {
|
||||||
payload.push(("Reason".into(), (reason as i32).into()));
|
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() {
|
if CONFIG.enable_websocket() {
|
||||||
self.send_update(&user.uuid, &data).await;
|
self.send_update(&user.uuid, &data).await;
|
||||||
@@ -456,7 +456,7 @@ impl WebSocketUsers {
|
|||||||
("RevisionDate".into(), serialize_date(folder.updated_at)),
|
("RevisionDate".into(), serialize_date(folder.updated_at)),
|
||||||
],
|
],
|
||||||
ut,
|
ut,
|
||||||
Some(device.uuid.clone()),
|
Some(&device.uuid),
|
||||||
);
|
);
|
||||||
|
|
||||||
if CONFIG.enable_websocket() {
|
if CONFIG.enable_websocket() {
|
||||||
@@ -503,7 +503,7 @@ impl WebSocketUsers {
|
|||||||
("RevisionDate".into(), revision_date),
|
("RevisionDate".into(), revision_date),
|
||||||
],
|
],
|
||||||
ut,
|
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() {
|
if CONFIG.enable_websocket() {
|
||||||
@@ -559,7 +559,7 @@ impl WebSocketUsers {
|
|||||||
let data = create_update(
|
let data = create_update(
|
||||||
vec![("Id".into(), auth_request_uuid.to_owned().into()), ("UserId".into(), user_id.to_string().into())],
|
vec![("Id".into(), auth_request_uuid.to_owned().into()), ("UserId".into(), user_id.to_string().into())],
|
||||||
UpdateType::AuthRequest,
|
UpdateType::AuthRequest,
|
||||||
Some(device.uuid.clone()),
|
Some(&device.uuid),
|
||||||
);
|
);
|
||||||
if CONFIG.enable_websocket() {
|
if CONFIG.enable_websocket() {
|
||||||
self.send_update(user_id, &data).await;
|
self.send_update(user_id, &data).await;
|
||||||
@@ -584,7 +584,7 @@ impl WebSocketUsers {
|
|||||||
let data = create_update(
|
let data = create_update(
|
||||||
vec![("Id".into(), auth_request_id.to_string().into()), ("UserId".into(), user_id.to_string().into())],
|
vec![("Id".into(), auth_request_id.to_string().into()), ("UserId".into(), user_id.to_string().into())],
|
||||||
UpdateType::AuthRequestResponse,
|
UpdateType::AuthRequestResponse,
|
||||||
Some(device.uuid.clone()),
|
Some(&device.uuid),
|
||||||
);
|
);
|
||||||
if CONFIG.enable_websocket() {
|
if CONFIG.enable_websocket() {
|
||||||
self.send_update(user_id, &data).await;
|
self.send_update(user_id, &data).await;
|
||||||
@@ -615,23 +615,22 @@ impl AnonymousWebSocketSubscriptions {
|
|||||||
|
|
||||||
/// Releases a slot taken by `try_reserve`.
|
/// Releases a slot taken by `try_reserve`.
|
||||||
fn release(&self, addr: IpAddr) {
|
fn release(&self, addr: IpAddr) {
|
||||||
let empty = if let Some(mut count) = self.connections.get_mut(&addr) {
|
let empty = self.connections.get_mut(&addr).is_some_and(|mut c| {
|
||||||
*count = count.saturating_sub(1);
|
*c = c.saturating_sub(1);
|
||||||
*count == 0
|
*c == 0
|
||||||
} else {
|
});
|
||||||
false
|
|
||||||
};
|
|
||||||
// Only remove once the guard above is dropped, otherwise this deadlocks.
|
// Only remove once the guard above is dropped, otherwise this deadlocks.
|
||||||
if empty {
|
if empty {
|
||||||
self.connections.remove_if(&addr, |_, count| *count == 0);
|
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.
|
// 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 {
|
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}");
|
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;
|
use rmpv::Value as V;
|
||||||
|
|
||||||
let value = V::Array(vec![
|
let value = V::Array(vec![
|
||||||
@@ -683,7 +682,7 @@ fn create_update(payload: Vec<(Value, Value)>, ut: UpdateType, acting_device_id:
|
|||||||
serialize(&value)
|
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;
|
use rmpv::Value as V;
|
||||||
|
|
||||||
let value = V::Array(vec![
|
let value = V::Array(vec![
|
||||||
|
|||||||
+32
-31
@@ -43,12 +43,12 @@ use crate::{
|
|||||||
|
|
||||||
const JWT_ALGORITHM: Algorithm = Algorithm::RS256;
|
const JWT_ALGORITHM: Algorithm = Algorithm::RS256;
|
||||||
|
|
||||||
// Limit when BitWarden consider the token as expired
|
// Limit when Bitwarden consider the token as expired
|
||||||
pub static BW_EXPIRATION: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_minutes(5).unwrap());
|
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 DEFAULT_REFRESH_VALIDITY: TimeDelta = TimeDelta::try_days(30).unwrap();
|
||||||
pub static MOBILE_REFRESH_VALIDITY: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_days(90).unwrap());
|
pub static MOBILE_REFRESH_VALIDITY: TimeDelta = TimeDelta::try_days(90).unwrap();
|
||||||
pub static DEFAULT_ACCESS_VALIDITY: LazyLock<TimeDelta> = LazyLock::new(|| TimeDelta::try_hours(2).unwrap());
|
pub static DEFAULT_ACCESS_VALIDITY: TimeDelta = TimeDelta::try_hours(2).unwrap();
|
||||||
static JWT_HEADER: LazyLock<Header> = LazyLock::new(|| Header::new(JWT_ALGORITHM));
|
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()));
|
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 {
|
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 {
|
} else {
|
||||||
let rsa_key = Rsa::generate(2048)?;
|
let rsa_key = Rsa::generate(2048)?;
|
||||||
let priv_key_buffer = rsa_key.private_key_to_pem()?;
|
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 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();
|
// 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.");
|
warn!("Raise access_token lifetime to more than 5min.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,7 +287,7 @@ impl LoginJwtClaims {
|
|||||||
sstamp: user.security_stamp.clone(),
|
sstamp: user.security_stamp.clone(),
|
||||||
device: device.uuid.clone(),
|
device: device.uuid.clone(),
|
||||||
devicetype: DeviceType::from_i32(device.atype).to_string(),
|
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,
|
scope,
|
||||||
amr: vec!["Application".into()],
|
amr: vec!["Application".into()],
|
||||||
}
|
}
|
||||||
@@ -298,7 +299,7 @@ impl LoginJwtClaims {
|
|||||||
device,
|
device,
|
||||||
user,
|
user,
|
||||||
time_now.timestamp(),
|
time_now.timestamp(),
|
||||||
(time_now + *DEFAULT_ACCESS_VALIDITY).timestamp(),
|
(time_now + DEFAULT_ACCESS_VALIDITY).timestamp(),
|
||||||
auth_method.scope_vec(),
|
auth_method.scope_vec(),
|
||||||
client_id,
|
client_id,
|
||||||
time_now,
|
time_now,
|
||||||
@@ -623,7 +624,7 @@ impl<'r> FromRequest<'r> for Host {
|
|||||||
format!("{protocol}://{host}")
|
format!("{protocol}://{host}")
|
||||||
};
|
};
|
||||||
|
|
||||||
Outcome::Success(Host {
|
Outcome::Success(Self {
|
||||||
host,
|
host,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -654,7 +655,7 @@ impl<'r> FromRequest<'r> for ClientHeaders {
|
|||||||
let client_version =
|
let client_version =
|
||||||
request.headers().get_one("Bitwarden-Client-Version").and_then(|v| semver::Version::parse(v).ok());
|
request.headers().get_one("Bitwarden-Client-Version").and_then(|v| semver::Version::parse(v).ok());
|
||||||
|
|
||||||
Outcome::Success(ClientHeaders {
|
Outcome::Success(Self {
|
||||||
device_type,
|
device_type,
|
||||||
ip,
|
ip,
|
||||||
client_version,
|
client_version,
|
||||||
@@ -723,7 +724,7 @@ impl<'r> FromRequest<'r> for Headers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Outcome::Success(Headers {
|
Outcome::Success(Self {
|
||||||
host,
|
host,
|
||||||
device,
|
device,
|
||||||
user,
|
user,
|
||||||
@@ -789,7 +790,7 @@ impl<'r> FromRequest<'r> for OrgIdGuard {
|
|||||||
|
|
||||||
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||||
match get_org_id(request) {
|
match get_org_id(request) {
|
||||||
Some(_) => Outcome::Success(OrgIdGuard),
|
Some(_) => Outcome::Success(Self),
|
||||||
None => Outcome::Forward(rocket::http::Status::NotFound),
|
None => Outcome::Forward(rocket::http::Status::NotFound),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1065,8 +1066,8 @@ macro_rules! collection_headers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<$name> for Headers {
|
impl From<$name> for Headers {
|
||||||
fn from(h: $name) -> Headers {
|
fn from(h: $name) -> Self {
|
||||||
Headers {
|
Self {
|
||||||
host: h.host,
|
host: h.host,
|
||||||
device: h.device,
|
device: h.device,
|
||||||
user: h.user,
|
user: h.user,
|
||||||
@@ -1132,8 +1133,8 @@ impl<'r> FromRequest<'r> for ManagerHeadersLoose {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<ManagerHeadersLoose> for Headers {
|
impl From<ManagerHeadersLoose> for Headers {
|
||||||
fn from(h: ManagerHeadersLoose) -> Headers {
|
fn from(h: ManagerHeadersLoose) -> Self {
|
||||||
Headers {
|
Self {
|
||||||
host: h.host,
|
host: h.host,
|
||||||
device: h.device,
|
device: h.device,
|
||||||
user: h.user,
|
user: h.user,
|
||||||
@@ -1147,7 +1148,7 @@ impl CollectionDeleteHeaders {
|
|||||||
h: ManagerHeadersLoose,
|
h: ManagerHeadersLoose,
|
||||||
collections: &Vec<CollectionId>,
|
collections: &Vec<CollectionId>,
|
||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> Result<CollectionDeleteHeaders, Error> {
|
) -> Result<Self, Error> {
|
||||||
let is_custom = h.membership.has_type(MembershipType::Custom) && custom_roles_enabled();
|
let is_custom = h.membership.has_type(MembershipType::Custom) && custom_roles_enabled();
|
||||||
for col_id in collections {
|
for col_id in collections {
|
||||||
if uuid::Uuid::parse_str(col_id.as_ref()).is_err() {
|
if uuid::Uuid::parse_str(col_id.as_ref()).is_err() {
|
||||||
@@ -1164,7 +1165,7 @@ impl CollectionDeleteHeaders {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(CollectionDeleteHeaders {
|
Ok(Self {
|
||||||
host: h.host,
|
host: h.host,
|
||||||
device: h.device,
|
device: h.device,
|
||||||
user: h.user,
|
user: h.user,
|
||||||
@@ -1229,8 +1230,8 @@ impl<'r> FromRequest<'r> for OrgMemberHeaders {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<OrgMemberHeaders> for Headers {
|
impl From<OrgMemberHeaders> for Headers {
|
||||||
fn from(h: OrgMemberHeaders) -> Headers {
|
fn from(h: OrgMemberHeaders) -> Self {
|
||||||
Headers {
|
Self {
|
||||||
host: h.host,
|
host: h.host,
|
||||||
device: h.device,
|
device: h.device,
|
||||||
user: h.user,
|
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> {
|
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;
|
let mut client_ip = None;
|
||||||
for entry in entries.into_iter().rev() {
|
for entry in entries {
|
||||||
let Ok(ip) = entry.parse() else {
|
let Ok(ip) = entry.parse() else {
|
||||||
warn!("'{header}' header is malformed: {entry}");
|
warn!("'{header}' header is malformed: {entry}");
|
||||||
break;
|
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());
|
let ip = ip.or(remote).unwrap_or_else(|| "0.0.0.0".parse().unwrap());
|
||||||
|
|
||||||
Outcome::Success(ClientIp {
|
Outcome::Success(Self {
|
||||||
ip,
|
ip,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1352,7 +1353,7 @@ impl<'r> FromRequest<'r> for Secure {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Outcome::Success(Secure {
|
Outcome::Success(Self {
|
||||||
https: protocol == "https",
|
https: protocol == "https",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1398,7 +1399,7 @@ impl<'r> FromRequest<'r> for ClientVersion {
|
|||||||
err_handler!("Invalid Bitwarden-Client-Version header provided")
|
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 {
|
impl AuthMethod {
|
||||||
pub fn scope(&self) -> String {
|
pub fn scope(&self) -> String {
|
||||||
match self {
|
match self {
|
||||||
AuthMethod::OrgApiKey => "api.organization".to_owned(),
|
Self::OrgApiKey => "api.organization".to_owned(),
|
||||||
AuthMethod::UserApiKey => "api".to_owned(),
|
Self::UserApiKey => "api".to_owned(),
|
||||||
AuthMethod::Password | AuthMethod::Sso => "api offline_access".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 access_claims = LoginJwtClaims::default(device, user, &sub, client_id);
|
||||||
|
|
||||||
let validity = if device.is_mobile() {
|
let validity = if device.is_mobile() {
|
||||||
*MOBILE_REFRESH_VALIDITY
|
MOBILE_REFRESH_VALIDITY
|
||||||
} else {
|
} else {
|
||||||
*DEFAULT_REFRESH_VALIDITY
|
DEFAULT_REFRESH_VALIDITY
|
||||||
};
|
};
|
||||||
|
|
||||||
let refresh_claims = RefreshJwtClaims {
|
let refresh_claims = RefreshJwtClaims {
|
||||||
|
|||||||
+4
-4
@@ -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!({
|
let err = json!({
|
||||||
"kind": "expected_server",
|
"kind": "expected_server",
|
||||||
"error": "invalid_request",
|
"error": "invalid_request",
|
||||||
@@ -55,7 +55,7 @@ impl SendTokens {
|
|||||||
Err(Error::new_msg(msg).with_kind(ErrorKind::Json(err)).silent())
|
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!({
|
let err = json!({
|
||||||
"kind": "expected_server",
|
"kind": "expected_server",
|
||||||
"error": "invalid_grant",
|
"error": "invalid_grant",
|
||||||
@@ -70,7 +70,7 @@ impl SendTokens {
|
|||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
ip: &ClientIp,
|
ip: &ClientIp,
|
||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> ApiResult<SendTokens> {
|
) -> ApiResult<Self> {
|
||||||
let Some(send_id) = Self::as_send_id(access_id) else {
|
let Some(send_id) = Self::as_send_id(access_id) else {
|
||||||
return Self::invalid_error(
|
return Self::invalid_error(
|
||||||
&format!("Can't convert {}", access_id.escape_debug()),
|
&format!("Can't convert {}", access_id.escape_debug()),
|
||||||
@@ -140,7 +140,7 @@ impl<'r> FromRequest<'r> for SendHeaders {
|
|||||||
err_handler!("Invalid claim")
|
err_handler!("Invalid claim")
|
||||||
};
|
};
|
||||||
|
|
||||||
Outcome::Success(SendHeaders {
|
Outcome::Success(Self {
|
||||||
send_id: claims.sub.into(),
|
send_id: claims.sub.into(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-32
@@ -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 {
|
enum Field {
|
||||||
$($(
|
$($(
|
||||||
$name,
|
$name,
|
||||||
@@ -362,7 +362,6 @@ macro_rules! make_config {
|
|||||||
elements: Vec<ElementData>,
|
elements: Vec<ElementData>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(unused)]
|
|
||||||
impl Config {
|
impl Config {
|
||||||
$($(
|
$($(
|
||||||
$(#[doc = $doc])+
|
$(#[doc = $doc])+
|
||||||
@@ -479,13 +478,11 @@ macro_rules! make_config {
|
|||||||
let mut json = serde_json::Map::new();
|
let mut json = serde_json::Map::new();
|
||||||
$($(
|
$($(
|
||||||
json.insert(String::from(stringify!($name)), make_config! { @supportstr $name, cfg.$name, $ty, $none_action });
|
json.insert(String::from(stringify!($name)), make_config! { @supportstr $name, cfg.$name, $ty, $none_action });
|
||||||
)+)+;
|
)+)+
|
||||||
// Loop through all privacy sensitive keys and mask them
|
// Loop through all privacy sensitive keys and mask them
|
||||||
for mask_key in PRIVACY_CONFIG {
|
for mask_key in PRIVACY_CONFIG {
|
||||||
if let Some(value) = json.get_mut(*mask_key) {
|
if let Some(value) = json.get_mut(*mask_key) && let Some(s) = value.as_str() {
|
||||||
if let Some(s) = value.as_str() {
|
*value = privacy_mask(s).into();
|
||||||
*value = privacy_mask(s).into();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
json
|
json
|
||||||
@@ -693,7 +690,7 @@ make_config! {
|
|||||||
/// Set to the string "none" (without quotes), to disable any headers and just use the remote IP
|
/// 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();
|
ip_header: String, true, def, "X-Real-IP".to_owned();
|
||||||
/// Internal IP header property, used to avoid recomputing each time
|
/// 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
|
/// 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.
|
/// 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
|
/// 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;
|
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}.",));
|
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}.",));
|
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.
|
/// Extracts the path from a URL.
|
||||||
/// All trailing '/' chars are trimmed, even if the path is a lone '/'.
|
/// All trailing '/' chars are trimmed, even if the path is a lone '/'.
|
||||||
fn extract_url_path(url: &str) -> String {
|
fn extract_url_path(url: &str) -> String {
|
||||||
match Url::parse(url) {
|
Url::parse(url).map_or_default(|u| u.path().trim_end_matches('/').to_owned())
|
||||||
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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_smtp_img_src(embed_images: bool, domain: &str) -> String {
|
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 {
|
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.
|
// 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.
|
// 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('{') {
|
let csp_string = icon_service_url.split_once('{').map_or_default(|(c, _)| c.to_owned());
|
||||||
Some((c, _)) => c.to_owned(),
|
|
||||||
None => String::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Because Google does a second redirect to there gstatic.com domain, we need to add an extra csp string.
|
// Because Google does a second redirect to there gstatic.com domain, we need to add an extra csp string.
|
||||||
match icon_service {
|
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() {
|
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.");
|
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();
|
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 "off".to_owned();
|
||||||
}
|
}
|
||||||
// Return the default `starttls` in all other cases
|
// Return the default `starttls` in all other cases
|
||||||
@@ -1566,7 +1554,7 @@ impl Config {
|
|||||||
validate_config(&config, false)?;
|
validate_config(&config, false)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Config {
|
Ok(Self {
|
||||||
inner: RwLock::new(Inner {
|
inner: RwLock::new(Inner {
|
||||||
rocket_shutdown_handle: None,
|
rocket_shutdown_handle: None,
|
||||||
templates: load_templates(&config.templates_folder),
|
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
|
/// is in signups_domains_whitelist, or if no whitelist is set (so there
|
||||||
/// are no domain restrictions in effect).
|
/// are no domain restrictions in effect).
|
||||||
pub fn is_email_domain_allowed(&self, email: &str) -> bool {
|
pub fn is_email_domain_allowed(&self, email: &str) -> bool {
|
||||||
let e: Vec<&str> = email.rsplitn(2, '@').collect();
|
let Some((_, domain)) = email.rsplit_once('@').filter(|(name, domain)| !name.is_empty() && !domain.is_empty())
|
||||||
if e.len() != 2 || e[0].is_empty() || e[1].is_empty() {
|
else {
|
||||||
warn!("Failed to parse email address '{}'", email.escape_debug());
|
warn!("Failed to parse email address '{}'", email.escape_debug());
|
||||||
return false;
|
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
|
/// 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.
|
/// Tests whether the admin token is set to a non-empty value.
|
||||||
pub fn is_admin_token_set(&self) -> bool {
|
pub fn is_admin_token_set(&self) -> bool {
|
||||||
let token = self.admin_token();
|
let token = self.admin_token();
|
||||||
|
token.is_some_and(|t| !t.trim().is_empty())
|
||||||
token.is_some() && !token.unwrap().trim().is_empty()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn opendal_operator_for_path_type(&self, path_type: &PathType) -> Result<opendal::Operator, Error> {
|
pub fn opendal_operator_for_path_type(&self, path_type: &PathType) -> Result<opendal::Operator, Error> {
|
||||||
|
|||||||
+17
-11
@@ -1,7 +1,6 @@
|
|||||||
mod query_logger;
|
mod query_logger;
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
future::Future,
|
|
||||||
sync::{
|
sync::{
|
||||||
Arc, OnceLock,
|
Arc, OnceLock,
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
@@ -237,7 +236,7 @@ impl DbPool {
|
|||||||
error!("Tried to set the active database connection type more than once.");
|
error!("Tried to set the active database connection type more than once.");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(DbPool {
|
Ok(Self {
|
||||||
pool: Some(pool),
|
pool: Some(pool),
|
||||||
semaphore: Arc::new(Semaphore::new(max_conns as usize)),
|
semaphore: Arc::new(Semaphore::new(max_conns as usize)),
|
||||||
})
|
})
|
||||||
@@ -268,25 +267,25 @@ impl DbPool {
|
|||||||
impl DbConnType {
|
impl DbConnType {
|
||||||
pub fn from_url(url: &str) -> Result<Self, Error> {
|
pub fn from_url(url: &str) -> Result<Self, Error> {
|
||||||
// Mysql
|
// Mysql
|
||||||
if url.len() > 6 && &url[..6] == "mysql:" {
|
if url.starts_with("mysql:") {
|
||||||
#[cfg(mysql)]
|
#[cfg(mysql)]
|
||||||
return Ok(DbConnType::Mysql);
|
return Ok(Self::Mysql);
|
||||||
|
|
||||||
#[cfg(not(mysql))]
|
#[cfg(not(mysql))]
|
||||||
err!("`DATABASE_URL` is a MySQL URL, but the 'mysql' feature is not enabled")
|
err!("`DATABASE_URL` is a MySQL URL, but the 'mysql' feature is not enabled")
|
||||||
|
|
||||||
// Postgresql
|
// Postgresql
|
||||||
} else if url.len() > 11 && (&url[..11] == "postgresql:" || &url[..9] == "postgres:") {
|
} else if url.starts_with("postgresql:") || url.starts_with("postgres:") {
|
||||||
#[cfg(postgresql)]
|
#[cfg(postgresql)]
|
||||||
return Ok(DbConnType::Postgresql);
|
return Ok(Self::Postgresql);
|
||||||
|
|
||||||
#[cfg(not(postgresql))]
|
#[cfg(not(postgresql))]
|
||||||
err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled")
|
err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled")
|
||||||
|
|
||||||
// Sqlite (explicit)
|
// Sqlite (explicit)
|
||||||
} else if url.len() > 7 && &url[..7] == "sqlite:" {
|
} else if url.starts_with("sqlite:") {
|
||||||
#[cfg(sqlite)]
|
#[cfg(sqlite)]
|
||||||
return Ok(DbConnType::Sqlite);
|
return Ok(Self::Sqlite);
|
||||||
|
|
||||||
#[cfg(not(sqlite))]
|
#[cfg(not(sqlite))]
|
||||||
err!("`DATABASE_URL` is a SQLite URL, but the 'sqlite' feature is not enabled")
|
err!("`DATABASE_URL` is a SQLite URL, but the 'sqlite' feature is not enabled")
|
||||||
@@ -297,7 +296,7 @@ impl DbConnType {
|
|||||||
#[cfg(sqlite)]
|
#[cfg(sqlite)]
|
||||||
{
|
{
|
||||||
if std::path::Path::new(url).exists() {
|
if std::path::Path::new(url).exists() {
|
||||||
return Ok(DbConnType::Sqlite);
|
return Ok(Self::Sqlite);
|
||||||
}
|
}
|
||||||
err!(format!(
|
err!(format!(
|
||||||
"`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://) \
|
"`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.
|
/// MySQL/MariaDB and PostgreSQL are not supported.
|
||||||
#[cfg(sqlite)]
|
#[cfg(sqlite)]
|
||||||
pub fn backup_sqlite() -> Result<String, Error> {
|
pub fn backup_sqlite() -> Result<String, Error> {
|
||||||
use diesel::Connection;
|
|
||||||
|
|
||||||
let db_url = CONFIG.database_url();
|
let db_url = CONFIG.database_url();
|
||||||
if DbConnType::from_url(&CONFIG.database_url()).is_ok_and(|t| t == DbConnType::Sqlite) {
|
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
|
// 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"])
|
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
||||||
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
||||||
.env("DATABASE_URL", "sqlite://:memory:")
|
.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()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ impl Attachment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_all_by_cipher(cipher_uuid: &CipherId, conn: &DbConn) -> EmptyResult {
|
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?;
|
attachment.delete(conn).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
+19
-27
@@ -97,8 +97,8 @@ impl CipherAccessScope {
|
|||||||
/// Whether `member` reaches every cipher of their organization with this access.
|
/// Whether `member` reaches every cipher of their organization with this access.
|
||||||
fn reaches_all_ciphers(self, member: &Membership) -> bool {
|
fn reaches_all_ciphers(self, member: &Membership) -> bool {
|
||||||
match self {
|
match self {
|
||||||
CipherAccessScope::User => member.has_full_access(),
|
Self::User => member.has_full_access(),
|
||||||
CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(),
|
Self::OrganizationAdmin => member.can_edit_any_collection(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,18 +106,18 @@ impl CipherAccessScope {
|
|||||||
/// administrative one still needs a member who may edit any collection.
|
/// administrative one still needs a member who may edit any collection.
|
||||||
pub fn requested(admin_request: Option<bool>) -> Self {
|
pub fn requested(admin_request: Option<bool>) -> Self {
|
||||||
if admin_request == Some(true) {
|
if admin_request == Some(true) {
|
||||||
CipherAccessScope::OrganizationAdmin
|
Self::OrganizationAdmin
|
||||||
} else {
|
} else {
|
||||||
CipherAccessScope::User
|
Self::User
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The access for a route that does not tell which one it is, from the member's own membership.
|
/// 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 {
|
pub fn for_member(member: Option<&Membership>) -> Self {
|
||||||
if member.is_some_and(Membership::can_edit_any_collection) {
|
if member.is_some_and(Membership::can_edit_any_collection) {
|
||||||
CipherAccessScope::OrganizationAdmin
|
Self::OrganizationAdmin
|
||||||
} else {
|
} else {
|
||||||
CipherAccessScope::User
|
Self::User
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -306,7 +306,7 @@ impl Cipher {
|
|||||||
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
|
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
|
||||||
.ok()
|
.ok()
|
||||||
})
|
})
|
||||||
.map(|d| {
|
.map_or_default(|d| {
|
||||||
d.into_iter()
|
d.into_iter()
|
||||||
.map(|mut f| {
|
.map(|mut f| {
|
||||||
// Check if the `type` key is a number, strings break some clients
|
// Check if the `type` key is a number, strings break some clients
|
||||||
@@ -326,8 +326,7 @@ impl Cipher {
|
|||||||
f.data
|
f.data
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
})
|
});
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let password_history_json: Vec<_> = self
|
let password_history_json: Vec<_> = self
|
||||||
.password_history
|
.password_history
|
||||||
@@ -337,7 +336,7 @@ impl Cipher {
|
|||||||
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
|
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
|
||||||
.ok()
|
.ok()
|
||||||
})
|
})
|
||||||
.map(|d| {
|
.map_or_default(|d| {
|
||||||
// Check every password history item if they are valid and return it.
|
// 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
|
// 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
|
// 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
|
d
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
})
|
});
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
// Like upstream, fields and password history stored as NULL are sent as null, not `[]`
|
// 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 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 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 {
|
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) {
|
cipher_sync_data.cipher_collections.get(&self.uuid).map_or_default(Cow::from)
|
||||||
Cow::from(cipher_collections)
|
|
||||||
} else {
|
|
||||||
Cow::from(Vec::new())
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
Cow::from(self.get_admin_collections(user_uuid.clone(), scope, conn).await)
|
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.
|
/// Returns whether this cipher is directly owned by the user.
|
||||||
pub fn is_owned_by_user(&self, user_uuid: &UserId) -> bool {
|
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`.
|
/// 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,
|
scope: CipherAccessScope,
|
||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
|
self.get_access_restrictions(user_uuid, scope, None, conn)
|
||||||
Some((read_only, _hide_passwords, manage)) => !read_only || manage,
|
.await
|
||||||
None => false,
|
.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
|
// 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,
|
scope: CipherAccessScope,
|
||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
|
self.get_access_restrictions(user_uuid, scope, None, conn)
|
||||||
Some((read_only, hide_passwords, manage)) => (!read_only && !hide_passwords) || manage,
|
.await
|
||||||
None => false,
|
.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 {
|
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());
|
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> =
|
let in_collections: HashSet<CipherId> =
|
||||||
Self::get_collections_with_cipher_by_organization(&member.org_uuid, conn)
|
Self::get_collections_with_cipher_by_organization(&member.org_uuid, conn)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -82,18 +82,8 @@ impl Collection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_external_id(&mut self, external_id: Option<String>) {
|
pub fn set_external_id(&mut self, external_id: Option<String>) {
|
||||||
//Check if external id is empty. We don't want to have
|
// Check if external id is empty. We don't want to have empty strings in the database
|
||||||
//empty strings in the database
|
self.external_id = external_id.filter(|e| !e.trim().is_empty());
|
||||||
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,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn to_json_details(
|
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 {
|
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;
|
User::update_uuid_revision(&collection.user_uuid, conn).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+31
-31
@@ -51,7 +51,7 @@ impl Device {
|
|||||||
|
|
||||||
push_uuid: Some(PushId(get_uuid())),
|
push_uuid: Some(PushId(get_uuid())),
|
||||||
push_token: None,
|
push_token: None,
|
||||||
refresh_token: Device::generate_refresh_token(),
|
refresh_token: Self::generate_refresh_token(),
|
||||||
twofactor_remember: None,
|
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.
|
// 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;
|
let devices = Self::find_by_user(user_uuid, conn).await;
|
||||||
for mut device in devices {
|
for mut device in devices {
|
||||||
device.refresh_token = Device::generate_refresh_token();
|
device.refresh_token = Self::generate_refresh_token();
|
||||||
device.twofactor_remember = None;
|
device.twofactor_remember = None;
|
||||||
device.save(false, conn).await?;
|
device.save(false, conn).await?;
|
||||||
}
|
}
|
||||||
@@ -347,36 +347,36 @@ pub enum DeviceType {
|
|||||||
|
|
||||||
impl DeviceType {
|
impl DeviceType {
|
||||||
#[expect(clippy::match_same_arms, reason = "Specifically define 14 and have a fallback for new types")]
|
#[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 {
|
match value {
|
||||||
0 => DeviceType::Android,
|
0 => Self::Android,
|
||||||
1 => DeviceType::Ios,
|
1 => Self::Ios,
|
||||||
2 => DeviceType::ChromeExtension,
|
2 => Self::ChromeExtension,
|
||||||
3 => DeviceType::FirefoxExtension,
|
3 => Self::FirefoxExtension,
|
||||||
4 => DeviceType::OperaExtension,
|
4 => Self::OperaExtension,
|
||||||
5 => DeviceType::EdgeExtension,
|
5 => Self::EdgeExtension,
|
||||||
6 => DeviceType::WindowsDesktop,
|
6 => Self::WindowsDesktop,
|
||||||
7 => DeviceType::MacOsDesktop,
|
7 => Self::MacOsDesktop,
|
||||||
8 => DeviceType::LinuxDesktop,
|
8 => Self::LinuxDesktop,
|
||||||
9 => DeviceType::ChromeBrowser,
|
9 => Self::ChromeBrowser,
|
||||||
10 => DeviceType::FirefoxBrowser,
|
10 => Self::FirefoxBrowser,
|
||||||
11 => DeviceType::OperaBrowser,
|
11 => Self::OperaBrowser,
|
||||||
12 => DeviceType::EdgeBrowser,
|
12 => Self::EdgeBrowser,
|
||||||
13 => DeviceType::IEBrowser,
|
13 => Self::IEBrowser,
|
||||||
14 => DeviceType::UnknownBrowser,
|
14 => Self::UnknownBrowser,
|
||||||
15 => DeviceType::AndroidAmazon,
|
15 => Self::AndroidAmazon,
|
||||||
16 => DeviceType::Uwp,
|
16 => Self::Uwp,
|
||||||
17 => DeviceType::SafariBrowser,
|
17 => Self::SafariBrowser,
|
||||||
18 => DeviceType::VivaldiBrowser,
|
18 => Self::VivaldiBrowser,
|
||||||
19 => DeviceType::VivaldiExtension,
|
19 => Self::VivaldiExtension,
|
||||||
20 => DeviceType::SafariExtension,
|
20 => Self::SafariExtension,
|
||||||
21 => DeviceType::Sdk,
|
21 => Self::Sdk,
|
||||||
22 => DeviceType::Server,
|
22 => Self::Server,
|
||||||
23 => DeviceType::WindowsCLI,
|
23 => Self::WindowsCLI,
|
||||||
24 => DeviceType::MacOsCLI,
|
24 => Self::MacOsCLI,
|
||||||
25 => DeviceType::LinuxCLI,
|
25 => Self::LinuxCLI,
|
||||||
26 => DeviceType::DuckDuckGoBrowser,
|
26 => Self::DuckDuckGoBrowser,
|
||||||
_ => DeviceType::UnknownBrowser,
|
_ => Self::UnknownBrowser,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -141,8 +141,8 @@ pub enum EmergencyAccessType {
|
|||||||
impl EmergencyAccessType {
|
impl EmergencyAccessType {
|
||||||
pub fn from_str(s: &str) -> Option<Self> {
|
pub fn from_str(s: &str) -> Option<Self> {
|
||||||
match s {
|
match s {
|
||||||
"0" | "View" => Some(EmergencyAccessType::View),
|
"0" | "View" => Some(Self::View),
|
||||||
"1" | "Takeover" => Some(EmergencyAccessType::Takeover),
|
"1" | "Takeover" => Some(Self::Takeover),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -397,7 +397,7 @@ impl EmergencyAccess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn accept_invite(&mut self, grantee_uuid: &UserId, grantee_email: &str, conn: &DbConn) -> EmptyResult {
|
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.");
|
err!("User email does not match invite.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -151,11 +151,7 @@ pub enum EventType {
|
|||||||
/// Local methods
|
/// Local methods
|
||||||
impl Event {
|
impl Event {
|
||||||
pub fn new(event_type: i32, event_date: Option<NaiveDateTime>) -> Self {
|
pub fn new(event_type: i32, event_date: Option<NaiveDateTime>) -> Self {
|
||||||
let event_date = match event_date {
|
let event_date = event_date.unwrap_or_else(|| Utc::now().naive_utc());
|
||||||
Some(d) => d,
|
|
||||||
None => Utc::now().naive_utc(),
|
|
||||||
};
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
uuid: EventId(crate::util::get_uuid()),
|
uuid: EventId(crate::util::get_uuid()),
|
||||||
event_type,
|
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.
|
// 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.
|
// SQLite doesn't support the DEFAULT argument, and does not support inserting multiple values at the same time.
|
||||||
// MySQL and PostgreSQL do.
|
// MySQL and PostgreSQL do.
|
||||||
|
|||||||
@@ -112,10 +112,7 @@ impl Group {
|
|||||||
|
|
||||||
pub fn set_external_id(&mut self, external_id: Option<String>) {
|
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
|
// Check if external_id is empty. We do not want to have empty strings in the database
|
||||||
self.external_id = match external_id {
|
self.external_id = external_id.filter(|e| !e.trim().is_empty());
|
||||||
Some(external_id) if !external_id.trim().is_empty() => Some(external_id),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +312,7 @@ impl Group {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CollectionGroup {
|
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;
|
let group_users = GroupUser::find_by_group(&self.groups_uuid, org_uuid, conn).await;
|
||||||
for group_user in group_users {
|
for group_user in group_users {
|
||||||
group_user.update_user_revision(conn).await;
|
group_user.update_user_revision(conn).await;
|
||||||
@@ -448,7 +445,7 @@ impl CollectionGroup {
|
|||||||
org_uuid: &OrganizationId,
|
org_uuid: &OrganizationId,
|
||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> EmptyResult {
|
) -> 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 {
|
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;
|
let group_users = GroupUser::find_by_group(&collection_assigned_to_group.groups_uuid, org_uuid, conn).await;
|
||||||
for group_user in group_users {
|
for group_user in group_users {
|
||||||
@@ -467,7 +464,7 @@ impl CollectionGroup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GroupUser {
|
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;
|
self.update_user_revision(conn).await;
|
||||||
|
|
||||||
let values = (
|
let values = (
|
||||||
@@ -574,7 +571,7 @@ impl GroupUser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_all_by_group(group_uuid: &GroupId, org_uuid: &OrganizationId, conn: &DbConn) -> EmptyResult {
|
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 {
|
for group_user in group_users {
|
||||||
group_user.update_user_revision(conn).await;
|
group_user.update_user_revision(conn).await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -301,11 +301,9 @@ impl OrgPolicy {
|
|||||||
exclude_org_uuid: Option<&OrganizationId>,
|
exclude_org_uuid: Option<&OrganizationId>,
|
||||||
conn: &DbConn,
|
conn: &DbConn,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
for policy in
|
for policy in Self::find_accepted_and_confirmed_by_user_and_active_policy(user_uuid, policy_type, conn).await {
|
||||||
OrgPolicy::find_accepted_and_confirmed_by_user_and_active_policy(user_uuid, policy_type, conn).await
|
|
||||||
{
|
|
||||||
// Check if we need to skip this organization.
|
// 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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -370,7 +368,7 @@ impl OrgPolicy {
|
|||||||
return false;
|
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) {
|
Some(policy) => match serde_json::from_str::<ResetPasswordDataModel>(&policy.data) {
|
||||||
Ok(opts) => {
|
Ok(opts) => {
|
||||||
return policy.enabled && opts.auto_enroll_enabled;
|
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`
|
/// 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.
|
/// 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 {
|
pub async fn is_hide_email_disabled(user_uuid: &UserId, conn: &DbConn) -> bool {
|
||||||
for policy in
|
for policy in Self::find_confirmed_by_user_and_active_policy(user_uuid, OrgPolicyType::SendOptions, conn).await
|
||||||
OrgPolicy::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
|
if let Some(user) = Membership::find_confirmed_by_user_and_org(user_uuid, &policy.org_uuid, conn).await
|
||||||
&& user.atype < MembershipType::Admin
|
&& 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 {
|
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
|
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;
|
return policy.enabled;
|
||||||
}
|
}
|
||||||
|
|||||||
+153
-72
@@ -134,11 +134,11 @@ pub enum MembershipType {
|
|||||||
impl MembershipType {
|
impl MembershipType {
|
||||||
pub fn from_str(s: &str) -> Option<Self> {
|
pub fn from_str(s: &str) -> Option<Self> {
|
||||||
match s {
|
match s {
|
||||||
"0" | "Owner" => Some(MembershipType::Owner),
|
"0" | "Owner" => Some(Self::Owner),
|
||||||
"1" | "Admin" => Some(MembershipType::Admin),
|
"1" | "Admin" => Some(Self::Admin),
|
||||||
"2" | "User" => Some(MembershipType::User),
|
"2" | "User" => Some(Self::User),
|
||||||
"3" | "Manager" => Some(MembershipType::Manager),
|
"3" | "Manager" => Some(Self::Manager),
|
||||||
"4" | "Custom" => Some(MembershipType::Custom),
|
"4" | "Custom" => Some(Self::Custom),
|
||||||
_ => None,
|
_ => 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
|
/// 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.
|
/// Manager only becomes a Custom member when the permissions they are shown with are changed.
|
||||||
pub fn requested(
|
pub fn requested(
|
||||||
requested: MembershipType,
|
requested: Self,
|
||||||
current: Option<&Membership>,
|
current: Option<&Membership>,
|
||||||
custom_permissions: Option<&HashSet<CustomPermission>>,
|
custom_permissions: Option<&HashSet<CustomPermission>>,
|
||||||
) -> MembershipType {
|
) -> Self {
|
||||||
if requested != MembershipType::Custom {
|
if requested != Self::Custom {
|
||||||
return requested;
|
return requested;
|
||||||
}
|
}
|
||||||
match (current, custom_permissions) {
|
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))
|
(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(member), _) if member.has_type(Self::Manager) => Self::Manager,
|
||||||
(_, Some(_)) => MembershipType::Custom,
|
(_, Some(_)) => Self::Custom,
|
||||||
(_, None) => MembershipType::Manager,
|
(_, 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.
|
/// its permissions, never from its role, so the role itself ranks right above User and below Manager.
|
||||||
const fn rank(self) -> u8 {
|
const fn rank(self) -> u8 {
|
||||||
match self {
|
match self {
|
||||||
MembershipType::User => 0,
|
Self::User => 0,
|
||||||
MembershipType::Custom => 1,
|
Self::Custom => 1,
|
||||||
MembershipType::Manager => 2,
|
Self::Manager => 2,
|
||||||
MembershipType::Admin => 3,
|
Self::Admin => 3,
|
||||||
MembershipType::Owner => 4,
|
Self::Owner => 4,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Ord for MembershipType {
|
impl Ord for MembershipType {
|
||||||
fn cmp(&self, other: &MembershipType) -> Ordering {
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
self.rank().cmp(&other.rank())
|
self.rank().cmp(&other.rank())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialOrd for MembershipType {
|
impl PartialOrd for MembershipType {
|
||||||
fn partial_cmp(&self, other: &MembershipType) -> Option<Ordering> {
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||||
Some(self.cmp(other))
|
Some(self.cmp(other))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -212,17 +212,17 @@ impl PartialOrd<i32> for MembershipType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn gt(&self, other: &i32) -> bool {
|
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 {
|
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 {
|
impl PartialEq<MembershipType> for i32 {
|
||||||
fn eq(&self, other: &MembershipType) -> bool {
|
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 {
|
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 {
|
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 {
|
impl CustomPermission {
|
||||||
pub const ALL: [CustomPermission; 10] = [
|
pub const ALL: [Self; 10] = [
|
||||||
CustomPermission::ManageUsers,
|
Self::ManageUsers,
|
||||||
CustomPermission::ManageGroups,
|
Self::ManageGroups,
|
||||||
CustomPermission::ManagePolicies,
|
Self::ManagePolicies,
|
||||||
CustomPermission::CreateNewCollections,
|
Self::CreateNewCollections,
|
||||||
CustomPermission::EditAnyCollection,
|
Self::EditAnyCollection,
|
||||||
CustomPermission::DeleteAnyCollection,
|
Self::DeleteAnyCollection,
|
||||||
CustomPermission::AccessEventLogs,
|
Self::AccessEventLogs,
|
||||||
CustomPermission::AccessImportExport,
|
Self::AccessImportExport,
|
||||||
CustomPermission::AccessReports,
|
Self::AccessReports,
|
||||||
CustomPermission::ManageResetPassword,
|
Self::ManageResetPassword,
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The key of the permission in the `permissions` object of the Bitwarden clients.
|
/// The key of the permission in the `permissions` object of the Bitwarden clients.
|
||||||
pub const fn json_key(self) -> &'static str {
|
pub const fn json_key(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
CustomPermission::ManageUsers => "manageUsers",
|
Self::ManageUsers => "manageUsers",
|
||||||
CustomPermission::ManageGroups => "manageGroups",
|
Self::ManageGroups => "manageGroups",
|
||||||
CustomPermission::ManagePolicies => "managePolicies",
|
Self::ManagePolicies => "managePolicies",
|
||||||
CustomPermission::CreateNewCollections => "createNewCollections",
|
Self::CreateNewCollections => "createNewCollections",
|
||||||
CustomPermission::EditAnyCollection => "editAnyCollection",
|
Self::EditAnyCollection => "editAnyCollection",
|
||||||
CustomPermission::DeleteAnyCollection => "deleteAnyCollection",
|
Self::DeleteAnyCollection => "deleteAnyCollection",
|
||||||
CustomPermission::AccessEventLogs => "accessEventLogs",
|
Self::AccessEventLogs => "accessEventLogs",
|
||||||
CustomPermission::AccessImportExport => "accessImportExport",
|
Self::AccessImportExport => "accessImportExport",
|
||||||
CustomPermission::AccessReports => "accessReports",
|
Self::AccessReports => "accessReports",
|
||||||
CustomPermission::ManageResetPassword => "manageResetPassword",
|
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
|
/// 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
|
/// 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.
|
/// 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();
|
let mut granted = HashSet::new();
|
||||||
for permission in CustomPermission::ALL {
|
for permission in Self::ALL {
|
||||||
match permissions.get(permission.json_key()) {
|
match permissions.get(permission.json_key()) {
|
||||||
None | Some(Value::Bool(false)) => {}
|
None | Some(Value::Bool(false)) => {}
|
||||||
Some(Value::Bool(true)) if permission.is_supported() => {
|
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
|
/// Whether this member may act with every Custom role permission stored for `other`, as Bitwarden's
|
||||||
/// `Permissions.Includes`.
|
/// `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))
|
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 {
|
pub fn set_external_id(&mut self, external_id: Option<String>) -> bool {
|
||||||
//Check if external id is empty. We don't want to have
|
// Check if external id is empty. We don't want to have empty strings in the database
|
||||||
//empty strings in the database
|
let external_id = external_id.filter(|e| !e.trim().is_empty());
|
||||||
if self.external_id != external_id {
|
|
||||||
self.external_id = match external_id {
|
if self.external_id == external_id {
|
||||||
Some(external_id) if !external_id.is_empty() => Some(external_id),
|
return false;
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
false
|
|
||||||
|
self.external_id = external_id;
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// HACK: Convert the manager type to a custom type
|
/// 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 twofactor_enabled = !TwoFactor::find_by_user(&user.uuid, conn).await.is_empty();
|
||||||
|
|
||||||
let groups: Vec<GroupId> = if include_groups && CONFIG.org_groups_enabled() {
|
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 {
|
} else {
|
||||||
// The Bitwarden clients seem to call this API regardless of whether groups are enabled,
|
// The Bitwarden clients seem to call this API regardless of whether groups are enabled,
|
||||||
// so just act as if there are no groups.
|
// so just act as if there are no groups.
|
||||||
@@ -928,7 +927,7 @@ impl Membership {
|
|||||||
json!({
|
json!({
|
||||||
"id": self.uuid,
|
"id": self.uuid,
|
||||||
"userId": self.user_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,
|
"email": user.email,
|
||||||
"externalId": self.external_id,
|
"externalId": self.external_id,
|
||||||
"avatarColor": user.avatar_color,
|
"avatarColor": user.avatar_color,
|
||||||
@@ -1081,9 +1080,9 @@ impl Membership {
|
|||||||
Ok(())
|
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
|
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);
|
return Some(member);
|
||||||
}
|
}
|
||||||
@@ -1285,11 +1284,9 @@ impl Membership {
|
|||||||
.filter(users_organizations::org_uuid.eq(org_uuid))
|
.filter(users_organizations::org_uuid.eq(org_uuid))
|
||||||
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
|
.filter(users_organizations::status.eq(MembershipStatus::Confirmed as i32))
|
||||||
.filter(
|
.filter(
|
||||||
users_organizations::atype
|
users_organizations::atype.eq_any(ORG_ADMIN_ATYPES).or(users_organizations::atype
|
||||||
.eq_any(vec![MembershipType::Owner as i32, MembershipType::Admin as i32])
|
.eq(MembershipType::Manager as i32)
|
||||||
.or(users_organizations::atype
|
.and(users_organizations::access_all.eq(true))),
|
||||||
.eq(MembershipType::Manager as i32)
|
|
||||||
.and(users_organizations::access_all.eq(true))),
|
|
||||||
)
|
)
|
||||||
.load::<Self>(conn)
|
.load::<Self>(conn)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
@@ -1669,6 +1666,18 @@ mod tests {
|
|||||||
use CustomPermission::*;
|
use CustomPermission::*;
|
||||||
use MembershipType::{Admin, Custom, Manager, Owner, User};
|
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 {
|
fn member(role: MembershipType) -> Membership {
|
||||||
let mut member = Membership::new("user".into(), "org".into(), None);
|
let mut member = Membership::new("user".into(), "org".into(), None);
|
||||||
member.atype = role as i32;
|
member.atype = role as i32;
|
||||||
@@ -1678,22 +1687,94 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn membership_type_authority() {
|
fn membership_type_authority() {
|
||||||
assert!(Owner > Admin && Admin > Manager && Manager > Custom && Custom > User);
|
// Roles compare by authority, never by their stored number, whichever side the raw `i32` is on
|
||||||
assert!((Custom as i32) >= User && (Custom as i32) < Manager && (Custom as i32) < Admin);
|
for (i, role) in AUTHORITY.into_iter().enumerate() {
|
||||||
for raw in [99, -1] {
|
for (j, other) in AUTHORITY.into_iter().enumerate() {
|
||||||
assert_eq!((raw >= User, raw >= Manager, raw >= Admin, raw < Admin), (false, false, false, true));
|
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 [
|
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)),
|
("3", Some(Manager)),
|
||||||
("Manager", Some(Manager)),
|
("Manager", Some(Manager)),
|
||||||
("4", Some(Custom)),
|
("4", Some(Custom)),
|
||||||
("Custom", Some(Custom)),
|
("Custom", Some(Custom)),
|
||||||
("5", None),
|
("5", None),
|
||||||
|
("Invalid", None),
|
||||||
] {
|
] {
|
||||||
assert_eq!(MembershipType::from_str(value), expected);
|
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]
|
#[test]
|
||||||
fn requested_membership_type() {
|
fn requested_membership_type() {
|
||||||
let none = HashSet::new();
|
let none = HashSet::new();
|
||||||
|
|||||||
@@ -58,9 +58,9 @@ pub enum SendType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
enum SendAuthType {
|
enum SendAuthType {
|
||||||
#[allow(dead_code)]
|
#[expect(unused, reason = "Not yet supported")]
|
||||||
// Send requires email OTP verification
|
// Send requires email OTP verification
|
||||||
Email = 0, // Not yet supported by Vaultwarden
|
Email = 0,
|
||||||
// Send requires a password
|
// Send requires a password
|
||||||
Password = 1,
|
Password = 1,
|
||||||
// Send requires no auth
|
// Send requires no auth
|
||||||
@@ -145,7 +145,7 @@ impl Send {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn to_json(&self) -> Value {
|
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
|
// Mobile clients expect size to be a string instead of a number
|
||||||
if let Some(size) = data.get("size").and_then(Value::as_i64) {
|
if let Some(size) = data.get("size").and_then(Value::as_i64) {
|
||||||
@@ -159,8 +159,8 @@ impl Send {
|
|||||||
|
|
||||||
"name": self.name,
|
"name": self.name,
|
||||||
"notes": self.notes,
|
"notes": self.notes,
|
||||||
"text": if self.atype == SendType::Text as i32 { Some(&data) } else { None },
|
"text": (self.atype == SendType::Text as i32).then_some(&data),
|
||||||
"file": if self.atype == SendType::File as i32 { Some(&data) } else { None },
|
"file": (self.atype == SendType::File as i32).then_some(&data),
|
||||||
|
|
||||||
"key": self.akey,
|
"key": self.akey,
|
||||||
"maxAccessCount": self.max_access_count,
|
"maxAccessCount": self.max_access_count,
|
||||||
@@ -178,7 +178,7 @@ impl Send {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn to_json_access(&self, conn: &DbConn) -> Value {
|
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
|
// Mobile clients expect size to be a string instead of a number
|
||||||
if let Some(size) = data.get("size").and_then(Value::as_i64) {
|
if let Some(size) = data.get("size").and_then(Value::as_i64) {
|
||||||
@@ -190,8 +190,8 @@ impl Send {
|
|||||||
"type": self.atype,
|
"type": self.atype,
|
||||||
|
|
||||||
"name": self.name,
|
"name": self.name,
|
||||||
"text": if self.atype == SendType::Text as i32 { Some(&data) } else { None },
|
"text": (self.atype == SendType::Text as i32).then_some(&data),
|
||||||
"file": if self.atype == SendType::File as i32 { Some(&data) } else { None },
|
"file": (self.atype == SendType::File as i32).then_some(&data),
|
||||||
|
|
||||||
"expirationDate": self.expiration_date.as_ref().map(format_date),
|
"expirationDate": self.expiration_date.as_ref().map(format_date),
|
||||||
"creatorIdentifier": self.creator_identifier(conn).await,
|
"creatorIdentifier": self.creator_identifier(conn).await,
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ impl SsoAuth {
|
|||||||
) -> Self {
|
) -> Self {
|
||||||
let now = Utc::now().naive_utc();
|
let now = Utc::now().naive_utc();
|
||||||
|
|
||||||
SsoAuth {
|
Self {
|
||||||
state,
|
state,
|
||||||
client_challenge,
|
client_challenge,
|
||||||
nonce,
|
nonce,
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ impl TwoFactor {
|
|||||||
for mut u2f in u2f_factors {
|
for mut u2f in u2f_factors {
|
||||||
let mut regs: Vec<U2FRegistration> = serde_json::from_str(&u2f.data)?;
|
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 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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +227,7 @@ impl TwoFactor {
|
|||||||
u2f.data = serde_json::to_string(®s)?;
|
u2f.data = serde_json::to_string(®s)?;
|
||||||
u2f.save(conn).await?;
|
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)
|
.save(conn)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
@@ -254,7 +254,7 @@ impl TwoFactor {
|
|||||||
|
|
||||||
let regs = regs.into_iter().map(Into::into).collect::<Vec<WebauthnRegistration>>();
|
let regs = regs.into_iter().map(Into::into).collect::<Vec<WebauthnRegistration>>();
|
||||||
|
|
||||||
TwoFactor::new(webauthn_factor.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(®s)?)
|
Self::new(webauthn_factor.user_uuid.clone(), TwoFactorType::Webauthn, serde_json::to_string(®s)?)
|
||||||
.save(conn)
|
.save(conn)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-8
@@ -147,7 +147,7 @@ impl User {
|
|||||||
verified_at: None,
|
verified_at: None,
|
||||||
last_verifying_at: None,
|
last_verifying_at: None,
|
||||||
login_verify_count: 0,
|
login_verify_count: 0,
|
||||||
name: name.unwrap_or(email.clone()),
|
name: name.unwrap_or_else(|| email.clone()),
|
||||||
email,
|
email,
|
||||||
akey: String::new(),
|
akey: String::new(),
|
||||||
email_new: None,
|
email_new: None,
|
||||||
@@ -222,15 +222,11 @@ impl User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_valid_recovery_code(&self, recovery_code: &str) -> bool {
|
pub fn check_valid_recovery_code(&self, recovery_code: &str) -> bool {
|
||||||
if let Some(ref totp_recover) = self.totp_recover {
|
self.totp_recover.as_ref().is_some_and(|c| crypto::ct_eq(recovery_code, c.to_lowercase()))
|
||||||
crypto::ct_eq(recovery_code, totp_recover.to_lowercase())
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_valid_api_key(&self, key: &str) -> bool {
|
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
|
/// Set the password hash generated
|
||||||
@@ -290,7 +286,7 @@ impl User {
|
|||||||
grace.push(UserStampException {
|
grace.push(UserStampException {
|
||||||
routes: None,
|
routes: None,
|
||||||
security_stamp: previous_stamp,
|
security_stamp: previous_stamp,
|
||||||
expire: (Utc::now() + *DEFAULT_ACCESS_VALIDITY).timestamp(),
|
expire: (Utc::now() + DEFAULT_ACCESS_VALIDITY).timestamp(),
|
||||||
});
|
});
|
||||||
let mut exceptions = self.stamp_exceptions();
|
let mut exceptions = self.stamp_exceptions();
|
||||||
exceptions.extend(grace);
|
exceptions.extend(grace);
|
||||||
@@ -773,6 +769,15 @@ mod tests {
|
|||||||
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
||||||
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
||||||
.env("DATABASE_URL", "sqlite://:memory:")
|
.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()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
|
|||||||
+1
-2
@@ -238,8 +238,7 @@ impl Serialize for ApiErrorResponse<'_> {
|
|||||||
|
|
||||||
state.serialize_field("message", self.0.message)?;
|
state.serialize_field("message", self.0.message)?;
|
||||||
|
|
||||||
let mut validation_errors = std::collections::HashMap::with_capacity(1);
|
let validation_errors = std::collections::HashMap::from([("", vec![self.0.message])]);
|
||||||
validation_errors.insert("", vec![self.0.message]);
|
|
||||||
state.serialize_field("validationErrors", &validation_errors)?;
|
state.serialize_field("validationErrors", &validation_errors)?;
|
||||||
|
|
||||||
let error_model = ErrorModel {
|
let error_model = ErrorModel {
|
||||||
|
|||||||
+14
-16
@@ -161,13 +161,9 @@ pub fn should_block_host<S: AsRef<str>>(host: &Host<S>) -> Result<(), CustomHttp
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if should_block_address_regex(&host_str) {
|
(!should_block_address_regex(&host_str)).ok_or(CustomHttpClientError::Blocked {
|
||||||
return Err(CustomHttpClientError::Blocked {
|
domain: host_str,
|
||||||
domain: host_str,
|
})
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -211,7 +207,7 @@ impl CustomHttpClientError {
|
|||||||
|
|
||||||
while let Some(err) = source {
|
while let Some(err) = source {
|
||||||
source = err.source();
|
source = err.source();
|
||||||
if let Some(err) = err.downcast_ref::<CustomHttpClientError>() {
|
if let Some(err) = err.downcast_ref::<Self>() {
|
||||||
return Some(err);
|
return Some(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -258,7 +254,7 @@ impl CustomDns {
|
|||||||
fn instance(enforce_block: bool) -> Self {
|
fn instance(enforce_block: bool) -> Self {
|
||||||
static INSTANCE: LazyLock<Arc<CustomDnsResolver>> = LazyLock::new(CustomDnsResolver::new);
|
static INSTANCE: LazyLock<Arc<CustomDnsResolver>> = LazyLock::new(CustomDnsResolver::new);
|
||||||
|
|
||||||
CustomDns {
|
Self {
|
||||||
enforce_block,
|
enforce_block,
|
||||||
resolver: Arc::clone(&*INSTANCE),
|
resolver: Arc::clone(&*INSTANCE),
|
||||||
}
|
}
|
||||||
@@ -409,7 +405,7 @@ pub(crate) mod aws {
|
|||||||
Ok(HttpResponse::new(status, bytes.into()))
|
Ok(HttpResponse::new(status, bytes.into()))
|
||||||
};
|
};
|
||||||
|
|
||||||
HttpConnectorFuture::new(Box::pin(future))
|
HttpConnectorFuture::new(future)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -419,7 +415,7 @@ pub(crate) mod aws {
|
|||||||
_settings: &HttpConnectorSettings,
|
_settings: &HttpConnectorSettings,
|
||||||
_components: &RuntimeComponents,
|
_components: &RuntimeComponents,
|
||||||
) -> SharedHttpConnector {
|
) -> SharedHttpConnector {
|
||||||
SharedHttpConnector::new(AwsReqwestConnector {
|
SharedHttpConnector::new(Self {
|
||||||
client: self.client.clone(),
|
client: self.client.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -430,8 +426,10 @@ pub(crate) mod aws {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::util::is_global_hardcoded;
|
use crate::util::is_global_hardcoded;
|
||||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
use std::{
|
||||||
use url::Host;
|
assert_matches,
|
||||||
|
net::{Ipv4Addr, Ipv6Addr},
|
||||||
|
};
|
||||||
|
|
||||||
// ===
|
// ===
|
||||||
// IPv4 numeric-format normalization
|
// IPv4 numeric-format normalization
|
||||||
@@ -535,19 +533,19 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn get_valid_host_normalizes_decimal_int() {
|
fn get_valid_host_normalizes_decimal_int() {
|
||||||
let h = get_valid_host("2130706433").expect("valid");
|
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]
|
#[test]
|
||||||
fn get_valid_host_normalizes_hex() {
|
fn get_valid_host_normalizes_hex() {
|
||||||
let h = get_valid_host("0x7f000001").expect("valid");
|
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]
|
#[test]
|
||||||
fn get_valid_host_normalizes_octal() {
|
fn get_valid_host_normalizes_octal() {
|
||||||
let h = get_valid_host("017700000001").expect("valid");
|
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
@@ -74,8 +74,8 @@ fn smtp_transport() -> AsyncSmtpTransport<Tokio1Executor> {
|
|||||||
let mut selected_mechanisms = vec![];
|
let mut selected_mechanisms = vec![];
|
||||||
for wanted_mechanism in mechanism.split(',') {
|
for wanted_mechanism in mechanism.split(',') {
|
||||||
for m in &allowed_mechanisms {
|
for m in &allowed_mechanisms {
|
||||||
if m.to_string().to_lowercase()
|
if m.to_string()
|
||||||
== wanted_mechanism.trim_matches(|c| c == '"' || c == '\'' || c == ' ').to_lowercase()
|
.eq_ignore_ascii_case(wanted_mechanism.trim_matches(|c| c == '"' || c == '\'' || c == ' '))
|
||||||
{
|
{
|
||||||
selected_mechanisms.push(*m);
|
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> {
|
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 text = CONFIG.render_template(template_name, data)?;
|
||||||
let mut text_split = text.split("<!---------------->");
|
let Some((subject, body)) = text.split_once(DELIMITER) else {
|
||||||
|
|
||||||
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 {
|
|
||||||
err!("Template doesn't contain body")
|
err!("Template doesn't contain body")
|
||||||
};
|
};
|
||||||
|
|
||||||
if text_split.next().is_some() {
|
if body.contains(DELIMITER) {
|
||||||
err!("Template contains more than one body");
|
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 {
|
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();
|
let mut query_params = query.query_pairs_mut();
|
||||||
query_params
|
query_params
|
||||||
.append_pair("id", &emer_id.to_string())
|
.append_pair("id", emer_id.as_str())
|
||||||
.append_pair("name", grantor_name)
|
.append_pair("name", grantor_name)
|
||||||
.append_pair("email", address)
|
.append_pair("email", address)
|
||||||
.append_pair("token", &encode_jwt(&claims));
|
.append_pair("token", &encode_jwt(&claims));
|
||||||
|
|||||||
+12
-22
@@ -243,22 +243,20 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
|
|||||||
let level = caps
|
let level = caps
|
||||||
.get(1)
|
.get(1)
|
||||||
.and_then(|m| log::LevelFilter::from_str(m.as_str()).ok())
|
.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
|
let levels_override: Vec<(&str, log::LevelFilter)> = caps
|
||||||
.get(2)
|
.get(2)
|
||||||
.map(|m| {
|
.map(|m| {
|
||||||
m.as_str()
|
m.as_str()
|
||||||
.split(',')
|
.split(',')
|
||||||
.collect::<Vec<&str>>()
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|s| match s.split_once('=') {
|
.filter_map(|s| match s.split_once('=') {
|
||||||
Some((log, lvl_str)) => log::LevelFilter::from_str(lvl_str).ok().map(|lvl| (log, lvl)),
|
Some((log, lvl_str)) => log::LevelFilter::from_str(lvl_str).ok().map(|lvl| (log, lvl)),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.collect()
|
.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)
|
(level, levels_override)
|
||||||
} else {
|
} else {
|
||||||
@@ -366,15 +364,14 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(log_file) = CONFIG.log_file() {
|
if let Some(log_file) = CONFIG.log_file() {
|
||||||
#[cfg(windows)]
|
std::cfg_select! {
|
||||||
{
|
windows => { logger = logger.chain(fern::log_file(log_file)?); }
|
||||||
logger = logger.chain(fern::log_file(log_file)?);
|
unix => {
|
||||||
}
|
const SIGHUP: i32 = SignalKind::hangup().as_raw_value();
|
||||||
#[cfg(unix)]
|
let path = Path::new(&log_file);
|
||||||
{
|
logger = logger.chain(fern::log_reopen1(path, [SIGHUP])?);
|
||||||
const SIGHUP: i32 = SignalKind::hangup().as_raw_value();
|
}
|
||||||
let path = Path::new(&log_file);
|
_ => {}
|
||||||
logger = logger.chain(fern::log_reopen1(path, [SIGHUP])?);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -394,14 +391,7 @@ fn init_logging() -> Result<log::LevelFilter, Error> {
|
|||||||
let thread = thread::current();
|
let thread = thread::current();
|
||||||
let thread = thread.name().unwrap_or("unnamed");
|
let thread = thread.name().unwrap_or("unnamed");
|
||||||
|
|
||||||
let msg = match info.payload().downcast_ref::<&'static str>() {
|
let msg = info.payload_as_str().unwrap_or("Box<Any>");
|
||||||
Some(s) => *s,
|
|
||||||
None => match info.payload().downcast_ref::<String>() {
|
|
||||||
Some(s) => &**s,
|
|
||||||
None => "Box<Any>",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let backtrace = std::backtrace::Backtrace::force_capture();
|
let backtrace = std::backtrace::Backtrace::force_capture();
|
||||||
|
|
||||||
match info.location() {
|
match info.location() {
|
||||||
@@ -764,7 +754,7 @@ fn schedule_jobs(pool: db::DbPool) {
|
|||||||
// tick, the one that was added earlier will run first.
|
// tick, the one that was added earlier will run first.
|
||||||
loop {
|
loop {
|
||||||
sched.tick();
|
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(),
|
CONFIG.job_poll_interval_ms(),
|
||||||
))));
|
))));
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -236,7 +236,7 @@ pub struct OIDCIdentifier(String);
|
|||||||
|
|
||||||
impl OIDCIdentifier {
|
impl OIDCIdentifier {
|
||||||
fn new(issuer: &str, subject: &str) -> Self {
|
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 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"),
|
None => err!("Neither id token nor userinfo contained an email"),
|
||||||
Some(e) => e.to_string().to_lowercase(),
|
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);
|
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()) {
|
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) {
|
match decode_token_claims("refresh_token", &rt) {
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
let time_now = Utc::now();
|
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})");
|
debug!("Non jwt refresh_token (expiration set to {exp})");
|
||||||
(time_now.timestamp(), exp, TokenWrapper::Refresh(rt))
|
(time_now.timestamp(), exp, TokenWrapper::Refresh(rt))
|
||||||
}
|
}
|
||||||
@@ -454,7 +454,7 @@ pub async fn exchange_refresh_token(
|
|||||||
}
|
}
|
||||||
Some(TokenWrapper::Access(access_token)) => {
|
Some(TokenWrapper::Access(access_token)) => {
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let exp_limit = (now + *BW_EXPIRATION).timestamp();
|
let exp_limit = (now + BW_EXPIRATION).timestamp();
|
||||||
|
|
||||||
if exp < exp_limit {
|
if exp < exp_limit {
|
||||||
err_silent!("Access token is close to expiration but we have no refresh token")
|
err_silent!("Access token is close to expiration but we have no refresh token")
|
||||||
|
|||||||
+17
-15
@@ -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::{
|
use openidconnect::{
|
||||||
AccessToken, AsyncHttpClient, AuthDisplay, AuthPrompt, AuthType, AuthenticationFlow, AuthorizationCode,
|
AccessToken, AsyncHttpClient, AuthDisplay, AuthPrompt, AuthType, AuthenticationFlow, AuthorizationCode,
|
||||||
@@ -12,7 +12,7 @@ use openidconnect::{
|
|||||||
CoreProviderMetadata, CoreResponseType, CoreRevocableToken, CoreRevocationErrorResponse,
|
CoreProviderMetadata, CoreResponseType, CoreRevocableToken, CoreRevocationErrorResponse,
|
||||||
CoreTokenIntrospectionResponse, CoreTokenResponse, CoreTokenType, CoreUserInfoClaims,
|
CoreTokenIntrospectionResponse, CoreTokenResponse, CoreTokenType, CoreUserInfoClaims,
|
||||||
},
|
},
|
||||||
http, url,
|
http,
|
||||||
};
|
};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
@@ -25,8 +25,8 @@ use crate::{
|
|||||||
sso::{OIDCCode, OIDCCodeChallenge, OIDCCodeVerifier, OIDCState},
|
sso::{OIDCCode, OIDCCodeChallenge, OIDCCodeVerifier, OIDCState},
|
||||||
};
|
};
|
||||||
|
|
||||||
static CLIENT_CACHE_KEY: LazyLock<String> = LazyLock::new(|| "sso-client".to_owned());
|
const CLIENT_CACHE_KEY: &str = "sso-client";
|
||||||
static CLIENT_CACHE: LazyLock<moka::sync::Cache<String, Client>> = LazyLock::new(|| {
|
static CLIENT_CACHE: LazyLock<moka::sync::Cache<&'static str, Client>> = LazyLock::new(|| {
|
||||||
moka::sync::Cache::builder()
|
moka::sync::Cache::builder()
|
||||||
.max_capacity(1)
|
.max_capacity(1)
|
||||||
.time_to_live(Duration::from_secs(u64::from(CONFIG.sso_client_cache_expiration())))
|
.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 {
|
fn call(&'c self, request: HttpRequest) -> Self::Future {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let response = self.client.execute(request.try_into().map_err(Box::new)?).await.map_err(|e| {
|
let response = self
|
||||||
debug!("Request failed {e:?}");
|
.client
|
||||||
Box::new(e)
|
.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());
|
let mut builder = http::Response::builder().status(response.status()).version(response.version());
|
||||||
|
|
||||||
@@ -154,7 +156,7 @@ impl Client {
|
|||||||
.set_token_uri(token_uri)
|
.set_token_uri(token_uri)
|
||||||
.set_user_info_url(user_info_url);
|
.set_user_info_url(user_info_url);
|
||||||
|
|
||||||
Ok(Client {
|
Ok(Self {
|
||||||
http_client,
|
http_client,
|
||||||
core_client,
|
core_client,
|
||||||
})
|
})
|
||||||
@@ -163,11 +165,11 @@ impl Client {
|
|||||||
// Simple cache to prevent recalling the discovery endpoint each time
|
// Simple cache to prevent recalling the discovery endpoint each time
|
||||||
pub async fn cached() -> ApiResult<Self> {
|
pub async fn cached() -> ApiResult<Self> {
|
||||||
if CONFIG.sso_client_cache_expiration() > 0 {
|
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),
|
Some(client) => Ok(client),
|
||||||
None => Self::get_client().await.inspect(|client| {
|
None => Self::get_client().await.inspect(|client| {
|
||||||
debug!("Inserting new client in cache");
|
debug!("Inserting new client in cache");
|
||||||
CLIENT_CACHE.insert(CLIENT_CACHE_KEY.clone(), client.clone());
|
CLIENT_CACHE.insert(CLIENT_CACHE_KEY, client.clone());
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -177,7 +179,7 @@ impl Client {
|
|||||||
|
|
||||||
pub fn invalidate() {
|
pub fn invalidate() {
|
||||||
if CONFIG.sso_client_cache_expiration() > 0 {
|
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>,
|
binding_hash: Option<String>,
|
||||||
) -> ApiResult<(Url, SsoAuth)> {
|
) -> ApiResult<(Url, SsoAuth)> {
|
||||||
let scopes = CONFIG.sso_scopes_vec().into_iter().map(Scope::new);
|
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 client = Self::cached().await?;
|
||||||
let mut auth_req = client
|
let mut auth_req = client
|
||||||
@@ -287,7 +289,7 @@ impl Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn check_validity(access_token: String) -> EmptyResult {
|
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 {
|
match client.user_info(AccessToken::new(access_token)).await {
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
err_silent!(format!("Failed to retrieve user info, token has probably been invalidated: {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> {
|
pub async fn exchange_refresh_token(refresh_token: String) -> ApiResult<RefreshTokenResponse> {
|
||||||
let client = Client::cached().await?;
|
let client = Self::cached().await?;
|
||||||
|
|
||||||
REFRESH_CACHE
|
REFRESH_CACHE
|
||||||
.get_with(refresh_token.clone(), async move { client.exchange_refresh_token_impl(refresh_token).await })
|
.get_with(refresh_token.clone(), async move { client.exchange_refresh_token_impl(refresh_token).await })
|
||||||
|
|||||||
+1
-2
@@ -147,8 +147,7 @@ mod s3 {
|
|||||||
|
|
||||||
fn path_segments(url: &Url) -> Vec<String> {
|
fn path_segments(url: &Url) -> Vec<String> {
|
||||||
url.path_segments()
|
url.path_segments()
|
||||||
.map(|segments| segments.filter(|segment| !segment.is_empty()).map(str::to_owned).collect())
|
.map_or_default(|segments| segments.filter(|segment| !segment.is_empty()).map(str::to_owned).collect())
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_path_segments(url: &mut Url, segments: &[String]) {
|
fn set_path_segments(url: &mut Url, segments: &[String]) {
|
||||||
|
|||||||
+64
-108
@@ -38,23 +38,14 @@ impl Fairing for AppHeaders {
|
|||||||
|
|
||||||
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
|
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
|
||||||
let req_uri_path = req.uri().path();
|
let req_uri_path = req.uri().path();
|
||||||
let req_headers = req.headers();
|
|
||||||
|
|
||||||
// Check if this connection is an Upgrade/WebSocket connection and return early
|
// 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
|
// 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") {
|
if res.upgrade("websocket").is_some() {
|
||||||
match (req_headers.get_one("connection"), req_headers.get_one("upgrade")) {
|
res.remove_header("X-Frame-Options");
|
||||||
(Some(c), Some(u))
|
res.remove_header("X-Content-Type-Options");
|
||||||
if c.to_lowercase().contains("upgrade") && u.to_lowercase().contains("websocket") =>
|
res.remove_header("Permissions-Policy");
|
||||||
{
|
return;
|
||||||
// Remove headers which could cause websocket connection issues
|
|
||||||
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`
|
// NOTE: When modifying or adding security headers be sure to also update the diagnostic checks in `src/static/scripts/admin_diagnostics.js` in `checkSecurityHeaders`
|
||||||
@@ -151,16 +142,13 @@ pub struct Cors();
|
|||||||
|
|
||||||
impl Cors {
|
impl Cors {
|
||||||
fn get_header(headers: &HeaderMap<'_>, name: &str) -> String {
|
fn get_header(headers: &HeaderMap<'_>, name: &str) -> String {
|
||||||
match headers.get_one(name) {
|
headers.get_one(name).map_or_default(ToOwned::to_owned)
|
||||||
Some(h) => h.to_owned(),
|
|
||||||
_ => String::new(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check a request's `Origin` header against the list of allowed origins.
|
// Check a request's `Origin` header against the list of allowed origins.
|
||||||
// If a match exists, return it. Otherwise, return None.
|
// If a match exists, return it. Otherwise, return None.
|
||||||
fn get_allowed_origin(headers: &HeaderMap<'_>) -> Option<String> {
|
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 safari_extension_origin = "file://";
|
||||||
let desktop_custom_file_origin = "bw-desktop-file://bundle";
|
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>) {
|
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
|
||||||
let req_headers = request.headers();
|
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));
|
response.set_header(Header::new("Access-Control-Allow-Origin", origin));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Preflight request
|
// Preflight request
|
||||||
if request.method() == Method::Options {
|
if request.method() == Method::Options {
|
||||||
let req_allow_headers = Cors::get_header(req_headers, "Access-Control-Request-Headers");
|
let req_allow_headers = Self::get_header(req_headers, "Access-Control-Request-Headers");
|
||||||
let req_allow_method = Cors::get_header(req_headers, "Access-Control-Request-Method");
|
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-Methods", req_allow_method));
|
||||||
response.set_header(Header::new("Access-Control-Allow-Headers", req_allow_headers));
|
response.set_header(Header::new("Access-Control-Allow-Headers", req_allow_headers));
|
||||||
@@ -214,7 +202,7 @@ pub struct Cached<R> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<R> 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 {
|
Self {
|
||||||
response,
|
response,
|
||||||
is_immutable,
|
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 {
|
Self {
|
||||||
response,
|
response,
|
||||||
is_immutable,
|
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 {
|
Self {
|
||||||
response,
|
response,
|
||||||
is_immutable,
|
is_immutable,
|
||||||
@@ -447,19 +435,19 @@ pub fn get_uuid() -> String {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn upcase_first(s: &str) -> String {
|
pub fn upcase_first(s: &str) -> String {
|
||||||
let mut c = s.chars();
|
let mut c = s.chars();
|
||||||
match c.next() {
|
c.next().map_or_default(|f| f.to_uppercase().collect::<String>() + c.as_str())
|
||||||
None => String::new(),
|
|
||||||
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn lcase_first(s: &str) -> String {
|
pub fn lcase_first(mut s: String) -> String {
|
||||||
let mut c = s.chars();
|
// get_mut(0..1) is None if empty or if the first char is multi-byte
|
||||||
match c.next() {
|
if let Some(first) = s.get_mut(0..1) {
|
||||||
None => String::new(),
|
first.make_ascii_lowercase();
|
||||||
Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),
|
} 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>
|
pub fn try_parse_string<S, T>(string: Option<S>) -> Option<T>
|
||||||
@@ -467,11 +455,7 @@ where
|
|||||||
S: AsRef<str>,
|
S: AsRef<str>,
|
||||||
T: FromStr,
|
T: FromStr,
|
||||||
{
|
{
|
||||||
if let Some(Ok(value)) = string.map(|s| s.as_ref().parse::<T>()) {
|
string.and_then(|s| s.as_ref().parse::<T>().ok())
|
||||||
Some(value)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -513,15 +497,15 @@ pub fn get_env_bool(key: &'static str) -> Option<bool> {
|
|||||||
const TRUE_VALUES: &[&str] = &["true", "t", "yes", "y", "1"];
|
const TRUE_VALUES: &[&str] = &["true", "t", "yes", "y", "1"];
|
||||||
const FALSE_VALUES: &[&str] = &["false", "f", "no", "n", "0"];
|
const FALSE_VALUES: &[&str] = &["false", "f", "no", "n", "0"];
|
||||||
|
|
||||||
match get_env_str_value(key) {
|
let val = get_env_str_value(key)?;
|
||||||
Some(val) if TRUE_VALUES.contains(&val.to_lowercase().as_ref()) => Some(true),
|
if TRUE_VALUES.iter().any(|v| val.eq_ignore_ascii_case(v)) {
|
||||||
Some(val) if FALSE_VALUES.contains(&val.to_lowercase().as_ref()) => Some(false),
|
Some(true)
|
||||||
Some(_) => {
|
} else if FALSE_VALUES.iter().any(|v| val.eq_ignore_ascii_case(v)) {
|
||||||
println!("[ERROR] `{key}` contains an invalid boolean value and is ignored, the default is used instead.");
|
Some(false)
|
||||||
INVALID_ENV_VARS.lock().unwrap().push(key);
|
} else {
|
||||||
None
|
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.
|
// Inner function to handle a special case for the 'ssn' key.
|
||||||
// This key is part of the Identity Cipher (Social Security Number)
|
// This key is part of the Identity Cipher (Social Security Number)
|
||||||
fn process_json_key(key: &str) -> String {
|
fn process_json_key(mut key: String) -> String {
|
||||||
match key.to_lowercase().as_ref() {
|
if key.eq_ignore_ascii_case("ssn") {
|
||||||
"ssn" => "ssn".into(),
|
key.make_ascii_lowercase();
|
||||||
_ => lcase_first(key),
|
key
|
||||||
|
} else {
|
||||||
|
lcase_first(key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -728,13 +714,7 @@ where
|
|||||||
T: From<String>,
|
T: From<String>,
|
||||||
{
|
{
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
Ok(Option::<String>::deserialize(deserializer)?.and_then(|s| {
|
Ok(Option::<String>::deserialize(deserializer)?.filter(|s| !s.is_empty()).map(T::from))
|
||||||
if s.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(T::from(s))
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
@@ -747,8 +727,8 @@ pub enum NumberOrString {
|
|||||||
impl NumberOrString {
|
impl NumberOrString {
|
||||||
pub fn into_string(self) -> String {
|
pub fn into_string(self) -> String {
|
||||||
match self {
|
match self {
|
||||||
NumberOrString::Number(n) => n.to_string(),
|
Self::Number(n) => n.to_string(),
|
||||||
NumberOrString::String(s) => s,
|
Self::String(s) => s,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -756,16 +736,14 @@ impl NumberOrString {
|
|||||||
pub fn into_i32(&self) -> Result<i32, crate::Error> {
|
pub fn into_i32(&self) -> Result<i32, crate::Error> {
|
||||||
use std::num::ParseIntError as PIE;
|
use std::num::ParseIntError as PIE;
|
||||||
match self {
|
match self {
|
||||||
NumberOrString::Number(n) => {
|
Self::Number(n) => {
|
||||||
if let Some(n) = n.to_i32() {
|
if let Ok(n) = i32::try_from(*n) {
|
||||||
Ok(n)
|
Ok(n)
|
||||||
} else {
|
} else {
|
||||||
err!("Number does not fit in i32")
|
err!("Number does not fit in i32")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NumberOrString::String(s) => {
|
Self::String(s) => s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string())),
|
||||||
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> {
|
pub fn into_i64(&self) -> Result<i64, crate::Error> {
|
||||||
use std::num::ParseIntError as PIE;
|
use std::num::ParseIntError as PIE;
|
||||||
match self {
|
match self {
|
||||||
NumberOrString::Number(n) => Ok(*n),
|
Self::Number(n) => Ok(*n),
|
||||||
NumberOrString::String(s) => {
|
Self::String(s) => s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string())),
|
||||||
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 {
|
pub fn convert_json_key_lcase_first(src_json: Value) -> Value {
|
||||||
match src_json {
|
match src_json {
|
||||||
Value::Array(elm) => {
|
Value::Array(mut elm) => {
|
||||||
let mut new_array: Vec<Value> = Vec::with_capacity(elm.len());
|
for obj in &mut elm {
|
||||||
|
*obj = convert_json_key_lcase_first(obj.take());
|
||||||
for obj in elm {
|
|
||||||
new_array.push(convert_json_key_lcase_first(obj));
|
|
||||||
}
|
}
|
||||||
Value::Array(new_array)
|
Value::Array(elm)
|
||||||
}
|
}
|
||||||
|
|
||||||
Value::Object(obj) => {
|
Value::Object(obj) => {
|
||||||
let mut json_map = JsonMap::new();
|
let mut json_map = JsonMap::new();
|
||||||
for (key, value) in obj {
|
for (key, value) in obj {
|
||||||
match (key, value) {
|
json_map.insert(process_json_key(key), convert_json_key_lcase_first(value));
|
||||||
(key, Value::Object(elm)) => {
|
|
||||||
let inner_value = convert_json_key_lcase_first(Value::Object(elm));
|
|
||||||
json_map.insert(process_json_key(&key), inner_value);
|
|
||||||
}
|
|
||||||
|
|
||||||
(key, Value::Array(elm)) => {
|
|
||||||
let mut inner_array: Vec<Value> = Vec::with_capacity(elm.len());
|
|
||||||
|
|
||||||
for inner_obj in elm {
|
|
||||||
inner_array.push(convert_json_key_lcase_first(inner_obj));
|
|
||||||
}
|
|
||||||
|
|
||||||
json_map.insert(process_json_key(&key), Value::Array(inner_array));
|
|
||||||
}
|
|
||||||
|
|
||||||
(key, value) => {
|
|
||||||
json_map.insert(process_json_key(&key), value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Value::Object(json_map)
|
Value::Object(json_map)
|
||||||
}
|
}
|
||||||
|
|
||||||
value => value,
|
value => value,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum FeatureFlagFilter {
|
pub enum FeatureFlagFilter {
|
||||||
#[allow(dead_code)]
|
|
||||||
Unfiltered,
|
|
||||||
ValidOnly,
|
ValidOnly,
|
||||||
InvalidOnly,
|
InvalidOnly,
|
||||||
}
|
}
|
||||||
@@ -891,7 +842,6 @@ pub fn parse_experimental_client_feature_flags(
|
|||||||
.map(str::trim)
|
.map(str::trim)
|
||||||
.filter(|flag| !flag.is_empty())
|
.filter(|flag| !flag.is_empty())
|
||||||
.filter(|flag| match filter_mode {
|
.filter(|flag| match filter_mode {
|
||||||
FeatureFlagFilter::Unfiltered => true,
|
|
||||||
FeatureFlagFilter::ValidOnly => SUPPORTED_FEATURE_FLAGS.contains(flag),
|
FeatureFlagFilter::ValidOnly => SUPPORTED_FEATURE_FLAGS.contains(flag),
|
||||||
FeatureFlagFilter::InvalidOnly => !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::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")]
|
#[expect(clippy::decimal_bitwise_operands, reason = "Mostly copy/paste from std, keep as-is")]
|
||||||
#[cfg(any(not(feature = "unstable"), test))]
|
#[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 {
|
match ip {
|
||||||
std::net::IpAddr::V4(ip) => {
|
core::net::IpAddr::V4(ip) => {
|
||||||
!(ip.octets()[0] == 0 // "This network"
|
!(ip.octets()[0] == 0 // "This network"
|
||||||
|| ip.is_private()
|
|| ip.is_private()
|
||||||
|| (ip.octets()[0] == 100 && (ip.octets()[1] & 0b1100_0000 == 0b0100_0000)) // ip.is_shared()
|
|| (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()[0] == 192 && ip.octets()[1] == 0 && ip.octets()[2] == 0
|
||||||
&& ip.octets()[3] != 9 && ip.octets()[3] != 10
|
&& 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.is_documentation()
|
||||||
|| (ip.octets()[0] == 198 && (ip.octets()[1] & 0xfe) == 18) // ip.is_benchmarking()
|
|| (ip.octets()[0] == 198 && (ip.octets()[1] & 0xfe) == 18) // ip.is_benchmarking()
|
||||||
|| (ip.octets()[0] & 240 == 240 && !ip.is_broadcast()) // ip.is_reserved()
|
|| (ip.octets()[0] & 240 == 240 && !ip.is_broadcast()) // ip.is_reserved()
|
||||||
|| ip.is_broadcast())
|
|| ip.is_broadcast())
|
||||||
}
|
}
|
||||||
std::net::IpAddr::V6(ip) => {
|
core::net::IpAddr::V6(ip) => {
|
||||||
!(ip.is_unspecified()
|
!(ip.is_unspecified()
|
||||||
|| ip.is_loopback()
|
|| ip.is_loopback()
|
||||||
// IPv4-mapped Address (`::ffff:0:0/96`)
|
// 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, _, _, _, _, _])
|
|| matches!(ip.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
|
||||||
// Discard-Only Address Block (`100::/64`)
|
// Discard-Only Address Block (`100::/64`)
|
||||||
|| matches!(ip.segments(), [0x100, 0, 0, 0, _, _, _, _])
|
|| 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`)
|
// IETF Protocol Assignments (`2001::/23`)
|
||||||
|| (matches!(ip.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
|
|| (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
|
u128::from_be_bytes(ip.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
|
||||||
// Traversal Using Relays around NAT Anycast (`2001:1::2`)
|
// Traversal Using Relays around NAT Anycast (`2001:1::2`)
|
||||||
|| u128::from_be_bytes(ip.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
|
|| 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`)
|
// AMT (`2001:3::/32`)
|
||||||
|| matches!(ip.segments(), [0x2001, 3, _, _, _, _, _, _])
|
|| matches!(ip.segments(), [0x2001, 3, _, _, _, _, _, _])
|
||||||
// AS112-v6 (`2001:4:112::/48`)
|
// AS112-v6 (`2001:4:112::/48`)
|
||||||
@@ -1027,11 +983,11 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore = "exhaustive IPv4 check is too slow for the regular test suite"]
|
#[ignore = "exhaustive IPv4 check is too slow for the regular test suite"]
|
||||||
fn test_ipv4_global() {
|
fn test_ipv4_global() {
|
||||||
for a in 0..u8::MAX {
|
for a in 0..=u8::MAX {
|
||||||
println!("Iter: {a}/255");
|
println!("Iter: {a}/255");
|
||||||
for b in 0..u8::MAX {
|
for b in 0..=u8::MAX {
|
||||||
for c in 0..u8::MAX {
|
for c in 0..=u8::MAX {
|
||||||
for d in 0..u8::MAX {
|
for d in 0..=u8::MAX {
|
||||||
let ip = IpAddr::V4(std::net::Ipv4Addr::new(a, b, c, d));
|
let ip = IpAddr::V4(std::net::Ipv4Addr::new(a, b, c, d));
|
||||||
assert_eq!(ip.is_global(), is_global_hardcoded(ip), "IP mismatch: {ip}");
|
assert_eq!(ip.is_global(), is_global_hardcoded(ip), "IP mismatch: {ip}");
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user