use crate::credentials::{AwsCredential, AwsSessionCredential}; use crate::error::CreddyError; use crate::session::AppSession; use futures::channel::oneshot::{self, Sender}; use gpui_kit::{AsyncApp, Global}; use http_body_util::Full; use hyper::body::{Bytes, Incoming}; use hyper::http::Uri; use hyper::server::conn::http1; use hyper::service::service_fn; use hyper::{Method, Request, Response, StatusCode}; use rustix::net::sockopt::socket_peercred; use rustix::process::Pid; use serde::{Deserialize, Serialize}; use smol::Timer; use smol::net::unix::{UnixListener, UnixStream}; use smol_hyper::rt::FuturesIo; use std::collections::{HashMap, VecDeque}; use std::convert::Infallible; use std::fs; use std::io; use std::path::Path; use std::time::Duration; #[derive(Clone)] pub enum CredentialRequest { AwsGet { name: Option, session: bool, } } pub struct CredentialResponse { approved: bool, session: bool, } impl CredentialResponse { pub fn yes_session() -> CredentialResponse { CredentialResponse { approved: true, session: true } } pub fn yes_longterm() -> CredentialResponse { CredentialResponse { approved: true, session: false } } pub fn no() -> CredentialResponse { CredentialResponse { approved: false, session: true } } } pub struct PendingRequests(pub VecDeque<(CredentialRequest, Sender)>); impl PendingRequests { pub fn new() -> PendingRequests { PendingRequests(VecDeque::new()) } } impl Global for PendingRequests {} #[derive(Deserialize, Serialize)] pub struct ErrorResponse { code: &'static str, message: String, } impl ErrorResponse { fn into_http(&self) -> serde_json::Result>> { let bytes = serde_json::to_vec(self)?; Ok(Response::new(Full::new(Bytes::from(bytes)))) } } impl From for ErrorResponse { fn from(e: CreddyError) -> ErrorResponse { let message = e.to_string(); ErrorResponse { code: e.into(), message, } } } pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError> { if path.exists() { fs::remove_file(path)?; } let listener = UnixListener::bind(path) .map_err(|_| CreddyError::SocketBind(path.to_string_lossy().into()))?; app.spawn(async move |app| { loop { let (stream, pid) = match accept(&listener).await { Ok((stream, pid)) => (stream, pid), Err(e) => { eprintln!("Error accepting connection: {e}"); Timer::after(Duration::from_millis(100)).await; continue; } }; app.spawn(async move |app| { let adapter = FuturesIo::new(stream); let service = service_fn(|req| handle(req, pid, app.clone())); let conn = http1::Builder::new().serve_connection(adapter, service); if let Err(e) = conn.await { eprintln!("Error serving connection: {e}") } }) .detach(); } }) .detach(); Ok(()) } async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> { let (stream, _) = listener.accept().await?; // pid() never returns None on Linux let pid = socket_peercred(&stream)?.pid; Ok((stream, pid)) } async fn handle( req: Request, pid: Pid, app: AsyncApp, ) -> Result>, Infallible> { let (parts, _body) = req.into_parts(); let response = match (parts.method, parts.uri.path()) { (Method::GET, "/ping") => text(StatusCode::OK, "pong"), (Method::GET, "/aws") => handle_aws_get(parts.uri, app).await, (_, p) => text(StatusCode::NOT_FOUND, &format!("Not found: {p}")), }; match response { Ok(r) => Ok(r), Err(e) => Ok(ErrorResponse::from(e).into_http().unwrap()), } } async fn handle_aws_get(uri: Uri, app: AsyncApp) -> Result>, CreddyError> { let qs = uri.query().unwrap_or("").as_bytes(); let params: HashMap<_, _> = form_urlencoded::parse(qs).collect(); let name = params.get("name").map(|n| n.to_string()); let session = params.get("session").map(|s| s == "true").unwrap_or(false); let req = CredentialRequest::AwsGet { name: name.clone(), session }; let (sender, receiver) = oneshot::channel::(); app.update_global::(|pending, _cx| pending.0.push_back((req.clone(), sender))); let resp = receiver.await.unwrap_or_else(|_| CredentialResponse::no()); if !resp.approved { return Err(CreddyError::RequestDenied); } // eventually: let session = AppSession::wait_for_unlock().await; or something like that let creds = app.read_global::(|session, cx| { let AppSession::Unlocked(db) = session else { unreachable!() }; db.load_aws_credential(&name.unwrap_or_else(|| "default".into())) })?; // todo: session credential handling let body = serde_json::to_vec(&creds).unwrap(); Ok(Response::new(Full::new(Bytes::from(body)))) } fn text(status: StatusCode, body: &str) -> Result>, CreddyError> { let mut response = Response::new(Full::new(Bytes::from(body.to_owned()))); *response.status_mut() = status; Ok(response) }