diff --git a/crates/twigpine-node/src/auth/mod.rs b/crates/twigpine-node/src/auth/mod.rs index c96423b55..ef37290dc 100644 --- a/crates/twigpine-node/src/auth/mod.rs +++ b/crates/twigpine-node/src/auth/mod.rs @@ -894,9 +894,9 @@ pub async fn consume_signature( } /// Charge one verified signature against the ledger: the nonce policy, then the -/// atomic insert. Shared by [`consume_signature`] and [`LedgerTicket::spend`] so -/// the two spenders cannot drift on policy, metrics or wire codes. -async fn spend_signature( +/// atomic insert. Shared by [`consume_signature`], [`LedgerTicket::spend`] and +/// the GraphQL handler so every spender uses one policy, metrics and wire-code path. +pub(crate) async fn spend_signature( state: &AppState, identity: &SignatureIdentity, ) -> std::result::Result<(), (NodeDenial, String)> { diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 53ac2eee1..c59a97376 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -22,17 +22,30 @@ use crate::auth; use crate::rate_limit; use crate::state::AppState; +fn graphql_ledger_denial( + denial: twigpine_core::node_denial::NodeDenial, + message: String, +) -> GraphQLResponse { + let mut extensions = async_graphql::ErrorExtensionValues::default(); + extensions.set("code", denial.as_str()); + let mut error = async_graphql::ServerError::new(message, None); + error.extensions = Some(extensions); + async_graphql::Response::from_errors(vec![error]).into() +} + async fn graphql_handler( State(state): State, auth: Option>, + signature_identity: Option>, headers: axum::http::HeaderMap, rate_limit::PeerAddr(peer): rate_limit::PeerAddr, req: GraphQLRequest, ) -> GraphQLResponse { // `optional_signature` attaches the verified DID when a signature is present. - // Thread it into request-scoped GraphQL data; mutations enforce its presence - // in-resolver (N2) while queries stay open. + // Thread it into request-scoped GraphQL data; mutations spend that signature + // below and enforce the DID in-resolver while queries stay open. let mut inner = req.into_inner(); + let has_authenticated_did = auth.is_some(); if let Some(axum::Extension(did)) = auth { inner = inner.data(did); } @@ -48,6 +61,31 @@ async fn graphql_handler( key: state.client_key(&headers, peer), request_count: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)), }); + + // Classify the whole document rather than the selected operation: spending + // for an unused mutation is safer than trusting operationName routing. + let contains_mutation = inner + .parsed_query() + .map(|document| { + document.operations.iter().any(|(_, operation)| { + operation.node.ty == async_graphql::parser::types::OperationType::Mutation + }) + }) + .unwrap_or(false); + if contains_mutation { + if let Some(axum::Extension(identity)) = signature_identity { + // Spend before resolver validation, as REST does: a signed mutation + // refused for ownership or input is still single-use. + if let Err((denial, message)) = auth::spend_signature(&state, &identity).await { + return graphql_ledger_denial(denial, message); + } + } else if has_authenticated_did { + return graphql_ledger_denial( + twigpine_core::node_denial::NodeDenial::IdentityMissing, + "the request reached the signature ledger without a verified identity".to_string(), + ); + } + } state.graphql_schema.execute(inner).await.into() } @@ -1437,6 +1475,495 @@ mod tests { ); } + fn graphql_mutation_query(delegator_did: &str) -> String { + format!( + r#"mutation {{ createTask(delegatorDid: "{delegator_did}", input: {{ kind: "build", capability: "repo:write" }}) {{ id }} }}"# + ) + } + + fn build_graphql_request( + body: &str, + signed: Option<&twigpine_core::http_sig::SignedHeaders>, + ) -> Request { + let mut builder = Request::builder() + .method("POST") + .uri("/graphql") + .header("content-type", "application/json"); + if let Some(signed) = signed { + builder = builder + .header("content-digest", &signed.content_digest) + .header("signature-input", &signed.signature_input) + .header("signature", &signed.signature); + } + let mut req = builder.body(Body::from(body.to_string())).unwrap(); + req.extensions_mut().insert(axum::extract::ConnectInfo( + "203.0.113.10:5000".parse::().unwrap(), + )); + req + } + + fn signed_graphql_request( + keypair: &twigpine_core::identity::Keypair, + body: &str, + ) -> Request { + let signed = + twigpine_core::http_sig::sign_request(keypair, "POST", "/graphql", body.as_bytes()); + build_graphql_request(body, Some(&signed)) + } + + async fn read_graphql_json(response: axum::response::Response) -> serde_json::Value { + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + async fn graphql_task_count(pool: &PgPool, delegator_did: &str) -> i64 { + sqlx::query_scalar("SELECT COUNT(*) FROM agent_tasks WHERE delegator_did = $1") + .bind(delegator_did) + .fetch_one(pool) + .await + .unwrap() + } + + async fn graphql_ledger_rows(pool: &PgPool) -> i64 { + sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM consumed_signatures") + .fetch_one(pool) + .await + .unwrap() + } + + fn graphql_error_code(json: &serde_json::Value) -> Option<&str> { + json.pointer("/errors/0/extensions/code") + .and_then(|code| code.as_str()) + } + + fn sign_graphql_nonceless( + keypair: &twigpine_core::identity::Keypair, + body: &str, + ) -> twigpine_core::http_sig::SignedHeaders { + use base64::Engine as _; + + let did = keypair.did().to_string(); + let created = chrono::Utc::now().timestamp(); + let signature_input = format!( + r#"sig1=("@method" "@path" "content-digest");keyid="{did}";alg="ed25519";created={created}"# + ); + let content_digest = twigpine_core::http_sig::compute_content_digest(body.as_bytes()); + let sig_params_value = &signature_input["sig1=".len()..]; + let mut values = std::collections::HashMap::new(); + values.insert("@method".to_string(), "POST".to_string()); + values.insert("@path".to_string(), "/graphql".to_string()); + values.insert("content-digest".to_string(), content_digest.clone()); + let signing_string = twigpine_core::http_sig::build_signing_string( + twigpine_core::http_sig::COVERED_COMPONENTS, + sig_params_value, + &values, + ) + .unwrap(); + let signature = format!( + "sig1=:{}:", + base64::engine::general_purpose::STANDARD + .encode(keypair.sign(signing_string.as_bytes()).to_bytes()) + ); + twigpine_core::http_sig::SignedHeaders { + content_digest, + signature_input, + signature, + nonce: String::new(), + } + } + + async fn inject_authenticated_did( + axum::extract::State(did): axum::extract::State, + mut request: axum::extract::Request, + next: axum::middleware::Next, + ) -> axum::response::Response { + request + .extensions_mut() + .insert(crate::auth::AuthenticatedDid(did)); + next.run(request).await + } + + #[sqlx::test] + async fn graphql_mutation_signature_is_single_use(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let body = + serde_json::json!({ "query": graphql_mutation_query(&delegator_did) }).to_string(); + let signed = + twigpine_core::http_sig::sign_request(&keypair, "POST", "/graphql", body.as_bytes()); + let make_request = || build_graphql_request(&body, Some(&signed)); + + let first_response = router.clone().oneshot(make_request()).await.unwrap(); + assert_eq!(first_response.status(), StatusCode::OK); + let first_json = read_graphql_json(first_response).await; + assert!( + first_json + .pointer("/data/createTask/id") + .and_then(|id| id.as_str()) + .is_some(), + "first signed mutation must create its task: {first_json}" + ); + + let second_response = router.oneshot(make_request()).await.unwrap(); + assert_eq!(second_response.status(), StatusCode::OK); + let second_json = read_graphql_json(second_response).await; + + assert_eq!( + graphql_task_count(&pool, &delegator_did).await, + 1, + "replaying one signed GraphQL mutation must not execute it twice" + ); + assert!( + second_json.pointer("/data/createTask").is_none(), + "replayed signed mutation must not return a created task: {second_json}" + ); + assert_eq!( + second_json + .get("errors") + .and_then(|errors| errors.as_array()) + .map(|errors| errors.len()), + Some(1), + "the replay denial must carry exactly one GraphQL error: {second_json}" + ); + assert_eq!( + graphql_error_code(&second_json), + Some("signature_replayed"), + "replay denial must carry the shared wire code: {second_json}" + ); + } + + #[sqlx::test] + async fn graphql_multi_mutation_document_spends_signature_once(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let input = r#"input: { kind: "build", capability: "repo:write" }"#; + let query = format!( + r#"mutation {{ first: createTask(delegatorDid: "{delegator_did}", {input}) {{ id }} second: createTask(delegatorDid: "{delegator_did}", {input}) {{ id }} }}"# + ); + let body = serde_json::json!({ "query": query }).to_string(); + + let response = router + .oneshot(signed_graphql_request(&keypair, &body)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + assert!( + json.pointer("/data/first/id").is_some() && json.pointer("/data/second/id").is_some(), + "both fields in one mutation document must execute: {json}" + ); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 2); + assert_eq!( + graphql_ledger_rows(&pool).await, + 1, + "one HTTP request must spend one signature no matter how many mutation fields it has" + ); + } + + #[sqlx::test] + async fn graphql_signed_query_replay_never_spends_signature(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let body = serde_json::json!({ "query": "query { __typename }" }).to_string(); + let signed = + twigpine_core::http_sig::sign_request(&keypair, "POST", "/graphql", body.as_bytes()); + + for attempt in 1..=2 { + let response = router + .clone() + .oneshot(build_graphql_request(&body, Some(&signed))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + assert!( + json.pointer("/data/__typename") + .and_then(|v| v.as_str()) + .is_some(), + "signed query attempt {attempt} must execute: {json}" + ); + } + assert_eq!(graphql_ledger_rows(&pool).await, 0); + } + + #[sqlx::test] + async fn graphql_unsigned_requests_never_spend_signature(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + + let query_body = serde_json::json!({ "query": "query { __typename }" }).to_string(); + let query_response = router + .clone() + .oneshot(build_graphql_request(&query_body, None)) + .await + .unwrap(); + assert_eq!(query_response.status(), StatusCode::OK); + let query_json = read_graphql_json(query_response).await; + assert!( + query_json.pointer("/data/__typename").is_some(), + "unsigned query must still execute: {query_json}" + ); + + let mutation_body = + serde_json::json!({ "query": graphql_mutation_query(&delegator_did) }).to_string(); + let mutation_response = router + .oneshot(build_graphql_request(&mutation_body, None)) + .await + .unwrap(); + assert_eq!(mutation_response.status(), StatusCode::OK); + let mutation_json = read_graphql_json(mutation_response).await; + assert!( + mutation_json + .get("errors") + .and_then(|errors| errors.as_array()) + .is_some_and(|errors| errors.iter().any(|error| error + .get("message") + .and_then(|message| message.as_str()) + .is_some_and(|message| message.contains("authentication required")))), + "unsigned mutation must keep the resolver auth refusal: {mutation_json}" + ); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 0); + assert_eq!(graphql_ledger_rows(&pool).await, 0); + } + + #[sqlx::test] + async fn graphql_unparseable_signed_document_spends_nothing(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let body = serde_json::json!({ "query": "mutation {" }).to_string(); + + let response = router + .oneshot(signed_graphql_request(&keypair, &body)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + assert!( + json.get("errors") + .and_then(|errors| errors.as_array()) + .is_some_and(|errors| !errors.is_empty()), + "an unparseable signed document must be a GraphQL error: {json}" + ); + assert_eq!(graphql_ledger_rows(&pool).await, 0); + } + + #[sqlx::test] + async fn graphql_nonce_less_mutation_is_refused_when_nonce_is_required(pool: PgPool) { + let base_state = test_state(pool.clone()).await; + let mut config = (*base_state.config).clone(); + config.require_signature_nonce = true; + let state = crate::state::AppState { + config: std::sync::Arc::new(config), + ..base_state + }; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let body = + serde_json::json!({ "query": graphql_mutation_query(&delegator_did) }).to_string(); + let signed = sign_graphql_nonceless(&keypair, &body); + + let response = router + .oneshot(build_graphql_request(&body, Some(&signed))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + assert_eq!( + graphql_error_code(&json), + Some("signature_nonce_required"), + "nonce policy must use the shared wire code: {json}" + ); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 0); + assert_eq!(graphql_ledger_rows(&pool).await, 0); + } + + #[sqlx::test] + async fn graphql_concurrent_replays_execute_exactly_once(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let body = + serde_json::json!({ "query": graphql_mutation_query(&delegator_did) }).to_string(); + let signed = + twigpine_core::http_sig::sign_request(&keypair, "POST", "/graphql", body.as_bytes()); + let make_request = || build_graphql_request(&body, Some(&signed)); + + let (first_response, second_response) = tokio::join!( + router.clone().oneshot(make_request()), + router.clone().oneshot(make_request()) + ); + let mut success_count = 0; + let mut denial_count = 0; + for response in [first_response.unwrap(), second_response.unwrap()] { + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + if json.pointer("/data/createTask/id").is_some() { + success_count += 1; + } + if graphql_error_code(&json) == Some("signature_replayed") { + denial_count += 1; + } + } + assert_eq!( + success_count, 1, + "exactly one concurrent request may execute" + ); + assert_eq!( + denial_count, 1, + "the losing concurrent request must be a replay denial" + ); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 1); + } + + fn mixed_graphql_document(delegator_did: &str) -> String { + format!( + "query ReadOnly {{ __typename }}\nmutation CreateTaskOnce {{ createTask(delegatorDid: \"{delegator_did}\", input: {{ kind: \"build\", capability: \"repo:write\" }}) {{ id }} }}" + ) + } + + #[sqlx::test] + async fn graphql_mixed_document_mutation_replay_is_single_use(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let body = serde_json::json!({ + "query": mixed_graphql_document(&delegator_did), + "operationName": "CreateTaskOnce" + }) + .to_string(); + let signed = + twigpine_core::http_sig::sign_request(&keypair, "POST", "/graphql", body.as_bytes()); + let make_request = || build_graphql_request(&body, Some(&signed)); + + let first_response = router.clone().oneshot(make_request()).await.unwrap(); + let first_json = read_graphql_json(first_response).await; + assert!( + first_json.pointer("/data/createTask/id").is_some(), + "the selected mutation operation must execute first: {first_json}" + ); + let second_response = router.oneshot(make_request()).await.unwrap(); + let second_json = read_graphql_json(second_response).await; + assert_eq!(graphql_error_code(&second_json), Some("signature_replayed")); + assert!(second_json.pointer("/data/createTask").is_none()); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 1); + } + + #[sqlx::test] + async fn graphql_mixed_document_query_selection_still_spends_signature(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let body = serde_json::json!({ + "query": mixed_graphql_document(&delegator_did), + "operationName": "ReadOnly" + }) + .to_string(); + + let response = router + .oneshot(signed_graphql_request(&keypair, &body)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + assert!( + json.pointer("/data/__typename").is_some(), + "the selected query operation must execute: {json}" + ); + assert_eq!( + graphql_ledger_rows(&pool).await, + 1, + "a document containing any mutation spends even when operationName selects the query" + ); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 0); + } + + #[sqlx::test] + async fn graphql_mutation_with_did_but_no_signature_identity_fails_closed(pool: PgPool) { + let state = test_state(pool.clone()).await; + let keypair = twigpine_core::identity::Keypair::generate(); + let delegator_did = keypair.did().to_string(); + let router = Router::new() + .route("/graphql", post(graphql_handler)) + .layer(middleware::from_fn_with_state( + delegator_did.clone(), + inject_authenticated_did, + )) + .with_state(state); + let body = + serde_json::json!({ "query": graphql_mutation_query(&delegator_did) }).to_string(); + + let response = router + .oneshot(build_graphql_request(&body, None)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let json = read_graphql_json(response).await; + assert_eq!( + graphql_error_code(&json), + Some("signature_identity_missing"), + "a mutation must fail closed when auth data has no verified identity: {json}" + ); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 0); + assert_eq!(graphql_ledger_rows(&pool).await, 0); + } + + #[sqlx::test] + async fn graphql_resolver_refusal_still_spends_signature(pool: PgPool) { + let state = test_state(pool.clone()).await; + let router = build_router(state); + let signer = twigpine_core::identity::Keypair::generate(); + let other = twigpine_core::identity::Keypair::generate(); + let delegator_did = other.did().to_string(); + let body = + serde_json::json!({ "query": graphql_mutation_query(&delegator_did) }).to_string(); + let signed = + twigpine_core::http_sig::sign_request(&signer, "POST", "/graphql", body.as_bytes()); + let make_request = || build_graphql_request(&body, Some(&signed)); + + let first_response = router.clone().oneshot(make_request()).await.unwrap(); + assert_eq!(first_response.status(), StatusCode::OK); + let first_json = read_graphql_json(first_response).await; + assert!( + first_json + .get("errors") + .and_then(|errors| errors.as_array()) + .is_some_and(|errors| errors.iter().any(|error| error + .get("message") + .and_then(|message| message.as_str()) + .is_some_and(|message| message + .contains("delegator_did must be the authenticated signer")))), + "the resolver must refuse the foreign delegator: {first_json}" + ); + assert!(first_json.pointer("/data/createTask").is_none()); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 0); + assert_eq!( + graphql_ledger_rows(&pool).await, + 1, + "a signed mutation refused by its resolver must still spend its signature" + ); + + let second_response = router.oneshot(make_request()).await.unwrap(); + assert_eq!(second_response.status(), StatusCode::OK); + let second_json = read_graphql_json(second_response).await; + assert_eq!(graphql_error_code(&second_json), Some("signature_replayed")); + assert_eq!(graphql_task_count(&pool, &delegator_did).await, 0); + assert_eq!(graphql_ledger_rows(&pool).await, 1); + } + use axum::body::Body; use axum::http::{Request, StatusCode};