1use indexmap::IndexMap;
9use lex_ast::canonicalize_program;
10use lex_bytecode::{compile_program, vm::Vm, Value};
11use lex_runtime::{check_program as check_policy, DefaultHandler, Policy};
12use lex_store::Store;
13use lex_syntax::{load_program, load_program_from_str, Manifest};
14use lex_vcs::{MergeSession, MergeSessionId};
15use serde::{Deserialize, Serialize};
16use std::collections::{BTreeMap, BTreeSet, HashMap};
17use std::path::PathBuf;
18use std::sync::{Arc, Mutex};
19use std::time::{SystemTime, UNIX_EPOCH};
20use tiny_http::{Header, Method, Request, Response};
21
22pub struct State {
23 pub store: Mutex<Store>,
24 pub root: PathBuf,
29 pub sessions: Mutex<HashMap<MergeSessionId, ApiMergeSession>>,
36 pub policy_ceiling: Option<Policy>,
57}
58
59pub struct ApiMergeSession {
66 pub inner: MergeSession,
67 pub src_branch: String,
68 pub dst_branch: String,
69}
70
71impl State {
72 pub fn open(root: PathBuf) -> anyhow::Result<Self> {
73 Self::open_with_ceiling(root, None)
74 }
75
76 pub fn open_with_ceiling(
81 root: PathBuf,
82 policy_ceiling: Option<Policy>,
83 ) -> anyhow::Result<Self> {
84 Ok(Self {
85 store: Mutex::new(Store::open(&root)?),
86 root,
87 sessions: Mutex::new(HashMap::new()),
88 policy_ceiling,
89 })
90 }
91
92 pub fn new_with_tenant(tenant_id: &str, store_root: PathBuf) -> anyhow::Result<Self> {
102 validate_tenant_id(tenant_id)?;
103 Self::open(store_root.join(tenant_id))
104 }
105
106 pub fn new_with_tenant_and_ceiling(
111 tenant_id: &str,
112 store_root: PathBuf,
113 policy_ceiling: Option<Policy>,
114 ) -> anyhow::Result<Self> {
115 validate_tenant_id(tenant_id)?;
116 Self::open_with_ceiling(store_root.join(tenant_id), policy_ceiling)
117 }
118}
119
120fn clamp_policy(requested: Policy, ceiling: &Policy) -> Policy {
136 let allow_effects: BTreeSet<String> = requested
137 .allow_effects
138 .intersection(&ceiling.allow_effects)
139 .cloned()
140 .collect();
141 let budget = match (requested.budget, ceiling.budget) {
142 (Some(r), Some(c)) => Some(r.min(c)),
143 (None, Some(c)) => Some(c),
144 (Some(r), None) => Some(r),
145 (None, None) => None,
146 };
147 Policy {
148 allow_effects,
149 allow_fs_read: ceiling.allow_fs_read.clone(),
150 allow_fs_write: ceiling.allow_fs_write.clone(),
151 allow_net_host: ceiling.allow_net_host.clone(),
152 allow_proc: ceiling.allow_proc.clone(),
153 allow_approval: ceiling.allow_approval.clone(),
154 budget,
155 }
156}
157
158fn validate_tenant_id(tenant_id: &str) -> anyhow::Result<()> {
159 if tenant_id.is_empty() {
160 anyhow::bail!("tenant_id must not be empty");
161 }
162 if tenant_id.len() > 64 {
163 anyhow::bail!("tenant_id must be at most 64 bytes");
164 }
165 if !tenant_id
166 .bytes()
167 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
168 {
169 anyhow::bail!(
170 "tenant_id {tenant_id:?} contains characters outside [A-Za-z0-9_-]"
171 );
172 }
173 Ok(())
174}
175
176#[derive(Debug, Serialize, Deserialize)]
177struct ErrorEnvelope {
178 error: String,
179 #[serde(skip_serializing_if = "Option::is_none")]
180 detail: Option<serde_json::Value>,
181}
182
183fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {
184 let bytes = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
185 Response::from_data(bytes)
186 .with_status_code(status)
187 .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap())
188}
189
190fn error_response(status: u16, msg: impl Into<String>) -> Response<std::io::Cursor<Vec<u8>>> {
191 json_response(status, &serde_json::to_value(ErrorEnvelope {
192 error: msg.into(), detail: None,
193 }).unwrap())
194}
195
196fn error_with_detail(status: u16, msg: impl Into<String>, detail: serde_json::Value)
197 -> Response<std::io::Cursor<Vec<u8>>>
198{
199 json_response(status, &serde_json::to_value(ErrorEnvelope {
200 error: msg.into(), detail: Some(detail),
201 }).unwrap())
202}
203
204fn write_error_response(prefix: &str, err: lex_store::StoreError)
210 -> Response<std::io::Cursor<Vec<u8>>>
211{
212 if let lex_store::StoreError::Contention { branch, attempts } = &err {
213 let body = serde_json::to_vec(&ErrorEnvelope {
214 error: format!("{prefix}: branch '{branch}' is contended (attempts={attempts})"),
215 detail: Some(serde_json::json!({
216 "kind": "contention",
217 "branch": branch,
218 "attempts": attempts,
219 })),
220 }).unwrap_or_else(|_| b"{}".to_vec());
221 return Response::from_data(body)
222 .with_status_code(503)
223 .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap())
224 .with_header(Header::from_bytes(&b"Retry-After"[..], &b"1"[..]).unwrap());
225 }
226 if let lex_store::StoreError::BudgetExceeded { session_id, cap, spent_after } = &err {
234 let body = serde_json::to_vec(&ErrorEnvelope {
235 error: format!(
236 "{prefix}: session `{session_id}` budget exceeded \
237 (spent_after={spent_after}, cap={cap})"
238 ),
239 detail: Some(serde_json::json!({
240 "kind": "budget_exceeded",
241 "session_id": session_id,
242 "cap": cap,
243 "spent_after": spent_after,
244 })),
245 }).unwrap_or_else(|_| b"{}".to_vec());
246 return Response::from_data(body)
247 .with_status_code(503)
248 .with_header(Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap())
249 .with_header(Header::from_bytes(&b"Retry-After"[..], &b"0"[..]).unwrap());
250 }
251 error_response(500, format!("{prefix}: {err}"))
252}
253
254pub fn handle(state: Arc<State>, mut req: Request) -> std::io::Result<()> {
255 let method = req.method().clone();
256 let url = req.url().to_string();
257 let path = url.split('?').next().unwrap_or("").to_string();
258 let query = url.split_once('?').map(|(_, q)| q.to_string()).unwrap_or_default();
259
260 let x_lex_user = req.headers().iter()
265 .find(|h| h.field.equiv("x-lex-user"))
266 .map(|h| h.value.as_str().to_string());
267
268 if matches!(method, Method::Post) && path == "/v1/pkg/publish" {
270 let mut body_bytes: Vec<u8> = Vec::new();
271 let _ = req.as_reader().read_to_end(&mut body_bytes);
272 let resp = pkg_publish_handler(&state, &body_bytes);
273 return req.respond(resp);
274 }
275
276 let mut body = String::new();
277 let _ = req.as_reader().read_to_string(&mut body);
278
279 let resp = route(&state, &method, &path, &query, &body, x_lex_user.as_deref());
280 req.respond(resp)
281}
282
283pub fn handle_with_auth<F>(state: Arc<State>, req: Request, auth: F) -> std::io::Result<()>
287where
288 F: FnOnce(&str, &[Header]) -> bool,
289{
290 let path = req.url().split('?').next().unwrap_or("").to_string();
291 if !auth(&path, req.headers()) {
292 return req.respond(
293 Response::from_data(br#"{"error":"unauthorized"}"#.to_vec())
294 .with_status_code(401)
295 .with_header(
296 Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]).unwrap(),
297 ),
298 );
299 }
300 handle(state, req)
301}
302
303fn route(
304 state: &State,
305 method: &Method,
306 path: &str,
307 query: &str,
308 body: &str,
309 x_lex_user: Option<&str>,
310) -> Response<std::io::Cursor<Vec<u8>>> {
311 match (method, path) {
312 (Method::Get, "/") => crate::web::activity_handler(state),
314 (Method::Get, "/web/branches") => crate::web::branches_handler(state),
315 (Method::Get, "/web/trust") => crate::web::trust_handler(state),
316 (Method::Get, "/web/attention") => crate::web::attention_handler(state),
317 (Method::Get, p) if p.starts_with("/web/branch/") => {
318 let name = &p["/web/branch/".len()..];
319 crate::web::branch_handler(state, name)
320 }
321 (Method::Get, p) if p.starts_with("/web/stage/") => {
322 let id = &p["/web/stage/".len()..];
323 crate::web::stage_html_handler(state, id)
324 }
325 (Method::Post, p) if p.starts_with("/web/stage/") && (
330 p.ends_with("/pin") || p.ends_with("/defer")
331 || p.ends_with("/block") || p.ends_with("/unblock")
332 ) => {
333 let prefix_len = "/web/stage/".len();
334 let last_slash = p.rfind('/').unwrap_or(p.len());
335 let id = &p[prefix_len..last_slash];
336 let verb = &p[last_slash + 1..];
337 let decision = match verb {
338 "pin" => crate::web::WebStageDecision::Pin,
339 "defer" => crate::web::WebStageDecision::Defer,
340 "block" => crate::web::WebStageDecision::Block,
341 "unblock" => crate::web::WebStageDecision::Unblock,
342 _ => unreachable!("matched in outer guard"),
343 };
344 crate::web::stage_decision_handler(state, id, body, decision, x_lex_user)
345 }
346 (Method::Get, "/v1/health") => json_response(200, &serde_json::json!({"ok": true})),
348 (Method::Post, "/v1/parse") => parse_handler(body),
349 (Method::Post, "/v1/check") => check_handler(body),
350 (Method::Post, "/v1/publish") => publish_handler(state, body),
351 (Method::Post, "/v1/patch") => patch_handler(state, body),
352 (Method::Get, p) if p.starts_with("/v1/stage/") => {
353 let suffix = &p["/v1/stage/".len()..];
354 if let Some(id) = suffix.strip_suffix("/attestations") {
357 stage_attestations_handler(state, id)
358 } else {
359 stage_handler(state, suffix)
360 }
361 }
362 (Method::Post, "/v1/run") => run_handler(state, body, false),
363 (Method::Post, "/v1/replay") => run_handler(state, body, true),
364 (Method::Get, p) if p.starts_with("/v1/trace/") => {
365 let id = &p["/v1/trace/".len()..];
366 trace_handler(state, id)
367 }
368 (Method::Get, "/v1/diff") => diff_handler(state, query),
369 (Method::Post, "/v1/merge/start") => merge_start_handler(state, body),
370 (Method::Post, p) if p.starts_with("/v1/merge/") && p.ends_with("/resolve") => {
371 let id = &p["/v1/merge/".len()..p.len() - "/resolve".len()];
372 merge_resolve_handler(state, id, body)
373 }
374 (Method::Post, p) if p.starts_with("/v1/merge/") && p.ends_with("/commit") => {
375 let id = &p["/v1/merge/".len()..p.len() - "/commit".len()];
376 merge_commit_handler(state, id)
377 }
378 (Method::Post, "/v1/ops/batch") => ops_batch_handler(state, body),
380 (Method::Post, "/v1/attestations/batch") => attestations_batch_handler(state, body),
381 (Method::Get, p) if p.starts_with("/v1/branches/") && p.ends_with("/head") => {
385 let name = &p["/v1/branches/".len()..p.len() - "/head".len()];
386 branch_head_handler(state, name)
387 }
388 (Method::Get, "/v1/ops/since") => ops_since_handler(state, query),
392 (Method::Get, "/v1/attestations/since") => attestations_since_handler(state, query),
393 (Method::Get, "/v1/pkg") => pkg_list_handler(state),
397 (Method::Put, p) if p.starts_with("/v1/pkg/") && p.ends_with("/visibility") => {
401 let name = &p["/v1/pkg/".len()..p.len() - "/visibility".len()];
402 pkg_set_visibility_handler(state, name, body)
403 }
404 (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/head") => {
405 let name = &p["/v1/pkg/".len()..p.len() - "/head".len()];
406 pkg_head_handler(state, name)
407 }
408 (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/versions") => {
409 let name = &p["/v1/pkg/".len()..p.len() - "/versions".len()];
410 pkg_versions_handler(state, name)
411 }
412 (Method::Get, p) if p.starts_with("/v1/pkg/") && p.ends_with("/archive") => {
414 let inner = &p["/v1/pkg/".len()..p.len() - "/archive".len()];
415 if let Some((name, version)) = inner.split_once('/') {
417 pkg_archive_handler(state, name, version)
418 } else {
419 error_response(400, "expected /v1/pkg/{name}/{version}/archive")
420 }
421 }
422 (Method::Get, p) if p.starts_with("/v1/pkg/") && p["/v1/pkg/".len()..].contains('/') => {
424 let inner = &p["/v1/pkg/".len()..];
425 if let Some((name, version)) = inner.split_once('/') {
426 pkg_get_version_handler(state, name, version)
427 } else {
428 error_response(400, "expected /v1/pkg/{name}/{version}")
429 }
430 }
431 (Method::Get, p) if p.starts_with("/v1/pkg/") => {
432 let name = &p["/v1/pkg/".len()..];
433 pkg_get_handler(state, name)
434 }
435 (Method::Delete, p) if p.starts_with("/v1/pkg/") => {
436 let name = &p["/v1/pkg/".len()..];
437 pkg_delete_handler(state, name)
438 }
439 _ => error_response(404, format!("unknown route: {method:?} {path}")),
440 }
441}
442
443#[derive(Deserialize)]
444struct ParseReq { source: String }
445
446fn parse_handler(body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
447 let req: ParseReq = match serde_json::from_str(body) {
448 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
449 };
450 match load_program_from_str(&req.source) {
451 Ok(prog) => {
452 let stages = canonicalize_program(&prog);
453 json_response(200, &serde_json::to_value(&stages).unwrap())
454 }
455 Err(e) => error_response(400, format!("syntax error: {e}")),
456 }
457}
458
459pub(crate) fn check_handler(body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
460 let req: ParseReq = match serde_json::from_str(body) {
461 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
462 };
463 let prog = match load_program_from_str(&req.source) {
464 Ok(p) => p, Err(e) => return error_response(400, format!("syntax error: {e}")),
465 };
466 let stages = canonicalize_program(&prog);
467 match lex_types::check_program(&stages) {
468 Ok(_) => json_response(200, &serde_json::json!({"ok": true})),
469 Err(errs) => json_response(422, &serde_json::to_value(&errs).unwrap()),
470 }
471}
472
473#[derive(Deserialize)]
474struct PublishReq { source: String, #[serde(default)] activate: bool }
475
476pub(crate) fn publish_handler(state: &State, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
477 let req: PublishReq = match serde_json::from_str(body) {
478 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
479 };
480 let prog = match load_program_from_str(&req.source) {
481 Ok(p) => p, Err(e) => return error_response(400, format!("syntax error: {e}")),
482 };
483 let mut stages = canonicalize_program(&prog);
487 if let Err(errs) = lex_types::check_and_rewrite_program(&mut stages) {
488 return error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap());
489 }
490
491 let store = state.store.lock().unwrap();
492 let branch = store.current_branch();
493
494 let old_head = match store.branch_head(&branch) {
496 Ok(h) => h,
497 Err(e) => return error_response(500, format!("branch_head: {e}")),
498 };
499 let old_fns: std::collections::BTreeMap<String, lex_ast::FnDecl> = old_head.values()
500 .filter_map(|stg| store.get_ast(stg).ok())
501 .filter_map(|s| match s {
502 lex_ast::Stage::FnDecl(fd) => Some((fd.name.clone(), fd)),
503 _ => None,
504 })
505 .collect();
506 let new_fns: std::collections::BTreeMap<String, lex_ast::FnDecl> = stages.iter()
507 .filter_map(|s| match s {
508 lex_ast::Stage::FnDecl(fd) => Some((fd.name.clone(), fd.clone())),
509 _ => None,
510 })
511 .collect();
512 let report = lex_vcs::compute_diff(&old_fns, &new_fns, false);
513
514 let mut new_imports: lex_vcs::ImportMap = lex_vcs::ImportMap::new();
516 {
517 let entry = new_imports.entry("<source>".into()).or_default();
518 for s in &stages {
519 if let lex_ast::Stage::Import(im) = s {
520 entry.insert(im.reference.clone());
521 }
522 }
523 }
524
525 match store.publish_program(&branch, &stages, &report, &new_imports, req.activate) {
526 Ok(outcome) => json_response(200, &serde_json::json!({
527 "ops": outcome.ops,
528 "head_op": outcome.head_op,
529 })),
530 Err(lex_store::StoreError::TypeError(errs)) => {
538 error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap())
539 }
540 Err(e) => write_error_response("publish_program", e),
541 }
542}
543
544#[derive(Deserialize)]
545struct PatchReq {
546 stage_id: String,
547 patch: lex_ast::Patch,
548 #[serde(default)] activate: bool,
549}
550
551fn patch_handler(state: &State, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
554 let req: PatchReq = match serde_json::from_str(body) {
555 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
556 };
557 let store = state.store.lock().unwrap();
558
559 let original = match store.get_ast(&req.stage_id) {
561 Ok(s) => s, Err(e) => return error_response(404, format!("stage: {e}")),
562 };
563
564 let patched = match lex_ast::apply_patch(&original, &req.patch) {
566 Ok(s) => s,
567 Err(e) => return error_with_detail(422, "patch failed",
568 serde_json::to_value(&e).unwrap_or_default()),
569 };
570
571 let stages = vec![patched.clone()];
573 if let Err(errs) = lex_types::check_program(&stages) {
574 return error_with_detail(422, "type errors after patch",
575 serde_json::to_value(&errs).unwrap_or_default());
576 }
577
578 let branch = store.current_branch();
582
583 let sig = match lex_ast::sig_id(&patched) {
585 Some(s) => s,
586 None => return error_response(500, "patched stage has no sig_id"),
587 };
588
589 let new_id = match store.publish(&patched) {
590 Ok(id) => id, Err(e) => return error_response(500, format!("publish: {e}")),
591 };
592 if req.activate {
593 if let Err(e) = store.activate(&new_id) {
594 return error_response(500, format!("activate: {e}"));
595 }
596 }
597
598 let original_effects: std::collections::BTreeSet<String> = match &original {
600 lex_ast::Stage::FnDecl(fd) => fd.effects.iter().map(|e| e.name.clone()).collect(),
601 _ => std::collections::BTreeSet::new(),
602 };
603 let patched_effects: std::collections::BTreeSet<String> = match &patched {
604 lex_ast::Stage::FnDecl(fd) => fd.effects.iter().map(|e| e.name.clone()).collect(),
605 _ => std::collections::BTreeSet::new(),
606 };
607 let head_now = match store.get_branch(&branch) {
608 Ok(b) => b.and_then(|b| b.head_op),
609 Err(e) => return error_response(500, format!("get_branch: {e}")),
610 };
611 let kind = if original_effects != patched_effects {
612 let from_budget = lex_vcs::operation_budget_from_effects(&original_effects);
619 let to_budget = lex_vcs::operation_budget_from_effects(&patched_effects);
620 lex_vcs::OperationKind::ChangeEffectSig {
621 sig_id: sig.clone(),
622 from_stage_id: req.stage_id.clone(),
623 to_stage_id: new_id.clone(),
624 from_effects: original_effects,
625 to_effects: patched_effects,
626 from_budget,
627 to_budget,
628 }
629 } else {
630 let budget = lex_vcs::operation_budget_from_effects(&original_effects);
631 lex_vcs::OperationKind::ModifyBody {
632 sig_id: sig.clone(),
633 from_stage_id: req.stage_id.clone(),
634 to_stage_id: new_id.clone(),
635 from_budget: budget,
636 to_budget: budget,
637 }
638 };
639 let transition = lex_vcs::StageTransition::Replace {
640 sig_id: sig.clone(),
641 from: req.stage_id.clone(),
642 to: new_id.clone(),
643 };
644 let op = lex_vcs::Operation::new(
645 kind,
646 head_now.into_iter().collect::<Vec<_>>(),
647 );
648 let op_id = match store.apply_operation(&branch, op, transition) {
649 Ok(id) => id,
650 Err(e) => return write_error_response("apply_operation", e),
651 };
652
653 let status = format!("{:?}",
654 store.get_status(&new_id).unwrap_or(lex_store::StageStatus::Draft)).to_lowercase();
655 json_response(200, &serde_json::json!({
656 "old_stage_id": req.stage_id,
657 "new_stage_id": new_id,
658 "sig_id": sig,
659 "status": status,
660 "op_id": op_id,
661 }))
662}
663
664pub(crate) fn stage_handler(state: &State, id: &str) -> Response<std::io::Cursor<Vec<u8>>> {
665 let store = state.store.lock().unwrap();
666 let meta = match store.get_metadata(id) {
667 Ok(m) => m, Err(e) => return error_response(404, format!("{e}")),
668 };
669 let ast = match store.get_ast(id) {
670 Ok(a) => a, Err(e) => return error_response(404, format!("{e}")),
671 };
672 let status = format!("{:?}", store.get_status(id).unwrap_or(lex_store::StageStatus::Draft)).to_lowercase();
673 json_response(200, &serde_json::json!({
674 "metadata": meta,
675 "ast": ast,
676 "status": status,
677 }))
678}
679
680pub(crate) fn stage_attestations_handler(state: &State, id: &str) -> Response<std::io::Cursor<Vec<u8>>> {
689 let store = state.store.lock().unwrap();
690 if let Err(e) = store.get_metadata(id) {
691 return error_response(404, format!("{e}"));
692 }
693 let log = match store.attestation_log() {
694 Ok(l) => l,
695 Err(e) => return error_response(500, format!("attestation log: {e}")),
696 };
697 let mut listing = match log.list_for_stage(&id.to_string()) {
698 Ok(v) => v,
699 Err(e) => return error_response(500, format!("list_for_stage: {e}")),
700 };
701 listing.sort_by_key(|a| std::cmp::Reverse(a.timestamp));
702 json_response(200, &serde_json::json!({"attestations": listing}))
703}
704
705#[derive(Deserialize, Default)]
706struct PolicyJson {
707 #[serde(default)] allow_effects: Vec<String>,
708 #[serde(default)] allow_fs_read: Vec<String>,
709 #[serde(default)] allow_fs_write: Vec<String>,
710 #[serde(default)] budget: Option<u64>,
711}
712
713impl PolicyJson {
714 fn into_policy(self) -> Policy {
715 Policy {
716 allow_effects: self.allow_effects.into_iter().collect::<BTreeSet<_>>(),
717 allow_fs_read: self.allow_fs_read.into_iter().map(PathBuf::from).collect(),
718 allow_fs_write: self.allow_fs_write.into_iter().map(PathBuf::from).collect(),
719 allow_net_host: Vec::new(),
720 allow_proc: Vec::new(),
721 allow_approval: Vec::new(),
722 budget: self.budget,
723 }
724 }
725}
726
727#[derive(Deserialize)]
728struct RunReq {
729 source: String,
730 #[serde(rename = "fn")] func: String,
731 #[serde(default)] args: Vec<serde_json::Value>,
732 #[serde(default)] policy: PolicyJson,
733 #[serde(default)] overrides: IndexMap<String, serde_json::Value>,
734}
735
736pub(crate) fn run_handler(state: &State, body: &str, with_overrides: bool) -> Response<std::io::Cursor<Vec<u8>>> {
737 let req: RunReq = match serde_json::from_str(body) {
738 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
739 };
740 let prog = match load_program_from_str(&req.source) {
741 Ok(p) => p, Err(e) => return error_response(400, format!("syntax error: {e}")),
742 };
743 let stages = canonicalize_program(&prog);
744 if let Err(errs) = lex_types::check_program(&stages) {
745 return error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap());
746 }
747 let bc = compile_program(&stages);
748 let mut policy = req.policy.into_policy();
749 if let Some(ceiling) = &state.policy_ceiling {
755 policy = clamp_policy(policy, ceiling);
756 }
757 if let Err(violations) = check_policy(&bc, &policy) {
758 return error_with_detail(403, "policy violation", serde_json::to_value(&violations).unwrap());
759 }
760
761 let mut recorder = lex_trace::Recorder::new();
762 if with_overrides && !req.overrides.is_empty() {
763 recorder = recorder.with_overrides(req.overrides);
764 }
765 let handle = recorder.handle();
766 let handler = DefaultHandler::new(policy);
767 let mut vm = Vm::with_handler(&bc, Box::new(handler));
768 vm.set_tracer(Box::new(recorder));
769
770 let vargs: Vec<Value> = req.args.iter().map(json_to_value).collect();
771 let started = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
772 let result = vm.call(&req.func, vargs);
773 let ended = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
774
775 let store = state.store.lock().unwrap();
776 let (root_out, root_err, status) = match &result {
777 Ok(v) => (Some(value_to_json(v)), None, 200u16),
778 Err(e) => (None, Some(format!("{e}")), 200u16),
779 };
780 let tree = handle.finalize(req.func.clone(), serde_json::Value::Null,
781 root_out.clone(), root_err.clone(), started, ended);
782 let run_id = match store.save_trace(&tree) {
783 Ok(id) => id,
784 Err(e) => return error_response(500, format!("save_trace: {e}")),
785 };
786
787 let mut body = serde_json::json!({
788 "run_id": run_id,
789 "output": root_out,
790 });
791 if let Some(err) = root_err {
792 body["error"] = serde_json::Value::String(err);
793 }
794 json_response(status, &body)
795}
796
797fn trace_handler(state: &State, id: &str) -> Response<std::io::Cursor<Vec<u8>>> {
798 let store = state.store.lock().unwrap();
799 match store.load_trace(id) {
800 Ok(t) => json_response(200, &serde_json::to_value(&t).unwrap()),
801 Err(e) => error_response(404, format!("{e}")),
802 }
803}
804
805fn diff_handler(state: &State, query: &str) -> Response<std::io::Cursor<Vec<u8>>> {
806 let mut a = None;
807 let mut b = None;
808 for kv in query.split('&') {
809 if let Some((k, v)) = kv.split_once('=') {
810 match k { "a" => a = Some(v.to_string()), "b" => b = Some(v.to_string()), _ => {} }
811 }
812 }
813 let (Some(a), Some(b)) = (a, b) else {
814 return error_response(400, "missing a or b query params");
815 };
816 let store = state.store.lock().unwrap();
817 let ta = match store.load_trace(&a) { Ok(t) => t, Err(e) => return error_response(404, format!("a: {e}")) };
818 let tb = match store.load_trace(&b) { Ok(t) => t, Err(e) => return error_response(404, format!("b: {e}")) };
819 match lex_trace::diff_runs(&ta, &tb) {
820 Some(d) => json_response(200, &serde_json::to_value(&d).unwrap()),
821 None => json_response(200, &serde_json::json!({"divergence": null})),
822 }
823}
824
825fn json_to_value(v: &serde_json::Value) -> Value { Value::from_json(v) }
826
827fn value_to_json(v: &Value) -> serde_json::Value { v.to_json() }
828
829#[derive(Deserialize)]
830struct MergeStartReq {
831 src_branch: String,
832 dst_branch: String,
833}
834
835fn merge_start_handler(state: &State, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
846 let req: MergeStartReq = match serde_json::from_str(body) {
847 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
848 };
849 let store = state.store.lock().unwrap();
850 let src_head = match store.get_branch(&req.src_branch) {
851 Ok(Some(b)) => b.head_op,
852 Ok(None) => return error_response(404, format!("unknown src branch `{}`", req.src_branch)),
853 Err(e) => return error_response(500, format!("src branch read: {e}")),
854 };
855 let dst_head = match store.get_branch(&req.dst_branch) {
856 Ok(Some(b)) => b.head_op,
857 Ok(None) => return error_response(404, format!("unknown dst branch `{}`", req.dst_branch)),
858 Err(e) => return error_response(500, format!("dst branch read: {e}")),
859 };
860 let log = match lex_vcs::OpLog::open(store.root()) {
861 Ok(l) => l,
862 Err(e) => return error_response(500, format!("op log: {e}")),
863 };
864 let merge_id = mint_merge_id();
868 let session = match MergeSession::start(
869 merge_id.clone(),
870 &log,
871 src_head.as_ref(),
872 dst_head.as_ref(),
873 ) {
874 Ok(s) => s,
875 Err(e) => return error_response(500, format!("merge start: {e}")),
876 };
877 let conflicts: Vec<&lex_vcs::ConflictRecord> = session.remaining_conflicts();
878 let auto_resolved_count = session.auto_resolved.len();
879 let body = serde_json::json!({
880 "merge_id": merge_id,
881 "src_head": session.src_head,
882 "dst_head": session.dst_head,
883 "lca": session.lca,
884 "conflicts": conflicts,
885 "auto_resolved_count": auto_resolved_count,
886 });
887 drop(conflicts);
888 drop(store);
889 let wrapped = ApiMergeSession {
890 inner: session,
891 src_branch: req.src_branch,
892 dst_branch: req.dst_branch,
893 };
894 state.sessions.lock().unwrap().insert(merge_id, wrapped);
895 json_response(200, &body)
896}
897
898#[derive(Deserialize)]
899struct MergeResolveReq {
900 resolutions: Vec<MergeResolveEntry>,
905}
906
907#[derive(Deserialize)]
908struct MergeResolveEntry {
909 conflict_id: String,
910 resolution: lex_vcs::Resolution,
911}
912
913fn merge_resolve_handler(
924 state: &State,
925 merge_id: &str,
926 body: &str,
927) -> Response<std::io::Cursor<Vec<u8>>> {
928 let req: MergeResolveReq = match serde_json::from_str(body) {
929 Ok(r) => r, Err(e) => return error_response(400, format!("bad request: {e}")),
930 };
931 let mut sessions = state.sessions.lock().unwrap();
932 let Some(wrapped) = sessions.get_mut(merge_id) else {
933 return error_response(404, format!("unknown merge_id `{merge_id}`"));
934 };
935 let pairs: Vec<(String, lex_vcs::Resolution)> = req.resolutions.into_iter()
936 .map(|e| (e.conflict_id, e.resolution))
937 .collect();
938 let verdicts = wrapped.inner.resolve(pairs);
939 let remaining: Vec<&lex_vcs::ConflictRecord> = wrapped.inner.remaining_conflicts();
940 let body = serde_json::json!({
941 "verdicts": verdicts,
942 "remaining_conflicts": remaining,
943 });
944 json_response(200, &body)
945}
946
947fn merge_commit_handler(
966 state: &State,
967 merge_id: &str,
968) -> Response<std::io::Cursor<Vec<u8>>> {
969 use std::collections::BTreeMap;
970 let wrapped = match state.sessions.lock().unwrap().remove(merge_id) {
971 Some(w) => w,
972 None => return error_response(404, format!("unknown merge_id `{merge_id}`")),
973 };
974 let dst_branch = wrapped.dst_branch.clone();
975 let src_head = wrapped.inner.src_head.clone();
976 let dst_head = wrapped.inner.dst_head.clone();
977 let auto_resolved = wrapped.inner.auto_resolved.clone();
978
979 let mut entries: BTreeMap<lex_vcs::SigId, Option<lex_vcs::StageId>> = BTreeMap::new();
982
983 for outcome in &auto_resolved {
985 if let lex_vcs::MergeOutcome::Src { sig_id, stage_id } = outcome {
986 entries.insert(sig_id.clone(), stage_id.clone());
987 }
988 }
989
990 let resolved = match wrapped.inner.commit() {
992 Ok(r) => r,
993 Err(lex_vcs::CommitError::ConflictsRemaining(ids)) => {
994 return error_with_detail(
998 422,
999 "conflicts remaining",
1000 serde_json::json!({"unresolved": ids}),
1001 );
1002 }
1003 };
1004
1005 for (conflict_id, resolution) in resolved {
1006 match resolution {
1007 lex_vcs::Resolution::TakeOurs => {
1008 }
1010 lex_vcs::Resolution::TakeTheirs => {
1011 match resolve_take_theirs(state, &src_head, &conflict_id) {
1021 Ok(stage_id) => {
1022 entries.insert(conflict_id.clone(), stage_id);
1023 }
1024 Err(e) => return error_response(500, format!("resolve take_theirs: {e}")),
1025 }
1026 }
1027 lex_vcs::Resolution::Custom { op } => {
1028 match op.kind.merge_target() {
1037 Some((sig, stage)) => {
1038 if sig != conflict_id {
1039 return error_with_detail(
1040 422,
1041 "custom op targets a different sig than the conflict",
1042 serde_json::json!({
1043 "conflict_id": conflict_id,
1044 "op_targets": sig,
1045 }),
1046 );
1047 }
1048 entries.insert(conflict_id, stage);
1049 }
1050 None => {
1051 return error_with_detail(
1052 422,
1053 "custom op kind doesn't yield a single sig→stage delta",
1054 serde_json::json!({
1055 "conflict_id": conflict_id,
1056 "kind": serde_json::to_value(&op.kind).unwrap_or(serde_json::Value::Null),
1057 }),
1058 );
1059 }
1060 }
1061 }
1062 lex_vcs::Resolution::Defer => {
1063 return error_response(500, "internal: Defer slipped past commit gate");
1065 }
1066 }
1067 }
1068
1069 let resolved_count = entries.len();
1070 let mut parents: Vec<lex_vcs::OpId> = Vec::new();
1071 if let Some(d) = dst_head { parents.push(d); }
1072 if let Some(s) = src_head { parents.push(s); }
1073 let op = lex_vcs::Operation::new(
1074 lex_vcs::OperationKind::Merge { resolved: resolved_count },
1075 parents,
1076 );
1077 let transition = lex_vcs::StageTransition::Merge { entries };
1078 let store = state.store.lock().unwrap();
1079 match store.apply_operation(&dst_branch, op, transition) {
1080 Ok(new_head_op) => json_response(200, &serde_json::json!({
1081 "new_head_op": new_head_op,
1082 "dst_branch": dst_branch,
1083 })),
1084 Err(e) => write_error_response("apply merge op", e),
1085 }
1086}
1087
1088fn resolve_take_theirs(
1093 state: &State,
1094 src_head: &Option<lex_vcs::OpId>,
1095 sig: &lex_vcs::SigId,
1096) -> std::io::Result<Option<lex_vcs::StageId>> {
1097 let store = state.store.lock().unwrap();
1098 let log = lex_vcs::OpLog::open(store.root())?;
1099 let Some(head) = src_head.as_ref() else { return Ok(None); };
1100 let mut current: Option<lex_vcs::StageId> = None;
1103 for record in log.walk_forward(head, None)? {
1104 match &record.produces {
1105 lex_vcs::StageTransition::Create { sig_id, stage_id }
1106 if sig_id == sig => { current = Some(stage_id.clone()); }
1107 lex_vcs::StageTransition::Replace { sig_id, to, .. }
1108 if sig_id == sig => { current = Some(to.clone()); }
1109 lex_vcs::StageTransition::Remove { sig_id, .. }
1110 if sig_id == sig => { current = None; }
1111 lex_vcs::StageTransition::Rename { from, to, body_stage_id }
1112 if from == sig || to == sig => {
1113 if from == sig { current = None; }
1114 if to == sig { current = Some(body_stage_id.clone()); }
1115 }
1116 lex_vcs::StageTransition::Merge { entries } => {
1117 if let Some(opt) = entries.get(sig) {
1118 current = opt.clone();
1119 }
1120 }
1121 _ => {}
1122 }
1123 }
1124 Ok(current)
1125}
1126
1127fn mint_merge_id() -> MergeSessionId {
1128 use std::sync::atomic::{AtomicU64, Ordering};
1129 static COUNTER: AtomicU64 = AtomicU64::new(0);
1130 let nanos = SystemTime::now()
1131 .duration_since(UNIX_EPOCH)
1132 .map(|d| d.as_nanos())
1133 .unwrap_or(0);
1134 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
1135 format!("merge_{nanos:x}_{n:x}")
1136}
1137
1138pub(crate) fn ops_batch_handler(state: &State, body: &str)
1169 -> Response<std::io::Cursor<Vec<u8>>>
1170{
1171 let records: Vec<lex_vcs::OperationRecord> = match serde_json::from_str(body) {
1172 Ok(r) => r,
1173 Err(e) => return error_response(400,
1174 format!("body must be a JSON array of OperationRecord: {e}")),
1175 };
1176 let store = state.store.lock().unwrap();
1177 let log = match lex_vcs::OpLog::open(store.root()) {
1178 Ok(l) => l,
1179 Err(e) => return error_response(500, format!("opening op log: {e}")),
1180 };
1181
1182 let mut batch_ids: std::collections::BTreeSet<lex_vcs::OpId> =
1190 std::collections::BTreeSet::new();
1191 for rec in &records {
1192 let expected = rec.op.op_id();
1193 if expected != rec.op_id {
1194 return error_with_detail(409, "OpIdMismatch", serde_json::json!({
1195 "supplied": rec.op_id,
1196 "expected": expected,
1197 }));
1198 }
1199 for parent in &rec.op.parents {
1200 let known = match log.get(parent) {
1201 Ok(Some(_)) => true,
1202 Ok(None) => false,
1203 Err(e) => return error_response(500, format!("op log read: {e}")),
1204 };
1205 if !known && !batch_ids.contains(parent) {
1206 return error_with_detail(422, "MissingParent", serde_json::json!({
1207 "op_id": rec.op_id,
1208 "missing_parent": parent,
1209 }));
1210 }
1211 }
1212 batch_ids.insert(rec.op_id.clone());
1213 }
1214
1215 let mut added = 0usize;
1218 let mut added_ids: Vec<&lex_vcs::OpId> = Vec::new();
1219 for rec in &records {
1220 let already_present = matches!(log.get(&rec.op_id), Ok(Some(_)));
1221 match log.put(rec) {
1222 Ok(()) => {
1223 if !already_present {
1224 added += 1;
1225 added_ids.push(&rec.op_id);
1226 }
1227 }
1228 Err(e) => return error_response(500, format!("op log write: {e}")),
1229 }
1230 }
1231
1232 json_response(200, &serde_json::json!({
1233 "received": records.len(),
1234 "added": added,
1235 "skipped": records.len() - added,
1236 "added_ids": added_ids,
1237 }))
1238}
1239
1240pub(crate) fn attestations_batch_handler(state: &State, body: &str)
1262 -> Response<std::io::Cursor<Vec<u8>>>
1263{
1264 let attestations: Vec<lex_vcs::Attestation> = match serde_json::from_str(body) {
1265 Ok(a) => a,
1266 Err(e) => return error_response(400,
1267 format!("body must be a JSON array of Attestation: {e}")),
1268 };
1269 let store = state.store.lock().unwrap();
1270 let log = match store.attestation_log() {
1271 Ok(l) => l,
1272 Err(e) => return error_response(500, format!("opening attestation log: {e}")),
1273 };
1274 let op_log = match lex_vcs::OpLog::open(store.root()) {
1275 Ok(l) => l,
1276 Err(e) => return error_response(500, format!("opening op log: {e}")),
1277 };
1278
1279 for att in &attestations {
1281 let expected = lex_vcs::Attestation::with_timestamp(
1284 att.stage_id.clone(),
1285 att.op_id.clone(),
1286 att.intent_id.clone(),
1287 att.kind.clone(),
1288 att.result.clone(),
1289 att.produced_by.clone(),
1290 att.cost.clone(),
1291 att.timestamp,
1292 ).attestation_id;
1293 if expected != att.attestation_id {
1294 return error_with_detail(409, "AttestationIdMismatch", serde_json::json!({
1295 "supplied": att.attestation_id,
1296 "expected": expected,
1297 }));
1298 }
1299 if let Some(op_id) = &att.op_id {
1303 match op_log.get(op_id) {
1304 Ok(Some(_)) => {}
1305 Ok(None) => return error_with_detail(422, "UnknownOp", serde_json::json!({
1306 "attestation_id": att.attestation_id,
1307 "op_id": op_id,
1308 })),
1309 Err(e) => return error_response(500, format!("op log read: {e}")),
1310 }
1311 }
1312 }
1313
1314 let mut added = 0usize;
1318 let mut added_ids: Vec<&lex_vcs::AttestationId> = Vec::new();
1319 for att in &attestations {
1320 let already_present = matches!(log.get(&att.attestation_id), Ok(Some(_)));
1321 match log.put(att) {
1322 Ok(()) => {
1323 if !already_present {
1324 added += 1;
1325 added_ids.push(&att.attestation_id);
1326 }
1327 }
1328 Err(e) => return error_response(500, format!("attestation log write: {e}")),
1329 }
1330 }
1331
1332 json_response(200, &serde_json::json!({
1333 "received": attestations.len(),
1334 "added": added,
1335 "skipped": attestations.len() - added,
1336 "added_ids": added_ids,
1337 }))
1338}
1339
1340pub(crate) fn branch_head_handler(state: &State, name: &str)
1349 -> Response<std::io::Cursor<Vec<u8>>>
1350{
1351 let store = state.store.lock().unwrap();
1352 let head = match store.get_branch(name) {
1353 Ok(Some(b)) => b.head_op,
1354 Ok(None) => None,
1355 Err(e) => return error_response(500, format!("get_branch: {e}")),
1356 };
1357 json_response(200, &serde_json::json!({
1358 "branch": name,
1359 "head_op": head,
1360 }))
1361}
1362
1363pub(crate) fn ops_since_handler(state: &State, query: &str)
1387 -> Response<std::io::Cursor<Vec<u8>>>
1388{
1389 let mut after: Option<String> = None;
1390 let mut branch = String::from("main");
1391 let mut limit: Option<usize> = None;
1392 for kv in query.split('&') {
1393 let Some((k, v)) = kv.split_once('=') else { continue };
1394 match k {
1395 "after" => after = Some(v.to_string()),
1396 "branch" => branch = v.to_string(),
1397 "limit" => {
1398 limit = Some(match v.parse::<usize>() {
1399 Ok(n) => n,
1400 Err(_) => return error_response(400,
1401 format!("limit must be a positive integer, got `{v}`")),
1402 });
1403 }
1404 _ => {}
1405 }
1406 }
1407
1408 let store = state.store.lock().unwrap();
1409 let log = match lex_vcs::OpLog::open(store.root()) {
1410 Ok(l) => l,
1411 Err(e) => return error_response(500, format!("opening op log: {e}")),
1412 };
1413 let head = match store.get_branch(&branch) {
1414 Ok(Some(b)) => b.head_op,
1415 Ok(None) => None,
1416 Err(e) => return error_response(500, format!("get_branch: {e}")),
1417 };
1418 let Some(head) = head else {
1419 return json_response(200, &serde_json::json!([]));
1420 };
1421
1422 let ops_since = match log.ops_since(&head, after.as_ref()) {
1423 Ok(o) => o,
1424 Err(e) => return error_response(500, format!("ops_since: {e}")),
1425 };
1426 let mut ops = ops_since;
1430 ops.reverse();
1431 if let Some(n) = limit {
1432 ops.truncate(n);
1433 }
1434
1435 json_response(200, &serde_json::to_value(&ops).unwrap_or_default())
1436}
1437
1438pub(crate) fn attestations_since_handler(state: &State, query: &str)
1451 -> Response<std::io::Cursor<Vec<u8>>>
1452{
1453 let mut after_op: Option<String> = None;
1454 let mut limit: Option<usize> = None;
1455 for kv in query.split('&') {
1456 let Some((k, v)) = kv.split_once('=') else { continue };
1457 match k {
1458 "after-op" => after_op = Some(v.to_string()),
1459 "limit" => {
1460 limit = Some(match v.parse::<usize>() {
1461 Ok(n) => n,
1462 Err(_) => return error_response(400,
1463 format!("limit must be a positive integer, got `{v}`")),
1464 });
1465 }
1466 _ => {}
1467 }
1468 }
1469
1470 let store = state.store.lock().unwrap();
1471 let log = match store.attestation_log() {
1472 Ok(l) => l,
1473 Err(e) => return error_response(500, format!("opening attestation log: {e}")),
1474 };
1475
1476 let exclude: std::collections::BTreeSet<String> = match &after_op {
1480 None => std::collections::BTreeSet::new(),
1481 Some(cutoff) => {
1482 let op_log = match lex_vcs::OpLog::open(store.root()) {
1483 Ok(l) => l,
1484 Err(e) => return error_response(500, format!("opening op log: {e}")),
1485 };
1486 match op_log.walk_back(cutoff, None) {
1487 Ok(records) => records.into_iter().map(|r| r.op_id).collect(),
1488 Err(_) => {
1489 std::collections::BTreeSet::new()
1493 }
1494 }
1495 }
1496 };
1497
1498 let all = match log.list_all() {
1499 Ok(v) => v,
1500 Err(e) => return error_response(500, format!("listing attestations: {e}")),
1501 };
1502 let mut filtered: Vec<lex_vcs::Attestation> = all
1503 .into_iter()
1504 .filter(|a| match &a.op_id {
1505 Some(op_id) => !exclude.contains(op_id),
1506 None => true,
1510 })
1511 .collect();
1512 filtered.sort_by(|a, b| {
1516 a.timestamp.cmp(&b.timestamp)
1517 .then_with(|| a.attestation_id.cmp(&b.attestation_id))
1518 });
1519 if let Some(n) = limit {
1520 filtered.truncate(n);
1521 }
1522
1523 json_response(200, &serde_json::to_value(&filtered).unwrap_or_default())
1524}
1525
1526#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1530struct PkgRecord {
1531 name: String,
1532 version: String,
1533 head_op: Option<String>,
1534 published_at: u64,
1535 function_names: Vec<String>,
1537 ops: Vec<serde_json::Value>,
1539}
1540
1541#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
1548#[serde(rename_all = "lowercase")]
1549pub enum Visibility {
1550 #[default]
1551 Private,
1552 Public,
1553}
1554
1555#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
1560struct PkgIndex {
1561 latest: Option<String>,
1563 versions: Vec<PkgVersionSummary>,
1565 #[serde(default)]
1569 visibility: Visibility,
1570}
1571
1572#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1573struct PkgVersionSummary {
1574 version: String,
1575 head_op: Option<String>,
1576 published_at: u64,
1577}
1578
1579fn pkg_name_dir(root: &std::path::Path, name: &str) -> PathBuf {
1580 root.join("packages").join(name)
1581}
1582
1583fn pkg_index_path(root: &std::path::Path, name: &str) -> PathBuf {
1584 pkg_name_dir(root, name).join("index.json")
1585}
1586
1587fn pkg_version_path(root: &std::path::Path, name: &str, version: &str) -> PathBuf {
1588 pkg_name_dir(root, name).join(format!("{version}.json"))
1589}
1590
1591fn pkg_archive_path(root: &std::path::Path, name: &str, version: &str) -> PathBuf {
1592 pkg_name_dir(root, name).join(format!("{version}.tar.gz"))
1593}
1594
1595fn load_pkg_index(root: &std::path::Path, name: &str) -> Option<PkgIndex> {
1596 let bytes = std::fs::read(pkg_index_path(root, name)).ok()?;
1597 serde_json::from_slice(&bytes).ok()
1598}
1599
1600fn load_pkg_record(root: &std::path::Path, name: &str, version: &str) -> Option<PkgRecord> {
1601 let bytes = std::fs::read(pkg_version_path(root, name, version)).ok()?;
1602 serde_json::from_slice(&bytes).ok()
1603}
1604
1605fn load_latest_pkg_record(root: &std::path::Path, name: &str) -> Option<PkgRecord> {
1606 let index = load_pkg_index(root, name)?;
1607 let latest = index.latest.clone()?;
1608 load_pkg_record(root, name, &latest)
1609}
1610
1611fn pkg_is_public(root: &std::path::Path, name: &str) -> bool {
1615 load_pkg_index(root, name).map(|i| i.visibility) == Some(Visibility::Public)
1616}
1617
1618fn valid_pkg_segment(s: &str) -> bool {
1623 !s.is_empty()
1624 && s.len() <= 128
1625 && s != "."
1626 && s != ".."
1627 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1628}
1629
1630#[derive(Deserialize)]
1631struct VisibilityReq {
1632 visibility: Visibility,
1633}
1634
1635fn pkg_set_visibility_handler(
1642 state: &State,
1643 name: &str,
1644 body: &str,
1645) -> Response<std::io::Cursor<Vec<u8>>> {
1646 if !valid_pkg_segment(name) {
1647 return error_response(400, format!("invalid package name {name:?}"));
1648 }
1649 let req: VisibilityReq = match serde_json::from_str(body) {
1650 Ok(r) => r,
1651 Err(e) => return error_response(400, format!("bad request: {e}")),
1652 };
1653 let mut index = match load_pkg_index(&state.root, name) {
1654 Some(i) => i,
1655 None => return error_response(404, format!("package {name:?} not found")),
1656 };
1657 index.visibility = req.visibility;
1658 let bytes = serde_json::to_vec_pretty(&index).unwrap_or_default();
1659 match std::fs::write(pkg_index_path(&state.root, name), bytes) {
1660 Ok(()) => json_response(
1661 200,
1662 &serde_json::json!({ "name": name, "visibility": index.visibility }),
1663 ),
1664 Err(e) => error_response(500, format!("write index: {e}")),
1665 }
1666}
1667
1668fn public_pkg_names(root: &std::path::Path) -> Vec<String> {
1671 list_pkg_names(root)
1672 .into_iter()
1673 .filter(|name| pkg_is_public(root, name))
1674 .collect()
1675}
1676
1677fn public_pkg_list_handler(state: &State) -> Response<std::io::Cursor<Vec<u8>>> {
1681 let packages: Vec<serde_json::Value> = public_pkg_names(&state.root)
1682 .iter()
1683 .filter_map(|name| {
1684 let r = load_latest_pkg_record(&state.root, name)?;
1685 Some(serde_json::json!({
1686 "name": r.name,
1687 "version": r.version,
1688 "head_op": r.head_op,
1689 "published_at": r.published_at,
1690 }))
1691 })
1692 .collect();
1693 json_response(200, &serde_json::json!({ "packages": packages }))
1694}
1695
1696#[derive(Debug, PartialEq, Eq)]
1701enum PublicTarget {
1702 List,
1703 Latest(String),
1704 Versions(String),
1705 Head(String),
1706 Version(String, String),
1707 Archive(String, String),
1708}
1709
1710impl PublicTarget {
1711 fn pkg_name(&self) -> Option<&str> {
1713 match self {
1714 PublicTarget::List => None,
1715 PublicTarget::Latest(n)
1716 | PublicTarget::Versions(n)
1717 | PublicTarget::Head(n)
1718 | PublicTarget::Version(n, _)
1719 | PublicTarget::Archive(n, _) => Some(n),
1720 }
1721 }
1722}
1723
1724fn resolve_public(method: &Method, path: &str) -> Result<PublicTarget, u16> {
1729 if !matches!(method, Method::Get) {
1730 return Err(405);
1731 }
1732 let rest = path.trim_matches('/');
1733 if rest.is_empty() {
1734 return Ok(PublicTarget::List);
1735 }
1736 let segs: Vec<&str> = rest.split('/').collect();
1737 if !segs.iter().all(|s| valid_pkg_segment(s)) {
1738 return Err(404);
1739 }
1740 match segs.as_slice() {
1741 [n] => Ok(PublicTarget::Latest(n.to_string())),
1742 [n, "versions"] => Ok(PublicTarget::Versions(n.to_string())),
1743 [n, "head"] => Ok(PublicTarget::Head(n.to_string())),
1744 [n, v, "archive"] => Ok(PublicTarget::Archive(n.to_string(), v.to_string())),
1745 [n, v] => Ok(PublicTarget::Version(n.to_string(), v.to_string())),
1746 _ => Err(404),
1747 }
1748}
1749
1750pub fn route_public(
1761 state: &State,
1762 method: &Method,
1763 path: &str,
1764 _query: &str,
1765) -> Response<std::io::Cursor<Vec<u8>>> {
1766 let target = match resolve_public(method, path) {
1767 Ok(t) => t,
1768 Err(405) => return error_response(405, "public read is GET-only"),
1769 Err(_) => return error_response(404, "not found"),
1770 };
1771 if let PublicTarget::List = target {
1773 return public_pkg_list_handler(state);
1774 }
1775 if let Some(name) = target.pkg_name() {
1777 if !pkg_is_public(&state.root, name) {
1778 return error_response(404, format!("package {name:?} not found"));
1779 }
1780 }
1781 match target {
1782 PublicTarget::List => unreachable!("handled above"),
1783 PublicTarget::Latest(n) => pkg_get_handler(state, &n),
1784 PublicTarget::Versions(n) => pkg_versions_handler(state, &n),
1785 PublicTarget::Head(n) => pkg_head_handler(state, &n),
1786 PublicTarget::Version(n, v) => pkg_get_version_handler(state, &n, &v),
1787 PublicTarget::Archive(n, v) => pkg_archive_handler(state, &n, &v),
1788 }
1789}
1790
1791fn save_pkg_record(
1792 root: &std::path::Path,
1793 record: &PkgRecord,
1794 archive: &[u8],
1795) -> std::io::Result<()> {
1796 let dir = pkg_name_dir(root, &record.name);
1797 std::fs::create_dir_all(&dir)?;
1798
1799 let rec_bytes = serde_json::to_vec_pretty(record).unwrap_or_default();
1801 std::fs::write(pkg_version_path(root, &record.name, &record.version), rec_bytes)?;
1802
1803 std::fs::write(pkg_archive_path(root, &record.name, &record.version), archive)?;
1805
1806 let mut index = load_pkg_index(root, &record.name).unwrap_or_default();
1808 index.latest = Some(record.version.clone());
1809 if !index.versions.iter().any(|v| v.version == record.version) {
1810 index.versions.push(PkgVersionSummary {
1811 version: record.version.clone(),
1812 head_op: record.head_op.clone(),
1813 published_at: record.published_at,
1814 });
1815 }
1816 let idx_bytes = serde_json::to_vec_pretty(&index).unwrap_or_default();
1817 std::fs::write(pkg_index_path(root, &record.name), idx_bytes)
1818}
1819
1820fn list_pkg_names(root: &std::path::Path) -> Vec<String> {
1821 let dir = root.join("packages");
1822 let Ok(entries) = std::fs::read_dir(&dir) else {
1823 return Vec::new();
1824 };
1825 let mut names: Vec<String> = entries
1826 .filter_map(|e| e.ok())
1827 .filter(|e| e.path().is_dir())
1828 .filter_map(|e| e.file_name().into_string().ok())
1829 .collect();
1830 names.sort();
1831 names
1832}
1833
1834fn collect_lex_files(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
1835 let Ok(entries) = std::fs::read_dir(dir) else { return };
1836 let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect();
1837 entries.sort_by_key(|e| e.path());
1838 for entry in entries {
1839 let path = entry.path();
1840 if path.is_dir() {
1841 collect_lex_files(&path, out);
1842 } else if path.extension().and_then(|x| x.to_str()) == Some("lex") {
1843 out.push(path);
1844 }
1845 }
1846}
1847
1848fn pkg_publish_handler(state: &State, body: &[u8]) -> Response<std::io::Cursor<Vec<u8>>> {
1851 let tmp = match tempfile::TempDir::new() {
1852 Ok(t) => t,
1853 Err(e) => return error_response(500, format!("create temp dir: {e}")),
1854 };
1855 {
1856 let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(body));
1857 let mut ar = tar::Archive::new(gz);
1858 if let Err(e) = ar.unpack(tmp.path()) {
1859 return error_response(400, format!("unpack archive: {e}"));
1860 }
1861 }
1862
1863 let toml_path = tmp.path().join("lex.toml");
1864 if !toml_path.exists() {
1865 return error_response(400, "archive must contain lex.toml at root");
1866 }
1867 let manifest = match Manifest::load(&toml_path) {
1868 Ok(m) => m,
1869 Err(e) => return error_response(400, format!("lex.toml: {e}")),
1870 };
1871 let (pkg_name, pkg_version) = match &manifest.package {
1872 Some(m) => (m.name.clone(), m.version.clone()),
1873 None => return error_response(400, "lex.toml must have a [package] section"),
1874 };
1875
1876 let src_dir = tmp.path().join("src");
1877 if !src_dir.exists() {
1878 return error_response(400, "archive must contain a src/ directory");
1879 }
1880 let mut lex_files: Vec<PathBuf> = Vec::new();
1881 collect_lex_files(&src_dir, &mut lex_files);
1882 if lex_files.is_empty() {
1883 return error_response(400, "no .lex files found in src/");
1884 }
1885
1886 let store = state.store.lock().unwrap();
1887 let branch = store.current_branch();
1888
1889 let mut all_ops: Vec<serde_json::Value> = Vec::new();
1890 let mut final_head_op: Option<String> = None;
1891 let mut all_function_names: Vec<String> = Vec::new();
1892
1893 for lex_path in &lex_files {
1894 let prog = match load_program(lex_path) {
1895 Ok(p) => p,
1896 Err(e) => return error_response(400, format!("load {}: {e}", lex_path.display())),
1897 };
1898 let mut stages = canonicalize_program(&prog);
1899 if let Err(errs) = lex_types::check_and_rewrite_program(&mut stages) {
1900 return error_with_detail(
1901 422,
1902 format!("type errors in {}", lex_path.display()),
1903 serde_json::to_value(&errs).unwrap(),
1904 );
1905 }
1906
1907 let old_head = match store.branch_head(&branch) {
1908 Ok(h) => h,
1909 Err(e) => return error_response(500, format!("branch_head: {e}")),
1910 };
1911 let old_fns: BTreeMap<String, lex_ast::FnDecl> = old_head.values()
1912 .filter_map(|stg| store.get_ast(stg).ok())
1913 .filter_map(|s| match s {
1914 lex_ast::Stage::FnDecl(fd) => Some((fd.name.clone(), fd)),
1915 _ => None,
1916 })
1917 .collect();
1918 let new_fns: BTreeMap<String, lex_ast::FnDecl> = stages.iter()
1919 .filter_map(|s| match s {
1920 lex_ast::Stage::FnDecl(fd) => Some((fd.name.clone(), fd.clone())),
1921 _ => None,
1922 })
1923 .collect();
1924
1925 for name in new_fns.keys() {
1926 if !all_function_names.contains(name) {
1927 all_function_names.push(name.clone());
1928 }
1929 }
1930
1931 let report = lex_vcs::compute_diff(&old_fns, &new_fns, false);
1932
1933 let file_key = lex_path
1934 .strip_prefix(tmp.path())
1935 .unwrap_or(lex_path)
1936 .display()
1937 .to_string();
1938 let mut new_imports = lex_vcs::ImportMap::new();
1939 {
1940 let entry = new_imports.entry(file_key).or_default();
1941 for s in &stages {
1942 if let lex_ast::Stage::Import(im) = s {
1943 entry.insert(im.reference.clone());
1944 }
1945 }
1946 }
1947
1948 match store.publish_program(&branch, &stages, &report, &new_imports, false) {
1949 Ok(outcome) => {
1950 let ops_json = serde_json::to_value(&outcome.ops).unwrap_or_default();
1951 if let serde_json::Value::Array(arr) = ops_json {
1952 all_ops.extend(arr);
1953 }
1954 if let Some(h) = outcome.head_op {
1955 final_head_op = Some(h);
1956 }
1957 }
1958 Err(lex_store::StoreError::TypeError(errs)) => {
1959 return error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap());
1960 }
1961 Err(e) => return write_error_response("publish_program", e),
1962 }
1963 }
1964
1965 if load_pkg_record(&state.root, &pkg_name, &pkg_version).is_some() {
1967 return error_response(
1968 409,
1969 format!(
1970 "package {pkg_name}@{pkg_version} already published; \
1971 bump the version in lex.toml to publish a new release"
1972 ),
1973 );
1974 }
1975
1976 let now = SystemTime::now()
1977 .duration_since(UNIX_EPOCH)
1978 .map(|d| d.as_secs())
1979 .unwrap_or(0);
1980 let record = PkgRecord {
1981 name: pkg_name.clone(),
1982 version: pkg_version,
1983 head_op: final_head_op.clone(),
1984 published_at: now,
1985 function_names: all_function_names,
1986 ops: all_ops.clone(),
1987 };
1988 if let Err(e) = save_pkg_record(&state.root, &record, body) {
1989 return error_response(500, format!("save package index: {e}"));
1990 }
1991
1992 json_response(200, &serde_json::json!({
1993 "package": pkg_name,
1994 "ops": all_ops,
1995 "head_op": final_head_op,
1996 }))
1997}
1998
1999fn pkg_list_handler(state: &State) -> Response<std::io::Cursor<Vec<u8>>> {
2001 let names = list_pkg_names(&state.root);
2002 let packages: Vec<serde_json::Value> = names.iter()
2003 .filter_map(|name| {
2004 let idx = load_pkg_index(&state.root, name)?;
2005 let latest = idx.latest.as_deref()?;
2006 let r = load_pkg_record(&state.root, name, latest)?;
2007 Some(serde_json::json!({
2008 "name": r.name,
2009 "version": r.version,
2010 "head_op": r.head_op,
2011 "published_at": r.published_at,
2012 }))
2013 })
2014 .collect();
2015 json_response(200, &serde_json::json!({ "packages": packages }))
2016}
2017
2018fn pkg_get_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2020 match load_latest_pkg_record(&state.root, name) {
2021 Some(r) => json_response(200, &serde_json::json!({
2022 "name": r.name,
2023 "version": r.version,
2024 "head_op": r.head_op,
2025 "published_at": r.published_at,
2026 "function_names": r.function_names,
2027 "ops": r.ops,
2028 })),
2029 None => error_response(404, format!("package {name:?} not found")),
2030 }
2031}
2032
2033fn pkg_versions_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2035 match load_pkg_index(&state.root, name) {
2036 Some(idx) => json_response(200, &serde_json::json!({
2037 "name": name,
2038 "latest": idx.latest,
2039 "versions": idx.versions,
2040 })),
2041 None => error_response(404, format!("package {name:?} not found")),
2042 }
2043}
2044
2045fn pkg_get_version_handler(state: &State, name: &str, version: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2047 match load_pkg_record(&state.root, name, version) {
2048 Some(r) => json_response(200, &serde_json::json!({
2049 "name": r.name,
2050 "version": r.version,
2051 "head_op": r.head_op,
2052 "published_at": r.published_at,
2053 "function_names": r.function_names,
2054 "ops": r.ops,
2055 })),
2056 None => error_response(404, format!("package {name:?}@{version:?} not found")),
2057 }
2058}
2059
2060fn pkg_archive_handler(state: &State, name: &str, version: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2062 let path = pkg_archive_path(&state.root, name, version);
2063 match std::fs::read(&path) {
2064 Ok(bytes) => Response::from_data(bytes)
2065 .with_status_code(200)
2066 .with_header(
2067 tiny_http::Header::from_bytes(
2068 &b"Content-Type"[..],
2069 &b"application/gzip"[..],
2070 )
2071 .unwrap(),
2072 ),
2073 Err(_) => error_response(404, format!("archive for {name:?}@{version:?} not found")),
2074 }
2075}
2076
2077fn pkg_head_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2079 match load_latest_pkg_record(&state.root, name) {
2080 Some(r) => json_response(200, &serde_json::json!({
2081 "name": r.name,
2082 "version": r.version,
2083 "head_op": r.head_op,
2084 })),
2085 None => error_response(404, format!("package {name:?} not found")),
2086 }
2087}
2088
2089fn pkg_delete_handler(state: &State, name: &str) -> Response<std::io::Cursor<Vec<u8>>> {
2091 let record = match load_latest_pkg_record(&state.root, name) {
2092 Some(r) => r,
2093 None => return error_response(404, format!("package {name:?} not found")),
2094 };
2095
2096 let store = state.store.lock().unwrap();
2097 let branch = store.current_branch();
2098
2099 let head = match store.branch_head(&branch) {
2100 Ok(h) => h,
2101 Err(e) => return error_response(500, format!("branch_head: {e}")),
2102 };
2103
2104 let old_fns: BTreeMap<String, lex_ast::FnDecl> = head.values()
2106 .filter_map(|stage_id| store.get_ast(stage_id).ok())
2107 .filter_map(|s| match s {
2108 lex_ast::Stage::FnDecl(fd)
2109 if record.function_names.contains(&fd.name) => Some((fd.name.clone(), fd)),
2110 _ => None,
2111 })
2112 .collect();
2113
2114 let new_fns: BTreeMap<String, lex_ast::FnDecl> = BTreeMap::new();
2115 let report = lex_vcs::compute_diff(&old_fns, &new_fns, false);
2116 let empty_imports = lex_vcs::ImportMap::new();
2117
2118 match store.publish_program(&branch, &[], &report, &empty_imports, false) {
2119 Ok(outcome) => {
2120 let ver = record.version.clone();
2122 let _ = std::fs::remove_file(pkg_version_path(&state.root, name, &ver));
2123 let _ = std::fs::remove_file(pkg_archive_path(&state.root, name, &ver));
2124 if let Some(mut idx) = load_pkg_index(&state.root, name) {
2126 idx.versions.retain(|v| v.version != ver);
2127 idx.latest = idx.versions.last().map(|v| v.version.clone());
2128 if idx.versions.is_empty() {
2129 let _ = std::fs::remove_dir_all(pkg_name_dir(&state.root, name));
2130 } else {
2131 let bytes = serde_json::to_vec_pretty(&idx).unwrap_or_default();
2132 let _ = std::fs::write(pkg_index_path(&state.root, name), bytes);
2133 }
2134 }
2135 json_response(200, &serde_json::json!({
2136 "deleted": name,
2137 "version": ver,
2138 "ops": outcome.ops,
2139 "head_op": outcome.head_op,
2140 }))
2141 }
2142 Err(lex_store::StoreError::TypeError(errs)) => {
2143 error_with_detail(422, "type errors", serde_json::to_value(&errs).unwrap())
2144 }
2145 Err(e) => write_error_response("retract package", e),
2146 }
2147}
2148
2149#[cfg(test)]
2150mod policy_ceiling_tests {
2151 use super::*;
2152 use lex_runtime::Policy;
2153 use std::path::PathBuf;
2154
2155 fn permissive_request() -> Policy {
2159 Policy {
2160 allow_effects: ["io", "fs_read", "fs_write", "net", "proc"]
2161 .iter()
2162 .map(|s| s.to_string())
2163 .collect(),
2164 allow_fs_read: vec![PathBuf::from("/")],
2165 allow_fs_write: vec![PathBuf::from("/")],
2166 allow_net_host: Vec::new(),
2167 allow_proc: Vec::new(),
2168 allow_approval: Vec::new(),
2169 budget: None,
2170 }
2171 }
2172
2173 #[test]
2174 fn ceiling_drops_effects_the_caller_was_not_granted() {
2175 let ceiling = Policy {
2176 allow_effects: ["io", "time"].iter().map(|s| s.to_string()).collect(),
2177 ..Policy::default()
2178 };
2179 let got = clamp_policy(permissive_request(), &ceiling);
2180 assert!(got.allow_effects.contains("io"));
2181 assert!(!got.allow_effects.contains("proc"), "proc must not survive a ceiling without it");
2182 assert!(!got.allow_effects.contains("fs_write"));
2183 assert!(!got.allow_effects.contains("net"));
2184 assert!(!got.allow_effects.contains("time"));
2186 }
2187
2188 #[test]
2189 fn ceiling_scopes_override_caller_scopes() {
2190 let ceiling = Policy {
2191 allow_effects: ["fs_read"].iter().map(|s| s.to_string()).collect(),
2192 allow_fs_read: vec![PathBuf::from("/srv/tenant")],
2193 ..Policy::default()
2194 };
2195 let got = clamp_policy(permissive_request(), &ceiling);
2196 assert_eq!(got.allow_fs_read, vec![PathBuf::from("/srv/tenant")]);
2199 assert!(got.allow_fs_write.is_empty());
2200 assert!(got.allow_proc.is_empty());
2201 assert!(got.allow_net_host.is_empty());
2202 }
2203
2204 #[test]
2205 fn ceiling_caps_budget_and_prefers_the_smaller() {
2206 let mut req = permissive_request();
2208 req.budget = None;
2209 let ceiling = Policy { budget: Some(1_000), ..Policy::default() };
2210 assert_eq!(clamp_policy(req, &ceiling).budget, Some(1_000));
2211
2212 let mut req2 = permissive_request();
2214 req2.budget = Some(50);
2215 let ceiling2 = Policy { budget: Some(1_000), ..Policy::default() };
2216 assert_eq!(clamp_policy(req2, &ceiling2).budget, Some(50));
2217 }
2218
2219 #[test]
2220 fn empty_ceiling_is_pure_only() {
2221 let got = clamp_policy(permissive_request(), &Policy::default());
2222 assert!(got.allow_effects.is_empty(), "an empty ceiling grants nothing");
2223 assert!(got.allow_proc.is_empty());
2224 assert!(got.allow_fs_write.is_empty());
2225 }
2226}
2227
2228#[cfg(test)]
2229mod public_read_tests {
2230 use super::*;
2231
2232 fn seed_pkg(root: &std::path::Path, name: &str, version: &str) {
2235 let record = PkgRecord {
2236 name: name.to_string(),
2237 version: version.to_string(),
2238 head_op: Some(format!("op-{name}")),
2239 published_at: 1,
2240 function_names: vec![format!("{name}.f")],
2241 ops: vec![],
2242 };
2243 save_pkg_record(root, &record, format!("ARCHIVE:{name}@{version}").as_bytes())
2244 .expect("seed package");
2245 }
2246
2247 #[test]
2248 fn new_package_defaults_to_private() {
2249 let tmp = tempfile::TempDir::new().unwrap();
2250 seed_pkg(tmp.path(), "lex-schema", "0.9.2");
2251 assert!(!pkg_is_public(tmp.path(), "lex-schema"));
2252 assert!(!pkg_is_public(tmp.path(), "does-not-exist"));
2254 }
2255
2256 #[test]
2257 fn set_visibility_round_trips_and_index_persists() {
2258 let tmp = tempfile::TempDir::new().unwrap();
2259 let state = State::open(tmp.path().to_path_buf()).unwrap();
2260 seed_pkg(tmp.path(), "lex-schema", "0.9.2");
2261
2262 let _ = pkg_set_visibility_handler(&state, "lex-schema", r#"{"visibility":"public"}"#);
2263 assert!(pkg_is_public(tmp.path(), "lex-schema"));
2264 let idx = load_pkg_index(tmp.path(), "lex-schema").unwrap();
2266 assert_eq!(idx.latest.as_deref(), Some("0.9.2"));
2267 assert_eq!(idx.versions.len(), 1);
2268
2269 let _ = pkg_set_visibility_handler(&state, "lex-schema", r#"{"visibility":"private"}"#);
2270 assert!(!pkg_is_public(tmp.path(), "lex-schema"));
2271 }
2272
2273 #[test]
2274 fn set_visibility_on_unknown_package_is_a_noop() {
2275 let tmp = tempfile::TempDir::new().unwrap();
2276 let state = State::open(tmp.path().to_path_buf()).unwrap();
2277 let _ = pkg_set_visibility_handler(&state, "ghost", r#"{"visibility":"public"}"#);
2279 assert!(load_pkg_index(tmp.path(), "ghost").is_none());
2280 }
2281
2282 #[test]
2283 fn public_listing_omits_private_packages() {
2284 let tmp = tempfile::TempDir::new().unwrap();
2285 let state = State::open(tmp.path().to_path_buf()).unwrap();
2286 seed_pkg(tmp.path(), "pub-pkg", "1.0.0");
2287 seed_pkg(tmp.path(), "priv-pkg", "1.0.0");
2288 let _ = pkg_set_visibility_handler(&state, "pub-pkg", r#"{"visibility":"public"}"#);
2289
2290 let names = public_pkg_names(tmp.path());
2291 assert_eq!(names, vec!["pub-pkg".to_string()]);
2292 }
2293
2294 #[test]
2295 fn resolve_public_maps_routes() {
2296 let get = Method::Get;
2297 assert_eq!(resolve_public(&get, "").unwrap(), PublicTarget::List);
2298 assert_eq!(resolve_public(&get, "/").unwrap(), PublicTarget::List);
2299 assert_eq!(
2300 resolve_public(&get, "/lex-schema").unwrap(),
2301 PublicTarget::Latest("lex-schema".into())
2302 );
2303 assert_eq!(
2304 resolve_public(&get, "/lex-schema/versions").unwrap(),
2305 PublicTarget::Versions("lex-schema".into())
2306 );
2307 assert_eq!(
2308 resolve_public(&get, "/lex-schema/head").unwrap(),
2309 PublicTarget::Head("lex-schema".into())
2310 );
2311 assert_eq!(
2312 resolve_public(&get, "/lex-schema/0.9.2").unwrap(),
2313 PublicTarget::Version("lex-schema".into(), "0.9.2".into())
2314 );
2315 assert_eq!(
2316 resolve_public(&get, "/lex-schema/0.9.2/archive").unwrap(),
2317 PublicTarget::Archive("lex-schema".into(), "0.9.2".into())
2318 );
2319 }
2320
2321 #[test]
2322 fn resolve_public_rejects_bad_method_and_traversal() {
2323 assert_eq!(resolve_public(&Method::Put, "/lex-schema"), Err(405));
2325 assert_eq!(resolve_public(&Method::Post, "").err(), Some(405));
2326 assert_eq!(resolve_public(&Method::Get, "/.."), Err(404));
2328 assert_eq!(resolve_public(&Method::Get, "/lex-schema/../etc"), Err(404));
2329 assert_eq!(resolve_public(&Method::Get, "/a/b/c/d"), Err(404));
2330 assert!(resolve_public(&Method::Get, "/lex schema").is_err());
2332 }
2333}