Cross Site Request Forgery in Axum with Cockroachdb
Cross Site Request Forgery in Axum with Cockroachdb — how this specific combination creates or exposes the vulnerability
Cross Site Request Forgery (CSRF) in an Axum application that uses CockroachDB can arise when state-changing HTTP requests rely solely on cookies for authentication without additional anti-CSRF controls. In Axum, if session or user identity is expressed only through cookie-based session identifiers and endpoints perform direct database operations against CockroachDB without verifying request intent, a malicious site can trick a logged-in user into submitting requests that the database will execute with their privileges.
Consider an Axum handler that reads a session cookie, queries CockroachDB to identify the user, and then performs a sensitive update (for example, changing an email or transferring funds) based on form parameters. If the handler does not validate a per-request token or referrer/header check, an attacker can craft a form on another origin that invokes this endpoint. When the victim’s browser sends the request, the session cookie is included automatically, and CockroachDB executes the update under the victim’s identity. The database itself does not enforce CSRF protections; the responsibility lies in the application layer in Axum to ensure each mutation is intentional and tied to the authenticated user’s actions.
Because CockroachDB is often used in distributed, high-concurrency environments, developers may focus on consistency and transactions and inadvertently omit per-request authorization checks. An Axum handler that builds SQL like UPDATE accounts SET email = $1 WHERE user_id = $2 using parameters from the request body, without first verifying a CSRF token or same-origin header, exposes a direct path for unauthorized state changes. The combination of Axum’s flexible routing and CockroachDB’s SQL interface makes it essential to validate origin and include anti-CSRF tokens for any endpoint that performs writes, deletes, or sensitive updates.
Cockroachdb-Specific Remediation in Axum — concrete code fixes
Remediation centers on ensuring every state-changing request in Axum includes a verifiable anti-CSRF token and that database operations are tied explicitly to the authenticated user with parameterized queries. Below is a concrete Axum handler pattern that integrates a CSRF token (e.g., synchronizer token pattern) with CockroachDB operations using sqlx in Rust.
use axum::{
extract::{Form, State},
response::Html,
routing::post,
Router,
};
use serde::Deserialize;
use sqlx::PgPool;
use std::net::SocketAddr;
struct AppState {
pool: PgPool,
// In practice, store tokens server-side or sign them; this is simplified.
csrf_secret: String,
}
#[derive(Deserialize)]
struct UpdateEmailForm {
user_id: i64,
new_email: String,
csrf_token: String,
}
async fn update_email_handler(
State(state): State<AppState>,
Form(form): Form<UpdateEmailForm>,
) -> Html<String> {
// Verify CSRF token (pseudo-validation; use constant-time compare and per-user tokens in production).
if form.csrf_token.is_empty() {
return Html("Missing CSRF token".to_string());
}
// Ensure the user can only modify their own record.
let row = sqlx::query!(
"UPDATE accounts SET email = $1 WHERE user_id = $2 AND user_id = (SELECT user_id FROM sessions WHERE csrf_token = $3)",
form.new_email,
form.user_id,
form.csrf_token
)
.execute(&state.pool)
.await;
match row {
Ok(_) => Html("Email updated".to_string()),
Err(e) => Html(format!("Error: {:?}", e)),
}
}
#[tokio::main]
async fn main() {
let pool = PgPool::connect("postgres://user:pass@host:26257/db?sslmode=require")
.await
.expect("connect failed");
let app = Router::new()
.route("/update-email", post(update_email_handler))
.with_state(AppState { pool, csrf_secret: "example-secret".to_string() });
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
If you use Axum middleware, integrate a CSRF token extraction and validation layer before reaching handlers that execute CockroachDB writes. For API consumers, prefer same-site cookies and CORS policies that restrict origins, but always pair these with a per-request token for sensitive endpoints. The key is to ensure each request that modifies data in CockroachDB is accompanied by a verifier that cannot be forged by a third-party site, thereby neutralizing CSRF regardless of the database backend.