ave-http 0.10.0

HTTP API server for the Ave runtime, auth system, and admin surface
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
// Ave HTTP Auth System - Data Models
//
// This module defines the core data structures for the authentication and authorization system.

use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use utoipa::ToSchema;

fn serialize_ts<S>(ts: &i64, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serialize_ts_opt(&Some(*ts), serializer)
}

fn serialize_ts_opt<S>(
    ts: &Option<i64>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    let formatted = ts.as_ref().map_or_else(String::new, |v| {
        OffsetDateTime::from_unix_timestamp(*v).map_or_else(
            |_| String::new(),
            |dt| dt.format(&Rfc3339).unwrap_or_default(),
        )
    });
    serializer.serialize_str(&formatted)
}

// =============================================================================
// COMMON ERROR RESPONSE
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ErrorResponse {
    pub error: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct PaginationQuery {
    pub limit: Option<i64>,
    pub offset: Option<i64>,
}

impl IntoResponse for ErrorResponse {
    fn into_response(self) -> Response {
        (StatusCode::BAD_REQUEST, Json(self)).into_response()
    }
}

// =============================================================================
// USER MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct User {
    pub id: i64,
    pub username: String,
    #[serde(skip_serializing)]
    pub password_hash: String,
    pub is_active: bool,
    pub is_deleted: bool,
    pub must_change_password: bool,
    pub failed_login_attempts: i32,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub locked_until: Option<i64>,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub last_login_at: Option<i64>,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub updated_at: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UserInfo {
    /// User ID
    pub id: i64,
    /// Username
    pub username: String,
    /// Is account active
    pub is_active: bool,
    /// Must change password on next login
    pub must_change_password: bool,
    /// Failed login attempts
    pub failed_login_attempts: i32,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub locked_until: Option<i64>,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub last_login_at: Option<i64>,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
    /// Roles assigned to this user
    pub roles: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CreateUserRequest {
    pub username: String,
    pub password: String,
    pub role_ids: Option<Vec<i64>>,
    pub must_change_password: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct UpdateUserRequest {
    pub password: Option<String>,
    pub is_active: Option<bool>,
    pub role_ids: Option<Vec<i64>>,
}

// =============================================================================
// ROLE MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Role {
    pub id: i64,
    pub name: Option<String>,
    pub description: Option<String>,
    pub is_system: bool,
    pub is_deleted: bool,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub updated_at: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RoleInfo {
    pub id: i64,
    pub name: String,
    pub description: Option<String>,
    pub is_system: bool,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
    pub permission_count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CreateRoleRequest {
    pub name: String,
    pub description: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct UpdateRoleRequest {
    pub description: Option<String>,
}

// =============================================================================
// RESOURCE AND ACTION MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Resource {
    pub id: i64,
    pub name: String,
    pub description: Option<String>,
    pub is_system: bool,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct Action {
    pub id: i64,
    pub name: String,
    pub description: Option<String>,
    pub is_system: bool,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
}

// =============================================================================
// PERMISSION MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Permission {
    pub resource: String,
    pub action: String,
    pub allowed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_system: Option<bool>,
    /// Source of the permission: 'direct' (user-specific) or 'role' (inherited from role)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// If source is 'role', the name of the role providing this permission
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role_name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct SetPermissionRequest {
    pub resource: String,
    pub action: String,
    pub allowed: bool,
}

// =============================================================================
// API KEY MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApiKeyInfo {
    /// UUID identifier - serves as both public ID and primary key
    pub id: String,
    #[serde(skip_serializing)]
    pub user_id: i64,
    pub username: String,
    pub key_prefix: String,
    pub name: String,
    pub description: Option<String>,
    pub is_management: bool,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub expires_at: Option<i64>,
    pub revoked: bool,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub revoked_at: Option<i64>,
    pub revoked_reason: Option<String>,
    #[serde(serialize_with = "serialize_ts_opt", skip_deserializing)]
    pub last_used_at: Option<i64>,
    pub last_used_ip: Option<String>,
    pub plan_id: Option<String>,
    pub plan_name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CreateApiKeyRequest {
    pub name: String,
    pub description: Option<String>,
    pub expires_in_seconds: Option<i64>,
}

/// Request payload for rotating an API key
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RotateApiKeyRequest {
    pub name: Option<String>,
    pub description: Option<String>,
    pub expires_in_seconds: Option<i64>,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CreateApiKeyResponse {
    pub api_key: String,
    pub key_info: ApiKeyInfo,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RevokeApiKeyRequest {
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct UsagePlan {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub monthly_events: i64,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub updated_at: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CreateUsagePlanRequest {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub monthly_events: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct UpdateUsagePlanRequest {
    pub name: Option<String>,
    pub description: Option<String>,
    pub monthly_events: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AssignApiKeyPlanRequest {
    pub plan_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct CreateQuotaExtensionRequest {
    pub extra_events: i64,
    /// UTC month in YYYY-MM format. If omitted, current UTC month is used.
    pub usage_month: Option<String>,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct QuotaExtensionInfo {
    pub id: i64,
    pub api_key_id: String,
    pub api_key_name: Option<String>,
    pub usage_month: String,
    pub extra_events: i64,
    pub reason: Option<String>,
    pub created_by: Option<i64>,
    pub created_by_username: Option<String>,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub created_at: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApiKeyQuotaStatus {
    pub api_key_id: String,
    pub api_key_name: Option<String>,
    pub usage_month: String,
    pub plan_id: Option<String>,
    pub plan_name: Option<String>,
    pub plan_limit: Option<i64>,
    pub extensions_total: i64,
    pub effective_limit: Option<i64>,
    pub used_events: i64,
    pub remaining_events: Option<i64>,
    pub has_quota: bool,
}

// =============================================================================
// AUDIT LOG MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuditLog {
    pub id: i64,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub timestamp: i64,
    pub user_id: Option<i64>,
    pub username: Option<String>,
    pub api_key_id: Option<String>,
    pub api_key_name: Option<String>,
    pub action_type: String,
    pub endpoint: Option<String>,
    pub http_method: Option<String>,
    pub ip_address: Option<String>,
    pub user_agent: Option<String>,
    pub request_id: Option<String>,
    pub details: Option<String>,
    pub success: bool,
    pub error_message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct AuditLogQuery {
    pub user_id: Option<i64>,
    pub api_key_id: Option<String>,
    pub endpoint: Option<String>,
    pub http_method: Option<String>,
    pub ip_address: Option<String>,
    pub user_agent: Option<String>,
    pub success: Option<bool>,
    pub start_timestamp: Option<i64>,
    pub end_timestamp: Option<i64>,
    pub limit: Option<i64>,
    pub offset: Option<i64>,
    // Exclusion filters (NOT conditions)
    pub exclude_user_id: Option<i64>,
    pub exclude_api_key_id: Option<String>,
    pub exclude_ip_address: Option<String>,
    pub exclude_endpoint: Option<String>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuditLogPage {
    pub items: Vec<AuditLog>,
    pub limit: i64,
    pub offset: i64,
    pub total: i64,
    pub has_more: bool,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuditValueCount {
    pub value: String,
    pub count: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuditUserCount {
    pub user_id: i64,
    pub username: Option<String>,
    pub count: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuditApiKeyCount {
    pub api_key_id: String,
    pub api_key_name: Option<String>,
    pub user_id: Option<i64>,
    pub username: Option<String>,
    pub count: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct AuditStats {
    pub total_logs: i64,
    pub success_count: i64,
    pub failure_count: i64,
    pub success_rate: f64,
    pub top_action_types: Vec<AuditValueCount>,
    pub top_users: Vec<AuditUserCount>,
    pub top_api_keys: Vec<AuditApiKeyCount>,
    pub top_endpoints: Vec<AuditValueCount>,
    pub top_http_methods: Vec<AuditValueCount>,
    pub top_ip_addresses: Vec<AuditValueCount>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RateLimitApiKeyStats {
    pub api_key_id: Option<String>,
    pub key_name: Option<String>,
    pub user_id: Option<i64>,
    pub username: Option<String>,
    pub total_requests: i64,
    pub last_request_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RateLimitIpStats {
    pub ip_address: Option<String>,
    pub total_requests: i64,
    pub last_request_at: Option<String>,
    pub unique_api_keys: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RateLimitEndpointStats {
    pub endpoint: Option<String>,
    pub total_requests: i64,
    pub last_request_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RateLimitIpEndpointStats {
    pub ip_address: Option<String>,
    pub endpoint: Option<String>,
    pub total_requests: i64,
    pub last_request_at: Option<String>,
    pub unique_api_keys: i64,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct RateLimitStats {
    pub total_requests: i64,
    pub window_seconds: i64,
    pub max_requests_per_window: u32,
    pub by_api_key: Vec<RateLimitApiKeyStats>,
    pub by_ip: Vec<RateLimitIpStats>,
    pub by_endpoint: Vec<RateLimitEndpointStats>,
    pub by_ip_endpoint: Vec<RateLimitIpEndpointStats>,
}

// =============================================================================
// AUTHENTICATION MODELS
// =============================================================================

#[derive(Debug, Clone, Deserialize, ToSchema)]
pub struct LoginRequest {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct LoginResponse {
    pub api_key: String,
    pub user: UserInfo,
    pub permissions: Vec<Permission>,
}

// =============================================================================
// AUTH CONTEXT (Internal use, not for API)
// =============================================================================

#[derive(Debug, Clone)]
pub struct AuthContext {
    pub user_id: i64,
    pub username: String,
    pub roles: Vec<String>,
    pub permissions: Vec<Permission>,
    pub api_key_id: String, // UUID
    pub is_management_key: bool,
    pub ip_address: Option<String>,
}

impl AuthContext {
    /// Check if user has the superadmin role
    pub fn is_superadmin(&self) -> bool {
        self.roles.iter().any(|r| r == "superadmin")
    }

    /// Check if user has permission for a specific resource and action
    pub fn has_permission(&self, resource: &str, action: &str) -> bool {
        // Superadmin role always has all permissions
        if self.is_superadmin() {
            return true;
        }

        // Check permissions list
        // Denials take precedence over allows
        let mut has_allow = false;
        let mut has_deny = false;

        for perm in &self.permissions {
            if perm.resource != resource {
                continue;
            }

            // "all" acts as wildcard over actions
            if perm.action != action && perm.action != "all" {
                continue;
            }

            if perm.allowed {
                has_allow = true;
            } else {
                has_deny = true;
            }
        }

        // If there's an explicit deny, return false
        if has_deny {
            return false;
        }

        // Otherwise return true if there's an allow
        has_allow
    }
}

// =============================================================================
// SYSTEM CONFIG MODELS
// =============================================================================

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct SystemConfig {
    pub key: String,
    pub value_type: SystemConfigValueType,
    pub value: SystemConfigValue,
    pub description: Option<String>,
    #[serde(serialize_with = "serialize_ts", skip_deserializing)]
    pub updated_at: i64,
    pub updated_by: Option<i64>,
    pub updated_by_username: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct UpdateSystemConfigRequest {
    pub value: SystemConfigValue,
}

#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct SystemConfigPage {
    pub items: Vec<SystemConfig>,
    pub limit: i64,
    pub offset: i64,
    pub total: i64,
    pub has_more: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SystemConfigValueType {
    Integer,
    Boolean,
    EndpointRateLimits,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
pub struct SystemConfigEndpointRateLimit {
    pub endpoint: String,
    pub max_requests: u32,
    pub window_seconds: Option<i64>,
}

impl From<ave_bridge::auth::EndpointRateLimit>
    for SystemConfigEndpointRateLimit
{
    fn from(value: ave_bridge::auth::EndpointRateLimit) -> Self {
        Self {
            endpoint: value.endpoint,
            max_requests: value.max_requests,
            window_seconds: value.window_seconds,
        }
    }
}

impl From<SystemConfigEndpointRateLimit>
    for ave_bridge::auth::EndpointRateLimit
{
    fn from(value: SystemConfigEndpointRateLimit) -> Self {
        Self {
            endpoint: value.endpoint,
            max_requests: value.max_requests,
            window_seconds: value.window_seconds,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
#[serde(untagged)]
pub enum SystemConfigValue {
    Integer(i64),
    Boolean(bool),
    EndpointRateLimits(Vec<SystemConfigEndpointRateLimit>),
}