Skip to main content

omnigraph_server/
lib.rs

1pub mod api;
2mod handlers;
3mod settings;
4pub use settings::{load_server_settings, classify_server_runtime_state, ServerRuntimeState};
5use settings::*;
6use handlers::*;
7pub mod auth;
8pub mod graph_id;
9pub mod identity;
10pub mod policy;
11pub mod queries;
12pub mod registry;
13pub mod workload;
14
15pub use graph_id::GraphId;
16pub use identity::{AuthSource, GraphKey, ResolvedActor, Scope, TenantId};
17pub use registry::{GraphHandle, GraphRegistry, InsertError, RegistryLookup, RegistrySnapshot};
18
19use crate::queries::{QueryRegistry, check, format_check_breakages};
20
21use std::collections::{BTreeMap, HashMap, HashSet};
22use std::fs;
23use std::io;
24use std::io::Write;
25use std::path::PathBuf;
26use std::sync::Arc;
27
28use api::{
29    BranchCreateOutput, BranchCreateRequest, BranchDeleteOutput, BranchListOutput,
30    BranchMergeOutput, BranchMergeRequest, ChangeOutput, ChangeRequest, CommitListOutput,
31    CommitListQuery, ErrorCode, ErrorOutput, ExportRequest, GraphInfo, GraphListResponse,
32    HealthOutput, IngestOutput, IngestRequest, InvokeStoredQueryRequest,
33    InvokeStoredQueryResponse, QueriesCatalogOutput, QueryRequest, ReadOutput, ReadRequest,
34    SchemaApplyOutput, SchemaApplyRequest, SchemaOutput, SnapshotQuery, ingest_output,
35    schema_apply_output, snapshot_payload,
36};
37pub use auth::{AWS_SECRET_ENV, EnvOrFileTokenSource, TokenSource, resolve_token_source};
38use axum::body::{Body, Bytes};
39use axum::extract::DefaultBodyLimit;
40use axum::extract::{Extension, OriginalUri, Path, Query, Request, State};
41use axum::http::StatusCode;
42use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderName, HeaderValue};
43use axum::middleware::{self, Next};
44use axum::response::{IntoResponse, Response};
45use axum::routing::{delete, get, post};
46use axum::{Json, Router};
47use color_eyre::eyre::{Result, WrapErr, bail, eyre};
48use futures::stream;
49use omnigraph::db::{Omnigraph, ReadTarget};
50use omnigraph::error::{ManifestConflictDetails, ManifestErrorKind, OmniError};
51use omnigraph::storage::normalize_root_uri;
52use omnigraph_compiler::catalog::Catalog;
53use omnigraph_compiler::json_params_to_param_map;
54use omnigraph_compiler::query::parser::parse_query;
55use omnigraph_compiler::{JsonParamMode, ParamMap};
56pub use policy::{
57    PolicyAction, PolicyCompiler, PolicyConfig, PolicyDecision, PolicyEngine, PolicyExpectation,
58    PolicyRequest, PolicyResourceKind, PolicyTestConfig,
59};
60use serde::Deserialize;
61use serde_json::Value;
62use sha2::{Digest, Sha256};
63use subtle::ConstantTimeEq;
64use tokio::net::TcpListener;
65use tokio::sync::mpsc;
66use tower_http::trace::TraceLayer;
67use tracing::{error, info, warn};
68use tracing_subscriber::EnvFilter;
69use utoipa::OpenApi;
70use utoipa::openapi::path::{Parameter, ParameterIn};
71use utoipa::openapi::schema::{Object, Type};
72use utoipa::openapi::security::{Http, HttpAuthScheme, SecurityScheme};
73
74type BearerTokenHash = [u8; 32];
75
76fn hash_bearer_token(token: &str) -> BearerTokenHash {
77    let digest = Sha256::digest(token.as_bytes());
78    let mut out = [0u8; 32];
79    out.copy_from_slice(&digest);
80    out
81}
82
83#[derive(OpenApi)]
84#[openapi(
85    info(
86        title = "Omnigraph API",
87        description = "HTTP API for the Omnigraph graph database",
88    ),
89    paths(
90        handlers::server_health,
91        handlers::server_graphs_list,
92        handlers::server_snapshot,
93        // deprecated; the #[deprecated] attribute on the handler
94        // surfaces as `deprecated: true` on the OpenAPI operation.
95        #[allow(deprecated)] handlers::server_read,
96        handlers::server_query,
97        handlers::server_export,
98        #[allow(deprecated)] handlers::server_change,
99        handlers::server_mutate,
100        handlers::server_list_queries,
101        handlers::server_invoke_query,
102        handlers::server_schema_apply,
103        handlers::server_schema_get,
104        handlers::server_load,
105        // deprecated; the #[deprecated] attribute on the handler surfaces as
106        // `deprecated: true` on the OpenAPI operation.
107        #[allow(deprecated)] handlers::server_ingest,
108        handlers::server_branch_list,
109        handlers::server_branch_create,
110        handlers::server_branch_delete,
111        handlers::server_branch_merge,
112        handlers::server_commit_list,
113        handlers::server_commit_show,
114    ),
115    modifiers(&SecurityAddon),
116)]
117pub struct ApiDoc;
118
119/// The canonical served OpenAPI shape (RFC-011 cluster-only): the static
120/// `ApiDoc` with every protected path nested under `/graphs/{graph_id}/…`
121/// and `cluster_`-prefixed operation ids. `/healthz` and `/graphs` stay
122/// flat. This is the single source of nesting — both the runtime
123/// `server_openapi` handler and the committed `openapi.json` derive from
124/// it, so the published spec can never describe routes the server does
125/// not serve. The handler additionally strips security in open mode; the
126/// committed spec retains it.
127pub fn served_openapi() -> utoipa::openapi::OpenApi {
128    let mut doc = ApiDoc::openapi();
129    handlers::nest_paths_under_cluster_prefix(&mut doc);
130    doc
131}
132
133struct SecurityAddon;
134
135impl utoipa::Modify for SecurityAddon {
136    fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
137        openapi
138            .components
139            .get_or_insert_with(Default::default)
140            .add_security_scheme(
141                "bearer_token",
142                SecurityScheme::Http(Http::new(HttpAuthScheme::Bearer)),
143            );
144    }
145}
146
147const DEFAULT_REQUEST_BODY_LIMIT_BYTES: usize = 1_048_576;
148const INGEST_REQUEST_BODY_LIMIT_BYTES: usize = 32 * 1024 * 1024;
149const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
150const SERVER_SOURCE_VERSION: Option<&str> = option_env!("OMNIGRAPH_SOURCE_VERSION");
151
152#[derive(Debug, Clone)]
153pub struct ServerConfig {
154    /// Server topology + the graphs to open at startup. RFC-011
155    /// cluster-only: the server always boots from a cluster
156    /// (`--cluster <dir | s3://…>`) and serves N graphs under cluster
157    /// routes.
158    pub mode: ServerConfigMode,
159    pub bind: String,
160    /// Operator opt-in for fully-unauthenticated dev mode (MR-723).
161    /// When neither bearer tokens nor a policy file are configured,
162    /// `serve()` refuses to start unless this is true (set via
163    /// `--unauthenticated` or `OMNIGRAPH_UNAUTHENTICATED=1`). The
164    /// motivation is that "no tokens + no policy" looks like protection
165    /// (no Cedar errors at boot) but is actually fully open — operators
166    /// who set up auth and forgot the policy file would otherwise ship
167    /// the illusion of protection.
168    pub allow_unauthenticated: bool,
169}
170
171/// What `load_server_settings` produces. RFC-011 cluster-only: the
172/// server always boots from a cluster's applied revision into a
173/// multi-graph deployment (N ≥ 1 graphs).
174#[derive(Debug, Clone)]
175pub enum ServerConfigMode {
176    /// Cluster boot — `--cluster <dir | s3://…>` resolves the applied
177    /// revision into per-graph startup configs plus an optional
178    /// server-level policy.
179    Multi {
180        /// Per-graph startup configs, sorted by graph id (BTreeMap
181        /// iteration order). The parallel-open loop iterates this.
182        graphs: Vec<GraphStartupConfig>,
183        /// The cluster boot source (config directory or storage root).
184        /// Kept on the mode so future runtime mutation (deferred — see
185        /// release notes) can locate the source of truth without
186        /// re-parsing CLI args.
187        config_path: PathBuf,
188        /// Server-level Cedar policy for the management endpoints
189        /// (`GET /graphs`). Wired into `GET /graphs` authorization.
190        server_policy: Option<PolicySource>,
191    },
192}
193
194/// Where a Cedar policy bundle comes from at startup. Cluster-local files are
195/// used during config application; inline digest-verified catalog content is
196/// used for serving, where the catalog may live on object storage and the
197/// server must not re-read mutable state after the snapshot.
198#[derive(Debug, Clone)]
199pub enum PolicySource {
200    File(PathBuf),
201    Inline(String),
202}
203
204/// One graph's startup-time configuration: id, opened URI, optional
205/// per-graph policy source. Constructed by `load_server_settings`
206/// in multi mode; consumed by `serve`'s parallel open loop.
207#[derive(Debug, Clone)]
208pub struct GraphStartupConfig {
209    pub graph_id: String,
210    pub uri: String,
211    pub policy: Option<PolicySource>,
212    /// Pre-resolved embedding config from an applied cluster provider profile.
213    /// Legacy config paths leave this unset and continue to use env resolution.
214    pub embedding: Option<omnigraph::embedding::EmbeddingConfig>,
215    /// Per-graph stored-query registry, loaded and identity-checked at
216    /// settings-build time; type-checked against the schema when this
217    /// graph's engine opens.
218    pub queries: QueryRegistry,
219}
220
221/// Runtime routing for the server (RFC-011 cluster-only). Every
222/// deployment serves cluster routes (`/graphs/{graph_id}/...`) backed by
223/// a registry of N graphs (N ≥ 1). The single-graph convenience
224/// constructors build a one-graph registry keyed by `default`; the
225/// cluster boot path builds an N-graph registry. There is no longer a
226/// flat-route mode.
227///
228/// `config_path` is the boot source (the cluster directory or storage
229/// root); preserved here so future runtime mutation (deferred) can find
230/// the source of truth without re-parsing CLI args. The server treats
231/// the source as operator-owned and never writes it.
232///
233/// All handler bodies are mode-agnostic — the routing middleware
234/// (`resolve_graph_handle`) injects `Arc<GraphHandle>` as a request
235/// extension by looking up the `{graph_id}` URL segment in the registry.
236#[derive(Clone)]
237pub struct GraphRouting {
238    pub registry: Arc<GraphRegistry>,
239    pub config_path: Option<PathBuf>,
240}
241
242#[derive(Clone)]
243pub struct AppState {
244    /// Runtime routing — the single source of truth for where each
245    /// request's graph lives. Single mode holds the handle directly;
246    /// multi mode holds the registry + config path. Both arms are
247    /// the same shape from a handler's perspective: middleware
248    /// extracts an `Arc<GraphHandle>` and injects it as a request
249    /// extension.
250    routing: GraphRouting,
251    /// Per-actor admission control. Process-wide (not per-graph) —
252    /// see MR-668 decision Q6.
253    workload: Arc<workload::WorkloadController>,
254    bearer_tokens: Arc<[(BearerTokenHash, Arc<str>)]>,
255    /// Server-level Cedar policy. Used by management endpoints (`GET
256    /// /graphs`) which act on the registry resource, not on a per-graph
257    /// resource. Loaded from the cluster-scoped policy binding when
258    /// configured. Per-graph policies live on each `GraphHandle.policy`.
259    server_policy: Option<Arc<PolicyEngine>>,
260}
261
262struct ExportStreamWriter {
263    sender: mpsc::UnboundedSender<std::result::Result<Bytes, io::Error>>,
264}
265
266impl Write for ExportStreamWriter {
267    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
268        self.sender
269            .send(Ok(Bytes::copy_from_slice(buf)))
270            .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "export stream closed"))?;
271        Ok(buf.len())
272    }
273
274    fn flush(&mut self) -> io::Result<()> {
275        Ok(())
276    }
277}
278
279#[derive(Debug)]
280pub struct ApiError {
281    status: StatusCode,
282    code: ErrorCode,
283    message: String,
284    merge_conflicts: Vec<api::MergeConflictOutput>,
285    manifest_conflict: Option<api::ManifestConflictOutput>,
286}
287
288impl AppState {
289    /// Canonical single-mode constructor. Every other `new_*` / `open_*`
290    /// helper is a thin convenience wrapper around this one. Builds the
291    /// engine + per-graph policy through `build_single_mode`, which
292    /// applies `Omnigraph::with_policy` so HTTP-layer and engine-layer
293    /// policy can never diverge — there is no "policy installed on HTTP
294    /// but not on engine" representable state (closes the prior
295    /// `with_policy_engine` footgun that reused the engine `Arc`
296    /// without re-applying `with_policy`).
297    pub fn new_single(
298        uri: String,
299        db: Omnigraph,
300        bearer_tokens: Vec<(String, String)>,
301        policy_engine: Option<PolicyEngine>,
302        workload: workload::WorkloadController,
303    ) -> Self {
304        let bearer_tokens = hash_bearer_tokens(bearer_tokens);
305        let per_graph_policy = policy_engine.map(Arc::new);
306        Self::build_single_mode(uri, db, bearer_tokens, per_graph_policy, Arc::new(workload), None)
307    }
308
309    /// Like `new_single`, but attaches a pre-validated stored-query
310    /// registry. Private — the production single-mode boot path
311    /// (`open_single_with_queries`) is the only caller; every public
312    /// `new_*` constructor builds with no stored queries.
313    fn new_single_with_queries(
314        uri: String,
315        db: Omnigraph,
316        bearer_tokens: Vec<(String, String)>,
317        policy_engine: Option<PolicyEngine>,
318        workload: workload::WorkloadController,
319        queries: Option<Arc<QueryRegistry>>,
320    ) -> Self {
321        let bearer_tokens = hash_bearer_tokens(bearer_tokens);
322        let per_graph_policy = policy_engine.map(Arc::new);
323        Self::build_single_mode(
324            uri,
325            db,
326            bearer_tokens,
327            per_graph_policy,
328            Arc::new(workload),
329            queries,
330        )
331    }
332
333    pub fn new(uri: String, db: Omnigraph) -> Self {
334        Self::new_single(
335            uri,
336            db,
337            Vec::new(),
338            None,
339            workload::WorkloadController::from_env(),
340        )
341    }
342
343    pub fn new_with_bearer_token(uri: String, db: Omnigraph, bearer_token: Option<String>) -> Self {
344        let bearer_tokens = normalize_bearer_token(bearer_token)
345            .into_iter()
346            .map(|token| ("default".to_string(), token))
347            .collect();
348        Self::new_with_bearer_tokens(uri, db, bearer_tokens)
349    }
350
351    pub fn new_with_bearer_tokens(
352        uri: String,
353        db: Omnigraph,
354        bearer_tokens: Vec<(String, String)>,
355    ) -> Self {
356        Self::new_single(
357            uri,
358            db,
359            bearer_tokens,
360            None,
361            workload::WorkloadController::from_env(),
362        )
363    }
364
365    pub fn new_with_bearer_tokens_and_policy(
366        uri: String,
367        db: Omnigraph,
368        bearer_tokens: Vec<(String, String)>,
369        policy_engine: Option<PolicyEngine>,
370    ) -> Self {
371        Self::new_single(
372            uri,
373            db,
374            bearer_tokens,
375            policy_engine,
376            workload::WorkloadController::from_env(),
377        )
378    }
379
380    /// Construct with a caller-provided [`workload::WorkloadController`].
381    /// Tests and benches use this to override per-actor caps without
382    /// mutating global env vars (unsafe in Rust 2024 once the async
383    /// runtime is up — `setenv` isn't thread-safe). For tests that also
384    /// need a custom `PolicyEngine`, use [`new_single`] directly.
385    pub fn new_with_workload(
386        uri: String,
387        db: Omnigraph,
388        bearer_tokens: Vec<(String, String)>,
389        workload: workload::WorkloadController,
390    ) -> Self {
391        Self::new_single(uri, db, bearer_tokens, None, workload)
392    }
393
394    pub async fn open(uri: impl Into<String>) -> Result<Self> {
395        Self::open_with_bearer_token(uri, None).await
396    }
397
398    pub async fn open_with_bearer_token(
399        uri: impl Into<String>,
400        bearer_token: Option<String>,
401    ) -> Result<Self> {
402        let bearer_tokens = normalize_bearer_token(bearer_token)
403            .into_iter()
404            .map(|token| ("default".to_string(), token))
405            .collect();
406        Self::open_with_bearer_tokens(uri, bearer_tokens).await
407    }
408
409    pub async fn open_with_bearer_tokens(
410        uri: impl Into<String>,
411        bearer_tokens: Vec<(String, String)>,
412    ) -> Result<Self> {
413        let uri = normalize_root_uri(&uri.into()).wrap_err("normalize graph URI")?;
414        let db = Omnigraph::open(&uri).await?;
415        Ok(Self::new_with_bearer_tokens(uri, db, bearer_tokens))
416    }
417
418    pub async fn open_with_bearer_tokens_and_policy(
419        uri: impl Into<String>,
420        bearer_tokens: Vec<(String, String)>,
421        policy_file: Option<&PathBuf>,
422    ) -> Result<Self> {
423        Self::open_single_with_queries(
424            uri,
425            bearer_tokens,
426            policy_file,
427            QueryRegistry::default(),
428        )
429        .await
430    }
431
432    /// Single-mode boot with a stored-query registry: open the engine,
433    /// **type-check the registry against the live schema and refuse to
434    /// start on a breakage** (same posture as bad policy YAML), log
435    /// non-blocking warnings, then attach the registry to the handle.
436    /// With an empty registry the check is a no-op and no registry is
437    /// attached — that is the path `open_with_bearer_tokens_and_policy`
438    /// (no stored queries) takes.
439    pub async fn open_single_with_queries(
440        uri: impl Into<String>,
441        bearer_tokens: Vec<(String, String)>,
442        policy_file: Option<&PathBuf>,
443        queries: QueryRegistry,
444    ) -> Result<Self> {
445        Self::open_single_with_queries_for_graph_id(uri, bearer_tokens, policy_file, queries, None)
446            .await
447    }
448
449    async fn open_single_with_queries_for_graph_id(
450        uri: impl Into<String>,
451        bearer_tokens: Vec<(String, String)>,
452        policy_file: Option<&PathBuf>,
453        queries: QueryRegistry,
454        graph_id: Option<String>,
455    ) -> Result<Self> {
456        // The "policy requires tokens" invariant is enforced once by
457        // `classify_server_runtime_state` in `serve()`, before either
458        // single-mode or multi-mode construction is reached. By the
459        // time we get here, the (policy, no-tokens) combination has
460        // already been rejected — no second bail needed.
461        let uri = normalize_root_uri(&uri.into()).wrap_err("normalize graph URI")?;
462        let graph_id = graph_id.unwrap_or_else(|| uri.clone());
463        let db = Omnigraph::open(&uri).await?;
464
465        // Validate the registry against the live schema and resolve it to
466        // an attachable handle (refuse boot on breakage).
467        let registry = validate_and_attach(queries, &db.catalog(), &graph_id)?;
468
469        let policy_engine = match policy_file {
470            Some(path) => Some(PolicyEngine::load_graph(path, &graph_id)?),
471            None => None,
472        };
473        Ok(Self::new_single_with_queries(
474            uri,
475            db,
476            bearer_tokens,
477            policy_engine,
478            workload::WorkloadController::from_env(),
479            registry,
480        ))
481    }
482
483    /// Single-graph convenience construction (RFC-011 cluster-only):
484    /// wraps the bare engine + per-graph policy in a `GraphHandle` keyed
485    /// by `default`, then builds a one-graph registry so the deployment
486    /// serves the same `/graphs/{graph_id}/...` cluster routes as any
487    /// other. Per-graph policy enforcement on the engine (MR-722) is
488    /// re-applied via `Omnigraph::with_policy` so HTTP and engine layers
489    /// can never diverge.
490    fn build_single_mode(
491        uri: String,
492        db: Omnigraph,
493        bearer_tokens: Arc<[(BearerTokenHash, Arc<str>)]>,
494        policy_engine: Option<Arc<PolicyEngine>>,
495        workload: Arc<workload::WorkloadController>,
496        queries: Option<Arc<QueryRegistry>>,
497    ) -> Self {
498        // Engine-layer policy gate (MR-722). With a per-graph policy
499        // installed, every `_as` writer on `Omnigraph` calls into the
500        // PolicyChecker. HTTP-layer `authorize_request` is the first
501        // gate; engine-layer is the redundant-but-correct backstop.
502        let db = if let Some(policy) = policy_engine.as_ref() {
503            let checker = Arc::clone(policy) as Arc<dyn omnigraph_policy::PolicyChecker>;
504            db.with_policy(checker)
505        } else {
506            db
507        };
508        // The convenience constructors address the single graph by the
509        // reserved id `default` — both the registry key and the URL
510        // segment (`/graphs/default/...`).
511        let uri = normalize_root_uri(&uri).unwrap_or(uri);
512        let graph_id =
513            GraphId::try_from("default").expect("'default' is a valid GraphId");
514        let key = GraphKey::cluster(graph_id);
515        let handle = Arc::new(GraphHandle {
516            key,
517            uri,
518            engine: Arc::new(db),
519            policy: policy_engine,
520            queries,
521        });
522        let registry = Arc::new(
523            GraphRegistry::from_handles(vec![handle])
524                .expect("a single handle never collides on graph id"),
525        );
526        Self {
527            routing: GraphRouting {
528                registry,
529                config_path: None,
530            },
531            workload,
532            bearer_tokens,
533            server_policy: None,
534        }
535    }
536
537    /// Multi-mode constructor — used by the startup loop. Operators
538    /// reach this by invoking `omnigraph-server --cluster <dir|s3://...>`.
539    ///
540    /// Caller supplies the already-opened `GraphHandle`s and (optionally)
541    /// the path to the source cluster. `server_policy` is loaded from the
542    /// cluster-scoped policy binding if configured.
543    pub fn new_multi(
544        handles: Vec<Arc<GraphHandle>>,
545        bearer_tokens: Vec<(String, String)>,
546        server_policy: Option<PolicyEngine>,
547        workload: workload::WorkloadController,
548        config_path: Option<PathBuf>,
549    ) -> std::result::Result<Self, InsertError> {
550        let bearer_tokens = hash_bearer_tokens(bearer_tokens);
551        let registry = Arc::new(GraphRegistry::from_handles(handles)?);
552        Ok(Self {
553            routing: GraphRouting {
554                registry,
555                config_path,
556            },
557            workload: Arc::new(workload),
558            bearer_tokens,
559            server_policy: server_policy.map(Arc::new),
560        })
561    }
562
563    /// Runtime routing accessor. Handlers don't typically inspect this —
564    /// they extract `Arc<GraphHandle>` via the routing middleware — but
565    /// `server_graphs_list` reads the registry through it.
566    pub fn routing(&self) -> &GraphRouting {
567        &self.routing
568    }
569
570    fn requires_bearer_auth(&self) -> bool {
571        if !self.bearer_tokens.is_empty() {
572            return true;
573        }
574        if self.server_policy.is_some() {
575            return true;
576        }
577        // Any per-graph policy also requires auth — otherwise the
578        // policy gate would receive unauthenticated requests. Reading
579        // the cached `any_per_graph_policy` flag off the registry
580        // snapshot is O(1).
581        self.routing.registry.snapshot_ref().any_per_graph_policy
582    }
583
584    fn authenticate_bearer_token(&self, provided_token: &str) -> Option<ResolvedActor> {
585        // Hash the incoming token and compare against every stored digest in
586        // constant time. Iterate all entries unconditionally so total work —
587        // and therefore response timing — doesn't depend on which slot matches.
588        let provided_hash = hash_bearer_token(provided_token);
589        let mut matched: Option<Arc<str>> = None;
590        for (hash, actor) in self.bearer_tokens.iter() {
591            if bool::from(hash.ct_eq(&provided_hash)) && matched.is_none() {
592                matched = Some(Arc::clone(actor));
593            }
594        }
595        matched.map(ResolvedActor::cluster_static)
596    }
597}
598
599fn hash_bearer_tokens(bearer_tokens: Vec<(String, String)>) -> Arc<[(BearerTokenHash, Arc<str>)]> {
600    let tokens: Vec<(BearerTokenHash, Arc<str>)> = bearer_tokens
601        .into_iter()
602        .map(|(actor, token)| (hash_bearer_token(&token), Arc::<str>::from(actor)))
603        .collect();
604    Arc::from(tokens)
605}
606
607impl ApiError {
608    pub fn unauthorized(message: impl Into<String>) -> Self {
609        Self {
610            status: StatusCode::UNAUTHORIZED,
611            code: ErrorCode::Unauthorized,
612            message: message.into(),
613            merge_conflicts: Vec::new(),
614            manifest_conflict: None,
615        }
616    }
617
618    pub fn forbidden(message: impl Into<String>) -> Self {
619        Self {
620            status: StatusCode::FORBIDDEN,
621            code: ErrorCode::Forbidden,
622            message: message.into(),
623            merge_conflicts: Vec::new(),
624            manifest_conflict: None,
625        }
626    }
627
628    pub fn bad_request(message: impl Into<String>) -> Self {
629        Self {
630            status: StatusCode::BAD_REQUEST,
631            code: ErrorCode::BadRequest,
632            message: message.into(),
633            merge_conflicts: Vec::new(),
634            manifest_conflict: None,
635        }
636    }
637
638    pub fn not_found(message: impl Into<String>) -> Self {
639        Self {
640            status: StatusCode::NOT_FOUND,
641            code: ErrorCode::NotFound,
642            message: message.into(),
643            merge_conflicts: Vec::new(),
644            manifest_conflict: None,
645        }
646    }
647
648    /// HTTP 405 Method Not Allowed. Used when the route is mounted but
649    /// the active server mode doesn't serve it (`GET /graphs` in
650    /// single-graph mode returns this instead of 404 so clients can
651    /// distinguish "wrong context" from "no such resource").
652    pub fn method_not_allowed(message: impl Into<String>) -> Self {
653        Self {
654            status: StatusCode::METHOD_NOT_ALLOWED,
655            code: ErrorCode::MethodNotAllowed,
656            message: message.into(),
657            merge_conflicts: Vec::new(),
658            manifest_conflict: None,
659        }
660    }
661
662    pub fn conflict(message: impl Into<String>) -> Self {
663        Self {
664            status: StatusCode::CONFLICT,
665            code: ErrorCode::Conflict,
666            message: message.into(),
667            merge_conflicts: Vec::new(),
668            manifest_conflict: None,
669        }
670    }
671
672    pub fn internal(message: impl Into<String>) -> Self {
673        Self {
674            status: StatusCode::INTERNAL_SERVER_ERROR,
675            code: ErrorCode::Internal,
676            message: message.into(),
677            merge_conflicts: Vec::new(),
678            manifest_conflict: None,
679        }
680    }
681
682    /// HTTP 429 Too Many Requests — actor exceeded their per-actor
683    /// admission cap (count or byte budget). Clients should respect the
684    /// `Retry-After` header. Mapped from `RejectReason::InFlightCountExceeded`
685    /// and `RejectReason::ByteBudgetExceeded`.
686    pub fn too_many_requests(message: impl Into<String>) -> Self {
687        Self {
688            status: StatusCode::TOO_MANY_REQUESTS,
689            code: ErrorCode::TooManyRequests,
690            message: message.into(),
691            merge_conflicts: Vec::new(),
692            manifest_conflict: None,
693        }
694    }
695
696    /// Convert a `WorkloadController` rejection into the matching
697    /// `ApiError` variant.
698    pub fn from_workload_reject(reject: workload::RejectReason) -> Self {
699        match reject {
700            workload::RejectReason::InFlightCountExceeded { .. }
701            | workload::RejectReason::ByteBudgetExceeded { .. } => {
702                Self::too_many_requests(reject.to_string())
703            }
704        }
705    }
706
707    fn merge_conflict(conflicts: Vec<api::MergeConflictOutput>) -> Self {
708        Self {
709            status: StatusCode::CONFLICT,
710            code: ErrorCode::Conflict,
711            message: summarize_merge_conflicts(&conflicts),
712            merge_conflicts: conflicts,
713            manifest_conflict: None,
714        }
715    }
716
717    fn manifest_version_conflict(message: String, details: api::ManifestConflictOutput) -> Self {
718        Self {
719            status: StatusCode::CONFLICT,
720            code: ErrorCode::Conflict,
721            message,
722            merge_conflicts: Vec::new(),
723            manifest_conflict: Some(details),
724        }
725    }
726
727    fn from_omni(err: OmniError) -> Self {
728        match err {
729            OmniError::Compiler(err) => Self::bad_request(err.to_string()),
730            OmniError::DataFusion(message) => Self::bad_request(format!("query: {message}")),
731            OmniError::Manifest(err) => match err.kind {
732                ManifestErrorKind::BadRequest => Self::bad_request(err.message),
733                ManifestErrorKind::NotFound => Self::not_found(err.message),
734                ManifestErrorKind::Conflict => match err.details {
735                    Some(ManifestConflictDetails::ExpectedVersionMismatch {
736                        table_key,
737                        expected,
738                        actual,
739                    }) => Self::manifest_version_conflict(
740                        err.message,
741                        api::ManifestConflictOutput {
742                            table_key,
743                            expected,
744                            actual,
745                        },
746                    ),
747                    _ => Self::conflict(err.message),
748                },
749                ManifestErrorKind::Internal => Self::internal(err.message),
750            },
751            OmniError::MergeConflicts(conflicts) => Self::merge_conflict(
752                conflicts
753                    .iter()
754                    .map(api::MergeConflictOutput::from)
755                    .collect(),
756            ),
757            OmniError::Lance(message) => Self::internal(format!("storage: {message}")),
758            OmniError::Io(err) => Self::internal(format!("io: {err}")),
759            // Engine-layer policy enforcement (MR-722). All denials and
760            // evaluation failures surface here as 403. The HTTP-layer
761            // `authorize_request` already distinguishes 401 (missing
762            // bearer) from 403 (policy denial), so by the time the
763            // engine gate fires, the bearer is valid — any failure from
764            // the engine is a policy outcome, not an auth one.
765            OmniError::Policy(message) => Self::forbidden(message),
766            // `Omnigraph::init` against an existing graph URI in strict
767            // mode. Not currently HTTP-reachable (POST /graphs was
768            // pulled), but mapping is wired so the variant has a
769            // single canonical translation when a future runtime
770            // create endpoint lands.
771            err @ OmniError::AlreadyInitialized { .. } => Self::conflict(err.to_string()),
772        }
773    }
774}
775
776fn summarize_merge_conflicts(conflicts: &[api::MergeConflictOutput]) -> String {
777    if conflicts.is_empty() {
778        return "merge conflicts".to_string();
779    }
780
781    let preview: Vec<String> = conflicts
782        .iter()
783        .take(3)
784        .map(|conflict| match conflict.row_id.as_deref() {
785            Some(row_id) => format!(
786                "{}:{} ({})",
787                conflict.table_key,
788                row_id,
789                conflict.kind.as_str()
790            ),
791            None => format!("{} ({})", conflict.table_key, conflict.kind.as_str()),
792        })
793        .collect();
794
795    let suffix = if conflicts.len() > preview.len() {
796        format!("; and {} more", conflicts.len() - preview.len())
797    } else {
798        String::new()
799    };
800
801    format!("merge conflicts: {}{}", preview.join("; "), suffix)
802}
803
804/// Constant `Retry-After` value (seconds) emitted on 429 responses.
805const RETRY_AFTER_SECONDS: &str = "60";
806
807impl IntoResponse for ApiError {
808    fn into_response(self) -> Response {
809        let mut headers = axum::http::HeaderMap::new();
810        if matches!(self.code, ErrorCode::TooManyRequests) {
811            headers.insert(
812                axum::http::header::RETRY_AFTER,
813                axum::http::HeaderValue::from_static(RETRY_AFTER_SECONDS),
814            );
815        }
816        (
817            self.status,
818            headers,
819            Json(ErrorOutput {
820                error: self.message,
821                code: Some(self.code),
822                merge_conflicts: self.merge_conflicts,
823                manifest_conflict: self.manifest_conflict,
824            }),
825        )
826            .into_response()
827    }
828}
829
830pub fn init_tracing() {
831    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
832    let _ = tracing_subscriber::fmt().with_env_filter(filter).try_init();
833}
834
835/// Log each non-blocking advisory from a registry check report.
836fn log_registry_warnings(label: &str, report: &queries::CheckReport) {
837    for warning in &report.warnings {
838        warn!(graph = label, query = %warning.query, "stored query: {}", warning.message);
839    }
840}
841
842fn validate_registry_against_catalog(
843    registry: &QueryRegistry,
844    catalog: &Catalog,
845    label: &str,
846) -> omnigraph::error::Result<()> {
847    let report = check(registry, catalog);
848    if report.has_breakages() {
849        return Err(OmniError::manifest(format_check_breakages(label, &report)));
850    }
851    log_registry_warnings(label, &report);
852    Ok(())
853}
854
855/// Validate a loaded stored-query registry against the live schema and
856/// resolve it to an attachable handle. Refuses boot on any breakage
857/// (same posture as bad policy YAML), logs the non-blocking warnings,
858/// and collapses an empty registry to `None` (nothing attached). This is
859/// the single gate every open path funnels through, so no opener can
860/// attach a registry that has not been schema-checked. `label` names the
861/// graph in messages.
862fn validate_and_attach(
863    queries: QueryRegistry,
864    catalog: &Catalog,
865    label: &str,
866) -> Result<Option<Arc<QueryRegistry>>> {
867    validate_registry_against_catalog(&queries, catalog, label)
868        .map_err(|err| color_eyre::eyre::eyre!(err.to_string()))?;
869    Ok(if queries.is_empty() {
870        None
871    } else {
872        Some(Arc::new(queries))
873    })
874}
875
876pub fn build_app(state: AppState) -> Router {
877    // The per-graph protected routes, identical in single + multi mode.
878    // Two middleware layers wrap them (outer first, inner last):
879    //   1. `require_bearer_auth` — extracts the bearer token and injects
880    //      `ResolvedActor` (or rejects 401).
881    //   2. `resolve_graph_handle` — injects `Arc<GraphHandle>` based on
882    //      the active mode (single: the only handle; multi: lookup by
883    //      `{graph_id}` in the URI path).
884    let per_graph_protected = Router::new()
885        .route("/snapshot", get(server_snapshot))
886        .route("/export", post(server_export))
887        // /read and /change are kept indefinitely for back-compat;
888        // their handlers carry #[deprecated] so the OpenAPI operation is
889        // flagged and their responses include RFC 9745 Deprecation +
890        // RFC 8288 Link headers. Suppress the call-site warning for the
891        // route registration itself.
892        .route("/read", post({
893            #[allow(deprecated)]
894            server_read
895        }))
896        .route("/query", post(server_query))
897        .route("/change", post({
898            #[allow(deprecated)]
899            server_change
900        }))
901        .route("/mutate", post(server_mutate))
902        .route("/queries", get(server_list_queries))
903        .route("/queries/{name}", post(server_invoke_query))
904        .route("/schema", get(server_schema_get))
905        .route("/schema/apply", post(server_schema_apply))
906        .route(
907            "/load",
908            post(server_load).layer(DefaultBodyLimit::max(INGEST_REQUEST_BODY_LIMIT_BYTES)),
909        )
910        // /ingest is the deprecated alias of /load; its handler carries
911        // #[deprecated] (OpenAPI operation flagged) and emits RFC 9745
912        // Deprecation + RFC 8288 Link headers. Suppress the call-site warning.
913        .route(
914            "/ingest",
915            post({
916                #[allow(deprecated)]
917                server_ingest
918            })
919            .layer(DefaultBodyLimit::max(INGEST_REQUEST_BODY_LIMIT_BYTES)),
920        )
921        .route(
922            "/branches",
923            get(server_branch_list).post(server_branch_create),
924        )
925        .route("/branches/{branch}", delete(server_branch_delete))
926        .route("/branches/merge", post(server_branch_merge))
927        .route("/commits", get(server_commit_list))
928        .route("/commits/{commit_id}", get(server_commit_show))
929        .route_layer(middleware::from_fn_with_state(
930            state.clone(),
931            resolve_graph_handle,
932        ))
933        .route_layer(middleware::from_fn_with_state(
934            state.clone(),
935            require_bearer_auth,
936        ));
937
938    // Management endpoints (`GET /graphs`) live alongside the per-graph
939    // router. They go through bearer auth but NOT through
940    // `resolve_graph_handle` — they operate on the registry directly.
941    //
942    // Runtime add/remove (`POST /graphs`, `DELETE /graphs/{id}`) is not
943    // exposed — operators run `cluster apply` and restart.
944    let management = Router::new()
945        .route("/graphs", get(server_graphs_list))
946        .route_layer(middleware::from_fn_with_state(
947            state.clone(),
948            require_bearer_auth,
949        ));
950
951    // RFC-011 cluster-only: per-graph routes always nest under
952    // `/graphs/{graph_id}/...`; there are no flat single-graph routes.
953    let protected: Router<AppState> = Router::new()
954        .nest("/graphs/{graph_id}", per_graph_protected)
955        .merge(management);
956
957    Router::new()
958        .route("/healthz", get(server_health))
959        .route("/openapi.json", get(server_openapi))
960        .merge(protected)
961        .layer(DefaultBodyLimit::max(DEFAULT_REQUEST_BODY_LIMIT_BYTES))
962        .layer(TraceLayer::new_for_http())
963        .with_state(state)
964}
965
966pub async fn serve(config: ServerConfig) -> Result<()> {
967    let token_source = resolve_token_source().await?;
968    info!(source = token_source.name(), "loaded bearer token source");
969    let tokens = token_source.load().await?;
970
971    // For runtime-state classification, "any policy configured" means
972    // either the top-level/single-mode policy file OR a server-level
973    // policy OR any per-graph policy file. Mirrors the
974    // `requires_bearer_auth` semantics on AppState.
975    let has_policy_configured = match &config.mode {
976        ServerConfigMode::Multi {
977            graphs,
978            server_policy,
979            ..
980        } => server_policy.is_some() || graphs.iter().any(|g| g.policy.is_some()),
981    };
982    let runtime_state = classify_server_runtime_state(
983        !tokens.is_empty(),
984        has_policy_configured,
985        config.allow_unauthenticated,
986    )?;
987    match runtime_state {
988        ServerRuntimeState::Open => warn!(
989            "running with --unauthenticated: no bearer tokens, no policy file, all \
990             requests permitted. This is for local dev only — do not expose to a \
991             network you don't fully trust."
992        ),
993        ServerRuntimeState::DefaultDeny => warn!(
994            "bearer tokens are configured but no policy file is set — running in \
995             default-deny mode (only `read` actions are permitted for authenticated \
996             actors). Configure a graph or cluster policy bundle in the cluster config, \
997             run `omnigraph cluster apply`, and restart to enable Cedar rules."
998        ),
999        ServerRuntimeState::PolicyEnabled => {}
1000    }
1001
1002    let bind = config.bind.clone();
1003    let state = match config.mode {
1004        ServerConfigMode::Multi {
1005            graphs,
1006            config_path,
1007            server_policy,
1008        } => {
1009            info!(
1010                bind = %bind,
1011                mode = "cluster",
1012                graph_count = graphs.len(),
1013                config = %config_path.display(),
1014                "serving omnigraph"
1015            );
1016            open_multi_graph_state(graphs, tokens, server_policy.as_ref(), config_path).await?
1017        }
1018    };
1019
1020    let listener = TcpListener::bind(&bind).await?;
1021    axum::serve(listener, build_app(state))
1022        .with_graceful_shutdown(shutdown_signal())
1023        .await?;
1024    Ok(())
1025}
1026
1027/// Load a graph-scoped policy bundle from either source kind.
1028fn load_graph_policy(source: &PolicySource, graph_id: &str) -> Result<PolicyEngine> {
1029    match source {
1030        PolicySource::File(path) => Ok(PolicyEngine::load_graph(path, graph_id)?),
1031        PolicySource::Inline(text) => Ok(PolicyEngine::load_graph_from_source(text, graph_id)?),
1032    }
1033}
1034
1035/// Parallel open of every graph in the startup config, with bounded
1036/// concurrency (`buffer_unordered(4)`). Fail-fast — the first open error
1037/// aborts startup; other in-flight opens are dropped (their `Omnigraph`
1038/// instances close cleanly via Arc drop).
1039///
1040/// The bound 4 is a rule-of-thumb for I/O-bound work. At N ≤ 10 this
1041/// trades startup latency for a small amount of concurrent S3 / Lance
1042/// open pressure.
1043pub async fn open_multi_graph_state(
1044    graphs: Vec<GraphStartupConfig>,
1045    tokens: Vec<(String, String)>,
1046    server_policy_source: Option<&PolicySource>,
1047    config_path: PathBuf,
1048) -> Result<AppState> {
1049    use futures::{StreamExt, TryStreamExt};
1050
1051    if graphs.is_empty() {
1052        bail!("multi-graph mode requires at least one graph in the `graphs:` map");
1053    }
1054
1055    // Server-level policy (loaded once, applies to management endpoints).
1056    // The placeholder graph_id `"server"` is the sentinel the Cedar
1057    // resource-model refactor maps to the singleton
1058    // `Omnigraph::Server::"root"` entity at evaluation time.
1059    let server_policy = match server_policy_source {
1060        Some(PolicySource::File(path)) => Some(PolicyEngine::load_server(path)?),
1061        Some(PolicySource::Inline(source)) => {
1062            Some(PolicyEngine::load_server_from_source(source)?)
1063        }
1064        None => None,
1065    };
1066
1067    // `try_collect` propagates the first error eagerly, dropping every
1068    // in-flight open. `buffer_unordered + collect::<Vec<_>>` would drain
1069    // the stream before checking errors — incorrect for the docstring's
1070    // "fail-fast" claim and wasteful on S3-backed graphs.
1071    let handles: Vec<Arc<GraphHandle>> = futures::stream::iter(graphs.into_iter())
1072        .map(|cfg| async move { open_single_graph(cfg).await })
1073        .buffer_unordered(4)
1074        .try_collect()
1075        .await?;
1076
1077    let workload = workload::WorkloadController::from_env();
1078    let state = AppState::new_multi(handles, tokens, server_policy, workload, Some(config_path))
1079        .map_err(|err| color_eyre::eyre::eyre!("multi-graph registry: {err}"))?;
1080    Ok(state)
1081}
1082
1083/// Open one graph and wrap it in a `GraphHandle`. Used at startup by
1084/// `open_multi_graph_state`.
1085async fn open_single_graph(cfg: GraphStartupConfig) -> Result<Arc<GraphHandle>> {
1086    let graph_id = GraphId::try_from(cfg.graph_id.clone())
1087        .map_err(|err| color_eyre::eyre::eyre!("graph id '{}': {err}", cfg.graph_id))?;
1088    let uri = normalize_root_uri(&cfg.uri)
1089        .wrap_err_with(|| format!("normalize URI for graph '{}'", cfg.graph_id))?;
1090
1091    let db = Omnigraph::open(&uri)
1092        .await
1093        .map_err(|err| color_eyre::eyre::eyre!("open graph '{}' at {}: {err}", graph_id, uri))?;
1094    let db = if let Some(embedding) = cfg.embedding {
1095        db.with_embedding_config(Arc::new(embedding))
1096    } else {
1097        db
1098    };
1099
1100    // Validate this graph's stored queries against the live schema and
1101    // resolve them to an attachable handle (refuse boot on breakage).
1102    // Done before the policy match rebinds `db`; the catalog handle is an
1103    // owned `Arc`, so no borrow of `db` survives into the match.
1104    let queries = validate_and_attach(cfg.queries, &db.catalog(), graph_id.as_str())?;
1105
1106    let (policy_arc, db) = match &cfg.policy {
1107        Some(source) => {
1108            let policy = load_graph_policy(source, graph_id.as_str())?;
1109            let policy_arc: Arc<PolicyEngine> = Arc::new(policy);
1110            let checker = Arc::clone(&policy_arc) as Arc<dyn omnigraph_policy::PolicyChecker>;
1111            (Some(policy_arc), db.with_policy(checker))
1112        }
1113        None => (None, db),
1114    };
1115
1116    Ok(Arc::new(GraphHandle {
1117        key: GraphKey::cluster(graph_id),
1118        uri,
1119        engine: Arc::new(db),
1120        policy: policy_arc,
1121        queries,
1122    }))
1123}
1124
1125async fn shutdown_signal() {
1126    if let Err(err) = tokio::signal::ctrl_c().await {
1127        error!(error = %err, "failed to install ctrl-c handler");
1128        return;
1129    }
1130    info!("shutdown signal received");
1131}