Compare commits

...

4 Commits

Author SHA1 Message Date
99390ce8b7 tsk-50: Create Special endpoint for services to obtain a token (#53)
All checks were successful
Rust Build / Check (push) Successful in 32s
Release Tagging / release (push) Successful in 51s
Rust Build / Rustfmt (push) Successful in 25s
Rust Build / build (push) Successful in 42s
Rust Build / Check (pull_request) Successful in 36s
Rust Build / Clippy (push) Successful in 2m2s
Rust Build / Test Suite (pull_request) Successful in 42s
Rust Build / Rustfmt (pull_request) Successful in 32s
Rust Build / Clippy (pull_request) Successful in 37s
Rust Build / Test Suite (push) Successful in 3m57s
Rust Build / build (pull_request) Successful in 3m14s
Reviewed-on: #53
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-08-03 23:09:50 +00:00
5967ed5b13 minor refactoring (#52)
All checks were successful
Release Tagging / release (push) Successful in 35s
Rust Build / Check (push) Successful in 37s
Rust Build / Rustfmt (push) Successful in 27s
Rust Build / Test Suite (push) Successful in 41s
Rust Build / build (push) Successful in 46s
Rust Build / Clippy (push) Successful in 1m46s
Rust Build / Check (pull_request) Successful in 37s
Rust Build / Rustfmt (pull_request) Successful in 28s
Rust Build / Test Suite (pull_request) Successful in 39s
Rust Build / build (pull_request) Successful in 45s
Rust Build / Clippy (pull_request) Successful in 1m44s
Reviewed-on: #52
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-08-01 20:49:15 +00:00
be4d1109a7 Update rust in docker (#48)
Some checks failed
Release Tagging / release (push) Successful in 29s
Rust Build / Check (push) Successful in 36s
Rust Build / Test Suite (push) Successful in 45s
Rust Build / Rustfmt (push) Successful in 27s
Rust Build / Clippy (push) Successful in 35s
Rust Build / build (push) Successful in 59s
Rust Build / Check (pull_request) Failing after 44s
Rust Build / Test Suite (pull_request) Failing after 1m17s
Rust Build / Rustfmt (pull_request) Failing after 39s
Rust Build / Clippy (pull_request) Failing after 38s
Rust Build / build (pull_request) Failing after 37s
Reviewed-on: #48
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-07-13 23:01:16 +00:00
4353414c69 Upgrade postgresql (#47)
All checks were successful
Rust Build / Check (push) Successful in 36s
Rust Build / Test Suite (push) Successful in 49s
Rust Build / Rustfmt (push) Successful in 29s
Rust Build / Clippy (push) Successful in 40s
Rust Build / build (push) Successful in 1m4s
Release Tagging / release (push) Successful in 30s
Rust Build / Check (pull_request) Successful in 39s
Rust Build / Test Suite (pull_request) Successful in 46s
Rust Build / Rustfmt (pull_request) Successful in 25s
Rust Build / Clippy (pull_request) Successful in 37s
Rust Build / build (pull_request) Successful in 56s
Reviewed-on: #47

Closes #46

Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-07-12 19:32:56 +00:00
15 changed files with 202 additions and 80 deletions

View File

@@ -1,4 +1,5 @@
SECRET_KEY=refero34o8rfhfjn983thf39fhc943rf923n3h
SERVICE_PASSPHRASE=iUOo1fxshf3y1tUGn1yU8l9raPApHCdinW0VdCHdRFEjqhR3Bf02aZzsKbLtaDFH
POSTGRES_AUTH_USER=icarus_op
POSTGRES_AUTH_PASSWORD=password
POSTGRES_AUTH_DB=icarus_auth_db

View File

@@ -1,4 +1,5 @@
SECRET_KEY=refero34o8rfhfjn983thf39fhc943rf923n3h
SERVICE_PASSPHRASE=iUOo1fxshf3y1tUGn1yU8l9raPApHCdinW0VdCHdRFEjqhR3Bf02aZzsKbLtaDFH
POSTGRES_AUTH_USER=icarus_op_test
POSTGRES_AUTH_PASSWORD=password
POSTGRES_AUTH_DB=icarus_auth_test_db

View File

@@ -49,5 +49,3 @@ jobs:
release_name: Release ${{ steps.version.outputs.project_tag_release }}
body: |
Release of version ${{ steps.version.outputs.project_tag_release }}
# draft: false
# prerelease: ${{ startsWith(github.ref, 'v') == false }} # prerelease if not a valid release tag

View File

@@ -36,7 +36,7 @@ jobs:
# --- Add database service definition ---
services:
postgres:
image: postgres:17.4 # Or pin to a more specific version like 14.9
image: postgres:17.5
env:
# Use secrets for DB init, with fallbacks for flexibility
POSTGRES_USER: ${{ secrets.DB_TEST_USER || 'testuser' }}

11
Cargo.lock generated
View File

@@ -728,7 +728,7 @@ dependencies = [
[[package]]
name = "icarus_auth"
version = "0.4.0"
version = "0.4.2"
dependencies = [
"argon2",
"axum",
@@ -752,8 +752,8 @@ dependencies = [
[[package]]
name = "icarus_envy"
version = "0.3.0"
source = "git+ssh://git@git.kundeng.us/phoenix/icarus_envy.git?tag=v0.3.0-devel-d73fba9899-006#d73fba9899372b0655a90cb426645930135152da"
version = "0.3.1"
source = "git+ssh://git@git.kundeng.us/phoenix/icarus_envy.git?tag=v0.3.1-main-3cd42dab6b-006#3cd42dab6b2503609883f5f57ad3508755c34a2e"
dependencies = [
"const_format",
"dotenvy",
@@ -761,9 +761,10 @@ dependencies = [
[[package]]
name = "icarus_models"
version = "0.5.0"
source = "git+ssh://git@git.kundeng.us/phoenix/icarus_models.git?tag=v0.5.0-devel-7958b89abc-111#7958b89abc56bc9262015b3e201ea2906cc8a9ff"
version = "0.5.4"
source = "git+ssh://git@git.kundeng.us/phoenix/icarus_models.git?tag=v0.5.4-devel-1e95822b5a-111#1e95822b5a349bd73cc501d921052f289105ec55"
dependencies = [
"josekit",
"rand 0.9.1",
"serde",
"serde_json",

View File

@@ -1,6 +1,6 @@
[package]
name = "icarus_auth"
version = "0.4.0"
version = "0.4.2"
edition = "2024"
rust-version = "1.88"
@@ -18,8 +18,8 @@ argon2 = { version = "0.5.3", features = ["std"] } # Use the latest 0.5.x versio
rand = { version = "0.9.1" }
time = { version = "0.3.41", features = ["macros", "serde"] }
josekit = { version = "0.10.3" }
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.5.0-devel-7958b89abc-111" }
icarus_envy = { git = "ssh://git@git.kundeng.us/phoenix/icarus_envy.git", tag = "v0.3.0-devel-d73fba9899-006" }
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.5.4-devel-1e95822b5a-111" }
icarus_envy = { git = "ssh://git@git.kundeng.us/phoenix/icarus_envy.git", tag = "v0.3.1-main-3cd42dab6b-006" }
[dev-dependencies]
http-body-util = { version = "0.1.3" }

View File

@@ -1,7 +1,7 @@
# Stage 1: Build the application
# Use a specific Rust version for reproducibility. Choose one that matches your development environment.
# Using slim variant for smaller base image
FROM rust:1.86 as builder
FROM rust:1.88 as builder
# Set the working directory inside the container
WORKDIR /usr/src/app

View File

@@ -19,7 +19,7 @@ services:
# PostgreSQL Database Service
auth_db:
image: postgres:17.4-alpine # Use an official Postgres image (Alpine variant is smaller)
image: postgres:17.5-alpine # Use an official Postgres image (Alpine variant is smaller)
container_name: icarus_auth_db # Optional: Give the container a specific name
environment:
# These MUST match the user, password, and database name in the DATABASE_URL above

View File

@@ -20,3 +20,9 @@ CREATE TABLE IF NOT EXISTS "salt" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
salt TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS "passphrase" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
passphrase TEXT NOT NULL,
date_created TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

View File

@@ -0,0 +1,2 @@
-- Add migration script here
INSERT INTO "passphrase" (passphrase) VALUES('iUOo1fxshf3y1tUGn1yU8l9raPApHCdinW0VdCHdRFEjqhR3Bf02aZzsKbLtaDFH');

View File

@@ -6,6 +6,13 @@ pub mod request {
pub username: String,
pub password: String,
}
pub mod service_login {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Request {
pub passphrase: String,
}
}
}
pub mod response {
@@ -16,6 +23,14 @@ pub mod response {
pub message: String,
pub data: Vec<icarus_models::login_result::LoginResult>,
}
pub mod service_login {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::login_result::LoginResult>,
}
}
}
pub mod endpoint {
@@ -62,7 +77,7 @@ pub mod endpoint {
id: user.id,
username: user.username.clone(),
token: token_literal,
token_type: String::from(token_stuff::TOKENTYPE),
token_type: String::from(icarus_models::token::TOKEN_TYPE),
expiration: duration,
}],
}),
@@ -79,4 +94,42 @@ pub mod endpoint {
}
}
}
pub async fn service_login(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<request::service_login::Request>,
) -> (
axum::http::StatusCode,
axum::Json<response::service_login::Response>,
) {
let mut response = response::service_login::Response::default();
match repo::service::valid_passphrase(&pool, &payload.passphrase).await {
Ok((id, _passphrase, _date_created)) => {
let key = icarus_envy::environment::get_secret_key().await;
let (token_literal, duration) = token_stuff::create_service_token(&key).unwrap();
if token_stuff::verify_token(&key, &token_literal) {
let login_result = icarus_models::login_result::LoginResult {
id,
username: String::from("service"),
token: token_literal,
token_type: String::from(icarus_models::token::TOKEN_TYPE),
expiration: duration,
};
response.data.push(login_result);
response.message = String::from("Successful");
(axum::http::StatusCode::OK, axum::Json(response))
} else {
(axum::http::StatusCode::OK, axum::Json(response))
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
}

View File

@@ -7,4 +7,5 @@ pub mod endpoints {
pub const REGISTER: &str = "/api/v2/register";
pub const DBTEST: &str = "/api/v2/test/db";
pub const LOGIN: &str = "/api/v2/login";
pub const SERVICE_LOGIN: &str = "/api/v2/service/login";
}

View File

@@ -41,6 +41,10 @@ mod init {
callers::endpoints::LOGIN,
post(callers::login::endpoint::login),
)
.route(
callers::endpoints::SERVICE_LOGIN,
post(callers::login::endpoint::service_login),
)
}
pub async fn app() -> Router {
@@ -154,6 +158,25 @@ mod tests {
})
}
pub mod requests {
use tower::ServiceExt; // for `call`, `oneshot`, and `ready`
pub async fn register(
app: &axum::Router,
usr: &icarus_auth::callers::register::request::Request,
) -> Result<axum::response::Response, std::convert::Infallible> {
let payload = super::get_test_register_payload(&usr);
let req = axum::http::Request::builder()
.method(axum::http::Method::POST)
.uri(crate::callers::endpoints::REGISTER)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string()))
.unwrap();
app.clone().oneshot(req).await
}
}
#[tokio::test]
async fn test_hello_world() {
let app = init::app().await;
@@ -198,18 +221,8 @@ mod tests {
let app = init::routes().await.layer(axum::Extension(pool));
let usr = get_test_register_request();
let payload = get_test_register_payload(&usr);
let response = app
.oneshot(
Request::builder()
.method(axum::http::Method::POST)
.uri(callers::endpoints::REGISTER)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(Body::from(payload.to_string()))
.unwrap(),
)
.await;
let response = requests::register(&app, &usr).await;
match response {
Ok(resp) => {
@@ -265,19 +278,8 @@ mod tests {
let app = init::routes().await.layer(axum::Extension(pool));
let usr = get_test_register_request();
let payload = get_test_register_payload(&usr);
let response = app
.clone()
.oneshot(
Request::builder()
.method(axum::http::Method::POST)
.uri(callers::endpoints::REGISTER)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(Body::from(payload.to_string()))
.unwrap(),
)
.await;
let response = requests::register(&app, &usr).await;
match response {
Ok(resp) => {
@@ -341,4 +343,58 @@ mod tests {
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
#[tokio::test]
async fn test_service_login_user() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(e) => {
assert!(false, "Error: {:?}", e.to_string());
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
icarus_auth::db::migrations(&pool).await;
let app = init::routes().await.layer(axum::Extension(pool));
let passphrase =
String::from("iUOo1fxshf3y1tUGn1yU8l9raPApHCdinW0VdCHdRFEjqhR3Bf02aZzsKbLtaDFH");
let payload = serde_json::json!({
"passphrase": passphrase
});
match app
.oneshot(
Request::builder()
.method(axum::http::Method::POST)
.uri(callers::endpoints::SERVICE_LOGIN)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(Body::from(payload.to_string()))
.unwrap(),
)
.await
{
Ok(response) => {
assert_eq!(StatusCode::OK, response.status(), "Status is not right");
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let parsed_body: callers::login::response::service_login::Response =
serde_json::from_slice(&body).unwrap();
let _login_result = &parsed_body.data[0];
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
}

View File

@@ -195,3 +195,32 @@ pub mod salt {
}
}
}
pub mod service {
use sqlx::Row;
pub async fn valid_passphrase(
pool: &sqlx::PgPool,
passphrase: &String,
) -> Result<(uuid::Uuid, String, time::OffsetDateTime), sqlx::Error> {
let result = sqlx::query(
r#"
SELECT * FROM "passphrase" WHERE passphrase = $1
"#,
)
.bind(passphrase)
.fetch_one(pool)
.await;
match result {
Ok(row) => {
let id: uuid::Uuid = row.try_get("id")?;
let passphrase: String = row.try_get("passphrase")?;
let date_created: Option<time::OffsetDateTime> = row.try_get("date_created")?;
Ok((id, passphrase, date_created.unwrap()))
}
Err(err) => Err(err),
}
}
}

View File

@@ -1,12 +1,11 @@
use josekit::{
self,
jws::{JwsHeader, alg::hmac::HmacJwsAlgorithm::Hs256},
jwt::{self, JwtPayload},
jws::alg::hmac::HmacJwsAlgorithm::Hs256,
jwt::{self},
};
use time;
pub const TOKENTYPE: &str = "JWT";
pub const KEY_ENV: &str = "SECRET_KEY";
pub const MESSAGE: &str = "Something random";
pub const ISSUER: &str = "icarus_auth";
@@ -21,46 +20,22 @@ pub fn get_expiration(issued: &time::OffsetDateTime) -> Result<time::OffsetDateT
Ok(*issued + duration_expire)
}
mod util {
pub fn time_to_std_time(
provided_time: &time::OffsetDateTime,
) -> Result<std::time::SystemTime, std::time::SystemTimeError> {
let converted = std::time::SystemTime::from(*provided_time);
Ok(converted)
}
pub fn create_token(provided_key: &String) -> Result<(String, i64), josekit::JoseError> {
let resource = icarus_models::token::TokenResource {
message: String::from(MESSAGE),
issuer: String::from(ISSUER),
audiences: vec![String::from(AUDIENCE)],
};
icarus_models::token::create_token(provided_key, &resource, time::Duration::hours(4))
}
pub fn create_token(provided_key: &String) -> Result<(String, i64), josekit::JoseError> {
let mut header = JwsHeader::new();
header.set_token_type(TOKENTYPE);
let mut payload = JwtPayload::new();
payload.set_subject(MESSAGE);
payload.set_issuer(ISSUER);
payload.set_audience(vec![AUDIENCE]);
match get_issued() {
Ok(issued) => {
let expire = get_expiration(&issued).unwrap();
payload.set_issued_at(&util::time_to_std_time(&issued).unwrap());
payload.set_expires_at(&util::time_to_std_time(&expire).unwrap());
let key: String = if provided_key.is_empty() {
let rt = tokio::runtime::Runtime::new().unwrap();
// Block on the async function to get the result
rt.block_on(icarus_envy::environment::get_secret_key())
} else {
provided_key.to_owned()
};
let signer = Hs256.signer_from_bytes(key.as_bytes()).unwrap();
Ok((
josekit::jwt::encode_with_signer(&payload, &header, &signer).unwrap(),
(expire - time::OffsetDateTime::UNIX_EPOCH).whole_seconds(),
))
}
Err(e) => Err(josekit::JoseError::InvalidClaim(e.into())),
}
pub fn create_service_token(provided: &String) -> Result<(String, i64), josekit::JoseError> {
let resource = icarus_models::token::TokenResource {
message: String::from("Service random"),
issuer: String::from(ISSUER),
audiences: vec![String::from(AUDIENCE)],
};
icarus_models::token::create_token(provided, &resource, time::Duration::hours(1))
}
pub fn verify_token(key: &String, token: &String) -> bool {
@@ -74,7 +49,6 @@ pub fn verify_token(key: &String, token: &String) -> bool {
#[cfg(test)]
mod tests {
use super::*;
#[test]