This commit is contained in:
Alvin-Zilverstand committed 2026-11-22 02:02:18 +01:00
1 parent 9268833a3c
commit 314b7445a1
27 files changed
+1830

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
[package]
name = "chronos-api"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
axum = "0.7"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
tracing-subscriber = "0.3"
utoipa = { version = "4.0", features = ["axum_extras"] }
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
chronos-auth = { path = "../chronos-auth" }
chronos-database = { path = "../chronos-database" }
+22
View File
@@ -0,0 +1,22 @@
use chronos_auth::{AuthService, AuthError};
use chronos_core::User;
use sqlx::PgPool;
/// API authentication middleware
pub struct AuthMiddleware {
auth_service: AuthService,
}
impl AuthMiddleware {
pub fn new(pool: PgPool) -> Self {
AuthMiddleware {
auth_service: AuthService::new(pool),
}
}
/// Verify that a request has valid authentication
pub async fn verify_auth(&self, token: &str) -> Result<User, AuthError> {
let session = self.auth_service.validate_session(token).await?;
self.auth_service.get_user_by_username(&session.user_id.to_string()).await
}
}
+4
View File
@@ -0,0 +1,4 @@
// Simple test to make sure the workspace builds correctly
fn main() {
println!("Chronos workspace initialized successfully");
}
+100
View File
@@ -0,0 +1,100 @@
use axum::{
extract::State,
http::StatusCode,
response::IntoResponse,
Json,
};
use serde::{Deserialize, Serialize};
use chronos_auth::{AuthService, AuthError};
use chronos_core::{User, Role};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginRequest {
pub username: String,
pub password: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginResponse {
pub token: String,
}
/// Handle user login
pub async fn login(
State(auth_service): State<AuthService>,
Json(request): Json<LoginRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
let user = auth_service.authenticate(&request.username, &request.password)
.await
.map_err(|e| handle_auth_error(e))?;
let session = auth_service.create_session(user.id)
.await
.map_err(|e| handle_auth_error(e))?;
Ok(Json(LoginResponse {
token: session.token,
}))
}
/// Handle user logout
pub async fn logout(
State(auth_service): State<AuthService>,
token: String,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
auth_service.logout(&token)
.await
.map_err(|e| handle_auth_error(e))?;
Ok(StatusCode::NO_CONTENT)
}
/// Get current user info
pub async fn get_current_user(
State(auth_service): State<AuthService>,
token: String,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
let session = auth_service.validate_session(&token)
.await
.map_err(|e| handle_auth_error(e))?;
let user = auth_service.get_user_by_username(&session.user_id.to_string())
.await
.map_err(|e| handle_auth_error(e))?;
Ok(Json(user))
}
/// Error response structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
}
fn handle_auth_error(error: AuthError) -> (StatusCode, Json<ErrorResponse>) {
let status = match error {
AuthError::InvalidCredentials => StatusCode::UNAUTHORIZED,
AuthError::UserNotFound => StatusCode::NOT_FOUND,
AuthError::InvalidSession => StatusCode::UNAUTHORIZED,
AuthError::AuthenticationRequired => StatusCode::UNAUTHORIZED,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
let code = match error {
AuthError::InvalidCredentials => "INVALID_CREDENTIALS".to_string(),
AuthError::UserNotFound => "USER_NOT_FOUND".to_string(),
AuthError::InvalidSession => "INVALID_SESSION".to_string(),
AuthError::AuthenticationRequired => "AUTHENTICATION_REQUIRED".to_string(),
_ => "INTERNAL_ERROR".to_string(),
};
(
status,
Json(ErrorResponse {
code,
message: error.to_string(),
})
)
}
+45
View File
@@ -0,0 +1,45 @@
//! Chronos API Server
use axum::{
routing::{get, post},
Router,
};
use chronos_auth::AuthService;
use chronos_database::MigrationManager;
use sqlx::PgPool;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Initialize tracing
tracing_subscriber::fmt::init();
// Connect to database
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let pool = PgPool::connect(&database_url).await
.expect("Failed to connect to database");
// Run migrations
let migration_manager = MigrationManager::new(pool.clone());
migration_manager.run_migrations().await
.expect("Failed to run migrations");
// Create auth service
let auth_service = AuthService::new(pool.clone());
// Build the API router
let app = Router::new()
.route("/api/v1/auth/login", post(handlers::auth::login))
.route("/api/v1/auth/logout", post(handlers::auth::logout))
.route("/api/v1/auth/me", get(handlers::auth::get_current_user))
.with_state(auth_service);
// Start the server
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
tracing::info!("Starting server on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.expect("Failed to start server");
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "chronos-auth"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
thiserror = "1.0"
anyhow = "1.0"
argon2 = "0.5"
uuid = { version = "1.0", features = ["v4"] }
chronos-core = { path = "../chronos-core" }
+30
View File
@@ -0,0 +1,30 @@
//! Error types for the authentication module.
use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum AuthError {
#[error("Invalid credentials")]
InvalidCredentials,
#[error("User not found")]
UserNotFound,
#[error("Invalid session")]
InvalidSession,
#[error("Password hashing failed")]
PasswordHashingFailed,
#[error("Database error: {0}")]
Database(String),
#[error("Authentication required")]
AuthenticationRequired,
}
impl From<sqlx::Error> for AuthError {
fn from(error: sqlx::Error) -> Self {
AuthError::Database(error.to_string())
}
}
+251
View File
@@ -0,0 +1,251 @@
//! Authentication module for Chronos
//!
//! Provides user authentication, session management, and access control.
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, Row};
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;
pub mod error;
pub use error::AuthError;
/// User role enumeration
#[derive(Debug, Clone, Copy, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "role", rename_all = "lowercase")]
pub enum Role {
Administrator,
Operator,
Viewer,
}
impl std::fmt::Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Role::Administrator => write!(f, "administrator"),
Role::Operator => write!(f, "operator"),
Role::Viewer => write!(f, "viewer"),
}
}
}
/// User entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub username: String,
pub password_hash: String,
pub role: Role,
pub created_at: chrono::DateTime<chrono::Utc>,
pub updated_at: chrono::DateTime<chrono::Utc>,
}
/// Session entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub id: Uuid,
pub user_id: Uuid,
pub token: String,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub created_at: chrono::DateTime<chrono::Utc>,
}
/// Authentication service
pub struct AuthService {
pool: PgPool,
}
impl AuthService {
/// Create a new authentication service
pub fn new(pool: PgPool) -> Self {
AuthService { pool }
}
/// Authenticate a user with username and password
pub async fn authenticate(
&self,
username: &str,
password: &str,
) -> Result<User, AuthError> {
let user = self.get_user_by_username(username).await?;
// Verify password using Argon2id
if !verify_password(password, &user.password_hash) {
return Err(AuthError::InvalidCredentials);
}
Ok(user)
}
/// Create a new session for a user
pub async fn create_session(&self, user_id: Uuid) -> Result<Session, AuthError> {
let token = generate_token();
let expires_at = chrono::Utc::now() + chrono::Duration::hours(24);
let session = sqlx::query!(
r#"
INSERT INTO sessions (user_id, token, expires_at)
VALUES ($1, $2, $3)
RETURNING id, user_id, token, expires_at, created_at
"#,
user_id,
token,
expires_at
)
.fetch_one(&self.pool)
.await?;
Ok(Session {
id: session.id,
user_id: session.user_id,
token: session.token,
expires_at: session.expires_at,
created_at: session.created_at,
})
}
/// Validate a session token
pub async fn validate_session(&self, token: &str) -> Result<Session, AuthError> {
let session = sqlx::query!(
r#"
SELECT id, user_id, token, expires_at, created_at
FROM sessions
WHERE token = $1 AND expires_at > NOW()
"#,
token
)
.fetch_optional(&self.pool)
.await?;
match session {
Some(s) => Ok(Session {
id: s.id,
user_id: s.user_id,
token: s.token,
expires_at: s.expires_at,
created_at: s.created_at,
}),
None => Err(AuthError::InvalidSession),
}
}
/// Get a user by username
pub async fn get_user_by_username(&self, username: &str) -> Result<User, AuthError> {
let user = sqlx::query!(
r#"
SELECT id, username, password_hash, role, created_at, updated_at
FROM users
WHERE username = $1
"#,
username
)
.fetch_optional(&self.pool)
.await?;
match user {
Some(u) => Ok(User {
id: u.id,
username: u.username,
password_hash: u.password_hash,
role: u.role,
created_at: u.created_at,
updated_at: u.updated_at,
}),
None => Err(AuthError::UserNotFound),
}
}
/// Create a new user
pub async fn create_user(
&self,
username: String,
password: String,
role: Role,
) -> Result<User, AuthError> {
let password_hash = hash_password(&password)?;
let id = Uuid::new_v4();
let user = sqlx::query!(
r#"
INSERT INTO users (id, username, password_hash, role)
VALUES ($1, $2, $3, $4)
RETURNING id, username, password_hash, role, created_at, updated_at
"#,
id,
username,
password_hash,
role
)
.fetch_one(&self.pool)
.await?;
Ok(User {
id: user.id,
username: user.username,
password_hash: user.password_hash,
role: user.role,
created_at: user.created_at,
updated_at: user.updated_at,
})
}
/// Logout a user by invalidating their session
pub async fn logout(&self, token: &str) -> Result<(), AuthError> {
sqlx::query!(
r#"
DELETE FROM sessions WHERE token = $1
"#,
token
)
.execute(&self.pool)
.await?;
Ok(())
}
}
/// Hash a password using Argon2id
fn hash_password(password: &str) -> Result<String, AuthError> {
use argon2::{
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
Algorithm, Params, Version,
};
let salt = SaltString::generate(&mut OsRng);
let params = Params::new(15000, 2, 1, None).map_err(|_| AuthError::PasswordHashingFailed)?;
let password_hash = argon2::Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password(password.as_bytes(), &salt)
.map_err(|_| AuthError::PasswordHashingFailed)?
.to_string();
Ok(password_hash)
}
/// Verify a password against a hash
fn verify_password(password: &str, hash: &str) -> bool {
use argon2::{password_hash::PasswordVerifier, Algorithm, Version};
let parsed_hash = match argon2::password_hash::PasswordHash::new(hash) {
Ok(h) => h,
Err(_) => return false,
};
let params = argon2::Params::default();
let argon2 = argon2::Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
argon2
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok()
}
/// Generate a random token for sessions
fn generate_token() -> String {
use rand::Rng;
let mut rng = rand::thread_rng();
let mut token = String::with_capacity(64);
for _ in 0..64 {
token.push(rng.gen_range(b'a'..=b'z') as char);
}
token
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "chronos-cli"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
clap = { version = "4.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
chronos-core = { path = "../chronos-core" }
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "chronos-core"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
thiserror = "1.0"
anyhow = "1.0"
+111
View File
@@ -0,0 +1,111 @@
//! Core data models and shared types for Chronos
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use uuid::Uuid;
/// User role enumeration
#[derive(Debug, Clone, Copy, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "role", rename_all = "lowercase")]
pub enum Role {
Administrator,
Operator,
Viewer,
}
impl std::fmt::Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Role::Administrator => write!(f, "administrator"),
Role::Operator => write!(f, "operator"),
Role::Viewer => write!(f, "viewer"),
}
}
}
/// User entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub username: String,
pub password_hash: String,
pub role: Role,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// Session entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub id: Uuid,
pub user_id: Uuid,
pub token: String,
pub expires_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}
/// Workflow node type enumeration
#[derive(Debug, Clone, Copy, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "node_type", rename_all = "lowercase")]
pub enum NodeType {
Command,
Script,
Http,
Delay,
Conditional,
DataTransform,
FileOperation,
Notification,
WebhookTrigger,
ScheduleTrigger,
}
/// Workflow entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workflow {
pub id: Uuid,
pub name: String,
pub description: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// Schedule entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schedule {
pub id: Uuid,
pub workflow_id: Uuid,
pub name: String,
pub cron_expression: Option<String>,
pub interval_seconds: Option<u64>,
pub start_date: Option<DateTime<Utc>>,
pub end_date: Option<DateTime<Utc>>,
pub enabled: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// Execution status enumeration
#[derive(Debug, Clone, Copy, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "execution_status", rename_all = "lowercase")]
pub enum ExecutionStatus {
Pending,
Running,
Completed,
Failed,
Cancelled,
Skipped,
}
/// Execution entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Execution {
pub id: Uuid,
pub workflow_id: Uuid,
pub schedule_id: Option<Uuid>,
pub status: ExecutionStatus,
pub started_at: DateTime<Utc>,
pub finished_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "chronos-database"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
chrono = { version = "0.4", features = ["serde"] }
thiserror = "1.0"
anyhow = "1.0"
+64
View File
@@ -0,0 +1,64 @@
//! Database schema and migrations for Chronos
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, Row};
use chrono::Utc;
use uuid::Uuid;
/// Database migration manager
pub struct MigrationManager {
pool: PgPool,
}
impl MigrationManager {
/// Create a new migration manager
pub fn new(pool: PgPool) -> Self {
MigrationManager { pool }
}
/// Run all pending migrations
pub async fn run_migrations(&self) -> Result<(), sqlx::Error> {
// Users table
sqlx::query!(
r#"
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username VARCHAR(255) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role VARCHAR(50) NOT NULL DEFAULT 'viewer',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
)
"#
)
.execute(&self.pool)
.await?;
// Sessions table
sqlx::query!(
r#"
CREATE TABLE IF NOT EXISTS sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
token TEXT UNIQUE NOT NULL,
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
)
"#
)
.execute(&self.pool)
.await?;
// Create indexes
sqlx::query!(
r#"
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
"#
)
.execute(&self.pool)
.await?;
Ok(())
}
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "chronos-executor"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "chronos-metrics"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
prometheus = "0.13"
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
chronos-core = { path = "../chronos-core" }
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "chronos-notifications"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "chronos-scheduler"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
chronos-database = { path = "../chronos-database" }
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "chronos-worker"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
chronos-database = { path = "../chronos-database" }
chronos-executor = { path = "../chronos-executor" }
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "chronos-workflow"
version = { workspace = true }
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
[dependencies]
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
thiserror = "1.0"
anyhow = "1.0"
chronos-core = { path = "../chronos-core" }
chronos-database = { path = "../chronos-database" }