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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Models API endpoints for AxonML
//!
//! # File
//! `crates/axonml-server/src/api/models.rs`
//!
//! # Author
//! Andrew Jewell Sr. — AutomataNexus LLC
//! ORCID: 0009-0005-2158-7060
//!
//! # Updated
//! April 14, 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.

use crate::api::AppState;
use crate::auth::{AuthError, AuthUser};
use crate::db::models::{
    Endpoint, Model, ModelRepository, ModelVersion, NewEndpoint, NewModel, NewModelVersion,
};
use axum::{
    Json,
    body::Bytes,
    extract::{Multipart, Path, Query, State},
    http::{StatusCode, header},
    response::IntoResponse,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::io::AsyncWriteExt;

// ============================================================================
// Request/Response Types
// ============================================================================

#[derive(Debug, Deserialize)]
pub struct ListModelsQuery {
    #[serde(default = "default_limit")]
    pub limit: u32,
    #[serde(default)]
    pub offset: u32,
}

fn default_limit() -> u32 {
    100
}

#[derive(Debug, Deserialize)]
pub struct CreateModelRequest {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    pub model_type: String,
}

#[derive(Debug, Deserialize)]
pub struct UpdateModelRequest {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ModelResponse {
    pub id: String,
    pub user_id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub model_type: String,
    pub version_count: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<u32>,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Serialize)]
pub struct ModelVersionResponse {
    pub id: String,
    pub model_id: String,
    pub version: u32,
    pub file_path: String,
    pub file_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metrics: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub training_run_id: Option<String>,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct DeployRequest {
    pub name: String,
    #[serde(default = "default_port")]
    pub port: u16,
    #[serde(default = "default_replicas")]
    pub replicas: u32,
    #[serde(default)]
    pub config: Option<serde_json::Value>,
}

fn default_port() -> u16 {
    8080
}

fn default_replicas() -> u32 {
    1
}

#[derive(Debug, Serialize)]
pub struct EndpointResponse {
    pub id: String,
    pub model_version_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<u32>,
    pub name: String,
    pub status: String,
    pub port: u16,
    pub replicas: u32,
    pub config: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

// ============================================================================
// Security Helpers
// ============================================================================

/// SECURITY: Validate that an ID is safe to use in file paths.
/// Prevents path traversal by rejecting IDs with path separators or traversal patterns.
fn validate_path_id(id: &str) -> Result<(), AuthError> {
    if id.is_empty() {
        return Err(AuthError::InvalidInput("ID cannot be empty".to_string()));
    }
    if id.contains("..") || id.contains('/') || id.contains('\\') || id.contains('\0') {
        return Err(AuthError::InvalidInput(
            "ID contains invalid characters".to_string(),
        ));
    }
    Ok(())
}

// ============================================================================
// Helper Functions
// ============================================================================

fn model_to_response(
    model: Model,
    version_count: u32,
    latest_version: Option<u32>,
) -> ModelResponse {
    ModelResponse {
        id: model.id,
        user_id: model.user_id,
        name: model.name,
        description: model.description,
        model_type: model.model_type,
        version_count,
        latest_version,
        created_at: model.created_at.to_rfc3339(),
        updated_at: model.updated_at.to_rfc3339(),
    }
}

fn version_to_response(version: ModelVersion) -> ModelVersionResponse {
    ModelVersionResponse {
        id: version.id,
        model_id: version.model_id,
        version: version.version,
        file_path: version.file_path,
        file_size: version.file_size,
        metrics: version.metrics,
        training_run_id: version.training_run_id,
        created_at: version.created_at.to_rfc3339(),
    }
}

fn endpoint_to_response(endpoint: Endpoint) -> EndpointResponse {
    // Provide default config if none exists
    let config = endpoint.config.unwrap_or_else(|| {
        serde_json::json!({
            "batch_size": 1,
            "timeout_ms": 30000,
            "max_concurrent": 10
        })
    });

    EndpointResponse {
        id: endpoint.id,
        model_version_id: endpoint.model_version_id,
        model_name: None, // Would need to join with model table to get this
        version: None,    // Would need to join with version table to get this
        name: endpoint.name,
        status: format!("{:?}", endpoint.status).to_lowercase(),
        port: endpoint.port,
        replicas: endpoint.replicas,
        config,
        error_message: endpoint.error_message,
        created_at: endpoint.created_at.to_rfc3339(),
        updated_at: endpoint.updated_at.to_rfc3339(),
    }
}

// ============================================================================
// Handlers
// ============================================================================

/// List all models
pub async fn list_models(
    State(state): State<AppState>,
    user: AuthUser,
    Query(query): Query<ListModelsQuery>,
) -> Result<Json<Vec<ModelResponse>>, AuthError> {
    let repo = ModelRepository::new(&state.db);

    let models = if user.role == "admin" {
        repo.list_all(Some(query.limit), Some(query.offset)).await
    } else {
        repo.list_by_user(&user.id, Some(query.limit), Some(query.offset))
            .await
    }
    .map_err(|e| AuthError::Internal(e.to_string()))?;

    // Fetch version info for each model
    let mut response = Vec::with_capacity(models.len());
    for model in models {
        let versions = repo.list_versions(&model.id).await.unwrap_or_default();
        let version_count = versions.len() as u32;
        let latest_version = versions.iter().map(|v| v.version).max();
        response.push(model_to_response(model, version_count, latest_version));
    }

    Ok(Json(response))
}

/// Create a new model
pub async fn create_model(
    State(state): State<AppState>,
    user: AuthUser,
    Json(req): Json<CreateModelRequest>,
) -> Result<(StatusCode, Json<ModelResponse>), AuthError> {
    let repo = ModelRepository::new(&state.db);

    let model = repo
        .create(NewModel {
            user_id: user.id,
            name: req.name,
            description: req.description,
            model_type: req.model_type,
        })
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    // Create model directory (model.id is server-generated UUID, safe for path use)
    validate_path_id(&model.id)?;
    let model_dir = state.config.models_dir().join(&model.id);
    std::fs::create_dir_all(&model_dir).ok();

    // New model has no versions yet
    Ok((StatusCode::CREATED, Json(model_to_response(model, 0, None))))
}

/// Get a model by ID
pub async fn get_model(
    State(state): State<AppState>,
    user: AuthUser,
    Path(id): Path<String>,
) -> Result<Json<ModelResponse>, AuthError> {
    let repo = ModelRepository::new(&state.db);

    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    // Check ownership
    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    // Get version info
    let versions = repo.list_versions(&id).await.unwrap_or_default();
    let version_count = versions.len() as u32;
    let latest_version = versions.iter().map(|v| v.version).max();

    Ok(Json(model_to_response(
        model,
        version_count,
        latest_version,
    )))
}

/// Update a model
pub async fn update_model(
    State(state): State<AppState>,
    user: AuthUser,
    Path(id): Path<String>,
    Json(req): Json<UpdateModelRequest>,
) -> Result<Json<ModelResponse>, AuthError> {
    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    let model = repo
        .update(&id, req.name, req.description)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    // Get version info
    let versions = repo.list_versions(&id).await.unwrap_or_default();
    let version_count = versions.len() as u32;
    let latest_version = versions.iter().map(|v| v.version).max();

    Ok(Json(model_to_response(
        model,
        version_count,
        latest_version,
    )))
}

/// Delete a model
pub async fn delete_model(
    State(state): State<AppState>,
    user: AuthUser,
    Path(id): Path<String>,
) -> Result<StatusCode, AuthError> {
    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    // SECURITY: Validate ID before using in file path
    validate_path_id(&id)?;

    // Delete model directory
    let model_dir = state.config.models_dir().join(&id);
    std::fs::remove_dir_all(&model_dir).ok();

    repo.delete(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    Ok(StatusCode::NO_CONTENT)
}

/// List versions for a model
pub async fn list_versions(
    State(state): State<AppState>,
    user: AuthUser,
    Path(id): Path<String>,
) -> Result<Json<Vec<ModelVersionResponse>>, AuthError> {
    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    let versions = repo
        .list_versions(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    let response: Vec<ModelVersionResponse> =
        versions.into_iter().map(version_to_response).collect();

    Ok(Json(response))
}

/// Upload a new model version
pub async fn upload_version(
    State(state): State<AppState>,
    user: AuthUser,
    Path(id): Path<String>,
    mut multipart: Multipart,
) -> Result<(StatusCode, Json<ModelVersionResponse>), AuthError> {
    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    // SECURITY: Validate ID before using in file path
    validate_path_id(&id)?;

    // Parse multipart
    let mut file_data: Option<Bytes> = None;
    let mut file_name: Option<String> = None;
    let mut metrics: Option<serde_json::Value> = None;
    let mut training_run_id: Option<String> = None;

    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
    {
        let name = field.name().unwrap_or_default().to_string();

        match name.as_str() {
            "file" => {
                file_name = field.file_name().map(|s| s.to_string());
                file_data = Some(
                    field
                        .bytes()
                        .await
                        .map_err(|e| AuthError::Internal(e.to_string()))?,
                );
            }
            "metrics" => {
                let text = field
                    .text()
                    .await
                    .map_err(|e| AuthError::Internal(e.to_string()))?;
                metrics = serde_json::from_str(&text).ok();
            }
            "training_run_id" => {
                training_run_id = Some(
                    field
                        .text()
                        .await
                        .map_err(|e| AuthError::Internal(e.to_string()))?,
                );
            }
            _ => {}
        }
    }

    let file_data = file_data.ok_or(AuthError::Internal("No file uploaded".to_string()))?;
    let file_size = file_data.len() as u64;

    // Determine file extension (sanitize to prevent path traversal)
    let extension = file_name
        .as_ref()
        .and_then(|n| n.rsplit('.').next())
        .unwrap_or("bin")
        .replace(['/', '\\', '.'], "");

    // Create version to get the version number
    let version = repo
        .create_version(NewModelVersion {
            model_id: id.clone(),
            file_path: String::new(), // Will update after saving file
            file_size,
            metrics,
            training_run_id,
        })
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    // Save file
    let version_dir = state
        .config
        .models_dir()
        .join(&id)
        .join(format!("v{}", version.version));
    std::fs::create_dir_all(&version_dir).map_err(|e| AuthError::Internal(e.to_string()))?;

    let file_path = version_dir.join(format!("model.{}", extension));
    let mut file = tokio::fs::File::create(&file_path)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    file.write_all(&file_data)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    // Update version with file path
    // Note: In production, we'd update the version record with the file path
    // For now, we return the version with the intended path
    let mut response = version_to_response(version);
    response.file_path = file_path.to_string_lossy().to_string();

    Ok((StatusCode::CREATED, Json(response)))
}

/// Get a model version
pub async fn get_version(
    State(state): State<AppState>,
    user: AuthUser,
    Path((id, version)): Path<(String, u32)>,
) -> Result<Json<ModelVersionResponse>, AuthError> {
    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    let ver = repo
        .get_version_by_number(&id, version)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::Internal("Version not found".to_string()))?;

    Ok(Json(version_to_response(ver)))
}

/// Delete a model version
pub async fn delete_version(
    State(state): State<AppState>,
    user: AuthUser,
    Path((id, version)): Path<(String, u32)>,
) -> Result<StatusCode, AuthError> {
    // SECURITY: Validate ID before using in file path
    validate_path_id(&id)?;

    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    let ver = repo
        .get_version_by_number(&id, version)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::Internal("Version not found".to_string()))?;

    // Delete version directory
    let version_dir = state
        .config
        .models_dir()
        .join(&id)
        .join(format!("v{}", version));
    std::fs::remove_dir_all(&version_dir).ok();

    repo.delete_version(&ver.id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    Ok(StatusCode::NO_CONTENT)
}

/// Download a model version
pub async fn download_version(
    State(state): State<AppState>,
    user: AuthUser,
    Path((id, version)): Path<(String, u32)>,
) -> Result<impl IntoResponse, AuthError> {
    // SECURITY: Validate ID before using in file path
    validate_path_id(&id)?;

    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    // Verify version exists
    let _ver = repo
        .get_version_by_number(&id, version)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::Internal("Version not found".to_string()))?;

    // Find the model file. `validate_path_id` above rejects `..`, `/`, `\`,
    // and null bytes in `id`, which blocks the textual path-traversal
    // attack. Additionally canonicalize the composed path and require it to
    // be under `models_dir` so a symlink inside `models_dir/<id>/` cannot
    // escape the root at filesystem-resolution time either.
    let models_root = state.config.models_dir();
    let version_dir = models_root.join(&id).join(format!("v{}", version));
    let mut file_path: Option<PathBuf> = None;

    if version_dir.exists() {
        let canon_root =
            std::fs::canonicalize(&models_root).map_err(|e| AuthError::Internal(e.to_string()))?;
        let canon_dir =
            std::fs::canonicalize(&version_dir).map_err(|e| AuthError::Internal(e.to_string()))?;
        if !canon_dir.starts_with(&canon_root) {
            return Err(AuthError::InvalidInput(
                "version_dir escapes models root".to_string(),
            ));
        }
        for entry in std::fs::read_dir(&canon_dir)
            .map_err(|e| AuthError::Internal(e.to_string()))?
            .flatten()
        {
            let path = entry.path();
            if path.is_file() && path.starts_with(&canon_root) {
                file_path = Some(path);
                break;
            }
        }
    }

    let file_path = file_path.ok_or(AuthError::Internal("Model file not found".to_string()))?;
    let file_name = file_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("model.bin")
        .to_string();

    let file_data = tokio::fs::read(&file_path)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    let content_disposition = format!("attachment; filename=\"{}\"", file_name);

    Ok((
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "application/octet-stream".to_string()),
            (header::CONTENT_DISPOSITION, content_disposition),
        ],
        file_data,
    ))
}

/// Deploy a model version to inference endpoint
pub async fn deploy_version(
    State(state): State<AppState>,
    user: AuthUser,
    Path((id, version)): Path<(String, u32)>,
    Json(req): Json<DeployRequest>,
) -> Result<(StatusCode, Json<EndpointResponse>), AuthError> {
    let repo = ModelRepository::new(&state.db);

    // Check ownership
    let model = repo
        .find_by_id(&id)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::NotFound("Model not found".to_string()))?;

    if model.user_id != user.id && user.role != "admin" {
        return Err(AuthError::Unauthorized);
    }

    let ver = repo
        .get_version_by_number(&id, version)
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?
        .ok_or(AuthError::Internal("Version not found".to_string()))?;

    // Create endpoint
    let endpoint = repo
        .create_endpoint(NewEndpoint {
            model_version_id: ver.id,
            name: req.name,
            port: req.port,
            replicas: req.replicas,
            config: req.config,
        })
        .await
        .map_err(|e| AuthError::Internal(e.to_string()))?;

    Ok((StatusCode::CREATED, Json(endpoint_to_response(endpoint))))
}