Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(web): Cache-Control + ETag on /api/v1, opt-in CORS for off-origin SPAs

AkitaOnRails6daef1fb20f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 720638e2..b0e08a01 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `Cache-Control: private, max-age=N` headers on all `/api/v1` read endpoints
+ (lists/search/recent/briefing/overview: 30–60s; single-page reads: 300s).
+ Errors stay uncached. A polling SPA no longer hits the DB on every request.
+- **ETag + conditional GET** on the single-page read endpoint
+ (`GET /api/v1/workspaces/{ws}/projects/{p}/pages/{*path}`): the response
+ carries `ETag: "<sha256>"` over the markdown body, and a follow-up request
+ with matching `If-None-Match` returns `304 Not Modified` with no body.
+- **`--cors-allow-origin`** flag (repeatable) and
+ `AI_MEMORY_CORS_ALLOW_ORIGINS=a,b,c` env var. When set, a `CorsLayer` is
+ attached **only to `/api/v1`** (`/mcp`, `/hook`, `/admin`, and `/web` are
+ intentionally untouched) so a separately-hosted SPA can call the API. Each
+ origin must include a scheme; `*` is rejected at startup (CORS spec forbids
+ credentials + wildcard). Empty list = same-origin only, unchanged behaviour.
+
## [0.6.0] - 2026-05-28
### Added
diff --git a/Cargo.toml b/Cargo.toml
index 18aac688..d04d656f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -98,7 +98,7 @@ schemars = "1"
axum = "0.8"
# Direct dep so tests can use `Router::oneshot` via `ServiceExt`.
tower = { version = "0.5", features = ["util"] }
-tower-http = { version = "0.6", features = ["fs"] }
+tower-http = { version = "0.6", features = ["fs", "cors"] }
# Backup / restore archive format.
tar = "0.4"
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 3a8e555b..bff689ab 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -726,6 +726,13 @@ pub struct ServeArgs {
/// streams. No effect on `--transport stdio`.
#[arg(long)]
pub http_stateful: bool,
+ /// Origin allowed to call /api/v1 cross-origin (CORS). Repeat the flag
+ /// for multiple origins, or set AI_MEMORY_CORS_ALLOW_ORIGINS to a
+ /// comma-separated list. Must be a fully-qualified origin
+ /// (e.g. https://app.example.com); `*` is rejected (CORS spec forbids
+ /// credentials + wildcard). Empty = same-origin only.
+ #[arg(long = "cors-allow-origin")]
+ pub cors_allow_origin: Vec<String>,
}
/// Arguments for `write-page`.
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 60604437..f13f2512 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -2,6 +2,7 @@
use std::path::Path;
use std::sync::Arc;
+use std::time::Duration;
use ai_memory_consolidate::{Consolidator, run_lint, run_sweep};
use ai_memory_core::{ActiveProject, ProjectId, Sanitizer, WorkspaceId};
@@ -14,7 +15,7 @@ use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::{DefaultBodyLimit, State};
-use axum::http::{Request, StatusCode, header};
+use axum::http::{Method, Request, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use rmcp::ServiceExt;
@@ -23,6 +24,7 @@ use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
use tokio_util::sync::CancellationToken;
+use tower_http::cors::CorsLayer;
use tower_http::services::{ServeDir, ServeFile};
use tracing::info;
@@ -57,6 +59,11 @@ struct ConsolidatorSetup {
pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
validate_web_ui_args(args.enable_web, args.web_ui_dir.as_deref())?;
+ // Merge config + CLI CORS origins (config first, CLI adds new entries).
+ // Validation runs before binding so a misconfigured origin is caught early.
+ let cors_origins = merge_cors_origins(&config.cors_allow_origins, &args.cors_allow_origin);
+ validate_cors_origins(&cors_origins)?;
+
let store = Store::open(&config.data_dir)
.with_context(|| format!("opening store at {}", config.data_dir.display()))?;
@@ -209,6 +216,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
store.reader.clone(),
wiki.clone(),
args.web_ui_dir.as_deref(),
+ &cors_origins,
);
let router = apply_http_layers(router, auth_state, config.allowed_hosts.clone());
let listener = tokio::net::TcpListener::bind(&bind)
@@ -549,6 +557,50 @@ fn configure_consolidator(
})
}
+/// Validate a list of CORS origins before the server binds.
+///
+/// Rules match the spec: wildcard + credentials is forbidden, each entry
+/// must carry a scheme, and trailing slashes are rejected (they do not
+/// match browser origins which never carry a trailing slash).
+pub fn validate_cors_origins(origins: &[String]) -> Result<()> {
+ for origin in origins {
+ if origin == "*" {
+ anyhow::bail!(
+ "CORS origin `*` is not allowed: the CORS spec forbids credentials \
+ with a wildcard origin. Use explicit origins such as \
+ https://app.example.com"
+ );
+ }
+ if !origin.starts_with("http://") && !origin.starts_with("https://") {
+ anyhow::bail!(
+ "CORS origin `{origin}` is missing a scheme. Each entry must start \
+ with http:// or https://"
+ );
+ }
+ if origin.ends_with('/') {
+ anyhow::bail!(
+ "CORS origin `{origin}` has a trailing slash. Browser origins \
+ never carry a trailing slash — use `{}` instead",
+ origin.trim_end_matches('/')
+ );
+ }
+ }
+ Ok(())
+}
+
+/// Merge config-file origins with CLI flag origins, preserving order and
+/// deduplicating (config entries appear first).
+fn merge_cors_origins(from_config: &[String], from_cli: &[String]) -> Vec<String> {
+ let mut seen = std::collections::HashSet::new();
+ let mut merged = Vec::new();
+ for origin in from_config.iter().chain(from_cli.iter()) {
+ if seen.insert(origin.clone()) {
+ merged.push(origin.clone());
+ }
+ }
+ merged
+}
+
fn validate_web_ui_args(enable_web: bool, web_ui_dir: Option<&Path>) -> Result<()> {
if web_ui_dir.is_some() && !enable_web {
anyhow::bail!("--web-ui-dir requires --enable-web");
@@ -581,6 +633,7 @@ fn mount_web_router(
reader: ReaderPool,
wiki: Wiki,
web_ui_dir: Option<&Path>,
+ cors_origins: &[String],
) -> axum::Router {
if !enable_web {
return router;
@@ -589,11 +642,29 @@ fn mount_web_router(
// axum 0.8, `.layer()` only attaches to routes registered before the
// call; nesting after the layer would silently bypass auth for /web/*.
- // Read-only JSON API for third-party frontends (e.g. the custom UI).
- let router = router.nest(
- "/api/v1",
- ai_memory_web::api_router(reader.clone(), wiki.clone()),
- );
+ // Build the api router and optionally wrap it in a CorsLayer — the layer
+ // is scoped ONLY to /api/v1 so /mcp, /hook, /admin, and /web remain
+ // untouched (CORS_NOT_APPLIED_TO_OTHER_ROUTES invariant).
+ let api = ai_memory_web::api_router(reader.clone(), wiki.clone());
+ let api = if cors_origins.is_empty() {
+ api
+ } else {
+ // Origins were already validated before binding, so parsing here
+ // is expected to succeed; `.expect` surfaces a logic bug if it does not.
+ let parsed: Vec<axum::http::HeaderValue> = cors_origins
+ .iter()
+ .map(|o| o.parse().expect("pre-validated origin must parse"))
+ .collect();
+ let cors = CorsLayer::new()
+ .allow_origin(parsed)
+ .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
+ .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
+ .allow_credentials(true)
+ .max_age(Duration::from_secs(600));
+ info!(origins = ?cors_origins, "CORS layer attached to /api/v1");
+ api.layer(cors)
+ };
+ let router = router.nest("/api/v1", api);
// Custom SPA via --web-ui-dir (SPA fallback to index.html), otherwise
// the built-in server-side wiki browser.
@@ -750,7 +821,14 @@ mod tests {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
- let router = mount_web_router(axum::Router::new(), true, store.reader.clone(), wiki, None);
+ let router = mount_web_router(
+ axum::Router::new(),
+ true,
+ store.reader.clone(),
+ wiki,
+ None,
+ &[],
+ );
let router = apply_http_layers(
router,
Arc::new(AuthState::new(Some("secret".to_string()))),
@@ -823,4 +901,195 @@ mod tests {
ai_memory_llm::ProviderHealthStatus::Unknown
);
}
+
+ // ── Part B: CORS validation tests ──────────────────────────────────────
+
+ #[test]
+ fn validate_cors_origins_rejects_wildcard() {
+ let err = validate_cors_origins(&["*".to_string()]).unwrap_err();
+ assert!(
+ err.to_string().contains("wildcard"),
+ "error must mention wildcard: {err}"
+ );
+ }
+
+ #[test]
+ fn validate_cors_origins_rejects_missing_scheme() {
+ let err = validate_cors_origins(&["app.example.com".to_string()]).unwrap_err();
+ assert!(
+ err.to_string().contains("missing a scheme"),
+ "error must mention missing scheme: {err}"
+ );
+ }
+
+ #[test]
+ fn validate_cors_origins_rejects_trailing_slash() {
+ let err = validate_cors_origins(&["https://app.example.com/".to_string()]).unwrap_err();
+ assert!(
+ err.to_string().contains("trailing slash"),
+ "error must mention trailing slash: {err}"
+ );
+ }
+
+ #[test]
+ fn validate_cors_origins_accepts_well_formed() {
+ validate_cors_origins(&[
+ "https://app.example.com".to_string(),
+ "http://localhost:5173".to_string(),
+ ])
+ .unwrap();
+ }
+
+ #[test]
+ fn validate_cors_origins_accepts_empty_list() {
+ validate_cors_origins(&[]).unwrap();
+ }
+
+ #[test]
+ fn merge_cors_origins_deduplicates_preserving_order() {
+ let merged = merge_cors_origins(
+ &[
+ "https://a.example.com".to_string(),
+ "https://b.example.com".to_string(),
+ ],
+ &[
+ "https://b.example.com".to_string(),
+ "https://c.example.com".to_string(),
+ ],
+ );
+ assert_eq!(
+ merged,
+ vec![
+ "https://a.example.com",
+ "https://b.example.com",
+ "https://c.example.com"
+ ]
+ );
+ }
+
+ #[tokio::test]
+ async fn cors_layer_on_api_v1_allows_configured_origin() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+
+ let cors_origins = ["https://app.example.com".to_string()];
+ let router = mount_web_router(
+ axum::Router::new(),
+ true,
+ store.reader.clone(),
+ wiki,
+ None,
+ &cors_origins,
+ );
+ // No auth layer so we can reach /api/v1 directly.
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/api/v1/workspaces")
+ .header("Origin", "https://app.example.com")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ let acao = resp
+ .headers()
+ .get("access-control-allow-origin")
+ .expect("ACAO header must be present for allowed origin")
+ .to_str()
+ .unwrap();
+ assert_eq!(acao, "https://app.example.com");
+ let acac = resp
+ .headers()
+ .get("access-control-allow-credentials")
+ .expect("ACAC header must be present")
+ .to_str()
+ .unwrap();
+ assert_eq!(acac, "true");
+ }
+
+ #[tokio::test]
+ async fn cors_layer_on_api_v1_denies_unlisted_origin() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+
+ let cors_origins = ["https://app.example.com".to_string()];
+ let router = mount_web_router(
+ axum::Router::new(),
+ true,
+ store.reader.clone(),
+ wiki,
+ None,
+ &cors_origins,
+ );
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/api/v1/workspaces")
+ .header("Origin", "https://evil.example.com")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ // The request is still served (CORS does not block on the server side),
+ // but the ACAO header must be absent so the browser enforces the policy.
+ assert!(
+ resp.headers().get("access-control-allow-origin").is_none(),
+ "unlisted origin must not receive ACAO header"
+ );
+ }
+
+ #[tokio::test]
+ async fn cors_not_applied_to_other_routes() {
+ // /mcp and /admin routes must not carry CORS headers even when
+ // a CORS origin list is configured (CORS_NOT_APPLIED_TO_OTHER_ROUTES
+ // invariant). We verify by checking that a request to a non-/api/v1
+ // path that 404s (no actual handler mounted here) still lacks ACAO.
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+
+ let cors_origins = ["https://app.example.com".to_string()];
+ let router = mount_web_router(
+ axum::Router::new(),
+ true,
+ store.reader.clone(),
+ wiki,
+ None,
+ &cors_origins,
+ );
+ // /web is a non-api route; sending an Origin header must not trigger CORS.
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/web")
+ .header("Origin", "https://app.example.com")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ resp.headers().get("access-control-allow-origin").is_none(),
+ "/web must not carry CORS headers: {:?}",
+ resp.headers()
+ );
+ }
}
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 539129bb..f357da08 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -104,6 +104,17 @@ pub struct Config {
/// can't be sequences without ugly escaping.
#[serde(deserialize_with = "deserialize_string_or_vec")]
pub allowed_hosts: Vec<String>,
+ /// Origins allowed to make cross-origin requests to /api/v1. Empty
+ /// (default) means same-origin only — host your SPA via --web-ui-dir
+ /// instead of using CORS if you can. When non-empty, a CorsLayer is
+ /// attached ONLY to /api/v1; /mcp, /hook, /admin, and /web are NOT
+ /// CORS-enabled (those aren't browser-accessible by design).
+ ///
+ /// Settable via AI_MEMORY_CORS_ALLOW_ORIGINS=a,b,c or one or more
+ /// --cors-allow-origin flags. Each entry must include a scheme;
+ /// `*` is rejected.
+ #[serde(deserialize_with = "deserialize_string_or_vec", default)]
+ pub cors_allow_origins: Vec<String>,
/// Process-only env values that should never be written to config files.
#[serde(skip)]
pub runtime_env: RuntimeEnv,
@@ -232,6 +243,7 @@ impl Default for Config {
sanitize: ai_memory_core::SanitizeConfig::default(),
auth: AuthSettings::default(),
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
+ cors_allow_origins: Vec::new(),
runtime_env: RuntimeEnv::default(),
}
}
diff --git a/crates/ai-memory-web/Cargo.toml b/crates/ai-memory-web/Cargo.toml
index 0b18da53..1c315b95 100644
--- a/crates/ai-memory-web/Cargo.toml
+++ b/crates/ai-memory-web/Cargo.toml
@@ -20,6 +20,7 @@ tokio.workspace = true
tracing.workspace = true
axum.workspace = true
jiff.workspace = true
+sha2.workspace = true
# Templating + markdown.
askama = "0.12"
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index 4a82b2e2..fc0f4624 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -6,13 +6,21 @@ use std::sync::Arc;
use ai_memory_core::{PageId, PagePath, ProjectId, WorkspaceId};
use ai_memory_store::{BriefingSnapshot, HealthPage, PageHit, RelatedPage};
use axum::extract::{Path, Query, RawQuery, State};
-use axum::http::StatusCode;
+use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
use crate::state::WebState;
+/// Cache TTL for page-list, workspace, search, and summary endpoints.
+const LIST_CACHE_MAX_AGE: u32 = 30;
+/// Cache TTL for project page-list endpoint.
+const PAGES_LIST_CACHE_MAX_AGE: u32 = 60;
+/// Cache TTL (and ETag max-age) for single-page reads.
+const PAGE_CACHE_MAX_AGE: u32 = 300;
+
/// Build the `/api/v1` router from a shared [`WebState`].
pub(crate) fn build(state: Arc<WebState>) -> Router {
Router::new()
@@ -49,13 +57,38 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {
.with_state(state)
}
+/// Attach `Cache-Control: private, max-age=N` to a successful response.
+///
+/// Applied only to 2xx bodies — error paths return their responses
+/// directly without calling this, so error responses stay uncached.
+fn with_cache(resp: Response, max_age: u32) -> Response {
+ let mut resp = resp;
+ if let Ok(val) = HeaderValue::from_str(&format!("private, max-age={max_age}")) {
+ resp.headers_mut().insert(header::CACHE_CONTROL, val);
+ }
+ resp
+}
+
+/// Lowercase hex encoding of a SHA-256 digest.
+fn sha256_hex(data: &[u8]) -> String {
+ let digest = Sha256::digest(data);
+ digest.iter().fold(String::with_capacity(64), |mut s, b| {
+ use std::fmt::Write as _;
+ let _ = write!(s, "{b:02x}");
+ s
+ })
+}
+
async fn workspaces_handler(State(state): State<Arc<WebState>>) -> Result<Response, Response> {
let workspaces = state
.reader
.list_workspaces_with_stats()
.await
.map_err(internal_error)?;
- Ok(Json(workspaces).into_response())
+ Ok(with_cache(
+ Json(workspaces).into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
}
async fn projects_handler(
@@ -76,7 +109,10 @@ async fn projects_handler(
state.reader.list_projects_with_stats().await
}
.map_err(internal_error)?;
- Ok(Json(projects).into_response())
+ Ok(with_cache(
+ Json(projects).into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
}
async fn pages_handler(
@@ -89,11 +125,15 @@ async fn pages_handler(
.list_pages(&workspace, &project)
.await
.map_err(internal_error)?;
- Ok(Json(pages).into_response())
+ Ok(with_cache(
+ Json(pages).into_response(),
+ PAGES_LIST_CACHE_MAX_AGE,
+ ))
}
async fn page_handler(
State(state): State<Arc<WebState>>,
+ headers: axum::http::HeaderMap,
Path((workspace, project, path)): Path<(String, String, String)>,
) -> Result<Response, Response> {
let meta = state
@@ -110,29 +150,57 @@ async fn page_handler(
.read_page(meta.workspace_id, meta.project_id, &page_path)
.map_err(|_| not_found("page file not found"))?;
+ // ETag is computed over the markdown body bytes so a client can skip
+ // the JSON serialisation round-trip when content hasn't changed.
+ let etag_value = format!("\"{}\"", sha256_hex(markdown.body.as_bytes()));
+ let etag_header = HeaderValue::from_str(&etag_value).expect("sha256 hex is always valid ASCII");
+
+ // If-None-Match: if the client sends back the exact ETag we issued,
+ // return 304 with no body (no re-serialisation needed).
+ if let Some(inm) = headers
+ .get(header::IF_NONE_MATCH)
+ .and_then(|v| v.to_str().ok())
+ && inm == etag_value
+ {
+ let mut resp = axum::http::Response::builder()
+ .status(StatusCode::NOT_MODIFIED)
+ .body(axum::body::Body::empty())
+ .expect("static builder cannot fail");
+ resp.headers_mut().insert(header::ETAG, etag_header.clone());
+ if let Ok(cc) = HeaderValue::from_str(&format!("private, max-age={PAGE_CACHE_MAX_AGE}")) {
+ resp.headers_mut().insert(header::CACHE_CONTROL, cc);
+ }
+ return Ok(resp);
+ }
+
let links = state
.reader
.page_links(meta.workspace_id, meta.project_id, meta.path.clone())
.await
.map_err(internal_error)?;
- Ok(Json(ApiPage {
- backlinks: links.backlinks,
- body_markdown: markdown.body,
- created_at: meta.created_at,
- frontmatter: markdown.frontmatter,
- kind: meta.kind,
- links: links.links,
- path: meta.path,
- pinned: meta.pinned,
- project: meta.project_name,
- supersedes: meta.supersedes,
- tier: meta.tier,
- title: meta.title,
- updated_at: meta.updated_at,
- workspace: meta.workspace_name,
- })
- .into_response())
+ let mut resp = with_cache(
+ Json(ApiPage {
+ backlinks: links.backlinks,
+ body_markdown: markdown.body,
+ created_at: meta.created_at,
+ frontmatter: markdown.frontmatter,
+ kind: meta.kind,
+ links: links.links,
+ path: meta.path,
+ pinned: meta.pinned,
+ project: meta.project_name,
+ supersedes: meta.supersedes,
+ tier: meta.tier,
+ title: meta.title,
+ updated_at: meta.updated_at,
+ workspace: meta.workspace_name,
+ })
+ .into_response(),
+ PAGE_CACHE_MAX_AGE,
+ );
+ resp.headers_mut().insert(header::ETAG, etag_header);
+ Ok(resp)
}
async fn search_handler(
@@ -192,7 +260,10 @@ async fn search_with_request(
}
.map_err(internal_error)?;
- Ok(Json(enrich_hits(state, hits).await?).into_response())
+ Ok(with_cache(
+ Json(enrich_hits(state, hits).await?).into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
}
async fn scoped_search_mode(
@@ -298,7 +369,7 @@ async fn recent_handler(
.map_err(internal_error)?;
pages.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
pages.truncate(query.limit.clamp(1, 100));
- Ok(Json(pages).into_response())
+ Ok(with_cache(Json(pages).into_response(), LIST_CACHE_MAX_AGE))
}
async fn briefing_handler(
@@ -312,7 +383,10 @@ async fn briefing_handler(
.briefing_for_project(workspace_id, project_id, query.limit.clamp(1, 100))
.await
.map_err(internal_error)?;
- Ok(Json(briefing).into_response())
+ Ok(with_cache(
+ Json(briefing).into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
}
async fn overview_handler(
@@ -379,12 +453,15 @@ async fn overview_handler(
orphan_pages: detail.orphans,
};
- Ok(Json(ApiOverview {
- handoff,
- briefing,
- health,
- })
- .into_response())
+ Ok(with_cache(
+ Json(ApiOverview {
+ handoff,
+ briefing,
+ health,
+ })
+ .into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
}
async fn project_overview_handler(
@@ -436,12 +513,15 @@ async fn project_overview_handler(
orphan_pages: detail.orphans,
};
- Ok(Json(ApiOverview {
- handoff,
- briefing,
- health,
- })
- .into_response())
+ Ok(with_cache(
+ Json(ApiOverview {
+ handoff,
+ briefing,
+ health,
+ })
+ .into_response(),
+ LIST_CACHE_MAX_AGE,
+ ))
}
async fn lookup_project(
diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rs
index ca7f0d2e..cd02d477 100644
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@ -8,7 +8,7 @@ use ai_memory_store::Store;
use ai_memory_web::{api_router, router};
use ai_memory_wiki::{Wiki, WritePageRequest};
use axum::body::Body;
-use axum::http::{Method, Request, StatusCode};
+use axum::http::{Method, Request, StatusCode, header};
use serde_json::Value;
use tempfile::TempDir;
use tower::ServiceExt;
@@ -1455,3 +1455,232 @@ async fn api_search_rejects_invalid_percent_encoding() {
let json: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(json["error"], "invalid percent-encoding in query");
}
+
+// ── Part A: Cache-Control + ETag tests ─────────────────────────────────────
+
+#[tokio::test]
+async fn api_responses_set_cache_control_private() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ let req = Request::builder()
+ .uri("/workspaces")
+ .body(Body::empty())
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let cc = resp
+ .headers()
+ .get(header::CACHE_CONTROL)
+ .expect("Cache-Control header must be present on /workspaces")
+ .to_str()
+ .unwrap();
+ assert!(
+ cc.contains("private"),
+ "Cache-Control must be private: {cc}"
+ );
+ assert!(
+ cc.contains("max-age=30"),
+ "Cache-Control must be max-age=30 for /workspaces: {cc}"
+ );
+}
+
+#[tokio::test]
+async fn api_page_handler_emits_etag_and_supports_if_none_match() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("etag-test.md").unwrap(),
+ frontmatter: serde_json::json!({"kind": "fact"}),
+ body: "# ETag test\n\nSome content for hashing.".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ })
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+
+ // First request: must return 200 with ETag and Cache-Control.
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/etag-test.md")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
+ let etag = resp
+ .headers()
+ .get(header::ETAG)
+ .expect("ETag must be present on single-page read")
+ .to_str()
+ .unwrap()
+ .to_owned();
+ let cc = resp
+ .headers()
+ .get(header::CACHE_CONTROL)
+ .expect("Cache-Control must be present on single-page read")
+ .to_str()
+ .unwrap();
+ assert!(cc.contains("max-age=300"), "page max-age must be 300: {cc}");
+
+ // Second request with the returned ETag: must return 304 with empty body.
+ let resp304 = app
+ .oneshot(
+ Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/etag-test.md")
+ .header(header::IF_NONE_MATCH, &etag)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ resp304.status(),
+ StatusCode::NOT_MODIFIED,
+ "matching ETag must yield 304"
+ );
+ let body_bytes = axum::body::to_bytes(resp304.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ assert!(body_bytes.is_empty(), "304 body must be empty");
+}
+
+#[tokio::test]
+async fn api_page_handler_etag_differs_per_page() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("page-a.md").unwrap(),
+ frontmatter: serde_json::json!({"kind": "fact"}),
+ body: "Body for page A — unique content alpha.".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ })
+ .await
+ .unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("page-b.md").unwrap(),
+ frontmatter: serde_json::json!({"kind": "fact"}),
+ body: "Body for page B — unique content beta.".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: None,
+ })
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+
+ let etag_a = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/page-a.md")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ .headers()
+ .get(header::ETAG)
+ .unwrap()
+ .to_str()
+ .unwrap()
+ .to_owned();
+
+ let etag_b = app
+ .oneshot(
+ Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/page-b.md")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ .headers()
+ .get(header::ETAG)
+ .unwrap()
+ .to_str()
+ .unwrap()
+ .to_owned();
+
+ assert_ne!(
+ etag_a, etag_b,
+ "pages with different bodies must produce different ETags"
+ );
+}
+
+#[tokio::test]
+async fn api_error_responses_do_not_set_cache_control() {
+ let (_tmp, store, wiki) = setup().await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+
+ let app = api_router(store.reader.clone(), wiki.clone());
+ // Request a page that does not exist — handler returns 404.
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/missing.md")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+ assert!(
+ resp.headers().get(header::CACHE_CONTROL).is_none(),
+ "error responses must not carry a Cache-Control header"
+ );
+}