1use reqwest::Client;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use thiserror::Error;
5use uuid::Uuid;
6
7#[derive(Error, Debug)]
8pub enum SentinelError {
9 #[error("HTTP request failed: {0}")]
10 Http(#[from] reqwest::Error),
11 #[error("JSON serialization failed: {0}")]
12 Json(#[from] serde_json::Error),
13 #[error("Authentication failed")]
14 Authentication,
15 #[error("Threat detected: {0}")]
16 ThreatDetected(String),
17 #[error("Rate limit exceeded")]
18 RateLimit,
19 #[error("Invalid configuration: {0}")]
20 InvalidConfig(String),
21}
22
23#[derive(Debug, Clone)]
24pub struct SentinelClient {
25 client: Client,
26 base_url: String,
27 api_key: String,
28}
29
30#[derive(Serialize, Deserialize, Debug)]
31pub struct ThreatAnalysisRequest {
32 pub prompt: String,
33 pub user_id: Option<String>,
34 pub session_id: Option<String>,
35 pub context: Option<HashMap<String, serde_json::Value>>,
36}
37
38#[derive(Serialize, Deserialize, Debug)]
39pub struct ThreatAnalysisResponse {
40 pub threat_score: f64,
41 pub is_safe: bool,
42 pub threat_type: Option<String>,
43 pub confidence: f64,
44 pub explanation: String,
45 pub recommendations: Vec<String>,
46 pub request_id: String,
47}
48
49#[derive(Serialize, Deserialize, Debug)]
50pub struct PolicyValidationRequest {
51 pub content: String,
52 pub policy_type: String,
53 pub metadata: Option<HashMap<String, serde_json::Value>>,
54}
55
56#[derive(Serialize, Deserialize, Debug)]
57pub struct PolicyValidationResponse {
58 pub is_compliant: bool,
59 pub violations: Vec<PolicyViolation>,
60 pub score: f64,
61 pub recommendations: Vec<String>,
62}
63
64#[derive(Serialize, Deserialize, Debug)]
65pub struct PolicyViolation {
66 pub rule_id: String,
67 pub severity: String,
68 pub description: String,
69 pub suggestion: String,
70}
71
72impl SentinelClient {
73 pub fn new(base_url: String, api_key: String) -> Result<Self, SentinelError> {
74 if api_key.is_empty() {
75 return Err(SentinelError::InvalidConfig("API key cannot be empty".to_string()));
76 }
77
78 let client = Client::new();
79
80 Ok(SentinelClient {
81 client,
82 base_url,
83 api_key,
84 })
85 }
86
87 pub async fn analyze_threat(&self, request: ThreatAnalysisRequest) -> Result<ThreatAnalysisResponse, SentinelError> {
88 let url = format!("{}/api/v1/analyze", self.base_url);
89
90 let response = self.client
91 .post(&url)
92 .header("Authorization", format!("Bearer {}", self.api_key))
93 .header("Content-Type", "application/json")
94 .json(&request)
95 .send()
96 .await?;
97
98 if response.status() == 401 {
99 return Err(SentinelError::Authentication);
100 }
101
102 if response.status() == 429 {
103 return Err(SentinelError::RateLimit);
104 }
105
106 let analysis: ThreatAnalysisResponse = response.json().await?;
107
108 if !analysis.is_safe {
109 return Err(SentinelError::ThreatDetected(analysis.explanation.clone()));
110 }
111
112 Ok(analysis)
113 }
114
115 pub async fn validate_policy(&self, request: PolicyValidationRequest) -> Result<PolicyValidationResponse, SentinelError> {
116 let url = format!("{}/api/v1/policy/validate", self.base_url);
117
118 let response = self.client
119 .post(&url)
120 .header("Authorization", format!("Bearer {}", self.api_key))
121 .header("Content-Type", "application/json")
122 .json(&request)
123 .send()
124 .await?;
125
126 if response.status() == 401 {
127 return Err(SentinelError::Authentication);
128 }
129
130 Ok(response.json().await?)
131 }
132
133 pub async fn health_check(&self) -> Result<bool, SentinelError> {
134 let url = format!("{}/health", self.base_url);
135
136 let response = self.client
137 .get(&url)
138 .send()
139 .await?;
140
141 Ok(response.status().is_success())
142 }
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148 use tokio_test;
149
150 #[tokio::test]
151 async fn test_client_creation() {
152 let client = SentinelClient::new(
153 "https://api.sentinel.example.com".to_string(),
154 "test-api-key".to_string(),
155 );
156 assert!(client.is_ok());
157 }
158
159 #[tokio::test]
160 async fn test_empty_api_key() {
161 let client = SentinelClient::new(
162 "https://api.sentinel.example.com".to_string(),
163 "".to_string(),
164 );
165 assert!(client.is_err());
166 }
167}