mirror of
https://github.com/dani-garcia/vaultwarden.wiki.git
synced 2026-11-13 16:48:36 +02:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
816911001c |
No files matched your search
@@ -411,9 +411,6 @@
|
||||
## - "biometrics-sdk-ipc": Enable biometric unlock over the SDK IPC framework (Desktop >= 2026.9.0, Browser >= 2026.9.0)
|
||||
## - "windows-native-credential-sync": Register the desktop app as a passkey provider in Windows, so passkeys in the vault can be used by other apps and browsers.
|
||||
## Requires the Microsoft Store (appx) build of the desktop app. Stable releases up to and including 2026.9.1 lack the required plugin registration, so it has no effect there yet.
|
||||
## - "pm-27278-v2-password-registration": Register new accounts with v2 encryption. (Web >= 2026.6.4, Desktop/Browser/CLI >= 2026.7.0, Android >= 2026.4.1, iOS >= 2026.5.1)
|
||||
## - "enable-account-encryption-v2-jit-password-registration": Give SSO users who set their master password on their first login v2 encryption. (Web >= 2026.1.1, Desktop/Browser/CLI >= 2026.1.0, Android >= 2026.4.1, iOS >= 2026.6.0)
|
||||
## These two flags can't be undone: a v2 account stays v2, and it can only log in from clients that are 2026.10.1 or newer (2026.10.2 for the desktop app), so the versions above are only enough to create one.
|
||||
# EXPERIMENTAL_CLIENT_FEATURE_FLAGS=
|
||||
|
||||
## Require new device emails. When a user logs in an email is required to be sent.
|
||||
|
||||
@@ -4,3 +4,4 @@
|
||||
/.github/ISSUE_TEMPLATE/** @dani-garcia @BlackDex
|
||||
/.github/workflows/** @dani-garcia @BlackDex
|
||||
/SECURITY.md @dani-garcia @BlackDex
|
||||
/THREAT_MODEL.md @dani-garcia @BlackDex
|
||||
+3
-2
@@ -14,8 +14,9 @@ extend-ignore-re = [
|
||||
# In SMTP it's called HELO, so ignore it
|
||||
"(?i)helo_name",
|
||||
"Server name sent during.+HELO",
|
||||
# COSE Is short for CBOR Object Signing and Encryption
|
||||
"(?i)cose",
|
||||
# COSE Is short for CBOR Object Signing and Encryption, ignore these specific items
|
||||
"COSEKey",
|
||||
"COSEAlgorithm",
|
||||
# Ignore this specific string as it's valid
|
||||
"Ensure they are valid OTPs",
|
||||
# This word is misspelled upstream
|
||||
|
||||
+1
-1
@@ -107,7 +107,7 @@ serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
|
||||
# A safe, extensible ORM and Query builder
|
||||
diesel = { version = "2.3.14", features = ["chrono", "r2d2", "numeric", "64-column-tables"] }
|
||||
diesel = { version = "2.3.14", features = ["chrono", "r2d2", "numeric"] }
|
||||
diesel_migrations = "2.3.2"
|
||||
|
||||
derive_more = { version = "2.1.1", features = [
|
||||
|
||||
+24
-35
@@ -1,49 +1,38 @@
|
||||
Vaultwarden tries to prevent security issues but there could always slip something through.
|
||||
If you believe you've found a security issue in our application, we encourage you to
|
||||
notify us. We welcome working with you to resolve the issue promptly. Thanks in advance!
|
||||
Vaultwarden tries to prevent security issues, but something could always slip through. If you believe you've found a security issue in our application, we encourage you to notify us. We welcome working with you to resolve the issue promptly. Thanks in advance!
|
||||
|
||||
# Disclosure Policy
|
||||
# Scope
|
||||
|
||||
- Let us know as soon as possible upon discovery of a potential security issue, and we'll make every
|
||||
effort to quickly resolve the issue.
|
||||
- Provide us a reasonable amount of time to resolve the issue before any disclosure to the public or a
|
||||
third-party. We may publicly disclose the issue before resolving it, if appropriate.
|
||||
- Make a good faith effort to avoid privacy violations, destruction of data, and interruption or
|
||||
degradation of our service. Only interact with accounts you own or with explicit permission of the
|
||||
account holder.
|
||||
Security issues in the current release of Vaultwarden and in the `main` branch (the `testing` image) are in scope. Our [threat model](THREAT_MODEL.md) describes who is trusted with what, what is out of scope, and how we rate severity. Please read it before reporting.
|
||||
|
||||
# In-scope
|
||||
# How to report a security issue
|
||||
|
||||
- Security issues in any current release of Vaultwarden. Source code is available at https://github.com/dani-garcia/vaultwarden. This includes the current `latest` release and `main / testing` release.
|
||||
- Let us know as soon as possible upon discovery of a potential security issue, and we'll make every effort to quickly resolve the issue.
|
||||
- Provide us a reasonable amount of time to resolve the issue before any disclosure to the public or a third party. We may publicly disclose the issue before resolving it, if appropriate.
|
||||
- Credit goes on the advisory and needs a GitHub account or email address. Reports of an issue whose fix is already public, from the moment its pull request is opened, are normally not credited.
|
||||
- Vaultwarden is an open source project and does not offer rewards.
|
||||
|
||||
# Exclusions
|
||||
|
||||
The following bug classes are out-of scope:
|
||||
|
||||
- Bugs that are already reported on Vaultwarden's issue tracker (https://github.com/dani-garcia/vaultwarden/issues)
|
||||
- Bugs that are not part of Vaultwarden, like on the web-vault or mobile and desktop clients. These issues need to be reported in the respective project issue tracker at https://github.com/bitwarden to which we are not associated
|
||||
- Issues in an upstream software dependency (ex: Rust, or External Libraries) which are already reported to the upstream maintainer
|
||||
- Attacks requiring physical access to a user's device
|
||||
- Issues related to software or protocols not under Vaultwarden's control
|
||||
- Vulnerabilities in outdated versions of Vaultwarden
|
||||
- Missing security best practices that do not directly lead to a vulnerability (You may still report them as a normal issue)
|
||||
- Issues that do not have any impact on the general public
|
||||
Vaultwarden has no hosted service. Test only on instances you run yourself, and make a good-faith effort to avoid privacy violations, destruction of data, and interruption or degradation of other people's servers. Only interact with accounts you own or with the explicit permission of the account holder.
|
||||
|
||||
While researching, we'd like to ask you to refrain from:
|
||||
|
||||
- Denial of service
|
||||
- Spamming
|
||||
- Social engineering (including phishing) of Vaultwarden developers, contributors or users
|
||||
- Denial of service against servers you do not run. You can still report availability issues you reproduce on your own instance.
|
||||
- Spamming.
|
||||
- Social engineering (including phishing) of Vaultwarden developers, contributors or users.
|
||||
|
||||
Thank you for helping keep Vaultwarden and our users safe!
|
||||
A good report covers one root cause and states the version or commit you tested, the lowest privileges needed, what the attacker gains, any non-default settings, the steps to reproduce it, and whether you ran them or only read the code.
|
||||
|
||||
If you use AI tools, you remain responsible for what you send. Reproduce the issue on your own instance before reporting it, check its scope and severity against our threat model rather than the tool's assessment, and include the requests, responses or logs that show it.
|
||||
|
||||
# How to contact us
|
||||
|
||||
- You can contact us on Matrix https://matrix.to/#/#vaultwarden:matrix.org (users: `@danig:matrix.org` and/or `@blackdex:matrix.org`)
|
||||
- You can open a [private vulnerability report](https://github.com/dani-garcia/vaultwarden/security/advisories/new) on GitHub.
|
||||
- You can send an  to report a security issue.<br>
|
||||
If you want to send an encrypted email you can use the following GPG key: 13BB3A34C9E380258CE43D595CB150B31F6426BC<br>
|
||||
If you want to send an encrypted email, you can use the following GPG key: `13BB3A34C9E380258CE43D595CB150B31F6426BC`<br>
|
||||
It can be found on several public GPG key servers.<br>
|
||||
* https://keys.openpgp.org/search?q=security%40vaultwarden.org
|
||||
* https://keys.mailvelope.com/pks/lookup?op=get&search=security%40vaultwarden.org
|
||||
* https://pgpkeys.eu/pks/lookup?search=security%40vaultwarden.org&fingerprint=on&op=index
|
||||
* https://keyserver.ubuntu.com/pks/lookup?search=security%40vaultwarden.org&fingerprint=on&op=index
|
||||
- https://keys.openpgp.org/search?q=security%40vaultwarden.org
|
||||
- https://keys.mailvelope.com/pks/lookup?op=get&search=security%40vaultwarden.org
|
||||
- https://pgpkeys.eu/pks/lookup?search=security%40vaultwarden.org&fingerprint=on&op=index
|
||||
- https://keyserver.ubuntu.com/pks/lookup?search=security%40vaultwarden.org&fingerprint=on&op=index
|
||||
- You can contact us on Matrix for questions, without vulnerability details: https://matrix.to/#/#vaultwarden:matrix.org (users: `@danig:matrix.org` and/or `@blackdex:matrix.org`).
|
||||
|
||||
Thank you for helping keep Vaultwarden and our users safe!
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
# Vaultwarden threat model
|
||||
|
||||
To report a security issue, see [SECURITY.md](SECURITY.md).
|
||||
|
||||
## Overview
|
||||
|
||||
Vaultwarden is an unofficial, self-hosted server for the Bitwarden clients, written in Rust. It stores encrypted vaults, handles login, two-factor authentication, organizations, file and text sharing through Send, and emergency access, and provides an admin panel for the operator. It is not affiliated with Bitwarden. The browser, desktop, mobile and CLI clients come from Bitwarden. Our container images include a web vault built from Bitwarden's web client with our own patches.
|
||||
|
||||
## Security expectations
|
||||
|
||||
### Deployment
|
||||
|
||||
We expect a TLS-terminating reverse proxy in front of the server, `DOMAIN` set to its public URL, and an operator who keeps the host secure. This model covers Vaultwarden itself. Third-party software that consumes its output or sits in front of it, such as log parsers and reverse proxies, is the operator's to configure and secure.
|
||||
|
||||
### Encryption
|
||||
|
||||
Clients encrypt vault contents end to end. The server stores and serves ciphertext it cannot decrypt, and it never sees the master password. The server enforces access to data and actions itself, without relying on a client to behave. A few settings rely on the client for part of their effect, listed under [Out of scope](#out-of-scope).
|
||||
|
||||
A member receives the organization key when they are confirmed. Invited and accepted members do not have it. A revoked member who was once confirmed may still have it. Every confirmed member holds the same key for the whole organization, so only the server separates collections.
|
||||
|
||||
The server can read everything that is not end-to-end encrypted, such as user, group, device and organization names, email addresses, who owns what, item types and timestamps, attachment sizes, password hints, the stored master password hash and KDF settings, the TOTP and other 2FA secrets that protect login to the account, API keys, refresh tokens, security stamps, the JWT signing key, and SMTP and push credentials. TOTP secrets that users store in vault items are end-to-end encrypted with the rest of the item.
|
||||
|
||||
Someone who controls the server can also serve a modified web vault, so end-to-end encryption does not protect web vault users from them.
|
||||
|
||||
### Trust
|
||||
|
||||
Registration is open by default (`SIGNUPS_ALLOWED=true`), but many personal and small-team instances turn it off, so holding an account usually implies a minimal level of trust. Account holders are still never trusted with anyone else's data. Members of an organization have some trust in each other.
|
||||
|
||||
| Actor | Can reach | Must not reach |
|
||||
|---|---|---|
|
||||
| Anonymous internet | Login, prelogin, registration, public Send access, icons, the anonymous notifications hub, static files | Any vault, organization or member data; Sends they have no link to; the admin panel; the internal network through outbound requests |
|
||||
| Websites and icon sources | The icon fetcher, through any response, redirect or DNS answer; the server, through cross-site requests from a visitor's browser | The internal network through outbound requests; script on the vault origin; acting through a visitor's session |
|
||||
| Registered user | Their own vault, Sends, devices and settings; organizations they belong to | Another user's data; any other organization; raising their own role or status |
|
||||
| Invited or accepted member | Accepting the invitation, enrolling in account recovery, and the organization's name, public key and policies | Items, collections, the member list, the organization key, any other privileged action before confirmation |
|
||||
| Revoked member | Nothing in that organization | Any organization data from the server, even data they could once read |
|
||||
| Organization User | Items in assigned collections, with `read_only` and `manage` enforced by the server | Other collections, write access to read-only collections, Admin-level metadata |
|
||||
| Organization Manager (a legacy role, shown as Custom in clients) | The above, plus managing collections where they have `manage`. With "Manage all collections" (`access_all`), every collection and full member and group details | Without `access_all`: managing other collections, full member and group details. Always: changing policies or roles |
|
||||
| Organization Admin | All data in that organization, members below Owner (some actions on Managers and Admins are limited to Owners), policies, events, account recovery for enrolled members below Owner | Owners, other organizations, the personal vault of a member who is not enrolled in recovery, the organization API key |
|
||||
| Organization Owner | The whole organization, including account recovery for enrolled members | Other organizations, the personal vault of a member who is not enrolled in recovery |
|
||||
| Organization API key holder (Owner-issued) | Directory import into its own organization | Other organizations, item content, Owners |
|
||||
| Send recipient | One Send, within its limits | Other Sends, access beyond the configured limits, the owner's vault |
|
||||
| Emergency access grantee | After approval or the wait time: the access the grantor configured, which can be full takeover by design | Anything before that, or more than the access the grantor configured |
|
||||
| Admin panel (`ADMIN_TOKEN`) | All users, organizations and settings | No limit once authenticated |
|
||||
| Host operator, database and data folder access | Everything | No limit |
|
||||
| Services the operator configures (SSO provider, SMTP server, push relay, S3 endpoint, Yubico) | What they need for their function | Vault contents |
|
||||
|
||||
### Configuration
|
||||
|
||||
Optional features that operators turn on, other than experimental and beta ones, carry the same expectations as the defaults, such as SSO, organization events, anything needing SMTP (email 2FA, invitations), push, S3 storage, the admin panel, and the MySQL and PostgreSQL backends.
|
||||
|
||||
Some settings remove a protection on purpose, and using them is the operator's choice: `DISABLE_ADMIN_TOKEN`, a plain-text `ADMIN_TOKEN`, `IP_HEADER_TRUSTED_PROXIES=all` on a directly exposed instance, turning off `HTTP_REQUEST_BLOCK_NON_GLOBAL_IPS`, `SSO_DEBUG_TOKENS`, `SSO_ALLOW_UNKNOWN_EMAIL_VERIFICATION`, `SSO_PKCE=false`, `SHOW_PASSWORD_HINT`, `SMTP_SECURITY=off`, `SMTP_ACCEPT_INVALID_CERTS`, `SMTP_ACCEPT_INVALID_HOSTNAMES`, `SMTP_DEBUG`, `ALLOWED_IFRAME_ANCESTORS`, `ALLOWED_CONNECT_SRC`, and `LOG_LEVEL` set to `debug` or `trace`. Issues that need one of them are out of scope.
|
||||
|
||||
### Upstream Bitwarden
|
||||
|
||||
Where this document does not cover a behavior, we follow upstream Bitwarden by default.
|
||||
|
||||
## Out of scope
|
||||
|
||||
These are intended behavior or outside this model. Several match upstream Bitwarden.
|
||||
|
||||
- What an admin token holder or the host operator can do, including running code on the server. We expect them to have admin access to the machine.
|
||||
- Organization Owners and Admins reading all organization data, and account recovery of enrolled members.
|
||||
- Organization Managers listing basic member details, such as names and emails. Upstream allows this for all members.
|
||||
- Settings the client applies: `hide_passwords` ("hidden passwords" in the clients), master password reprompt, and organization policies on values the server never sees, such as master password complexity and password generator rules. The client already holds the data.
|
||||
- Bugs in Bitwarden's client code, including in the web vault we bundle, such as CSV formula injection (exports are built in the browser) or a client failing on a malformed stored value. The advisory and CVE for those belong to Bitwarden. Report them through [Bitwarden's HackerOne program](https://hackerone.com/bitwarden/). When the bundled web vault is affected, we ship a security release that references theirs. Bugs that our own web vault patches add are ours.
|
||||
- The server not decrypting or authenticating ciphertext. It holds no key.
|
||||
- `/identity/accounts/prelogin` and `/identity/accounts/prelogin/password` returning KDF settings for any email, with deterministic fake settings for unknown ones.
|
||||
- Login timing not being equalized.
|
||||
- Probing whether an icon is already cached. Setting `ICON_SERVICE` to an external service avoids it.
|
||||
- Download link replay: an attachment token or Send access token being reusable by its holder until it expires (1 and 2 minutes), and object storage presigned URLs that we cannot count or revoke. The holder already has the content.
|
||||
- Short-lived tokens that stay valid after an authorization change elsewhere until they expire, such as an organization API token (1 hour) after its key is rotated. This includes connections the notifications WebSocket accepted before the change, which stay open and carry change notifications and device login requests, not vault data.
|
||||
- The access token in the notifications WebSocket's `access_token` query parameter, which reverse proxies may log. Clients send it that way, and our [hardening guide](https://github.com/dani-garcia/vaultwarden/wiki/Hardening-Guide#access-logs-contain-access_token-parameter) covers redacting it.
|
||||
- The personal API key skipping 2FA, and working after a password change until the user rotates it. It is a separate credential.
|
||||
- A revoked or removed member's login session staying valid. It belongs to their own account, and the server checks membership on every request.
|
||||
- A revoked or removed member keeping what their client already synced, and the organization key not being rotated when a member leaves.
|
||||
- Unauthenticated requests to `/api/devices/identifier/<id>/clear-token`. The impact is delayed push delivery.
|
||||
- Limits we leave out or keep simple by design: no cap on the number of items a user stores, no cleanup of attachments reserved but never uploaded, and rate limits kept in memory per process and IP, which reset on restart and are shared by users behind one address.
|
||||
- Log injection. It only affects software that parses our logs, such as Fail2Ban with our community wiki's filters.
|
||||
- Attacks that need a misconfigured reverse proxy, such as one not sending `X-Forwarded-Proto` (it decides the admin cookie's `Secure` flag).
|
||||
- Attacks that need another component to break its own specification, such as a NAT64 translator that forwards the `64:ff9b::/96` prefix to private addresses, against RFC 6052.
|
||||
- Outbound requests to the SSO provider, Yubico server or S3 endpoint the operator configures, which skip the outbound filter and can be on the internal network.
|
||||
- File permissions in the data folder. Host security belongs to the operator.
|
||||
- Attacks that need physical access to a user's device.
|
||||
- Self-exploitation, where someone can only affect their own account, such as self-XSS or weak KDF settings they choose.
|
||||
- Text that users choose showing up in emails or pages, such as an organization, user or device name, as long as it can't cause XSS or modify the page.
|
||||
- Dependency and base image CVEs without a path reachable through Vaultwarden.
|
||||
- Packages, images and deployment templates that we don't publish. Report those to their maintainers.
|
||||
- Missing best practices with no demonstrated impact, such as security headers, `style-src 'unsafe-inline'` (the web vault needs it) or version disclosure, and design recommendations without a concrete issue.
|
||||
- Bugs already reported on our [issue tracker](https://github.com/dani-garcia/vaultwarden/issues).
|
||||
- Experimental and beta features. They are opt-in and outside this model until they are stable.
|
||||
- Issues that only affect outdated versions.
|
||||
|
||||
## Severity
|
||||
|
||||
We rate issues by what the attacker ends up with, such as decrypted data, ciphertext, or the power to change or delete data, and by the access they needed first. An attack that needs no account usually rates higher than one that does. Our ratings can differ from CVSS 3.1, which doesn't translate well to an end-to-end encrypted system. Older advisories may be rated differently.
|
||||
|
||||
Denial of service and resource exhaustion only count if they still apply with a reverse proxy in front. Races, denial of service and resource exhaustion are never rated above Medium.
|
||||
|
||||
Secrets written to logs at the default log level are rated by what they give someone who can read the logs but not the host.
|
||||
|
||||
### Critical
|
||||
|
||||
- Reading another account's data decrypted, with or without an account, such as through script on the vault origin or exposed key material.
|
||||
- Code execution on the server by anyone other than an admin token holder.
|
||||
- Changing released builds or images, including through our CI workflows or their secrets.
|
||||
- Anyone other than the named grantee reaching an emergency access outcome.
|
||||
- With no account: forging login or admin tokens, reading the JWT signing key, reaching the admin panel without the token, or taking over accounts with no action by the victim.
|
||||
|
||||
### High
|
||||
|
||||
- Decrypted reads within the same organization, such as a member reaching collections they are not assigned to.
|
||||
- Changing or deleting another user's or organization's existing data.
|
||||
- Reading another user's server-held secrets, such as their 2FA secrets, API keys, stored master password hash or encrypted user key.
|
||||
- SSRF that returns the response to the attacker.
|
||||
- Escalating within an organization.
|
||||
- Account takeover through SSO.
|
||||
- The named emergency access grantee reaching the outcome early.
|
||||
- Script or a cross-site request acting through an admin panel session.
|
||||
- Script on the vault origin that needs unusual victim interaction.
|
||||
|
||||
### Medium
|
||||
|
||||
- Ciphertext read by someone with no key.
|
||||
- Defeating login brute-force protection.
|
||||
- 2FA bypass that needs the password, such as a remembered device still skipping 2FA after the method is removed.
|
||||
- A refresh token still working after a password change or "Deauthorize sessions".
|
||||
- Getting past an organization policy the server enforces.
|
||||
- Adding data to another user's or organization's space without permission.
|
||||
- Data loss for another user or organization that the attacker cannot reliably trigger or aim.
|
||||
- SSRF where the response is filtered or blind.
|
||||
- Reading a Send that is disabled or expired.
|
||||
- Denial of service that lasts until someone restarts the server or repairs data, from one request with no account in the default configuration.
|
||||
|
||||
### Low
|
||||
|
||||
These may be handled as ordinary hardening.
|
||||
|
||||
- Behavior that differs from upstream Bitwarden with low impact.
|
||||
- Bypassing a non-default limit, such as `USER_ATTACHMENT_LIMIT`.
|
||||
- Metadata across a boundary, such as who is assigned to which collection.
|
||||
- Exceeding a Send's access limits when the attacker already holds the link.
|
||||
- A missing rate limit outside login.
|
||||
- Forging organization audit events.
|
||||
- Other ways to tell whether an email has an account.
|
||||
- Denial of service that lasts until someone acts, from one operation that needs an account or a non-default setting.
|
||||
- Denial of service that lasts only while the attacker keeps going or that recovers by itself, such as a crash the container restarts from.
|
||||
Whitespace-only changes.
@@ -1,3 +0,0 @@
|
||||
-- A blob-encrypted cipher keeps all of its content in `data`, up to 500,000 characters, so the
|
||||
-- 64 KiB of TEXT is too small. Like upstream, which uses LONGTEXT.
|
||||
ALTER TABLE ciphers MODIFY data LONGTEXT NOT NULL;
|
||||
@@ -1,5 +0,0 @@
|
||||
DROP TABLE IF EXISTS user_signature_key_pairs;
|
||||
|
||||
ALTER TABLE users DROP COLUMN signed_public_key;
|
||||
ALTER TABLE users DROP COLUMN security_state;
|
||||
ALTER TABLE users DROP COLUMN security_version;
|
||||
@@ -1,14 +0,0 @@
|
||||
ALTER TABLE users ADD COLUMN signed_public_key TEXT;
|
||||
ALTER TABLE users ADD COLUMN security_state TEXT;
|
||||
ALTER TABLE users ADD COLUMN security_version INTEGER;
|
||||
|
||||
CREATE TABLE user_signature_key_pairs (
|
||||
uuid CHAR(36) NOT NULL PRIMARY KEY,
|
||||
user_uuid CHAR(36) NOT NULL UNIQUE,
|
||||
signature_algorithm INTEGER NOT NULL, -- 0 = ed25519, 1 = mldsa44
|
||||
signing_key TEXT NOT NULL,
|
||||
verifying_key TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
updated_at DATETIME NOT NULL,
|
||||
FOREIGN KEY (user_uuid) REFERENCES users (uuid) ON DELETE CASCADE
|
||||
);
|
||||
Whitespace-only changes.
@@ -1,4 +0,0 @@
|
||||
-- Key rotations before this kept the id of the old user key, so every new
|
||||
-- cipher was refused from then on. Stale ids can't be told apart, so clear
|
||||
-- all of them; clients record their current key's id again when it's empty.
|
||||
UPDATE users SET key_id = NULL;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users DROP COLUMN v2_upgrade_token;
|
||||
ALTER TABLE users_organizations DROP COLUMN v2_upgrade_token;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users ADD COLUMN v2_upgrade_token TEXT;
|
||||
ALTER TABLE users_organizations ADD COLUMN v2_upgrade_token TEXT;
|
||||
Whitespace-only changes.
@@ -1,3 +0,0 @@
|
||||
-- TEXT has no size limit here, only MySQL needed the change.
|
||||
-- PostgreSQL rejects a migration that is only comments ("Received an empty query"), hence the no-op.
|
||||
SELECT 1;
|
||||
@@ -1,5 +0,0 @@
|
||||
DROP TABLE IF EXISTS user_signature_key_pairs;
|
||||
|
||||
ALTER TABLE users DROP COLUMN signed_public_key;
|
||||
ALTER TABLE users DROP COLUMN security_state;
|
||||
ALTER TABLE users DROP COLUMN security_version;
|
||||
@@ -1,13 +0,0 @@
|
||||
ALTER TABLE users ADD COLUMN signed_public_key TEXT;
|
||||
ALTER TABLE users ADD COLUMN security_state TEXT;
|
||||
ALTER TABLE users ADD COLUMN security_version INTEGER;
|
||||
|
||||
CREATE TABLE user_signature_key_pairs (
|
||||
uuid CHAR(36) NOT NULL PRIMARY KEY,
|
||||
user_uuid CHAR(36) NOT NULL UNIQUE REFERENCES users (uuid) ON DELETE CASCADE,
|
||||
signature_algorithm INTEGER NOT NULL, -- 0 = ed25519, 1 = mldsa44
|
||||
signing_key TEXT NOT NULL,
|
||||
verifying_key TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL
|
||||
);
|
||||
Whitespace-only changes.
@@ -1,4 +0,0 @@
|
||||
-- Key rotations before this kept the id of the old user key, so every new
|
||||
-- cipher was refused from then on. Stale ids can't be told apart, so clear
|
||||
-- all of them; clients record their current key's id again when it's empty.
|
||||
UPDATE users SET key_id = NULL;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users DROP COLUMN v2_upgrade_token;
|
||||
ALTER TABLE users_organizations DROP COLUMN v2_upgrade_token;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users ADD COLUMN v2_upgrade_token TEXT;
|
||||
ALTER TABLE users_organizations ADD COLUMN v2_upgrade_token TEXT;
|
||||
Whitespace-only changes.
@@ -1 +0,0 @@
|
||||
-- TEXT has no size limit here, only MySQL needed the change
|
||||
@@ -1,5 +0,0 @@
|
||||
DROP TABLE IF EXISTS user_signature_key_pairs;
|
||||
|
||||
ALTER TABLE users DROP COLUMN signed_public_key;
|
||||
ALTER TABLE users DROP COLUMN security_state;
|
||||
ALTER TABLE users DROP COLUMN security_version;
|
||||
@@ -1,13 +0,0 @@
|
||||
ALTER TABLE users ADD COLUMN signed_public_key TEXT;
|
||||
ALTER TABLE users ADD COLUMN security_state TEXT;
|
||||
ALTER TABLE users ADD COLUMN security_version INTEGER;
|
||||
|
||||
CREATE TABLE user_signature_key_pairs (
|
||||
uuid TEXT NOT NULL PRIMARY KEY,
|
||||
user_uuid TEXT NOT NULL UNIQUE REFERENCES users (uuid) ON DELETE CASCADE,
|
||||
signature_algorithm INTEGER NOT NULL, -- 0 = ed25519, 1 = mldsa44
|
||||
signing_key TEXT NOT NULL,
|
||||
verifying_key TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
updated_at DATETIME NOT NULL
|
||||
);
|
||||
Whitespace-only changes.
@@ -1,4 +0,0 @@
|
||||
-- Key rotations before this kept the id of the old user key, so every new
|
||||
-- cipher was refused from then on. Stale ids can't be told apart, so clear
|
||||
-- all of them; clients record their current key's id again when it's empty.
|
||||
UPDATE users SET key_id = NULL;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users DROP COLUMN v2_upgrade_token;
|
||||
ALTER TABLE users_organizations DROP COLUMN v2_upgrade_token;
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE users ADD COLUMN v2_upgrade_token TEXT;
|
||||
ALTER TABLE users_organizations ADD COLUMN v2_upgrade_token TEXT;
|
||||
+1
-1
@@ -445,7 +445,7 @@ async fn delete_user(user_id: UserId, token: AdminToken, conn: DbConn, nt: Notif
|
||||
if res.is_ok() {
|
||||
nt.send_logout(&user, None, &conn).await;
|
||||
if has_push_device {
|
||||
push_logout_to_relay(&user, None, None);
|
||||
push_logout_to_relay(&user, None);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+172
-970
File diff suppressed because it is too large.
Load diff
+315
-860
File diff suppressed because it is too large.
Load diff
@@ -10,9 +10,7 @@ use crate::{
|
||||
auth::{AdminHeaders, Headers},
|
||||
db::{
|
||||
DbConn, DbPool,
|
||||
models::{
|
||||
Cipher, CipherAccessScope, CipherId, Event, EventType, Membership, MembershipId, OrganizationId, UserId,
|
||||
},
|
||||
models::{Cipher, CipherId, Event, EventType, Membership, MembershipId, OrganizationId, UserId},
|
||||
},
|
||||
error::MapResult,
|
||||
util::parse_date,
|
||||
@@ -222,7 +220,7 @@ async fn post_events_collect(data: Json<Vec<EventCollection>>, headers: Headers,
|
||||
// user can actually access it instead of trusting the provided cipher uuid.
|
||||
if let Some(cipher_uuid) = &event.cipher_id
|
||||
&& let Some(cipher) = Cipher::find_by_uuid(cipher_uuid, &conn).await
|
||||
&& cipher.is_accessible_to_user(&headers.user.uuid, CipherAccessScope::User, &conn).await
|
||||
&& cipher.is_accessible_to_user(&headers.user.uuid, &conn).await
|
||||
&& let Some(org_id) = cipher.organization_uuid
|
||||
{
|
||||
log_event_impl(
|
||||
|
||||
+28
-114
@@ -8,18 +8,17 @@ use crate::{
|
||||
CONFIG,
|
||||
api::admin::FAKE_ADMIN_UUID,
|
||||
api::{
|
||||
ApiResult, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType,
|
||||
EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType,
|
||||
core::{CipherSyncData, CipherSyncType, accept_org_invite, log_event, two_factor},
|
||||
},
|
||||
auth::{AdminHeaders, Headers, ManagerHeaders, ManagerHeadersLoose, OrgMemberHeaders, OwnerHeaders, decode_invite},
|
||||
db::{
|
||||
DbConn,
|
||||
models::{
|
||||
Cipher, CipherAccessScope, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId,
|
||||
CollectionUser, CustomPermission, Device, EventType, FillAssistPolicyData, Group, GroupId, GroupUser,
|
||||
Invitation, Membership, MembershipId, MembershipStatus, MembershipType, OrgPolicy, OrgPolicyType,
|
||||
Organization, OrganizationApiKey, OrganizationId, TwoFactor, TwoFactorType, User, UserId,
|
||||
custom_roles_enabled,
|
||||
Cipher, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId, CollectionUser,
|
||||
CustomPermission, Device, EventType, FillAssistPolicyData, Group, GroupId, GroupUser, Invitation,
|
||||
Membership, MembershipId, MembershipStatus, MembershipType, OrgPolicy, OrgPolicyType, Organization,
|
||||
OrganizationApiKey, OrganizationId, TwoFactor, TwoFactorType, User, UserId, custom_roles_enabled,
|
||||
},
|
||||
},
|
||||
mail,
|
||||
@@ -48,7 +47,6 @@ pub fn routes() -> Vec<Route> {
|
||||
bulk_delete_organization_collections,
|
||||
post_bulk_collections,
|
||||
get_org_details,
|
||||
get_assigned_org_details,
|
||||
get_org_domain_sso_verified,
|
||||
get_members,
|
||||
send_invite,
|
||||
@@ -843,7 +841,7 @@ async fn get_org_details(data: OrgIdData, headers: ManagerHeadersLoose, conn: Db
|
||||
err_code!("Resource not found.", "Organization id's do not match", Status::NotFound.code);
|
||||
}
|
||||
|
||||
if !headers.membership.can_edit_any_collection() {
|
||||
if !headers.membership.has_full_access() {
|
||||
err_code!("Resource not found.", "User does not have full access", Status::NotFound.code);
|
||||
}
|
||||
|
||||
@@ -861,12 +859,7 @@ async fn get_org_details_impl(
|
||||
conn: &DbConn,
|
||||
) -> Result<Value, crate::Error> {
|
||||
let ciphers = Cipher::find_by_org(org_id, conn).await;
|
||||
let mut cipher_sync_data = CipherSyncData::new(user_id, CipherSyncType::Organization, conn).await;
|
||||
// Every cipher of the organization is listed, so list every collection of them too
|
||||
cipher_sync_data.cipher_collections = HashMap::new();
|
||||
for (cipher_id, collection_id) in Cipher::get_collections_with_cipher_by_organization(org_id, conn).await {
|
||||
cipher_sync_data.cipher_collections.entry(cipher_id).or_default().push(collection_id);
|
||||
}
|
||||
let cipher_sync_data = CipherSyncData::new(user_id, CipherSyncType::Organization, conn).await;
|
||||
|
||||
let mut ciphers_json = Vec::with_capacity(ciphers.len());
|
||||
for c in ciphers {
|
||||
@@ -875,39 +868,6 @@ async fn get_org_details_impl(
|
||||
Ok(json!(ciphers_json))
|
||||
}
|
||||
|
||||
// The Admin Console lists these instead of every cipher of the organization for a member who may not edit every
|
||||
// cipher, like a Custom member with Delete any collection only. As in Bitwarden, any confirmed member may list them.
|
||||
#[get("/ciphers/organization-details/assigned?<data..>")]
|
||||
async fn get_assigned_org_details(data: OrgIdData, headers: Headers, conn: DbConn) -> JsonResult {
|
||||
let Some(member) =
|
||||
Membership::find_confirmed_by_user_and_org(&headers.user.uuid, &data.organization_id, &conn).await
|
||||
else {
|
||||
err_code!("Resource not found.", "User is not a confirmed member of the organization", Status::NotFound.code);
|
||||
};
|
||||
|
||||
let (assigned, unassigned) = Cipher::find_assigned_to_member(&member, &conn).await;
|
||||
let mut ciphers_json = Vec::with_capacity(assigned.len() + unassigned.len());
|
||||
// The ciphers of the member's own vault, as they are there
|
||||
let cipher_sync_data = CipherSyncData::new(&headers.user.uuid, CipherSyncType::User, &conn).await;
|
||||
for cipher in assigned {
|
||||
ciphers_json.push(
|
||||
cipher
|
||||
.to_json(&headers.host, &headers.user.uuid, Some(&cipher_sync_data), CipherSyncType::User, &conn)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
// The ciphers in no collection, as the member may use them in the Admin Console
|
||||
for cipher in unassigned {
|
||||
ciphers_json.push(cipher.to_json_org_admin(&headers.host, &headers.user.uuid, &conn).await?);
|
||||
}
|
||||
|
||||
Ok(Json(json!({
|
||||
"data": ciphers_json,
|
||||
"object": "list",
|
||||
"continuationToken": null,
|
||||
})))
|
||||
}
|
||||
|
||||
// Returning a Domain/Organization here allow to prefill it and prevent prompting the user
|
||||
// So we return a dummy value, since we only support a single SSO integration, and do not use the response anywhere
|
||||
// In use since `v2025.6.0`, appears to use only the first `organizationIdentifier`
|
||||
@@ -1906,7 +1866,7 @@ async fn post_org_import(
|
||||
cipher_data.folder_id = None;
|
||||
// Replace the client-provided, unvalidated organizationId with the real target org
|
||||
cipher_data.organization_id = Some(org_id.clone());
|
||||
let mut cipher = Cipher::new(cipher_data.r#type);
|
||||
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone());
|
||||
update_cipher_from_data(
|
||||
&mut cipher,
|
||||
cipher_data,
|
||||
@@ -1915,7 +1875,6 @@ async fn post_org_import(
|
||||
&conn,
|
||||
&nt,
|
||||
UpdateType::None,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
@@ -1949,37 +1908,29 @@ struct BulkCollectionsData {
|
||||
async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
let data: BulkCollectionsData = data.into_inner();
|
||||
|
||||
let Some(member) =
|
||||
Membership::find_confirmed_by_user_and_org(&headers.user.uuid, &data.organization_id, &conn).await
|
||||
else {
|
||||
if Membership::find_confirmed_by_user_and_org(&headers.user.uuid, &data.organization_id, &conn).await.is_none() {
|
||||
err!("You need to be a Member of the Organization to call this endpoint")
|
||||
};
|
||||
// A member who may edit any collection may use every collection of the organization
|
||||
let can_edit_any_collection = member.can_edit_any_collection();
|
||||
}
|
||||
|
||||
// Get all the collection available to the user in one query
|
||||
// Also filter based upon the provided collections
|
||||
let collections = if can_edit_any_collection {
|
||||
Collection::find_by_organization(&data.organization_id, &conn).await
|
||||
} else {
|
||||
Collection::find_by_organization_and_user_uuid(&data.organization_id, &headers.user.uuid, &conn).await
|
||||
};
|
||||
let user_collections: HashMap<CollectionId, Collection> = collections
|
||||
.into_iter()
|
||||
.filter_map(|c| {
|
||||
if data.collection_ids.contains(&c.uuid) {
|
||||
Some((c.uuid.clone(), c))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let user_collections: HashMap<CollectionId, Collection> =
|
||||
Collection::find_by_organization_and_user_uuid(&data.organization_id, &headers.user.uuid, &conn)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter_map(|c| {
|
||||
if data.collection_ids.contains(&c.uuid) {
|
||||
Some((c.uuid.clone(), c))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Verify if all the collections requested exists and are writable for the user, else abort
|
||||
for collection_uuid in &data.collection_ids {
|
||||
match user_collections.get(collection_uuid) {
|
||||
Some(collection)
|
||||
if can_edit_any_collection || collection.is_writable_by_user(&headers.user.uuid, &conn).await => {}
|
||||
Some(collection) if collection.is_writable_by_user(&headers.user.uuid, &conn).await => (),
|
||||
_ => err_code!("Resource not found", "User does not have access to a collection", 404),
|
||||
}
|
||||
}
|
||||
@@ -1988,7 +1939,7 @@ async fn post_bulk_collections(data: Json<BulkCollectionsData>, headers: Headers
|
||||
// Only act on existing cipher uuid's
|
||||
// Do not abort the operation just ignore it, it could be a cipher was just deleted for example
|
||||
if let Some(cipher) = Cipher::find_by_uuid_and_org(cipher_id, &data.organization_id, &conn).await
|
||||
&& cipher.is_write_accessible_to_user(&headers.user.uuid, CipherAccessScope::OrganizationAdmin, &conn).await
|
||||
&& cipher.is_write_accessible_to_user(&headers.user.uuid, &conn).await
|
||||
{
|
||||
// When selecting a specific collection from the left filter list, and use the bulk option, you can remove an item from that collection
|
||||
// In these cases the client will call this endpoint twice, once for adding the new collections and a second for deleting.
|
||||
@@ -2918,26 +2869,8 @@ struct OrganizationUserRecoverAccountRequest {
|
||||
// But the clients do not seem to use this at all
|
||||
// Just add it here in case they will
|
||||
#[get("/organizations/<org_id>/public-key")]
|
||||
async fn get_organization_public_key(
|
||||
org_id: OrganizationId,
|
||||
headers: Headers,
|
||||
member: Result<OrgMemberHeaders, &'static str>,
|
||||
conn: DbConn,
|
||||
) -> JsonResult {
|
||||
// SSO users without an org get the fake one, whose key the v2 JIT password flow fetches anyway
|
||||
if org_id.eq_ignore_ascii_case(FAKE_SSO_IDENTIFIER) && headers.user.private_key.is_none() {
|
||||
return Ok(Json(json!({
|
||||
"object": "organizationPublicKey",
|
||||
"publicKey": fake_sso_org_public_key().await?,
|
||||
})));
|
||||
}
|
||||
let member = match member {
|
||||
Ok(member) => member,
|
||||
// The guard already logged it
|
||||
Err(e) => return Err(crate::error::Error::new_msg(e).with_code(Status::Unauthorized.code)),
|
||||
};
|
||||
|
||||
if org_id != member.membership.org_uuid {
|
||||
async fn get_organization_public_key(org_id: OrganizationId, headers: OrgMemberHeaders, conn: DbConn) -> JsonResult {
|
||||
if org_id != headers.membership.org_uuid {
|
||||
err!("Organization not found", "Organization id's do not match");
|
||||
}
|
||||
let Some(org) = Organization::find_by_uuid(&org_id, &conn).await else {
|
||||
@@ -2950,30 +2883,11 @@ async fn get_organization_public_key(
|
||||
})))
|
||||
}
|
||||
|
||||
/// The SDK only uses this key to wrap an account recovery key that it never sends for the fake org,
|
||||
/// so it is made once and its private half dropped.
|
||||
async fn fake_sso_org_public_key() -> ApiResult<String> {
|
||||
static PUBLIC_KEY: std::sync::LazyLock<Option<String>> = std::sync::LazyLock::new(|| {
|
||||
let der = openssl::rsa::Rsa::generate(2048).and_then(|rsa| rsa.public_key_to_der()).ok()?;
|
||||
Some(data_encoding::BASE64.encode(&der))
|
||||
});
|
||||
|
||||
let Ok(Some(public_key)) = tokio::task::spawn_blocking(|| PUBLIC_KEY.clone()).await else {
|
||||
err!("Failed to generate the organization key")
|
||||
};
|
||||
Ok(public_key)
|
||||
}
|
||||
|
||||
// Obsolete - Renamed to public-key (2023.8), left for backwards compatibility with older clients
|
||||
// https://github.com/bitwarden/server/blob/9ebe16587175b1c0e9208f84397bb75d0d595510/src/Api/AdminConsole/Controllers/OrganizationsController.cs#L487-L492
|
||||
#[get("/organizations/<org_id>/keys")]
|
||||
async fn get_organization_keys(
|
||||
org_id: OrganizationId,
|
||||
headers: Headers,
|
||||
member: Result<OrgMemberHeaders, &'static str>,
|
||||
conn: DbConn,
|
||||
) -> JsonResult {
|
||||
get_organization_public_key(org_id, headers, member, conn).await
|
||||
async fn get_organization_keys(org_id: OrganizationId, headers: OrgMemberHeaders, conn: DbConn) -> JsonResult {
|
||||
get_organization_public_key(org_id, headers, conn).await
|
||||
}
|
||||
|
||||
// Will allow to reset 2FA too
|
||||
|
||||
+35
-133
@@ -29,7 +29,7 @@ use crate::{
|
||||
db::{
|
||||
DbConn,
|
||||
models::{
|
||||
AuthRequest, AuthRequestId, Device, DeviceId, DeviceType, EventType, Invitation, OIDCCodeResponseError,
|
||||
AuthRequest, AuthRequestId, Device, DeviceId, EventType, Invitation, OIDCCodeResponseError,
|
||||
OrganizationApiKey, OrganizationId, SendId, SsoAuth, SsoUser, TwoFactor, TwoFactorIncomplete,
|
||||
TwoFactorType, User, UserId,
|
||||
},
|
||||
@@ -77,14 +77,14 @@ async fn login(data: Form<ConnectData>, client_header: ClientHeaders, conn: DbCo
|
||||
check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?;
|
||||
check_is_some(data.device_type.as_ref(), "device_type cannot be blank")?;
|
||||
|
||||
password_login(data, &mut user_id, &conn, &client_header).await
|
||||
password_login(data, &mut user_id, &conn, &client_header.ip).await
|
||||
}
|
||||
"client_credentials" => {
|
||||
check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?;
|
||||
check_is_some(data.client_secret.as_ref(), "client_secret cannot be blank")?;
|
||||
check_is_some(data.scope.as_ref(), "scope cannot be blank")?;
|
||||
|
||||
api_key_login(data, &mut user_id, &conn, &client_header).await
|
||||
api_key_login(data, &mut user_id, &conn, &client_header.ip).await
|
||||
}
|
||||
"authorization_code" if CONFIG.sso_enabled() => {
|
||||
check_is_some(data.client_id.as_ref(), "client_id cannot be blank")?;
|
||||
@@ -95,7 +95,7 @@ async fn login(data: Form<ConnectData>, client_header: ClientHeaders, conn: DbCo
|
||||
check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?;
|
||||
check_is_some(data.device_type.as_ref(), "device_type cannot be blank")?;
|
||||
|
||||
sso_login(data, &mut user_id, &conn, &client_header).await
|
||||
sso_login(data, &mut user_id, &conn, &client_header.ip).await
|
||||
}
|
||||
"authorization_code" => err!("SSO sign-in is not available"),
|
||||
"send_access" => {
|
||||
@@ -179,13 +179,7 @@ async fn refresh_login(data: ConnectData, conn: &DbConn, ip: &ClientIp) -> JsonR
|
||||
}
|
||||
|
||||
// After exchanging the code we need to check first if 2FA is needed before continuing
|
||||
async fn sso_login(
|
||||
data: ConnectData,
|
||||
user_id: &mut Option<UserId>,
|
||||
conn: &DbConn,
|
||||
client_header: &ClientHeaders,
|
||||
) -> JsonResult {
|
||||
let ip = &client_header.ip;
|
||||
async fn sso_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &DbConn, ip: &ClientIp) -> JsonResult {
|
||||
AuthMethod::Sso.check_scope(data.scope.as_ref())?;
|
||||
|
||||
// Ratelimit the login
|
||||
@@ -323,8 +317,6 @@ async fn sso_login(
|
||||
}
|
||||
|
||||
let mut user = User::new(&user_infos.email, user_infos.user_name.clone());
|
||||
// Before saving, so that a client that can't log in doesn't create the account
|
||||
check_client_version(&user, client_header)?;
|
||||
user.verified_at = Some(now);
|
||||
user.save(conn).await?;
|
||||
|
||||
@@ -333,8 +325,6 @@ async fn sso_login(
|
||||
(user, device, None, None)
|
||||
}
|
||||
Some((user, _)) if !user.enabled => {
|
||||
// Set in both arms, not only after the match, so that their failed logins are logged
|
||||
*user_id = Some(user.uuid.clone());
|
||||
err!(
|
||||
"This user has been disabled",
|
||||
format!("IP: {}. Username: {}.", ip.ip, user.email),
|
||||
@@ -344,9 +334,6 @@ async fn sso_login(
|
||||
)
|
||||
}
|
||||
Some((mut user, sso_user)) => {
|
||||
*user_id = Some(user.uuid.clone());
|
||||
check_client_version(&user, client_header)?;
|
||||
|
||||
let mut device = get_device(&data, conn, &user).await?;
|
||||
|
||||
let twofactor_token = twofactor_auth(&mut user, &data, &mut device, ip, conn).await?;
|
||||
@@ -381,13 +368,7 @@ async fn sso_login(
|
||||
authenticated_response(&user, &mut device, auth_tokens, twofactor_token, conn, ip).await
|
||||
}
|
||||
|
||||
async fn password_login(
|
||||
data: ConnectData,
|
||||
user_id: &mut Option<UserId>,
|
||||
conn: &DbConn,
|
||||
client_header: &ClientHeaders,
|
||||
) -> JsonResult {
|
||||
let ip = &client_header.ip;
|
||||
async fn password_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &DbConn, ip: &ClientIp) -> JsonResult {
|
||||
// Validate scope
|
||||
AuthMethod::Password.check_scope(data.scope.as_ref())?;
|
||||
|
||||
@@ -457,8 +438,6 @@ async fn password_login(
|
||||
)
|
||||
}
|
||||
|
||||
check_client_version(&user, client_header)?;
|
||||
|
||||
// Change the KDF Iterations (only when not logging in with an auth request)
|
||||
if data.auth_request.is_none() {
|
||||
kdf_upgrade(&mut user, password, conn).await?;
|
||||
@@ -520,66 +499,6 @@ async fn password_login(
|
||||
authenticated_response(&user, &mut device, auth_tokens, twofactor_token, conn, ip).await
|
||||
}
|
||||
|
||||
/// Like upstream's `ClientVersionValidator`, every login needs the `Bitwarden-Client-Version` header, and a V2 account
|
||||
/// ([`User::has_v2_encryption`]) a client of at least 2026.10.1 (2026.10.2 for the desktop app). Called right after the
|
||||
/// credentials are checked, like upstream, so that it doesn't tell anyone else which accounts are V2.
|
||||
///
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/15c94ac58bf361a162381749c146d254a21b2098/src/Identity/IdentityServer/RequestValidators/ClientVersionValidator.cs#L33-L79>
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/15c94ac58bf361a162381749c146d254a21b2098/src/Core/KeyManagement/Constants.cs#L5-L6>
|
||||
fn check_client_version(user: &User, client_header: &ClientHeaders) -> EmptyResult {
|
||||
let Some((error, description)) = client_version_error(
|
||||
user.has_v2_encryption(),
|
||||
client_header.client_version.as_ref(),
|
||||
client_header.device_type,
|
||||
) else {
|
||||
return Ok(());
|
||||
};
|
||||
Err(crate::error::Error::from((
|
||||
// Escaped: on a first SSO login the email comes from the provider and isn't validated yet
|
||||
format!("IP: {}. Username: {}. {error}", client_header.ip.ip, user.email.escape_debug()),
|
||||
json!({
|
||||
"error": error,
|
||||
"error_description": description,
|
||||
"ErrorModel": { "Message": description, "Object": "error" },
|
||||
}),
|
||||
))
|
||||
.with_event(crate::error::ErrorEvent {
|
||||
event: EventType::UserFailedLogIn,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The error id and message of [`check_client_version`], `None` when the client may log in.
|
||||
fn client_version_error(
|
||||
is_v2: bool,
|
||||
client_version: Option<&semver::Version>,
|
||||
device_type: i32,
|
||||
) -> Option<(&'static str, &'static str)> {
|
||||
const MIN_V2_CLIENT: semver::Version = semver::Version::new(2026, 10, 1);
|
||||
const MIN_V2_DESKTOP_CLIENT: semver::Version = semver::Version::new(2026, 10, 2);
|
||||
|
||||
let Some(version) = client_version else {
|
||||
return Some((
|
||||
"version_header_missing",
|
||||
"No client version header found, required to prevent encryption errors. Please confirm your client is supplying the header: \"Bitwarden-Client-Version\"",
|
||||
));
|
||||
};
|
||||
if !is_v2 {
|
||||
return None;
|
||||
}
|
||||
// Upstream's desktop device types
|
||||
// Ref: <https://github.com/bitwarden/server/blob/15c94ac58bf361a162381749c146d254a21b2098/src/Libraries/Clients/DeviceTypes.cs#L14-L20>
|
||||
let is_desktop = matches!(
|
||||
DeviceType::from_i32(device_type),
|
||||
DeviceType::WindowsDesktop | DeviceType::MacOsDesktop | DeviceType::LinuxDesktop | DeviceType::Uwp
|
||||
);
|
||||
let min_version = if is_desktop {
|
||||
&MIN_V2_DESKTOP_CLIENT
|
||||
} else {
|
||||
&MIN_V2_CLIENT
|
||||
};
|
||||
(version < min_version).then_some(("invalid_client_version", "Please update your app to continue using Bitwarden"))
|
||||
}
|
||||
|
||||
async fn authenticated_response(
|
||||
user: &User,
|
||||
device: &mut Device,
|
||||
@@ -627,13 +546,24 @@ async fn authenticated_response(
|
||||
// https://github.com/bitwarden/android/blob/release/2025.12-rc41/network/src/main/kotlin/com/bitwarden/network/model/MasterPasswordUnlockDataJson.kt#L22-L26
|
||||
"MasterKeyEncryptedUserKey": user.akey,
|
||||
"MasterKeyWrappedUserKey": user.akey,
|
||||
"Salt": user.master_password_salt()
|
||||
"Salt": user.email
|
||||
})
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
|
||||
let account_keys = user.account_keys_json(conn).await;
|
||||
let account_keys = if user.private_key.is_some() {
|
||||
json!({
|
||||
"publicKeyEncryptionKeyPair": {
|
||||
"wrappedPrivateKey": user.private_key,
|
||||
"publicKey": user.public_key,
|
||||
"Object": "publicKeyEncryptionKeyPair"
|
||||
},
|
||||
"Object": "privateKeys"
|
||||
})
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
|
||||
let mut result = json!({
|
||||
"access_token": auth_tokens.access_token(),
|
||||
@@ -668,13 +598,7 @@ async fn authenticated_response(
|
||||
Ok(Json(result))
|
||||
}
|
||||
|
||||
async fn api_key_login(
|
||||
data: ConnectData,
|
||||
user_id: &mut Option<UserId>,
|
||||
conn: &DbConn,
|
||||
client_header: &ClientHeaders,
|
||||
) -> JsonResult {
|
||||
let ip = &client_header.ip;
|
||||
async fn api_key_login(data: ConnectData, user_id: &mut Option<UserId>, conn: &DbConn, ip: &ClientIp) -> JsonResult {
|
||||
// Ratelimit the login
|
||||
crate::ratelimit::check_limit_login(&ip.ip)?;
|
||||
|
||||
@@ -686,7 +610,7 @@ async fn api_key_login(
|
||||
check_is_some(data.device_name.as_ref(), "device_name cannot be blank")?;
|
||||
check_is_some(data.device_type.as_ref(), "device_type cannot be blank")?;
|
||||
|
||||
user_api_key_login(data, user_id, conn, client_header).await
|
||||
user_api_key_login(data, user_id, conn, ip).await
|
||||
}
|
||||
Some(scope) if scope == &AuthMethod::OrgApiKey.scope() => organization_api_key_login(data, conn, ip).await,
|
||||
_ => err!("Scope not supported"),
|
||||
@@ -697,9 +621,8 @@ async fn user_api_key_login(
|
||||
data: ConnectData,
|
||||
user_id: &mut Option<UserId>,
|
||||
conn: &DbConn,
|
||||
client_header: &ClientHeaders,
|
||||
ip: &ClientIp,
|
||||
) -> JsonResult {
|
||||
let ip = &client_header.ip;
|
||||
// Get the user via the client_id
|
||||
let client_id = data.client_id.as_ref().unwrap();
|
||||
let Some(client_user_id) = client_id.strip_prefix("user.") else {
|
||||
@@ -736,8 +659,6 @@ async fn user_api_key_login(
|
||||
)
|
||||
}
|
||||
|
||||
check_client_version(&user, client_header)?;
|
||||
|
||||
let mut device = get_device(&data, conn, &user).await?;
|
||||
|
||||
if CONFIG.mail_enabled() && device.is_new() {
|
||||
@@ -782,13 +703,24 @@ async fn user_api_key_login(
|
||||
// https://github.com/bitwarden/android/blob/release/2025.12-rc41/network/src/main/kotlin/com/bitwarden/network/model/MasterPasswordUnlockDataJson.kt#L22-L26
|
||||
"MasterKeyEncryptedUserKey": user.akey,
|
||||
"MasterKeyWrappedUserKey": user.akey,
|
||||
"Salt": user.master_password_salt()
|
||||
"Salt": user.email
|
||||
})
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
|
||||
let account_keys = user.account_keys_json(conn).await;
|
||||
let account_keys = if user.private_key.is_some() {
|
||||
json!({
|
||||
"publicKeyEncryptionKeyPair": {
|
||||
"wrappedPrivateKey": user.private_key,
|
||||
"publicKey": user.public_key,
|
||||
"Object": "publicKeyEncryptionKeyPair"
|
||||
},
|
||||
"Object": "privateKeys"
|
||||
})
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
|
||||
// Note: No refresh_token is returned. The CLI just repeats the
|
||||
// client_credentials login flow when the existing token expires.
|
||||
@@ -1419,33 +1351,3 @@ async fn authorize(data: AuthorizeData, cookies: &CookieJar<'_>, secure: Secure,
|
||||
|
||||
Ok(Redirect::temporary(String::from(auth_url)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_client_version_error() {
|
||||
let version = |v| semver::Version::parse(v).unwrap();
|
||||
let web = DeviceType::ChromeBrowser as i32;
|
||||
let desktop = DeviceType::WindowsDesktop as i32;
|
||||
// Every login needs the header
|
||||
assert_eq!(client_version_error(false, None, web).map(|e| e.0), Some("version_header_missing"));
|
||||
assert_eq!(client_version_error(true, None, desktop).map(|e| e.0), Some("version_header_missing"));
|
||||
// V1 accounts log in from any version
|
||||
assert_eq!(client_version_error(false, Some(&version("2024.1.0")), web), None);
|
||||
assert_eq!(client_version_error(false, Some(&version("2024.1.0")), desktop), None);
|
||||
// V2 accounts need 2026.10.1, and 2026.10.2 for the desktop app
|
||||
assert_eq!(
|
||||
client_version_error(true, Some(&version("2026.10.0")), web).map(|e| e.0),
|
||||
Some("invalid_client_version")
|
||||
);
|
||||
assert_eq!(client_version_error(true, Some(&version("2026.10.1")), web), None);
|
||||
assert_eq!(
|
||||
client_version_error(true, Some(&version("2026.10.1")), desktop).map(|e| e.0),
|
||||
Some("invalid_client_version")
|
||||
);
|
||||
assert_eq!(client_version_error(true, Some(&version("2026.10.2")), DeviceType::Uwp as i32), None);
|
||||
assert_eq!(client_version_error(true, Some(&version("2026.11.0")), desktop), None);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -23,7 +23,7 @@ pub use crate::api::{
|
||||
icons::routes as icons_routes,
|
||||
identity::routes as identity_routes,
|
||||
notifications::routes as notifications_routes,
|
||||
notifications::{AnonymousNotify, LogOutReason, Notify, UpdateType, WS_ANONYMOUS_SUBSCRIPTIONS, WS_USERS},
|
||||
notifications::{AnonymousNotify, Notify, UpdateType, WS_ANONYMOUS_SUBSCRIPTIONS, WS_USERS},
|
||||
push::{
|
||||
push_cipher_update, push_folder_update, push_logout, push_logout_to_relay, push_send_update, push_user_update,
|
||||
register_push_device, unregister_push_device,
|
||||
|
||||
@@ -412,35 +412,23 @@ impl WebSocketUsers {
|
||||
}
|
||||
|
||||
pub async fn send_logout(&self, user: &User, acting_device: Option<&Device>, conn: &DbConn) {
|
||||
self.send_logout_with_reason(user, acting_device, None, conn).await;
|
||||
}
|
||||
|
||||
/// A logout that clients may handle differently depending on `reason`
|
||||
pub async fn send_logout_with_reason(
|
||||
&self,
|
||||
user: &User,
|
||||
acting_device: Option<&Device>,
|
||||
reason: Option<LogOutReason>,
|
||||
conn: &DbConn,
|
||||
) {
|
||||
// Skip any processing if both WebSockets and Push are not active
|
||||
if *NOTIFICATIONS_DISABLED {
|
||||
return;
|
||||
}
|
||||
let acting_device_id = acting_device.map(|d| d.uuid.clone());
|
||||
let mut payload =
|
||||
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))];
|
||||
if let Some(reason) = reason {
|
||||
payload.push(("Reason".into(), (reason as i32).into()));
|
||||
}
|
||||
let data = create_update(payload, UpdateType::LogOut, acting_device_id);
|
||||
let data = create_update(
|
||||
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))],
|
||||
UpdateType::LogOut,
|
||||
acting_device_id,
|
||||
);
|
||||
|
||||
if CONFIG.enable_websocket() {
|
||||
self.send_update(&user.uuid, &data).await;
|
||||
}
|
||||
|
||||
if CONFIG.push_enabled() {
|
||||
push_logout(user, acting_device, reason, conn).await;
|
||||
push_logout(user, acting_device, conn).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -704,14 +692,6 @@ fn create_anonymous_update(payload: Vec<(Value, Value)>, ut: UpdateType, user_id
|
||||
serialize(&value)
|
||||
}
|
||||
|
||||
/// Why a logout was pushed, absent for a plain one. `KdfChange` isn't sent yet.
|
||||
///
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/9030c42bf7d8f9ac2ff9fee85c39588d5eb81499/src/Core/Enums/PushNotificationLogOutReason.cs#L3-L7>
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
pub enum LogOutReason {
|
||||
KeyRotation = 1,
|
||||
}
|
||||
|
||||
// https://github.com/bitwarden/server/blob/375af7c43b10d9da03525d41452f95de3f921541/src/Core/Enums/PushType.cs
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
pub enum UpdateType {
|
||||
|
||||
+5
-6
@@ -12,7 +12,7 @@ use tokio::sync::RwLock;
|
||||
|
||||
use crate::{
|
||||
CONFIG,
|
||||
api::{ApiResult, EmptyResult, LogOutReason, UpdateType},
|
||||
api::{ApiResult, EmptyResult, UpdateType},
|
||||
db::{
|
||||
DbConn,
|
||||
models::{AuthRequestId, Cipher, Device, Folder, PushId, Send, User, UserId},
|
||||
@@ -192,15 +192,15 @@ pub async fn push_cipher_update(ut: UpdateType, cipher: &Cipher, device: &Device
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn push_logout(user: &User, acting_device: Option<&Device>, reason: Option<LogOutReason>, conn: &DbConn) {
|
||||
pub async fn push_logout(user: &User, acting_device: Option<&Device>, conn: &DbConn) {
|
||||
if Device::check_user_has_push_device(&user.uuid, conn).await {
|
||||
push_logout_to_relay(user, acting_device, reason);
|
||||
push_logout_to_relay(user, acting_device);
|
||||
}
|
||||
}
|
||||
|
||||
// Sends the logout without checking for push devices first.
|
||||
// Needed after deleting a user, when the devices are already gone from the database.
|
||||
pub fn push_logout_to_relay(user: &User, acting_device: Option<&Device>, reason: Option<LogOutReason>) {
|
||||
pub fn push_logout_to_relay(user: &User, acting_device: Option<&Device>) {
|
||||
tokio::task::spawn(send_to_push_relay(json!({
|
||||
"userId": user.uuid,
|
||||
"organizationId": (),
|
||||
@@ -209,8 +209,7 @@ pub fn push_logout_to_relay(user: &User, acting_device: Option<&Device>, reason:
|
||||
"type": UpdateType::LogOut as i32,
|
||||
"payload": {
|
||||
"userId": user.uuid,
|
||||
"date": format_date(&user.updated_at),
|
||||
"reason": reason.map(|r| r as i32),
|
||||
"date": format_date(&user.updated_at)
|
||||
},
|
||||
"clientType": null,
|
||||
"installationId": null
|
||||
|
||||
+25
-12
@@ -34,7 +34,7 @@ use crate::{
|
||||
models::{
|
||||
AttachmentId, CipherId, Collection, CollectionId, Device, DeviceId, DeviceType, EmergencyAccessId,
|
||||
EventType, Membership, MembershipId, MembershipStatus, MembershipType, OrgApiKeyId, OrganizationId,
|
||||
SendFileId, SendId, User, UserId,
|
||||
SendFileId, SendId, User, UserId, UserStampException,
|
||||
},
|
||||
},
|
||||
error::Error,
|
||||
@@ -632,9 +632,6 @@ impl<'r> FromRequest<'r> for Host {
|
||||
pub struct ClientHeaders {
|
||||
pub device_type: i32,
|
||||
pub ip: ClientIp,
|
||||
/// `Bitwarden-Client-Version`, `None` when missing or not a version. Unlike the [`ClientVersion`] guard, this
|
||||
/// doesn't log an error, as not every client sends it.
|
||||
pub client_version: Option<semver::Version>,
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
@@ -651,13 +648,10 @@ impl<'r> FromRequest<'r> for ClientHeaders {
|
||||
.get_one("device-type")
|
||||
.and_then(|d| d.parse().ok())
|
||||
.unwrap_or(DeviceType::UnknownBrowser as i32);
|
||||
let client_version =
|
||||
request.headers().get_one("Bitwarden-Client-Version").and_then(|v| semver::Version::parse(v).ok());
|
||||
|
||||
Outcome::Success(ClientHeaders {
|
||||
device_type,
|
||||
ip,
|
||||
client_version,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -713,12 +707,31 @@ impl<'r> FromRequest<'r> for Headers {
|
||||
};
|
||||
|
||||
if user.security_stamp != claims.sstamp {
|
||||
let Some(current_route) = request.route().and_then(|r| r.name.as_deref()) else {
|
||||
err_handler!("Error getting current route for stamp exception")
|
||||
};
|
||||
if let Some(stamp_exception) =
|
||||
user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::<UserStampException>(s).ok())
|
||||
{
|
||||
let Some(current_route) = request.route().and_then(|r| r.name.as_deref()) else {
|
||||
err_handler!("Error getting current route for stamp exception")
|
||||
};
|
||||
|
||||
// Expired exceptions are only dropped on reset; writing them back here could undo a newer reset
|
||||
if !user.stamp_exceptions().iter().any(|e| e.allows(&claims.sstamp, current_route)) {
|
||||
// Check if the stamp exception has expired first.
|
||||
// Then, check if the current route matches any of the allowed routes.
|
||||
// After that check the stamp in exception matches the one in the claims.
|
||||
if Utc::now().timestamp() > stamp_exception.expire {
|
||||
// If the stamp exception has been expired remove it from the database.
|
||||
// This prevents checking this stamp exception for new requests.
|
||||
let mut user = user;
|
||||
user.reset_stamp_exception();
|
||||
if let Err(e) = user.save(&conn).await {
|
||||
error!("Error updating user: {e:#?}");
|
||||
}
|
||||
err_handler!("Stamp exception is expired")
|
||||
} else if !stamp_exception.routes.contains(¤t_route.to_owned()) {
|
||||
err_handler!("Invalid security stamp: Current route and exception route do not match")
|
||||
} else if stamp_exception.security_stamp != claims.sstamp {
|
||||
err_handler!("Invalid security stamp for matched stamp exception")
|
||||
}
|
||||
} else {
|
||||
err_handler!("Invalid security stamp")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1516,8 +1516,6 @@ pub const SUPPORTED_FEATURE_FLAGS: &[&str] = &[
|
||||
// Key Management Team
|
||||
"biometrics-sdk-ipc",
|
||||
"windows-native-credential-sync",
|
||||
"enable-account-encryption-v2-jit-password-registration",
|
||||
"pm-27278-v2-password-registration",
|
||||
// Mobile Team
|
||||
"pm-34171-card-scanner",
|
||||
// Platform Team
|
||||
|
||||
+4
-158
@@ -1,11 +1,7 @@
|
||||
mod query_logger;
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
sync::{
|
||||
Arc, OnceLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
sync::{Arc, OnceLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
@@ -127,7 +123,6 @@ pub static ACTIVE_DB_TYPE: OnceLock<DbConnType> = OnceLock::new();
|
||||
pub struct DbConn {
|
||||
conn: Arc<Mutex<Option<PooledConnection<DbConnManager>>>>,
|
||||
permit: Option<OwnedSemaphorePermit>,
|
||||
transaction_open: AtomicBool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -155,7 +150,6 @@ impl Drop for DbConn {
|
||||
fn drop(&mut self) {
|
||||
let conn = Arc::clone(&self.conn);
|
||||
let permit = self.permit.take();
|
||||
let transaction_open = self.transaction_open.load(Ordering::Acquire);
|
||||
|
||||
// Since connection can't be on the stack in an async fn during an
|
||||
// await, we have to spawn a new blocking-safe thread...
|
||||
@@ -163,13 +157,7 @@ impl Drop for DbConn {
|
||||
// And then re-enter the runtime to wait on the async mutex, but in a blocking fashion.
|
||||
let mut conn = tokio::runtime::Handle::current().block_on(conn.lock_owned());
|
||||
|
||||
if let Some(mut conn) = conn.take() {
|
||||
if transaction_open {
|
||||
// A cancelled request must not return an open transaction to the pool.
|
||||
if let Err(error) = conn.batch_execute("ROLLBACK") {
|
||||
error!("Failed to roll back a cancelled database transaction: {error}");
|
||||
}
|
||||
}
|
||||
if let Some(conn) = conn.take() {
|
||||
drop(conn);
|
||||
}
|
||||
|
||||
@@ -260,7 +248,6 @@ impl DbPool {
|
||||
Ok(DbConn {
|
||||
conn: Arc::new(Mutex::new(Some(c))),
|
||||
permit: Some(permit),
|
||||
transaction_open: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -333,29 +320,6 @@ impl DbConnType {
|
||||
}
|
||||
|
||||
impl DbConn {
|
||||
/// Run asynchronous model calls on this request's pooled connection in one transaction.
|
||||
/// Send external notifications only after this returns successfully.
|
||||
pub async fn transaction<F, Fut, T>(&self, operation: F) -> Result<T, Error>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<T, Error>>,
|
||||
{
|
||||
self.run(|conn| conn.batch_execute("BEGIN")).await.map_res("Error starting database transaction")?;
|
||||
self.transaction_open.store(true, Ordering::Release);
|
||||
let result = operation().await;
|
||||
if result.is_ok() {
|
||||
let committed = self.run(|conn| conn.batch_execute("COMMIT")).await;
|
||||
let closed = committed.is_ok() || self.run(|conn| conn.batch_execute("ROLLBACK")).await.is_ok();
|
||||
if closed {
|
||||
self.transaction_open.store(false, Ordering::Release);
|
||||
}
|
||||
committed.map_res("Error committing database transaction")?;
|
||||
} else if self.run(|conn| conn.batch_execute("ROLLBACK")).await.is_ok() {
|
||||
self.transaction_open.store(false, Ordering::Release);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn run<F, R>(&self, f: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut DbConnInner) -> R + Send,
|
||||
@@ -574,61 +538,9 @@ mod postgresql_migrations {
|
||||
/// A throwaway SQLite database with the real schema, for tests that need to run queries.
|
||||
#[cfg(all(test, sqlite))]
|
||||
pub mod test_db {
|
||||
use super::{DbConn, DbConnManager, sqlite_migrations::MIGRATIONS};
|
||||
use diesel::{Connection, connection::SimpleConnection, r2d2::Pool, sqlite::SqliteConnection};
|
||||
use super::sqlite_migrations::MIGRATIONS;
|
||||
use diesel::connection::SimpleConnection;
|
||||
use diesel_migrations::MigrationHarness;
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub struct TestDb {
|
||||
pool: Pool<DbConnManager>,
|
||||
// Keep the named in-memory database alive across pooled connections.
|
||||
_keeper: SqliteConnection,
|
||||
}
|
||||
|
||||
impl TestDb {
|
||||
fn new() -> Self {
|
||||
let url = format!("sqlite://{}?mode=memory&cache=shared", crate::util::get_uuid());
|
||||
let mut keeper = SqliteConnection::establish(&url).unwrap();
|
||||
keeper.run_pending_migrations(MIGRATIONS).unwrap();
|
||||
let pool = Pool::builder().max_size(2).build(DbConnManager::new(&url)).unwrap();
|
||||
Self {
|
||||
pool,
|
||||
_keeper: keeper,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn conn(&self) -> DbConn {
|
||||
DbConn {
|
||||
conn: Arc::new(Mutex::new(Some(self.pool.get().unwrap()))),
|
||||
permit: None,
|
||||
transaction_open: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CONFIG must initialize in a child process: the DNS bootstrap test needs it uninitialized.
|
||||
pub fn run(test: impl AsyncFnOnce(&TestDb)) {
|
||||
if std::env::var_os("VAULTWARDEN_ISOLATED_CONFIG_TEST").is_none() {
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
||||
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
||||
.env("DATABASE_URL", "sqlite://:memory:")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed"),
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return;
|
||||
}
|
||||
// DbConn::run uses block_in_place, requiring a multi-threaded runtime.
|
||||
tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap().block_on(async {
|
||||
test(&TestDb::new()).await;
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_role_migration_preserves_memberships_and_guards_downgrade() {
|
||||
@@ -692,70 +604,4 @@ pub mod test_db {
|
||||
assert_eq!(grants(&mut conn), 0);
|
||||
assert_eq!(rows(&mut conn), before);
|
||||
}
|
||||
|
||||
use super::models::{Collection, CustomPermission, Membership, MembershipType, Organization, OrganizationId, User};
|
||||
|
||||
pub async fn organization(conn: &DbConn) -> Organization {
|
||||
let org = Organization::new("Org".into(), "billing@example.com", None, None);
|
||||
org.save(conn).await.unwrap();
|
||||
org
|
||||
}
|
||||
|
||||
pub async fn member(
|
||||
conn: &DbConn,
|
||||
org: &OrganizationId,
|
||||
role: MembershipType,
|
||||
permissions: &[CustomPermission],
|
||||
) -> (User, Membership) {
|
||||
let mut user = User::new(&format!("{}@example.com", crate::util::get_uuid()), None);
|
||||
user.password_hash = b"existing-account".to_vec();
|
||||
user.save(conn).await.unwrap();
|
||||
let mut member = Membership::new(user.uuid.clone(), org.clone(), None);
|
||||
member.set_type(role);
|
||||
member.status = 2;
|
||||
member.set_custom_permissions(&permissions.iter().copied().collect());
|
||||
member.save(conn).await.unwrap();
|
||||
(user, member)
|
||||
}
|
||||
|
||||
pub async fn custom_member(conn: &DbConn, permission: CustomPermission) -> (Organization, User, Membership) {
|
||||
let org = organization(conn).await;
|
||||
let (user, member) = member(conn, &org.uuid, MembershipType::Custom, &[permission]).await;
|
||||
(org, user, member)
|
||||
}
|
||||
|
||||
pub async fn collection(conn: &DbConn, org: &OrganizationId) -> Collection {
|
||||
let collection = Collection::new(org.clone(), "Collection".into(), None);
|
||||
collection.save(conn).await.unwrap();
|
||||
collection
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transactions_rollback_before_connection_reuse_and_commit_success() {
|
||||
use crate::error::MapResult;
|
||||
use diesel::RunQueryDsl;
|
||||
run(async |db| {
|
||||
let conn = db.conn();
|
||||
conn.run(|c| c.batch_execute("CREATE TABLE probe (id INTEGER PRIMARY KEY)")).await.unwrap();
|
||||
for (sql, expected) in [
|
||||
("INSERT INTO probe VALUES (1); INSERT INTO probe VALUES (1)", 0_i64),
|
||||
("INSERT INTO probe VALUES (1)", 1),
|
||||
] {
|
||||
let result: Result<(), super::Error> = conn
|
||||
.transaction(async || conn.run(move |c| c.batch_execute(sql)).await.map_res("Insert failed"))
|
||||
.await;
|
||||
assert_eq!(result.is_ok(), expected == 1);
|
||||
let count: i64 = conn
|
||||
.run(|c| {
|
||||
diesel::select(diesel::dsl::sql::<diesel::sql_types::BigInt>("(SELECT COUNT(*) FROM probe)"))
|
||||
.get_result(c)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, expected);
|
||||
// The same live connection must accept another transaction, before DbConn::drop can help.
|
||||
conn.run(|c| c.batch_execute("BEGIN; ROLLBACK")).await.unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+73
-240
@@ -1,4 +1,4 @@
|
||||
use std::{borrow::Cow, collections::HashSet};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use chrono::{NaiveDateTime, TimeDelta, Utc};
|
||||
use derive_more::{AsRef, Deref, Display, From};
|
||||
@@ -19,7 +19,7 @@ use crate::{
|
||||
},
|
||||
},
|
||||
error::MapResult,
|
||||
util::{LowerCase, convert_json_key_lcase_first},
|
||||
util::LowerCase,
|
||||
};
|
||||
use macros::UuidFromParam;
|
||||
|
||||
@@ -63,68 +63,14 @@ pub struct Cipher {
|
||||
pub reprompt: Option<i32>,
|
||||
}
|
||||
|
||||
/// Whether `data` is a v2 cipher blob, recognized like upstream by a top-level `format_version` key.
|
||||
///
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/9030c42bf7d8f9ac2ff9fee85c39588d5eb81499/src/Core/Vault/Entities/Cipher.cs#L36-L41>
|
||||
pub fn is_data_blob_encrypted(data: &str) -> bool {
|
||||
serde_json::from_str::<Value>(data).is_ok_and(|d| is_blob_value(&d))
|
||||
}
|
||||
|
||||
/// [`is_data_blob_encrypted`] for `data` that was already parsed.
|
||||
fn is_blob_value(data: &Value) -> bool {
|
||||
data.get("format_version").is_some()
|
||||
}
|
||||
|
||||
pub enum RepromptType {
|
||||
None = 0,
|
||||
Password = 1,
|
||||
}
|
||||
|
||||
/// Which access a cipher operation is authorized with.
|
||||
///
|
||||
/// The administrative cipher routes (`/ciphers/<id>/admin` and friends) are served by the same handlers as the
|
||||
/// regular vault routes, so the handlers state which one applies. They only differ for a Custom member with Edit
|
||||
/// any collection, who reaches every cipher of the organization on the administrative routes, but keeps their
|
||||
/// own vault limited to the collections they are assigned to.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CipherAccessScope {
|
||||
User,
|
||||
OrganizationAdmin,
|
||||
}
|
||||
|
||||
impl CipherAccessScope {
|
||||
/// Whether `member` reaches every cipher of their organization with this access.
|
||||
fn reaches_all_ciphers(self, member: &Membership) -> bool {
|
||||
match self {
|
||||
CipherAccessScope::User => member.has_full_access(),
|
||||
CipherAccessScope::OrganizationAdmin => member.can_edit_any_collection(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The access the v2 attachment upload asks for with `adminRequest`. It only picks which check runs, the
|
||||
/// administrative one still needs a member who may edit any collection.
|
||||
pub fn requested(admin_request: Option<bool>) -> Self {
|
||||
if admin_request == Some(true) {
|
||||
CipherAccessScope::OrganizationAdmin
|
||||
} else {
|
||||
CipherAccessScope::User
|
||||
}
|
||||
}
|
||||
|
||||
/// The access for a route that does not tell which one it is, from the member's own membership.
|
||||
pub fn for_member(member: Option<&Membership>) -> Self {
|
||||
if member.is_some_and(Membership::can_edit_any_collection) {
|
||||
CipherAccessScope::OrganizationAdmin
|
||||
} else {
|
||||
CipherAccessScope::User
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Local methods
|
||||
impl Cipher {
|
||||
/// The name is set when the data is saved, since a blob-encrypted cipher has it inside `data`
|
||||
pub fn new(atype: i32) -> Self {
|
||||
pub fn new(atype: i32, name: String) -> Self {
|
||||
let now = Utc::now().naive_utc();
|
||||
|
||||
Self {
|
||||
@@ -138,7 +84,7 @@ impl Cipher {
|
||||
key: None,
|
||||
|
||||
atype,
|
||||
name: String::new(),
|
||||
name,
|
||||
|
||||
notes: None,
|
||||
fields: None,
|
||||
@@ -164,16 +110,6 @@ impl Cipher {
|
||||
.insert(format!("Ciphers[{index}].Notes"), serde_json::to_value([&max_note_size_msg]).unwrap());
|
||||
}
|
||||
|
||||
let is_blob = cipher.is_blob();
|
||||
if let Err(e) = cipher.validate_content(is_blob) {
|
||||
validation_errors
|
||||
.insert(format!("Ciphers[{index}].{}", e.field), serde_json::to_value([e.message]).unwrap());
|
||||
}
|
||||
if let Err(e) = cipher.validate_type_data(is_blob) {
|
||||
validation_errors
|
||||
.insert(format!("Ciphers[{index}].Type"), serde_json::to_value([e.message()]).unwrap());
|
||||
}
|
||||
|
||||
// Validate the password history if it contains `null` values and if so, return a warning
|
||||
if let Some(Value::Array(password_history)) = &cipher.password_history {
|
||||
for pwh in password_history {
|
||||
@@ -215,36 +151,9 @@ impl Cipher {
|
||||
cipher_sync_data: Option<&CipherSyncData>,
|
||||
sync_type: CipherSyncType,
|
||||
conn: &DbConn,
|
||||
) -> Result<Value, crate::Error> {
|
||||
self.to_json_scoped(host, user_uuid, cipher_sync_data, sync_type, CipherAccessScope::User, conn).await
|
||||
}
|
||||
|
||||
/// [`Cipher::to_json`] for an administrative route, telling what the member may do with the cipher there.
|
||||
pub async fn to_json_org_admin(
|
||||
&self,
|
||||
host: &str,
|
||||
user_uuid: &UserId,
|
||||
conn: &DbConn,
|
||||
) -> Result<Value, crate::Error> {
|
||||
self.to_json_scoped(host, user_uuid, None, CipherSyncType::User, CipherAccessScope::OrganizationAdmin, conn)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn to_json_scoped(
|
||||
&self,
|
||||
host: &str,
|
||||
user_uuid: &UserId,
|
||||
cipher_sync_data: Option<&CipherSyncData>,
|
||||
sync_type: CipherSyncType,
|
||||
scope: CipherAccessScope,
|
||||
conn: &DbConn,
|
||||
) -> Result<Value, crate::Error> {
|
||||
use crate::util::{format_date, validate_and_format_date};
|
||||
|
||||
// Parsed once, since `data` can be large and this runs for every cipher in a sync
|
||||
let type_data = serde_json::from_str::<Value>(&self.data);
|
||||
let is_blob_encrypted = type_data.as_ref().is_ok_and(is_blob_value);
|
||||
|
||||
let mut attachments_json: Value = Value::Null;
|
||||
if let Some(cipher_sync_data) = cipher_sync_data {
|
||||
if let Some(attachments) = cipher_sync_data.cipher_attachments.get(&self.uuid)
|
||||
@@ -270,7 +179,7 @@ impl Cipher {
|
||||
// We don't need these values at all for Organizational syncs
|
||||
// Skip any other database calls if this is the case and just return false.
|
||||
let (read_only, hide_passwords, _) = if sync_type == CipherSyncType::User {
|
||||
if let Some((ro, hp, mn)) = self.get_access_restrictions(user_uuid, scope, cipher_sync_data, conn).await {
|
||||
if let Some((ro, hp, mn)) = self.get_access_restrictions(user_uuid, cipher_sync_data, conn).await {
|
||||
(ro, hp, mn)
|
||||
} else {
|
||||
error!("Cipher ownership assertion failure");
|
||||
@@ -341,9 +250,63 @@ impl Cipher {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// Like upstream, fields and password history stored as NULL are sent as null, not `[]`
|
||||
let fields_json = self.fields.is_some().then_some(fields_json);
|
||||
let password_history_json = self.password_history.is_some().then_some(password_history_json);
|
||||
// Get the type_data or a default to an empty json object '{}'.
|
||||
// If not passing an empty object, mobile clients will crash.
|
||||
let mut type_data_json = serde_json::from_str::<LowerCase<Value>>(&self.data)
|
||||
.inspect_err(|_| warn!("Error parsing data field for {}", self.uuid))
|
||||
.map_or_else(|_| Value::Object(serde_json::Map::new()), |d| d.data);
|
||||
|
||||
// NOTE: This was marked as *Backwards Compatibility Code*, but as of January 2021 this is still being used by upstream
|
||||
// Set the first element of the Uris array as Uri, this is needed several (mobile) clients.
|
||||
if self.atype == 1 {
|
||||
// Upstream always has an `uri` key/value
|
||||
type_data_json["uri"] = Value::Null;
|
||||
if let Some(uris) = type_data_json["uris"].as_array_mut()
|
||||
&& !uris.is_empty()
|
||||
{
|
||||
// Fix uri match values first, they are only allowed to be a number or null
|
||||
// If it is a string, convert it to an int or null if that fails
|
||||
for uri in &mut *uris {
|
||||
if uri["match"].is_string() {
|
||||
let match_value = match uri["match"].as_str().unwrap_or_default().parse::<u8>() {
|
||||
Ok(n) => json!(n),
|
||||
_ => Value::Null,
|
||||
};
|
||||
uri["match"] = match_value;
|
||||
}
|
||||
}
|
||||
type_data_json["uri"] = uris[0]["uri"].clone();
|
||||
}
|
||||
|
||||
// Check if `passwordRevisionDate` is a valid date, else convert it
|
||||
if let Some(pw_revision) = type_data_json["passwordRevisionDate"].as_str() {
|
||||
type_data_json["passwordRevisionDate"] = json!(validate_and_format_date(pw_revision));
|
||||
}
|
||||
}
|
||||
|
||||
// Fix secure note issues when data is invalid
|
||||
// This breaks at least the native mobile clients
|
||||
if self.atype == 2 {
|
||||
match type_data_json {
|
||||
Value::Object(ref t) if t.get("type").is_some_and(Value::is_number) => {}
|
||||
_ => {
|
||||
type_data_json = json!({"type": 0});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fix invalid SSH Entries
|
||||
// This breaks at least the native mobile client if invalid
|
||||
// The only way to fix this is by setting type_data_json to `null`
|
||||
// Opening this ssh-key in the mobile client will probably crash the client, but you can edit, save and afterwards delete it
|
||||
if self.atype == 5
|
||||
&& (type_data_json["keyFingerprint"].as_str().is_none_or(str::is_empty)
|
||||
|| type_data_json["privateKey"].as_str().is_none_or(str::is_empty)
|
||||
|| type_data_json["publicKey"].as_str().is_none_or(str::is_empty))
|
||||
{
|
||||
warn!("Error parsing ssh-key, mandatory fields are invalid for {}", self.uuid);
|
||||
type_data_json = Value::Null;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -440,84 +403,10 @@ impl Cipher {
|
||||
_ => err!(format!("Cipher {} has an invalid type {}", self.uuid, self.atype)),
|
||||
};
|
||||
|
||||
if is_blob_encrypted {
|
||||
// Like upstream, sent as-is with the structured fields null
|
||||
json_object["data"] = json!(self.data);
|
||||
json_object["name"] = Value::Null;
|
||||
} else {
|
||||
json_object[key] = self.legacy_type_data_json(type_data);
|
||||
}
|
||||
json_object[key] = type_data_json;
|
||||
Ok(json_object)
|
||||
}
|
||||
|
||||
/// The per-type data of a legacy cipher, with fixups for values known to break clients.
|
||||
fn legacy_type_data_json(&self, type_data: Result<Value, serde_json::Error>) -> Value {
|
||||
use crate::util::validate_and_format_date;
|
||||
|
||||
// Get the type_data or a default to an empty json object '{}'.
|
||||
// If not passing an empty object, mobile clients will crash.
|
||||
let mut type_data_json = if let Ok(data @ Value::Object(_)) = type_data {
|
||||
convert_json_key_lcase_first(data)
|
||||
} else {
|
||||
warn!("Error parsing data field for {}", self.uuid);
|
||||
Value::Object(serde_json::Map::new())
|
||||
};
|
||||
|
||||
// NOTE: This was marked as *Backwards Compatibility Code*, but as of January 2021 this is still being used by upstream
|
||||
// Set the first element of the Uris array as Uri, this is needed several (mobile) clients.
|
||||
if self.atype == 1 {
|
||||
// Upstream always has an `uri` key/value
|
||||
type_data_json["uri"] = Value::Null;
|
||||
if let Some(uris) = type_data_json["uris"].as_array_mut()
|
||||
&& !uris.is_empty()
|
||||
{
|
||||
// Fix uri match values first, they are only allowed to be a number or null
|
||||
// If it is a string, convert it to an int or null if that fails
|
||||
for uri in &mut *uris {
|
||||
if uri["match"].is_string() {
|
||||
let match_value = match uri["match"].as_str().unwrap_or_default().parse::<u8>() {
|
||||
Ok(n) => json!(n),
|
||||
_ => Value::Null,
|
||||
};
|
||||
uri["match"] = match_value;
|
||||
}
|
||||
}
|
||||
type_data_json["uri"] = uris[0]["uri"].clone();
|
||||
}
|
||||
|
||||
// Check if `passwordRevisionDate` is a valid date, else convert it
|
||||
if let Some(pw_revision) = type_data_json["passwordRevisionDate"].as_str() {
|
||||
type_data_json["passwordRevisionDate"] = json!(validate_and_format_date(pw_revision));
|
||||
}
|
||||
}
|
||||
|
||||
// Fix secure note issues when data is invalid
|
||||
// This breaks at least the native mobile clients
|
||||
if self.atype == 2 {
|
||||
match type_data_json {
|
||||
Value::Object(ref t) if t.get("type").is_some_and(Value::is_number) => {}
|
||||
_ => {
|
||||
type_data_json = json!({"type": 0});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fix invalid SSH Entries
|
||||
// This breaks at least the native mobile client if invalid
|
||||
// The only way to fix this is by setting type_data_json to `null`
|
||||
// Opening this ssh-key in the mobile client will probably crash the client, but you can edit, save and afterwards delete it
|
||||
if self.atype == 5
|
||||
&& (type_data_json["keyFingerprint"].as_str().is_none_or(str::is_empty)
|
||||
|| type_data_json["privateKey"].as_str().is_none_or(str::is_empty)
|
||||
|| type_data_json["publicKey"].as_str().is_none_or(str::is_empty))
|
||||
{
|
||||
warn!("Error parsing ssh-key, mandatory fields are invalid for {}", self.uuid);
|
||||
type_data_json = Value::Null;
|
||||
}
|
||||
|
||||
type_data_json
|
||||
}
|
||||
|
||||
pub async fn update_users_revision(&self, conn: &DbConn) -> Vec<UserId> {
|
||||
let mut user_uuids = Vec::new();
|
||||
match self.user_uuid {
|
||||
@@ -673,21 +562,20 @@ impl Cipher {
|
||||
self.user_uuid.is_some() && self.user_uuid.as_ref().unwrap() == 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 has full access.
|
||||
async fn is_in_full_access_org(
|
||||
&self,
|
||||
user_uuid: &UserId,
|
||||
scope: CipherAccessScope,
|
||||
cipher_sync_data: Option<&CipherSyncData>,
|
||||
conn: &DbConn,
|
||||
) -> bool {
|
||||
if let Some(ref org_uuid) = self.organization_uuid {
|
||||
if let Some(cipher_sync_data) = cipher_sync_data {
|
||||
if let Some(cached_member) = cipher_sync_data.members.get(org_uuid) {
|
||||
return scope.reaches_all_ciphers(cached_member);
|
||||
return cached_member.has_full_access();
|
||||
}
|
||||
} else if let Some(member) = Membership::find_confirmed_by_user_and_org(user_uuid, org_uuid, conn).await {
|
||||
return scope.reaches_all_ciphers(&member);
|
||||
return member.has_full_access();
|
||||
}
|
||||
}
|
||||
false
|
||||
@@ -720,7 +608,6 @@ impl Cipher {
|
||||
pub async fn get_access_restrictions(
|
||||
&self,
|
||||
user_uuid: &UserId,
|
||||
scope: CipherAccessScope,
|
||||
cipher_sync_data: Option<&CipherSyncData>,
|
||||
conn: &DbConn,
|
||||
) -> Option<(bool, bool, bool)> {
|
||||
@@ -728,7 +615,7 @@ impl Cipher {
|
||||
// a collection that the user has full access to. If so, there are no
|
||||
// access restrictions.
|
||||
if self.is_owned_by_user(user_uuid)
|
||||
|| self.is_in_full_access_org(user_uuid, scope, cipher_sync_data, conn).await
|
||||
|| self.is_in_full_access_org(user_uuid, cipher_sync_data, conn).await
|
||||
|| self.is_in_full_access_group(user_uuid, cipher_sync_data, conn).await
|
||||
{
|
||||
return Some((false, false, true));
|
||||
@@ -851,13 +738,8 @@ impl Cipher {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn is_write_accessible_to_user(
|
||||
&self,
|
||||
user_uuid: &UserId,
|
||||
scope: CipherAccessScope,
|
||||
conn: &DbConn,
|
||||
) -> bool {
|
||||
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
|
||||
pub async fn is_write_accessible_to_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool {
|
||||
match self.get_access_restrictions(user_uuid, None, conn).await {
|
||||
Some((read_only, _hide_passwords, manage)) => !read_only || manage,
|
||||
None => false,
|
||||
}
|
||||
@@ -865,20 +747,15 @@ impl Cipher {
|
||||
|
||||
// used for checking if collection can be edited (only if user has access to a collection they
|
||||
// can write to and also passwords are not hidden to prevent privilege escalation)
|
||||
pub async fn is_in_editable_collection_by_user(
|
||||
&self,
|
||||
user_uuid: &UserId,
|
||||
scope: CipherAccessScope,
|
||||
conn: &DbConn,
|
||||
) -> bool {
|
||||
match self.get_access_restrictions(user_uuid, scope, None, conn).await {
|
||||
pub async fn is_in_editable_collection_by_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool {
|
||||
match self.get_access_restrictions(user_uuid, None, conn).await {
|
||||
Some((read_only, hide_passwords, manage)) => (!read_only && !hide_passwords) || manage,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn is_accessible_to_user(&self, user_uuid: &UserId, scope: CipherAccessScope, conn: &DbConn) -> bool {
|
||||
self.get_access_restrictions(user_uuid, scope, None, conn).await.is_some()
|
||||
pub async fn is_accessible_to_user(&self, user_uuid: &UserId, conn: &DbConn) -> bool {
|
||||
self.get_access_restrictions(user_uuid, None, conn).await.is_some()
|
||||
}
|
||||
|
||||
// Returns whether this cipher is a favorite of the specified user.
|
||||
@@ -1316,50 +1193,6 @@ impl Cipher {
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Every collection of every cipher of the organization, for the members who may see all of them.
|
||||
pub async fn get_collections_with_cipher_by_organization(
|
||||
org_uuid: &OrganizationId,
|
||||
conn: &DbConn,
|
||||
) -> Vec<(CipherId, CollectionId)> {
|
||||
conn.run(move |conn| {
|
||||
ciphers_collections::table
|
||||
.inner_join(collections::table.on(collections::uuid.eq(ciphers_collections::collection_uuid)))
|
||||
.filter(collections::org_uuid.eq(org_uuid))
|
||||
.select(ciphers_collections::all_columns)
|
||||
.load::<(CipherId, CollectionId)>(conn)
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The ciphers of the organization of `member` the Admin Console lists when they may not edit every cipher, like
|
||||
/// Bitwarden does: the ones in the member's own vault, then, for a member who may edit any collection, the ones in
|
||||
/// no collection at all.
|
||||
pub async fn find_assigned_to_member(member: &Membership, conn: &DbConn) -> (Vec<Self>, Vec<Self>) {
|
||||
let assigned: Vec<Self> = Self::find_by_user_visible(&member.user_uuid, conn)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|cipher| cipher.organization_uuid.as_ref() == Some(&member.org_uuid))
|
||||
.collect();
|
||||
if !member.can_edit_any_collection() {
|
||||
return (assigned, Vec::new());
|
||||
}
|
||||
|
||||
let listed: HashSet<CipherId> = assigned.iter().map(|cipher| cipher.uuid.clone()).collect();
|
||||
let in_collections: HashSet<CipherId> =
|
||||
Self::get_collections_with_cipher_by_organization(&member.org_uuid, conn)
|
||||
.await
|
||||
.into_iter()
|
||||
.map(|(cipher, _)| cipher)
|
||||
.collect();
|
||||
let unassigned = Self::find_by_org(&member.org_uuid, conn)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|cipher| !in_collections.contains(&cipher.uuid) && !listed.contains(&cipher.uuid))
|
||||
.collect();
|
||||
(assigned, unassigned)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(
|
||||
|
||||
@@ -17,12 +17,11 @@ mod two_factor;
|
||||
mod two_factor_duo_context;
|
||||
mod two_factor_incomplete;
|
||||
mod user;
|
||||
mod user_signature_key_pair;
|
||||
|
||||
pub use self::archive::Archive;
|
||||
pub use self::attachment::{Attachment, AttachmentId};
|
||||
pub use self::auth_request::{AuthRequest, AuthRequestId};
|
||||
pub use self::cipher::{Cipher, CipherAccessScope, CipherId, RepromptType, is_data_blob_encrypted};
|
||||
pub use self::cipher::{Cipher, CipherId, RepromptType};
|
||||
pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionUser};
|
||||
pub use self::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId};
|
||||
pub use self::emergency_access::{
|
||||
@@ -42,5 +41,4 @@ pub use self::sso_auth::{OIDCAuthenticatedUser, OIDCCodeResponseError, SsoAuth};
|
||||
pub use self::two_factor::{TwoFactor, TwoFactorType};
|
||||
pub use self::two_factor_duo_context::TwoFactorDuoContext;
|
||||
pub use self::two_factor_incomplete::TwoFactorIncomplete;
|
||||
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType};
|
||||
pub use self::user_signature_key_pair::{SignatureAlgorithm, UserSignatureKeyPair};
|
||||
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType, UserStampException};
|
||||
@@ -69,9 +69,6 @@ pub struct Membership {
|
||||
access_event_logs: bool,
|
||||
access_import_export: bool,
|
||||
access_reports: bool,
|
||||
|
||||
/// The user's v2 upgrade token, for the org to unwrap the v2 user key after an upgrade. Opaque to us.
|
||||
pub v2_upgrade_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Identifiable, Queryable, Insertable, AsChangeset)]
|
||||
@@ -410,8 +407,6 @@ impl Membership {
|
||||
access_event_logs: false,
|
||||
access_import_export: false,
|
||||
access_reports: false,
|
||||
|
||||
v2_upgrade_token: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,35 +483,6 @@ impl Membership {
|
||||
)
|
||||
}
|
||||
|
||||
fn custom_permission(&self, permission: CustomPermission) -> bool {
|
||||
match permission {
|
||||
CustomPermission::ManageUsers => self.manage_users,
|
||||
CustomPermission::ManageGroups => self.manage_groups,
|
||||
CustomPermission::ManagePolicies => self.manage_policies,
|
||||
CustomPermission::CreateNewCollections => self.create_new_collections,
|
||||
CustomPermission::EditAnyCollection => self.edit_any_collection,
|
||||
CustomPermission::DeleteAnyCollection => self.delete_any_collection,
|
||||
CustomPermission::AccessEventLogs => self.access_event_logs,
|
||||
CustomPermission::AccessImportExport => self.access_import_export,
|
||||
CustomPermission::AccessReports => self.access_reports,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the role of this member grants `permission`. Only a Custom role grants any, only while Custom roles
|
||||
/// are enabled, and only the permissions this version enforces.
|
||||
fn grants_custom_permission(&self, permission: CustomPermission) -> bool {
|
||||
custom_roles_enabled()
|
||||
&& permission.is_supported()
|
||||
&& self.has_type(MembershipType::Custom)
|
||||
&& self.custom_permission(permission)
|
||||
}
|
||||
|
||||
/// Whether this member may act with `permission`, granted by their Custom role. Like the authority of any
|
||||
/// other role, it needs a confirmed membership.
|
||||
pub fn has_custom_permission(&self, permission: CustomPermission) -> bool {
|
||||
self.has_status(MembershipStatus::Confirmed) && self.grants_custom_permission(permission)
|
||||
}
|
||||
|
||||
pub fn restore(&mut self) -> bool {
|
||||
if self.status < MembershipStatus::Invited as i32 {
|
||||
self.status += ACTIVATE_REVOKE_DIFF;
|
||||
@@ -1035,13 +1001,6 @@ impl Membership {
|
||||
(self.access_all || self.atype >= MembershipType::Admin) && self.has_status(MembershipStatus::Confirmed)
|
||||
}
|
||||
|
||||
/// Whether this member may edit every collection and the items in them in the Admin Console: every member with
|
||||
/// full access, and a Custom member with Edit any collection. Unlike full access, the permission does not add
|
||||
/// anything to the member's own vault.
|
||||
pub fn can_edit_any_collection(&self) -> bool {
|
||||
self.has_full_access() || self.has_custom_permission(CustomPermission::EditAnyCollection)
|
||||
}
|
||||
|
||||
pub async fn find_by_uuid(uuid: &MembershipId, conn: &DbConn) -> Option<Self> {
|
||||
conn.run(move |conn| {
|
||||
users_organizations::table.filter(users_organizations::uuid.eq(uuid)).first::<Self>(conn).ok()
|
||||
|
||||
+28
-202
@@ -6,7 +6,6 @@ use serde_json::Value;
|
||||
use crate::{
|
||||
CONFIG,
|
||||
api::EmptyResult,
|
||||
auth::DEFAULT_ACCESS_VALIDITY,
|
||||
crypto,
|
||||
db::{
|
||||
DbConn,
|
||||
@@ -21,7 +20,7 @@ use macros::UuidFromParam;
|
||||
|
||||
use super::{
|
||||
AuthRequest, Cipher, Device, EmergencyAccess, Favorite, Folder, Membership, MembershipType, TwoFactor,
|
||||
TwoFactorIncomplete, UserSignatureKeyPair,
|
||||
TwoFactorIncomplete,
|
||||
};
|
||||
|
||||
#[derive(Identifiable, Queryable, Insertable, AsChangeset, Selectable)]
|
||||
@@ -73,13 +72,6 @@ pub struct User {
|
||||
pub external_id: Option<String>, // Todo: Needs to be removed in the future, this is not used anymore.
|
||||
|
||||
pub key_id: Option<KeyId>,
|
||||
|
||||
// The v2 state: all set, with a `user_signature_key_pairs` row, or none, see `User::is_v2`
|
||||
pub signed_public_key: Option<String>,
|
||||
pub security_state: Option<String>,
|
||||
pub security_version: Option<i32>,
|
||||
/// JSON `{"wrappedUserKey1", "wrappedUserKey2"}` for sessions that still hold the v1 user key. Opaque to us.
|
||||
pub v2_upgrade_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Identifiable, Queryable, Insertable)]
|
||||
@@ -108,28 +100,13 @@ enum UserStatus {
|
||||
_Disabled = 2,
|
||||
}
|
||||
|
||||
/// A previous security stamp that is still accepted, until `expire`.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct UserStampException {
|
||||
/// The routes the stamp is still accepted on, or `None` for any route.
|
||||
pub routes: Option<Vec<String>>,
|
||||
pub routes: Vec<String>,
|
||||
pub security_stamp: String,
|
||||
pub expire: i64,
|
||||
}
|
||||
|
||||
impl UserStampException {
|
||||
pub fn is_expired(&self) -> bool {
|
||||
Utc::now().timestamp() > self.expire
|
||||
}
|
||||
|
||||
/// Whether this exception lets a token carrying `security_stamp` through on `route`.
|
||||
pub fn allows(&self, security_stamp: &str, route: &str) -> bool {
|
||||
!self.is_expired()
|
||||
&& self.security_stamp == security_stamp
|
||||
&& self.routes.as_ref().is_none_or(|routes| routes.iter().any(|r| r == route))
|
||||
}
|
||||
}
|
||||
|
||||
/// Local methods
|
||||
impl User {
|
||||
pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32;
|
||||
@@ -182,31 +159,9 @@ impl User {
|
||||
external_id: None, // Todo: Needs to be removed in the future, this is not used anymore.
|
||||
|
||||
key_id: None,
|
||||
|
||||
signed_public_key: None,
|
||||
security_state: None,
|
||||
security_version: None,
|
||||
v2_upgrade_token: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_v2(&self) -> bool {
|
||||
self.signed_public_key.is_some() && self.security_state.is_some() && self.security_version.is_some()
|
||||
}
|
||||
|
||||
/// Upstream's `HasV2Encryption`: a private key wrapped as `CoseEncrypt0B64` (type 7) and security version 2.
|
||||
/// Upstream only uses it to decide which accounts need a v2-capable client.
|
||||
///
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/8da186ad73f80d37157fe6fd42323e4284e83ec1/src/Core/Entities/User.cs#L245-L278>
|
||||
pub fn has_v2_encryption(&self) -> bool {
|
||||
self.security_version == Some(2)
|
||||
&& self
|
||||
.private_key
|
||||
.as_deref()
|
||||
.and_then(|private_key| private_key.split_once('.'))
|
||||
.is_some_and(|(enc_type, _)| enc_type.parse::<u8>() == Ok(7))
|
||||
}
|
||||
|
||||
pub fn check_valid_password(&self, password: &str) -> bool {
|
||||
crypto::verify_password_hash(
|
||||
password.as_bytes(),
|
||||
@@ -216,7 +171,6 @@ impl User {
|
||||
)
|
||||
}
|
||||
|
||||
/// Upstream's `GetMasterPasswordSalt`: there is no separate salt, so the normalized email
|
||||
pub fn master_password_salt(&self) -> String {
|
||||
self.email.trim().to_lowercase()
|
||||
}
|
||||
@@ -271,33 +225,10 @@ impl User {
|
||||
|
||||
pub async fn reset_security_stamp(&mut self, conn: &DbConn) -> EmptyResult {
|
||||
self.security_stamp = get_uuid();
|
||||
// Keeps the unexpired route exceptions, set for the stamp being replaced, and drops a rotation's grace
|
||||
let mut exceptions = self.stamp_exceptions();
|
||||
exceptions.retain(|e| e.routes.is_some() && !e.is_expired());
|
||||
self.set_stamp_exceptions(&exceptions);
|
||||
Device::rotate_refresh_tokens_by_user(&self.uuid, conn).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resets the stamp but lets issued access tokens run out, as upstream only checks it on refresh.
|
||||
pub async fn reset_security_stamp_after_key_rotation(&mut self, conn: &DbConn) -> EmptyResult {
|
||||
let previous_stamp = self.security_stamp.clone();
|
||||
let mut grace: Vec<UserStampException> =
|
||||
self.stamp_exceptions().into_iter().filter(|e| e.routes.is_none() && !e.is_expired()).collect();
|
||||
|
||||
self.reset_security_stamp(conn).await?;
|
||||
|
||||
grace.push(UserStampException {
|
||||
routes: None,
|
||||
security_stamp: previous_stamp,
|
||||
expire: (Utc::now() + *DEFAULT_ACCESS_VALIDITY).timestamp(),
|
||||
});
|
||||
let mut exceptions = self.stamp_exceptions();
|
||||
exceptions.extend(grace);
|
||||
self.set_stamp_exceptions(&exceptions);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set the stamp_exception to only allow a subsequent request matching a specific route using the current security-stamp.
|
||||
///
|
||||
/// # Arguments
|
||||
@@ -306,30 +237,17 @@ impl User {
|
||||
/// After these 2 minutes this stamp will expire.
|
||||
///
|
||||
pub fn set_stamp_exception(&mut self, route_exception: Vec<String>) {
|
||||
self.set_stamp_exceptions(&[UserStampException {
|
||||
routes: Some(route_exception),
|
||||
let stamp_exception = UserStampException {
|
||||
routes: route_exception,
|
||||
security_stamp: self.security_stamp.clone(),
|
||||
expire: (Utc::now() + TimeDelta::try_minutes(2).unwrap()).timestamp(),
|
||||
}]);
|
||||
};
|
||||
self.stamp_exception = Some(serde_json::to_string(&stamp_exception).unwrap_or_default());
|
||||
}
|
||||
|
||||
/// The previous security stamps that are still accepted, expired ones included.
|
||||
pub fn stamp_exceptions(&self) -> Vec<UserStampException> {
|
||||
let Some(stored) = self.stamp_exception.as_deref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
// Before key rotations kept sessions alive, only a single route exception was stored.
|
||||
serde_json::from_str::<Vec<UserStampException>>(stored)
|
||||
.or_else(|_| serde_json::from_str::<UserStampException>(stored).map(|e| vec![e]))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn set_stamp_exceptions(&mut self, exceptions: &[UserStampException]) {
|
||||
self.stamp_exception = if exceptions.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(serde_json::to_string(&exceptions).unwrap_or_default())
|
||||
};
|
||||
/// Resets the stamp_exception to prevent re-use of the previous security-stamp
|
||||
pub fn reset_stamp_exception(&mut self) {
|
||||
self.stamp_exception = None;
|
||||
}
|
||||
|
||||
pub fn display_name(&self) -> &str {
|
||||
@@ -348,37 +266,18 @@ impl User {
|
||||
!CONFIG.mail_enabled() || self.verified_at.is_some()
|
||||
}
|
||||
|
||||
async fn v2_signature_key_pair(&self, conn: &DbConn) -> Option<UserSignatureKeyPair> {
|
||||
if !self.is_v2() {
|
||||
return None;
|
||||
}
|
||||
UserSignatureKeyPair::find_by_user(&self.uuid, conn).await
|
||||
}
|
||||
|
||||
/// The `accountKeys` object (upstream's `PrivateKeysResponseModel`), null without a key pair
|
||||
pub async fn account_keys_json(&self, conn: &DbConn) -> Value {
|
||||
pub fn account_keys_json(&self) -> Value {
|
||||
if self.private_key.is_some() {
|
||||
let (signed_public_key, signature_key_pair, security_state) = match self.v2_signature_key_pair(conn).await {
|
||||
Some(key_pair) => (
|
||||
json!(self.signed_public_key),
|
||||
key_pair.to_json(),
|
||||
json!({
|
||||
"securityState": self.security_state,
|
||||
"securityVersion": self.security_version,
|
||||
}),
|
||||
),
|
||||
None => (Value::Null, Value::Null, Value::Null),
|
||||
};
|
||||
|
||||
json!({
|
||||
"publicKeyEncryptionKeyPair": {
|
||||
"wrappedPrivateKey": self.private_key,
|
||||
"publicKey": self.public_key,
|
||||
"signedPublicKey": signed_public_key,
|
||||
"signedPublicKey": null,
|
||||
"object": "publicKeyEncryptionKeyPair",
|
||||
},
|
||||
"securityState": security_state,
|
||||
"signatureKeyPair": signature_key_pair,
|
||||
"securityState": null,
|
||||
"signatureKeyPair": null,
|
||||
"object": "privateKeys"
|
||||
})
|
||||
} else {
|
||||
@@ -386,24 +285,6 @@ impl User {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn public_keys_json(&self, conn: &DbConn) -> Value {
|
||||
let (signed_public_key, verifying_key) = match self.v2_signature_key_pair(conn).await {
|
||||
Some(key_pair) => (json!(self.signed_public_key), json!(key_pair.verifying_key)),
|
||||
None => (Value::Null, Value::Null),
|
||||
};
|
||||
|
||||
json!({
|
||||
"publicKey": self.public_key,
|
||||
"signedPublicKey": signed_public_key,
|
||||
"verifyingKey": verifying_key,
|
||||
"object": "publicKeys"
|
||||
})
|
||||
}
|
||||
|
||||
pub fn v2_upgrade_token_json(&self) -> Option<Value> {
|
||||
self.v2_upgrade_token.as_ref().and_then(|token| serde_json::from_str(token).ok())
|
||||
}
|
||||
|
||||
pub async fn to_json(&self, conn: &DbConn) -> Value {
|
||||
let mut orgs_json = Vec::new();
|
||||
for c in Membership::find_confirmed_by_user(&self.uuid, conn).await {
|
||||
@@ -424,7 +305,7 @@ impl User {
|
||||
UserStatus::Enabled
|
||||
};
|
||||
|
||||
let account_keys = self.account_keys_json(conn).await;
|
||||
let account_keys = self.account_keys_json();
|
||||
|
||||
json!({
|
||||
"_status": status as i32,
|
||||
@@ -501,7 +382,6 @@ impl User {
|
||||
Device::delete_all_by_user(&self.uuid, conn).await?;
|
||||
TwoFactor::delete_all_by_user(&self.uuid, conn).await?;
|
||||
TwoFactorIncomplete::delete_all_by_user(&self.uuid, conn).await?;
|
||||
UserSignatureKeyPair::delete_all_by_user(&self.uuid, conn).await?;
|
||||
Invitation::take(&self.email, conn).await; // Delete invitation if any
|
||||
|
||||
conn.run(move |conn| {
|
||||
@@ -673,26 +553,25 @@ impl Invitation {
|
||||
pub struct UserId(String);
|
||||
|
||||
#[derive(
|
||||
Clone, Debug, DieselNewType, FromForm, PartialEq, Eq, Hash, Serialize, AsRef, Deref, Display, From, UuidFromParam,
|
||||
Clone,
|
||||
Debug,
|
||||
DieselNewType,
|
||||
FromForm,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
AsRef,
|
||||
Deref,
|
||||
Display,
|
||||
From,
|
||||
UuidFromParam,
|
||||
)]
|
||||
#[deref(forward)]
|
||||
#[from(forward)]
|
||||
pub struct KeyId(String);
|
||||
|
||||
/// Like upstream, a key id is 32 lowercase hex characters. Key ids are compared as strings, so one in any other
|
||||
/// format would never match the id the clients send.
|
||||
///
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/8da186ad73f80d37157fe6fd42323e4284e83ec1/src/Core/KeyManagement/Models/Data/KeyId.cs#L20-L42>
|
||||
impl<'de> serde::Deserialize<'de> for KeyId {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let key_id = String::deserialize(deserializer)?;
|
||||
if key_id.len() != 32 || !key_id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
|
||||
return Err(serde::de::Error::custom("Key id must be 32 lowercase hex characters"));
|
||||
}
|
||||
Ok(Self(key_id))
|
||||
}
|
||||
}
|
||||
|
||||
impl SsoUser {
|
||||
pub async fn save(&self, conn: &DbConn) -> EmptyResult {
|
||||
db_run! { conn:
|
||||
@@ -746,56 +625,3 @@ impl SsoUser {
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_key_id_format() {
|
||||
let key_id: KeyId = serde_json::from_str(r#""0123456789abcdef0123456789abcdef""#).unwrap();
|
||||
assert_eq!(key_id.as_ref(), "0123456789abcdef0123456789abcdef");
|
||||
|
||||
for invalid in ["", "0123456789ABCDEF0123456789ABCDEF", "0123456789abcdef", "0123456789abcdef0123456789abcdeg"]
|
||||
{
|
||||
assert!(serde_json::from_str::<KeyId>(&format!("\"{invalid}\"")).is_err(), "{invalid:?}");
|
||||
}
|
||||
|
||||
// An absent key id stays optional
|
||||
assert_eq!(serde_json::from_str::<Option<KeyId>>("null").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_v2_encryption() {
|
||||
// User::new loads CONFIG; isolate it from the DNS bootstrap test and filesystem configuration.
|
||||
if std::env::var_os("VAULTWARDEN_ISOLATED_CONFIG_TEST").is_none() {
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", std::thread::current().name().unwrap(), "--nocapture"])
|
||||
.env("VAULTWARDEN_ISOLATED_CONFIG_TEST", "1")
|
||||
.env("DATABASE_URL", "sqlite://:memory:")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed"),
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let user = |private_key: Option<&str>, security_version: Option<i32>| {
|
||||
let mut user = User::new("user@example.com", None);
|
||||
user.private_key = private_key.map(String::from);
|
||||
user.security_version = security_version;
|
||||
user
|
||||
};
|
||||
|
||||
assert!(user(Some("7.cose"), Some(2)).has_v2_encryption());
|
||||
assert!(!user(Some("7.cose"), Some(1)).has_v2_encryption());
|
||||
assert!(!user(Some("7.cose"), None).has_v2_encryption());
|
||||
assert!(!user(Some("2.iv|data|mac"), Some(2)).has_v2_encryption());
|
||||
assert!(!user(Some("7"), Some(2)).has_v2_encryption());
|
||||
assert!(!user(None, Some(2)).has_v2_encryption());
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
use chrono::{NaiveDateTime, Utc};
|
||||
use derive_more::{AsRef, Deref, Display, From};
|
||||
use diesel::prelude::*;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
api::EmptyResult,
|
||||
db::{DbConn, schema::user_signature_key_pairs},
|
||||
error::MapResult,
|
||||
util::get_uuid,
|
||||
};
|
||||
|
||||
use super::UserId;
|
||||
|
||||
/// A user's signature key pair, part of the v2 state, in its own table like upstream.
|
||||
///
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/9030c42bf7d8f9ac2ff9fee85c39588d5eb81499/src/Sql/dbo/KeyManagement/Tables/UserSignatureKeyPair.sql#L1-L15>
|
||||
#[derive(Identifiable, Queryable, Insertable, AsChangeset, Selectable)]
|
||||
#[diesel(table_name = user_signature_key_pairs)]
|
||||
#[diesel(treat_none_as_null = true)]
|
||||
#[diesel(primary_key(uuid))]
|
||||
pub struct UserSignatureKeyPair {
|
||||
pub uuid: UserSignatureKeyPairId,
|
||||
pub user_uuid: UserId,
|
||||
|
||||
pub signature_algorithm: i32,
|
||||
/// The signing (private) key, wrapped by the user key.
|
||||
pub signing_key: String,
|
||||
/// The COSE-encoded public verifying key.
|
||||
pub verifying_key: String,
|
||||
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
/// Ref: <https://github.com/bitwarden/server/blob/9030c42bf7d8f9ac2ff9fee85c39588d5eb81499/src/Core/KeyManagement/Enums/SignatureAlgorithm.cs#L6-L10>
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SignatureAlgorithm {
|
||||
Ed25519 = 0,
|
||||
MlDsa44 = 1,
|
||||
}
|
||||
|
||||
impl SignatureAlgorithm {
|
||||
pub fn parse(algorithm: &str) -> Option<Self> {
|
||||
match algorithm {
|
||||
"ed25519" => Some(Self::Ed25519),
|
||||
"mldsa44" => Some(Self::MlDsa44),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Local methods
|
||||
impl UserSignatureKeyPair {
|
||||
pub fn new(
|
||||
user_uuid: UserId,
|
||||
signature_algorithm: SignatureAlgorithm,
|
||||
signing_key: String,
|
||||
verifying_key: String,
|
||||
) -> Self {
|
||||
let now = Utc::now().naive_utc();
|
||||
|
||||
Self {
|
||||
uuid: UserSignatureKeyPairId(get_uuid()),
|
||||
user_uuid,
|
||||
signature_algorithm: signature_algorithm as i32,
|
||||
signing_key,
|
||||
verifying_key,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"wrappedSigningKey": self.signing_key,
|
||||
"verifyingKey": self.verifying_key,
|
||||
"object": "signatureKeyPair",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Database methods
|
||||
impl UserSignatureKeyPair {
|
||||
pub async fn save(&mut self, conn: &DbConn) -> EmptyResult {
|
||||
self.updated_at = Utc::now().naive_utc();
|
||||
|
||||
db_run! { conn:
|
||||
mysql {
|
||||
diesel::insert_into(user_signature_key_pairs::table)
|
||||
.values(&*self)
|
||||
.on_conflict(diesel::dsl::DuplicatedKeys)
|
||||
.do_update()
|
||||
.set(&*self)
|
||||
.execute(conn)
|
||||
.map_res("Error saving user signature key pair")
|
||||
}
|
||||
postgresql, sqlite {
|
||||
diesel::insert_into(user_signature_key_pairs::table)
|
||||
.values(&*self)
|
||||
.on_conflict(user_signature_key_pairs::user_uuid)
|
||||
.do_update()
|
||||
.set(&*self)
|
||||
.execute(conn)
|
||||
.map_res("Error saving user signature key pair")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's key pair. There is at most one, enforced by a unique index on `user_uuid`.
|
||||
pub async fn find_by_user(user_uuid: &UserId, conn: &DbConn) -> Option<Self> {
|
||||
conn.run(move |conn| {
|
||||
user_signature_key_pairs::table
|
||||
.filter(user_signature_key_pairs::user_uuid.eq(user_uuid))
|
||||
.first::<Self>(conn)
|
||||
.ok()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete_all_by_user(user_uuid: &UserId, conn: &DbConn) -> EmptyResult {
|
||||
conn.run(move |conn| {
|
||||
diesel::delete(user_signature_key_pairs::table.filter(user_signature_key_pairs::user_uuid.eq(user_uuid)))
|
||||
.execute(conn)
|
||||
.map_res("Error deleting user signature key pairs")
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, AsRef, Deref, DieselNewType, Display, From, Hash, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct UserSignatureKeyPairId(String);
|
||||
@@ -219,22 +219,6 @@ table! {
|
||||
avatar_color -> Nullable<Text>,
|
||||
external_id -> Nullable<Text>,
|
||||
key_id -> Nullable<Text>,
|
||||
signed_public_key -> Nullable<Text>,
|
||||
security_state -> Nullable<Text>,
|
||||
security_version -> Nullable<Integer>,
|
||||
v2_upgrade_token -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
user_signature_key_pairs (uuid) {
|
||||
uuid -> Text,
|
||||
user_uuid -> Text,
|
||||
signature_algorithm -> Integer,
|
||||
signing_key -> Text,
|
||||
verifying_key -> Text,
|
||||
created_at -> Timestamp,
|
||||
updated_at -> Timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,7 +253,6 @@ table! {
|
||||
access_event_logs -> Bool,
|
||||
access_import_export -> Bool,
|
||||
access_reports -> Bool,
|
||||
v2_upgrade_token -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,7 +393,6 @@ joinable!(collections_groups -> groups (groups_uuid));
|
||||
joinable!(event -> users_organizations (uuid));
|
||||
joinable!(auth_requests -> users (user_uuid));
|
||||
joinable!(sso_users -> users (user_uuid));
|
||||
joinable!(user_signature_key_pairs -> users (user_uuid));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
archives,
|
||||
@@ -437,5 +419,4 @@ allow_tables_to_appear_in_same_query!(
|
||||
collections_groups,
|
||||
event,
|
||||
auth_requests,
|
||||
user_signature_key_pairs,
|
||||
);
|
||||
@@ -899,12 +899,6 @@ pub fn parse_experimental_client_feature_flags(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the admin enabled this supported client feature flag
|
||||
pub fn is_client_feature_flag_enabled(flag: &str) -> bool {
|
||||
parse_experimental_client_feature_flags(&CONFIG.experimental_client_feature_flags(), &FeatureFlagFilter::ValidOnly)
|
||||
.contains_key(flag)
|
||||
}
|
||||
|
||||
/// TODO: This is extracted from IpAddr::is_global, which is unstable:
|
||||
/// https://doc.rust-lang.org/nightly/std/net/enum.IpAddr.html#method.is_global
|
||||
/// Remove once https://github.com/rust-lang/rust/issues/27709 is merged
|
||||
|
||||
Reference in new issue
Block a user