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

+41
View File
@@ -0,0 +1,41 @@
# Chronos Change Log
## [0.1.0] - 2024-01-01
### Added
- Initial project structure with Cargo workspace
- Core crates: chronos-core, chronos-api, chronos-scheduler, chronos-worker, chronos-workflow, chronos-database, chronos-auth, chronos-executor, chronos-notifications, chronos-metrics, chronos-cli
- Basic architecture documentation
- Security model documentation
- Installation guide
- Configuration documentation
- API documentation
### Changed
- None
### Removed
- None
[0.1.0] - 2024-01-01
### Added
- Initial project structure with Cargo workspace
- Core crates: chronos-core, chronos-api, chronos-scheduler, chronos-worker, chronos-workflow, chronos-database, chronos-auth, chronos-executor, chronos-notifications, chronos-metrics, chronos-cli
- Basic architecture documentation
- Security model documentation
- Installation guide
- Configuration documentation
- API documentation
### Changed
- None
### Removed
- None
+23
View File
@@ -0,0 +1,23 @@
[workspace]
members = [
"crates/chronos-core",
"crates/chronos-api",
"crates/chronos-scheduler",
"crates/chronos-worker",
"crates/chronos-workflow",
"crates/chronos-database",
"crates/chronos-auth",
"crates/chronos-executor",
"crates/chronos-notifications",
"crates/chronos-metrics",
"crates/chronos-cli",
]
resolver = "2"
[workspace.package]
version = "0.1.0"
edition = "2021"
authors = ["Chronos Team"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/chronos/chronos"
repository = "https://github.com/chronos/chronos"
+99
View File
@@ -0,0 +1,99 @@
# Implementation Progress
## Phase 1 - Research and Architecture
- [x] Project structure defined with Cargo workspace
- [x] Core crates created for all components
- [x] Architecture documentation completed
- [x] Security model documented
- [x] Installation guide created
- [x] Configuration documentation written
- [x] API reference documentation created
## Phase 2 - Rust Workspace Foundation
- [x] Cargo workspace configuration complete
- [x] Shared types and utilities defined in chronos-core
- [x] Basic database infrastructure established
- [x] Configuration system implemented
- [x] Logging framework set up
## Phase 3 - Authentication and Database
- [ ] User accounts and sessions
- [ ] Password hashing with Argon2id
- [ ] Role-based access control
- [ ] Database migrations
- [ ] API authentication endpoints
## Phase 4 - Scheduler
- [ ] Cron scheduling implementation
- [ ] Interval scheduling support
- [ ] Persistent state management
- [ ] Schedule dispatch coordination
- [ ] Missed-run handling
## Phase 5 - Native Execution Engine
- [ ] Process spawning capabilities
- [ ] Linux isolation mechanisms
- [ ] Timeout and cancellation support
- [ ] Resource limit enforcement
- [ ] Output capture
## Phase 6 - Worker Infrastructure
- [ ] Worker registration system
- [ ] Execution lease management
- [ ] Heartbeat monitoring
- [ ] Job dispatch logic
- [ ] Retry handling
## Phase 7 - Workflow Engine
- [ ] Graph validation and execution
- [ ] Dependency resolution
- [ ] Conditional execution support
- [ ] Parallel task execution
- [ ] State transition handling
## Phase 8 - REST API
- [ ] Authentication endpoints
- [ ] User management API
- [ ] Workflow CRUD operations
- [ ] Schedule management API
- [ ] Execution history API
- [ ] Worker monitoring API
- [ ] Credential management API
## Phase 9 - Frontend
- [ ] Dashboard UI implementation
- [ ] Visual workflow editor
- [ ] Execution monitoring interface
- [ ] Analytics and charts
- [ ] Administrative settings UI
## Phase 10 - Notifications and Metrics
- [ ] Notification delivery system
- [ ] Real-time updates
- [ ] Health checks
- [ ] Prometheus metrics
## Phase 11 - Native Deployment
- [ ] systemd service units
- [ ] Installation scripts
- [ ] Production configuration
- [ ] Binary packaging
- [ ] Upgrade procedures
## Phase 12 - Testing and Hardening
- [ ] Unit tests for all crates
- [ ] Integration tests
- [ ] Reliability testing
- [ ] Security review
- [ ] Performance benchmarks
## Phase 13 - Final Documentation and Release
- [ ] Complete documentation
- [ ] Examples and tutorials
- [ ] Installation instructions
- [ ] Final verification
## Current Status
The project has successfully completed the initial research and architecture phases. The Cargo workspace is fully configured with all necessary crates, and comprehensive documentation has been created covering architecture, security, installation, configuration, and API reference.
Next steps are to implement authentication and database components (Phase 3).
+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" }
+409
View File
@@ -0,0 +1,409 @@
# Chronos API Documentation
This document describes the REST API endpoints available in Chronos.
## Versioning
All API endpoints are prefixed with `/api/v1/`.
## Authentication
All API requests require authentication. Include an `Authorization` header with a valid session token:
```
Authorization: Bearer <session_token>
```
## Error Responses
All error responses use standard HTTP status codes and include a JSON body with error details:
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [
{
"field": "name",
"reason": "Name is required"
}
]
}
}
```
## Endpoints
### Authentication
#### POST `/api/v1/auth/login`
Authenticate a user.
**Request:**
```json
{
"username": "admin",
"password": "secret"
}
```
**Response (200):**
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
#### POST `/api/v1/auth/logout`
Logout the current user.
**Response (204):**
#### GET `/api/v1/auth/me`
Get current user information.
**Response (200):**
```json
{
"id": "1",
"username": "admin",
"role": "administrator"
}
```
### Users
#### GET `/api/v1/users`
List all users.
**Response (200):**
```json
[
{
"id": "1",
"username": "admin",
"role": "administrator",
"created_at": "2023-01-01T00:00:00Z"
}
]
```
#### POST `/api/v1/users`
Create a new user.
**Request:**
```json
{
"username": "operator",
"password": "secret",
"role": "operator"
}
```
**Response (201):**
```json
{
"id": "2",
"username": "operator",
"role": "operator",
"created_at": "2023-01-01T00:00:00Z"
}
```
#### GET `/api/v1/users/{id}`
Get a specific user.
**Response (200):**
```json
{
"id": "2",
"username": "operator",
"role": "operator",
"created_at": "2023-01-01T00:00:00Z"
}
```
#### PUT `/api/v1/users/{id}`
Update a user.
**Request:**
```json
{
"role": "administrator"
}
```
**Response (200):**
```json
{
"id": "2",
"username": "operator",
"role": "administrator",
"created_at": "2023-01-01T00:00:00Z"
}
```
#### DELETE `/api/v1/users/{id}`
Delete a user.
**Response (204):**
### Workflows
#### GET `/api/v1/workflows`
List all workflows.
**Response (200):**
```json
[
{
"id": "1",
"name": "Backup Workflow",
"description": "Daily backup job",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}
]
```
#### POST `/api/v1/workflows`
Create a new workflow.
**Request:**
```json
{
"name": "Backup Workflow",
"description": "Daily backup job",
"nodes": [
{
"id": "1",
"type": "command",
"config": {
"command": "tar -czf /backups/backup-$(date +\\%Y\\%m\\%d).tar.gz /home"
}
}
],
"edges": []
}
```
**Response (201):**
```json
{
"id": "1",
"name": "Backup Workflow",
"description": "Daily backup job",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}
```
#### GET `/api/v1/workflows/{id}`
Get a specific workflow.
**Response (200):**
```json
{
"id": "1",
"name": "Backup Workflow",
"description": "Daily backup job",
"nodes": [
{
"id": "1",
"type": "command",
"config": {
"command": "tar -czf /backups/backup-$(date +\\%Y\\%m\\%d).tar.gz /home"
}
}
],
"edges": [],
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}
```
#### PUT `/api/v1/workflows/{id}`
Update a workflow.
**Request:**
```json
{
"name": "Updated Backup Workflow",
"description": "Daily backup job with better compression"
}
```
**Response (200):**
```json
{
"id": "1",
"name": "Updated Backup Workflow",
"description": "Daily backup job with better compression",
"created_at": "2023-01-01T00:00:00Z",
"updated_at": "2023-01-01T00:00:00Z"
}
```
#### DELETE `/api/v1/workflows/{id}`
Delete a workflow.
**Response (204):**
### Schedules
#### GET `/api/v1/schedules`
List all schedules.
**Response (200):**
```json
[
{
"id": "1",
"workflow_id": "1",
"name": "Daily Backup",
"cron_expression": "0 0 * * *",
"enabled": true,
"created_at": "2023-01-01T00:00:00Z"
}
]
```
#### POST `/api/v1/schedules`
Create a new schedule.
**Request:**
```json
{
"workflow_id": "1",
"name": "Daily Backup",
"cron_expression": "0 0 * * *",
"enabled": true
}
```
**Response (201):**
```json
{
"id": "1",
"workflow_id": "1",
"name": "Daily Backup",
"cron_expression": "0 0 * * *",
"enabled": true,
"created_at": "2023-01-01T00:00:00Z"
}
```
#### GET `/api/v1/schedules/{id}`
Get a specific schedule.
**Response (200):**
```json
{
"id": "1",
"workflow_id": "1",
"name": "Daily Backup",
"cron_expression": "0 0 * * *",
"enabled": true,
"created_at": "2023-01-01T00:00:00Z"
}
```
#### PUT `/api/v1/schedules/{id}`
Update a schedule.
**Request:**
```json
{
"name": "Weekly Backup",
"cron_expression": "0 0 * * 0"
}
```
**Response (200):**
```json
{
"id": "1",
"workflow_id": "1",
"name": "Weekly Backup",
"cron_expression": "0 0 * * 0",
"enabled": true,
"created_at": "2023-01-01T00:00:00Z"
}
```
#### DELETE `/api/v1/schedules/{id}`
Delete a schedule.
**Response (204):**
### Executions
#### GET `/api/v1/executions`
List all executions.
**Response (200):**
```json
[
{
"id": "1",
"workflow_id": "1",
"schedule_id": "1",
"status": "completed",
"started_at": "2023-01-01T00:00:00Z",
"finished_at": "2023-01-01T00:00:05Z"
}
]
```
#### GET `/api/v1/executions/{id}`
Get a specific execution.
**Response (200):**
```json
{
"id": "1",
"workflow_id": "1",
"schedule_id": "1",
"status": "completed",
"started_at": "2023-01-01T00:00:00Z",
"finished_at": "2023-01-01T00:00:05Z",
"logs": [
{
"timestamp": "2023-01-01T00:00:00Z",
"level": "info",
"message": "Starting backup job"
}
]
}
```
### Workers
#### GET `/api/v1/workers`
List all workers.
**Response (200):**
```json
[
{
"id": "1",
"name": "worker-1",
"status": "online",
"last_heartbeat": "2023-01-01T00:00:00Z"
}
]
```
### Health
#### GET `/api/v1/health`
Check service health.
**Response (200):**
```json
{
"status": "healthy",
"timestamp": "2023-01-01T00:00:00Z"
}
```
+74
View File
@@ -0,0 +1,74 @@
# Chronos Architecture
This document outlines the high-level architecture of Chronos, a Rust-based workflow automation platform.
## Overview
Chronos is built as a Cargo workspace with multiple crates that implement different components:
- `chronos-core`: Shared data models and utilities
- `chronos-api`: HTTP API server using Axum
- `chronos-scheduler`: Scheduling service
- `chronos-worker`: Worker execution service
- `chronos-workflow`: Workflow engine
- `chronos-database`: Database interface
- `chronos-auth`: Authentication system
- `chronos-executor`: Native process execution engine
- `chronos-notifications`: Notification delivery system
- `chronos-metrics`: Metrics collection
- `chronos-cli`: Command-line interface
## Component Interactions
```
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ Browser │ │ Chronos │ │ Database │
└───────────┘ │ (API) │ └───────────┘
│ │ │ │
│ │ │ │
┌─────────────┐ │ │ │
│ Workflow│ │ │ │
│ Editor│ │ │ │
└───────────┘ │ │ │
│ │ │ │
│ │ │ │
┌─────────────┐ │ │ │
│ Scheduler │ │ │ │
│ │ │ │ │
└───────────┘ │ │ │
│ │ │ │
│ │ │ │
┌─────────────┐ │ │ │
│ Worker │ │ │ │
│ Executor│ │ │ │
└───────────┘ │ │ │
│ │ │ │
│ │ │ │
┌─────────────┐ │ │ │
│ Executor │ │ │ │
│ (Native)│ │ │ │
└───────────┘ │ │ │
│ │ │ │
│ │ │ │
┌─────────────┐ │ │ │
│ Executor │ │ │ │
│ (Native)│ │ │ │
└───────────┘ │ │ │
```
## Core Data Flow
1. **User Interface**: Users interact with the web dashboard to create and manage workflows
2. **API Layer**: The Axum API server receives requests, validates them, and dispatches to appropriate services
3. **Scheduler**: Handles scheduling decisions and job creation in the database
4. **Worker Pool**: Workers pick up scheduled jobs and execute them via the executor
5. **Executor**: Runs actual commands in isolated processes with resource limits
6. **Database**: Stores all persistent state including workflows, schedules, executions, and user data
## Security Model
- All user inputs are validated and sanitized
- Authentication is enforced at API layer
- Workers execute tasks in isolated native processes
- Sensitive credentials are encrypted at rest
- Access control is implemented through role-based permissions
+83
View File
@@ -0,0 +1,83 @@
# Chronos Configuration
Chronos uses a TOML configuration file for its settings. The configuration file is located at `config/chronos.toml` by default.
## Example Configuration
```toml
[server]
host = "127.0.0.1"
port = 8080
ssl_enabled = false
[database]
url = "postgres://chronos:password@localhost/chronos"
max_connections = 20
[redis]
enabled = true
url = "redis://localhost:6379"
[scheduler]
enabled = true
poll_interval_seconds = 5
[workers]
concurrency = 8
heartbeat_interval_seconds = 10
[execution]
default_timeout_seconds = 300
max_output_bytes = 10485760
max_processes = 100
[logging]
level = "info"
format = "json"
[security]
session_secret = "your-secret-here"
```
## Configuration Sections
### `[server]`
- `host`: Host address to bind the API server (default: "127.0.0.1")
- `port`: Port number for the API server (default: 8080)
- `ssl_enabled`: Enable HTTPS (default: false)
### `[database]`
- `url`: PostgreSQL connection string
- `max_connections`: Maximum concurrent database connections (default: 20)
### `[redis]`
- `enabled`: Enable Redis caching (default: true)
- `url`: Redis server connection URL
### `[scheduler]`
- `enabled`: Enable the scheduler service (default: true)
- `poll_interval_seconds`: How often to check for scheduled jobs (default: 5)
### `[workers]`
- `concurrency`: Number of concurrent worker threads (default: 8)
- `heartbeat_interval_seconds`: Interval for worker heartbeat updates (default: 10)
### `[execution]`
- `default_timeout_seconds`: Default timeout for job execution in seconds (default: 300)
- `max_output_bytes`: Maximum output size for job execution (default: 10485760)
- `max_processes`: Maximum number of processes that can be spawned per execution (default: 100)
### `[logging]`
- `level`: Log level ("trace", "debug", "info", "warn", "error") (default: "info")
- `format`: Log format ("json" or "text") (default: "json")
### `[security]`
- `session_secret`: Secret key for session encryption (required)
+184
View File
@@ -0,0 +1,184 @@
# Chronos Installation Guide
This document provides instructions for installing Chronos on supported Linux distributions.
## System Requirements
- Linux kernel 5.0 or newer
- Rust 1.70 or newer (stable toolchain)
- PostgreSQL 13 or newer
- Redis 6 or newer (optional, for caching)
- Node.js 18 or newer (for frontend build)
## Supported Distributions
Chronos is officially supported on:
- Debian 12 (Bookworm) and newer
- Ubuntu 22.04 LTS (Jammy) and newer
- Arch Linux
Other distributions may work but are not officially tested.
## Prerequisites
Before installing Chronos, ensure the following packages are installed:
### Debian/Ubuntu:
```bash
sudo apt update
sudo apt install -y build-essential postgresql redis-server nodejs npm
```
### Arch Linux:
```bash
sudo pacman -Syu --needed base-devel postgresql redis nodejs npm
```
## Installation Steps
1. **Clone the repository:**
```bash
git clone https://github.com/chronos/chronos.git
cd chronos
```
2. **Install Rust (if not already installed):**
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
```
3. **Set up PostgreSQL database:**
```bash
sudo systemctl start postgresql
sudo systemctl enable postgresql
sudo -u postgres createuser chronos
sudo -u postgres createdb chronos
```
4. **Create Chronos system users:**
```bash
sudo useradd -r -s /bin/false chronos-api
sudo useradd -r -s /bin/false chronos-scheduler
sudo useradd -r -s /bin/false chronos-worker
```
5. **Build the application:**
```bash
cargo build --release
```
6. **Install systemd service files:**
```bash
sudo cp systemd/*.service /etc/systemd/system/
sudo systemctl daemon-reload
```
7. **Configure the application:**
```bash
cp config/chronos.example.toml config/chronos.toml
# Edit config/chronos.toml with your settings
```
8. **Run database migrations:**
```bash
cargo run --bin chronos-cli -- migrate
```
9. **Start services:**
```bash
sudo systemctl enable chronos-api.service
sudo systemctl enable chronos-scheduler.service
sudo systemctl enable chronos-worker.service
sudo systemctl start chronos-api.service
sudo systemctl start chronos-scheduler.service
sudo systemctl start chronos-worker.service
```
## Configuration
Chronos uses a TOML configuration file. The example configuration is located at `config/chronos.example.toml`.
Key configuration sections:
- `[server]` - API server settings
- `[database]` - PostgreSQL connection details
- `[redis]` - Redis cache settings (optional)
- `[scheduler]` - Scheduling behavior
- `[workers]` - Worker pool configuration
- `[execution]` - Execution environment settings
## Verification
Check that services are running:
```bash
sudo systemctl status chronos-api.service
sudo systemctl status chronos-scheduler.service
sudo systemctl status chronos-worker.service
```
Verify the API is accessible:
```bash
curl http://localhost:8080/api/v1/health
```
## Updating
To update Chronos:
1. Pull latest changes:
```bash
git pull origin master
```
2. Rebuild:
```bash
cargo build --release
```
3. Run migrations if needed:
```bash
cargo run --bin chronos-cli -- migrate
```
4. Restart services:
```bash
sudo systemctl restart chronos-api.service
sudo systemctl restart chronos-scheduler.service
sudo systemctl restart chronos-worker.service
```
## Uninstalling
To uninstall Chronos:
1. Stop services:
```bash
sudo systemctl stop chronos-api.service
sudo systemctl stop chronos-scheduler.service
sudo systemctl stop chronos-worker.service
```
2. Disable services:
```bash
sudo systemctl disable chronos-api.service
sudo systemctl disable chronos-scheduler.service
sudo systemctl disable chronos-worker.service
```
3. Remove systemd service files:
```bash
sudo rm /etc/systemd/system/chronos-*.service
sudo systemctl daemon-reload
```
4. Remove system users:
```bash
sudo userdel chronos-api
sudo userdel chronos-scheduler
sudo userdel chronos-worker
```
5. Remove application files:
```bash
sudo rm -rf /path/to/chronos
```
+94
View File
@@ -0,0 +1,94 @@
# Chronos Security Model
This document outlines the security considerations and design decisions for Chronos, a Rust-based workflow automation platform.
## Overview
Chronos implements a multi-layered security approach to protect against common threats while maintaining usability for legitimate users. The system is designed with defense-in-depth principles, where multiple controls work together to provide comprehensive protection.
## Authentication and Authorization
### User Accounts
- Users are stored in the database with hashed passwords using Argon2id
- Passwords must meet minimum complexity requirements
- Session management uses secure server-side sessions with automatic expiration
- Login rate limiting prevents brute-force attacks
### Role-Based Access Control
Chronos implements a role-based system with three primary roles:
1. **Administrator**: Full access to all system functionality
2. **Operator**: Can create and manage workflows within granted permissions
3. **Viewer**: Can view authorized workflows and execution records
Access controls are enforced at the API layer for all endpoints.
## Data Protection
### Secrets Management
- All sensitive data (API keys, passwords, tokens) are encrypted at rest using authenticated encryption
- Encryption keys are stored separately from the database
- Secrets are redacted from logs and API responses
- Credential management is handled through dedicated credential stores
### Input Validation
All user inputs are validated and sanitized to prevent:
- SQL injection
- Cross-site scripting (XSS)
- Command injection
- Path traversal attacks
## Process Execution Security
### Native Execution Isolation
Chronos implements secure native process execution with multiple isolation layers:
1. **User Context Isolation**: Tasks execute under dedicated unprivileged system users
2. **Resource Limiting**: CPU, memory, and execution time limits enforced via cgroups v2
3. **Filesystem Restrictions**: Access to sensitive directories is restricted
4. **Process Limits**: Maximum number of processes per execution is enforced
5. **Network Isolation**: Outbound network access can be restricted by configuration
### Security Boundaries
The system explicitly documents security boundaries:
- Execution environment cannot access application secrets without explicit permission
- Regular users cannot configure unrestricted execution of privileged commands
- Administrative execution policies are separate from ordinary workflow configuration
## Network Security
### API Security
- All API endpoints require authentication
- HTTPS is required for all API communications
- CSRF protection is implemented for web forms
- Rate limiting is applied to prevent abuse
### Communication Protocols
- Internal service communication uses local Unix sockets where possible
- External communications use secure protocols with certificate validation
## Infrastructure Security
### System Integration
- Chronos integrates with systemd for service management and security hardening
- Dedicated service accounts are used for each component
- Filesystem permissions are configured appropriately
- Journald integration provides audit logging
### Container Exclusion
Chronos explicitly excludes container technologies:
- No Docker, Kubernetes, or other container runtimes
- All execution happens in native Linux processes
- This reduces attack surface by eliminating container escape vectors
## Audit and Logging
### Security Logging
- All authentication attempts are logged
- Access to sensitive data is recorded
- Administrative actions are audited
- Failed security events trigger alerts when configured
### Log Management
- Logs are structured for easy parsing and analysis
- Sensitive information is redacted from logs
- Log retention policies are configurable