mirror of
https://github.com/dani-garcia/vaultwarden.git
synced 2025-09-10 10:45:57 +03:00
Compare commits
56 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
924e4a17e5 | ||
|
fdbd73c716 | ||
|
f397f0cbd0 | ||
|
4d2c6e39b2 | ||
|
3e1afb139c | ||
|
af69606bea | ||
|
bc8ff14695 | ||
|
5f7b220eb4 | ||
|
1b20a25514 | ||
|
c1cd4d9a6b | ||
|
b63693aefb | ||
|
ec05f14f5a | ||
|
37d88be2be | ||
|
1c641d7635 | ||
|
e2ab2f7306 | ||
|
8df6f79f19 | ||
|
c58682e3fb | ||
|
db111ae2a0 | ||
|
049aa33f17 | ||
|
b1ac37609f | ||
|
53e8f78af6 | ||
|
1bced97e04 | ||
|
f94e626021 | ||
|
0a3b84b815 | ||
|
d336d89b83 | ||
|
1a5c1979e3 | ||
|
cec9566d2a | ||
|
fe473b9e75 | ||
|
062ae4dd59 | ||
|
45d676eb10 | ||
|
3cfdf9b585 | ||
|
08b551624c | ||
|
761a0a3393 | ||
|
6660b0aef3 | ||
|
781056152a | ||
|
6822bb28a0 | ||
|
b82710eecf | ||
|
c386b3bcf7 | ||
|
ffec0b065b | ||
|
5b7fe9f155 | ||
|
8d1ee859f2 | ||
|
c91f80c456 | ||
|
39891e86a0 | ||
|
575f701390 | ||
|
335099cd30 | ||
|
9fad541c87 | ||
|
007e053e2f | ||
|
ef2413a5aa | ||
|
ca8e1c646d | ||
|
346c7630c9 | ||
|
9e63985b28 | ||
|
401aa7c699 | ||
|
d68f57cbba | ||
|
19e0605d30 | ||
|
812387e586 | ||
|
f7ffb81d9e |
7
.env
7
.env
@@ -41,3 +41,10 @@
|
||||
# ROCKET_ADDRESS=0.0.0.0 # Enable this to test mobile app
|
||||
# ROCKET_PORT=8000
|
||||
# ROCKET_TLS={certs="/path/to/certs.pem",key="/path/to/key.pem"}
|
||||
|
||||
## Mail specific settings, if SMTP_HOST is specified, SMTP_USERNAME and SMTP_PASSWORD are mandatory
|
||||
# SMTP_HOST=smtp.domain.tld
|
||||
# SMTP_PORT=587
|
||||
# SMTP_SSL=true
|
||||
# SMTP_USERNAME=username
|
||||
# SMTP_PASSWORD=password
|
7
.travis.yml
Normal file
7
.travis.yml
Normal file
@@ -0,0 +1,7 @@
|
||||
# Copied from Rocket's .travis.yml
|
||||
language: rust
|
||||
sudo: required # so we get a VM with higher specs
|
||||
dist: trusty # so we get a VM with higher specs
|
||||
cache: cargo
|
||||
rust:
|
||||
- nightly
|
39
BUILD.md
39
BUILD.md
@@ -17,28 +17,29 @@ cargo build --release
|
||||
When run, the server is accessible in [http://localhost:80](http://localhost:80).
|
||||
|
||||
### Install the web-vault
|
||||
Download the latest official release from the [releases page](https://github.com/bitwarden/web/releases) and extract it.
|
||||
|
||||
Modify `web-vault/settings.Production.json` to look like this:
|
||||
```json
|
||||
{
|
||||
"appSettings": {
|
||||
"apiUri": "/api",
|
||||
"identityUri": "/identity",
|
||||
"iconsUri": "/icons",
|
||||
"stripeKey": "",
|
||||
"braintreeKey": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then, run the following from the `web-vault` directory:
|
||||
Clone the git repository at [bitwarden/web](https://github.com/bitwarden/web) and checkout the latest release tag (e.g. v2.1.1):
|
||||
```sh
|
||||
npm install
|
||||
npx gulp dist:selfHosted
|
||||
# clone the repository
|
||||
git clone https://github.com/bitwarden/web.git web-vault
|
||||
cd web-vault
|
||||
# switch to the latest tag
|
||||
git checkout "$(git tag | tail -n1)"
|
||||
```
|
||||
|
||||
Finally copy the contents of the `web-vault/dist` folder into the `bitwarden_rs/web-vault` folder.
|
||||
Apply the patch file from `docker/set-vault-baseurl.patch`:
|
||||
```sh
|
||||
# In the Vault repository directory
|
||||
git apply /path/to/bitwarden_rs/docker/set-vault-baseurl.patch
|
||||
```
|
||||
|
||||
Then, build the Vault:
|
||||
```sh
|
||||
npm run sub:init
|
||||
npm install
|
||||
npm run dist
|
||||
```
|
||||
|
||||
Finally copy the contents of the `build` folder into the `bitwarden_rs/web-vault` folder.
|
||||
|
||||
# Configuration
|
||||
The available configuration options are documented in the default `.env` file, and they can be modified by uncommenting the desired options in that file or by setting their respective environment variables. Look at the README file for the main configuration options available.
|
||||
|
557
Cargo.lock
generated
557
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
27
Cargo.toml
27
Cargo.toml
@@ -5,27 +5,27 @@ authors = ["Daniel García <dani-garcia@users.noreply.github.com>"]
|
||||
|
||||
[dependencies]
|
||||
# Web framework for nightly with a focus on ease-of-use, expressibility, and speed.
|
||||
rocket = { version = "0.3.15", features = ["tls"] }
|
||||
rocket_codegen = "0.3.15"
|
||||
rocket_contrib = "0.3.15"
|
||||
rocket = { version = "0.3.16", features = ["tls"] }
|
||||
rocket_codegen = "0.3.16"
|
||||
rocket_contrib = "0.3.16"
|
||||
|
||||
# HTTP client
|
||||
reqwest = "0.8.6"
|
||||
reqwest = "0.8.8"
|
||||
|
||||
# multipart/form-data support
|
||||
multipart = "0.15.0"
|
||||
multipart = "0.15.2"
|
||||
|
||||
# A generic serialization/deserialization framework
|
||||
serde = "1.0.70"
|
||||
serde_derive = "1.0.70"
|
||||
serde_json = "1.0.24"
|
||||
serde = "1.0.74"
|
||||
serde_derive = "1.0.74"
|
||||
serde_json = "1.0.26"
|
||||
|
||||
# A safe, extensible ORM and Query builder
|
||||
diesel = { version = "1.3.2", features = ["sqlite", "chrono", "r2d2"] }
|
||||
diesel_migrations = { version = "1.3.0", features = ["sqlite"] }
|
||||
|
||||
# Bundled SQLite
|
||||
libsqlite3-sys = { version = "0.9.1", features = ["bundled"] }
|
||||
libsqlite3-sys = { version = "0.9.3", features = ["bundled"] }
|
||||
|
||||
# Crypto library
|
||||
ring = { version = "= 0.11.0", features = ["rsa_signing"] }
|
||||
@@ -34,7 +34,7 @@ ring = { version = "= 0.11.0", features = ["rsa_signing"] }
|
||||
uuid = { version = "0.6.5", features = ["v4"] }
|
||||
|
||||
# Date and time library for Rust
|
||||
chrono = "0.4.4"
|
||||
chrono = "0.4.5"
|
||||
|
||||
# TOTP library
|
||||
oath = "0.10.2"
|
||||
@@ -52,12 +52,17 @@ u2f = "0.1.2"
|
||||
dotenv = { version = "0.13.0", default-features = false }
|
||||
|
||||
# Lazy static macro
|
||||
lazy_static = "1.0.2"
|
||||
lazy_static = "1.1.0"
|
||||
|
||||
# Numerical libraries
|
||||
num-traits = "0.2.5"
|
||||
num-derive = "0.2.2"
|
||||
|
||||
lettre = "0.8.2"
|
||||
lettre_email = "0.8.2"
|
||||
native-tls = "0.1.5"
|
||||
fast_chemail = "0.9.5"
|
||||
|
||||
[patch.crates-io]
|
||||
# Make jwt use ring 0.11, to match rocket
|
||||
jsonwebtoken = { path = "libs/jsonwebtoken" }
|
||||
|
@@ -4,7 +4,7 @@
|
||||
####################### VAULT BUILD IMAGE #######################
|
||||
FROM node:8-alpine as vault
|
||||
|
||||
ENV VAULT_VERSION "v2.1.1"
|
||||
ENV VAULT_VERSION "v2.2.0"
|
||||
|
||||
ENV URL "https://github.com/bitwarden/web.git"
|
||||
|
||||
|
80
Dockerfile.alpine
Normal file
80
Dockerfile.alpine
Normal file
@@ -0,0 +1,80 @@
|
||||
# Using multistage build:
|
||||
# https://docs.docker.com/develop/develop-images/multistage-build/
|
||||
# https://whitfin.io/speeding-up-rust-docker-builds/
|
||||
####################### VAULT BUILD IMAGE #######################
|
||||
FROM node:8-alpine as vault
|
||||
|
||||
ENV VAULT_VERSION "v2.2.0"
|
||||
|
||||
ENV URL "https://github.com/bitwarden/web.git"
|
||||
|
||||
RUN apk add --update-cache --upgrade \
|
||||
curl \
|
||||
git \
|
||||
tar
|
||||
|
||||
RUN git clone -b $VAULT_VERSION --depth 1 $URL web-build
|
||||
WORKDIR /web-build
|
||||
|
||||
COPY /docker/set-vault-baseurl.patch /web-build/
|
||||
RUN git apply set-vault-baseurl.patch
|
||||
|
||||
RUN npm run sub:init && npm install
|
||||
|
||||
RUN npm run dist \
|
||||
&& mv build /web-vault
|
||||
|
||||
########################## BUILD IMAGE ##########################
|
||||
# Musl build image for statically compiled binary
|
||||
FROM clux/muslrust:nightly-2018-08-24 as build
|
||||
|
||||
# Creates a dummy project used to grab dependencies
|
||||
RUN USER=root cargo init --bin
|
||||
|
||||
# Copies over *only* your manifests and vendored dependencies
|
||||
COPY ./Cargo.* ./
|
||||
COPY ./libs ./libs
|
||||
COPY ./rust-toolchain ./rust-toolchain
|
||||
|
||||
# Builds your dependencies and removes the
|
||||
# dummy project, except the target folder
|
||||
# This folder contains the compiled dependencies
|
||||
RUN cargo build --release
|
||||
RUN find . -not -path "./target*" -delete
|
||||
|
||||
# Copies the complete project
|
||||
# To avoid copying unneeded files, use .dockerignore
|
||||
COPY . .
|
||||
|
||||
# Builds again, this time it'll just be
|
||||
# your actual source files being built
|
||||
RUN cargo build --release
|
||||
|
||||
######################## RUNTIME IMAGE ########################
|
||||
# Create a new stage with a minimal image
|
||||
# because we already have a binary built
|
||||
FROM alpine:3.8
|
||||
|
||||
ENV ROCKET_ENV "staging"
|
||||
ENV ROCKET_WORKERS=10
|
||||
ENV SSL_CERT_DIR=/etc/ssl/certs
|
||||
|
||||
# Install needed libraries
|
||||
RUN apk add \
|
||||
openssl\
|
||||
ca-certificates \
|
||||
&& rm /var/cache/apk/*
|
||||
|
||||
RUN mkdir /data
|
||||
VOLUME /data
|
||||
EXPOSE 80
|
||||
|
||||
# Copies the files from the context (env file and web-vault)
|
||||
# and the binary from the "build" stage to the current stage
|
||||
COPY .env .
|
||||
COPY Rocket.toml .
|
||||
COPY --from=vault /web-vault ./web-vault
|
||||
COPY --from=build /volume/target/x86_64-unknown-linux-musl/release/bitwarden_rs .
|
||||
|
||||
# Configures the startup!
|
||||
CMD ./bitwarden_rs
|
113
Dockerfile.armv7
Normal file
113
Dockerfile.armv7
Normal file
@@ -0,0 +1,113 @@
|
||||
# Using multistage build:
|
||||
# https://docs.docker.com/develop/develop-images/multistage-build/
|
||||
# https://whitfin.io/speeding-up-rust-docker-builds/
|
||||
####################### VAULT BUILD IMAGE #######################
|
||||
FROM node:8-alpine as vault
|
||||
|
||||
ENV VAULT_VERSION "v2.2.0"
|
||||
|
||||
ENV URL "https://github.com/bitwarden/web.git"
|
||||
|
||||
RUN apk add --update-cache --upgrade \
|
||||
curl \
|
||||
git \
|
||||
tar
|
||||
|
||||
RUN git clone -b $VAULT_VERSION --depth 1 $URL web-build
|
||||
WORKDIR /web-build
|
||||
|
||||
COPY /docker/set-vault-baseurl.patch /web-build/
|
||||
RUN git apply set-vault-baseurl.patch
|
||||
|
||||
RUN npm run sub:init && npm install
|
||||
|
||||
RUN npm run dist \
|
||||
&& mv build /web-vault
|
||||
|
||||
########################## BUILD IMAGE ##########################
|
||||
# We need to use the Rust build image, because
|
||||
# we need the Rust compiler and Cargo tooling
|
||||
FROM rust as build
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y \
|
||||
gcc-arm-linux-gnueabihf \
|
||||
&& mkdir -p ~/.cargo \
|
||||
&& echo '[target.armv7-unknown-linux-gnueabihf]' >> ~/.cargo/config \
|
||||
&& echo 'linker = "arm-linux-gnueabihf-gcc"' >> ~/.cargo/config
|
||||
|
||||
ENV CARGO_HOME "/root/.cargo"
|
||||
ENV USER "root"
|
||||
|
||||
# Creates a dummy project used to grab dependencies
|
||||
RUN USER=root cargo new --bin app
|
||||
WORKDIR /app
|
||||
|
||||
# Copies over *only* your manifests and vendored dependencies
|
||||
COPY ./Cargo.* ./
|
||||
COPY ./libs ./libs
|
||||
COPY ./rust-toolchain ./rust-toolchain
|
||||
|
||||
# Prepare openssl armhf libs
|
||||
RUN sed 's/^deb/deb-src/' /etc/apt/sources.list > \
|
||||
/etc/apt/sources.list.d/deb-src.list \
|
||||
&& dpkg --add-architecture armhf \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y \
|
||||
libssl-dev:armhf \
|
||||
libc6-dev:armhf
|
||||
|
||||
ENV CC_armv7_unknown_linux_gnueabihf="/usr/bin/arm-linux-gnueabihf-gcc"
|
||||
ENV CROSS_COMPILE="1"
|
||||
ENV OPENSSL_INCLUDE_DIR="/usr/include/arm-linux-gnueabihf"
|
||||
ENV OPENSSL_LIB_DIR="/usr/lib/arm-linux-gnueabihf"
|
||||
|
||||
# Builds your dependencies and removes the
|
||||
# dummy project, except the target folder
|
||||
# This folder contains the compiled dependencies
|
||||
COPY . .
|
||||
RUN rustup target add armv7-unknown-linux-gnueabihf
|
||||
RUN cargo build --release --target=armv7-unknown-linux-gnueabihf -v
|
||||
RUN find . -not -path "./target*" -delete
|
||||
|
||||
# Copies the complete project
|
||||
# To avoid copying unneeded files, use .dockerignore
|
||||
COPY . .
|
||||
|
||||
# Builds again, this time it'll just be
|
||||
# your actual source files being built
|
||||
RUN cargo build --release --target=armv7-unknown-linux-gnueabihf -v
|
||||
|
||||
######################## RUNTIME IMAGE ########################
|
||||
# Create a new stage with a minimal image
|
||||
# because we already have a binary built
|
||||
FROM resin/armv7hf-debian:stretch
|
||||
|
||||
ENV ROCKET_ENV "staging"
|
||||
ENV ROCKET_WORKERS=10
|
||||
|
||||
RUN [ "cross-build-start" ]
|
||||
|
||||
# Install needed libraries
|
||||
RUN apt-get update && apt-get install -y\
|
||||
openssl\
|
||||
ca-certificates\
|
||||
--no-install-recommends\
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN mkdir /data
|
||||
|
||||
RUN [ "cross-build-end" ]
|
||||
|
||||
VOLUME /data
|
||||
EXPOSE 80
|
||||
|
||||
# Copies the files from the context (env file and web-vault)
|
||||
# and the binary from the "build" stage to the current stage
|
||||
COPY .env .
|
||||
COPY Rocket.toml .
|
||||
COPY --from=vault /web-vault ./web-vault
|
||||
COPY --from=build /app/target/armv7-unknown-linux-gnueabihf/release/bitwarden_rs .
|
||||
|
||||
# Configures the startup!
|
||||
CMD ./bitwarden_rs
|
71
README.md
71
README.md
@@ -1,9 +1,19 @@
|
||||
This is Bitwarden server API implementation written in rust compatible with [upstream Bitwarden clients](https://bitwarden.com/#download)*, ideal for self-hosted deployment where running official resource-heavy service might not be ideal.
|
||||
### This is a Bitwarden server API implementation written in Rust compatible with [upstream Bitwarden clients](https://bitwarden.com/#download)*, perfect for self-hosted deployment where running the official resource-heavy service might not be ideal.
|
||||
|
||||
---
|
||||
|
||||
[](https://travis-ci.org/dani-garcia/bitwarden_rs)
|
||||
[](https://deps.rs/repo/github/dani-garcia/bitwarden_rs)
|
||||
[](https://github.com/dani-garcia/bitwarden_rs/releases/latest)
|
||||
[](https://github.com/dani-garcia/bitwarden_rs/blob/master/LICENSE.txt)
|
||||
[](https://matrix.to/#/#bitwarden_rs:matrix.org)
|
||||
|
||||
Image is based on [Rust implementation of Bitwarden API](https://github.com/dani-garcia/bitwarden_rs).
|
||||
|
||||
_*Note, that this project is not associated with the [Bitwarden](https://bitwarden.com/) project nor 8bit Solutions LLC._
|
||||
|
||||
---
|
||||
|
||||
**Table of contents**
|
||||
|
||||
- [Features](#features)
|
||||
@@ -13,6 +23,7 @@ _*Note, that this project is not associated with the [Bitwarden](https://bitward
|
||||
- [Updating the bitwarden image](#updating-the-bitwarden-image)
|
||||
- [Configuring bitwarden service](#configuring-bitwarden-service)
|
||||
- [Disable registration of new users](#disable-registration-of-new-users)
|
||||
- [Disable invitations](#disable-invitations)
|
||||
- [Enabling HTTPS](#enabling-https)
|
||||
- [Enabling U2F authentication](#enabling-u2f-authentication)
|
||||
- [Changing persistent data location](#changing-persistent-data-location)
|
||||
@@ -22,6 +33,8 @@ _*Note, that this project is not associated with the [Bitwarden](https://bitward
|
||||
- [icons cache](#icons-cache)
|
||||
- [Changing the API request size limit](#changing-the-api-request-size-limit)
|
||||
- [Changing the number of workers](#changing-the-number-of-workers)
|
||||
- [SMTP configuration](#smtp-configuration)
|
||||
- [Password hint display](#password-hint-display)
|
||||
- [Disabling or overriding the Vault interface hosting](#disabling-or-overriding-the-vault-interface-hosting)
|
||||
- [Other configuration](#other-configuration)
|
||||
- [Building your own image](#building-your-own-image)
|
||||
@@ -38,6 +51,7 @@ _*Note, that this project is not associated with the [Bitwarden](https://bitward
|
||||
- [Changing user email](#changing-user-email)
|
||||
- [Creating organization](#creating-organization)
|
||||
- [Inviting users into organization](#inviting-users-into-organization)
|
||||
- [Running on unencrypted connection](#running-on-unencrypted-connection)
|
||||
- [Get in touch](#get-in-touch)
|
||||
|
||||
## Features
|
||||
@@ -125,6 +139,20 @@ docker run -d --name bitwarden \
|
||||
-p 80:80 \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
Note: While users can't register on their own, they can still be invited by already registered users. Read bellow if you also want to disable that.
|
||||
|
||||
### Disable invitations
|
||||
|
||||
Even when registration is disabled, organization administrators or owners can invite users to join organization. This won't send email invitation to the users, but after they are invited, they can register with the invited email even if `SIGNUPS_ALLOWED` is actually set to `false`. You can disable this functionality completely by setting `INVITATIONS_ALLOWED` env variable to `false`:
|
||||
|
||||
```sh
|
||||
docker run -d --name bitwarden \
|
||||
-e SIGNUPS_ALLOWED=false \
|
||||
-e INVITATIONS_ALLOWED=false \
|
||||
-v /bw-data/:/data/ \
|
||||
-p 80:80 \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
|
||||
### Enabling HTTPS
|
||||
To enable HTTPS, you need to configure the `ROCKET_TLS`.
|
||||
@@ -252,6 +280,36 @@ docker run -d --name bitwarden \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
|
||||
### SMTP configuration
|
||||
|
||||
You can configure bitwarden_rs to send emails via a SMTP agent:
|
||||
|
||||
```sh
|
||||
docker run -d --name bitwarden \
|
||||
-e SMTP_HOST=<smtp.domain.tld> \
|
||||
-e SMTP_PORT=587 \
|
||||
-e SMTP_SSL=true \
|
||||
-e SMTP_USERNAME=<username> \
|
||||
-e SMTP_PASSWORD=<password> \
|
||||
-v /bw-data/:/data/ \
|
||||
-p 80:80 \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
|
||||
When `SMTP_SSL` is set to `true`(this is the default), only TLSv1.1 and TLSv1.2 protocols will be accepted and `SMTP_PORT` will default to `587`. If set to `false`, `SMTP_PORT` will default to `25` and the connection won't be encrypted. This can be very insecure, use this setting only if you know what you're doing.
|
||||
|
||||
### Password hint display
|
||||
|
||||
Usually, password hints are sent by email. But as bitwarden_rs is made with small or personal deployment in mind, hints are also available from the password hint page, so you don't have to configure an email service. If you want to disable this feature, you can use the `SHOW_PASSWORD_HINT` variable:
|
||||
|
||||
```sh
|
||||
docker run -d --name bitwarden \
|
||||
-e SHOW_PASSWORD_HINT=false \
|
||||
-v /bw-data/:/data/ \
|
||||
-p 80:80 \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
|
||||
### Disabling or overriding the Vault interface hosting
|
||||
|
||||
As a convenience bitwarden_rs image will also host static files for Vault web interface. You can disable this static file hosting completely by setting the WEB_VAULT_ENABLED variable.
|
||||
@@ -263,7 +321,6 @@ docker run -d --name bitwarden \
|
||||
-p 80:80 \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
|
||||
Alternatively you can override the Vault files and provide your own static files to host. You can do that by mounting a path with your files over the `/web-vault` directory in the container. Just make sure the directory contains at least `index.html` file.
|
||||
|
||||
```sh
|
||||
@@ -272,7 +329,7 @@ docker run -d --name bitwarden \
|
||||
-v /bw-data/:/data/ \
|
||||
-p 80:80 \
|
||||
mprasil/bitwarden:latest
|
||||
```
|
||||
```
|
||||
|
||||
Note that you can also change the path where bitwarden_rs looks for static files by providing the `WEB_VAULT_FOLDER` environment variable with the path.
|
||||
|
||||
@@ -354,7 +411,13 @@ We use upstream Vault interface directly without any (significant) changes, this
|
||||
|
||||
### Inviting users into organization
|
||||
|
||||
The users must already be registered on your server to invite them, because we can't send the invitation via email. The invited users won't get the invitation email, instead they will appear in the interface as if they already accepted the invitation. Organization admin then just needs to confirm them to be proper Organization members and to give them access to the shared secrets.
|
||||
If you have [invitations disabled](#disable-invitations), the users must already be registered on your server to invite them. The invited users won't get the invitation email, instead they will appear in the interface as if they already accepted the invitation. (if the user has already registered) Organization admin then just needs to confirm them to be proper Organization members and to give them access to the shared secrets.
|
||||
|
||||
### Running on unencrypted connection
|
||||
|
||||
It is strongly recommended to run bitwarden_rs service over HTTPS. However the server itself while [supporting it](#enabling-https) does not strictly require such setup. This makes it a bit easier to spin up the service in cases where you can generally trust the connection (internal and secure network, access over VPN,..) or when you want to put the service behind HTTP proxy, that will do the encryption on the proxy end.
|
||||
|
||||
Running over HTTP is still reasonably secure provided you use really strong master password and that you avoid using web Vault over connection that is vulnerable to MITM attacks where attacker could inject javascript into your interface. However some forms of 2FA might not work in this setup and [Vault doesn't work in this configuration in Chrome](https://github.com/bitwarden/web/issues/254).
|
||||
|
||||
## Get in touch
|
||||
|
||||
|
@@ -1,7 +1,7 @@
|
||||
--- a/src/app/services/services.module.ts
|
||||
+++ b/src/app/services/services.module.ts
|
||||
@@ -116,17 +116,15 @@ const exportService = new ExportService(folderService, cipherService, apiService
|
||||
const importService = new ImportService(cipherService, folderService, apiService, i18nService, collectionService);
|
||||
@@ -120,20 +120,17 @@ const notificationsService = new NotificationsService(userService, syncService,
|
||||
const environmentService = new EnvironmentService(apiService, storageService, notificationsService);
|
||||
const auditService = new AuditService(cryptoFunctionService, apiService);
|
||||
|
||||
-const analytics = new Analytics(window, () => platformUtilsService.isDev() || platformUtilsService.isSelfHost(),
|
||||
@@ -15,9 +15,14 @@
|
||||
- const isDev = platformUtilsService.isDev();
|
||||
- if (!isDev && platformUtilsService.isSelfHost()) {
|
||||
- environmentService.baseUrl = window.location.origin;
|
||||
- } else {
|
||||
- environmentService.notificationsUrl = isDev ? 'http://localhost:61840' :
|
||||
- 'https://notifications.bitwarden.com'; // window.location.origin + '/notifications';
|
||||
- }
|
||||
+ const isDev = false;
|
||||
+ environmentService.baseUrl = window.location.origin;
|
||||
+ environmentService.notificationsUrl = window.location.origin + '/notifications';
|
||||
+
|
||||
await apiService.setUrls({
|
||||
base: isDev ? null : window.location.origin,
|
||||
api: isDev ? 'http://localhost:4000' : null,
|
||||
|
3
migrations/2018-08-27-172114_update_ciphers/up.sql
Normal file
3
migrations/2018-08-27-172114_update_ciphers/up.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE ciphers
|
||||
ADD COLUMN
|
||||
password_history TEXT;
|
1
migrations/2018-09-10-111213_add_invites/down.sql
Normal file
1
migrations/2018-09-10-111213_add_invites/down.sql
Normal file
@@ -0,0 +1 @@
|
||||
DROP TABLE invitations;
|
3
migrations/2018-09-10-111213_add_invites/up.sql
Normal file
3
migrations/2018-09-10-111213_add_invites/up.sql
Normal file
@@ -0,0 +1,3 @@
|
||||
CREATE TABLE invitations (
|
||||
email TEXT NOT NULL PRIMARY KEY
|
||||
);
|
@@ -1 +1 @@
|
||||
nightly-2018-07-18
|
||||
nightly-2018-08-24
|
||||
|
@@ -5,6 +5,8 @@ use db::models::*;
|
||||
|
||||
use api::{PasswordData, JsonResult, EmptyResult, JsonUpcase, NumberOrString};
|
||||
use auth::Headers;
|
||||
use fast_chemail::is_valid_email;
|
||||
use mail;
|
||||
|
||||
use CONFIG;
|
||||
|
||||
@@ -30,15 +32,34 @@ struct KeysData {
|
||||
fn register(data: JsonUpcase<RegisterData>, conn: DbConn) -> EmptyResult {
|
||||
let data: RegisterData = data.into_inner().data;
|
||||
|
||||
if !CONFIG.signups_allowed {
|
||||
err!("Signups not allowed")
|
||||
}
|
||||
|
||||
if User::find_by_mail(&data.Email, &conn).is_some() {
|
||||
err!("Email already exists")
|
||||
}
|
||||
let mut user = match User::find_by_mail(&data.Email, &conn) {
|
||||
Some(mut user) => {
|
||||
if Invitation::take(&data.Email, &conn) {
|
||||
for mut user_org in UserOrganization::find_invited_by_user(&user.uuid, &conn).iter_mut() {
|
||||
user_org.status = UserOrgStatus::Accepted as i32;
|
||||
user_org.save(&conn);
|
||||
};
|
||||
user
|
||||
} else {
|
||||
if CONFIG.signups_allowed {
|
||||
err!("Account with this email already exists")
|
||||
} else {
|
||||
err!("Registration not allowed")
|
||||
}
|
||||
}
|
||||
},
|
||||
None => {
|
||||
if CONFIG.signups_allowed || Invitation::take(&data.Email, &conn) {
|
||||
User::new(data.Email)
|
||||
} else {
|
||||
err!("Registration not allowed")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut user = User::new(data.Email, data.Key, data.MasterPasswordHash);
|
||||
user.set_password(&data.MasterPasswordHash);
|
||||
user.key = data.Key;
|
||||
|
||||
// Add extra fields if present
|
||||
if let Some(name) = data.Name {
|
||||
@@ -85,7 +106,10 @@ fn post_profile(data: JsonUpcase<ProfileData>, headers: Headers, conn: DbConn) -
|
||||
let mut user = headers.user;
|
||||
|
||||
user.name = data.Name;
|
||||
user.password_hint = data.MasterPasswordHint;
|
||||
user.password_hint = match data.MasterPasswordHint {
|
||||
Some(ref h) if h.is_empty() => None,
|
||||
_ => data.MasterPasswordHint,
|
||||
};
|
||||
user.save(&conn);
|
||||
|
||||
Ok(Json(user.to_json(&conn)))
|
||||
@@ -263,15 +287,55 @@ struct PasswordHintData {
|
||||
fn password_hint(data: JsonUpcase<PasswordHintData>, conn: DbConn) -> EmptyResult {
|
||||
let data: PasswordHintData = data.into_inner().data;
|
||||
|
||||
if !CONFIG.show_password_hint {
|
||||
return Ok(())
|
||||
if !is_valid_email(&data.Email) {
|
||||
err!("This email address is not valid...");
|
||||
}
|
||||
|
||||
let user = User::find_by_mail(&data.Email, &conn);
|
||||
if user.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let user = user.unwrap();
|
||||
if let Some(ref mail_config) = CONFIG.mail {
|
||||
if let Err(e) = mail::send_password_hint(&user.email, user.password_hint, mail_config) {
|
||||
err!(format!("There have been a problem sending the email: {}", e));
|
||||
}
|
||||
} else if CONFIG.show_password_hint {
|
||||
if let Some(hint) = user.password_hint {
|
||||
err!(format!("Your password hint is: {}", &hint));
|
||||
} else {
|
||||
err!(format!("Sorry, you have no password hint..."));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(non_snake_case)]
|
||||
struct PreloginData {
|
||||
Email: String,
|
||||
}
|
||||
|
||||
#[post("/accounts/prelogin", data = "<data>")]
|
||||
fn prelogin(data: JsonUpcase<PreloginData>, conn: DbConn) -> JsonResult {
|
||||
let data: PreloginData = data.into_inner().data;
|
||||
|
||||
match User::find_by_mail(&data.Email, &conn) {
|
||||
Some(user) => {
|
||||
let hint = user.password_hint.to_owned().unwrap_or_default();
|
||||
err!(format!("Your password hint is: {}", hint))
|
||||
let kdf_type = 0; // PBKDF2: 0
|
||||
|
||||
let _server_iter = user.password_iterations;
|
||||
let client_iter = 5000; // TODO: Make iterations user configurable
|
||||
|
||||
|
||||
Ok(Json(json!({
|
||||
"Kdf": kdf_type,
|
||||
"KdfIterations": client_iter
|
||||
})))
|
||||
},
|
||||
None => Ok(()),
|
||||
None => err!("Invalid user"),
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -86,7 +86,7 @@ fn get_cipher_details(uuid: String, headers: Headers, conn: DbConn) -> JsonResul
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[allow(non_snake_case)]
|
||||
struct CipherData {
|
||||
pub struct CipherData {
|
||||
// Id is optional as it is included only in bulk share
|
||||
Id: Option<String>,
|
||||
// Folder id is not included in import
|
||||
@@ -100,8 +100,8 @@ struct CipherData {
|
||||
Card = 3,
|
||||
Identity = 4
|
||||
*/
|
||||
Type: i32, // TODO: Change this to NumberOrString
|
||||
Name: String,
|
||||
pub Type: i32, // TODO: Change this to NumberOrString
|
||||
pub Name: String,
|
||||
Notes: Option<String>,
|
||||
Fields: Option<Value>,
|
||||
|
||||
@@ -112,6 +112,8 @@ struct CipherData {
|
||||
Identity: Option<Value>,
|
||||
|
||||
Favorite: Option<bool>,
|
||||
|
||||
PasswordHistory: Option<Value>,
|
||||
}
|
||||
|
||||
#[post("/ciphers/admin", data = "<data>")]
|
||||
@@ -125,26 +127,26 @@ fn post_ciphers(data: JsonUpcase<CipherData>, headers: Headers, conn: DbConn) ->
|
||||
let data: CipherData = data.into_inner().data;
|
||||
|
||||
let mut cipher = Cipher::new(data.Type, data.Name.clone());
|
||||
update_cipher_from_data(&mut cipher, data, &headers, true, &conn)?;
|
||||
update_cipher_from_data(&mut cipher, data, &headers, false, &conn)?;
|
||||
|
||||
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
|
||||
}
|
||||
|
||||
fn update_cipher_from_data(cipher: &mut Cipher, data: CipherData, headers: &Headers, is_new_or_shared: bool, conn: &DbConn) -> EmptyResult {
|
||||
if is_new_or_shared {
|
||||
if let Some(org_id) = data.OrganizationId {
|
||||
match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
|
||||
None => err!("You don't have permission to add item to organization"),
|
||||
Some(org_user) => if org_user.has_full_access() {
|
||||
cipher.organization_uuid = Some(org_id);
|
||||
cipher.user_uuid = None;
|
||||
} else {
|
||||
err!("You don't have permission to add cipher directly to organization")
|
||||
}
|
||||
pub fn update_cipher_from_data(cipher: &mut Cipher, data: CipherData, headers: &Headers, shared_to_collection: bool, conn: &DbConn) -> EmptyResult {
|
||||
if let Some(org_id) = data.OrganizationId {
|
||||
match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
|
||||
None => err!("You don't have permission to add item to organization"),
|
||||
Some(org_user) => if shared_to_collection
|
||||
|| org_user.has_full_access()
|
||||
|| cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
|
||||
cipher.organization_uuid = Some(org_id);
|
||||
cipher.user_uuid = None;
|
||||
} else {
|
||||
err!("You don't have permission to add cipher directly to organization")
|
||||
}
|
||||
} else {
|
||||
cipher.user_uuid = Some(headers.user.uuid.clone());
|
||||
}
|
||||
} else {
|
||||
cipher.user_uuid = Some(headers.user.uuid.clone());
|
||||
}
|
||||
|
||||
if let Some(ref folder_id) = data.FolderId {
|
||||
@@ -177,6 +179,7 @@ fn update_cipher_from_data(cipher: &mut Cipher, data: CipherData, headers: &Head
|
||||
type_data["Name"] = Value::String(data.Name.clone());
|
||||
type_data["Notes"] = data.Notes.clone().map(Value::String).unwrap_or(Value::Null);
|
||||
type_data["Fields"] = data.Fields.clone().unwrap_or(Value::Null);
|
||||
type_data["PasswordHistory"] = data.PasswordHistory.clone().unwrap_or(Value::Null);
|
||||
// TODO: ******* Backwards compat end **********
|
||||
|
||||
cipher.favorite = data.Favorite.unwrap_or(false);
|
||||
@@ -184,6 +187,7 @@ fn update_cipher_from_data(cipher: &mut Cipher, data: CipherData, headers: &Head
|
||||
cipher.notes = data.Notes;
|
||||
cipher.fields = data.Fields.map(|f| f.to_string());
|
||||
cipher.data = type_data.to_string();
|
||||
cipher.password_history = data.PasswordHistory.map(|f| f.to_string());
|
||||
|
||||
cipher.save(&conn);
|
||||
|
||||
@@ -239,7 +243,7 @@ fn post_ciphers_import(data: JsonUpcase<ImportData>, headers: Headers, conn: DbC
|
||||
.map(|i| folders[*i].uuid.clone());
|
||||
|
||||
let mut cipher = Cipher::new(cipher_data.Type, cipher_data.Name.clone());
|
||||
update_cipher_from_data(&mut cipher, cipher_data, &headers, true, &conn)?;
|
||||
update_cipher_from_data(&mut cipher, cipher_data, &headers, false, &conn)?;
|
||||
|
||||
cipher.move_to_folder(folder_uuid, &headers.user.uuid.clone(), &conn).ok();
|
||||
}
|
||||
@@ -373,11 +377,11 @@ fn put_cipher_share_seleted(data: JsonUpcase<ShareSelectedCipherData>, headers:
|
||||
if data.Ciphers.len() == 0 {
|
||||
err!("You must select at least one cipher.")
|
||||
}
|
||||
|
||||
|
||||
if data.CollectionIds.len() == 0 {
|
||||
err!("You must select at least one collection.")
|
||||
}
|
||||
|
||||
|
||||
for cipher in data.Ciphers.iter() {
|
||||
match cipher.Id {
|
||||
Some(ref id) => cipher_ids.push(id.to_string()),
|
||||
@@ -386,7 +390,7 @@ fn put_cipher_share_seleted(data: JsonUpcase<ShareSelectedCipherData>, headers:
|
||||
}
|
||||
|
||||
let attachments = Attachment::find_by_ciphers(cipher_ids, &conn);
|
||||
|
||||
|
||||
if attachments.len() > 0 {
|
||||
err!("Ciphers should not have any attachments.")
|
||||
}
|
||||
@@ -418,22 +422,28 @@ fn share_cipher_by_uuid(uuid: &str, data: ShareCipherData, headers: &Headers, co
|
||||
None => err!("Cipher doesn't exist")
|
||||
};
|
||||
|
||||
match data.Cipher.OrganizationId {
|
||||
match data.Cipher.OrganizationId.clone() {
|
||||
None => err!("Organization id not provided"),
|
||||
Some(_) => {
|
||||
update_cipher_from_data(&mut cipher, data.Cipher, &headers, true, &conn)?;
|
||||
Some(organization_uuid) => {
|
||||
let mut shared_to_collection = false;
|
||||
for uuid in &data.CollectionIds {
|
||||
match Collection::find_by_uuid(uuid, &conn) {
|
||||
None => err!("Invalid collection ID provided"),
|
||||
Some(collection) => {
|
||||
if collection.is_writable_by_user(&headers.user.uuid, &conn) {
|
||||
CollectionCipher::save(&cipher.uuid.clone(), &collection.uuid, &conn);
|
||||
if collection.org_uuid == organization_uuid {
|
||||
CollectionCipher::save(&cipher.uuid.clone(), &collection.uuid, &conn);
|
||||
shared_to_collection = true;
|
||||
} else {
|
||||
err!("Collection does not belong to organization")
|
||||
}
|
||||
} else {
|
||||
err!("No rights to modify the collection")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
update_cipher_from_data(&mut cipher, data.Cipher, &headers, shared_to_collection, &conn)?;
|
||||
|
||||
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
|
||||
}
|
||||
@@ -484,7 +494,10 @@ fn post_attachment(uuid: String, data: Data, content_type: &ContentType, headers
|
||||
};
|
||||
|
||||
let attachment = Attachment::new(file_name, cipher.uuid.clone(), name, size);
|
||||
attachment.save(&conn);
|
||||
match attachment.save(&conn) {
|
||||
Ok(()) => (),
|
||||
Err(_) => println!("Error: failed to save attachment")
|
||||
};
|
||||
}).expect("Error processing multipart data");
|
||||
|
||||
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
|
||||
@@ -516,6 +529,11 @@ fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn
|
||||
_delete_cipher_attachment_by_id(&uuid, &attachment_id, &headers, &conn)
|
||||
}
|
||||
|
||||
#[delete("/ciphers/<uuid>/attachment/<attachment_id>/admin")]
|
||||
fn delete_attachment_admin(uuid: String, attachment_id: String, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
_delete_cipher_attachment_by_id(&uuid, &attachment_id, &headers, &conn)
|
||||
}
|
||||
|
||||
#[post("/ciphers/<uuid>/delete")]
|
||||
fn delete_cipher_post(uuid: String, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
_delete_cipher_by_uuid(&uuid, &headers, &conn)
|
||||
@@ -531,13 +549,18 @@ fn delete_cipher(uuid: String, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
_delete_cipher_by_uuid(&uuid, &headers, &conn)
|
||||
}
|
||||
|
||||
#[delete("/ciphers/<uuid>/admin")]
|
||||
fn delete_cipher_admin(uuid: String, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
_delete_cipher_by_uuid(&uuid, &headers, &conn)
|
||||
}
|
||||
|
||||
#[delete("/ciphers", data = "<data>")]
|
||||
fn delete_cipher_selected(data: JsonUpcase<Value>, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
let data: Value = data.into_inner().data;
|
||||
|
||||
let uuids = match data.get("Ids") {
|
||||
Some(ids) => match ids.as_array() {
|
||||
Some(ids) => ids.iter().filter_map(|uuid| { uuid.as_str() }),
|
||||
Some(ids) => ids.iter().filter_map(Value::as_str),
|
||||
None => err!("Posted ids field is not an array")
|
||||
},
|
||||
None => err!("Request missing ids field")
|
||||
@@ -583,7 +606,7 @@ fn move_cipher_selected(data: JsonUpcase<Value>, headers: Headers, conn: DbConn)
|
||||
|
||||
let uuids = match data.get("Ids") {
|
||||
Some(ids) => match ids.as_array() {
|
||||
Some(ids) => ids.iter().filter_map(|uuid| { uuid.as_str() }),
|
||||
Some(ids) => ids.iter().filter_map(Value::as_str),
|
||||
None => err!("Posted ids field is not an array")
|
||||
},
|
||||
None => err!("Request missing ids field")
|
||||
@@ -636,7 +659,7 @@ fn delete_all(data: JsonUpcase<PasswordData>, headers: Headers, conn: DbConn) ->
|
||||
for f in Folder::find_by_user(&user.uuid, &conn) {
|
||||
if f.delete(&conn).is_err() {
|
||||
err!("Failed deleting folder")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
@@ -25,6 +25,7 @@ pub fn routes() -> Vec<Route> {
|
||||
delete_account,
|
||||
revision_date,
|
||||
password_hint,
|
||||
prelogin,
|
||||
|
||||
sync,
|
||||
|
||||
@@ -42,6 +43,7 @@ pub fn routes() -> Vec<Route> {
|
||||
delete_attachment_post,
|
||||
delete_attachment_post_admin,
|
||||
delete_attachment,
|
||||
delete_attachment_admin,
|
||||
post_cipher_admin,
|
||||
post_cipher_share,
|
||||
put_cipher_share,
|
||||
@@ -51,6 +53,7 @@ pub fn routes() -> Vec<Route> {
|
||||
delete_cipher_post,
|
||||
delete_cipher_post_admin,
|
||||
delete_cipher,
|
||||
delete_cipher_admin,
|
||||
delete_cipher_selected,
|
||||
delete_cipher_selected_post,
|
||||
delete_all,
|
||||
@@ -107,6 +110,7 @@ pub fn routes() -> Vec<Route> {
|
||||
put_organization_user,
|
||||
delete_user,
|
||||
post_delete_user,
|
||||
post_org_import,
|
||||
|
||||
clear_device_token,
|
||||
put_device_token,
|
||||
|
@@ -1,7 +1,5 @@
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use rocket_contrib::{Json, Value};
|
||||
|
||||
use CONFIG;
|
||||
use db::DbConn;
|
||||
use db::models::*;
|
||||
|
||||
@@ -140,9 +138,8 @@ fn get_user_collections(headers: Headers, conn: DbConn) -> JsonResult {
|
||||
"Data":
|
||||
Collection::find_by_user_uuid(&headers.user.uuid, &conn)
|
||||
.iter()
|
||||
.map(|collection| {
|
||||
collection.to_json()
|
||||
}).collect::<Value>(),
|
||||
.map(Collection::to_json)
|
||||
.collect::<Value>(),
|
||||
"Object": "list"
|
||||
})))
|
||||
}
|
||||
@@ -153,9 +150,8 @@ fn get_org_collections(org_id: String, _headers: AdminHeaders, conn: DbConn) ->
|
||||
"Data":
|
||||
Collection::find_by_organization(&org_id, &conn)
|
||||
.iter()
|
||||
.map(|collection| {
|
||||
collection.to_json()
|
||||
}).collect::<Value>(),
|
||||
.map(Collection::to_json)
|
||||
.collect::<Value>(),
|
||||
"Object": "list"
|
||||
})))
|
||||
}
|
||||
@@ -217,7 +213,7 @@ fn delete_organization_collection_user(org_id: String, col_id: String, org_user_
|
||||
}
|
||||
};
|
||||
|
||||
match UserOrganization::find_by_uuid(&org_user_id, &conn) {
|
||||
match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
|
||||
None => err!("User not found in organization"),
|
||||
Some(user_org) => {
|
||||
match CollectionUser::find_by_collection_and_user(&collection.uuid, &user_org.user_uuid, &conn) {
|
||||
@@ -373,54 +369,70 @@ fn send_invite(org_id: String, data: JsonUpcase<InviteData>, headers: AdminHeade
|
||||
err!("Only Owners can invite Admins or Owners")
|
||||
}
|
||||
|
||||
for user_opt in data.Emails.iter().map(|email| User::find_by_mail(email, &conn)) {
|
||||
match user_opt {
|
||||
None => err!("User email does not exist"),
|
||||
Some(user) => {
|
||||
if UserOrganization::find_by_user_and_org(&user.uuid, &org_id, &conn).is_some() {
|
||||
err!("User already in organization")
|
||||
for email in data.Emails.iter() {
|
||||
let mut user_org_status = UserOrgStatus::Accepted as i32;
|
||||
let user = match User::find_by_mail(&email, &conn) {
|
||||
None => if CONFIG.invitations_allowed { // Invite user if that's enabled
|
||||
let mut invitation = Invitation::new(email.clone());
|
||||
match invitation.save(&conn) {
|
||||
Ok(()) => {
|
||||
let mut user = User::new(email.clone());
|
||||
if user.save(&conn) {
|
||||
user_org_status = UserOrgStatus::Invited as i32;
|
||||
user
|
||||
} else {
|
||||
err!("Failed to create placeholder for invited user")
|
||||
}
|
||||
}
|
||||
Err(_) => err!(format!("Failed to invite: {}", email))
|
||||
}
|
||||
|
||||
} else {
|
||||
err!(format!("User email does not exist: {}", email))
|
||||
},
|
||||
Some(user) => if UserOrganization::find_by_user_and_org(&user.uuid, &org_id, &conn).is_some() {
|
||||
err!(format!("User already in organization: {}", email))
|
||||
} else {
|
||||
user
|
||||
}
|
||||
|
||||
let mut new_user = UserOrganization::new(user.uuid.clone(), org_id.clone());
|
||||
let access_all = data.AccessAll.unwrap_or(false);
|
||||
new_user.access_all = access_all;
|
||||
new_user.type_ = new_type;
|
||||
};
|
||||
|
||||
// If no accessAll, add the collections received
|
||||
if !access_all {
|
||||
for col in &data.Collections {
|
||||
match Collection::find_by_uuid_and_org(&col.Id, &org_id, &conn) {
|
||||
None => err!("Collection not found in Organization"),
|
||||
Some(collection) => {
|
||||
if CollectionUser::save(&user.uuid, &collection.uuid, col.ReadOnly, &conn).is_err() {
|
||||
err!("Failed saving collection access for user")
|
||||
}
|
||||
}
|
||||
let mut new_user = UserOrganization::new(user.uuid.clone(), org_id.clone());
|
||||
let access_all = data.AccessAll.unwrap_or(false);
|
||||
new_user.access_all = access_all;
|
||||
new_user.type_ = new_type;
|
||||
new_user.status = user_org_status;
|
||||
|
||||
// If no accessAll, add the collections received
|
||||
if !access_all {
|
||||
for col in &data.Collections {
|
||||
match Collection::find_by_uuid_and_org(&col.Id, &org_id, &conn) {
|
||||
None => err!("Collection not found in Organization"),
|
||||
Some(collection) => {
|
||||
if CollectionUser::save(&user.uuid, &collection.uuid, col.ReadOnly, &conn).is_err() {
|
||||
err!("Failed saving collection access for user")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
new_user.save(&conn);
|
||||
}
|
||||
}
|
||||
|
||||
new_user.save(&conn);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[post("/organizations/<org_id>/users/<user_id>/confirm", data = "<data>")]
|
||||
fn confirm_invite(org_id: String, user_id: String, data: JsonUpcase<Value>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
#[post("/organizations/<org_id>/users/<org_user_id>/confirm", data = "<data>")]
|
||||
fn confirm_invite(org_id: String, org_user_id: String, data: JsonUpcase<Value>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
let data = data.into_inner().data;
|
||||
|
||||
let mut user_to_confirm = match UserOrganization::find_by_uuid(&user_id, &conn) {
|
||||
let mut user_to_confirm = match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
|
||||
Some(user) => user,
|
||||
None => err!("Failed to find user membership")
|
||||
None => err!("The specified user isn't a member of the organization")
|
||||
};
|
||||
|
||||
if user_to_confirm.org_uuid != org_id {
|
||||
err!("The specified user isn't a member of the organization")
|
||||
}
|
||||
|
||||
if user_to_confirm.type_ != UserOrgType::User as i32 &&
|
||||
headers.org_user_type != UserOrgType::Owner as i32 {
|
||||
err!("Only Owners can confirm Admins or Owners")
|
||||
@@ -441,17 +453,13 @@ fn confirm_invite(org_id: String, user_id: String, data: JsonUpcase<Value>, head
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[get("/organizations/<org_id>/users/<user_id>")]
|
||||
fn get_user(org_id: String, user_id: String, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
|
||||
let user = match UserOrganization::find_by_uuid(&user_id, &conn) {
|
||||
#[get("/organizations/<org_id>/users/<org_user_id>")]
|
||||
fn get_user(org_id: String, org_user_id: String, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
|
||||
let user = match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
|
||||
Some(user) => user,
|
||||
None => err!("Failed to find user membership")
|
||||
None => err!("The specified user isn't a member of the organization")
|
||||
};
|
||||
|
||||
if user.org_uuid != org_id {
|
||||
err!("The specified user isn't a member of the organization")
|
||||
}
|
||||
|
||||
Ok(Json(user.to_json_details(&conn)))
|
||||
}
|
||||
|
||||
@@ -464,13 +472,13 @@ struct EditUserData {
|
||||
AccessAll: bool,
|
||||
}
|
||||
|
||||
#[put("/organizations/<org_id>/users/<user_id>", data = "<data>", rank = 1)]
|
||||
fn put_organization_user(org_id: String, user_id: String, data: JsonUpcase<EditUserData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
edit_user(org_id, user_id, data, headers, conn)
|
||||
#[put("/organizations/<org_id>/users/<org_user_id>", data = "<data>", rank = 1)]
|
||||
fn put_organization_user(org_id: String, org_user_id: String, data: JsonUpcase<EditUserData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
edit_user(org_id, org_user_id, data, headers, conn)
|
||||
}
|
||||
|
||||
#[post("/organizations/<org_id>/users/<user_id>", data = "<data>", rank = 1)]
|
||||
fn edit_user(org_id: String, user_id: String, data: JsonUpcase<EditUserData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
#[post("/organizations/<org_id>/users/<org_user_id>", data = "<data>", rank = 1)]
|
||||
fn edit_user(org_id: String, org_user_id: String, data: JsonUpcase<EditUserData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
let data: EditUserData = data.into_inner().data;
|
||||
|
||||
let new_type = match UserOrgType::from_str(&data.Type.into_string()) {
|
||||
@@ -478,19 +486,22 @@ fn edit_user(org_id: String, user_id: String, data: JsonUpcase<EditUserData>, he
|
||||
None => err!("Invalid type")
|
||||
};
|
||||
|
||||
let mut user_to_edit = match UserOrganization::find_by_uuid(&user_id, &conn) {
|
||||
let mut user_to_edit = match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
|
||||
Some(user) => user,
|
||||
None => err!("The specified user isn't member of the organization")
|
||||
};
|
||||
|
||||
if new_type != UserOrgType::User as i32 &&
|
||||
if new_type != user_to_edit.type_ as i32 && (
|
||||
user_to_edit.type_ <= UserOrgType::Admin as i32 ||
|
||||
new_type <= UserOrgType::Admin as i32
|
||||
) &&
|
||||
headers.org_user_type != UserOrgType::Owner as i32 {
|
||||
err!("Only Owners can grant Admin or Owner type")
|
||||
err!("Only Owners can grant and remove Admin or Owner privileges")
|
||||
}
|
||||
|
||||
if user_to_edit.type_ != UserOrgType::User as i32 &&
|
||||
if user_to_edit.type_ == UserOrgType::Owner as i32 &&
|
||||
headers.org_user_type != UserOrgType::Owner as i32 {
|
||||
err!("Only Owners can edit Admin or Owner")
|
||||
err!("Only Owners can edit Owner users")
|
||||
}
|
||||
|
||||
if user_to_edit.type_ == UserOrgType::Owner as i32 &&
|
||||
@@ -535,9 +546,9 @@ fn edit_user(org_id: String, user_id: String, data: JsonUpcase<EditUserData>, he
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[delete("/organizations/<org_id>/users/<user_id>")]
|
||||
fn delete_user(org_id: String, user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
let user_to_delete = match UserOrganization::find_by_uuid(&user_id, &conn) {
|
||||
#[delete("/organizations/<org_id>/users/<org_user_id>")]
|
||||
fn delete_user(org_id: String, org_user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
let user_to_delete = match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
|
||||
Some(user) => user,
|
||||
None => err!("User to delete isn't member of the organization")
|
||||
};
|
||||
@@ -564,7 +575,76 @@ fn delete_user(org_id: String, user_id: String, headers: AdminHeaders, conn: DbC
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/organizations/<org_id>/users/<user_id>/delete")]
|
||||
fn post_delete_user(org_id: String, user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
delete_user(org_id, user_id, headers, conn)
|
||||
#[post("/organizations/<org_id>/users/<org_user_id>/delete")]
|
||||
fn post_delete_user(org_id: String, org_user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
|
||||
delete_user(org_id, org_user_id, headers, conn)
|
||||
}
|
||||
|
||||
use super::ciphers::CipherData;
|
||||
use super::ciphers::update_cipher_from_data;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(non_snake_case)]
|
||||
struct ImportData {
|
||||
Ciphers: Vec<CipherData>,
|
||||
Collections: Vec<NewCollectionData>,
|
||||
CollectionRelationships: Vec<RelationsData>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(non_snake_case)]
|
||||
struct RelationsData {
|
||||
// Cipher index
|
||||
Key: usize,
|
||||
// Collection index
|
||||
Value: usize,
|
||||
}
|
||||
|
||||
#[post("/ciphers/import-organization?<query>", data = "<data>")]
|
||||
fn post_org_import(query: OrgIdData, data: JsonUpcase<ImportData>, headers: Headers, conn: DbConn) -> EmptyResult {
|
||||
let data: ImportData = data.into_inner().data;
|
||||
let org_id = query.organizationId;
|
||||
|
||||
let org_user = match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
|
||||
Some(user) => user,
|
||||
None => err!("User is not part of the organization")
|
||||
};
|
||||
|
||||
if org_user.type_ > UserOrgType::Admin as i32 {
|
||||
err!("Only admins or owners can import into an organization")
|
||||
}
|
||||
|
||||
// Read and create the collections
|
||||
let collections: Vec<_> = data.Collections.into_iter().map(|coll| {
|
||||
let mut collection = Collection::new(org_id.clone(), coll.Name);
|
||||
collection.save(&conn);
|
||||
collection
|
||||
}).collect();
|
||||
|
||||
// Read the relations between collections and ciphers
|
||||
let mut relations = Vec::new();
|
||||
for relation in data.CollectionRelationships {
|
||||
relations.push((relation.Key, relation.Value));
|
||||
}
|
||||
|
||||
// Read and create the ciphers
|
||||
let ciphers: Vec<_> = data.Ciphers.into_iter().map(|cipher_data| {
|
||||
let mut cipher = Cipher::new(cipher_data.Type, cipher_data.Name.clone());
|
||||
update_cipher_from_data(&mut cipher, cipher_data, &headers, false, &conn).ok();
|
||||
cipher
|
||||
}).collect();
|
||||
|
||||
// Assign the collections
|
||||
for (cipher_index, coll_index) in relations {
|
||||
let cipher_id = &ciphers[cipher_index].uuid;
|
||||
let coll_id = &collections[coll_index].uuid;
|
||||
|
||||
CollectionCipher::save(cipher_id, coll_id, &conn);
|
||||
}
|
||||
|
||||
let mut user = headers.user;
|
||||
match user.update_revision(&conn) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) => err!("Failed to update the revision, please log out and log back in to finish import.")
|
||||
}
|
||||
}
|
@@ -1,4 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
|
||||
use rocket::request::{self, Form, FormItems, FromForm, FromRequest, Request};
|
||||
use rocket::{Outcome, Route};
|
||||
@@ -21,12 +22,12 @@ pub fn routes() -> Vec<Route> {
|
||||
}
|
||||
|
||||
#[post("/connect/token", data = "<connect_data>")]
|
||||
fn login(connect_data: Form<ConnectData>, device_type: DeviceType, conn: DbConn) -> JsonResult {
|
||||
fn login(connect_data: Form<ConnectData>, device_type: DeviceType, conn: DbConn, socket: Option<SocketAddr>) -> JsonResult {
|
||||
let data = connect_data.get();
|
||||
|
||||
match data.grant_type {
|
||||
GrantType::RefreshToken => _refresh_login(data, device_type, conn),
|
||||
GrantType::Password => _password_login(data, device_type, conn),
|
||||
GrantType::Password => _password_login(data, device_type, conn, socket),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +58,13 @@ fn _refresh_login(data: &ConnectData, _device_type: DeviceType, conn: DbConn) ->
|
||||
})))
|
||||
}
|
||||
|
||||
fn _password_login(data: &ConnectData, device_type: DeviceType, conn: DbConn) -> JsonResult {
|
||||
fn _password_login(data: &ConnectData, device_type: DeviceType, conn: DbConn, remote: Option<SocketAddr>) -> JsonResult {
|
||||
// Get the ip for error reporting
|
||||
let ip = match remote {
|
||||
Some(ip) => ip.ip(),
|
||||
None => IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
|
||||
};
|
||||
|
||||
// Validate scope
|
||||
let scope = data.get("scope");
|
||||
if scope != "api offline_access" {
|
||||
@@ -68,13 +75,19 @@ fn _password_login(data: &ConnectData, device_type: DeviceType, conn: DbConn) ->
|
||||
let username = data.get("username");
|
||||
let user = match User::find_by_mail(username, &conn) {
|
||||
Some(user) => user,
|
||||
None => err!("Username or password is incorrect. Try again."),
|
||||
None => err!(format!(
|
||||
"Username or password is incorrect. Try again. IP: {}. Username: {}.",
|
||||
ip, username
|
||||
)),
|
||||
};
|
||||
|
||||
// Check password
|
||||
let password = data.get("password");
|
||||
if !user.check_valid_password(password) {
|
||||
err!("Username or password is incorrect. Try again.")
|
||||
err!(format!(
|
||||
"Username or password is incorrect. Try again. IP: {}. Username: {}.",
|
||||
ip, username
|
||||
))
|
||||
}
|
||||
|
||||
// Let's only use the header and ignore the 'devicetype' parameter
|
||||
|
@@ -2,11 +2,13 @@ pub(crate) mod core;
|
||||
mod icons;
|
||||
mod identity;
|
||||
mod web;
|
||||
mod notifications;
|
||||
|
||||
pub use self::core::routes as core_routes;
|
||||
pub use self::icons::routes as icons_routes;
|
||||
pub use self::identity::routes as identity_routes;
|
||||
pub use self::web::routes as web_routes;
|
||||
pub use self::notifications::routes as notifications_routes;
|
||||
|
||||
use rocket::response::status::BadRequest;
|
||||
use rocket_contrib::Json;
|
||||
|
31
src/api/notifications.rs
Normal file
31
src/api/notifications.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use rocket::Route;
|
||||
use rocket_contrib::Json;
|
||||
|
||||
use db::DbConn;
|
||||
use api::JsonResult;
|
||||
use auth::Headers;
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes![negotiate]
|
||||
}
|
||||
|
||||
#[post("/hub/negotiate")]
|
||||
fn negotiate(_headers: Headers, _conn: DbConn) -> JsonResult {
|
||||
use data_encoding::BASE64URL;
|
||||
use crypto;
|
||||
|
||||
// Store this in db?
|
||||
let conn_id = BASE64URL.encode(&crypto::get_random(vec![0u8; 16]));
|
||||
|
||||
// TODO: Implement transports
|
||||
// Rocket WS support: https://github.com/SergioBenitez/Rocket/issues/90
|
||||
// Rocket SSE support: https://github.com/SergioBenitez/Rocket/issues/33
|
||||
Ok(Json(json!({
|
||||
"connectionId": conn_id,
|
||||
"availableTransports":[
|
||||
// {"transport":"WebSockets", "transferFormats":["Text","Binary"]},
|
||||
// {"transport":"ServerSentEvents", "transferFormats":["Text"]},
|
||||
// {"transport":"LongPolling", "transferFormats":["Text","Binary"]}
|
||||
]
|
||||
})))
|
||||
}
|
@@ -53,13 +53,11 @@ use db::schema::attachments;
|
||||
|
||||
/// Database methods
|
||||
impl Attachment {
|
||||
pub fn save(&self, conn: &DbConn) -> bool {
|
||||
match diesel::replace_into(attachments::table)
|
||||
pub fn save(&self, conn: &DbConn) -> QueryResult<()> {
|
||||
diesel::replace_into(attachments::table)
|
||||
.values(self)
|
||||
.execute(&**conn) {
|
||||
Ok(1) => true, // One row inserted
|
||||
_ => false,
|
||||
}
|
||||
.execute(&**conn)
|
||||
.and(Ok(()))
|
||||
}
|
||||
|
||||
pub fn delete(self, conn: &DbConn) -> QueryResult<()> {
|
||||
@@ -67,7 +65,7 @@ impl Attachment {
|
||||
use std::{thread, time};
|
||||
|
||||
let mut retries = 10;
|
||||
|
||||
|
||||
loop {
|
||||
match diesel::delete(
|
||||
attachments::table.filter(
|
||||
|
@@ -32,6 +32,7 @@ pub struct Cipher {
|
||||
pub data: String,
|
||||
|
||||
pub favorite: bool,
|
||||
pub password_history: Option<String>,
|
||||
}
|
||||
|
||||
/// Local methods
|
||||
@@ -55,6 +56,7 @@ impl Cipher {
|
||||
fields: None,
|
||||
|
||||
data: String::new(),
|
||||
password_history: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +79,10 @@ impl Cipher {
|
||||
let fields_json: JsonValue = if let Some(ref fields) = self.fields {
|
||||
serde_json::from_str(fields).unwrap()
|
||||
} else { JsonValue::Null };
|
||||
|
||||
let password_history_json: JsonValue = if let Some(ref password_history) = self.password_history {
|
||||
serde_json::from_str(password_history).unwrap()
|
||||
} else { JsonValue::Null };
|
||||
|
||||
let mut data_json: JsonValue = serde_json::from_str(&self.data).unwrap();
|
||||
|
||||
@@ -108,6 +114,8 @@ impl Cipher {
|
||||
|
||||
"Object": "cipher",
|
||||
"Edit": true,
|
||||
|
||||
"PasswordHistory": password_history_json,
|
||||
});
|
||||
|
||||
let key = match self.type_ {
|
||||
|
@@ -12,7 +12,7 @@ pub use self::attachment::Attachment;
|
||||
pub use self::cipher::Cipher;
|
||||
pub use self::device::Device;
|
||||
pub use self::folder::{Folder, FolderCipher};
|
||||
pub use self::user::User;
|
||||
pub use self::user::{User, Invitation};
|
||||
pub use self::organization::Organization;
|
||||
pub use self::organization::{UserOrganization, UserOrgStatus, UserOrgType};
|
||||
pub use self::collection::{Collection, CollectionUser, CollectionCipher};
|
||||
|
@@ -27,7 +27,7 @@ pub struct UserOrganization {
|
||||
}
|
||||
|
||||
pub enum UserOrgStatus {
|
||||
_Invited = 0, // Unused, users are accepted automatically
|
||||
Invited = 0,
|
||||
Accepted = 1,
|
||||
Confirmed = 2,
|
||||
}
|
||||
@@ -270,6 +270,13 @@ impl UserOrganization {
|
||||
.first::<Self>(&**conn).ok()
|
||||
}
|
||||
|
||||
pub fn find_by_uuid_and_org(uuid: &str, org_uuid: &str, conn: &DbConn) -> Option<Self> {
|
||||
users_organizations::table
|
||||
.filter(users_organizations::uuid.eq(uuid))
|
||||
.filter(users_organizations::org_uuid.eq(org_uuid))
|
||||
.first::<Self>(&**conn).ok()
|
||||
}
|
||||
|
||||
pub fn find_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Self> {
|
||||
users_organizations::table
|
||||
.filter(users_organizations::user_uuid.eq(user_uuid))
|
||||
@@ -277,6 +284,13 @@ impl UserOrganization {
|
||||
.load::<Self>(&**conn).unwrap_or(vec![])
|
||||
}
|
||||
|
||||
pub fn find_invited_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Self> {
|
||||
users_organizations::table
|
||||
.filter(users_organizations::user_uuid.eq(user_uuid))
|
||||
.filter(users_organizations::status.eq(UserOrgStatus::Invited as i32))
|
||||
.load::<Self>(&**conn).unwrap_or(vec![])
|
||||
}
|
||||
|
||||
pub fn find_by_org(org_uuid: &str, conn: &DbConn) -> Vec<Self> {
|
||||
users_organizations::table
|
||||
.filter(users_organizations::org_uuid.eq(org_uuid))
|
||||
|
@@ -39,13 +39,12 @@ pub struct User {
|
||||
|
||||
/// Local methods
|
||||
impl User {
|
||||
pub fn new(mail: String, key: String, password: String) -> Self {
|
||||
pub fn new(mail: String) -> Self {
|
||||
let now = Utc::now().naive_utc();
|
||||
let email = mail.to_lowercase();
|
||||
|
||||
let iterations = CONFIG.password_iterations;
|
||||
let salt = crypto::get_random_64();
|
||||
let password_hash = crypto::hash_password(password.as_bytes(), &salt, iterations as u32);
|
||||
|
||||
Self {
|
||||
uuid: Uuid::new_v4().to_string(),
|
||||
@@ -53,9 +52,9 @@ impl User {
|
||||
updated_at: now,
|
||||
name: email.clone(),
|
||||
email,
|
||||
key,
|
||||
key: String::new(),
|
||||
|
||||
password_hash,
|
||||
password_hash: Vec::new(),
|
||||
salt,
|
||||
password_iterations: iterations,
|
||||
|
||||
@@ -103,7 +102,7 @@ impl User {
|
||||
use diesel;
|
||||
use diesel::prelude::*;
|
||||
use db::DbConn;
|
||||
use db::schema::users;
|
||||
use db::schema::{users, invitations};
|
||||
|
||||
/// Database methods
|
||||
impl User {
|
||||
@@ -186,3 +185,47 @@ impl User {
|
||||
.first::<Self>(&**conn).ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Identifiable, Queryable, Insertable)]
|
||||
#[table_name = "invitations"]
|
||||
#[primary_key(email)]
|
||||
pub struct Invitation {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
impl Invitation {
|
||||
pub fn new(email: String) -> Self {
|
||||
Self {
|
||||
email
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&mut self, conn: &DbConn) -> QueryResult<()> {
|
||||
diesel::replace_into(invitations::table)
|
||||
.values(&*self)
|
||||
.execute(&**conn)
|
||||
.and(Ok(()))
|
||||
}
|
||||
|
||||
pub fn delete(self, conn: &DbConn) -> QueryResult<()> {
|
||||
diesel::delete(invitations::table.filter(
|
||||
invitations::email.eq(self.email)))
|
||||
.execute(&**conn)
|
||||
.and(Ok(()))
|
||||
}
|
||||
|
||||
pub fn find_by_mail(mail: &str, conn: &DbConn) -> Option<Self> {
|
||||
let lower_mail = mail.to_lowercase();
|
||||
invitations::table
|
||||
.filter(invitations::email.eq(lower_mail))
|
||||
.first::<Self>(&**conn).ok()
|
||||
}
|
||||
|
||||
pub fn take(mail: &str, conn: &DbConn) -> bool {
|
||||
CONFIG.invitations_allowed &&
|
||||
match Self::find_by_mail(mail, &conn) {
|
||||
Some(invitation) => invitation.delete(&conn).is_ok(),
|
||||
None => false
|
||||
}
|
||||
}
|
||||
}
|
@@ -21,6 +21,7 @@ table! {
|
||||
fields -> Nullable<Text>,
|
||||
data -> Text,
|
||||
favorite -> Bool,
|
||||
password_history -> Nullable<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +113,12 @@ table! {
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
invitations (email) {
|
||||
email -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
users_collections (user_uuid, collection_uuid) {
|
||||
user_uuid -> Text,
|
||||
|
63
src/mail.rs
Normal file
63
src/mail.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use std::error::Error;
|
||||
use native_tls::{Protocol, TlsConnector};
|
||||
use lettre::{EmailTransport, SmtpTransport, ClientTlsParameters, ClientSecurity};
|
||||
use lettre::smtp::{ConnectionReuseParameters, SmtpTransportBuilder};
|
||||
use lettre::smtp::authentication::Credentials;
|
||||
use lettre_email::EmailBuilder;
|
||||
|
||||
use MailConfig;
|
||||
|
||||
fn mailer(config: &MailConfig) -> SmtpTransport {
|
||||
let client_security = if config.smtp_ssl {
|
||||
let mut tls_builder = TlsConnector::builder().unwrap();
|
||||
tls_builder.supported_protocols(&[Protocol::Tlsv11, Protocol::Tlsv12]).unwrap();
|
||||
ClientSecurity::Required(
|
||||
ClientTlsParameters::new(config.smtp_host.to_owned(), tls_builder.build().unwrap())
|
||||
)
|
||||
} else {
|
||||
ClientSecurity::None
|
||||
};
|
||||
|
||||
let smtp_transport = SmtpTransportBuilder::new(
|
||||
(config.smtp_host.to_owned().as_str(), config.smtp_port),
|
||||
client_security
|
||||
).unwrap();
|
||||
|
||||
let smtp_transport = match (&config.smtp_username, &config.smtp_password) {
|
||||
(Some(username), Some(password)) => {
|
||||
smtp_transport.credentials(Credentials::new(username.to_owned(), password.to_owned()))
|
||||
},
|
||||
(_, _) => smtp_transport,
|
||||
};
|
||||
|
||||
smtp_transport
|
||||
.smtp_utf8(true)
|
||||
.connection_reuse(ConnectionReuseParameters::NoReuse)
|
||||
.build()
|
||||
}
|
||||
|
||||
pub fn send_password_hint(address: &str, hint: Option<String>, config: &MailConfig) -> Result<(), String> {
|
||||
let (subject, body) = if let Some(hint) = hint {
|
||||
("Your master password hint",
|
||||
format!(
|
||||
"You (or someone) recently requested your master password hint.\n\n\
|
||||
Your hint is: \"{}\"\n\n\
|
||||
If you did not request your master password hint you can safely ignore this email.\n",
|
||||
hint))
|
||||
} else {
|
||||
("Sorry, you have no password hint...",
|
||||
"Sorry, you have not specified any password hint...\n".to_string())
|
||||
};
|
||||
|
||||
let email = EmailBuilder::new()
|
||||
.to(address)
|
||||
.from((config.smtp_from.to_owned(), "Bitwarden-rs"))
|
||||
.subject(subject)
|
||||
.body(body)
|
||||
.build().unwrap();
|
||||
|
||||
match mailer(config).send(&email) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(e.description().to_string()),
|
||||
}
|
||||
}
|
64
src/main.rs
64
src/main.rs
@@ -27,6 +27,10 @@ extern crate lazy_static;
|
||||
#[macro_use]
|
||||
extern crate num_derive;
|
||||
extern crate num_traits;
|
||||
extern crate lettre;
|
||||
extern crate lettre_email;
|
||||
extern crate native_tls;
|
||||
extern crate fast_chemail;
|
||||
|
||||
use std::{env, path::Path, process::{exit, Command}};
|
||||
use rocket::Rocket;
|
||||
@@ -38,6 +42,7 @@ mod api;
|
||||
mod db;
|
||||
mod crypto;
|
||||
mod auth;
|
||||
mod mail;
|
||||
|
||||
fn init_rocket() -> Rocket {
|
||||
rocket::ignite()
|
||||
@@ -45,6 +50,7 @@ fn init_rocket() -> Rocket {
|
||||
.mount("/api", api::core_routes())
|
||||
.mount("/identity", api::identity_routes())
|
||||
.mount("/icons", api::icons_routes())
|
||||
.mount("/notifications", api::notifications_routes())
|
||||
.manage(db::init_pool())
|
||||
}
|
||||
|
||||
@@ -154,6 +160,57 @@ lazy_static! {
|
||||
static ref CONFIG: Config = Config::load();
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MailConfig {
|
||||
smtp_host: String,
|
||||
smtp_port: u16,
|
||||
smtp_ssl: bool,
|
||||
smtp_from: String,
|
||||
smtp_username: Option<String>,
|
||||
smtp_password: Option<String>,
|
||||
}
|
||||
|
||||
impl MailConfig {
|
||||
fn load() -> Option<Self> {
|
||||
let smtp_host = env::var("SMTP_HOST").ok();
|
||||
|
||||
// When SMTP_HOST is absent, we assume the user does not want to enable it.
|
||||
if smtp_host.is_none() {
|
||||
return None
|
||||
}
|
||||
|
||||
let smtp_ssl = util::parse_option_string(env::var("SMTP_SSL").ok()).unwrap_or(true);
|
||||
let smtp_port = util::parse_option_string(env::var("SMTP_PORT").ok())
|
||||
.unwrap_or_else(|| {
|
||||
if smtp_ssl {
|
||||
587u16
|
||||
} else {
|
||||
25u16
|
||||
}
|
||||
});
|
||||
|
||||
let smtp_username = env::var("SMTP_USERNAME").ok();
|
||||
let smtp_password = env::var("SMTP_PASSWORD").ok().or_else(|| {
|
||||
if smtp_username.as_ref().is_some() {
|
||||
println!("Please specify SMTP_PASSWORD to enable SMTP support.");
|
||||
exit(1);
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
Some(MailConfig {
|
||||
smtp_host: smtp_host.unwrap(),
|
||||
smtp_port: smtp_port,
|
||||
smtp_ssl: smtp_ssl,
|
||||
smtp_from: util::parse_option_string(env::var("SMTP_FROM").ok())
|
||||
.unwrap_or("bitwarden-rs@localhost".to_string()),
|
||||
smtp_username: smtp_username,
|
||||
smtp_password: smtp_password,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Config {
|
||||
database_url: String,
|
||||
@@ -169,10 +226,14 @@ pub struct Config {
|
||||
|
||||
local_icon_extractor: bool,
|
||||
signups_allowed: bool,
|
||||
invitations_allowed: bool,
|
||||
password_iterations: i32,
|
||||
show_password_hint: bool,
|
||||
|
||||
domain: String,
|
||||
domain_set: bool,
|
||||
|
||||
mail: Option<MailConfig>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -198,11 +259,14 @@ impl Config {
|
||||
|
||||
local_icon_extractor: util::parse_option_string(env::var("LOCAL_ICON_EXTRACTOR").ok()).unwrap_or(false),
|
||||
signups_allowed: util::parse_option_string(env::var("SIGNUPS_ALLOWED").ok()).unwrap_or(true),
|
||||
invitations_allowed: util::parse_option_string(env::var("INVITATIONS_ALLOWED").ok()).unwrap_or(true),
|
||||
password_iterations: util::parse_option_string(env::var("PASSWORD_ITERATIONS").ok()).unwrap_or(100_000),
|
||||
show_password_hint: util::parse_option_string(env::var("SHOW_PASSWORD_HINT").ok()).unwrap_or(true),
|
||||
|
||||
domain_set: domain.is_ok(),
|
||||
domain: domain.unwrap_or("http://localhost".into()),
|
||||
|
||||
mail: MailConfig::load(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user