raxit-core 0.1.2

Core security scanning engine for AI agent applications
Documentation
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
//! Agent Assets Schema - Data structures for RAXIT scan results
//!
//! Based on Agent Assets Schema v0.1.0 from SPEC.md

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Complete scan result including all discovered assets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanResult {
    /// Manifest section (SPEC.md v0.1.0)
    pub manifest: Manifest,

    /// Discovered agents
    pub agents: Vec<Agent>,

    /// Discovered tools
    pub tools: Vec<Tool>,

    /// Discovered models
    pub models: Vec<Model>,

    /// Memory configurations
    pub memory: Vec<Memory>,

    /// Trust boundaries
    #[serde(rename = "trustBoundaries")]
    pub trust_boundaries: Vec<TrustBoundary>,

    /// Secret findings
    #[serde(rename = "secretFindings", skip_serializing_if = "Vec::is_empty")]
    pub secret_findings: Vec<SecretFinding>,

    /// Memory findings
    #[serde(rename = "memoryFindings", skip_serializing_if = "Vec::is_empty")]
    pub memory_findings: Vec<MemoryFinding>,

    /// Network findings
    #[serde(rename = "networkFindings", skip_serializing_if = "Vec::is_empty")]
    pub network_findings: Vec<NetworkFinding>,

    /// Provenance findings
    #[serde(rename = "provenanceFindings", skip_serializing_if = "Vec::is_empty")]
    pub provenance_findings: Vec<ProvenanceFinding>,
}

impl ScanResult {
    pub fn new() -> Self {
        Self {
            manifest: Manifest::default(),
            agents: Vec::new(),
            tools: Vec::new(),
            models: Vec::new(),
            memory: Vec::new(),
            trust_boundaries: Vec::new(),
            secret_findings: Vec::new(),
            memory_findings: Vec::new(),
            network_findings: Vec::new(),
            provenance_findings: Vec::new(),
        }
    }

    pub fn to_yaml(&self) -> crate::Result<String> {
        serde_yaml::to_string(self).map_err(Into::into)
    }

    pub fn to_json(&self) -> crate::Result<String> {
        serde_json::to_string_pretty(self).map_err(Into::into)
    }
}

impl Default for ScanResult {
    fn default() -> Self {
        Self::new()
    }
}

/// Alias for backward compatibility
pub type AgentAssets = ScanResult;

/// Manifest section - metadata about the scan and project (SPEC.md v0.1.0)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Manifest {
    /// Schema version
    pub schema_version: String,

    /// Subject - project being scanned
    pub subject: Subject,

    /// Unique scan ID
    pub scan_id: String,

    /// Timestamp when scan was performed
    pub scanned_at: String,

    /// Tool that performed the scan
    pub scanned_by: String,

    /// Files included in scan
    pub files: Vec<String>,

    /// Scan configuration
    pub scan_config: ScanConfigMetadata,

    /// Signature (optional, when signed via RAXIT API)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<Signature>,
}

impl Default for Manifest {
    fn default() -> Self {
        Self {
            schema_version: "0.1.0".to_string(),
            subject: Subject::default(),
            scan_id: generate_scan_id(),
            scanned_at: chrono::Utc::now().to_rfc3339(),
            scanned_by: format!("raxit-cli/{}", env!("CARGO_PKG_VERSION")),
            files: Vec::new(),
            scan_config: ScanConfigMetadata::default(),
            signature: None,
        }
    }
}

/// Subject - project being scanned
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subject {
    /// Project name
    pub name: String,

    /// Project version (from pyproject.toml if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Source repository URL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

impl Default for Subject {
    fn default() -> Self {
        Self {
            name: "unknown".to_string(),
            version: None,
            source: None,
        }
    }
}

/// Scan configuration metadata for reproducibility
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanConfigMetadata {
    /// Exclude patterns used
    pub exclude_patterns: Vec<String>,

    /// Frameworks detected
    pub frameworks_detected: Vec<String>,

    /// Number of parallel workers used
    pub parallel_workers: usize,

    /// Whether incremental scanning was enabled
    pub incremental: bool,

    /// Number of files scanned
    pub files_scanned: usize,

    /// Number of files skipped (incremental mode)
    pub files_skipped: usize,
}

impl Default for ScanConfigMetadata {
    fn default() -> Self {
        Self {
            exclude_patterns: Vec::new(),
            frameworks_detected: Vec::new(),
            parallel_workers: 1,
            incremental: false,
            files_scanned: 0,
            files_skipped: 0,
        }
    }
}

/// Signature from RAXIT API (optional)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Signature {
    /// Digest of the schema
    pub digest: String,

    /// Signing algorithm
    pub algorithm: String,

    /// Base64-encoded signature value
    pub signature_value: String,

    /// Timestamp when signed
    pub signed_at: String,

    /// Key metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_metadata: Option<KeyMetadata>,

    /// Attestation information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attestation: Option<Attestation>,
}

/// Key metadata from RAXIT API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyMetadata {
    pub key_id: String,
    pub key_version: String,
}

/// Attestation information from RAXIT API
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Attestation {
    pub project_id: String,
    pub project_name: String,
    pub organization: String,
    pub signed_by: String,
}

/// Generate a unique scan ID
fn generate_scan_id() -> String {
    let now = chrono::Utc::now();
    let random_suffix: String = (0..6)
        .map(|_| format!("{:x}", rand::random::<u8>() % 16))
        .collect();
    format!("scan-{}-{}", now.format("%Y%m%d"), random_suffix)
}

/// Metadata about the scan (legacy compatibility)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanMetadata {
    /// Framework name (e.g., "pydantic-ai", "langgraph")
    pub framework: String,

    /// Framework version
    #[serde(rename = "frameworkVersion")]
    pub framework_version: Option<String>,

    /// Scan timestamp
    pub timestamp: String,

    /// RAXIT SDK version
    #[serde(rename = "raxitVersion")]
    pub raxit_version: String,

    /// Source path scanned
    pub source_path: String,
}

impl Default for ScanMetadata {
    fn default() -> Self {
        Self {
            framework: "unknown".to_string(),
            framework_version: None,
            timestamp: chrono::Utc::now().to_rfc3339(),
            raxit_version: env!("CARGO_PKG_VERSION").to_string(),
            source_path: ".".to_string(),
        }
    }
}

/// Agent definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Agent {
    /// Unique agent identifier
    pub id: String,

    /// Agent name
    pub name: String,

    /// Source location
    pub location: SourceLocation,

    /// Model used by agent
    #[serde(rename = "modelId")]
    pub model_id: Option<String>,

    /// Tools available to agent
    #[serde(rename = "toolIds")]
    pub tool_ids: Vec<String>,

    /// Memory configuration
    #[serde(rename = "memoryId")]
    pub memory_id: Option<String>,

    /// System prompt
    #[serde(rename = "systemPrompt")]
    pub system_prompt: Option<String>,

    /// Result type schema
    #[serde(rename = "resultType")]
    pub result_type: Option<String>,

    /// Dependencies type
    #[serde(rename = "depsType")]
    pub deps_type: Option<String>,
}

/// Tool definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tool {
    /// Unique tool identifier
    pub id: String,

    /// Tool name
    pub name: String,

    /// Source location
    pub location: SourceLocation,

    /// Tool description
    pub description: Option<String>,

    /// Parameters schema
    pub parameters: Option<HashMap<String, String>>,

    /// Whether tool requires context
    #[serde(rename = "requiresContext")]
    pub requires_context: bool,

    /// Tool type (plain or context-aware)
    #[serde(rename = "toolType")]
    pub tool_type: String,

    /// Data flows (CaMeL-style provenance)
    #[serde(rename = "dataFlows")]
    pub data_flows: Vec<DataFlow>,
}

/// Model configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Model {
    /// Unique model identifier
    pub id: String,

    /// Provider (e.g., "openai", "anthropic")
    pub provider: String,

    /// Model name
    #[serde(rename = "modelName")]
    pub model_name: String,

    /// Source location
    pub location: SourceLocation,

    /// Configuration parameters
    pub config: HashMap<String, String>,
}

/// Memory configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Memory {
    /// Unique memory identifier
    pub id: String,

    /// Memory type
    #[serde(rename = "memoryType")]
    pub memory_type: String,

    /// Source location
    pub location: SourceLocation,

    /// Configuration
    pub config: HashMap<String, String>,
}

/// Trust boundary definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustBoundary {
    /// Boundary identifier
    pub id: String,

    /// Component ID (agent or tool)
    #[serde(rename = "componentId")]
    pub component_id: String,

    /// Component type
    #[serde(rename = "componentType")]
    pub component_type: String,

    /// Untrusted input (A)
    #[serde(rename = "hasUntrustedInput")]
    pub has_untrusted_input: bool,

    /// Sensitive access (B)
    #[serde(rename = "hasSensitiveAccess")]
    pub has_sensitive_access: bool,

    /// External actions (C)
    #[serde(rename = "hasExternalActions")]
    pub has_external_actions: bool,

    /// Compliance status
    pub compliant: bool,

    /// Violations (if not compliant)
    pub violations: Vec<String>,

    /// Source location
    pub location: SourceLocation,
}

/// Secret finding from secret detection analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretFinding {
    /// Unique finding identifier
    pub id: String,

    /// Type of secret detected
    #[serde(rename = "secretType")]
    pub secret_type: String,

    /// Source location
    pub location: SourceLocation,

    /// Severity level (critical, high, medium, low)
    pub severity: String,

    /// Description of the finding
    pub message: String,

    /// Matched pattern (masked for security)
    #[serde(rename = "matchedPattern", skip_serializing_if = "Option::is_none")]
    pub matched_pattern: Option<String>,
}

/// Memory finding from memory detection analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryFinding {
    /// Unique finding identifier
    pub id: String,

    /// Type of memory usage (vector_store, database, file_persistence, etc.)
    #[serde(rename = "memoryType")]
    pub memory_type: String,

    /// Technology used (chroma, pinecone, sqlite, redis, etc.)
    pub technology: String,

    /// Source location
    pub location: SourceLocation,

    /// Configuration details (connection string, file path, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub configuration: Option<String>,

    /// Description of the finding
    pub message: String,
}

/// Network finding from network detection analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkFinding {
    /// Unique finding identifier
    pub id: String,

    /// Type of network usage (http_call, api_client, socket_connection, etc.)
    #[serde(rename = "networkType")]
    pub network_type: String,

    /// Technology used (requests, httpx, openai, etc.)
    pub technology: String,

    /// Source location
    pub location: SourceLocation,

    /// Endpoint URL (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,

    /// HTTP method (GET, POST, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,

    /// Description of the finding
    pub message: String,
}

/// Provenance finding from data provenance analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceFinding {
    /// Unique finding identifier
    pub id: String,

    /// Type of finding (tainted_sink, unsafe_flow, etc.)
    #[serde(rename = "findingType")]
    pub finding_type: String,

    /// Source type (untrusted_input, external_data, etc.)
    #[serde(rename = "sourceType")]
    pub source_type: String,

    /// Sink type (print, file_write, database_insert, etc.)
    #[serde(rename = "sinkType")]
    pub sink_type: String,

    /// Tainted variables involved
    #[serde(rename = "taintedVariables")]
    pub tainted_variables: Vec<String>,

    /// Source location
    pub location: SourceLocation,

    /// Severity level (critical, high, medium, low)
    pub severity: String,

    /// Description of the finding
    pub message: String,

    /// Data flow path (optional)
    #[serde(rename = "dataFlow", skip_serializing_if = "Option::is_none")]
    pub data_flow: Option<String>,
}

/// Data flow for CaMeL-style provenance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataFlow {
    /// Variable or data identifier
    pub variable: String,

    /// Data source
    pub source: String,

    /// Readers
    pub readers: Vec<String>,

    /// Writers
    pub writers: Vec<String>,

    /// Taint level
    #[serde(rename = "taintLevel")]
    pub taint_level: String,
}

/// Source code location
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceLocation {
    /// File path
    pub file: String,

    /// Start line
    pub line: u32,

    /// End line
    #[serde(rename = "endLine")]
    pub end_line: Option<u32>,

    /// Function or class name
    pub function: Option<String>,
}

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

    #[test]
    fn test_scan_result_serialization() {
        let result = ScanResult::new();
        let yaml = result.to_yaml();
        assert!(yaml.is_ok());

        let json = result.to_json();
        assert!(json.is_ok());
    }

    #[test]
    fn test_default_metadata() {
        let result = ScanResult::default();
        assert_eq!(result.manifest.schema_version, "0.1.0");
        assert!(result
            .manifest
            .scanned_by
            .contains(env!("CARGO_PKG_VERSION")));
    }
}