HIGH ssrf server sideaxumapi keys

Ssrf Server Side in Axum with Api Keys

Ssrf Server Side in Axum with Api Keys — how this specific combination creates or exposes the vulnerability

Server-side request forgery (SSRF) in an Axum service that uses API keys for outbound calls can arise when user-controlled data influences the request target without adequate validation. For example, an endpoint that accepts a URL parameter to forward a request and appends an API key from server-side configuration can expose internal services or metadata if the URL is attacker-controlled. Because the API key is handled on the server, the client does not need to know it, but the SSRF vector can still lead to internal HTTP services, cloud metadata endpoints (e.g., 169.254.169.254), or SSRF-induced interactions with AI endpoints that expose system prompts or credentials.

In Axum, a handler that forwards a request based on a user-supplied URL can inadvertently allow an attacker to pivot to internal resources. Consider an Axum route that receives a target URL and uses reqwest to make an authenticated outbound call with a stored API key. If the target URL is not strictly validated and an SSRF-capable endpoint is reachable from the server, the API key may be sent to an arbitrary host under the server’s identity. This can result in unintended data exposure, internal network scanning, or abuse of internal APIs that trust the same key. The risk is compounded when the forwarded request reaches LLM endpoints or internal services that return sensitive information in responses, which middleBrick’s LLM/AI Security checks are designed to detect (e.g., system prompt leakage, output PII, or exposed keys).

middleBrick can help identify such issues by scanning the API’s unauthenticated surface. Its 12 security checks run in parallel and include Input Validation, Data Exposure, and SSRF testing, which can reveal whether user-supplied inputs can coerce the server into making unexpected authenticated calls. Because the scanner does not require credentials, it can safely probe the endpoint to uncover SSRF paths without exposing the API key itself. The findings include severity, guidance, and mappings to frameworks like OWASP API Top 10 and PCI-DSS, helping teams understand the practical impact of SSRF in authenticated contexts.

Api Keys-Specific Remediation in Axum — concrete code fixes

To mitigate SSRF when using API keys in Axum, validate and restrict the destinations your service can call, and avoid using keys in a way that amplifies SSRF impact. Use allowlists for hostnames and paths, prefer using server-side API keys only for known, fixed endpoints, and do not forward user-supplied URLs directly. The following patterns demonstrate secure approaches in Axum with reqwest.

Example 1: Fixed internal call with API key (no user-supplied URL)

use axum::{routing::get, Router};
use reqwest::Client;
use std::net::SocketAddr;

async fn call_fixed_service() -> Result {
    let client = Client::new();
    let api_key = std::env::var("API_KEY").expect("API_KEY must be set");
    let url = "https://api.example.com/v1/data";
    client.get(url)
        .header("Authorization", format!("Bearer {}", api_key))
        .send()
        .await?
        .text()
        .await
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/health", get(|| async { "ok" }));
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
}

This pattern avoids any user input for the destination, ensuring the API key is used only against a fixed, trusted endpoint.

Example 2: Validated user parameters without URL forwarding

use axum::{routing::get, Json, Router};
use serde::{Deserialize, Serialize};
use reqwest::Client;

#[derive(Deserialize)]
struct QueryParams {
    item_id: String,
}

#[derive(Serialize)]
struct ItemResponse {
    id String,
    name: String,
}

async fn get_item(
    params: Json,
) -> Result, (axum::http::StatusCode, String)> {
    let client = Client::new();
    let api_key = std::env::var("API_KEY").map_err(|_| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, "missing key".into()))?;
    // Strictly validate item_id to prevent path traversal or SSRF via indirect parameters
    let item_id = params.item_id.trim().strip_prefix("item-").ok_or_else(|| (axum::http::StatusCode::BAD_REQUEST, "invalid item_id".into()))?;
    let url = format!("https://api.example.com/v1/items/{}", item_id);
    let response = client.get(&url)
        .header("Authorization", format!("Bearer {}", api_key))
        .send()
        .await
        .map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, e.to_string()))?;
    let body = response.text().await.map_err(|e| (axum::http::StatusCode::BAD_GATEWAY, e.to_string()))?;
    // Basic parsing example; adapt to your schema
    Ok(Json(ItemResponse { id: item_id.to_string(), name: body }))
}

Here, the API key remains server-side, and the user input is constrained to a strict pattern (prefix + alphanumeric), preventing arbitrary host resolution. Do not construct outbound URLs directly from user input, and avoid passing user-controlled URLs to reqwest; if forwarding is required, use a strict allowlist of domains and reject non-HTTP/HTTPS schemes and private IP ranges.

For continuous protection, the middleBrick Pro plan includes continuous monitoring and configurable scans that can alert you if risk scores degrade. Its GitHub Action can enforce security thresholds in CI/CD, and the MCP Server lets AI coding assistants invoke scans directly from your IDE, helping catch SSRF and API key misuse early.

Frequently Asked Questions

Can SSRF in Axum be exploited even when API keys are not exposed to the client?
Yes. SSRF depends on what the server can do with the attacker’s input, not on whether the API key is sent to the client. If the server uses its own API key to call user-supplied URLs, an attacker can force the server to reach internal services, metadata endpoints, or external LLM endpoints, potentially causing data exposure or further compromise. Input validation and destination allowlists are essential.
Does middleBrick fix SSRF or API key leaks in Axum applications?
middleBrick detects and reports findings, including SSRF and API key exposure risks, with severity and remediation guidance. It does not fix, patch, block, or remediate. Use its output to guide secure coding practices, such as strict input validation and avoiding forwarding user-controlled URLs, and consider the Pro plan for continuous monitoring and CI/CD integration.