diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index d531fdc..ba7b8b6 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -15,6 +15,8 @@ on: - "Cargo.toml" - "Cargo.lock" - "rust-toolchain.toml" + - "contracts/**" + - "scripts/sync-query-contract.py" schedule: - cron: "17 9 * * 1" workflow_dispatch: @@ -49,6 +51,9 @@ jobs: - name: Check formatting run: cargo fmt --check + - name: Check generated query schema + run: python3 scripts/sync-query-contract.py --check + - name: Run Clippy run: cargo clippy --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious diff --git a/Dockerfile b/Dockerfile index c55124d..b0c8425 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,6 +14,7 @@ RUN apt-get update && apt-get install -y pkg-config libssl-dev build-essential c WORKDIR /app COPY Cargo.toml Cargo.lock ./ COPY src ./src +COPY contracts ./contracts RUN cargo build --locked --release --no-default-features --features oss diff --git a/contracts/client.rs b/contracts/client.rs new file mode 100644 index 0000000..653bcfb --- /dev/null +++ b/contracts/client.rs @@ -0,0 +1,123 @@ +//! Generated from query-api/contracts/client.rs. Run query-api/scripts/sync-query-contract.py. +//! Transport adapter only. Validation, authorization and query execution belong to the API. +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +pub const ENDPOINT: &str = "/api/v1/query/execute"; + +pub fn adapt(path: &str, body: &Value) -> Option { + let registry: Value = serde_json::from_str(include_str!("../contracts/query-v1.json")).ok()?; + let route = registry["routes"] + .as_array()? + .iter() + .find(|r| r["path"] == path)?; + let mut options = body.as_object()?.clone(); + let time_range = options.remove("time_range")?; + let filters = options.remove("filters").unwrap_or_else(|| json!([])); + let search = options.remove("search").unwrap_or(Value::Null); + let signal = if route["signal"] == "dynamic" { + options.remove(if route["operation"] == "scatter" { + "source" + } else { + "signal" + })? + } else { + route["signal"].clone() + }; + Some( + json!({"version":"v1", "signal":signal, "operation":route["operation"], + "time_range":time_range, "filters":filters, "search":search, "options":options}), + ) +} + +#[allow(dead_code)] // The tail-only CLI does not issue PromQL queries. +pub fn prom_request(path: &str, params: &[(&str, String)]) -> Option { + if !matches!(path, "/prom/api/v1/query" | "/prom/api/v1/query_range") { + return None; + } + let get = |key: &str| { + params + .iter() + .find(|(k, _)| *k == key) + .map(|(_, v)| v.clone()) + }; + // Resolve "now" once, so instant queries have an explicit, reproducible evaluation time. + let end = get(if path.ends_with("query_range") { + "end" + } else { + "time" + }) + .unwrap_or_else(|| (chrono::Utc::now().timestamp_millis() as f64 / 1000.0).to_string()); + let start = get("start").unwrap_or_else(|| end.clone()); + let timestamp = |s: &str| { + let seconds = s.parse::().ok()?; + if !seconds.is_finite() { + return None; + } + chrono::DateTime::from_timestamp_millis((seconds * 1000.0) as i64) + .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) + }; + let mut options = json!({"query": get("query")?}); + if let Some(step) = get("step") { + options["step"] = json!(step); + } + Some(json!({"version":"v1", "signal":"metrics", + "operation":if path.ends_with("query_range") { "range" } else { "instant" }, + "time_range":{"from":timestamp(&start)?, "to":timestamp(&end)?}, + "filters":[], "search":null, "options":options})) +} + +/// Reject a wrong version or a response for a different query before decoding data. +pub fn decode(bytes: &[u8], request: &Value) -> Result { + let envelope: Value = serde_json::from_slice(bytes)?; + for key in ["version", "signal", "operation"] { + if envelope.get(key) != request.get(key) { + return Err(::custom( + "query response contract mismatch", + )); + } + } + let data = envelope.get("data").cloned().ok_or_else(|| { + ::custom("query response is missing data") + })?; + serde_json::from_value(data) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shared_fixtures() { + let cases: Value = + serde_json::from_str(include_str!("../contracts/query-v1.fixtures.json")).unwrap(); + for c in cases.as_array().unwrap() { + let actual = if let Some(params) = c.get("params") { + let pairs: Vec<_> = params + .as_object() + .unwrap() + .iter() + .map(|(k, v)| (k.as_str(), v.as_str().unwrap().to_string())) + .collect(); + prom_request(c["path"].as_str().unwrap(), &pairs) + } else { + adapt(c["path"].as_str().unwrap(), &c["body"]) + }; + assert_eq!(actual, Some(c["request"].clone()), "{}", c["path"]); + let response = json!({"version":"v1", "signal":c["request"]["signal"], + "operation":c["request"]["operation"], "data":{"rows":[]}, "meta":{}}); + assert_eq!( + decode::(&serde_json::to_vec(&response).unwrap(), &c["request"]).unwrap(), + json!({"rows":[]}) + ); + } + } + + #[test] + fn rejects_wrong_envelopes_and_leaves_mutations_alone() { + assert!(adapt("/api/v1/dashboards", &json!({})).is_none()); + let request = json!({"version":"v1", "signal":"logs", "operation":"search"}); + assert!(decode::(br#"{"version":"v2","data":{}}"#, &request).is_err()); + assert!(decode::(br#"{"rows":[]}"#, &request).is_err()); + } +} diff --git a/contracts/client.ts b/contracts/client.ts new file mode 100644 index 0000000..97bbe47 --- /dev/null +++ b/contracts/client.ts @@ -0,0 +1,48 @@ +// Generated from query-api/contracts/client.ts. Run query-api/scripts/sync-query-contract.py. +import registry from '../../contracts/query-v1.json' + +export const QUERY_ENDPOINT = '/query/execute' +export interface UnifiedQuery { + version: 'v1' + signal: string + operation: string + time_range: { from: string; to: string } + filters: unknown[] + search: string | null + options: Record +} + +/** Preserve legacy call signatures at the UI boundary, not on the wire. */ +export function adaptQuery(path: string, body: Record): UnifiedQuery | undefined { + const fullPath = path.startsWith('/api/v1/') ? path : `/api/v1${path}` + const route = registry.routes.find(r => r.path === fullPath) + if (!route || !body.time_range) return undefined + const { time_range, filters = [], search = null, ...options } = body + let signal = route.signal + if (signal === 'dynamic') { + const key = route.operation === 'scatter' ? 'source' : 'signal' + signal = String(options[key]) + delete options[key] + } + return { version: 'v1', signal, operation: route.operation, + time_range: time_range as UnifiedQuery['time_range'], filters: filters as unknown[], + search: search as string | null, options } +} + +export function metricsQuery(query: string, start: number, end: number, step?: number): UnifiedQuery { + const options: Record = { query } + if (step !== undefined) options.step = String(step) + return { version: 'v1', signal: 'metrics', operation: step === undefined ? 'instant' : 'range', + time_range: { from: new Date(start * 1000).toISOString(), to: new Date(end * 1000).toISOString() }, + filters: [], search: null, options } +} + +export function decodeQuery(envelope: unknown, request: UnifiedQuery): T { + if (!envelope || typeof envelope !== 'object') throw new Error('Invalid query response') + const result = envelope as Record + if (result.version !== request.version || result.signal !== request.signal + || result.operation !== request.operation || !Object.hasOwn(result, 'data')) { + throw new Error('Query response contract mismatch. Check your API version.') + } + return result.data as T +} diff --git a/contracts/query-v1.fixtures.json b/contracts/query-v1.fixtures.json new file mode 100644 index 0000000..6cbedf7 --- /dev/null +++ b/contracts/query-v1.fixtures.json @@ -0,0 +1,7 @@ +[ + {"path":"/api/v1/logs","body":{"time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[{"field":"service_name","op":"=","value":"payments"}],"search":"timeout","limit":50,"slim":true},"request":{"version":"v1","signal":"logs","operation":"search","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[{"field":"service_name","op":"=","value":"payments"}],"search":"timeout","options":{"limit":50,"slim":true}}}, + {"path":"/api/v1/query","body":{"time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"cursor":"opaque","columns":"list"},"request":{"version":"v1","signal":"spans","operation":"search","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"search":null,"options":{"cursor":"opaque","columns":"list"}}}, + {"path":"/api/v1/explore/search","body":{"signal":"logs","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"include_rows":false,"include_summary":true},"request":{"version":"v1","signal":"logs","operation":"explore","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"search":null,"options":{"include_rows":false,"include_summary":true}}}, + {"path":"/prom/api/v1/query_range","params":{"query":"rate(requests_total[5m])","start":"1767225600","end":"1767229200","step":"15"},"request":{"version":"v1","signal":"metrics","operation":"range","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T01:00:00.000Z"},"filters":[],"search":null,"options":{"query":"rate(requests_total[5m])","step":"15"}}}, + {"path":"/prom/api/v1/query","params":{"query":"up","time":"1767225600"},"request":{"version":"v1","signal":"metrics","operation":"instant","time_range":{"from":"2026-01-01T00:00:00.000Z","to":"2026-01-01T00:00:00.000Z"},"filters":[],"search":null,"options":{"query":"up"}}} +] diff --git a/contracts/query-v1.json b/contracts/query-v1.json new file mode 100644 index 0000000..2ce7b63 --- /dev/null +++ b/contracts/query-v1.json @@ -0,0 +1,21 @@ +{ + "version": "v1", + "endpoint": "/api/v1/query/execute", + "max_filters": 30, + "max_search_bytes": 512, + "routes": [ + {"path":"/api/v1/query","signal":"spans","operation":"search","options":["limit","offset","cursor","columns","group_by","aggregation"]}, + {"path":"/api/v1/logs","signal":"logs","operation":"search","options":["limit","offset","cursor","slim","display_fields"]}, + {"path":"/api/v1/explore/search","signal":"dynamic","operation":"explore","options":["limit","interval","group_by","display_fields","include_rows","include_summary"]}, + {"path":"/api/v1/query/count","signal":"spans","operation":"count","options":["interval"]}, + {"path":"/api/v1/logs/count","signal":"logs","operation":"count","options":["interval"]}, + {"path":"/api/v1/query/group","signal":"spans","operation":"group","options":["group_by","aggregation","limit"]}, + {"path":"/api/v1/logs/group","signal":"logs","operation":"group","options":["group_by","aggregation","limit"]}, + {"path":"/api/v1/query/timeseries","signal":"spans","operation":"timeseries","options":["interval","group_by","include_heatmap"]}, + {"path":"/api/v1/logs/histogram","signal":"logs","operation":"histogram","options":[]}, + {"path":"/api/v1/logs/patterns","signal":"logs","operation":"patterns","options":["limit"]}, + {"path":"/api/v1/query/scatter","signal":"dynamic","operation":"scatter","options":["x_field","y_field","limit"]}, + {"path":"/prom/api/v1/query_range","signal":"metrics","operation":"range","options":["query","step"]}, + {"path":"/prom/api/v1/query","signal":"metrics","operation":"instant","options":["query"]} + ] +} diff --git a/contracts/query-v1.schema.json b/contracts/query-v1.schema.json new file mode 100644 index 0000000..af5ec55 --- /dev/null +++ b/contracts/query-v1.schema.json @@ -0,0 +1,541 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Rush query v1", + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "signal", + "operation", + "time_range" + ], + "properties": { + "version": { + "const": "v1" + }, + "signal": { + "enum": [ + "logs", + "spans", + "metrics" + ] + }, + "operation": { + "type": "string" + }, + "time_range": { + "type": "object", + "required": [ + "from", + "to" + ], + "properties": { + "from": { + "type": "string", + "format": "date-time" + }, + "to": { + "type": "string", + "format": "date-time" + } + } + }, + "filters": { + "type": "array", + "maxItems": 30, + "items": { + "type": "object", + "required": [ + "field", + "op", + "value" + ], + "properties": { + "field": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "not": { + "const": "tenant_id" + } + }, + "op": { + "enum": [ + "=", + "!=", + ">", + ">=", + "<", + "<=", + "LIKE", + "NOT LIKE", + "IN", + "NOT IN" + ] + }, + "value": { + "oneOf": [ + { + "type": [ + "string", + "number", + "boolean" + ] + }, + { + "type": "array", + "minItems": 1, + "maxItems": 100, + "items": { + "type": [ + "string", + "number", + "boolean" + ] + } + } + ] + } + } + } + }, + "search": { + "type": [ + "string", + "null" + ], + "maxLength": 512 + }, + "options": { + "type": "object" + } + }, + "oneOf": [ + { + "properties": { + "signal": { + "const": "spans" + }, + "operation": { + "const": "search" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + }, + "offset": { + "type": "integer", + "minimum": 0, + "maximum": 10000 + }, + "cursor": { + "type": [ + "string", + "null" + ], + "maxLength": 8192 + }, + "columns": { + "enum": [ + "list", + "wide", + null + ] + }, + "group_by": { + "type": "array", + "items": { + "type": "string" + } + }, + "aggregation": { + "type": "string" + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "logs" + }, + "operation": { + "const": "search" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + }, + "offset": { + "type": "integer", + "minimum": 0, + "maximum": 10000 + }, + "cursor": { + "type": [ + "string", + "null" + ], + "maxLength": 8192 + }, + "slim": { + "type": "boolean" + }, + "display_fields": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + }, + { + "properties": { + "signal": { + "enum": [ + "logs", + "spans" + ] + }, + "operation": { + "const": "explore" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + }, + "interval": { + "enum": [ + "1s", + "10s", + "1m", + "5m", + "15m", + "1h", + "1d" + ] + }, + "group_by": { + "type": [ + "string", + "null" + ] + }, + "display_fields": { + "type": "array", + "items": { + "type": "string" + } + }, + "include_rows": { + "type": "boolean" + }, + "include_summary": { + "type": "boolean" + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "spans" + }, + "operation": { + "const": "count" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "interval": { + "enum": [ + "1s", + "10s", + "1m", + "5m", + "15m", + "1h", + "1d" + ] + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "logs" + }, + "operation": { + "const": "count" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "interval": { + "enum": [ + "1s", + "10s", + "1m", + "5m", + "15m", + "1h", + "1d" + ] + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "spans" + }, + "operation": { + "const": "group" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "group_by": { + "type": "array", + "items": { + "type": "string" + } + }, + "aggregation": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "logs" + }, + "operation": { + "const": "group" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "group_by": { + "type": "array", + "items": { + "type": "string" + } + }, + "aggregation": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "spans" + }, + "operation": { + "const": "timeseries" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "interval": { + "enum": [ + "1s", + "10s", + "1m", + "5m", + "15m", + "1h", + "1d" + ] + }, + "group_by": { + "type": [ + "string", + "null" + ] + }, + "include_heatmap": { + "type": "boolean" + } + } + } + } + }, + { + "properties": { + "signal": { + "const": "logs" + }, + "operation": { + "const": "histogram" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": {} + } + } + }, + { + "properties": { + "signal": { + "const": "logs" + }, + "operation": { + "const": "patterns" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 50 + } + } + } + } + }, + { + "properties": { + "signal": { + "enum": [ + "logs", + "spans" + ] + }, + "operation": { + "const": "scatter" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "x_field": { + "type": "string" + }, + "y_field": { + "type": "string" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 2000 + } + }, + "required": [ + "x_field", + "y_field" + ] + } + }, + "required": [ + "options" + ] + }, + { + "properties": { + "signal": { + "const": "metrics" + }, + "operation": { + "const": "range" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 16384 + }, + "step": { + "type": "string", + "minLength": 1, + "maxLength": 32 + } + }, + "required": [ + "query" + ] + } + }, + "required": [ + "options" + ] + }, + { + "properties": { + "signal": { + "const": "metrics" + }, + "operation": { + "const": "instant" + }, + "options": { + "type": "object", + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 16384 + } + }, + "required": [ + "query" + ] + } + }, + "required": [ + "options" + ] + } + ] +} diff --git a/docs/unified-query-contract.md b/docs/unified-query-contract.md new file mode 100644 index 0000000..c2e7ff2 --- /dev/null +++ b/docs/unified-query-contract.md @@ -0,0 +1,119 @@ +# Unified query contract + +`POST /api/v1/query/execute` is the query boundary for the frontend, CLI, MCP +server and SRE agent. Deploy query-api before the updated clients. There is no +automatic retry against legacy endpoints, so a failed query runs only once. +The existing endpoints, including the Prometheus-compatible GET/form APIs, +remain available to older clients and external tools. + +```json +{ + "version": "v1", + "signal": "logs", + "operation": "search", + "time_range": { + "from": "2026-11-07T10:00:00.000Z", + "to": "2026-11-07T11:00:00.000Z" + }, + "filters": [{"field": "service_name", "op": "=", "value": "payments"}], + "search": "timeout", + "options": {"limit": 100, "slim": true} +} +``` + +Send the authenticated session/API key and `X-Rush-Tenant` as before. Tenant scope +comes exclusively from authentication and the tenant middleware, never the body. +Internal SRE reads retain their internal token and explicit investigation tenant. +This endpoint does not create or mutate resources or add telemetry queries to +the user-activity audit log. + +The common fields mean the same thing in every client: + +- `version` is required. Only `v1` is supported. Unknown top-level fields fail. +- `signal` is `logs`, `spans` or `metrics`. UI trace mode is a span query with + its existing root-span filters, not a fourth telemetry signal. +- `time_range` contains absolute RFC3339 bounds. Clients resolve relative + lookbacks once. Existing query-engine boundary semantics are unchanged. +- `filters` are ANDed. Operators are `=`, `!=`, `>`, `>=`, `<`, `<=`, `LIKE`, + `NOT LIKE`, `IN` and `NOT IN`. Membership takes a nonempty scalar array of at + most 100 values. Other operators take a scalar. There are at most 30 filters. + Fields are at most 128 bytes, values at most 8192 encoded bytes. `tenant_id` + is reserved. Attribute aliases and search syntax use the existing builders. +- `search` is optional, at most 512 UTF-8 bytes. Metrics put selectors inside + PromQL. Nonempty search/filters on metrics are rejected, not ignored. +- `options` is an operation-specific object. Unknown options fail rather than + silently changing a query. `contracts/query-v1.json` lists supported options. + +| Signal | Operations | +| --- | --- | +| Logs | search, explore, count, group, histogram, patterns, scatter | +| Spans | search, explore, count, group, timeseries, scatter | +| Metrics | range, instant | + +Search defaults to 100 rows, capped at 1000. Offset is capped at 10000; prefer +the returned opaque cursor. Pattern limit is at most 50 and scatter at most 2000. +Pattern/scatter operations support structured filters, not free-text search. +Their existing tighter validation still applies. Explore can request rows and +summaries independently. Time buckets use `1s`, `10s`, `1m`, `5m`, `15m`, `1h` +or `1d`; the existing server-side bucket cap can increase the interval. + +For metrics, use `options.query` and, for a range, `options.step` as a positive +seconds/duration string. Instant queries use equal `from`/`to` bounds. The shared +adapters convert existing Unix-second client arguments to RFC3339. + +## Results and errors + +```json +{ + "version": "v1", + "signal": "logs", + "operation": "search", + "data": {"rows": [], "total": 0, "has_more": false}, + "meta": { + "request_id": "server-generated-id", + "time_range": {"from": "2026-11-07T10:00:00Z", "to": "2026-11-07T11:00:00Z"}, + "elapsed_ms": 12, + "partial": false, + "warnings": [] + } +} +``` + +`data` preserves the operation's current result format. Search returns rows; +count returns buckets; range/instant retains the Prometheus response including +`resultType` and series. Exact/capped Explore counts, authenticated cursors, +histogram/facet errors and scatter's `truncated` flag remain intact. `partial` +means a summary failed, not that the returned rows were truncated. Truncation +and count precision remain explicit in `data`. Clients check version, signal +and operation before decoding it. Results over 32 MiB fail, not truncate. + +Failures use HTTP status plus +`{"error":{"code":"invalid_query","message":"...","request_id":"..."}}`. +Version mismatches use `unsupported_query_version`. Auth, CSRF, workload and +JSON failures use the same envelope. Internal SQL, query text and backend +causes are never returned in error messages. `Retry-After`, request IDs and +existing admission/time/read budgets are preserved. No tenant/auth policy is +implemented separately inside this dispatcher. + +## Updating the contract + +The API owns the registry, generated JSON Schema and language adapters in +`contracts/`. `GET /api/v1/query/schema` returns the request schema. Change +the registry and adapter templates in query-api, not their generated copies. + +```sh +# From repos/query-api. App repositories can still build independently. +rustfmt --edition 2024 contracts/client.rs +python3 scripts/sync-query-contract.py --workspace .. +python3 scripts/sync-query-contract.py --workspace .. --check +``` + +Commit the updated copies in each affected repository. Standalone API CI checks +that its schema is current. All three Rust clients and the frontend run the same +JSON fixtures for request serialization and response checks. The dispatcher +has validation and partial-result tests, and transport/browser tests exercise +tenant headers, credentials, cancellation and dashboard query sharing. + +This contract covers telemetry search, aggregation and PromQL execution. +Trace detail, profiles, metadata discovery, integrations and resource mutations +keep their dedicated APIs. It is not a raw-SQL endpoint or a cross-signal join. diff --git a/scripts/sync-query-contract.py b/scripts/sync-query-contract.py new file mode 100644 index 0000000..b626d89 --- /dev/null +++ b/scripts/sync-query-contract.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Generate the v1 JSON Schema; optionally sync standalone client contract copies. + + python3 scripts/sync-query-contract.py --check + python3 scripts/sync-query-contract.py --workspace .. + python3 scripts/sync-query-contract.py --workspace .. --check + +No network, dependencies, or runtime paths to sibling repositories. +""" +import argparse +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def schema(registry): + scalar = {"type": ["string", "number", "boolean"]} + option_types = { + "limit": {"type": "integer", "minimum": 1, "maximum": 2000}, + "offset": {"type": "integer", "minimum": 0, "maximum": 10000}, + "cursor": {"type": ["string", "null"], "maxLength": 8192}, + "columns": {"enum": ["list", "wide", None]}, + "slim": {"type": "boolean"}, + "display_fields": {"type": "array", "items": {"type": "string"}}, + "include_rows": {"type": "boolean"}, "include_summary": {"type": "boolean"}, + "include_heatmap": {"type": "boolean"}, + "interval": {"enum": ["1s", "10s", "1m", "5m", "15m", "1h", "1d"]}, + "aggregation": {"type": "string"}, + "group_by": {"oneOf": [{"type": ["string", "null"]}, {"type": "array", "items": {"type": "string"}}]}, + "x_field": {"type": "string"}, "y_field": {"type": "string"}, + "query": {"type": "string", "minLength": 1, "maxLength": 16384}, + "step": {"type": "string", "minLength": 1, "maxLength": 32}, + } + variants = [] + for route in registry["routes"]: + options = {k: dict(option_types[k]) for k in route["options"]} + if "limit" in options: + options["limit"]["maximum"] = {"patterns": 50, "scatter": 2000}.get(route["operation"], 1000) + if "group_by" in options: + options["group_by"] = {"type": ["string", "null"]} if route["operation"] in ("timeseries", "explore") else {"type":"array", "items":{"type":"string"}} + option_schema = {"type": "object", "additionalProperties": False, "properties": options} + if route["signal"] == "metrics": option_schema["required"] = ["query"] + if route["operation"] == "scatter": option_schema["required"] = ["x_field", "y_field"] + variant = {"properties": { + "signal": {"enum": ["logs", "spans"]} if route["signal"] == "dynamic" else {"const": route["signal"]}, + "operation": {"const": route["operation"]}, "options": option_schema, + }} + if "required" in option_schema: variant["required"] = ["options"] + variants.append(variant) + return {"$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Rush query v1", + "type": "object", "additionalProperties": False, + "required": ["version", "signal", "operation", "time_range"], + "properties": { + "version": {"const": "v1"}, "signal": {"enum": ["logs", "spans", "metrics"]}, + "operation": {"type": "string"}, + "time_range": {"type": "object", "required": ["from", "to"], "properties": { + "from": {"type": "string", "format": "date-time"}, "to": {"type": "string", "format": "date-time"}}}, + "filters": {"type": "array", "maxItems": registry["max_filters"], "items": { + "type": "object", "required": ["field", "op", "value"], "properties": { + "field": {"type": "string", "minLength": 1, "maxLength": 128, "not": {"const": "tenant_id"}}, + "op": {"enum": ["=", "!=", ">", ">=", "<", "<=", "LIKE", "NOT LIKE", "IN", "NOT IN"]}, + "value": {"oneOf": [scalar, {"type": "array", "minItems": 1, "maxItems": 100, "items": scalar}]}}}}, + "search": {"type": ["string", "null"], "maxLength": registry["max_search_bytes"]}, + "options": {"type": "object"}, + }, "oneOf": variants} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--workspace", type=Path, help="directory containing app checkouts") + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + registry = json.loads((ROOT / "contracts/query-v1.json").read_text()) + schema_bytes = (json.dumps(schema(registry), indent=2) + "\n").encode() + outputs = {ROOT / "contracts/query-v1.schema.json": schema_bytes} + if args.workspace: + for repo in ("frontend", "rush-cli", "mcp-server", "sre-agent"): + checkout = args.workspace.resolve() / repo + if not (checkout / ".git").exists(): + parser.error(f"not a checkout: {checkout}") + for name in ("query-v1.json", "query-v1.fixtures.json"): + outputs[checkout / "contracts" / name] = (ROOT / "contracts" / name).read_bytes() + target = "src/lib/queryContract.ts" if repo == "frontend" else "src/query_contract.rs" + template = "client.ts" if repo == "frontend" else "client.rs" + outputs[checkout / target] = (ROOT / "contracts" / template).read_bytes() + stale = [] + for path, data in outputs.items(): + if path.exists() and path.read_bytes() == data: continue + if args.check: stale.append(str(path)) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + if stale: + raise SystemExit("Stale generated contracts:\n" + "\n".join(stale)) + print(f"{'Checked' if args.check else 'Synced'} {len(outputs)} contract files") + + +if __name__ == "__main__": + main() diff --git a/src/api_error.rs b/src/api_error.rs index 7db8776..c49a03e 100644 --- a/src/api_error.rs +++ b/src/api_error.rs @@ -201,6 +201,7 @@ fn normalize_server_error(mut response: Response, request_id: &str) -> Response /// non-sensitive response contract as routed handlers. pub async fn public_error_middleware(mut req: Request, next: Next) -> Response { let request_id = new_request_id(); + let unified_query = req.uri().path() == "/api/v1/query/execute"; if let Ok(value) = HeaderValue::from_str(&request_id) { req.headers_mut() .insert(HeaderName::from_static(REQUEST_ID_HEADER), value); @@ -211,6 +212,38 @@ pub async fn public_error_middleware(mut req: Request, next: Next) -> Response { let mut response = next.run(req).await; if response.status().is_server_error() { response = normalize_server_error(response, &request_id); + } else if unified_query + && response.status().is_client_error() + && response + .extensions() + .get::() + .is_none() + { + // Auth, JSON extraction, CSRF and admission failures must use the + // same safe envelope as errors originating in the query handler. + let status = response.status(); + let (code, message) = match status { + StatusCode::UNAUTHORIZED => ("unauthorized", "authentication is required"), + StatusCode::FORBIDDEN => ("forbidden", "access to this query is denied"), + StatusCode::TOO_MANY_REQUESTS => { + ("rate_limited", "query capacity is busy; retry shortly") + } + StatusCode::PAYLOAD_TOO_LARGE => ( + "query_body_too_large", + "query request body exceeds the configured limit", + ), + _ => ("invalid_query", "query does not match the v1 contract"), + }; + let (parts, _) = response.into_parts(); + response = ApiError::public(status, code, message).into_response(); + for (name, value) in &parts.headers { + if name != header::CONTENT_TYPE + && name != header::CONTENT_LENGTH + && name != header::CONTENT_ENCODING + { + response.headers_mut().append(name.clone(), value.clone()); + } + } } if let Ok(value) = HeaderValue::from_str(&request_id) { response @@ -294,6 +327,44 @@ mod tests { assert!(rendered.contains(&error.request_id)); } + #[tokio::test] + async fn query_contract_normalizes_pre_handler_errors_without_losing_retry_headers() { + let app = Router::new() + .route( + "/api/v1/query/execute", + get(|| async { + ( + StatusCode::TOO_MANY_REQUESTS, + [(header::RETRY_AFTER, "7")], + "secret SQL details", + ) + }), + ) + .layer(axum::middleware::from_fn(public_error_middleware)); + let response = app + .oneshot( + Request::builder() + .uri("/api/v1/query/execute") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); + assert_eq!(response.headers()[header::RETRY_AFTER], "7"); + let id = response.headers()[REQUEST_ID_HEADER] + .to_str() + .unwrap() + .to_string(); + let bytes = axum::body::to_bytes(response.into_body(), 10000) + .await + .unwrap(); + let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["error"]["code"], "rate_limited"); + assert_eq!(value["error"]["request_id"], id); + assert!(!String::from_utf8_lossy(&bytes).contains("secret")); + } + #[tokio::test] async fn middleware_replaces_a_legacy_internal_error_body() { let app = Router::new() diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 0ab72ec..2b03020 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -42,6 +42,7 @@ pub mod parse_promql; pub mod parse_query; pub mod profiles; pub mod query; +pub mod query_contract; pub mod query_diagnostics; pub mod remote_write; pub mod repository_access; diff --git a/src/handlers/query_contract.rs b/src/handlers/query_contract.rs new file mode 100644 index 0000000..74e95bd --- /dev/null +++ b/src/handlers/query_contract.rs @@ -0,0 +1,492 @@ +//! Versioned query boundary. Existing handlers remain the only query executors. +use axum::{ + Extension, Json, + extract::{Query, State, rejection::JsonRejection}, + http::StatusCode, + response::{IntoResponse, Response}, +}; +use serde::{Deserialize, de::DeserializeOwned}; +use serde_json::{Value, json}; +use std::{sync::LazyLock, time::Instant}; + +use super::{dashboard_panels, explore, logs, metrics, query}; +use crate::{ + AppState, TenantContext, + api_error::ApiError, + models::query::{Filter, FilterOp, TimeRange}, + query_governor::ValidatedTimeRange, +}; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Request { + version: String, + signal: String, + operation: String, + time_range: TimeRange, + #[serde(default)] + filters: Vec, + #[serde(default)] + search: Option, + #[serde(default = "empty_options")] + options: Value, +} + +fn empty_options() -> Value { + json!({}) +} +fn invalid() -> ApiError { + ApiError::public( + StatusCode::BAD_REQUEST, + "invalid_query", + "query does not match the v1 contract", + ) +} +fn decode(body: Value) -> Result { + serde_json::from_value(body).map_err(|_| invalid()) +} + +static REGISTRY: LazyLock = LazyLock::new(|| { + serde_json::from_str(include_str!("../../contracts/query-v1.json")).expect("query registry") +}); + +fn unix_seconds(value: &str) -> String { + (chrono::DateTime::parse_from_rfc3339(value) + .expect("validated time") + .timestamp_millis() as f64 + / 1000.0) + .to_string() +} + +/// The same registry ships in each client repository. No checkout-relative runtime dependency. +pub async fn schema() -> Json { + Json( + serde_json::from_str(include_str!("../../contracts/query-v1.schema.json")) + .expect("query schema"), + ) +} + +impl Request { + fn legacy_body(&self) -> Result { + if self.version != "v1" { + return Err(ApiError::public( + StatusCode::BAD_REQUEST, + "unsupported_query_version", + "supported query contract version is v1", + )); + } + let route = REGISTRY["routes"] + .as_array() + .unwrap() + .iter() + .find(|r| { + r["operation"] == self.operation + && (r["signal"] == self.signal + || r["signal"] == "dynamic" + && matches!(self.signal.as_str(), "logs" | "spans")) + }) + .ok_or_else(invalid)?; + let options = self.options.as_object().ok_or_else(invalid)?; + if options + .keys() + .any(|k| !route["options"].as_array().unwrap().iter().any(|v| v == k)) + { + return Err(invalid()); + } + let budget = + crate::query_governor::active_budget().map_or(30 * 86400, |b| b.max_time_range_secs); + // All callers send absolute RFC3339. Relative lookbacks are resolved exactly once by clients. + if chrono::DateTime::parse_from_rfc3339(&self.time_range.from).is_err() + || chrono::DateTime::parse_from_rfc3339(&self.time_range.to).is_err() + { + return Err(invalid()); + } + ValidatedTimeRange::parse(&self.time_range.from, &self.time_range.to, budget) + .map_err(|_| invalid())?; + if self.filters.len() > REGISTRY["max_filters"].as_u64().unwrap() as usize + || self + .search + .as_ref() + .is_some_and(|s| s.len() > REGISTRY["max_search_bytes"].as_u64().unwrap() as usize) + { + return Err(invalid()); + } + for filter in &self.filters { + if filter.field.is_empty() + || filter.field.len() > 128 + || filter.field.trim() != filter.field + || filter.field == "tenant_id" + || filter.field.chars().any(char::is_control) + { + return Err(invalid()); + } + let scalar = |v: &Value| v.is_string() || v.is_number() || v.is_boolean(); + let valid = match filter.op { + FilterOp::In | FilterOp::NotIn => filter + .value + .as_array() + .is_some_and(|a| !a.is_empty() && a.len() <= 100 && a.iter().all(scalar)), + _ => scalar(&filter.value), + }; + if !valid || serde_json::to_vec(&filter.value).map_or(true, |v| v.len() > 8192) { + return Err(invalid()); + } + } + if self.signal == "metrics" + && (!self.filters.is_empty() || self.search.as_ref().is_some_and(|s| !s.is_empty())) + { + // PromQL owns its selectors. Never silently ignore a structured filter. + return Err(invalid()); + } + if matches!(self.operation.as_str(), "patterns" | "scatter") + && self.search.as_ref().is_some_and(|s| !s.is_empty()) + { + return Err(invalid()); + } + if let Some(limit) = options.get("limit") { + let max = match self.operation.as_str() { + "patterns" => 50, + "scatter" => 2000, + _ => 1000, + }; + if !limit.as_u64().is_some_and(|v| v > 0 && v <= max) { + return Err(invalid()); + } + } + if options + .get("offset") + .is_some_and(|v| v.as_u64().is_none_or(|v| v > 10_000)) + { + return Err(invalid()); + } + if options + .get("cursor") + .is_some_and(|v| !v.is_null() && (!v.is_string() || v.as_str().unwrap().len() > 8192)) + { + return Err(invalid()); + } + if options + .get("columns") + .is_some_and(|v| !v.is_null() && !matches!(v.as_str(), Some("list" | "wide"))) + { + return Err(invalid()); + } + if options.get("interval").is_some_and(|interval| { + !matches!( + interval.as_str(), + Some("1s" | "10s" | "1m" | "5m" | "15m" | "1h" | "1d") + ) + }) { + return Err(invalid()); + } + if self.signal == "metrics" { + if !options + .get("query") + .and_then(Value::as_str) + .is_some_and(|q| !q.trim().is_empty() && q.len() <= 16384) + { + return Err(invalid()); + } + if self.operation == "instant" && self.time_range.from != self.time_range.to { + return Err(invalid()); + } + if options + .get("step") + .is_some_and(|v| !v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 32)) + { + return Err(invalid()); + } + } + let mut body = self.options.clone(); + body["time_range"] = serde_json::to_value(&self.time_range).unwrap(); + body["filters"] = serde_json::to_value(&self.filters).unwrap(); + if !matches!(self.operation.as_str(), "patterns" | "scatter") { + body["search"] = json!(self.search); + } + if self.operation == "explore" { + body["signal"] = json!(self.signal); + } + if self.operation == "scatter" { + body["source"] = json!(self.signal); + } + Ok(body) + } +} + +/// Authentication, signal policy, admission and time budgets run on this route before dispatch. +pub async fn execute( + State(state): State, + Extension(tenant): Extension, + payload: Result, JsonRejection>, +) -> Result { + let Json(req) = payload.map_err(|_| invalid())?; + let body = req.legacy_body()?; + let started = Instant::now(); + // Keep dispatch explicit. None of these handlers accepts SQL or mutates resources. + let result = match (req.signal.as_str(), req.operation.as_str()) { + ("spans", "search") => { + query::execute_query(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs", "search") => { + logs::query_logs(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs" | "spans", "explore") => { + explore::search(State(state), Extension(tenant), Json(decode(body)?)).await + } + ("spans", "count") => { + query::count_query(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs", "count") => logs::count_logs(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response), + ("spans", "group") => { + query::group_query(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs", "group") => logs::group_logs(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response), + ("spans", "timeseries") => { + query::timeseries_query(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs", "histogram") => { + logs::log_histogram(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs", "patterns") => { + dashboard_panels::patterns(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("logs" | "spans", "scatter") => { + dashboard_panels::scatter(State(state), Extension(tenant), Json(decode(body)?)) + .await + .map(IntoResponse::into_response) + } + ("metrics", "range") => metrics::prom_query_range( + State(state), + Extension(tenant), + Query(metrics::RangeQueryParams { + query: req.options["query"].as_str().unwrap().into(), + start: unix_seconds(&req.time_range.from), + end: unix_seconds(&req.time_range.to), + step: req + .options + .get("step") + .and_then(Value::as_str) + .map(str::to_owned), + }), + ) + .await + .map(IntoResponse::into_response), + ("metrics", "instant") => metrics::prom_query( + State(state), + Extension(tenant), + Query(metrics::InstantQueryParams { + query: req.options["query"].as_str().unwrap().into(), + time: Some(unix_seconds(&req.time_range.to)), + }), + ) + .await + .map(IntoResponse::into_response), + _ => return Err(invalid()), + }; + let response = result.map_err(|(status, cause)| { + if status.is_server_error() { + ApiError::internal_with_status(status, "query.execute", cause) + } else { + ApiError::public( + status, + "invalid_query", + "query could not be executed; check its fields and options", + ) + } + })?; + wrap_response(&req, response, started).await +} + +async fn wrap_response( + req: &Request, + response: Response, + started: Instant, +) -> Result { + let (mut parts, body) = response.into_parts(); + let bytes = axum::body::to_bytes(body, 32 * 1024 * 1024) + .await + .map_err(|e| ApiError::internal("query.response", e))?; + let data: Value = + serde_json::from_slice(&bytes).map_err(|e| ApiError::internal("query.response", e))?; + let partial = data + .get("errors") + .and_then(Value::as_object) + .is_some_and(|e| !e.is_empty()); + let warnings: Vec<&str> = if partial { + vec!["Some query summaries are unavailable. Rows may still be complete."] + } else { + vec![] + }; + // Preserve cursors, exact/capped counts and source-specific row/series shapes inside data. + let envelope = json!({"version":"v1", "signal":req.signal, "operation":req.operation, "data":data, + "meta":{"request_id":crate::api_error::current_request_id(), "time_range":req.time_range, + "elapsed_ms":started.elapsed().as_millis() as u64, "partial":partial, "warnings":warnings}}); + parts.headers.remove(axum::http::header::CONTENT_LENGTH); + parts.headers.remove(axum::http::header::CONTENT_ENCODING); + let mut response = Json(envelope).into_response(); + response.headers_mut().extend(parts.headers); + Ok(response) +} + +#[cfg(test)] +mod tests { + use super::*; + fn base() -> Value { + json!({"version":"v1","signal":"logs","operation":"search", + "time_range":{"from":"2026-01-01T00:00:00Z","to":"2026-01-01T01:00:00Z"},"filters":[],"options":{}}) + } + + #[test] + fn client_fixtures_are_accepted() { + let cases: Value = + serde_json::from_str(include_str!("../../contracts/query-v1.fixtures.json")).unwrap(); + for c in cases.as_array().unwrap() { + let request: Request = serde_json::from_value(c["request"].clone()).unwrap(); + request.legacy_body().unwrap(); + } + } + #[test] + fn every_registered_operation_builds_its_existing_handler_request() { + for route in REGISTRY["routes"].as_array().unwrap() { + let signals = if route["signal"] == "dynamic" { + vec!["logs", "spans"] + } else { + vec![route["signal"].as_str().unwrap()] + }; + for signal in signals { + let mut value = base(); + value["signal"] = json!(signal); + value["operation"] = route["operation"].clone(); + value["options"] = match route["operation"].as_str().unwrap() { + "group" => json!({"group_by":["service_name"]}), + "scatter" => json!({"x_field":"attributes.bytes","y_field":"duration_ms"}), + "range" | "instant" => json!({"query":"up"}), + _ => json!({}), + }; + if route["operation"] == "instant" { + value["time_range"]["to"] = value["time_range"]["from"].clone(); + } + let req: Request = serde_json::from_value(value).unwrap(); + let body = req.legacy_body().unwrap(); + match (signal, req.operation.as_str()) { + ("spans", "search" | "group") | ("logs", "group") => { + decode::(body).unwrap(); + } + ("logs", "search") => { + decode::(body).unwrap(); + } + (_, "count") => { + decode::(body).unwrap(); + } + (_, "timeseries") => { + decode::(body).unwrap(); + } + (_, "explore") => { + decode::(body).unwrap(); + } + (_, "histogram") => { + decode::(body).unwrap(); + } + (_, "patterns") => { + decode::(body).unwrap(); + } + (_, "scatter") => { + decode::(body).unwrap(); + } + ("metrics", _) => {} + _ => panic!("uncovered operation"), + } + } + } + assert_eq!(unix_seconds("2026-01-01T00:00:00.250Z"), "1767225600.25"); + } + #[test] + fn rejects_invalid_versions_signals_options_and_scoping() { + for (key, value) in [ + ("version", json!("v2")), + ("signal", json!("audit")), + ("operation", json!("delete")), + ("options", json!({"tenant_id":"other"})), + ("options", json!({"limit":0})), + ("options", json!({"limit":1001})), + ("options", json!({"offset":10001})), + ( + "filters", + json!([{"field":"tenant_id","op":"=","value":"other"}]), + ), + ("filters", json!([{"field":"x","op":"IN","value":"wrong"}])), + ("search", json!("x".repeat(513))), + ] { + let mut body = base(); + body[key] = value; + assert!( + serde_json::from_value::(body) + .unwrap() + .legacy_body() + .is_err(), + "{key}" + ); + } + let mut body = base(); + body["tenant_id"] = json!("other"); + assert!(serde_json::from_value::(body).is_err()); + } + #[test] + fn rejects_ignored_metric_filters_and_bad_time_ranges() { + for range in [ + json!({"from":"yesterday","to":"now"}), + json!({"from":"2026-01-02T00:00:00Z","to":"2026-01-01T00:00:00Z"}), + ] { + let mut body = base(); + body["time_range"] = range; + assert!( + serde_json::from_value::(body) + .unwrap() + .legacy_body() + .is_err() + ); + } + let mut body = base(); + body["signal"] = json!("metrics"); + body["operation"] = json!("range"); + body["options"] = json!({"query":"up"}); + body["search"] = json!("ignored"); + assert!( + serde_json::from_value::(body) + .unwrap() + .legacy_body() + .is_err() + ); + } + #[tokio::test] + async fn preserves_partial_results_and_pagination() { + let req: Request = serde_json::from_value(base()).unwrap(); + let response = wrap_response(&req, Json(json!({"rows":[],"next_cursor":"opaque","count":{"value":1000,"kind":"capped"},"errors":{"histogram":"unavailable"}})).into_response(), Instant::now()).await.unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 10000) + .await + .unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["data"]["next_cursor"], "opaque"); + assert_eq!(value["data"]["count"]["kind"], "capped"); + assert_eq!(value["meta"]["partial"], true); + assert_eq!(value["meta"]["warnings"].as_array().unwrap().len(), 1); + } +} diff --git a/src/main.rs b/src/main.rs index 48d054d..7c30912 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1304,6 +1304,7 @@ fn internal_sre_route_allowed(method: &Method, path: &str) -> bool { matches!( path, "/api/v1/query" + | "/api/v1/query/execute" | "/api/v1/query/count" | "/api/v1/query/group" | "/api/v1/query/timeseries" @@ -2912,6 +2913,8 @@ async fn main() -> anyhow::Result<()> { .route("/jaeger/api/dependencies", get(handlers::jaeger::dependencies)) // Query endpoints .route("/api/v1/query", post(handlers::query::execute_query)) + .route("/api/v1/query/execute", post(handlers::query_contract::execute)) + .route("/api/v1/query/schema", get(handlers::query_contract::schema)) .route("/api/v1/query/count", post(handlers::query::count_query)) .route("/api/v1/query/group", post(handlers::query::group_query)) .route("/api/v1/query/timeseries", post(handlers::query::timeseries_query)) @@ -4196,6 +4199,29 @@ mod tenant_auth_tests { #[test] fn workload_policy_classifies_queries_and_preserves_explicit_bypasses() { + let unified = Request::builder() + .method(Method::POST) + .uri("/api/v1/query/execute") + .body(Body::empty()) + .unwrap(); + assert_eq!( + query_workload_for_request(&unified), + Some(rush_api::query_governor::WorkloadClass::Interactive) + ); + assert!(internal_sre_route_allowed( + &Method::POST, + "/api/v1/query/execute" + )); + assert!(!internal_sre_route_allowed( + &Method::DELETE, + "/api/v1/query/execute" + )); + assert!(should_reject_for_tenant_auth( + &Method::POST, + "/api/v1/query/execute", + true, + false + )); let draft = Request::builder() .method(Method::POST) .uri("/api/v1/sessions/session-1/dashboard-draft")