Added basic service token functionality and root token creation.
This commit is contained in:
parent
d77237aefe
commit
27dcc5489d
6 changed files with 160 additions and 5 deletions
11
Cargo.lock
generated
11
Cargo.lock
generated
|
|
@ -1725,12 +1725,14 @@ dependencies = [
|
|||
"env_logger",
|
||||
"log",
|
||||
"p256",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
"time",
|
||||
"tokio",
|
||||
"tower",
|
||||
"uuid",
|
||||
"vsss-rs",
|
||||
"zeroize",
|
||||
]
|
||||
|
|
@ -2457,6 +2459,15 @@ version = "0.2.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
|
||||
dependencies = [
|
||||
"getrandom 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@ 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
|
||||
|
|
|
|||
25
migrations/20250407112735_BasicIdentity.sql
Normal file
25
migrations/20250407112735_BasicIdentity.sql
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
CREATE TABLE identity (
|
||||
id TEXT PRIMARY KEY,
|
||||
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,
|
||||
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
|
||||
);
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
use axum::Router;
|
||||
pub(crate) mod token;
|
||||
|
||||
use axum::Router;
|
||||
use crate::auth::token::*;
|
||||
use crate::storage::DbPool;
|
||||
|
||||
// route prefix: `/auth/token/`
|
||||
|
|
@ -8,6 +10,6 @@ use crate::storage::DbPool;
|
|||
// use self::token::token_auth_router;
|
||||
|
||||
pub fn auth_router(pool: DbPool) -> Router<DbPool> {
|
||||
Router::new().with_state(pool)
|
||||
Router::new().nest("/token", token_auth_router(pool.clone())).with_state(pool)
|
||||
// .nest("/token", token_auth_router())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,121 @@
|
|||
use axum::Router;
|
||||
use std::ops::Index;
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::{Json, Router};
|
||||
use axum::response::{IntoResponse, NoContent, Response};
|
||||
use axum::routing::post;
|
||||
use log::error;
|
||||
use serde::Deserialize;
|
||||
use sqlx::Error;
|
||||
use rand::{distributions::Alphanumeric, Rng};
|
||||
use uuid::Uuid;
|
||||
use crate::storage::DbPool;
|
||||
|
||||
pub fn token_auth_router() -> Router {
|
||||
enum TokenType {
|
||||
|
||||
}
|
||||
|
||||
struct Identity {
|
||||
id: String,
|
||||
name: String
|
||||
}
|
||||
|
||||
struct Token {
|
||||
key: Option<String>,
|
||||
id: Option<String>,
|
||||
identity_id: Option<String>,
|
||||
parent_id: Option<String>,
|
||||
expiry: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RequestBodyPostLookup {
|
||||
token: String,
|
||||
}
|
||||
|
||||
// TODO: Make string generation secure
|
||||
fn get_random_string(len: usize) -> String {
|
||||
rand::thread_rng()
|
||||
.sample_iter(&Alphanumeric)
|
||||
.take(len)
|
||||
.map(char::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Returns if a token was created or not. Prints out the created token to the console.
|
||||
pub async fn create_root_token_if_none_exist(pool: &DbPool) -> bool {
|
||||
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;
|
||||
}
|
||||
let result = create_root_token(pool).await;
|
||||
if result.is_err() {
|
||||
let error = result.err().unwrap();
|
||||
error!("create_root_token failed: {:?}", error);
|
||||
panic!("create_root_token failed: {:?}", error);
|
||||
}
|
||||
println!("\n\nYour root token is: {}", result.unwrap());
|
||||
println!("It will only be displayed once!\n\n");
|
||||
true
|
||||
}
|
||||
|
||||
// Return the token key if successful
|
||||
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);
|
||||
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 result.is_ok() {
|
||||
return Ok(key);
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
fn get_token_type(token: &Token) -> Result<String, &str> {
|
||||
Ok(match token.key.clone().unwrap().chars().next().unwrap_or('?') {
|
||||
's' => "service",
|
||||
'b' => "batch",
|
||||
'r' => "recovery",
|
||||
_ => {
|
||||
error!("Unsupported token type");
|
||||
return Err("Unsupported token type");
|
||||
}
|
||||
}.to_string())
|
||||
}
|
||||
|
||||
async fn get_token_from_key(token_key: &str, pool: &DbPool) -> Result<Token, Error> {
|
||||
let time = get_time_as_int();
|
||||
sqlx::query_as!(
|
||||
Token,
|
||||
r#"SELECT id, key, expiry, parent_id, identity_id FROM 'service_token' WHERE key = $1 AND (expiry = NULL OR expiry > $2) LIMIT 1"#,
|
||||
token_key, time).fetch_one(pool).await
|
||||
}
|
||||
|
||||
pub fn token_auth_router(pool: DbPool) -> Router<DbPool> {
|
||||
Router::new()
|
||||
.route("/lookup", post(post_lookup))
|
||||
.with_state(pool)
|
||||
}
|
||||
|
||||
|
||||
async fn post_lookup(
|
||||
State(pool): State<DbPool>,
|
||||
Json(body): Json<RequestBodyPostLookup>
|
||||
) -> Result<Response, ()> {
|
||||
let token = body.token;
|
||||
|
||||
Ok(IntoResponse::into_response(token))
|
||||
}
|
||||
|
||||
async fn get_accessors() {}
|
||||
|
|
@ -14,7 +128,6 @@ async fn post_create_role() {}
|
|||
|
||||
async fn get_lookup() {}
|
||||
|
||||
async fn post_lookup() {}
|
||||
|
||||
async fn get_lookup_self() {}
|
||||
|
||||
|
|
|
|||
|
|
@ -54,6 +54,8 @@ 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();
|
||||
|
|
|
|||
Loading…
Reference in a new issue