cpa-server 0.4.1

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
Documentation
//! Template-key startup guard (Go cmd/server/main.go and server_middleware.go).
use std::sync::Arc;

use axum::extract::{Request, State};
use axum::http::{Method, header};
use axum::middleware::Next;
use axum::response::Response;

use crate::Runtime;

fn examples(keys: &[String]) -> Vec<&str> {
    let mut found = Vec::new();
    for key in keys {
        let key = crate::gojson::trim(key);
        if matches!(key, "your-api-key-1" | "your-api-key-2" | "your-api-key-3") && !found.contains(&key) {
            found.push(key);
        }
    }
    found
}

fn warning(keys: &[&str]) -> String {
    // Generated by the pinned Go harness; only known template strings are inserted.
    let template = include_str!("example_api_key_warning.html");
    if keys.is_empty() {
        return template.to_owned();
    }
    let mut list = String::from("<p>Replace these values before using the proxy:</p><ul class=\"keys\">");
    for key in keys {
        list.push_str(&format!("<li><code>{key}</code></li>"));
    }
    list.push_str("</ul>");
    template.replacen(
        "<p>Set strong random API keys",
        &format!("{list}<p>Set strong random API keys"),
        1,
    )
}

/// Install before CORS, on the serving path only. Login/command, remote TUI,
/// missing-cloud-config and Home modes never reach this binary serving path.
/// Startup enabling is sticky; removing all examples on reload clears the guard,
/// and putting them back reactivates it only if startup enabled it.
pub fn router(rt: &Arc<Runtime>, app: axum::Router) -> axum::Router {
    let config = rt.config();
    let keys = examples(&config.api_keys);
    if keys.is_empty() {
        return app;
    }
    tracing::error!(
        api_keys = keys.join(","),
        "unsafe example API key configured; proxy API endpoints disabled until api-keys is updated"
    );
    app.layer(axum::middleware::from_fn_with_state(rt.clone(), guard))
}

async fn guard(State(rt): State<Arc<Runtime>>, request: Request, next: Next) -> Response {
    let config = rt.config();
    let keys = examples(&config.api_keys);
    if keys.is_empty() {
        return next.run(request).await;
    }
    let path = crate::management::percent_decode(request.uri().path());
    if path == "/management.html"
        && crate::access::query_get(request.uri().query().unwrap_or_default(), "safe-mode").as_deref()
            == Some(b"configure")
    {
        return next.run(request).await;
    }
    if matches!(path.as_str(), "/" | "/management.html") && matches!(*request.method(), Method::GET | Method::HEAD) {
        let mut response = Response::new(axum::body::Body::from(if request.method() == Method::HEAD {
            String::new()
        } else {
            warning(&keys)
        }));
        response
            .headers_mut()
            .insert(header::CONTENT_TYPE, "text/html; charset=utf-8".parse().unwrap());
        response
            .headers_mut()
            .insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
        return response;
    }
    if ["/v1", "/v1beta", "/openai/v1", "/backend-api/codex"]
        .iter()
        .any(|prefix| path == *prefix || path.strip_prefix(prefix).is_some_and(|s| s.starts_with('/')))
    {
        let mut response = crate::respond::gin_json(403, r#"{"error":"unsafe_example_api_key","message":"Proxy API endpoints are disabled because api-keys contains template values. Open /management.html?safe-mode=configure, update api-keys in Management, then retry."}"#.into());
        response
            .headers_mut()
            .insert("x-cpa-safe-mode", "example-api-key".parse().unwrap());
        return response;
    }
    next.run(request).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use tower_service::Service;

    #[test]
    fn templates_and_html_match_real_go() {
        let cases: serde_json::Value =
            serde_json::from_str(include_str!("../tests/fixtures/safe_mode_go.json")).unwrap();
        for case in cases.as_array().unwrap() {
            let keys: Vec<String> = serde_json::from_value(case["keys"].clone()).unwrap();
            let expected: Vec<String> = serde_json::from_value(case["matches"].clone()).unwrap_or_default();
            let found = examples(&keys);
            assert_eq!(found, expected);
            assert_eq!(warning(&found), case["html"].as_str().unwrap());
        }
    }

    #[tokio::test]
    async fn startup_reload_paths_query_and_cors_order() {
        let dir = std::env::temp_dir().join(format!("cpa-safe-mode-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        for startup in [false, true] {
            let config = |enabled| {
                let key = if enabled { "your-api-key-2" } else { "not-a-template" };
                cpa_core::config::Config::parse(&format!("api-keys: [{key}]\noauth: {{auth-dir: {}}}\n", dir.display()))
                    .unwrap()
            };
            let rt = Arc::new(crate::testing::runtime(
                config(startup),
                Vec::new(),
                cpa_exec::Executors {
                    claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:9").unwrap(),
                    codex: Default::default(),
                    devices: Default::default(),
                    openai: Default::default(),
                    google: Default::default(),
                },
            ));
            let app = axum::Router::new().fallback(|| async { "normal" });
            let mut app = router(&rt, app).layer(axum::middleware::from_fn(crate::management::cors));
            for active in [true, false, true] {
                rt.publish_config(config(active));
                for (method, path, blocked, html) in [
                    ("POST", "/v1", true, false),
                    ("GET", "/v1/models", true, false),
                    ("DELETE", "/v1beta/models", true, false),
                    ("PUT", "/openai/v1/test", true, false),
                    ("GET", "/backend-api/codex", true, false),
                    ("GET", "/v11/models", false, false),
                    ("GET", "/v8/management/config", false, false),
                    ("GET", "/healthz", false, false),
                    ("GET", "/", false, true),
                    ("HEAD", "/management.html", false, true),
                    ("GET", "/management.html?safe-mode=configure", false, false),
                    ("GET", "/management.html?safe-mode=bad&safe-mode=configure", false, true),
                    ("OPTIONS", "/v1/responses", false, false),
                ] {
                    let response = app
                        .call(
                            axum::http::Request::builder()
                                .method(method)
                                .uri(path)
                                .body(Body::empty())
                                .unwrap(),
                        )
                        .await
                        .unwrap();
                    let enabled = startup && active;
                    assert_eq!(
                        response.status().as_u16(),
                        if method == "OPTIONS" {
                            204
                        } else if enabled && blocked {
                            403
                        } else {
                            200
                        },
                        "{method} {path}"
                    );
                    assert_eq!(response.headers().get("access-control-allow-origin").unwrap(), "*");
                    assert_eq!(response.headers().contains_key("x-cpa-safe-mode"), enabled && blocked);
                    assert_eq!(
                        response.headers().get("cache-control").map(|v| v.to_str().unwrap()),
                        (enabled && html).then_some("no-store")
                    );
                    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
                    if enabled && html && method != "HEAD" {
                        assert_eq!(bytes, warning(&["your-api-key-2"]));
                    }
                    if enabled && html && method == "HEAD" {
                        assert!(bytes.is_empty());
                    }
                }
            }
        }
        std::fs::remove_dir_all(dir).unwrap();
    }
}