Browse Source

Merge bd12af6e86 into d626ea81ab

pull/5591/merge
Chase Douglas 3 days ago
committed by GitHub
parent
commit
66d761e42e
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 49
      .github/workflows/lambda.yml
  2. 55
      Cargo.lock
  3. 5
      Cargo.toml
  4. 7
      CargoLambda.toml
  5. 3
      aws/.gitignore
  6. 60
      aws/README.md
  7. 74
      aws/build-lambda.sh
  8. 9
      aws/deploy.sh
  9. 12
      aws/samconfig.toml
  10. 711
      aws/template.yaml
  11. 11
      build.rs
  12. 1
      migrations/dsql/2024-12-30-100000_create_tables/metadata.toml
  13. 281
      migrations/dsql/2024-12-30-100000_create_tables/up.sql
  14. 0
      migrations/dsql/2025-01-09-172300_add_manage/down.sql
  15. 1
      migrations/dsql/2025-01-09-172300_add_manage/metadata.toml
  16. 8
      migrations/dsql/2025-01-09-172300_add_manage/up.sql
  17. 1
      migrations/dsql/2025-08-20-120000_add_users_organizations_invited_by_email/down.sql
  18. 1
      migrations/dsql/2025-08-20-120000_add_users_organizations_invited_by_email/metadata.toml
  19. 2
      migrations/dsql/2025-08-20-120000_add_users_organizations_invited_by_email/up.sql
  20. 1
      migrations/dsql/2025-08-20-120100_add_sso_users/down.sql
  21. 1
      migrations/dsql/2025-08-20-120100_add_sso_users/metadata.toml
  22. 4
      migrations/dsql/2025-08-20-120100_add_sso_users/up.sql
  23. 1
      migrations/dsql/2025-08-20-120200_add_sso_auth/down.sql
  24. 1
      migrations/dsql/2025-08-20-120200_add_sso_auth/metadata.toml
  25. 10
      migrations/dsql/2025-08-20-120200_add_sso_auth/up.sql
  26. 1
      migrations/dsql/2026-03-09-005927_add_archives/down.sql
  27. 1
      migrations/dsql/2026-03-09-005927_add_archives/metadata.toml
  28. 6
      migrations/dsql/2026-03-09-005927_add_archives/up.sql
  29. 1
      migrations/dsql/2026-04-25-120000_sso_auth_binding/down.sql
  30. 1
      migrations/dsql/2026-04-25-120000_sso_auth_binding/metadata.toml
  31. 2
      migrations/dsql/2026-04-25-120000_sso_auth_binding/up.sql
  32. 2
      src/api/admin.rs
  33. 39
      src/aws.rs
  34. 13
      src/config.rs
  35. 110
      src/db/dsql.rs
  36. 46
      src/db/mod.rs
  37. 2
      src/http_client.rs
  38. 47
      src/mail.rs
  39. 2
      src/main.rs
  40. 24
      src/storage.rs

49
.github/workflows/lambda.yml

@ -0,0 +1,49 @@
name: Build Lambda Package
on: workflow_dispatch
jobs:
build:
runs-on: ubuntu-24.04-arm
container:
image: public.ecr.aws/codebuild/amazonlinux2-aarch64-standard:3.0
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Install development packages
run: sudo yum install -y krb5-devel openldap-devel
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Install Cargo Lambda
uses: jaxxstorm/action-install-gh-release@v1.9.0
with:
repo: cargo-lambda/cargo-lambda
platform: linux
arch: aarch64
- name: Setup rust Cache
uses: Swatinem/rust-cache@v2
- name: Build with Cargo
run: cargo lambda build --verbose
- name: Copy libpq and its dependencies
run: cp /lib64/{libcrypt.so.2,liblber-2.4.so.2,libldap_r-2.4.so.2,libpq.so.5,libsasl2.so.3} target/lambda/vaultwarden/
# This ensures passes the startup checks for the web-vault, which is
# instead served statically from an S3 Bucket
- name: Create placeholder web-vault/index.html
run: |-
mkdir target/lambda/vaultwarden/web-vault
echo "<html><body><h1>Web Vault Placeholder</h1></body></html>" > target/lambda/vaultwarden/web-vault/index.html
- name: Archive function package
uses: actions/upload-artifact@v4
with:
name: vaultwarden-lambda
path: target/lambda/vaultwarden/*

55
Cargo.lock

@ -405,6 +405,56 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "aws-sdk-dsql"
version = "1.55.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f914acf80007b4d0fc1e68d7f8045b39d58367bc3aaa8270c44368e8b8dd3ee1"
dependencies = [
"aws-credential-types",
"aws-runtime",
"aws-sigv4",
"aws-smithy-async",
"aws-smithy-http",
"aws-smithy-json",
"aws-smithy-observability",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-types",
"aws-types",
"bytes",
"fastrand",
"http 0.2.12",
"http 1.4.0",
"regex-lite",
"tracing",
"url",
]
[[package]]
name = "aws-sdk-sesv2"
version = "1.118.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8d0642857f4fe76cd9a3d8c4f2b393546f7561f7725052dd9f268005fda92b7"
dependencies = [
"aws-credential-types",
"aws-runtime",
"aws-smithy-async",
"aws-smithy-http",
"aws-smithy-json",
"aws-smithy-observability",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-types",
"aws-types",
"bytes",
"fastrand",
"http 0.2.12",
"http 1.4.0",
"regex-lite",
"tracing",
]
[[package]] [[package]]
name = "aws-sdk-sso" name = "aws-sdk-sso"
version = "1.98.0" version = "1.98.0"
@ -622,6 +672,7 @@ dependencies = [
"base64-simd", "base64-simd",
"bytes", "bytes",
"bytes-utils", "bytes-utils",
"futures-core",
"http 0.2.12", "http 0.2.12",
"http 1.4.0", "http 1.4.0",
"http-body 0.4.6", "http-body 0.4.6",
@ -634,6 +685,8 @@ dependencies = [
"ryu", "ryu",
"serde", "serde",
"time", "time",
"tokio",
"tokio-util",
] ]
[[package]] [[package]]
@ -5765,6 +5818,8 @@ dependencies = [
"argon2", "argon2",
"aws-config", "aws-config",
"aws-credential-types", "aws-credential-types",
"aws-sdk-dsql",
"aws-sdk-sesv2",
"aws-smithy-runtime-api", "aws-smithy-runtime-api",
"bigdecimal", "bigdecimal",
"bytes", "bytes",

5
Cargo.toml

@ -40,6 +40,8 @@ vendored_openssl = ["openssl/vendored"]
# Enable MiMalloc memory allocator to replace the default malloc # Enable MiMalloc memory allocator to replace the default malloc
# This can improve performance for Alpine builds # This can improve performance for Alpine builds
enable_mimalloc = ["dep:mimalloc"] enable_mimalloc = ["dep:mimalloc"]
aws = ["dsql", "s3", "ses"]
dsql = ["postgresql", "dep:aws-config", "dep:aws-sdk-dsql", "dep:aws-smithy-runtime-api"]
s3 = [ s3 = [
"opendal/services-s3", "opendal/services-s3",
"dep:aws-config", "dep:aws-config",
@ -49,6 +51,7 @@ s3 = [
"dep:reqsign-aws-v4", "dep:reqsign-aws-v4",
"dep:reqsign-core", "dep:reqsign-core",
] ]
ses = ["dep:aws-config", "dep:aws-sdk-sesv2", "dep:aws-smithy-runtime-api"]
# OIDC specific features # OIDC specific features
oidc-accept-rfc3339-timestamps = ["openidconnect/accept-rfc3339-timestamps"] oidc-accept-rfc3339-timestamps = ["openidconnect/accept-rfc3339-timestamps"]
@ -264,6 +267,8 @@ aws-config = { version = "1.8.16", optional = true, default-features = false, fe
"sso", "sso",
] } ] }
aws-credential-types = { version = "1.2.14", optional = true } aws-credential-types = { version = "1.2.14", optional = true }
aws-sdk-dsql = { version = "1.55.0", features = ["behavior-version-latest", "rt-tokio"], default-features = false, optional = true }
aws-sdk-sesv2 = { version = "1.118.0", features = ["behavior-version-latest", "rt-tokio"], default-features = false, optional = true }
aws-smithy-runtime-api = { version = "1.12.0", optional = true } aws-smithy-runtime-api = { version = "1.12.0", optional = true }
http = { version = "1.4.0", optional = true } http = { version = "1.4.0", optional = true }
reqsign-aws-v4 = { version = "3.0.0", optional = true } reqsign-aws-v4 = { version = "3.0.0", optional = true }

7
CargoLambda.toml

@ -0,0 +1,7 @@
[build]
features = ["aws"]
release = true
arm64 = true
[build.compiler]
type = "cargo"

3
aws/.gitignore

@ -0,0 +1,3 @@
.aws-sam
vaultwarden-lambda.zip
web-vault

60
aws/README.md

@ -0,0 +1,60 @@
# AWS Serverless Deployment Instructions
## Architecture
```
CloudFront CDN
├─ API Lambda Function
│ ├─ Data S3 Bucket
│ ├─ Aurora DSQL Database
│ └─ Amazon Simple Email Service (SES)
└─ Web-vault static assets S3 Bucket
```
## A Note On AWS Accounts and Security
It is common to have one AWS account host multiple services. But it's easy, and doesn't cost any additional amount, to separate workloads into their own accounts. Doing so makes it easier to control for security concerns and monitor costs. AWS Identity and Access Management (IAM) enforces additional controls for cross-account access than for within-account access, for example, making it harder for security attacks to hop from workload to workload when they are in separate accounts.
Given the confidential nature of data stored in Vaultwarden, it is *highly* recommended that you create a new, separate AWS account just for Vaultwarden. If you only have one account, investigate creating an [AWS Organization](https://aws.amazon.com/organizations/) to make it easy to create a second account tied to the same billing and account management mechanism, and investigate creating an [AWS IAM Identity Center](https://aws.amazon.com/iam/identity-center/) instance for easy SSO access across your accounts.
## Initial Deployment
1. Create an AWS account
1. Install the AWS CLI
1. Install AWS SAM CLI
1. Build or download the `vaultwarden-lambda.zip` Lambda Function code package to this directory (build instructions below)
1. Pick a region that supports DSQL to deploy the Vaultwarden application into (see the [DSQL docs](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/what-is-aurora-dsql.html#region-availability) for supported regions))
1. Setup local AWS configuration to access account and region from CLI
1. Run `./deploy.sh` in this directory
* Parameters either have reasonable default values or can be left blank
1. Note the "Output" values from the deploy command
* These can also be retrieved later by running `sam list stack-outputs`
1. Download the latest [web-vault build](https://github.com/dani-garcia/bw_web_builds/releases) and extract it
1. Sync the web-vault build contents into the WebVaultAssetsBucket:
* Inside the web-vault build folder run `aws s3 sync . s3://<WebVaultAssetsBucket>`, where `WebVaultAssetsBucket` is a stack output value
1. You can now navigate to your instance at the location of your `CDNDomain` stack output value
## Building The Lambda Package Locally
The GitHub Actions Lambda workflow builds inside Amazon Linux for arm64 and packages the contents of `target/lambda/vaultwarden`. To do the same locally, run the VS Code `Build Lambda package` task or run:
```sh
./aws/build-lambda.sh
```
This uses Docker with `public.ecr.aws/codebuild/amazonlinux2-aarch64-standard:3.0`, installs the same build dependencies as `.github/workflows/lambda.yml`, runs `cargo lambda build --verbose`, copies the required shared libraries, creates the placeholder web vault file, and writes `aws/vaultwarden-lambda.zip`.
## Custom Domain
1. Create an AWS Certificate Manager (ACM) Certificate for your domain **in the us-east-1 region**
* There are many tutorials and/or automated ways to do this, including following the official docs [here](https://docs.aws.amazon.com/acm/latest/userguide/acm-public-certificates.html)
* It must be in the us-east-1 region because CloudFront only supports certificates from us-east-1
* Use key algorithm RSA 2048
* Continue to the next step once the certificate is in the *Issued* state
* Note the certificate's ARN
1. Run `./deploy.sh` again and add the following parameter values:
* **Domain**: `https://<custom domain>`
* **ACMCertificateArn**: The ARN of the certificate you created for the domain
1. Create a CNAME record for the custom domain set to the value of the CDNDomain stack output
## Email via AWS Simple Email Service (SES)
Email is complicated. These instructions will not attempt to walk you through setting up SES identities for sending email. You may find docs and guides online for how to do this.
In order for Vaultwarden to send emails using SES you must have an SES Email Address Identity that **does not have a default configuration set**. An identity with a default configuration set breaks the IAM permission model set up for the Vaultwarden API Function.
Once you have an SES Identity for the sending email address, run `./deploy.sh` again and provide the email address in the `SMTP_FROM` parameter.

74
aws/build-lambda.sh

@ -0,0 +1,74 @@
#!/usr/bin/env bash
set -euo pipefail
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "${script_dir}/.." && pwd)"
image="${VAULTWARDEN_LAMBDA_BUILD_IMAGE:-public.ecr.aws/codebuild/amazonlinux2-aarch64-standard:3.0}"
platform="${VAULTWARDEN_LAMBDA_BUILD_PLATFORM:-linux/arm64}"
package_path="${repo_root}/aws/vaultwarden-lambda.zip"
docker_tty_args=()
if [ -t 1 ]; then
docker_tty_args=(-t)
fi
printf 'Building Lambda package with %s for %s\n' "${image}" "${platform}"
docker run \
--rm \
--pull=missing \
--platform "${platform}" \
"${docker_tty_args[@]}" \
--entrypoint /bin/bash \
-e HOST_UID="$(id -u)" \
-e HOST_GID="$(id -g)" \
-v "${repo_root}:/work" \
-v vaultwarden-lambda-cargo-home:/root/.cargo \
-v vaultwarden-lambda-rustup-home:/root/.rustup \
-w /work \
"${image}" \
-lc '
set -euo pipefail
export PATH="$HOME/.cargo/bin:$PATH"
restore_ownership() {
for path in target aws/vaultwarden-lambda.zip; do
if [ -e "$path" ]; then
chown -R "${HOST_UID}:${HOST_GID}" "$path"
fi
done
}
trap restore_ownership EXIT
yum install -y krb5-devel openldap-devel unzip xz zip
if ! command -v rustup >/dev/null 2>&1; then
curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal --default-toolchain stable
fi
rustup default stable
if ! command -v cargo-lambda >/dev/null 2>&1; then
curl -fsSL https://cargo-lambda.info/install.sh | sh
fi
cargo lambda build --verbose
cp /lib64/{libcrypt.so.2,liblber-2.4.so.2,libldap_r-2.4.so.2,libpq.so.5,libsasl2.so.3} \
target/lambda/vaultwarden/
mkdir -p target/lambda/vaultwarden/web-vault
printf "%s\n" "<html><body><h1>Web Vault Placeholder</h1></body></html>" \
> target/lambda/vaultwarden/web-vault/index.html
rm -f aws/vaultwarden-lambda.zip
(
cd target/lambda/vaultwarden
zip -r /work/aws/vaultwarden-lambda.zip .
)
'
printf 'Created %s\n' "${package_path}"

9
aws/deploy.sh

@ -0,0 +1,9 @@
#!/bin/sh -e
echo 'Building template...'
sam build
echo ''
sam deploy --guided

12
aws/samconfig.toml

@ -0,0 +1,12 @@
version = 0.1
[default.global.parameters]
stack_name = "vaultwarden"
[default.deploy.parameters]
resolve_s3 = true
s3_prefix = "vaultwarden"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
image_repositories = []
disable_rollback = true

711
aws/template.yaml

@ -0,0 +1,711 @@
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS CloudFormation template for running VaultWarden on AWS serverless services.
Parameters:
Domain:
Type: String
Description: >-
The domain name for the Vaultwarden instance (e.g. https://example.com). If this parameter or the ACMCertificateArn
parameter are left empty, the Vaultwarden instance can still be reached at the output CDN domain
(e.g. https://xxxxxxxx.cloudfront.net).
AllowedPattern: (https://[a-z0-9.-]+|)
Default: ''
ACMCertificateArn:
Type: String
Description: The ARN of a us-east-1 ACM certificate to use for the domain. Required if the `Domain` parameter is set.
AllowedPattern: (arn:aws:acm:us-east-1:[0-9]+:certificate/[0-9a-f-]+|)
Default: ''
DataBackupRetention:
Type: Number
Description: The number of days to retain the backups in AWS Backup. Backups older than this value will be automatically deleted. Set to 0 to disable automatic deletion of old backups. Set to -1 to disable backups.
Default: 365
APILogRetention:
Type: Number
Description: The number of days to retain the API logs. -1 means to never expire.
Default: -1
AllowedValues: [-1, 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653]
SignupsAllowed:
Type: String
Description: Controls if new users can register
Default: 'true'
AllowedValues: ['true', 'false']
IconService:
Type: String
Description: Allowed icon service sources.
Default: bitwarden
AdminToken:
Type: String
Description: Token for the admin interface, preferably an Argon2 PCH string. If empty, the admin interface will be disabled.
Default: ''
SMTPFrom:
Type: String
Description: The email address to send emails from. Email service is disabled if this value is empty.
Default: ''
SMTPFromName:
Type: String
Description: The name to send emails from.
Default: Vaultwarden
Mappings:
IconSource:
internal:
CSP: ''
bitwarden:
CSP: https://icons.bitwarden.net/
duckduckgo:
CSP: https://icons.duckduckgo.com/ip3/
google:
CSP: https://www.google.com/s2/favicons https://*.gstatic.com/favicon
Conditions:
IsDomainAndCertificateSet: !And
- !Not [!Equals [!Ref Domain, '']]
- !Not [!Equals [!Ref ACMCertificateArn, '']]
IsApiLogRetentionNeverExpire: !Equals
- !Ref APILogRetention
- -1
IconSourceIsPredefined: !Or
- !Equals [!Ref IconService, internal]
- !Equals [!Ref IconService, bitwarden]
- !Equals [!Ref IconService, duckduckgo]
- !Equals [!Ref IconService, google]
IsAdminTokenEmpty: !Equals
- !Ref AdminToken
- ''
IsEmailEnabled: !Not
- !Equals
- !Ref SMTPFrom
- ''
EnableBackups: !Not
- !Equals
- !Ref DataBackupRetention
- -1
EnableBackupLifecycle: !And
- !Condition EnableBackups
- !Not
- !Equals
- !Ref DataBackupRetention
- 0
Resources:
DataBucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- BucketKeyEnabled: true
ServerSideEncryptionByDefault:
SSEAlgorithm: aws:kms
BucketName: !Sub ${AWS::StackName}-${AWS::AccountId}-${AWS::Region}-data
CorsConfiguration:
CorsRules:
- AllowedMethods:
- GET
- HEAD
AllowedOrigins:
- '*'
LifecycleConfiguration:
Rules:
- AbortIncompleteMultipartUpload:
DaysAfterInitiation: 2
ExpiredObjectDeleteMarker: true
NoncurrentVersionExpiration:
NoncurrentDays: 30
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
VersioningConfiguration:
Status: Enabled
DataBucketEnforceEncryptionAndStorageTier:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref DataBucket
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: DenyUnencryptedObjectUploads
Effect: Deny
Principal: '*'
Action: s3:PutObject
Resource: !Sub arn:${AWS::Partition}:s3:::${DataBucket}/*
Condition:
'Null':
s3:x-amz-server-side-encryption-aws-kms-key-id: true
- Sid: DenyUnencryptedTransit
Effect: Deny
Principal: '*'
Action: s3:*
Resource:
- !Sub arn:${AWS::Partition}:s3:::${DataBucket}
- !Sub arn:${AWS::Partition}:s3:::${DataBucket}/*
Condition:
Bool:
aws:SecureTransport: false
- Sid: DenyNonIntelligentTieringStorageClass
Effect: Deny
Principal: '*'
Action: s3:PutObject
Resource: !Sub arn:aws:s3:::${DataBucket}/*
Condition:
StringNotEquals:
s3:x-amz-storage-class: INTELLIGENT_TIERING
Database:
Type: AWS::DSQL::Cluster
Properties:
DeletionProtectionEnabled: true
Tags:
- Key: Name
Value: !Ref AWS::StackName
DataBackupRole:
Type: AWS::IAM::Role
Condition: EnableBackups
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: backup.amazonaws.com
Policies:
- PolicyName: BackupData
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- backup:CopyIntoBackupVault
- backup:DescribeBackupVault
Resource: !Sub arn:${AWS::Partition}:backup:${AWS::Region}:${AWS::AccountId}:backup-vault:Default
- Effect: Allow
Action:
- dsql:GetCluster
- dsql:ListTagsForResource
- dsql:StartBackupJob
- dsql:StopBackupJob
Resource: !GetAtt Database.ResourceArn
- Effect: Allow
Action: dsql:GetBackupJob
Resource: !Sub arn:${AWS::Partition}:dsql:${AWS::Region}:${AWS::AccountId}:cluster/*
- Effect: Allow
Action:
- kms:Decrypt
Resource: '*'
Condition:
StringEquals:
kms:ViaService: !Sub dsql.${AWS::Region}.amazonaws.com
ForAnyValue:StringEquals:
kms:EncryptionContextKeys: aws:dsql:ClusterId
- Effect: Allow
Action:
- s3:ListBucket
- s3:GetBucketTagging
- s3:GetInventoryConfiguration
- s3:ListBucketVersions
- s3:ListBucket
- s3:GetBucketVersioning
- s3:GetBucketLocation
- s3:GetBucketAcl
- s3:PutInventoryConfiguration
- s3:GetBucketNotification
- s3:PutBucketNotification
Resource: !Sub arn:${AWS::Partition}:s3:::${DataBucket}
- Effect: Allow
Action:
- s3:GetObjectAcl
- s3:GetObject
- s3:GetObjectVersionTagging
- s3:GetObjectVersionAcl
- s3:GetObjectTagging
- s3:GetObjectVersion
Resource: !Sub arn:${AWS::Partition}:s3:::${DataBucket}/*
- Effect: Allow
Action:
- kms:Decrypt
- kms:DescribeKey
Resource: '*'
Condition:
StringEquals:
kms:ViaService: !Sub s3.${AWS::Region}.amazonaws.com
- Effect: Allow
Action:
- events:DeleteRule
- events:PutTargets
- events:DescribeRule
- events:EnableRule
- events:PutRule
- events:RemoveTargets
- events:ListTargetsByRule
- events:DisableRule
Resource: !Sub arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:rule/AwsBackupManagedRule*
- Effect: Allow
Action: events:ListRules
Resource: '*'
- Effect: Allow
Action: cloudwatch:GetMetricData
Resource: '*'
DataBackupPlan:
Type: AWS::Backup::BackupPlan
Condition: EnableBackups
Properties:
BackupPlan:
BackupPlanName: !Ref AWS::StackName
BackupPlanRule:
- RuleName: DailyBackup
Lifecycle: !If
- EnableBackupLifecycle
- DeleteAfterDays: !Ref DataBackupRetention
- !Ref AWS::NoValue
TargetBackupVault: Default
DataBackupSelection:
Type: AWS::Backup::BackupSelection
Condition: EnableBackups
Properties:
BackupPlanId: !Ref DataBackupPlan
BackupSelection:
SelectionName: !Ref AWS::StackName
IamRoleArn: !GetAtt DataBackupRole.Arn
Resources:
- !Sub arn:${AWS::Partition}:s3:::${DataBucket}
- !GetAtt Database.ResourceArn
ApiFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: AccessAWSServices
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:AbortMultipartUpload
- s3:GetObject
- s3:ListBucket
- s3:PutObject
- s3:DeleteObject
Resource:
- !Sub arn:${AWS::Partition}:s3:::${DataBucket}
- !Sub arn:${AWS::Partition}:s3:::${DataBucket}/*
- Effect: Allow
Action: dsql:DbConnectAdmin
Resource: !GetAtt Database.ResourceArn
- !If
- IsEmailEnabled
- Effect: Allow
Action:
- ses:SendEmail
- ses:SendRawEmail
Resource: '*'
Condition:
StringEquals:
ses:FromAddress: !Ref SMTPFrom
ses:FromDisplayName: !Ref SMTPFromName
- !Ref AWS::NoValue
ApiFunction:
Type: AWS::Lambda::Function
Properties:
Architectures:
- arm64
Code: ./vaultwarden-lambda.zip
Environment:
Variables:
AWS_LWA_PORT: 8000
AWS_LWA_READINESS_CHECK_PATH: /alive
AWS_LWA_ASYNC_INIT: true
AWS_LWA_ENABLE_COMPRESSION: true
AWS_LWA_INVOKE_MODE: RESPONSE_STREAM
DATA_FOLDER: !Sub s3://${DataBucket}
TMP_FOLDER: /tmp
DATABASE_URL: !Sub dsql://${Database.Endpoint}
ENABLE_WEBSOCKET: false
DOMAIN: !If
- IsDomainAndCertificateSet
- !Ref Domain
- !Ref AWS::NoValue
SIGNUPS_ALLOWED: !Ref SignupsAllowed
IP_HEADER: X-Forwarded-For
ICON_SERVICE: !Ref IconService
ICON_REDIRECT_CODE: 301
ADMIN_TOKEN: !If
- IsAdminTokenEmpty
- !Ref AWS::NoValue
- !Ref AdminToken
SMTP_FROM: !If
- IsEmailEnabled
- !Ref SMTPFrom
- !Ref AWS::NoValue
SMTP_FROM_NAME: !Ref SMTPFromName
USE_AWS_SES: !If
- IsEmailEnabled
- 'true'
- 'false'
FunctionName: !Sub ${AWS::StackName}-api
Handler: bootstrap
Layers:
- !Sub arn:aws:lambda:${AWS::Region}:753240598075:layer:LambdaAdapterLayerArm64:24
MemorySize: 3008 # Maximum value allowed for new accounts, higher value reduces cold start times, should still fit under free tier usage for personal use
Role: !GetAtt ApiFunctionRole.Arn
Runtime: provided.al2023
Timeout: 300
ApiFunctionLogs:
Type: AWS::Logs::LogGroup
DeletionPolicy: RetainExceptOnCreate
Properties:
LogGroupName: !Sub /aws/lambda/${ApiFunction}
RetentionInDays: !If
- IsApiLogRetentionNeverExpire
- !Ref AWS::NoValue
- !Ref APILogRetention
ApiFunctionUrl:
Type: AWS::Lambda::Url
Properties:
TargetFunctionArn: !Ref ApiFunction
AuthType: NONE
InvokeMode: RESPONSE_STREAM
ApiFunctionUrlPublicPermissions:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunctionUrl
FunctionName: !Ref ApiFunction
Principal: '*'
FunctionUrlAuthType: NONE
WebVaultAssetsBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub ${AWS::StackName}-${AWS::AccountId}-${AWS::Region}-web-vault
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
WebVaultAssetsBucketPolicies:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref WebVaultAssetsBucket
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: DenyUnencryptedTransit
Effect: Deny
Principal: '*'
Action: s3:*
Resource:
- !Sub arn:${AWS::Partition}:s3:::${WebVaultAssetsBucket}
- !Sub arn:${AWS::Partition}:s3:::${WebVaultAssetsBucket}/*
Condition:
Bool:
aws:SecureTransport: false
- Sid: AllowCloudFrontOriginAccessControlRead
Effect: Allow
Principal:
Service: !Sub cloudfront.${AWS::URLSuffix}
Action: s3:GetObject
Resource: !Sub ${WebVaultAssetsBucket.Arn}/*
Condition:
StringEquals:
AWS:SourceArn: !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${CDN.Id}
WebVaultAssetsBucketOriginAccessControl:
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: !Sub ${AWS::StackName}-${AWS::Region}-web-vault-access-control
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4
# The following mirrors the header values in util.rs
ResponseHeaderPolicy:
Type: AWS::CloudFront::ResponseHeadersPolicy
Properties:
ResponseHeadersPolicyConfig:
Name: !Sub ${AWS::StackName}-${AWS::Region}
CustomHeadersConfig:
Items:
- Header: Cache-Control
Override: false
Value: no-cache, no-store, max-age=0
- Header: X-Robots-Tag
Override: true
Value: noindex, nofollow
- Header: Permissions-Policy
Override: true
Value: accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()
SecurityHeadersConfig:
ContentSecurityPolicy:
ContentSecurityPolicy: !Sub
- >-
default-src 'none';
font-src 'self';
manifest-src 'self';
base-uri 'self';
form-action 'self';
media-src 'self';
object-src 'self' blob:;
script-src 'self' 'wasm-unsafe-eval';
style-src 'self' 'unsafe-inline';
child-src 'self' https://*.duosecurity.com https://*.duofederal.com;
frame-src 'self' https://*.duosecurity.com https://*.duofederal.com;
frame-ancestors 'self'
chrome-extension://nngceckbapebfimnlniiiahkandclblb
chrome-extension://jbkfoedolllekgbhcbcoahefnbanhhlh
moz-extension://*;
img-src 'self' data:
https://haveibeenpwned.com
${IconServiceCSP};
connect-src 'self'
https://api.pwnedpasswords.com
https://api.2fa.directory
https://app.simplelogin.io/api/
https://app.addy.io/api/
https://api.fastmail.com/
https://api.forwardemail.net
https://${DataBucket.RegionalDomainName};
- IconServiceCSP: !If
- IconSourceIsPredefined
- !FindInMap [IconSource, !Ref IconService, CSP]
- !Select
- 0
- !Split ['{', !Ref IconService]
Override: true
ContentTypeOptions:
Override: true
FrameOptions:
FrameOption: SAMEORIGIN
Override: true
ReferrerPolicy:
Override: true
ReferrerPolicy: same-origin
StrictTransportSecurity:
AccessControlMaxAgeSec: 63072000
IncludeSubdomains: true
Override: true
Preload: true
XSSProtection:
Override: true
Protection: false
# The following mirrors the header values in util.rs
ConnectorHtmlResponseHeaderPolicy:
Type: AWS::CloudFront::ResponseHeadersPolicy
Properties:
ResponseHeadersPolicyConfig:
Name: !Sub ${AWS::StackName}-${AWS::Region}-connector-html
CustomHeadersConfig:
Items:
- Header: Cache-Control
Override: true
Value: no-cache, no-store, max-age=0
- Header: X-Robots-Tag
Override: true
Value: noindex, nofollow
- Header: Permissions-Policy
Override: true
Value: accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()
SecurityHeadersConfig:
ContentTypeOptions:
Override: true
ReferrerPolicy:
Override: true
ReferrerPolicy: same-origin
StrictTransportSecurity:
AccessControlMaxAgeSec: 63072000
IncludeSubdomains: true
Override: true
Preload: true
XSSProtection:
Override: true
Protection: false
CDN:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Aliases: !If
- IsDomainAndCertificateSet
- - !Select
- 2
- !Split
- /
- !Ref Domain
- !Ref AWS::NoValue
CacheBehaviors:
- AllowedMethods:
- DELETE
- HEAD
- GET
- OPTIONS
- PATCH
- POST
- PUT
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /api/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- AllowedMethods:
- DELETE
- HEAD
- GET
- OPTIONS
- PATCH
- POST
- PUT
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /admin
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- AllowedMethods:
- DELETE
- HEAD
- GET
- OPTIONS
- PATCH
- POST
- PUT
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /admin/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- AllowedMethods:
- DELETE
- HEAD
- GET
- OPTIONS
- PATCH
- POST
- PUT
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /events/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- AllowedMethods:
- DELETE
- HEAD
- GET
- OPTIONS
- PATCH
- POST
- PUT
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /identity/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /css/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /vw_static/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # CachingOptimized
Compress: true
OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac # AllViewerExceptHostHeader
PathPattern: /icons/*
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: Api
ViewerProtocolPolicy: redirect-to-https
- CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
PathPattern: '*.html'
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: WebVaultAssetsBucket
ViewerProtocolPolicy: redirect-to-https
- CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # CachingDisabled
Compress: true
PathPattern: '*connector.html'
ResponseHeadersPolicyId: !Ref ConnectorHtmlResponseHeaderPolicy
TargetOriginId: WebVaultAssetsBucket
ViewerProtocolPolicy: redirect-to-https
Comment: Vaultwarden CDN
CustomErrorResponses:
- ErrorCode: 403
ResponseCode: 200
ResponsePagePath: /404.html
DefaultCacheBehavior:
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # CachingOptimized
Compress: true
ResponseHeadersPolicyId: !Ref ResponseHeaderPolicy
TargetOriginId: WebVaultAssetsBucket
ViewerProtocolPolicy: redirect-to-https
DefaultRootObject: index.html
Enabled: true
HttpVersion: http2and3
IPV6Enabled: true
Origins:
- Id: WebVaultAssetsBucket
DomainName: !GetAtt WebVaultAssetsBucket.RegionalDomainName
OriginAccessControlId: !GetAtt WebVaultAssetsBucketOriginAccessControl.Id
S3OriginConfig:
OriginAccessIdentity: ''
- Id: Api
CustomOriginConfig:
OriginProtocolPolicy: https-only
OriginSSLProtocols:
- TLSv1.2
DomainName: !Select
- 2
- !Split
- /
- !GetAtt ApiFunctionUrl.FunctionUrl
PriceClass: PriceClass_All
ViewerCertificate: !If
- IsDomainAndCertificateSet
- AcmCertificateArn: !Ref ACMCertificateArn
MinimumProtocolVersion: TLSv1.3_2025
SslSupportMethod: sni-only
- !Ref AWS::NoValue
Tags:
- Key: Name
Value: !Ref AWS::StackName
Outputs:
WebVaultAssetsBucket:
Value: !Ref WebVaultAssetsBucket
CDNDomain:
Value: !GetAtt CDN.DomainName

11
build.rs

@ -8,20 +8,29 @@ fn main() {
println!("cargo:rustc-cfg=mysql"); println!("cargo:rustc-cfg=mysql");
#[cfg(feature = "postgresql")] #[cfg(feature = "postgresql")]
println!("cargo:rustc-cfg=postgresql"); println!("cargo:rustc-cfg=postgresql");
#[cfg(not(any(feature = "sqlite_system", feature = "mysql", feature = "postgresql")))] #[cfg(feature = "dsql")]
println!("cargo:rustc-cfg=dsql");
#[cfg(not(any(feature = "sqlite_system", feature = "mysql", feature = "postgresql", feature = "dsql")))]
compile_error!( compile_error!(
"You need to enable one DB backend. To build with previous defaults do: cargo build --features sqlite" "You need to enable one DB backend. To build with previous defaults do: cargo build --features sqlite"
); );
#[cfg(feature = "s3")] #[cfg(feature = "s3")]
println!("cargo:rustc-cfg=s3"); println!("cargo:rustc-cfg=s3");
#[cfg(feature = "ses")]
println!("cargo:rustc-cfg=ses");
#[cfg(feature = "aws")]
println!("cargo:rustc-cfg=aws");
// Use check-cfg to let cargo know which cfg's we define, // Use check-cfg to let cargo know which cfg's we define,
// and avoid warnings when they are used in the code. // and avoid warnings when they are used in the code.
println!("cargo::rustc-check-cfg=cfg(sqlite)"); println!("cargo::rustc-check-cfg=cfg(sqlite)");
println!("cargo::rustc-check-cfg=cfg(mysql)"); println!("cargo::rustc-check-cfg=cfg(mysql)");
println!("cargo::rustc-check-cfg=cfg(postgresql)"); println!("cargo::rustc-check-cfg=cfg(postgresql)");
println!("cargo::rustc-check-cfg=cfg(dsql)");
println!("cargo::rustc-check-cfg=cfg(s3)"); println!("cargo::rustc-check-cfg=cfg(s3)");
println!("cargo::rustc-check-cfg=cfg(ses)");
println!("cargo::rustc-check-cfg=cfg(aws)");
// Rerun when these paths are changed. // Rerun when these paths are changed.
// Someone could have checked-out a tag or specific commit, but no other files changed. // Someone could have checked-out a tag or specific commit, but no other files changed.

1
migrations/dsql/2024-12-30-100000_create_tables/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

281
migrations/dsql/2024-12-30-100000_create_tables/up.sql

@ -0,0 +1,281 @@
CREATE TABLE attachments (
id text NOT NULL PRIMARY KEY,
cipher_uuid character varying(40) NOT NULL,
file_name text NOT NULL,
file_size bigint NOT NULL,
akey text
);
CREATE TABLE auth_requests (
uuid character(36) NOT NULL PRIMARY KEY,
user_uuid character(36) NOT NULL,
organization_uuid character(36),
request_device_identifier character(36) NOT NULL,
device_type integer NOT NULL,
request_ip text NOT NULL,
response_device_id character(36),
access_code text NOT NULL,
public_key text NOT NULL,
enc_key text,
master_password_hash text,
approved boolean,
creation_date timestamp without time zone NOT NULL,
response_date timestamp without time zone,
authentication_date timestamp without time zone
);
CREATE TABLE ciphers (
uuid character varying(40) NOT NULL PRIMARY KEY,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
user_uuid character varying(40),
organization_uuid character varying(40),
atype integer NOT NULL,
name text NOT NULL,
notes text,
fields text,
data text NOT NULL,
password_history text,
deleted_at timestamp without time zone,
reprompt integer,
key text
);
CREATE TABLE ciphers_collections (
cipher_uuid character varying(40) NOT NULL,
collection_uuid character varying(40) NOT NULL,
PRIMARY KEY (cipher_uuid, collection_uuid)
);
CREATE TABLE collections (
uuid character varying(40) NOT NULL PRIMARY KEY,
org_uuid character varying(40) NOT NULL,
name text NOT NULL,
external_id text
);
CREATE TABLE collections_groups (
collections_uuid character varying(40) NOT NULL,
groups_uuid character(36) NOT NULL,
read_only boolean NOT NULL,
hide_passwords boolean NOT NULL,
PRIMARY KEY (collections_uuid, groups_uuid)
);
CREATE TABLE devices (
uuid character varying(40) NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
user_uuid character varying(40) NOT NULL,
name text NOT NULL,
atype integer NOT NULL,
push_token text,
refresh_token text NOT NULL,
twofactor_remember text,
push_uuid text,
PRIMARY KEY (uuid, user_uuid)
);
CREATE TABLE emergency_access (
uuid character(36) NOT NULL PRIMARY KEY,
grantor_uuid character(36),
grantee_uuid character(36),
email character varying(255),
key_encrypted text,
atype integer NOT NULL,
status integer NOT NULL,
wait_time_days integer NOT NULL,
recovery_initiated_at timestamp without time zone,
last_notification_at timestamp without time zone,
updated_at timestamp without time zone NOT NULL,
created_at timestamp without time zone NOT NULL
);
CREATE TABLE event (
uuid character(36) NOT NULL PRIMARY KEY,
event_type integer NOT NULL,
user_uuid character(36),
org_uuid character(36),
cipher_uuid character(36),
collection_uuid character(36),
group_uuid character(36),
org_user_uuid character(36),
act_user_uuid character(36),
device_type integer,
ip_address text,
event_date timestamp without time zone NOT NULL,
policy_uuid character(36),
provider_uuid character(36),
provider_user_uuid character(36),
provider_org_uuid character(36)
);
CREATE TABLE favorites (
user_uuid character varying(40) NOT NULL,
cipher_uuid character varying(40) NOT NULL,
PRIMARY KEY (user_uuid, cipher_uuid)
);
CREATE TABLE folders (
uuid character varying(40) NOT NULL PRIMARY KEY,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
user_uuid character varying(40) NOT NULL,
name text NOT NULL
);
CREATE TABLE folders_ciphers (
cipher_uuid character varying(40) NOT NULL,
folder_uuid character varying(40) NOT NULL,
PRIMARY KEY (cipher_uuid, folder_uuid)
);
CREATE TABLE groups (
uuid character(36) NOT NULL PRIMARY KEY,
organizations_uuid character varying(40) NOT NULL,
name character varying(100) NOT NULL,
access_all boolean NOT NULL,
external_id character varying(300),
creation_date timestamp without time zone NOT NULL,
revision_date timestamp without time zone NOT NULL
);
CREATE TABLE groups_users (
groups_uuid character(36) NOT NULL,
users_organizations_uuid character varying(36) NOT NULL,
PRIMARY KEY (groups_uuid, users_organizations_uuid)
);
CREATE TABLE invitations (
email text NOT NULL PRIMARY KEY
);
CREATE TABLE org_policies (
uuid character(36) NOT NULL PRIMARY KEY,
org_uuid character(36) NOT NULL,
atype integer NOT NULL,
enabled boolean NOT NULL,
data text NOT NULL,
UNIQUE (org_uuid, atype)
);
CREATE TABLE organization_api_key (
uuid character(36) NOT NULL,
org_uuid character(36) NOT NULL,
atype integer NOT NULL,
api_key character varying(255),
revision_date timestamp without time zone NOT NULL,
PRIMARY KEY (uuid, org_uuid)
);
CREATE TABLE organizations (
uuid character varying(40) NOT NULL PRIMARY KEY,
name text NOT NULL,
billing_email text NOT NULL,
private_key text,
public_key text
);
CREATE TABLE sends (
uuid character(36) NOT NULL PRIMARY KEY,
user_uuid character(36),
organization_uuid character(36),
name text NOT NULL,
notes text,
atype integer NOT NULL,
data text NOT NULL,
akey text NOT NULL,
password_hash bytea,
password_salt bytea,
password_iter integer,
max_access_count integer,
access_count integer NOT NULL,
creation_date timestamp without time zone NOT NULL,
revision_date timestamp without time zone NOT NULL,
expiration_date timestamp without time zone,
deletion_date timestamp without time zone NOT NULL,
disabled boolean NOT NULL,
hide_email boolean
);
CREATE TABLE twofactor (
uuid character varying(40) NOT NULL PRIMARY KEY,
user_uuid character varying(40) NOT NULL,
atype integer NOT NULL,
enabled boolean NOT NULL,
data text NOT NULL,
last_used bigint DEFAULT 0 NOT NULL,
UNIQUE (user_uuid, atype)
);
CREATE TABLE twofactor_duo_ctx (
state character varying(64) NOT NULL PRIMARY KEY,
user_email character varying(255) NOT NULL,
nonce character varying(64) NOT NULL,
exp bigint NOT NULL
);
CREATE TABLE twofactor_incomplete (
user_uuid character varying(40) NOT NULL,
device_uuid character varying(40) NOT NULL,
device_name text NOT NULL,
login_time timestamp without time zone NOT NULL,
ip_address text NOT NULL,
device_type integer DEFAULT 14 NOT NULL,
PRIMARY KEY (user_uuid, device_uuid)
);
CREATE TABLE users (
uuid character varying(40) NOT NULL PRIMARY KEY,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
email text NOT NULL UNIQUE,
name text NOT NULL,
password_hash bytea NOT NULL,
salt bytea NOT NULL,
password_iterations integer NOT NULL,
password_hint text,
akey text NOT NULL,
private_key text,
public_key text,
totp_secret text,
totp_recover text,
security_stamp text NOT NULL,
equivalent_domains text NOT NULL,
excluded_globals text NOT NULL,
client_kdf_type integer DEFAULT 0 NOT NULL,
client_kdf_iter integer DEFAULT 100000 NOT NULL,
verified_at timestamp without time zone,
last_verifying_at timestamp without time zone,
login_verify_count integer DEFAULT 0 NOT NULL,
email_new character varying(255) DEFAULT NULL::character varying,
email_new_token character varying(16) DEFAULT NULL::character varying,
enabled boolean DEFAULT true NOT NULL,
stamp_exception text,
api_key text,
avatar_color text,
client_kdf_memory integer,
client_kdf_parallelism integer,
external_id text
);
CREATE TABLE users_collections (
user_uuid character varying(40) NOT NULL,
collection_uuid character varying(40) NOT NULL,
read_only boolean DEFAULT false NOT NULL,
hide_passwords boolean DEFAULT false NOT NULL,
PRIMARY KEY (user_uuid, collection_uuid)
);
CREATE TABLE users_organizations (
uuid character varying(40) NOT NULL PRIMARY KEY,
user_uuid character varying(40) NOT NULL,
org_uuid character varying(40) NOT NULL,
access_all boolean NOT NULL,
akey text NOT NULL,
status integer NOT NULL,
atype integer NOT NULL,
reset_password_key text,
external_id text,
UNIQUE (user_uuid, org_uuid)
);

0
migrations/dsql/2025-01-09-172300_add_manage/down.sql

1
migrations/dsql/2025-01-09-172300_add_manage/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

8
migrations/dsql/2025-01-09-172300_add_manage/up.sql

@ -0,0 +1,8 @@
-- DSQL preview can't add columns with constraints, dropping `NOT NULL DEFAULT FALSE` constraint
-- It appears Diesel will ensure the column has appropriate values when saving records.
ALTER TABLE users_collections
ADD COLUMN manage BOOLEAN;
ALTER TABLE collections_groups
ADD COLUMN manage BOOLEAN;

1
migrations/dsql/2025-08-20-120000_add_users_organizations_invited_by_email/down.sql

@ -0,0 +1 @@

1
migrations/dsql/2025-08-20-120000_add_users_organizations_invited_by_email/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

2
migrations/dsql/2025-08-20-120000_add_users_organizations_invited_by_email/up.sql

@ -0,0 +1,2 @@
ALTER TABLE users_organizations
ADD COLUMN invited_by_email TEXT;

1
migrations/dsql/2025-08-20-120100_add_sso_users/down.sql

@ -0,0 +1 @@

1
migrations/dsql/2025-08-20-120100_add_sso_users/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

4
migrations/dsql/2025-08-20-120100_add_sso_users/up.sql

@ -0,0 +1,4 @@
CREATE TABLE sso_users (
user_uuid character(36) NOT NULL PRIMARY KEY,
identifier text NOT NULL UNIQUE
);

1
migrations/dsql/2025-08-20-120200_add_sso_auth/down.sql

@ -0,0 +1 @@

1
migrations/dsql/2025-08-20-120200_add_sso_auth/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

10
migrations/dsql/2025-08-20-120200_add_sso_auth/up.sql

@ -0,0 +1,10 @@
CREATE TABLE sso_auth (
state text NOT NULL PRIMARY KEY,
client_challenge text NOT NULL,
nonce text NOT NULL,
redirect_uri text NOT NULL,
code_response text,
auth_response text,
created_at timestamp without time zone NOT NULL DEFAULT now(),
updated_at timestamp without time zone NOT NULL DEFAULT now()
);

1
migrations/dsql/2026-03-09-005927_add_archives/down.sql

@ -0,0 +1 @@

1
migrations/dsql/2026-03-09-005927_add_archives/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

6
migrations/dsql/2026-03-09-005927_add_archives/up.sql

@ -0,0 +1,6 @@
CREATE TABLE archives (
user_uuid character(36) NOT NULL,
cipher_uuid character(36) NOT NULL,
archived_at timestamp without time zone NOT NULL DEFAULT now(),
PRIMARY KEY (user_uuid, cipher_uuid)
);

1
migrations/dsql/2026-04-25-120000_sso_auth_binding/down.sql

@ -0,0 +1 @@

1
migrations/dsql/2026-04-25-120000_sso_auth_binding/metadata.toml

@ -0,0 +1 @@
run_in_transaction = false

2
migrations/dsql/2026-04-25-120000_sso_auth_binding/up.sql

@ -0,0 +1,2 @@
ALTER TABLE sso_auth
ADD COLUMN binding_hash TEXT;

2
src/api/admin.rs

@ -83,6 +83,8 @@ pub fn catchers() -> Vec<Catcher> {
} }
static DB_TYPE: LazyLock<&str> = LazyLock::new(|| match ACTIVE_DB_TYPE.get() { static DB_TYPE: LazyLock<&str> = LazyLock::new(|| match ACTIVE_DB_TYPE.get() {
#[cfg(dsql)]
Some(DbConnType::Dsql) => "Aurora DSQL",
#[cfg(mysql)] #[cfg(mysql)]
Some(DbConnType::Mysql) => "MySQL", Some(DbConnType::Mysql) => "MySQL",
#[cfg(postgresql)] #[cfg(postgresql)]

39
src/aws.rs

@ -0,0 +1,39 @@
#[cfg(dsql)]
use std::io::Error;
use aws_config::{AppName, BehaviorVersion};
use tokio::sync::OnceCell;
use crate::http_client::aws::AwsReqwestConnector;
fn aws_reqwest_connector() -> AwsReqwestConnector {
let reqwest_client = reqwest::Client::builder().build().expect("Failed to build reqwest client");
AwsReqwestConnector {
client: reqwest_client,
}
}
pub(crate) async fn aws_sdk_config() -> &'static aws_config::SdkConfig {
static AWS_CONFIG: OnceCell<aws_config::SdkConfig> = OnceCell::const_new();
AWS_CONFIG
.get_or_init(async || {
aws_config::defaults(BehaviorVersion::latest())
.app_name(AppName::new("vaultwarden").expect("Failed to build AWS app name"))
.http_client(aws_reqwest_connector())
.load()
.await
})
.await
}
#[cfg(dsql)]
pub(crate) fn aws_sdk_config_blocking() -> std::io::Result<&'static aws_config::SdkConfig> {
std::thread::spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
std::io::Result::Ok(rt.block_on(aws_sdk_config()))
})
.join()
.map_err(|e| Error::other(format!("Failed to load AWS SDK config: {e:?}")))?
}

13
src/config.rs

@ -901,12 +901,14 @@ make_config! {
smtp_accept_invalid_certs: bool, true, def, false; smtp_accept_invalid_certs: bool, true, def, false;
/// Accept Invalid Hostnames (Know the risks!) |> DANGEROUS: Allow invalid hostnames. This option introduces significant vulnerabilities to man-in-the-middle attacks! /// Accept Invalid Hostnames (Know the risks!) |> DANGEROUS: Allow invalid hostnames. This option introduces significant vulnerabilities to man-in-the-middle attacks!
smtp_accept_invalid_hostnames: bool, true, def, false; smtp_accept_invalid_hostnames: bool, true, def, false;
/// Use AWS SES |> Whether to send mail via AWS Simple Email Service (SES)
use_aws_ses: bool, true, def, false;
}, },
/// Email 2FA Settings /// Email 2FA Settings
email_2fa: _enable_email_2fa { email_2fa: _enable_email_2fa {
/// Enabled |> Disabling will prevent users from setting up new email 2FA and using existing email 2FA configured /// Enabled |> Disabling will prevent users from setting up new email 2FA and using existing email 2FA configured
_enable_email_2fa: bool, true, auto, |c| c._enable_smtp && (c.smtp_host.is_some() || c.use_sendmail); _enable_email_2fa: bool, true, auto, |c| c._enable_smtp && (c.smtp_host.is_some() || c.use_sendmail || c.use_aws_ses);
/// Email token size |> Number of digits in an email 2FA token (min: 6, max: 255). Note that the Bitwarden clients are hardcoded to mention 6 digit codes regardless of this setting. /// Email token size |> Number of digits in an email 2FA token (min: 6, max: 255). Note that the Bitwarden clients are hardcoded to mention 6 digit codes regardless of this setting.
email_token_size: u8, true, def, 6; email_token_size: u8, true, def, 6;
/// Token expiration time |> Maximum time in seconds a token is valid. The time the user has to open email client and copy token. /// Token expiration time |> Maximum time in seconds a token is valid. The time the user has to open email client and copy token.
@ -1142,6 +1144,9 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
} }
} }
} }
} else if cfg.use_aws_ses {
#[cfg(not(ses))]
err!("`USE_AWS_SES` is set, but the `ses` feature is not enabled in this build");
} else { } else {
if cfg.smtp_host.is_some() == cfg.smtp_from.is_empty() { if cfg.smtp_host.is_some() == cfg.smtp_from.is_empty() {
err!("Both `SMTP_HOST` and `SMTP_FROM` need to be set for email support without `USE_SENDMAIL`") err!("Both `SMTP_HOST` and `SMTP_FROM` need to be set for email support without `USE_SENDMAIL`")
@ -1154,7 +1159,7 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
} }
} }
if (cfg.smtp_host.is_some() || cfg.use_sendmail) && !is_valid_email(&cfg.smtp_from) { if (cfg.smtp_host.is_some() || cfg.use_sendmail || cfg.use_aws_ses) && !is_valid_email(&cfg.smtp_from) {
err!(format!("SMTP_FROM '{}' is not a valid email address", cfg.smtp_from)) err!(format!("SMTP_FROM '{}' is not a valid email address", cfg.smtp_from))
} }
@ -1163,7 +1168,7 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
} }
} }
if cfg._enable_email_2fa && !(cfg.smtp_host.is_some() || cfg.use_sendmail) { if cfg._enable_email_2fa && !(cfg.smtp_host.is_some() || cfg.use_sendmail || cfg.use_aws_ses) {
err!("To enable email 2FA, a mail transport must be configured") err!("To enable email 2FA, a mail transport must be configured")
} }
@ -1567,7 +1572,7 @@ impl Config {
} }
pub fn mail_enabled(&self) -> bool { pub fn mail_enabled(&self) -> bool {
let inner = &self.inner.read().unwrap().config; let inner = &self.inner.read().unwrap().config;
inner._enable_smtp && (inner.smtp_host.is_some() || inner.use_sendmail) inner._enable_smtp && (inner.smtp_host.is_some() || inner.use_sendmail || inner.use_aws_ses)
} }
pub async fn get_duo_akey(&self) -> String { pub async fn get_duo_akey(&self) -> String {

110
src/db/dsql.rs

@ -0,0 +1,110 @@
use std::{
collections::HashMap,
sync::{Arc, LazyLock, Mutex},
time::Duration,
};
use diesel::ConnectionError;
use url::Url;
// Generate a Postgres libpq connection string. The input connection string has
// the following format:
//
// dsql://<dsql-id>.dsql.<aws-region>.on.aws
//
// The generated connection string has the form:
//
// postgresql://<dsql-id>.dsql.<aws-region>.on.aws/postgres?sslmode=require&user=admin&password=<auth-token>
//
// The auth token is generated by the AWS SDK for DSQL and is valid for up to
// 15 minutes. Cache each unique DSQL URL for 14 minutes to avoid regenerating
// a token for every pooled connection.
pub(crate) fn psql_url(url: &str) -> Result<String, ConnectionError> {
struct PsqlUrl {
timestamp: std::time::Instant,
url: String,
}
static PSQL_URLS: LazyLock<Mutex<HashMap<String, Arc<Mutex<Option<PsqlUrl>>>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
let mut psql_urls =
PSQL_URLS.lock().map_err(|e| ConnectionError::BadConnection(format!("Failed to lock DSQL URLs: {e}")))?;
let psql_url_lock = if let Some(existing_psql_url_lock) = psql_urls.get(url) {
existing_psql_url_lock.clone()
} else {
let psql_url_lock = Arc::new(Mutex::new(None));
psql_urls.insert(url.to_string(), psql_url_lock.clone());
psql_url_lock
};
let mut psql_url_lock_guard =
psql_url_lock.lock().map_err(|e| ConnectionError::BadConnection(format!("Failed to lock DSQL URL: {e}")))?;
drop(psql_urls);
if let Some(ref psql_url) = *psql_url_lock_guard {
if psql_url.timestamp.elapsed() < Duration::from_secs(14 * 60) {
debug!("Reusing DSQL auth token for connection '{url}'");
return Ok(psql_url.url.clone());
}
info!("Refreshing DSQL auth token for connection '{url}'");
} else {
info!("Generating new DSQL auth token for connection '{url}'");
}
let mut psql_url = Url::parse(url).map_err(|e| ConnectionError::InvalidConnectionUrl(e.to_string()))?;
let host = psql_url
.host_str()
.ok_or_else(|| ConnectionError::InvalidConnectionUrl("Missing hostname in DSQL URL".to_string()))?
.to_string();
static DSQL_REGION_FROM_HOST_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(r"^[a-z0-9]+\.dsql\.(?P<region>[a-z0-9-]+)\.on\.aws$")
.expect("Failed to compile DSQL region regex")
});
let region = DSQL_REGION_FROM_HOST_RE
.captures(&host)
.and_then(|captures| captures.name("region"))
.ok_or_else(|| ConnectionError::InvalidConnectionUrl("Failed to find AWS region in DSQL hostname".to_string()))?
.as_str()
.to_string();
let auth_config = aws_sdk_dsql::auth_token::Config::builder()
.hostname(host)
.region(aws_config::Region::new(region))
.build()
.map_err(|e| ConnectionError::BadConnection(format!("Failed to build DSQL auth token signer config: {e}")))?;
let signer = aws_sdk_dsql::auth_token::AuthTokenGenerator::new(auth_config);
let sdk_config = crate::aws::aws_sdk_config_blocking()
.map_err(|e| ConnectionError::BadConnection(format!("Failed to load AWS SDK config: {e}")))?;
let now = std::time::Instant::now();
let auth_token = std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
rt.block_on(signer.db_connect_admin_auth_token(sdk_config))
})
.join()
.map_err(|e| ConnectionError::BadConnection(format!("Failed to generate DSQL auth token: {e:?}")))?
.map_err(|e| ConnectionError::BadConnection(format!("Failed to generate DSQL auth token: {e}")))?;
psql_url.set_scheme("postgresql").expect("Failed to set 'postgresql' as scheme for DSQL connection URL");
psql_url.set_path("postgres");
psql_url
.query_pairs_mut()
.append_pair("sslmode", "require")
.append_pair("user", "admin")
.append_pair("password", auth_token.as_str());
psql_url_lock_guard.replace(PsqlUrl {
timestamp: now,
url: psql_url.to_string(),
});
Ok(psql_url.to_string())
}

46
src/db/mod.rs

@ -1,3 +1,5 @@
#[cfg(dsql)]
mod dsql;
mod query_logger; mod query_logger;
use std::{ use std::{
@ -66,6 +68,12 @@ impl DbConnManager {
fn establish_connection(&self) -> Result<DbConnInner, diesel::r2d2::Error> { fn establish_connection(&self) -> Result<DbConnInner, diesel::r2d2::Error> {
match DbConnType::from_url(&self.database_url) { match DbConnType::from_url(&self.database_url) {
#[cfg(dsql)]
Ok(DbConnType::Dsql) => {
let db_url = dsql::psql_url(&self.database_url).map_err(diesel::r2d2::Error::ConnectionError)?;
let conn = diesel::pg::PgConnection::establish(&db_url)?;
Ok(DbConnInner::Postgresql(conn))
}
#[cfg(mysql)] #[cfg(mysql)]
Ok(DbConnType::Mysql) => { Ok(DbConnType::Mysql) => {
let conn = diesel::mysql::MysqlConnection::establish(&self.database_url)?; let conn = diesel::mysql::MysqlConnection::establish(&self.database_url)?;
@ -108,8 +116,10 @@ impl diesel::r2d2::ManageConnection for DbConnManager {
} }
} }
#[derive(Eq, PartialEq)] #[derive(Clone, Copy, Eq, PartialEq)]
pub enum DbConnType { pub enum DbConnType {
#[cfg(dsql)]
Dsql,
#[cfg(mysql)] #[cfg(mysql)]
Mysql, Mysql,
#[cfg(postgresql)] #[cfg(postgresql)]
@ -193,6 +203,10 @@ impl DbPool {
} }
match conn_type { match conn_type {
#[cfg(dsql)]
DbConnType::Dsql => {
dsql_migrations::run_migrations(&db_url)?;
}
#[cfg(mysql)] #[cfg(mysql)]
DbConnType::Mysql => { DbConnType::Mysql => {
mysql_migrations::run_migrations(&db_url)?; mysql_migrations::run_migrations(&db_url)?;
@ -270,6 +284,14 @@ impl DbConnType {
#[cfg(not(postgresql))] #[cfg(not(postgresql))]
err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled") err!("`DATABASE_URL` is a PostgreSQL URL, but the 'postgresql' feature is not enabled")
// Amazon Aurora DSQL
} else if url.len() > 5 && &url[..5] == "dsql:" {
#[cfg(dsql)]
return Ok(DbConnType::Dsql);
#[cfg(not(dsql))]
err!("`DATABASE_URL` is a DSQL URL, but the 'dsql' feature is not enabled")
// Sqlite (explicit) // Sqlite (explicit)
} else if url.len() > 7 && &url[..7] == "sqlite:" { } else if url.len() > 7 && &url[..7] == "sqlite:" {
#[cfg(sqlite)] #[cfg(sqlite)]
@ -298,7 +320,7 @@ impl DbConnType {
err!("`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://)") err!("`DATABASE_URL` does not match any known database scheme (mysql://, postgresql://, sqlite://)")
} }
pub fn get_init_stmts(&self) -> String { pub fn get_init_stmts(self) -> String {
let init_stmts = CONFIG.database_conn_init(); let init_stmts = CONFIG.database_conn_init();
if init_stmts.is_empty() { if init_stmts.is_empty() {
self.default_init_stmts() self.default_init_stmts()
@ -307,8 +329,10 @@ impl DbConnType {
} }
} }
pub fn default_init_stmts(&self) -> String { pub fn default_init_stmts(self) -> String {
match self { match self {
#[cfg(dsql)]
Self::Dsql => String::new(),
#[cfg(mysql)] #[cfg(mysql)]
Self::Mysql => String::new(), Self::Mysql => String::new(),
#[cfg(postgresql)] #[cfg(postgresql)]
@ -534,3 +558,19 @@ mod postgresql_migrations {
Ok(()) Ok(())
} }
} }
#[cfg(dsql)]
mod dsql_migrations {
use diesel::Connection;
use diesel_migrations::{EmbeddedMigrations, MigrationHarness};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/dsql");
pub fn run_migrations(db_url: &str) -> Result<(), super::Error> {
let db_url = super::dsql::psql_url(db_url)?;
let mut connection = diesel::pg::PgConnection::establish(&db_url)?;
connection.run_pending_migrations(MIGRATIONS).expect("Error running DSQL migrations");
Ok(())
}
}

2
src/http_client.rs

@ -296,7 +296,7 @@ impl Resolve for CustomDnsResolver {
} }
} }
#[cfg(s3)] #[cfg(any(dsql, s3, ses))]
pub(crate) mod aws { pub(crate) mod aws {
use aws_smithy_runtime_api::client::{ use aws_smithy_runtime_api::client::{
http::{HttpClient, HttpConnector, HttpConnectorFuture, HttpConnectorSettings, SharedHttpConnector}, http::{HttpClient, HttpConnector, HttpConnectorFuture, HttpConnectorSettings, SharedHttpConnector},

47
src/mail.rs

@ -96,6 +96,44 @@ fn smtp_transport() -> AsyncSmtpTransport<Tokio1Executor> {
smtp_client.build() smtp_client.build()
} }
#[cfg(ses)]
async fn send_with_aws_ses(email: Message) -> std::io::Result<()> {
use std::io::Error;
use aws_sdk_sesv2::{
Client,
types::{EmailContent, RawMessage},
};
use tokio::sync::OnceCell;
static AWS_SESV2_CLIENT: OnceCell<Client> = OnceCell::const_new();
let client = AWS_SESV2_CLIENT
.get_or_init(async || {
let config = crate::aws::aws_sdk_config().await;
Client::new(config)
})
.await;
client
.send_email()
.content(
EmailContent::builder()
.raw(
RawMessage::builder()
.data(email.formatted().into())
.build()
.map_err(|e| Error::other(format!("Failed to build AWS SESv2 RawMessage: {e:?}")))?,
)
.build(),
)
.send()
.await
.map_err(Error::other)?;
Ok(())
}
// This will sanitize the string values by stripping all the html tags to prevent XSS and HTML Injections // This will sanitize the string values by stripping all the html tags to prevent XSS and HTML Injections
fn sanitize_data(data: &mut serde_json::Value) { fn sanitize_data(data: &mut serde_json::Value) {
use regex::Regex; use regex::Regex;
@ -667,6 +705,15 @@ async fn send_with_selected_transport(email: Message) -> EmptyResult {
err!(format!("Sendmail error: {e}")); err!(format!("Sendmail error: {e}"));
} }
} }
} else if CONFIG.use_aws_ses() {
#[cfg(ses)]
match send_with_aws_ses(email).await {
Ok(_) => Ok(()),
Err(e) => err!("Failed to send email", format!("Failed to send email using AWS SES: {e:?}")),
}
#[cfg(not(ses))]
unreachable!("Failed to send email using AWS SES: `ses` feature is not enabled");
} else { } else {
match smtp_transport().send(email).await { match smtp_transport().send(email).await {
Ok(_) => Ok(()), Ok(_) => Ok(()),

2
src/main.rs

@ -51,6 +51,8 @@ use rocket::data::{Limits, ToByteUnit};
mod error; mod error;
mod api; mod api;
mod auth; mod auth;
#[cfg(any(dsql, s3, ses))]
mod aws;
mod config; mod config;
mod crypto; mod crypto;
#[macro_use] #[macro_use]

24
src/storage.rs

@ -152,8 +152,6 @@ mod s3 {
} }
pub(super) fn operator_for_path(path: &str) -> Result<opendal::Operator, Error> { pub(super) fn operator_for_path(path: &str) -> Result<opendal::Operator, Error> {
use crate::http_client::aws::AwsReqwestConnector;
use aws_config::{default_provider::credentials::DefaultCredentialsChain, provider_config::ProviderConfig};
use opendal::Configurator; use opendal::Configurator;
use reqsign_aws_v4::Credential; use reqsign_aws_v4::Credential;
use reqsign_core::{Context, ProvideCredential, ProvideCredentialChain}; use reqsign_core::{Context, ProvideCredential, ProvideCredentialChain};
@ -171,24 +169,12 @@ mod s3 {
async fn provide_credential(&self, _ctx: &Context) -> reqsign_core::Result<Option<Self::Credential>> { async fn provide_credential(&self, _ctx: &Context) -> reqsign_core::Result<Option<Self::Credential>> {
use aws_credential_types::provider::ProvideCredentials as _; use aws_credential_types::provider::ProvideCredentials as _;
use reqsign_core::time::Timestamp; use reqsign_core::time::Timestamp;
use tokio::sync::OnceCell;
static DEFAULT_CREDENTIAL_CHAIN: OnceCell<DefaultCredentialsChain> = OnceCell::const_new(); let credentials_provider =
crate::aws::aws_sdk_config().await.credentials_provider().ok_or_else(|| {
let chain = DEFAULT_CREDENTIAL_CHAIN reqsign_core::Error::unexpected("failed to load AWS credentials provider from AWS SDK config")
.get_or_init(|| { })?;
let reqwest_client = reqwest::Client::builder().build().unwrap(); let creds = credentials_provider.provide_credentials().await.map_err(|e| {
let connector = AwsReqwestConnector {
client: reqwest_client,
};
let conf = ProviderConfig::default().with_http_client(connector);
DefaultCredentialsChain::builder().configure(conf).build()
})
.await;
let creds = chain.provide_credentials().await.map_err(|e| {
reqsign_core::Error::unexpected("failed to load AWS credentials via AWS SDK").with_source(e) reqsign_core::Error::unexpected("failed to load AWS credentials via AWS SDK").with_source(e)
})?; })?;

Loading…
Cancel
Save