fukurow-cli 0.1.0

Command-line interface for Fukurow reasoning and knowledge graph operations
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
//! CLI command definitions and handlers

use clap::{Parser, Subcommand};
use fukurow_engine::ReasonerEngine;
use fukurow_core::model::CyberEvent;
use fukurow_domain_cyber::threat_intelligence::{ThreatProcessor, IndicatorType};
use std::path::PathBuf;
use anyhow::Result;

/// Main CLI structure
#[derive(Parser)]
#[command(name = "reasoner")]
#[command(about = "JSON-LD Reasoner for Cyber Security Events")]
#[command(version = env!("CARGO_PKG_VERSION"))]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

/// Available CLI commands
#[derive(Subcommand)]
pub enum Commands {
    /// Start the API server
    Serve {
        /// Host to bind to
        #[arg(long, default_value = "0.0.0.0")]
        host: String,

        /// Port to bind to
        #[arg(short, long, default_value = "3000")]
        port: u16,
    },

    /// Analyze a single event
    Analyze {
        /// Event data as JSON file
        #[arg(short, long)]
        file: Option<PathBuf>,

        /// Event data as JSON string
        #[arg(short, long)]
        json: Option<String>,

        /// Output format
        #[arg(short, long, default_value = "text")]
        format: OutputFormat,
    },

    /// Process events from file
    Process {
        /// Input file containing events
        #[arg(short, long)]
        input: PathBuf,

        /// Output file for results
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Output format
        #[arg(short, long, default_value = "json")]
        format: OutputFormat,
    },

    /// Query the knowledge graph
    Query {
        /// Subject filter
        #[arg(short, long)]
        subject: Option<String>,

        /// Predicate filter
        #[arg(short, long)]
        predicate: Option<String>,

        /// Object filter
        #[arg(short, long)]
        object: Option<String>,

        /// Output format
        #[arg(short, long, default_value = "text")]
        format: OutputFormat,
    },

    /// Threat intelligence operations
    Threat {
        #[command(subcommand)]
        command: ThreatCommands,
    },

    /// Show system information
    Info,
}

/// Threat intelligence subcommands
#[derive(Subcommand)]
pub enum ThreatCommands {
    /// Show threat intelligence statistics
    Stats,

    /// Export threat indicators
    Export {
        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Import threat indicators
    Import {
        /// Input file containing indicators
        #[arg(short, long)]
        input: PathBuf,
    },

    /// Check if value is a known threat
    Check {
        /// Value to check
        #[arg(short, long)]
        value: String,

        /// Type of indicator (ip, domain, hash, etc.)
        #[arg(short, long)]
        r#type: String,
    },
}

/// Output format options
#[derive(Clone, Debug, PartialEq, clap::ValueEnum)]
pub enum OutputFormat {
    Text,
    Json,
    JsonPretty,
}

/// Command execution result
pub struct CommandResult {
    pub success: bool,
    pub message: String,
    pub data: Option<serde_json::Value>,
}

/// Execute CLI commands
pub struct CommandExecutor {
    reasoner: ReasonerEngine,
    threat_processor: ThreatProcessor,
}

impl CommandExecutor {
    pub fn new() -> Self {
        let reasoner = ReasonerEngine::new();
        // Note: Adding default rules to reasoner would require API change

        Self {
            reasoner,
            threat_processor: ThreatProcessor::new(),
        }
    }

    /// Execute a CLI command
    pub async fn execute(&mut self, command: Commands) -> Result<CommandResult> {
        match command {
            Commands::Serve { host, port } => self.execute_serve(host, port).await,
            Commands::Analyze { file, json, format } => self.execute_analyze(file, json, format).await,
            Commands::Process { input, output, format } => self.execute_process(input, output, format).await,
            Commands::Query { subject, predicate, object, format } => {
                self.execute_query(subject, predicate, object, format).await
            }
            Commands::Threat { command } => self.execute_threat_command(command).await,
            Commands::Info => self.execute_info(),
        }
    }

    async fn execute_serve(&self, host: String, port: u16) -> Result<CommandResult> {
        use fukurow_api::{ReasonerServer, ServerConfig};

        let config = ServerConfig { host: host.clone(), port, max_connections: 100 };
        let server = ReasonerServer::with_config(config);

        println!("Starting server on {}:{}", host, port);
        println!("Press Ctrl+C to stop");

        server.serve().await?;

        Ok(CommandResult {
            success: true,
            message: "Server stopped".to_string(),
            data: None,
        })
    }

    async fn execute_analyze(
        &mut self,
        file: Option<PathBuf>,
        json: Option<String>,
        format: OutputFormat,
    ) -> Result<CommandResult> {
        let event_data = if let Some(file_path) = file {
            std::fs::read_to_string(file_path)?
        } else if let Some(json_str) = json {
            json_str
        } else {
            return Err(anyhow::anyhow!("Either --file or --json must be specified"));
        };

        let event: CyberEvent = serde_json::from_str(&event_data)?;

        self.reasoner.add_event(event).await?;
        let actions = self.reasoner.reason().await?;

        match format {
            OutputFormat::Text => {
                println!("Event analyzed successfully\nActions proposed: {}", actions.len());
                for (i, action) in actions.iter().enumerate() {
                    println!("{}. {:?}", i + 1, action);
                }
            }
            OutputFormat::Json => println!("{}", serde_json::to_string(&actions)?),
            OutputFormat::JsonPretty => println!("{}", serde_json::to_string_pretty(&actions)?),
        }

        Ok(CommandResult {
            success: true,
            message: "Event analyzed".to_string(),
            data: Some(serde_json::json!({ "actions": actions })),
        })
    }

    async fn execute_process(
        &mut self,
        input: PathBuf,
        output: Option<PathBuf>,
        format: OutputFormat,
    ) -> Result<CommandResult> {
        let content = std::fs::read_to_string(&input)?;
        let events: Vec<CyberEvent> = serde_json::from_str(&content)?;

        let mut all_actions = Vec::new();
        let mut processed_count = 0;

        for event in events {
            self.reasoner.add_event(event).await?;
            processed_count += 1;
        }

        let actions = self.reasoner.reason().await?;
        all_actions.extend(actions);

        let result = match format {
            OutputFormat::Text => {
                format!("Processed {} events, generated {} actions", processed_count, all_actions.len())
            }
            OutputFormat::Json => serde_json::to_string(&all_actions)?,
            OutputFormat::JsonPretty => serde_json::to_string_pretty(&all_actions)?,
        };

        if let Some(output_path) = output {
            std::fs::write(output_path, &result)?;
        } else {
            println!("{}", result);
        }

        Ok(CommandResult {
            success: true,
            message: format!("Processed {} events", processed_count),
            data: Some(serde_json::json!({
                "processed_events": processed_count,
                "actions": all_actions
            })),
        })
    }

    async fn execute_query(
        &self,
        subject: Option<String>,
        predicate: Option<String>,
        object: Option<String>,
        format: OutputFormat,
    ) -> Result<CommandResult> {
        let store = self.reasoner.get_graph_store().await;
        let graph_store = store.read().await;

        let triples = graph_store.find_triples(
            subject.as_deref(),
            predicate.as_deref(),
            object.as_deref(),
        );

        let count = triples.len();
        let result = match format {
            OutputFormat::Text => {
                let mut output = format!("Found {} triples:\n", count);
                for triple in &triples {
                    output.push_str(&format!("  {} {} {}\n", triple.triple.subject, triple.triple.predicate, triple.triple.object));
                }
                output
            }
            OutputFormat::Json => serde_json::to_string(&triples)?,
            OutputFormat::JsonPretty => serde_json::to_string_pretty(&triples)?,
        };

        println!("{}", result);

        Ok(CommandResult {
            success: true,
            message: format!("Found {} triples", count),
            data: Some(serde_json::json!({ "triples": triples })),
        })
    }

    async fn execute_threat_command(&self, command: ThreatCommands) -> Result<CommandResult> {
        match command {
            ThreatCommands::Stats => {
                let stats = self.threat_processor.get_statistics();
                let result = serde_json::to_string_pretty(&stats)?;
                println!("{}", result);

                Ok(CommandResult {
                    success: true,
                    message: "Threat intelligence statistics".to_string(),
                    data: Some(serde_json::json!(stats)),
                })
            }
            ThreatCommands::Export { output } => {
                let json_data = self.threat_processor.export_indicators()?;

                if let Some(output_path) = output {
                    std::fs::write(output_path, &json_data)?;
                } else {
                    println!("{}", json_data);
                }

                Ok(CommandResult {
                    success: true,
                    message: "Threat indicators exported".to_string(),
                    data: Some(serde_json::json!({ "exported": true })),
                })
            }
            ThreatCommands::Import { input } => {
                let _content = std::fs::read_to_string(input)?;
                // Note: Would need mutable access to threat processor
                println!("Import functionality not yet implemented");

                Ok(CommandResult {
                    success: false,
                    message: "Import not implemented".to_string(),
                    data: None,
                })
            }
            ThreatCommands::Check { value, r#type } => {
                // Parse indicator type
                let indicator_type = match r#type.as_str() {
                    "ip" => IndicatorType::IpAddress,
                    "domain" => IndicatorType::Domain,
                    "hash" => IndicatorType::FileHash,
                    _ => return Err(anyhow::anyhow!("Unknown indicator type: {}", r#type)),
                };

                let is_threat = self.threat_processor.process_event(&value, indicator_type);

                let result = if let Some(ref threat_info) = is_threat {
                    format!("THREAT DETECTED: {} - {}", value, threat_info)
                } else {
                    format!("No threat detected for: {}", value)
                };

                println!("{}", result);

                Ok(CommandResult {
                    success: true,
                    message: "Threat check completed".to_string(),
                    data: Some(serde_json::json!({
                        "value": value,
                        "type": r#type,
                        "is_threat": is_threat.is_some(),
                        "threat_info": is_threat
                    })),
                })
            }
        }
    }

    fn execute_info(&self) -> Result<CommandResult> {
        let info = serde_json::json!({
            "name": env!("CARGO_PKG_NAME"),
            "version": env!("CARGO_PKG_VERSION"),
            "description": env!("CARGO_PKG_DESCRIPTION"),
            "authors": env!("CARGO_PKG_AUTHORS"),
            "repository": env!("CARGO_PKG_REPOSITORY"),
            "rust_version": "1.70+",
            "features": ["jsonld", "cyber-security", "rest-api", "cli"]
        });

        let result = serde_json::to_string_pretty(&info)?;
        println!("{}", result);

        Ok(CommandResult {
            success: true,
            message: "System information".to_string(),
            data: Some(info),
        })
    }
}

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