interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-mail-rs / src / api.rs

283 lines · 8996 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::cortex_sync::CortexSync;
17use crate::models::{EmailMessage, MailboxStatus, SendEmailRequest};
18use crate::relay::MailRelay;
19use crate::store::MailStore;
20use axum::{
21 Router,
22 extract::{Path as AxumPath, State},
23 http::StatusCode,
24 response::Json,
25 routing::{get, post},
26};
27use axum::{
28 extract::Request,
29 middleware::{self, Next},
30 response::{IntoResponse, Response},
31};
32use serde_json::{Value, json};
33use std::sync::Arc;
34
35#[derive(Clone)]
36pub struct ApiState {
37 pub store: Arc<MailStore>,
38 pub cortex: Arc<CortexSync>,
39 pub relay: Arc<MailRelay>,
40 pub smtp_port: u16,
41 pub api_port: u16,
42 pub operator_email: String,
43}
44
45pub fn create_router(state: ApiState) -> Router {
46 Router::new()
47 .route("/api/mail/status", get(handle_status))
48 .route("/api/mail/inbox", get(handle_list_inbox))
49 .route("/api/mail/sent", get(handle_list_sent))
50 .route("/api/mail/archive", get(handle_list_archive))
51 .route("/api/mail/message/{id}", get(handle_get_message))
52 .route("/api/mail/send", post(handle_send_mail))
53 .route("/api/mail/ingest-test", post(handle_ingest_test))
54 .layer(middleware::from_fn(require_mail_access))
55 .with_state(state)
56 .merge(Router::new().route("/health", get(handle_health)))
57}
58
59async fn require_mail_access(request: Request, next: Next) -> Response {
60 // Browser access goes through the authenticated cockpit, never directly to mail.
61 if request.headers().contains_key(axum::http::header::ORIGIN) {
62 return StatusCode::FORBIDDEN.into_response();
63 }
64 let token = tokio::task::spawn_blocking(resolve_mail_token)
65 .await
66 .unwrap_or_default();
67 if let Err(status) = validate_mail_token(
68 token.trim(),
69 request
70 .headers()
71 .get(axum::http::header::AUTHORIZATION)
72 .and_then(|v| v.to_str().ok()),
73 ) {
74 return status.into_response();
75 }
76 let mut response = next.run(request).await;
77 response.headers_mut().insert(
78 axum::http::header::CACHE_CONTROL,
79 "no-store".parse().unwrap(),
80 );
81 response
82}
83
84/// Resolve through process memory or the TPM-bound vault; never a plaintext file.
85/// A vault hit is cached for 60 seconds so each request does not pay a TPM
86/// unseal (about 2 s); failures are not cached, so provisioning takes effect
87/// on the next request.
88fn resolve_mail_token() -> String {
89 use std::sync::Mutex;
90 use std::time::{Duration, Instant};
91 static CACHE: Mutex<Option<(Instant, String)>> = Mutex::new(None);
92
93 if let Ok(value) = std::env::var("AIEN_MAIL_API_TOKEN")
94 && !value.trim().is_empty()
95 {
96 return value;
97 }
98 if let Ok(guard) = CACHE.lock()
99 && let Some((at, value)) = guard.as_ref()
100 && at.elapsed() < Duration::from_secs(60)
101 {
102 return value.clone();
103 }
104 let value = vault_get("AIEN_MAIL_API_TOKEN");
105 if !value.trim().is_empty()
106 && let Ok(mut guard) = CACHE.lock()
107 {
108 *guard = Some((Instant::now(), value.clone()));
109 }
110 value
111}
112
113/// Runs `atlas-vault get`. The mail unit's PATH lacks ~/.local/bin, so fall
114/// back to the operator's install location when PATH lookup finds nothing.
115fn vault_get(name: &str) -> String {
116 let run = |program: &std::ffi::OsStr| {
117 std::process::Command::new(program)
118 .args(["get", name])
119 .stdin(std::process::Stdio::null())
120 .stderr(std::process::Stdio::null())
121 .output()
122 };
123 let output = match run(std::ffi::OsStr::new("atlas-vault")) {
124 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
125 let home = std::env::var_os("HOME").unwrap_or_default();
126 run(std::path::Path::new(&home)
127 .join(".local/bin/atlas-vault")
128 .as_os_str())
129 }
130 other => other,
131 };
132 match output {
133 Ok(out) if out.status.success() => String::from_utf8(out.stdout).unwrap_or_default(),
134 _ => String::new(),
135 }
136}
137
138fn validate_mail_token(expected: &str, authorization: Option<&str>) -> Result<(), StatusCode> {
139 if expected.len() < 32 {
140 return Err(StatusCode::SERVICE_UNAVAILABLE);
141 }
142 let supplied = authorization.and_then(|v| v.strip_prefix("Bearer "));
143 let valid = supplied.is_some_and(|t| {
144 t.len() == expected.len()
145 && t.bytes()
146 .zip(expected.bytes())
147 .fold(0u8, |d, (a, b)| d | (a ^ b))
148 == 0
149 });
150 if valid {
151 Ok(())
152 } else {
153 Err(StatusCode::UNAUTHORIZED)
154 }
155}
156
157async fn handle_health() -> Json<Value> {
158 Json(json!({
159 "status": "ok",
160 "service": "spark-mail-rs",
161 "version": "0.1.0"
162 }))
163}
164
165async fn handle_status(State(state): State<ApiState>) -> Json<MailboxStatus> {
166 let cortex_ok = state.cortex.check_health().await;
167 let bridge_ok = state.relay.check_bridge().await;
168
169 let status = state.store.get_status(
170 &state.operator_email,
171 state.smtp_port,
172 state.api_port,
173 cortex_ok,
174 bridge_ok,
175 );
176 Json(status)
177}
178
179async fn handle_list_inbox(State(state): State<ApiState>) -> Json<Vec<EmailMessage>> {
180 let messages = state.store.list_folder("inbox");
181 Json(messages)
182}
183
184async fn handle_list_sent(State(state): State<ApiState>) -> Json<Vec<EmailMessage>> {
185 let messages = state.store.list_folder("sent");
186 Json(messages)
187}
188
189async fn handle_list_archive(State(state): State<ApiState>) -> Json<Vec<EmailMessage>> {
190 let messages = state.store.list_folder("archive");
191 Json(messages)
192}
193
194async fn handle_get_message(
195 State(state): State<ApiState>,
196 AxumPath(id): AxumPath<String>,
197) -> Result<Json<EmailMessage>, StatusCode> {
198 state
199 .store
200 .get_message(&id)
201 .map(Json)
202 .ok_or(StatusCode::NOT_FOUND)
203}
204
205async fn handle_send_mail(
206 State(state): State<ApiState>,
207 Json(req): Json<SendEmailRequest>,
208) -> Result<Json<EmailMessage>, (StatusCode, String)> {
209 state
210 .relay
211 .send_email(req)
212 .await
213 .map(Json)
214 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))
215}
216
217async fn handle_ingest_test(
218 State(state): State<ApiState>,
219) -> Result<Json<EmailMessage>, (StatusCode, String)> {
220 let test_req = SendEmailRequest {
221 to: vec![state.operator_email.clone()],
222 subject: "Sovereign Mail Node Online".to_string(),
223 body: "Your sovereign mail server is running directly on Spark hardware. Messages are stored on local NVMe disk with zero cloud telemetry and synced to Atlas Cortex memory.".to_string(),
224 from: Some("aien@aienos.com".to_string()),
225 };
226
227 let id = uuid::Uuid::new_v4().to_string();
228 let now = chrono::Utc::now().to_rfc3339();
229 let mut headers = std::collections::HashMap::new();
230 headers.insert("From".to_string(), "aien@aienos.com".to_string());
231 headers.insert("To".to_string(), state.operator_email.clone());
232 headers.insert("Subject".to_string(), test_req.subject.clone());
233
234 let mut msg = EmailMessage {
235 id: id.clone(),
236 from: "aien@aienos.com".to_string(),
237 to: test_req.to,
238 subject: test_req.subject,
239 body: test_req.body,
240 headers,
241 received_at: now,
242 folder: "inbox".to_string(),
243 cortex_indexed: false,
244 untrusted: false,
245 };
246
247 state
248 .store
249 .save_message(&msg)
250 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
251
252 if state.cortex.commit_mail(&msg).await.is_ok() {
253 msg.cortex_indexed = true;
254 let _ = state.store.save_message(&msg);
255 }
256
257 Ok(Json(msg))
258}
259
260#[cfg(test)]
261mod access_tests {
262 use super::*;
263 #[test]
264 fn mail_access_fails_closed() {
265 let token = "a".repeat(64);
266 assert_eq!(
267 validate_mail_token("", None),
268 Err(StatusCode::SERVICE_UNAVAILABLE)
269 );
270 assert_eq!(
271 validate_mail_token(&token, None),
272 Err(StatusCode::UNAUTHORIZED)
273 );
274 assert_eq!(
275 validate_mail_token(&token, Some("Bearer wrong")),
276 Err(StatusCode::UNAUTHORIZED)
277 );
278 assert_eq!(
279 validate_mail_token(&token, Some(&format!("Bearer {token}"))),
280 Ok(())
281 );
282 }
283}