axonml-server 0.6.2

REST API server for AxonML Machine Learning Framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Server Configuration — TOML-Based Config Loading and Validation
//!
//! Defines the `Config` struct and its nested sub-configs that are
//! deserialized from `~/.axonml/config.toml` via `toml`:
//!
//! - `ServerConfig` — host, port, data directory.
//! - `AegisConfig` — Aegis-DB connection (host, port, credentials).
//! - `AuthConfig` — JWT secret/expiry, session timeout, MFA policy,
//!   public registration toggle.
//! - `InferenceConfig` — port range and max endpoint count.
//! - `DashboardConfig` — dashboard port.
//! - `HubConfig` — model hub URL and local cache directory.
//!
//! `Config::load` reads from the default path; `Config::validate` enforces
//! security invariants (non-empty JWT secret >= 32 chars, non-empty DB
//! credentials). Helper methods expose derived paths (`models_dir`,
//! `runs_dir`, `logs_dir`, `checkpoints_dir`, `hub_cache_dir`) and
//! `ensure_directories` creates them on disk. Tilde expansion is handled
//! manually via `dirs::home_dir`.
//!
//! # File
//! `crates/axonml-server/src/config.rs`
//!
//! # Author
//! Andrew Jewell Sr. — AutomataNexus LLC
//! ORCID: 0009-0005-2158-7060
//!
//! # Updated
//! April 16, 2026 11:15 PM EST
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

// =============================================================================
// Imports
// =============================================================================

use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;

// =============================================================================
// Error Types
// =============================================================================

#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Failed to read config file: {0}")]
    ReadError(#[from] std::io::Error),
    #[error("Failed to parse config: {0}")]
    ParseError(#[from] toml::de::Error),
    #[error("Missing required configuration: {0}")]
    MissingConfig(String),
}

// =============================================================================
// Configuration Structs
// =============================================================================

/// Main server configuration
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct Config {
    pub server: ServerConfig,
    pub aegis: AegisConfig,
    pub auth: AuthConfig,
    pub inference: InferenceConfig,
    pub dashboard: DashboardConfig,
    #[serde(default)]
    pub hub: HubConfig,
}

/// HTTP server configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ServerConfig {
    #[serde(default = "default_host")]
    pub host: String,
    #[serde(default = "default_port")]
    pub port: u16,
    #[serde(default = "default_data_dir")]
    pub data_dir: String,
}

/// Aegis-DB connection configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AegisConfig {
    #[serde(default = "default_aegis_host")]
    pub host: String,
    #[serde(default = "default_aegis_port")]
    pub port: u16,
    #[serde(default = "default_aegis_user")]
    pub username: String,
    #[serde(default = "default_aegis_pass")]
    pub password: String,
}

/// Authentication configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthConfig {
    #[serde(default = "default_jwt_secret")]
    pub jwt_secret: String,
    #[serde(default = "default_jwt_expiry")]
    pub jwt_expiry_hours: u64,
    #[serde(default = "default_session_timeout")]
    pub session_timeout_minutes: u64,
    #[serde(default)]
    pub require_mfa: bool,
    #[serde(default = "default_allow_registration")]
    pub allow_public_registration: bool,
}

/// Inference server configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InferenceConfig {
    #[serde(default = "default_port_start")]
    pub default_port_range_start: u16,
    #[serde(default = "default_port_end")]
    pub default_port_range_end: u16,
    #[serde(default = "default_max_endpoints")]
    pub max_endpoints: u32,
}

/// Dashboard configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DashboardConfig {
    #[serde(default = "default_dashboard_port")]
    pub port: u16,
}

/// Model Hub configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HubConfig {
    #[serde(default = "default_hub_url")]
    pub hub_url: String,
    #[serde(default = "default_hub_cache_dir")]
    pub cache_dir: String,
}

// =============================================================================
// Default Value Functions
// =============================================================================

fn default_host() -> String {
    "0.0.0.0".to_string()
}
fn default_port() -> u16 {
    3000
}
fn default_data_dir() -> String {
    "~/.axonml".to_string()
}
fn default_aegis_host() -> String {
    "localhost".to_string()
}
fn default_aegis_port() -> u16 {
    9090
}
// SECURITY: No default database credentials - must be explicitly configured
fn default_aegis_user() -> String {
    String::new()
}
fn default_aegis_pass() -> String {
    String::new()
}
// SECURITY: No default JWT secret - must be explicitly configured
fn default_jwt_secret() -> String {
    String::new()
}
fn default_jwt_expiry() -> u64 {
    24
}
fn default_session_timeout() -> u64 {
    30
}
fn default_allow_registration() -> bool {
    true
}
fn default_port_start() -> u16 {
    8100
}
fn default_port_end() -> u16 {
    8199
}
fn default_max_endpoints() -> u32 {
    10
}
fn default_dashboard_port() -> u16 {
    8080
}
fn default_hub_url() -> String {
    "https://hub.axonml.dev/v1".to_string()
}
fn default_hub_cache_dir() -> String {
    "~/.axonml/hub_cache".to_string()
}

// =============================================================================
// Default Implementations
// =============================================================================

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            data_dir: default_data_dir(),
        }
    }
}

impl Default for AegisConfig {
    fn default() -> Self {
        Self {
            host: default_aegis_host(),
            port: default_aegis_port(),
            username: default_aegis_user(),
            password: default_aegis_pass(),
        }
    }
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            jwt_secret: default_jwt_secret(),
            jwt_expiry_hours: default_jwt_expiry(),
            session_timeout_minutes: default_session_timeout(),
            require_mfa: false,
            allow_public_registration: default_allow_registration(),
        }
    }
}

impl Default for InferenceConfig {
    fn default() -> Self {
        Self {
            default_port_range_start: default_port_start(),
            default_port_range_end: default_port_end(),
            max_endpoints: default_max_endpoints(),
        }
    }
}

impl Default for DashboardConfig {
    fn default() -> Self {
        Self {
            port: default_dashboard_port(),
        }
    }
}

impl Default for HubConfig {
    fn default() -> Self {
        Self {
            hub_url: default_hub_url(),
            cache_dir: default_hub_cache_dir(),
        }
    }
}

// =============================================================================
// Config Implementation
// =============================================================================

impl Config {
    // -------------------------------------------------------------------------
    // Loading
    // -------------------------------------------------------------------------

    /// Load configuration from the default location (~/.axonml/config.toml)
    pub fn load() -> Result<Self, ConfigError> {
        let config_path = Self::config_path();
        if config_path.exists() {
            Self::load_from_path(&config_path)
        } else {
            Ok(Self::default())
        }
    }

    /// Load configuration from a specific path
    pub fn load_from_path(path: &PathBuf) -> Result<Self, ConfigError> {
        let content = std::fs::read_to_string(path)?;
        let config: Config = toml::from_str(&content)?;
        Ok(config)
    }

    /// Get the default configuration file path
    pub fn config_path() -> PathBuf {
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".axonml")
            .join("config.toml")
    }

    // -------------------------------------------------------------------------
    // Directory Paths
    // -------------------------------------------------------------------------

    /// Get the data directory path (expanded)
    pub fn data_dir(&self) -> PathBuf {
        let path = self.server.data_dir.replace(
            "~",
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .to_str()
                .unwrap_or("."),
        );
        PathBuf::from(path)
    }

    /// Get the models directory
    pub fn models_dir(&self) -> PathBuf {
        self.data_dir().join("models")
    }

    /// Get the runs directory
    pub fn runs_dir(&self) -> PathBuf {
        self.data_dir().join("runs")
    }

    /// Get the logs directory
    pub fn logs_dir(&self) -> PathBuf {
        self.data_dir().join("logs")
    }

    /// Get the checkpoints directory (for training notebook checkpoints)
    pub fn checkpoints_dir(&self) -> PathBuf {
        self.data_dir().join("checkpoints")
    }

    /// Get the hub cache directory
    pub fn hub_cache_dir(&self) -> PathBuf {
        let path = self.hub.cache_dir.replace(
            "~",
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .to_str()
                .unwrap_or("."),
        );
        PathBuf::from(path)
    }

    /// Ensure all required directories exist
    pub fn ensure_directories(&self) -> std::io::Result<()> {
        std::fs::create_dir_all(self.data_dir())?;
        std::fs::create_dir_all(self.models_dir())?;
        std::fs::create_dir_all(self.runs_dir())?;
        std::fs::create_dir_all(self.logs_dir())?;
        std::fs::create_dir_all(self.checkpoints_dir())?;
        std::fs::create_dir_all(self.hub_cache_dir())?;
        Ok(())
    }

    // -------------------------------------------------------------------------
    // Connection Helpers
    // -------------------------------------------------------------------------

    /// Get the Aegis-DB connection URL
    pub fn aegis_url(&self) -> String {
        format!("http://{}:{}", self.aegis.host, self.aegis.port)
    }

    // -------------------------------------------------------------------------
    // Validation
    // -------------------------------------------------------------------------

    /// Validate configuration - always called on startup
    pub fn validate(&self) -> Result<(), ConfigError> {
        // SECURITY: JWT secret must be explicitly configured
        if self.auth.jwt_secret.is_empty() {
            return Err(ConfigError::MissingConfig(
                "jwt_secret is required. Set auth.jwt_secret in config.toml or AXONML_JWT_SECRET environment variable.".to_string()
            ));
        }

        // Check if JWT secret is long enough (at least 32 bytes for HS256)
        if self.auth.jwt_secret.len() < 32 {
            return Err(ConfigError::MissingConfig(
                "jwt_secret must be at least 32 characters long for security.".to_string(),
            ));
        }

        // SECURITY: Database credentials must be explicitly configured
        if self.aegis.username.is_empty() || self.aegis.password.is_empty() {
            return Err(ConfigError::MissingConfig(
                "Database credentials are required. Set aegis.username and aegis.password in config.toml.".to_string()
            ));
        }

        Ok(())
    }

    /// Validate configuration for production (returns warnings for non-critical issues)
    pub fn validate_warnings(&self) -> Vec<String> {
        let mut warnings = Vec::new();

        if self.auth.allow_public_registration {
            warnings.push("INFO: Public registration is enabled.".to_string());
        }

        if !self.auth.require_mfa {
            warnings.push("INFO: MFA is not required for users.".to_string());
        }

        warnings
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.server.port, 3000);
        assert_eq!(config.aegis.port, 9090);
    }

    #[test]
    fn test_parse_config() {
        let toml = r#"
[server]
host = "127.0.0.1"
port = 8000

[aegis]
host = "db.example.com"
port = 5432

[auth]
jwt_secret = "test_secret_that_is_at_least_32_characters_long_for_security"
require_mfa = true

[inference]
max_endpoints = 5

[dashboard]
port = 3000
"#;
        let config: Config = toml::from_str(toml).unwrap();
        assert_eq!(config.server.port, 8000);
        assert_eq!(config.aegis.host, "db.example.com");
        assert!(config.auth.require_mfa);
    }
}