Skip to content

Commit

Permalink
Upload and download attachments, and added License file
Browse files Browse the repository at this point in the history
  • Loading branch information
dani-garcia committed Feb 14, 2018
1 parent 5cd40c6 commit b54684b
Show file tree
Hide file tree
Showing 20 changed files with 1,133 additions and 185 deletions.
150 changes: 94 additions & 56 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ rocket_contrib = "0.3.6"
reqwest = "0.8.4"

# multipart/form-data support
multipart = "0.13.6"
multipart = "0.14.1"

# A generic serialization/deserialization framework
serde = "1.0.27"
Expand All @@ -26,15 +26,15 @@ serde_json = "1.0.9"

# A safe, extensible ORM and Query builder
# If tables need more than 16 columns, add feature "large-tables"
diesel = { version = "1.1.1", features = ["sqlite", "chrono"] }
diesel_migrations = {version = "1.1.0", features = ["sqlite"] }
diesel = { version = "1.1.1", features = ["sqlite", "chrono", "large-tables"] }
diesel_migrations = { version = "1.1.0", features = ["sqlite"] }

# A generic connection pool
r2d2 = "0.8.2"
r2d2-diesel = "1.0.0"

# Crypto library
ring = { version = "0.11.0", features = ["rsa_signing"]}
ring = { version = "0.11.0", features = ["rsa_signing"] }

# UUID generation
uuid = { version = "0.5.1", features = ["v4"] }
Expand Down
674 changes: 674 additions & 0 deletions LICENSE.txt

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions migrations/2018-01-14-171611_create_tables/down.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ DROP TABLE devices;

DROP TABLE ciphers;

DROP TABLE attachments;

DROP TABLE folders;
49 changes: 29 additions & 20 deletions migrations/2018-01-14-171611_create_tables/up.sql
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
CREATE TABLE users (
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
email TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
password_hash BLOB NOT NULL,
salt BLOB NOT NULL,
password_iterations INTEGER NOT NULL,
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
password_hash BLOB NOT NULL,
salt BLOB NOT NULL,
password_iterations INTEGER NOT NULL,
password_hint TEXT,
key TEXT NOT NULL,
key TEXT NOT NULL,
private_key TEXT,
public_key TEXT,
totp_secret TEXT,
totp_recover TEXT,
security_stamp TEXT NOT NULL
security_stamp TEXT NOT NULL,
equivalent_domains TEXT NOT NULL,
excluded_globals TEXT NOT NULL
);

CREATE TABLE devices (
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
user_uuid TEXT NOT NULL REFERENCES users (uuid),
name TEXT NOT NULL,
type INTEGER NOT NULL,
push_token TEXT UNIQUE,
refresh_token TEXT UNIQUE NOT NULL
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
user_uuid TEXT NOT NULL REFERENCES users (uuid),
name TEXT NOT NULL,
type INTEGER NOT NULL,
push_token TEXT,
refresh_token TEXT NOT NULL
);

CREATE TABLE ciphers (
Expand All @@ -36,8 +38,15 @@ CREATE TABLE ciphers (
organization_uuid TEXT,
type INTEGER NOT NULL,
data TEXT NOT NULL,
favorite BOOLEAN NOT NULL,
attachments BLOB
favorite BOOLEAN NOT NULL
);

CREATE TABLE attachments (
id TEXT NOT NULL PRIMARY KEY,
cipher_uuid TEXT NOT NULL REFERENCES ciphers (uuid),
file_name TEXT NOT NULL,
file_size INTEGER NOT NULL

);

CREATE TABLE folders (
Expand Down
31 changes: 21 additions & 10 deletions src/api/core/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ struct KeysData {

#[post("/accounts/register", data = "<data>")]
fn register(data: Json<RegisterData>, conn: DbConn) -> Result<(), BadRequest<Json>> {
if CONFIG.signups_allowed {
if !CONFIG.signups_allowed {
err!(format!("Signups not allowed"))
}
println!("DEBUG - {:#?}", data);
Expand Down Expand Up @@ -81,7 +81,7 @@ fn post_keys(data: Json<KeysData>, headers: Headers, conn: DbConn) -> Result<Jso
}

#[post("/accounts/password", data = "<data>")]
fn post_password(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn post_password(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let key = data["key"].as_str().unwrap();
let password_hash = data["masterPasswordHash"].as_str().unwrap();
let new_password_hash = data["newMasterPasswordHash"].as_str().unwrap();
Expand All @@ -94,14 +94,13 @@ fn post_password(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Js

user.set_password(new_password_hash);
user.key = key.to_string();

user.save(&conn);

Ok(Json(json!({})))
Ok(())
}

#[post("/accounts/security-stamp", data = "<data>")]
fn post_sstamp(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn post_sstamp(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let password_hash = data["masterPasswordHash"].as_str().unwrap();

let mut user = headers.user;
Expand All @@ -111,26 +110,34 @@ fn post_sstamp(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json
}

user.reset_security_stamp();
user.save(&conn);

Ok(Json(json!({})))
Ok(())
}

#[post("/accounts/email-token", data = "<data>")]
fn post_email(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
println!("{:#?}", data);
fn post_email(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let password_hash = data["masterPasswordHash"].as_str().unwrap();
let new_email = data["newEmail"].as_str().unwrap();

let mut user = headers.user;

if !user.check_valid_password(password_hash) {
err!("Invalid password")
}

err!("Not implemented")
if User::find_by_mail(new_email, &conn).is_some() {
err!("Email already in use");
}

user.email = new_email.to_string();
user.save(&conn);

Ok(())
}

#[post("/accounts/delete", data = "<data>")]
fn delete_account(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn delete_account(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let password_hash = data["masterPasswordHash"].as_str().unwrap();

let mut user = headers.user;
Expand All @@ -139,6 +146,10 @@ fn delete_account(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<J
err!("Invalid password")
}

// Delete all ciphers by user_uuid
// Delete all devices by user_uuid
// Delete user

err!("Not implemented")
}

Expand Down
109 changes: 77 additions & 32 deletions src/api/core/ciphers.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
use std::io::{Cursor, Read};
use std::path::Path;

use rocket::{Route, Data};
use rocket::http::ContentType;
use rocket::response::status::BadRequest;

use rocket_contrib::{Json, Value};

use multipart::server::Multipart;
use multipart::server::{Multipart, SaveResult};
use multipart::server::save::SavedData;

use data_encoding::HEXLOWER;

use db::DbConn;
use db::models::*;

use util;
use crypto;

use auth::Headers;

use CONFIG;

#[get("/sync")]
fn sync(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let user = headers.user;
Expand All @@ -22,7 +30,7 @@ fn sync(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let folders_json: Vec<Value> = folders.iter().map(|c| c.to_json()).collect();

let ciphers = Cipher::find_by_user(&user.uuid, &conn);
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json()).collect();
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json(&conn)).collect();

Ok(Json(json!({
"Profile": user.to_json(),
Expand All @@ -42,7 +50,7 @@ fn sync(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn get_ciphers(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let ciphers = Cipher::find_by_user(&headers.user.uuid, &conn);

let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json()).collect();
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json(&conn)).collect();

Ok(Json(json!({
"Data": ciphers_json,
Expand All @@ -58,10 +66,10 @@ fn get_cipher(uuid: String, headers: Headers, conn: DbConn) -> Result<Json, BadR
};

if cipher.user_uuid != headers.user.uuid {
err!("Cipher is now owned by user")
err!("Cipher is not owned by user")
}

Ok(Json(cipher.to_json()))
Ok(Json(cipher.to_json(&conn)))
}

#[derive(Deserialize, Debug)]
Expand All @@ -86,7 +94,15 @@ fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn) -> Resul
data.favorite.unwrap_or(false));

if let Some(ref folder_id) = data.folderId {
// TODO: Validate folder is owned by user
match Folder::find_by_uuid(folder_id, &conn) {
Some(folder) => {
if folder.user_uuid != headers.user.uuid {
err!("Folder is not owned by user")
}
}
None => err!("Folder doesn't exist")
}

cipher.folder_uuid = Some(folder_id.clone());
}

Expand All @@ -107,7 +123,7 @@ fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn) -> Resul

cipher.save(&conn);

Ok(Json(cipher.to_json()))
Ok(Json(cipher.to_json(&conn)))
}

fn value_from_data(data: &CipherData) -> Result<Value, &'static str> {
Expand Down Expand Up @@ -180,48 +196,77 @@ fn post_ciphers_import(data: Json<Value>, headers: Headers, conn: DbConn) -> Res

#[post("/ciphers/<uuid>/attachment", format = "multipart/form-data", data = "<data>")]
fn post_attachment(uuid: String, data: Data, content_type: &ContentType, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
// TODO: Check if cipher exists
let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
Some(cipher) => cipher,
None => err!("Cipher doesn't exist")
};

if cipher.user_uuid != headers.user.uuid {
err!("Cipher is not owned by user")
}

let mut params = content_type.params();
let boundary_pair = params.next().expect("No boundary provided"); // ("boundary", "----WebKitFormBoundary...")
let boundary_pair = params.next().expect("No boundary provided");
let boundary = boundary_pair.1;

use data_encoding::BASE64URL;
use crypto;
use CONFIG;
let base_path = Path::new(&CONFIG.attachments_folder).join(&cipher.uuid);

// TODO: Maybe use the same format as the official server?
let attachment_id = BASE64URL.encode(&crypto::get_random_64());
let path = format!("{}/{}/{}", CONFIG.attachments_folder,
headers.user.uuid, attachment_id);
println!("Path {:#?}", path);
Multipart::with_body(data.open(), boundary).foreach_entry(|mut field| {
let name = field.headers.filename.unwrap(); // This is provided by the client, don't trust it

let mut mp = Multipart::with_body(data.open(), boundary);
match mp.save().with_dir(path).into_entries() {
Some(entries) => {
println!("Entries {:#?}", entries);
let file_name = HEXLOWER.encode(&crypto::get_random(vec![0; 10]));
let path = base_path.join(&file_name);

let saved_file = &entries.files["data"][0]; // Only one file at a time
let file_name = &saved_file.filename; // This is provided by the client, don't trust it
let file_size = &saved_file.size;
}
None => err!("No data entries")
}
let size = match field.data.save()
.memory_threshold(0)
.size_limit(None)
.with_path(path) {
SaveResult::Full(SavedData::File(path, size)) => size as i32,
_ => return
};

err!("Not implemented")
let attachment = Attachment::new(file_name, cipher.uuid.clone(), name, size);
println!("Attachment: {:#?}", attachment);
attachment.save(&conn);
});

Ok(Json(cipher.to_json(&conn)))
}

#[post("/ciphers/<uuid>/attachment/<attachment_id>/delete", data = "<data>")]
fn delete_attachment_post(uuid: String, attachment_id: String, data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
// Data contains a json object with the id, but we don't need it
delete_attachment(uuid, attachment_id, headers, conn)
}

#[delete("/ciphers/<uuid>/attachment/<attachment_id>")]
fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
if uuid != headers.user.uuid {
err!("Permission denied")
fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let attachment = match Attachment::find_by_id(&attachment_id, &conn) {
Some(attachment) => attachment,
None => err!("Attachment doesn't exist")
};

if attachment.cipher_uuid != uuid {
err!("Attachment from other cipher")
}

let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
Some(cipher) => cipher,
None => err!("Cipher doesn't exist")
};

if cipher.user_uuid != headers.user.uuid {
err!("Cipher is not owned by user")
}

// Delete file
let file = attachment.get_file_path();
util::delete_file(&file);

// Delete entry in cipher
attachment.delete(&conn);

err!("Not implemented")
Ok(())
}

#[post("/ciphers/<uuid>")]
Expand Down
Loading

0 comments on commit b54684b

Please sign in to comment.