Compare commits

..

No commits in common. "dev" and "sealing" have entirely different histories.
dev ... sealing

32 changed files with 488 additions and 1005 deletions

View file

@ -1,44 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT service_token.* FROM service_token, service_token_role_membership\n WHERE service_token.id = service_token_role_membership.token_id AND\n service_token_role_membership.role_name = 'root'\n LIMIT 1",
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "key",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "expiry",
"ordinal": 2,
"type_info": "Integer"
},
{
"name": "parent_id",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "identity_id",
"ordinal": 4,
"type_info": "Text"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
true,
true,
true
]
},
"hash": "0aa5c76c9ea1692da29a0f39998946d230f92a8f252294b25afeabe05749f4ca"
}

View file

@ -1,44 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT * FROM 'service_token' WHERE key = $1 AND (expiry IS NULL OR expiry > $2) LIMIT 1",
"describe": {
"columns": [
{
"name": "id",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "key",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "expiry",
"ordinal": 2,
"type_info": "Integer"
},
{
"name": "parent_id",
"ordinal": 3,
"type_info": "Text"
},
{
"name": "identity_id",
"ordinal": 4,
"type_info": "Text"
}
],
"parameters": {
"Right": 2
},
"nullable": [
false,
false,
true,
true,
true
]
},
"hash": "2cbe2fbcd5d8fb6d489f9e3cc7e04182f226964ea9d84219abbe6958dcccfefe"
}

View file

@ -1,26 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT * FROM 'service_token_role_membership' WHERE token_id = $1",
"describe": {
"columns": [
{
"name": "role_name",
"ordinal": 0,
"type_info": "Text"
},
{
"name": "token_id",
"ordinal": 1,
"type_info": "Text"
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false
]
},
"hash": "36485bb70f499346cd1be569887ea8b6f438f4f845ef883e80d58875b839500a"
}

View file

@ -1,32 +0,0 @@
{
"db_name": "SQLite",
"query": "SELECT encrypted_key, type as protection_type, nonce FROM root_key ORDER BY version LIMIT 1",
"describe": {
"columns": [
{
"name": "encrypted_key",
"ordinal": 0,
"type_info": "Blob"
},
{
"name": "protection_type",
"ordinal": 1,
"type_info": "Text"
},
{
"name": "nonce",
"ordinal": 2,
"type_info": "Blob"
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false,
true
]
},
"hash": "5630a591626bd416be0d1ab12fa993055b521e81382897d247ceee1b41f0bf42"
}

View file

@ -1,36 +1,31 @@
{
"db_name": "SQLite",
"query": "SELECT nonce, encrypted_data, created_time, deletion_time, version_number, secret_path\n FROM kv2_secret_version WHERE engine_path = $1 AND secret_path = $2 AND deletion_time IS NULL\n ORDER BY version_number DESC LIMIT 1",
"query": "SELECT secret_data, created_time, deletion_time, version_number, secret_path\n FROM kv2_secret_version WHERE engine_path = $1 AND secret_path = $2 AND deletion_time IS NULL\n ORDER BY version_number DESC LIMIT 1",
"describe": {
"columns": [
{
"name": "nonce",
"name": "secret_data",
"ordinal": 0,
"type_info": "Blob"
},
{
"name": "encrypted_data",
"ordinal": 1,
"type_info": "Blob"
"type_info": "Text"
},
{
"name": "created_time",
"ordinal": 2,
"ordinal": 1,
"type_info": "Datetime"
},
{
"name": "deletion_time",
"ordinal": 3,
"ordinal": 2,
"type_info": "Datetime"
},
{
"name": "version_number",
"ordinal": 4,
"ordinal": 3,
"type_info": "Integer"
},
{
"name": "secret_path",
"ordinal": 5,
"ordinal": 4,
"type_info": "Text"
}
],
@ -38,7 +33,6 @@
"Right": 2
},
"nullable": [
false,
false,
false,
true,
@ -46,5 +40,5 @@
false
]
},
"hash": "b78c62fe22c4e93c54ecbc0c0cdfa31387baf14bea1ac8d27170e8b6cb456114"
"hash": "844de8351a0ed204e2080857373507389c90453b5d3ad92344272838958ab28e"
}

View file

@ -1,20 +0,0 @@
{
"db_name": "SQLite",
"query": "\nWITH latest_version AS (\n SELECT MAX(version_number) AS max_version\n FROM kv2_secret_version\n WHERE engine_path = $1 AND secret_path = $2 -- engine_path AND secret_path\n)\nINSERT INTO kv2_secret_version (engine_path, secret_path, nonce, encrypted_data, created_time, version_number)\nVALUES (\n $1, -- engine_path\n $2, -- secret_path\n $3, -- nonce\n $4, -- encrypted_data\n $5, -- created_time\n CASE -- Use provided version if given\n WHEN $6 IS NOT NULL THEN $6 -- version_number (optional)\n ELSE COALESCE((SELECT max_version FROM latest_version) + 1, 1) -- otherwise 1\n END -- version_number logic\n)\nRETURNING version_number;\n",
"describe": {
"columns": [
{
"name": "version_number",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 6
},
"nullable": [
false
]
},
"hash": "8f7bfd1840d14efec44c7b59ab10461ff122ead43076ad841883a9dd189a4f37"
}

View file

@ -1,36 +1,31 @@
{
"db_name": "SQLite",
"query": "SELECT nonce, encrypted_data, created_time, deletion_time, version_number, secret_path\n FROM kv2_secret_version WHERE engine_path = $1 AND secret_path = $2 AND deletion_time IS NULL\n AND version_number = $3",
"query": "SELECT secret_data, created_time, deletion_time, version_number, secret_path\n FROM kv2_secret_version WHERE engine_path = $1 AND secret_path = $2 AND deletion_time IS NULL\n AND version_number = $3",
"describe": {
"columns": [
{
"name": "nonce",
"name": "secret_data",
"ordinal": 0,
"type_info": "Blob"
},
{
"name": "encrypted_data",
"ordinal": 1,
"type_info": "Blob"
"type_info": "Text"
},
{
"name": "created_time",
"ordinal": 2,
"ordinal": 1,
"type_info": "Datetime"
},
{
"name": "deletion_time",
"ordinal": 3,
"ordinal": 2,
"type_info": "Datetime"
},
{
"name": "version_number",
"ordinal": 4,
"ordinal": 3,
"type_info": "Integer"
},
{
"name": "secret_path",
"ordinal": 5,
"ordinal": 4,
"type_info": "Text"
}
],
@ -38,7 +33,6 @@
"Right": 3
},
"nullable": [
false,
false,
false,
true,
@ -46,5 +40,5 @@
false
]
},
"hash": "fa8c74205ae4d497983d394ee04181c08d20cdb4a93bfce3c06a114133cd6619"
"hash": "919758dd0aee1053065d62d528bca5bbd5220b909b6c1b5eb5c77ce0dd2259e4"
}

View file

@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "\n INSERT INTO root_key (encrypted_key, type, version, nonce)\n VALUES ($1, $2, 1, $3)\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "aa131c57e0e255bfe07488095bdf25ab39e9dee182d0aecf988c9d3c2d04e66d"
}

View file

@ -0,0 +1,20 @@
{
"db_name": "SQLite",
"query": "\nWITH latest_version AS (\n SELECT MAX(version_number) AS max_version\n FROM kv2_secret_version\n WHERE engine_path = $1 AND secret_path = $2 -- engine_path AND secret_path\n)\nINSERT INTO kv2_secret_version (engine_path, secret_path, secret_data, created_time, version_number)\nVALUES (\n $1, -- engine_path\n $2, -- secret_path\n $3, -- secret_data\n $4, -- created_time\n CASE -- Use provided version if given\n WHEN $5 IS NOT NULL THEN $5 -- version_number (optional)\n ELSE COALESCE((SELECT max_version FROM latest_version) + 1, 0)\n END -- version_number logic\n)\nRETURNING version_number;\n",
"describe": {
"columns": [
{
"name": "version_number",
"ordinal": 0,
"type_info": "Integer"
}
],
"parameters": {
"Right": 5
},
"nullable": [
false
]
},
"hash": "c6beeb7d8672039df5258ada802920aae8f16db215dda5ab447dbe832f4a6703"
}

View file

@ -1,12 +0,0 @@
{
"db_name": "SQLite",
"query": "\n INSERT INTO service_token (id, key) VALUES ($1, $2);\n INSERT INTO service_token_role_membership (token_id, role_name) VALUES ($3, 'root');\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 3
},
"nullable": []
},
"hash": "fe6bf34448b9f9defc27ce30a128935d991cd06e22861086c3b1377916731e57"
}

598
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -36,8 +36,6 @@ sqlx = { version = "0.8.3", features = [
aes-gcm-siv = "0.11.1"
vsss-rs = { version = "5.1.0", optional = true, default-features = false, features = ["zeroize", "std"] }
p256 = { version = "0.13.2", optional = true, default-features = false, features = ["std", "ecdsa"] }
rand = "0.8.5"
uuid = { version = "1.16.0", features = ["v4"] }
[lints]
workspace = true

View file

@ -1,4 +1,4 @@
ARG alpine_version=3.22
ARG alpine_version=3.21
FROM docker.io/library/rust:1-alpine${alpine_version} AS builder

View file

@ -1,30 +0,0 @@
# rvault
rvault is an open-source implementation of the API of Vault and OpenBao, written in Rust.
## Running
You can run an offline build with `SQLX_OFFLINE=true cargo run` or `build`, respectively.
An offline build requires an up-to-date SQLx preparation.
An OCI container image can be created using `podman build . -t rvault`.
Furthermore, rvault attempts to read a `.env` file in the current working directory.
For example, its content could be:
```txt
DATABASE_URL=sqlite:test.db
RUST_LOG=debug
```
## Development
SQLx preparation can be updated with `cargo sqlx prep`.
Hence, it is not useful for development.
With `cargo sqlx database reset` the database will be recreated,
deleting all contents and reapplying migrations.
This is helpful when changing migrations during development.
When running a normal, not-offline, build, the database must be migrated (e.g. using `cargo sqlx database reset`)
for compilation of compile-time-checked queries.

View file

@ -1,25 +0,0 @@
CREATE TABLE identity (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL
);
CREATE TABLE service_token_role_membership (
role_name TEXT NOT NULL,
token_id TEXT NOT NULL
REFERENCES service_token(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
PRIMARY KEY (role_name, token_id)
);
CREATE TABLE service_token (
id TEXT PRIMARY KEY NOT NULL,
key TEXT NOT NULL,
expiry INTEGER,
parent_id TEXT NULL REFERENCES service_token(id)
ON DELETE NO ACTION
ON UPDATE CASCADE,
identity_id TEXT NULL REFERENCES identity(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);

View file

@ -1,14 +1,13 @@
pub mod auth_extractor;
pub(crate) mod token;
use crate::auth::token::*;
use crate::storage::DbPool;
use axum::Router;
/// Authentication routes
use crate::storage::DbPool;
// route prefix: `/auth/token/`
// mod token;
// use self::token::token_auth_router;
pub fn auth_router(pool: DbPool) -> Router<DbPool> {
// The token auth router handles all token-related authentication routes
Router::new()
.nest("/token", token_auth_router(pool.clone()))
.with_state(pool)
Router::new().with_state(pool)
// .nest("/token", token_auth_router())
}

View file

@ -1,66 +0,0 @@
use crate::auth::token::{TokenDTO, get_roles_from_token, get_token_from_key};
use crate::storage::DbPool;
use axum::body::Body;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::{HeaderMap, Request, StatusCode, header};
use std::fmt::Debug;
// Currently unused but for usage in the future
#[allow(unused)]
/// AuthInfo is an extractor that retrieves authentication information from the request.
#[derive(Debug)]
pub struct AuthInfo {
token: TokenDTO,
roles: Vec<String>,
}
impl FromRequestParts<DbPool> for AuthInfo {
type Rejection = StatusCode;
/// Extracts authentication information from the request parts.
async fn from_request_parts(
parts: &mut Parts,
state: &DbPool,
) -> Result<Self, Self::Rejection> {
let header = &parts.headers;
inspect_with_header(state, header).await
}
}
// Currently unused but for usage in the future
#[allow(unused)]
/// Extracts the headers from request and returns the result from inspect_with_header function.
pub async fn inspect_req(state: &DbPool, req: &Request<Body>) -> Result<AuthInfo, StatusCode> {
let header = req.headers();
inspect_with_header(state, header).await
}
/// Inspects the request headers and extracts authentication information.
/// Returns an `AuthInfo` struct containing the token and roles if successful.
/// If the authorization header is missing or invalid, it returns a `StatusCode::UNAUTHORIZED`.
///
/// This function is intentionally separated so it can be used from
/// within the Axum extractor as well as in other functions.
pub async fn inspect_with_header(
state: &DbPool,
header: &HeaderMap,
) -> Result<AuthInfo, StatusCode> {
let auth_header = header
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok());
match auth_header {
Some(auth_value) => {
let token = get_token_from_key(auth_value, state).await;
if token.is_err() {
return Err(StatusCode::UNAUTHORIZED);
}
let token = token.unwrap();
let roles = get_roles_from_token(&token, state).await;
Ok(AuthInfo { token, roles })
}
None => Err(StatusCode::UNAUTHORIZED),
}
}

View file

@ -1,286 +1,45 @@
// There are some placeholder functions, that will have to be implemented before the first release.
// They are marked with `todo!()` to indicate that they need to be implemented.
// We want to keep these functions in the codebase.
// That is why we choose to suppress unused warnings for now.
// TODO
#![allow(unused)]
use axum::Router;
use crate::storage::DbPool;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use log::error;
use rand::{Rng, distributions::Alphanumeric};
use serde::{Deserialize, Serialize};
use sqlx::Error;
use uuid::Uuid;
#[derive(Debug, Serialize)]
pub struct IdentityDTO {
id: String,
name: String,
}
#[derive(Debug)]
pub struct TokenDTO {
key: String,
id: String,
identity_id: Option<String>,
parent_id: Option<String>,
expiry: Option<i64>,
}
#[derive(Debug)]
pub struct TokenRoleMembershipDTO {
role_name: String,
token_id: String,
}
/// Represents a request body for the `/auth/token/lookup` endpoint.
#[derive(Deserialize)]
struct RequestBodyPostLookup {
token: String,
}
/// Represents the response body for the `/auth/token/lookup` endpoint.
#[derive(Serialize)]
struct TokenLookupResponse {
id: String,
type_name: String,
roles: Vec<String>,
}
/// Represents an error response for the API.
#[derive(Serialize)]
struct ErrorResponse {
error: String,
}
/// Generates a random string of the specified length using alphanumeric characters.
// TODO: Make string generation secure
fn get_random_string(len: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(len)
.map(char::from)
.collect()
}
/// Creates a root token if none exists in the database.
/// Returns true if a new root token was created, false if one already exists.
pub async fn create_root_token_if_none_exist(pool: &DbPool) -> bool {
// Check if a root token already exists
let exists = sqlx::query!(
r#"SELECT service_token.* FROM service_token, service_token_role_membership
WHERE service_token.id = service_token_role_membership.token_id AND
service_token_role_membership.role_name = 'root'
LIMIT 1"#
)
.fetch_one(pool)
.await
.is_ok();
if exists {
return false;
}
// If no root token exists, create one
let result = create_root_token(pool).await;
if result.is_err() {
let error = result.err().unwrap();
// Log the error and panic
error!("create_root_token failed: {error:?}");
panic!("create_root_token failed: {error:?}");
}
// If successful, print the root token. This will only happen once.
println!("\n\nYour root token is: {}", result.unwrap());
println!("It will only be displayed once!\n\n");
true
}
/// Creates a root token in the database.
async fn create_root_token(pool: &DbPool) -> Result<String, Error> {
let id = Uuid::new_v4().to_string();
let key = "s.".to_string() + &get_random_string(24);
// Insert the root token into the database
let result = sqlx::query!(r#"
INSERT INTO service_token (id, key) VALUES ($1, $2);
INSERT INTO service_token_role_membership (token_id, role_name) VALUES ($3, 'root');
"#, id, key, id).execute(pool).await;
// If the insert was successful, return the key
if result.is_ok() {
return Ok(key);
}
// Else, return the error
Err(result.unwrap_err())
}
/// Gets the current time in seconds since unix epoch
fn get_time_as_int() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64
}
/// Gets the type of token. (The first character of the key always specifies the type)
fn get_token_type(token: &TokenDTO) -> Result<String, &str> {
Ok(match token.key.clone().chars().next().unwrap_or('?') {
's' => "service",
'b' => "batch",
'r' => "recovery",
_ => {
error!("Unsupported token type");
return Err("Unsupported token type");
}
}
.to_string())
}
/// Retrieves a token from the database using its key.
/// If the token is found and not expired, it returns the token.
/// Else, it returns an error.
pub async fn get_token_from_key(token_key: &str, pool: &DbPool) -> Result<TokenDTO, Error> {
let time = get_time_as_int();
sqlx::query_as!(
TokenDTO,
r#"SELECT * FROM 'service_token' WHERE key = $1 AND (expiry IS NULL OR expiry > $2) LIMIT 1"#,
token_key, time).fetch_one(pool).await
}
/// Retrieves the roles associated with a given token from the database.
/// If the token does not exist, it returns an empty vector.
pub async fn get_roles_from_token(token: &TokenDTO, pool: &DbPool) -> Vec<String> {
let result = sqlx::query_as!(
TokenRoleMembershipDTO,
r#"SELECT * FROM 'service_token_role_membership' WHERE token_id = $1"#,
token.id
)
.fetch_all(pool)
.await;
result
.unwrap_or(Vec::new())
.iter()
.map(|r| r.role_name.to_string())
.collect()
}
/// Return a router, that may be used to route traffic to the corresponding handlers
pub fn token_auth_router(pool: DbPool) -> Router<DbPool> {
pub fn token_auth_router() -> Router {
Router::new()
.route("/lookup", post(post_lookup))
.with_state(pool)
}
/// Handles the `/auth/token/lookup` endpoint.
/// Retrieves the token and its associated roles from the database using the provided token key.
/// The output format does not yet match the openBao specification and is for testing only!
async fn post_lookup(
State(pool): State<DbPool>,
Json(body): Json<RequestBodyPostLookup>,
) -> Response {
let token_str = body.token;
// Validate the token string
match get_token_from_key(&token_str, &pool).await {
// If the token is found, retrieve its type and roles
Ok(token) => {
let type_name = get_token_type(&token).unwrap_or_else(|_| String::from("Unknown"));
let roles = get_roles_from_token(&token, &pool).await;
let resp = TokenLookupResponse {
id: token.id,
type_name,
roles,
};
// Return the token information as a JSON response
(StatusCode::OK, axum::Json(resp)).into_response()
}
// If the token is not found, return a 404 Not Found error
Err(e) => {
error!("Failed to retrieve token: {e:?}");
let err = ErrorResponse {
error: "Failed to retrieve token".to_string(),
};
(StatusCode::NOT_FOUND, axum::Json(err)).into_response()
}
}
}
async fn get_accessors() {}
//
// The following functions are placeholders for the various token-related operations.
//
async fn post_create() {}
async fn get_accessors() -> &'static str {
todo!("not implemented")
}
async fn post_create_orphan() {}
async fn post_create() -> &'static str {
todo!("not implemented")
}
async fn post_create_role() {}
async fn post_create_orphan() -> &'static str {
todo!("not implemented")
}
async fn get_lookup() {}
async fn post_create_role() -> &'static str {
todo!("not implemented")
}
async fn post_lookup() {}
async fn get_lookup() -> &'static str {
todo!("not implemented")
}
async fn get_lookup_self() {}
async fn get_lookup_self() -> &'static str {
todo!("not implemented")
}
async fn post_lookup_self() {}
async fn post_lookup_self() -> &'static str {
todo!("not implemented")
}
async fn post_renew() {}
async fn post_renew() -> &'static str {
todo!("not implemented")
}
async fn post_renew_accessor() {}
async fn post_renew_accessor() -> &'static str {
todo!("not implemented")
}
async fn post_renew_self() {}
async fn post_renew_self() -> &'static str {
todo!("not implemented")
}
async fn post_revoke() {}
async fn post_revoke() -> &'static str {
todo!("not implemented")
}
async fn post_revoke_accessor() {}
async fn post_revoke_accessor() -> &'static str {
todo!("not implemented")
}
async fn post_revoke_orphan() {}
async fn post_revoke_orphan() -> &'static str {
todo!("not implemented")
}
async fn post_revoke_self() {}
async fn post_revoke_self() -> &'static str {
todo!("not implemented")
}
async fn get_roles() {}
async fn get_roles() -> &'static str {
todo!("not implemented")
}
async fn get_role_by_name() {}
async fn get_role_by_name() -> &'static str {
todo!("not implemented")
}
async fn post_role_by_name() {}
async fn post_role_by_name() -> &'static str {
todo!("not implemented")
}
async fn delete_role_by_name() {}
async fn delete_role_by_name() -> &'static str {
todo!("not implemented")
}
async fn post_tidy() -> &'static str {
todo!("not implemented")
}
async fn post_tidy() {}

View file

@ -1,8 +1,8 @@
use axum::{
Json,
body::Body,
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
@ -13,11 +13,22 @@ pub struct HttpError {
}
impl HttpError {
pub fn multiple_errors(status_code: StatusCode, errors: Vec<String>) -> Response<Body> {
pub fn new(status_code: StatusCode, errors: Vec<String>) -> Response<Body> {
(status_code, Json(HttpError { errors })).into_response()
}
pub fn simple(status_code: StatusCode, error: impl ToString) -> Response<Body> {
HttpError::multiple_errors(status_code, vec![error.to_string(); 1])
HttpError::new(status_code, vec![error.to_string(); 1])
}
}
/// Custom serialization function for `secret_data`
pub fn serialize_reject_none<S>(value: &Option<String>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match value {
Some(data) => serializer.serialize_str(data),
None => Err(serde::ser::Error::custom("`secret_data` must not be None during serialization!")),
}
}

View file

@ -1,11 +1,11 @@
pub mod kv;
use axum::{
Extension, Router,
body::Body,
extract::{Request, State},
http::{StatusCode, Uri},
response::{IntoResponse, Response},
Extension, Router,
};
use log::*;
use tower::Service;
@ -14,7 +14,7 @@ use crate::{common::HttpError, storage::DbPool};
#[derive(Clone)]
/// State to be used to store the database pool
/// and the routers for each engine.
/// and the routers for each engine
struct EngineMapperState {
pool: DbPool,
kv_v2: Router,
@ -23,8 +23,7 @@ struct EngineMapperState {
#[derive(Clone)]
struct EnginePath(String);
/// Secret engine router.
/// Dynamically puts requests into routers depending on database content.
/// Secret engine router
pub fn secrets_router(pool: DbPool) -> Router<DbPool> {
// State containing the pool and engine routers
let state = EngineMapperState {
@ -43,7 +42,7 @@ async fn engine_handler(
req: Request,
) -> Response<Body> {
if let Some((mount_path, engine_type)) = map_mount_points(req.uri(), &engines.pool).await {
info!("Found mount point {mount_path} of type {engine_type}");
info!("Found mount point {} of type {}", mount_path, engine_type);
// Match the engine type to the appropriate router
match engine_type.as_str() {
"kv_v2" => call_router(engines.kv_v2, mount_path, req).await,
@ -73,7 +72,7 @@ async fn call_router(engine: Router, mount_path: String, mut req: Request) -> Re
/// Occurs when the mount path is found in the database
/// but the registered is unknown
fn unknown_engine(engine_type: String) -> impl IntoResponse {
error!("Engine type {engine_type} not implemented");
error!("Engine type {} not implemented", engine_type);
HttpError::simple(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Engine type {engine_type} not implemented"),

View file

@ -1,12 +1,15 @@
mod structs;
mod data;
mod meta;
mod structs;
// #[cfg(test)]
// mod tests;
use crate::storage::DbPool;
use axum::{Router, routing::*};
use axum::{
Router,
routing::*,
};
pub fn kv_router(pool: DbPool) -> Router {
Router::new()

View file

@ -1,19 +1,8 @@
// There are some placeholder functions, that will have to be implemented before the first release.
// They are marked with `todo!()` to indicate that they need to be implemented.
// We want to keep these functions in the codebase.
// That is why we choose to suppress unused warnings for now.
// TODO
#![allow(unused)]
use super::structs::KvV2WriteRequest;
use crate::{
DbPool,
common::HttpError,
engines::{
EnginePath,
kv::structs::{KvSecretData, KvSecretRes, KvV2WriteResponse, Wrapper},
},
storage::sealing::Secret,
common::HttpError, engines::{
kv::structs::{KvSecretData, KvSecretRes, KvV2WriteResponse, Wrapper}, EnginePath
}, storage::sealing::Secret, DbPool
};
use axum::{
Extension, Json,
@ -132,10 +121,7 @@ pub async fn post_data(
let content = serde_json::to_string(&secret.data).unwrap();
let Secret {
nonce,
protected_data,
} = Secret::encrypt(&content).await.unwrap();
let Secret { nonce, protected_data } = Secret::encrypt(&content).await.unwrap();
let nonce = nonce.as_slice();
let mut tx = pool.begin().await.unwrap();
@ -248,6 +234,7 @@ pub async fn patch_data(
Path(kv_path): Path<String>,
Extension(EnginePath(engine_path)): Extension<EnginePath>,
Json(secret): Json<KvV2WriteRequest>,
) -> &'static str {
todo!("not implemented")
) -> Result<Response, ()> {
// TODO: implement only application/merge-patch+json
todo!("Not implemented")
}

View file

@ -1,10 +1,3 @@
// There are some placeholder functions, that will have to be implemented before the first release.
// They are marked with `todo!()` to indicate that they need to be implemented.
// We want to keep these functions in the codebase.
// That is why we choose to suppress unused warnings for now.
// TODO
#![allow(unused)]
use crate::storage::DbPool;
use axum::extract::{Path, State};

View file

@ -1,9 +1,3 @@
// There are some placeholder functions, that will have to be implemented before the first release.
// They are marked with `todo!()` to indicate that they need to be implemented.
// We want to keep these functions in the codebase.
// That is why we choose to suppress unused warnings for now.
#![allow(unused)]
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, vec};
use time::{OffsetDateTime, UtcDateTime, serde::rfc3339};

66
src/engines/kv/tests.rs Normal file
View file

@ -0,0 +1,66 @@
use std::collections::HashMap;
use chrono::Utc;
use tests::{
logic::patch_metadata,
structs::{SecretMeta, VersionMeta},
};
use super::*;
#[test]
#[cfg(target_feature = "_disabled")]
fn print_serialized_test() {
let temp_secret = TempSecret {
content: String::from("Hallo"),
version: 12,
};
let serialized = serialize_secret_json(&temp_secret);
println!("string serialized: {:?}", serialized);
let deserialized = deserialize_secret_struct(&serialized.unwrap());
println!(
"Struct field from deserialized: {}",
deserialized.unwrap().content
)
}
#[test]
#[cfg(target_feature = "_disabled")]
fn test_patching() {
// TODO add more assertions
let mut base = create_mock_meta();
println!("OLD metadata: {:?}", base);
let overwrite: SecretMeta = SecretMeta {
max_versions: 10,
versions: vec![VersionMeta {
created_time: Utc::now(),
deletion_time: Some(Utc::now()),
destroyed: true,
}],
cas_required: true,
delete_version_after: "10m".to_string(),
current_version: 4,
oldest_version: 2,
updated_time: Utc::now(),
created_time: Utc::now(),
custom_metadata: Some(HashMap::new()),
};
let mut patched: Option<SecretMeta> = None; // Laurenz here
match patch_metadata(&mut base, &overwrite) {
Ok(meta) => {
println!("NEW metadata: {:?}", meta);
println!("patched successfully");
patched = Some(meta);
}
Err(e) => {
log::error!("error patching metadata: {}", e);
panic!("Patching failed");
}
}
if let Some(patched_meta) = patched {
assert!(patched_meta.current_version == 4);
assert!(patched_meta.versions[0].destroyed == true);
} else {
panic!("patched was not initialized");
}
}

View file

@ -1,12 +1,5 @@
#![forbid(unsafe_code)]
// // There are some placeholder functions, that will have to be implemented before the first release.
// // They are marked with `todo!()` to indicate that they need to be implemented.
// // We want to keep these functions in the codebase.
// // That is why we choose to suppress unused warnings for now.
// #![allow(unused)]
use crate::common::HttpError;
use axum::{
Router,
extract::Request,
@ -20,6 +13,8 @@ use std::{env, net::SocketAddr, str::FromStr};
use storage::DbPool;
use tokio::{net::TcpListener, signal};
use crate::common::HttpError;
mod auth;
mod common;
mod engines;
@ -29,8 +24,11 @@ mod sys;
#[tokio::main]
async fn main() {
// NOTE: Rethink choice of environment variables in regards to security in the future
let _ = dotenvy::dotenv();
// To be configured via environment variables
// choose from (highest to lowest): error, warn, info, debug, trace, off
// env::set_var("RUST_LOG", "trace"); // TODO: Remove to respect user configuration
// env::set_var("DATABASE_URL", "sqlite:test.db"); // TODO: move to .env
env_logger::init();
// Listen on all IPv4 and IPv6 interfaces on port 8200 by default
@ -56,8 +54,6 @@ async fn main() {
storage::sealing::init_default(&pool).await;
}
auth::token::create_root_token_if_none_exist(&pool).await;
warn!("Listening on {listen_addr}");
// Start listening
let listener = TcpListener::bind(listen_addr).await.unwrap();
@ -67,15 +63,13 @@ async fn main() {
.unwrap();
}
/// Middleware setting unspecified `Content-Type`s to json since this is done by client libraries.
/// Axum's [axum::extract::Json] rejects extraction attempts without json content type.
async fn set_default_content_type_json(
mut req: Request,
next: Next,
) -> Result<impl IntoResponse, Response> {
if req.headers().get("content-type").is_none() {
let headers = req.headers_mut();
// debug!("Request header: \n{:?}", headers);
headers.insert("content-type", "application/json".parse().unwrap());
}
@ -109,7 +103,6 @@ async fn shutdown_signal(pool: DbPool) {
}
/// Fallback route for unknown routes
///
/// Note: `/v1/*` is handled by [`engines::secrets_router`]
async fn fallback_route_unknown(req: Request) -> Response {
log::error!(
@ -122,7 +115,7 @@ async fn fallback_route_unknown(req: Request) -> Response {
HttpError::simple(StatusCode::NOT_FOUND, "Route not implemented")
}
/// Basic handler that responds with a static string
/// basic handler that responds with a static string
async fn root() -> &'static str {
info!("Hello world");
"Hello, World!"

View file

@ -3,18 +3,11 @@ pub mod sealing;
use std::{fs::File, path::Path};
use log::*;
use sqlx::{Pool, Sqlite, sqlite::SqlitePoolOptions};
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
pub(crate) type DbType = Sqlite;
pub(crate) type DbPool = Pool<DbType>;
/// Creates a SQLx SQLite database pool.
/// If nonexistent, it creates a new SQLite file.
///
/// Note: rvault uses compile-time queries.
/// Hence, during development a migrated SQLite file is required.
/// Use `cargo sqlx database reset` if required.
/// Otherwise, set the env var `SQLX_OFFLINE=true` during compilation (not helpful for development).
pub async fn create_pool(db_url: String) -> DbPool {
// Create SQLite database file if it does not exist
if db_url.starts_with("sqlite:") && db_url != ("sqlite::memory:") {

View file

@ -212,6 +212,10 @@ impl Secret {
/// Encrypt a secret
///
/// # Panics
///
/// Panics if .
///
/// # Errors
///
/// This function will return an error if the vault is uninitialized or an unknown error occurs.
@ -317,11 +321,11 @@ pub async fn init_default(pool: &DbPool) {
#[cfg(feature = "shamir")]
{
shamir::init_shamir(pool, 2, 5).await
shamir::init_shamir(&pool, 2, 5).await
}
};
let success = prepare_unseal(pool).await;
let success = prepare_unseal(&pool).await;
warn!("New sealing password generated: {user_key:?}");
assert!(
success,

View file

@ -15,7 +15,7 @@ use zeroize::ZeroizeOnDrop;
use crate::DbPool;
use super::{Sealing, UnsealResult, write_new_root_key};
use super::{write_new_root_key, Sealing, UnsealResult};
type P256Share = DefaultShare<IdentifierPrimeField<Scalar>, IdentifierPrimeField<Scalar>>;
@ -29,8 +29,6 @@ struct ShamirPortion {
}
#[derive(PartialEq)]
/// Container for multiple [ShamirPortion]s and the protected root key.
/// Multiple instances could exist in the future for per-namespace encryption.
pub struct ShamirBucket {
portions: Vec<ShamirPortion>,
protected_rk: Vec<u8>,
@ -38,7 +36,7 @@ pub struct ShamirBucket {
}
impl Sealing for ShamirBucket {
fn new(protected_rk: Vec<u8>, nonce: Vec<u8>) -> Self {
fn new(protected_rk: Vec<u8>, nonce: Vec<u8>) -> Self {
Self {
portions: Vec::with_capacity(2),
protected_rk,
@ -46,7 +44,7 @@ impl Sealing for ShamirBucket {
}
}
async fn unseal(&mut self, key: String) -> UnsealResult {
async fn unseal(&mut self, key: String) -> UnsealResult {
let key = match BASE64_STANDARD.decode(key) {
Ok(v) => v,
Err(e) => {
@ -68,7 +66,7 @@ impl Sealing for ShamirBucket {
}
self.portions.push(key_portion);
let joined_keys = match join_keys(&self.portions) {
let abc = match join_keys(&self.portions) {
Ok(v) => v,
Err(e) => {
return match e {
@ -86,7 +84,7 @@ impl Sealing for ShamirBucket {
}
.to_bytes();
let cipher = match Aes256GcmSiv::new_from_slice(&joined_keys) {
let cipher = match Aes256GcmSiv::new_from_slice(&abc) {
Ok(v) => v,
Err(e) => {
info!("Cipher could not be created from slice: {e}");

View file

@ -6,7 +6,7 @@ use base64::{Engine, prelude::BASE64_STANDARD};
use crate::DbPool;
use super::{Sealing, UnsealResult, write_new_root_key};
use super::{write_new_root_key, Sealing, UnsealResult};
/// Pair of protected root key and nonce
#[derive(PartialEq)]
@ -26,7 +26,6 @@ impl Sealing for SimpleSealing {
}
}
/// Initialize the vault with a simple password
#[allow(unused)]
pub async fn init_simple(pool: &DbPool) -> String {
let root_key = Aes256GcmSiv::generate_key(&mut OsRng);

View file

@ -5,10 +5,8 @@ use crate::DbPool;
pub fn root_generation() -> Router<DbPool> {
Router::new()
// .route("/generate-root", get(get_root_generation_attempt))
// .route("/generate-root", delete(cancel_generate_root))
.route("/generate-root", post(generate_new_root))
// .route("/generate-root", delete(cancel_generate_root))
}
async fn generate_new_root() {
todo!()
}
async fn generate_new_root() {}

View file

@ -1,7 +1,5 @@
use axum::{
Json, Router,
extract::State,
routing::{get, post, put},
extract::State, routing::{get, post, put}, Json, Router
};
use log::warn;
use serde::Deserialize;
@ -13,7 +11,7 @@ pub fn sealing_routes() -> Router<DbPool> {
.route("/seal", post(seal_post))
.route("/seal-status", get(seal_status_get))
.route("/unseal", post(unseal_post))
// Again? Its supposed to be POST but actually a PUT
// WTF? Again? Its supposed to be POST but actually a PUT
.route("/unseal", put(unseal_post))
}
@ -49,6 +47,4 @@ async fn unseal_post(State(pool): State<DbPool>, Json(req): Json<UnsealRequest>)
Ok(())
}
async fn seal_status_get(State(_pool): State<DbPool>) -> &'static str {
todo!("not implemented")
}
async fn seal_status_get(State(pool): State<DbPool>) {}