phoebus_os/installer-rs/crates/phoebus-executor/src/ai.rs
Phoebus 3a405dd1e7 feat(installer): require AI to install; add local provider
Installing Phoebus now requires a connected model: the install gate refuses
with no provider unless the explicit break-glass --no-ai (alias --legacy, or
PHOEBUS_NO_AI=1) is used. Add a 'local' provider kind (Ollama/llama.cpp/
LM Studio) with an optional API key and --ai-endpoint override, so a user can
run a model they downloaded; no model is shipped. Desktop installs now include
xdg-desktop-portal + gtk/wlr backends for Flatpak and Wayland apps.
2026-09-20 14:41:53 -07:00

194 lines
6.7 KiB
Rust

//! Model provider transport.
//!
//! The API key never appears on a command line or in a log. It is injected into
//! a curl configuration file passed on stdin, while curl reads the JSON request
//! body from a 0600 temporary file. The body contains only the approved facts
//! built by `phoebus_ai::provider`.
use std::path::Path;
use phoebus_ai::provider::{ModelTransport, ProviderKind};
use phoebus_ai::AiError;
use phoebus_core::SecretString;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// Read an API key from a file that must be mode 0600. The value is returned
/// as a `SecretString`; callers must register it with the redactor (the
/// transport does this automatically).
pub fn load_api_key(path: &Path) -> Result<SecretString> {
use std::os::unix::fs::PermissionsExt;
let meta = std::fs::metadata(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
if meta.permissions().mode() & 0o077 != 0 {
return Err(ExecError::operation(
"ai",
"read API key",
format!("{} must be mode 0600", path.display()),
));
}
let key = std::fs::read_to_string(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
let key = key.trim().to_string();
if key.is_empty() {
return Err(ExecError::operation(
"ai",
"read API key",
"API key file is empty",
));
}
Ok(SecretString::new(key))
}
/// A transport that talks to an OpenAI-compatible endpoint with curl.
///
/// The API key is optional: a self-hosted local model usually needs none, while
/// DeepSeek/OpenAI require one.
pub struct CurlTransport<'a> {
exec: &'a Exec,
api_key: Option<SecretString>,
}
impl<'a> CurlTransport<'a> {
pub fn new(exec: &'a Exec, api_key: Option<SecretString>) -> Self {
if let Some(key) = &api_key {
exec.register_secret(key);
}
Self { exec, api_key }
}
}
impl ModelTransport for CurlTransport<'_> {
fn send(
&self,
_provider: ProviderKind,
url: &str,
body: &str,
) -> std::result::Result<String, AiError> {
let mut request = tempfile::Builder::new()
.prefix("phoebus-ai-request.")
.tempfile()
.map_err(|e| AiError::Provider(e.to_string()))?;
use std::io::Write;
request
.write_all(body.as_bytes())
.and_then(|_| request.flush())
.map_err(|e| AiError::Provider(e.to_string()))?;
// curl reads this config from stdin, so Exec marks the stdin as hidden
// and never logs it. The key is therefore absent from argv and logs.
let auth = match &self.api_key {
Some(key) => format!("header = \"Authorization: Bearer {}\"\n", key.expose()),
None => String::new(),
};
let config = format!(
"url = \"{url}\"\n\
header = \"Content-Type: application/json\"\n\
{auth}\
data = \"@{path}\"\n\
silent\nshow-error\nfail-with-body\nmax-time = 120\n",
path = request.path().display()
);
let spec = CommandSpec::new("ai", "query model", "curl")
.args(["-sS", "-K", "-"])
.stdin(config.into_bytes());
let out = self
.exec
.run(spec)
.map_err(|e| AiError::Provider(e.to_string()))?;
Ok(out.stdout_lossy())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::{CommandOutput, RecordingRunner};
use crate::log::Logger;
use phoebus_core::Redactor;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn api_key_must_be_mode_0600() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("key");
std::fs::write(&path, "sk-test\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(load_api_key(&path).is_err());
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
assert_eq!(load_api_key(&path).unwrap().expose(), "sk-test");
}
#[test]
fn curl_transport_keeps_the_key_out_of_arguments_and_logs() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: br#"{"choices":[{"message":{"content":"{}"}}]}"#.to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
let transport = CurlTransport::new(&exec, Some(SecretString::new("sk-secret-value")));
let out = transport
.send(
ProviderKind::OpenAi,
"https://example.invalid/v1/chat/completions",
r#"{"model":"m"}"#,
)
.unwrap();
assert!(out.contains("choices"));
let specs = runner.recorded();
let spec = &specs[0];
assert_eq!(spec.program, "curl");
assert!(
!spec.args.iter().any(|a| a.contains("sk-secret-value")),
"the key must not be in argv: {:?}",
spec.args
);
let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap();
assert!(stdin.contains("Authorization: Bearer sk-secret-value"));
// And the key is registered for redaction.
assert_eq!(exec.redactor().redact("sk-secret-value"), "<redacted>");
}
#[test]
fn curl_transport_omits_auth_without_a_key() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: b"{}".to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
let transport = CurlTransport::new(&exec, None);
transport
.send(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"{}",
)
.unwrap();
let spec = &runner.recorded()[0];
let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap();
assert!(!stdin.contains("Authorization"));
assert!(stdin.contains("http://127.0.0.1"));
}
}