shellfirm 0.3.8

`shellfirm` will intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification, kinda like a captcha for your terminal.
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
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
//! LLM-powered semantic command analysis (feature-gated behind `llm`).
//!
//! Provides optional deep analysis of commands using large language models.
//! This can catch risks that regex patterns miss (e.g. subtle data exfiltration,
//! semantic intent behind complex pipelines).
//!
//! **Safety rule:** LLM analysis can only *increase* risk (flip allowed → denied),
//! never *decrease* it. LLM failure silently falls back to regex-only results.

use crate::error::Result;
use serde_derive::{Deserialize, Serialize};

use crate::config::LlmConfig;
use crate::env::Environment;

/// Result of LLM command analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmAnalysis {
    /// Whether the LLM considers the command risky (true = risky).
    pub is_risky: bool,
    /// Risk score from 0.0 (safe) to 1.0 (extremely dangerous).
    pub risk_score: f64,
    /// Human-readable explanation of risks found.
    pub explanation: String,
    /// Additional risks not caught by regex patterns.
    pub additional_risks: Vec<String>,
}

/// A safer alternative suggested by the LLM.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmAlternative {
    /// The suggested safer command.
    pub command: String,
    /// Why this alternative is safer.
    pub explanation: String,
}

/// Trait for LLM providers — enables testing with mocks.
pub trait LlmProvider: Send + Sync {
    /// Analyze a command for risks beyond what regex patterns detect.
    ///
    /// # Errors
    /// Returns an error if the LLM API call fails.
    fn analyze_command(
        &self,
        command: &str,
        context_hints: &[String],
        matched_descriptions: &[String],
    ) -> Result<LlmAnalysis>;

    /// Suggest safer alternatives to a risky command.
    ///
    /// # Errors
    /// Returns an error if the LLM API call fails.
    fn suggest_alternatives(&self, command: &str, risk: &str) -> Result<Vec<LlmAlternative>>;

    /// Generate a detailed risk explanation.
    ///
    /// # Errors
    /// Returns an error if the LLM API call fails.
    fn explain_risk(
        &self,
        command: &str,
        matched_checks: &[String],
        context_hints: &[String],
    ) -> Result<String>;

    /// Check if the provider is configured and available.
    fn is_available(&self) -> bool;
}

// ---------------------------------------------------------------------------
// NoOpProvider — fallback when LLM is unconfigured
// ---------------------------------------------------------------------------

/// A no-op provider that returns neutral results. Used when LLM is not configured.
pub struct NoOpProvider;

impl LlmProvider for NoOpProvider {
    fn analyze_command(
        &self,
        _command: &str,
        _context_hints: &[String],
        _matched_descriptions: &[String],
    ) -> Result<LlmAnalysis> {
        Ok(LlmAnalysis {
            is_risky: false,
            risk_score: 0.0,
            explanation: String::new(),
            additional_risks: vec![],
        })
    }

    fn suggest_alternatives(&self, _command: &str, _risk: &str) -> Result<Vec<LlmAlternative>> {
        Ok(vec![])
    }

    fn explain_risk(
        &self,
        _command: &str,
        _matched_checks: &[String],
        _context_hints: &[String],
    ) -> Result<String> {
        Ok(String::new())
    }

    fn is_available(&self) -> bool {
        false
    }
}

// ---------------------------------------------------------------------------
// AnthropicProvider — calls Claude Messages API
// ---------------------------------------------------------------------------

/// Provider that calls the Anthropic (Claude) Messages API.
pub struct AnthropicProvider {
    api_key: String,
    model: String,
    max_tokens: u32,
    client: reqwest::blocking::Client,
}

impl AnthropicProvider {
    /// Create a new Anthropic provider.
    ///
    /// # Errors
    /// Returns an error if the HTTP client cannot be built.
    pub fn new(api_key: String, config: &LlmConfig) -> Result<Self> {
        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_millis(config.timeout_ms))
            .build()?;
        Ok(Self {
            api_key,
            model: config.model.clone(),
            max_tokens: config.max_tokens,
            client,
        })
    }

    fn call_api(&self, system_prompt: &str, user_prompt: &str) -> Result<String> {
        let body = serde_json::json!({
            "model": self.model,
            "max_tokens": self.max_tokens,
            "system": system_prompt,
            "messages": [
                {"role": "user", "content": user_prompt}
            ]
        });

        let resp = self
            .client
            .post("https://api.anthropic.com/v1/messages")
            .header("x-api-key", &self.api_key)
            .header("anthropic-version", "2023-06-01")
            .header("content-type", "application/json")
            .json(&body)
            .send()?;

        let status = resp.status();
        let text = resp.text()?;

        if !status.is_success() {
            return Err(crate::error::Error::LlmApi(format!(
                "Anthropic API error ({status}): {text}"
            )));
        }

        // Extract text content from the response
        let json: serde_json::Value = serde_json::from_str(&text)?;
        let content = json["content"]
            .as_array()
            .and_then(|arr| arr.first())
            .and_then(|block| block["text"].as_str())
            .unwrap_or("")
            .to_string();

        Ok(content)
    }
}

impl LlmProvider for AnthropicProvider {
    fn analyze_command(
        &self,
        command: &str,
        context_hints: &[String],
        matched_descriptions: &[String],
    ) -> Result<LlmAnalysis> {
        let system = "You are a shell command security analyzer. Respond ONLY with valid JSON. \
            Analyze the given command for security risks. Return: \
            {\"is_risky\": bool, \"risk_score\": float 0-1, \"explanation\": string, \
            \"additional_risks\": [string]}";

        let user = format!(
            "Command: {}\nContext: {}\nAlready matched risks: {}",
            command,
            context_hints.join(", "),
            matched_descriptions.join("; "),
        );

        let response = self.call_api(system, &user)?;
        Ok(parse_analysis_response(&response))
    }

    fn suggest_alternatives(&self, command: &str, risk: &str) -> Result<Vec<LlmAlternative>> {
        let system = "You are a shell command security advisor. Respond ONLY with valid JSON. \
            Suggest safer alternatives. Return: \
            [{\"command\": string, \"explanation\": string}]";

        let user = format!("Risky command: {command}\nRisk: {risk}");
        let response = self.call_api(system, &user)?;
        Ok(parse_alternatives_response(&response))
    }

    fn explain_risk(
        &self,
        command: &str,
        matched_checks: &[String],
        context_hints: &[String],
    ) -> Result<String> {
        let system = "You are a shell command security advisor. Explain the risks of the given \
            command in 2-3 concise sentences. Consider the environment context.";

        let user = format!(
            "Command: {}\nMatched patterns: {}\nContext: {}",
            command,
            matched_checks.join(", "),
            context_hints.join(", "),
        );

        self.call_api(system, &user)
    }

    fn is_available(&self) -> bool {
        !self.api_key.is_empty()
    }
}

// ---------------------------------------------------------------------------
// OpenAiCompatibleProvider — calls /v1/chat/completions
// ---------------------------------------------------------------------------

/// Provider that calls any `OpenAI`-compatible API (`OpenAI`, local models, etc.).
pub struct OpenAiCompatibleProvider {
    api_key: String,
    model: String,
    base_url: String,
    max_tokens: u32,
    client: reqwest::blocking::Client,
}

impl OpenAiCompatibleProvider {
    /// Create a new OpenAI-compatible provider.
    ///
    /// # Errors
    /// Returns an error if the HTTP client cannot be built.
    pub fn new(api_key: String, config: &LlmConfig) -> Result<Self> {
        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_millis(config.timeout_ms))
            .build()?;
        let base_url = config
            .base_url
            .clone()
            .unwrap_or_else(|| "https://api.openai.com".into());
        Ok(Self {
            api_key,
            model: config.model.clone(),
            base_url,
            max_tokens: config.max_tokens,
            client,
        })
    }

    fn call_api(&self, system_prompt: &str, user_prompt: &str) -> Result<String> {
        let body = serde_json::json!({
            "model": self.model,
            "max_tokens": self.max_tokens,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ]
        });

        let url = format!(
            "{}/v1/chat/completions",
            self.base_url.trim_end_matches('/')
        );
        let resp = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("content-type", "application/json")
            .json(&body)
            .send()?;

        let status = resp.status();
        let text = resp.text()?;

        if !status.is_success() {
            return Err(crate::error::Error::LlmApi(format!(
                "OpenAI API error ({status}): {text}"
            )));
        }

        let json: serde_json::Value = serde_json::from_str(&text)?;
        let content = json["choices"]
            .as_array()
            .and_then(|arr| arr.first())
            .and_then(|choice| choice["message"]["content"].as_str())
            .unwrap_or("")
            .to_string();

        Ok(content)
    }
}

impl LlmProvider for OpenAiCompatibleProvider {
    fn analyze_command(
        &self,
        command: &str,
        context_hints: &[String],
        matched_descriptions: &[String],
    ) -> Result<LlmAnalysis> {
        let system = "You are a shell command security analyzer. Respond ONLY with valid JSON. \
            Analyze the given command for security risks. Return: \
            {\"is_risky\": bool, \"risk_score\": float 0-1, \"explanation\": string, \
            \"additional_risks\": [string]}";

        let user = format!(
            "Command: {}\nContext: {}\nAlready matched risks: {}",
            command,
            context_hints.join(", "),
            matched_descriptions.join("; "),
        );

        let response = self.call_api(system, &user)?;
        Ok(parse_analysis_response(&response))
    }

    fn suggest_alternatives(&self, command: &str, risk: &str) -> Result<Vec<LlmAlternative>> {
        let system = "You are a shell command security advisor. Respond ONLY with valid JSON. \
            Suggest safer alternatives. Return: \
            [{\"command\": string, \"explanation\": string}]";

        let user = format!("Risky command: {command}\nRisk: {risk}");
        let response = self.call_api(system, &user)?;
        Ok(parse_alternatives_response(&response))
    }

    fn explain_risk(
        &self,
        command: &str,
        matched_checks: &[String],
        context_hints: &[String],
    ) -> Result<String> {
        let system = "You are a shell command security advisor. Explain the risks of the given \
            command in 2-3 concise sentences. Consider the environment context.";

        let user = format!(
            "Command: {}\nMatched patterns: {}\nContext: {}",
            command,
            matched_checks.join(", "),
            context_hints.join(", "),
        );

        self.call_api(system, &user)
    }

    fn is_available(&self) -> bool {
        !self.api_key.is_empty()
    }
}

// ---------------------------------------------------------------------------
// MockLlmProvider — for tests
// ---------------------------------------------------------------------------

/// Test provider that returns preconfigured responses.
pub struct MockLlmProvider {
    pub analysis: LlmAnalysis,
    pub alternatives: Vec<LlmAlternative>,
    pub explanation: String,
    pub available: bool,
}

impl Default for MockLlmProvider {
    fn default() -> Self {
        Self {
            analysis: LlmAnalysis {
                is_risky: false,
                risk_score: 0.0,
                explanation: String::new(),
                additional_risks: vec![],
            },
            alternatives: vec![],
            explanation: String::new(),
            available: true,
        }
    }
}

impl LlmProvider for MockLlmProvider {
    fn analyze_command(
        &self,
        _command: &str,
        _context_hints: &[String],
        _matched_descriptions: &[String],
    ) -> Result<LlmAnalysis> {
        Ok(self.analysis.clone())
    }

    fn suggest_alternatives(&self, _command: &str, _risk: &str) -> Result<Vec<LlmAlternative>> {
        Ok(self.alternatives.clone())
    }

    fn explain_risk(
        &self,
        _command: &str,
        _matched_checks: &[String],
        _context_hints: &[String],
    ) -> Result<String> {
        Ok(self.explanation.clone())
    }

    fn is_available(&self) -> bool {
        self.available
    }
}

// ---------------------------------------------------------------------------
// Factory
// ---------------------------------------------------------------------------

/// Create an LLM provider based on the configuration and environment.
///
/// Looks for an API key in `SHELLFIRM_LLM_API_KEY`, then falls back to
/// `ANTHROPIC_API_KEY` (for anthropic provider) or `OPENAI_API_KEY`
/// (for openai-compatible). Returns `NoOpProvider` if no key is found.
#[must_use]
pub fn create_provider(config: &LlmConfig, env: &dyn Environment) -> Box<dyn LlmProvider> {
    let api_key = env
        .var("SHELLFIRM_LLM_API_KEY")
        .or_else(|| match config.provider.as_str() {
            "anthropic" => env.var("ANTHROPIC_API_KEY"),
            "openai-compatible" => env.var("OPENAI_API_KEY"),
            _ => None,
        });

    let Some(key) = api_key else {
        tracing::debug!("No LLM API key found, using NoOpProvider");
        return Box::new(NoOpProvider);
    };

    if key.is_empty() {
        return Box::new(NoOpProvider);
    }

    match config.provider.as_str() {
        "anthropic" => match AnthropicProvider::new(key, config) {
            Ok(p) => Box::new(p),
            Err(e) => {
                tracing::warn!("Failed to create Anthropic provider: {e}");
                Box::new(NoOpProvider)
            }
        },
        "openai-compatible" => match OpenAiCompatibleProvider::new(key, config) {
            Ok(p) => Box::new(p),
            Err(e) => {
                tracing::warn!("Failed to create OpenAI-compatible provider: {e}");
                Box::new(NoOpProvider)
            }
        },
        other => {
            tracing::warn!("Unknown LLM provider: {other}, using NoOpProvider");
            Box::new(NoOpProvider)
        }
    }
}

// ---------------------------------------------------------------------------
// Response parsing helpers
// ---------------------------------------------------------------------------

fn parse_analysis_response(response: &str) -> LlmAnalysis {
    // Try to extract JSON from the response (LLMs sometimes wrap in markdown)
    let json_str = extract_json(response);
    match serde_json::from_str::<LlmAnalysis>(json_str) {
        Ok(analysis) => analysis,
        Err(e) => {
            tracing::warn!("Failed to parse LLM analysis response: {e}");
            LlmAnalysis {
                is_risky: false,
                risk_score: 0.0,
                explanation: String::new(),
                additional_risks: vec![],
            }
        }
    }
}

fn parse_alternatives_response(response: &str) -> Vec<LlmAlternative> {
    let json_str = extract_json(response);
    match serde_json::from_str::<Vec<LlmAlternative>>(json_str) {
        Ok(alts) => alts,
        Err(e) => {
            tracing::warn!("Failed to parse LLM alternatives response: {e}");
            vec![]
        }
    }
}

/// Extract JSON from a response that might contain markdown code fences.
fn extract_json(text: &str) -> &str {
    let trimmed = text.trim();
    // Handle ```json ... ``` blocks
    if let Some(start) = trimmed.find("```json") {
        let after_fence = &trimmed[start + 7..];
        if let Some(end) = after_fence.find("```") {
            return after_fence[..end].trim();
        }
    }
    // Handle ``` ... ``` blocks
    if let Some(start) = trimmed.find("```") {
        let after_fence = &trimmed[start + 3..];
        if let Some(end) = after_fence.find("```") {
            return after_fence[..end].trim();
        }
    }
    trimmed
}

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

    #[test]
    fn test_noop_provider_returns_safe() {
        let provider = NoOpProvider;
        let result = provider.analyze_command("rm -rf /", &[], &[]).unwrap();
        assert!(!result.is_risky);
        assert_eq!(result.risk_score, 0.0);
        assert!(!provider.is_available());
    }

    #[test]
    fn test_mock_provider_returns_configured() {
        let provider = MockLlmProvider {
            analysis: LlmAnalysis {
                is_risky: true,
                risk_score: 0.9,
                explanation: "Very dangerous".into(),
                additional_risks: vec!["data loss".into()],
            },
            ..Default::default()
        };

        let result = provider.analyze_command("rm -rf /", &[], &[]).unwrap();
        assert!(result.is_risky);
        assert_eq!(result.risk_score, 0.9);
        assert_eq!(result.explanation, "Very dangerous");
    }

    #[test]
    fn test_mock_provider_availability() {
        let available = MockLlmProvider {
            available: true,
            ..Default::default()
        };
        assert!(available.is_available());

        let unavailable = MockLlmProvider {
            available: false,
            ..Default::default()
        };
        assert!(!unavailable.is_available());
    }

    #[test]
    fn test_extract_json_plain() {
        let json = r#"{"is_risky": true}"#;
        assert_eq!(extract_json(json), json);
    }

    #[test]
    fn test_extract_json_from_markdown() {
        let response = "Here is the analysis:\n```json\n{\"is_risky\": true}\n```\nDone.";
        assert_eq!(extract_json(response), r#"{"is_risky": true}"#);
    }

    #[test]
    fn test_extract_json_from_plain_fences() {
        let response = "```\n{\"is_risky\": false}\n```";
        assert_eq!(extract_json(response), r#"{"is_risky": false}"#);
    }

    #[test]
    fn test_parse_analysis_response_valid() {
        let json = r#"{"is_risky": true, "risk_score": 0.8, "explanation": "bad", "additional_risks": ["x"]}"#;
        let result = parse_analysis_response(json);
        assert!(result.is_risky);
        assert_eq!(result.risk_score, 0.8);
    }

    #[test]
    fn test_parse_analysis_response_invalid_falls_back() {
        let result = parse_analysis_response("not json at all");
        assert!(!result.is_risky);
        assert_eq!(result.risk_score, 0.0);
    }

    #[test]
    fn test_parse_alternatives_response_valid() {
        let json = r#"[{"command": "rm -i /path", "explanation": "interactive mode"}]"#;
        let result = parse_alternatives_response(json);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].command, "rm -i /path");
    }

    #[test]
    fn test_create_provider_no_key() {
        let config = LlmConfig::default();
        let env = crate::env::MockEnvironment::default();
        let provider = create_provider(&config, &env);
        assert!(!provider.is_available());
    }

    #[test]
    fn test_create_provider_unknown_provider() {
        let mut config = LlmConfig::default();
        config.provider = "unknown".into();
        let mut env = crate::env::MockEnvironment::default();
        env.env_vars
            .insert("SHELLFIRM_LLM_API_KEY".into(), "test-key".into());
        let provider = create_provider(&config, &env);
        assert!(!provider.is_available());
    }

    #[test]
    fn test_llm_analysis_serialization() {
        let analysis = LlmAnalysis {
            is_risky: true,
            risk_score: 0.75,
            explanation: "Recursive delete".into(),
            additional_risks: vec!["no confirmation".into()],
        };
        let json = serde_json::to_string(&analysis).unwrap();
        assert!(json.contains("\"is_risky\":true"));
        let deserialized: LlmAnalysis = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.risk_score, 0.75);
    }
}