use std::path::{Component, Path, PathBuf};
const MAX_PROJECT_HEADER: usize = 4096;
const PROJECT_READ_ROUTES: &[&str] = &[
"/api/health",
"/api/stats",
"/api/session",
"/api/agents",
"/api/knowledge",
"/api/knowledge-relations",
"/api/context-ledger",
"/api/context-control",
"/api/context-overlay-history",
"/api/context-plan",
"/api/context-handles",
"/api/context-risk",
"/api/context-client",
"/api/context-introspect",
"/api/events",
"/api/snapshots",
"/api/snapshot",
"/api/settings",
"/api/doctor",
"/api/roi",
"/api/memory",
"/api/gotchas",
"/api/search",
"/api/provenance",
"/api/value",
"/api/owasp",
"/api/gain",
"/api/solution",
"/api/verification",
"/api/spend",
"/api/signals",
"/api/learning",
"/api/context-triage",
"/api/graph/stats",
"/api/graph-files",
"/api/graph",
"/api/heatmap",
"/api/call-graph",
"/api/call-graph/status",
"/api/symbols",
"/api/workspaces",
"/api/routes",
"/api/version",
"/api/buddy",
"/api/kernel",
"/api/workspace-health",
"/api/scope",
"/api/tree",
"/api/architecture",
"/api/compression-demo",
"/api/tools-health",
"/api/search-index",
"/api/intent",
"/api/hotspots",
"/api/communities",
"/api/smells",
"/api/smells/summary",
"/api/gateway/receipts",
"/api/gateway/control",
"/api/gateway/deliver",
"/api/gateway/connect",
];
const GLOBAL_READ_ROUTES: &[&str] = &[
"/api/telemetry",
"/api/context-summary",
"/api/context-history",
"/api/context-capabilities",
"/api/context-field",
"/api/context-pressure",
"/api/context-bounce",
"/api/context-radar",
"/api/context-model",
"/api/context-events",
"/api/context-dynamic-tools",
"/api/mcp",
"/api/profile",
"/api/theme-tokens",
"/api/pulse",
"/api/pipeline-stats",
"/api/gateway/detectors",
"/metrics",
"/api/episodes",
"/api/procedures",
];
const PROJECT_WRITE_ROUTES: &[&str] = &[
"/api/dashboard-analysis/inputs",
"/api/dashboard-analysis/apply",
"/api/session/note",
"/api/knowledge/edit",
"/api/knowledge-relations/edit",
"/api/context-overlay",
"/api/context-policy",
"/api/graph/enrich",
];
const GLOBAL_WRITE_ROUTES: &[&str] = &["/api/settings", "/api/feedback", "/api/episodes/annotate"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProjectScope {
Project,
Global,
Refused,
}
const ROUTE_ALIASES: &[(&str, &str)] = &[("/api/context-overlays", "/api/context-overlay-history")];
pub(crate) fn canonical_route(path: &str) -> &str {
ROUTE_ALIASES
.iter()
.find_map(|(alias, route)| (*alias == path).then_some(*route))
.unwrap_or(path)
}
pub(crate) fn project_scope(route: &str, method: &str) -> ProjectScope {
let read = method.eq_ignore_ascii_case("GET") || method.eq_ignore_ascii_case("HEAD");
let write = method.eq_ignore_ascii_case("POST");
if (read && PROJECT_READ_ROUTES.contains(&route))
|| (write && PROJECT_WRITE_ROUTES.contains(&route))
{
ProjectScope::Project
} else if (read && GLOBAL_READ_ROUTES.contains(&route))
|| (write && GLOBAL_WRITE_ROUTES.contains(&route))
|| !route.starts_with("/api/")
{
ProjectScope::Global
} else {
ProjectScope::Refused
}
}
pub(crate) fn project_pool() -> Vec<String> {
let mut pool: Vec<String> = Vec::new();
if let (Some(own), _) = super::routes::helpers::dashboard_project_binding() {
pool.push(own);
}
for summary in lean_ctx::core::session::SessionState::list_sessions() {
if let Some(root) = summary.project_root.filter(|root| !root.is_empty())
&& !pool.contains(&root)
{
pool.push(root);
}
}
pool
}
fn canonical_project_dir(path: &Path) -> Option<PathBuf> {
let canonical = lean_ctx::core::pathutil::safe_canonicalize(path).ok()?;
(canonical.is_dir() && !lean_ctx::core::pathutil::is_broad_or_unsafe_root(&canonical))
.then_some(canonical)
}
pub(crate) fn authorise(requested: &str, pool: &[String]) -> Option<String> {
let requested = requested.trim();
if requested.is_empty() || requested.len() > MAX_PROJECT_HEADER || requested.contains('\0') {
return None;
}
let path = Path::new(requested);
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return None;
}
let canonical = canonical_project_dir(path)?;
pool.iter()
.find(|root| {
let root_path = Path::new(root.as_str());
root_path.is_absolute()
&& canonical_project_dir(root_path).is_some_and(|known| known == canonical)
})
.cloned()
}
pub(crate) fn in_request_project<T>(project: Option<&str>, operation: impl FnOnce() -> T) -> T {
match project {
Some(root) => lean_ctx::core::policy::runtime::in_project(root, operation),
None => operation(),
}
}
pub(crate) fn partition_of(project: Option<&str>) -> String {
let root = project.map_or_else(
|| super::routes::helpers::dashboard_project_binding().0,
|root| Some(root.to_string()),
);
root.as_deref().filter(|root| !root.is_empty()).map_or_else(
|| "unbound".to_string(),
lean_ctx::core::project_hash::hash_project_root,
)
}
#[cfg(test)]
mod tests {
use super::*;
fn project(dir: &Path, name: &str) -> String {
let root = dir.join(name);
std::fs::create_dir_all(root.join(".git")).unwrap();
root.to_string_lossy().into_owned()
}
#[test]
fn only_a_pool_project_is_accepted_and_bound_to_the_pools_spelling() {
let _home = lean_ctx::core::data_dir::test_env_lock();
let dir = tempfile::tempdir().unwrap();
let alpha = project(dir.path(), "alpha");
let beta = project(dir.path(), "beta");
let foreign = project(dir.path(), "foreign");
let pool = vec![alpha.clone(), beta.clone()];
assert_eq!(authorise(&alpha, &pool), Some(alpha.clone()));
assert_eq!(authorise(&format!("{beta}/"), &pool), Some(beta.clone()));
let detour = format!("{alpha}/.git/..");
assert_eq!(authorise(&detour, &pool), None, "traversal is refused");
#[cfg(unix)]
{
let link = dir.path().join("link-to-alpha");
std::os::unix::fs::symlink(&alpha, &link).unwrap();
assert_eq!(
authorise(&link.to_string_lossy(), &pool),
Some(alpha.clone())
);
}
for refused in [
foreign.as_str(),
"relative/path",
"",
"/definitely/not/here",
"/",
] {
assert_eq!(authorise(refused, &pool), None, "{refused:?}");
}
let with_nul = format!("{alpha}\0");
assert_eq!(authorise(&with_nul, &pool), None);
if let Some(home) = dirs::home_dir() {
let home = home.to_string_lossy().into_owned();
assert_eq!(authorise(&home, std::slice::from_ref(&home)), None);
}
}
#[test]
fn the_overlay_alias_and_only_reads_are_project_scoped() {
assert_eq!(
canonical_route("/api/context-overlays"),
"/api/context-overlay-history"
);
assert_eq!(
project_scope(canonical_route("/api/context-overlays"), "GET"),
ProjectScope::Project
);
assert_eq!(project_scope("/api/roi", "GET"), ProjectScope::Project);
assert_eq!(project_scope("/api/roi", "POST"), ProjectScope::Refused);
assert_eq!(
project_scope("/api/agents/work-graph", "GET"),
ProjectScope::Refused
);
}
#[test]
fn the_analysis_bridge_posts_are_project_scoped() {
for route in [
"/api/dashboard-analysis/inputs",
"/api/dashboard-analysis/apply",
] {
assert_eq!(project_scope(route, "POST"), ProjectScope::Project);
}
assert_eq!(
project_scope("/api/dashboard-analysis/inputs", "GET"),
ProjectScope::Refused
);
assert_eq!(project_scope("/api/settings", "POST"), ProjectScope::Global);
}
#[test]
fn every_read_with_a_named_project_is_bound_global_or_refused() {
for route in [
"/api/tree",
"/api/architecture",
"/api/compression-demo",
"/api/tools-health",
"/api/intent",
"/api/gateway/receipts",
] {
assert_eq!(
project_scope(route, "GET"),
ProjectScope::Project,
"{route}"
);
}
for route in [
"/api/telemetry",
"/api/context-summary",
"/api/context-history",
"/api/gateway/detectors",
"/metrics",
"/",
] {
assert_eq!(project_scope(route, "GET"), ProjectScope::Global, "{route}");
}
for (route, method) in [
("/api/live", "GET"),
("/api/roi-report", "GET"),
("/api/doctor/fix", "POST"),
("/api/agents/sessions", "POST"),
("/api/tree", "DELETE"),
] {
assert_eq!(
project_scope(route, method),
ProjectScope::Refused,
"{method} {route}"
);
}
}
#[test]
fn project_writes_follow_the_named_project() {
for route in [
"/api/session/note",
"/api/knowledge/edit",
"/api/knowledge-relations/edit",
"/api/context-overlay",
] {
assert_eq!(
project_scope(route, "POST"),
ProjectScope::Project,
"{route}"
);
}
}
#[test]
fn the_route_classes_do_not_overlap() {
for route in PROJECT_READ_ROUTES {
assert!(!GLOBAL_READ_ROUTES.contains(route), "{route}");
}
for route in PROJECT_WRITE_ROUTES {
assert!(!GLOBAL_WRITE_ROUTES.contains(route), "{route}");
}
}
}