Skip to main content

tryaudex_core/
server.rs

1use serde::{Deserialize, Serialize};
2
3/// Request to issue scoped credentials via the server API.
4#[derive(Debug, Clone, Serialize, Deserialize)]
5pub struct CredentialRequest {
6    /// IAM actions to allow (e.g. "s3:GetObject,s3:ListBucket")
7    pub allow: Option<String>,
8    /// Named policy profile (e.g. "s3-readonly")
9    pub profile: Option<String>,
10    /// Resource ARN restriction
11    pub resource: Option<String>,
12    /// Cloud provider (aws, gcp, azure)
13    #[serde(default = "default_provider")]
14    pub provider: String,
15    /// TTL for credentials (e.g. "15m", "1h")
16    #[serde(default = "default_ttl")]
17    pub ttl: String,
18    /// IAM role ARN to assume
19    pub role_arn: Option<String>,
20    /// Command that will use these credentials (for audit)
21    #[serde(default)]
22    pub command: Vec<String>,
23    /// Agent identity
24    pub agent_id: Option<String>,
25}
26
27fn default_provider() -> String {
28    "aws".to_string()
29}
30
31fn default_ttl() -> String {
32    "15m".to_string()
33}
34
35/// Response from the credential issuance endpoint.
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct CredentialResponse {
38    pub session_id: String,
39    pub provider: String,
40    pub expires_at: String,
41    pub ttl_seconds: u64,
42    pub credentials: CredentialEnvVars,
43}
44
45/// Credential environment variables returned by the server.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct CredentialEnvVars {
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub aws_access_key_id: Option<String>,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub aws_secret_access_key: Option<String>,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub aws_session_token: Option<String>,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub gcp_access_token: Option<String>,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub azure_token: Option<String>,
58}
59
60/// Server configuration.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct ServerConfig {
63    /// Port to listen on
64    #[serde(default = "default_port")]
65    pub port: u16,
66    /// Bind address
67    #[serde(default = "default_bind")]
68    pub bind: String,
69    /// Optional API key for authentication
70    pub api_key: Option<String>,
71}
72
73fn default_port() -> u16 {
74    8080
75}
76
77fn default_bind() -> String {
78    "0.0.0.0".to_string()
79}
80
81impl Default for ServerConfig {
82    fn default() -> Self {
83        Self {
84            port: default_port(),
85            bind: default_bind(),
86            api_key: None,
87        }
88    }
89}
90
91/// API error response.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct ApiError {
94    pub error: String,
95    pub code: u16,
96}
97
98/// Simple HTTP response builder.
99pub fn http_response(status: u16, status_text: &str, content_type: &str, body: &str) -> String {
100    format!(
101        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
102        status, status_text, content_type, body.len(), body
103    )
104}
105
106pub fn json_ok(body: &str) -> String {
107    http_response(200, "OK", "application/json", body)
108}
109
110pub fn json_error(code: u16, message: &str) -> String {
111    let err = ApiError {
112        error: message.to_string(),
113        code,
114    };
115    let body = serde_json::to_string(&err).unwrap_or_else(|_| {
116        format!("{{\"error\":\"{}\",\"code\":{}}}", message, code)
117    });
118    let status_text = match code {
119        400 => "Bad Request",
120        401 => "Unauthorized",
121        404 => "Not Found",
122        405 => "Method Not Allowed",
123        500 => "Internal Server Error",
124        _ => "Error",
125    };
126    http_response(code, status_text, "application/json", &body)
127}
128
129/// Parse a minimal HTTP request: returns (method, path, body).
130pub fn parse_http_request(raw: &str) -> Option<(&str, &str, &str)> {
131    let mut lines = raw.split("\r\n");
132    let first_line = lines.next()?;
133    let mut parts = first_line.split_whitespace();
134    let method = parts.next()?;
135    let path = parts.next()?;
136
137    // Find body after double CRLF
138    let body = raw.split("\r\n\r\n").nth(1).unwrap_or("");
139
140    Some((method, path, body))
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn test_parse_http_request_get() {
149        let raw = "GET /v1/sessions HTTP/1.1\r\nHost: localhost\r\n\r\n";
150        let (method, path, body) = parse_http_request(raw).unwrap();
151        assert_eq!(method, "GET");
152        assert_eq!(path, "/v1/sessions");
153        assert_eq!(body, "");
154    }
155
156    #[test]
157    fn test_parse_http_request_post() {
158        let raw = "POST /v1/credentials HTTP/1.1\r\nContent-Type: application/json\r\n\r\n{\"allow\":\"s3:GetObject\"}";
159        let (method, path, body) = parse_http_request(raw).unwrap();
160        assert_eq!(method, "POST");
161        assert_eq!(path, "/v1/credentials");
162        assert_eq!(body, "{\"allow\":\"s3:GetObject\"}");
163    }
164
165    #[test]
166    fn test_json_ok() {
167        let resp = json_ok("{\"status\":\"ok\"}");
168        assert!(resp.contains("200 OK"));
169        assert!(resp.contains("application/json"));
170    }
171
172    #[test]
173    fn test_json_error() {
174        let resp = json_error(400, "bad request");
175        assert!(resp.contains("400 Bad Request"));
176        assert!(resp.contains("bad request"));
177    }
178
179    #[test]
180    fn test_credential_request_defaults() {
181        let json = r#"{"allow":"s3:GetObject"}"#;
182        let req: CredentialRequest = serde_json::from_str(json).unwrap();
183        assert_eq!(req.provider, "aws");
184        assert_eq!(req.ttl, "15m");
185        assert!(req.role_arn.is_none());
186    }
187
188    #[test]
189    fn test_server_config_default() {
190        let config = ServerConfig::default();
191        assert_eq!(config.port, 8080);
192        assert_eq!(config.bind, "0.0.0.0");
193        assert!(config.api_key.is_none());
194    }
195}