Skip to main content

agentmux_srv/server/app_api/
agent_export.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents export` (`POST /api/v1/agent/export`): one agent saved as a portable archive file (`.abf`, kind `agent`):
5//! its definition, Personal Memory and conversation in the history store's compact form (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER
6//! section 4, step A of the build). The file is written as a stream, never held in memory and never base64.
7//!
8//! **Who may ask:** the agent itself, or the agent that leads it (its seat's lead). Another agent's conversation is
9//! its own to share (`conversation_visibility`), so no other agent is let read it through here. **Where the file goes:**
10//! under the caller's own working folder, never over an existing file, and never outside it by `..` or a link. A
11//! container agent has no host folder to write to; its export arrives with the container step of the build.
12//! Each export, and each refusal, is recorded in the audit log under the calling agent.
13
14use std::io::BufWriter;
15use std::path::{Component, Path, PathBuf};
16
17use axum::extract::State;
18use axum::http::StatusCode;
19use axum::response::{IntoResponse, Response};
20use axum::{Extension, Json};
21use serde::Deserialize;
22use serde_json::{json, Value};
23
24use super::agent_lifecycle::{actor_of, refuse, Actor, Refusal};
25use crate::backend::agent_archive::build::{self, Inputs, Options};
26use crate::backend::agent_archive::Limits;
27use crate::server::caller::Caller;
28use crate::server::state::AppState;
29
30/// The audit entry's action.
31pub(crate) const AUDIT_ACTION: &str = "agent.export";
32/// The extension of an agent archive.
33const EXTENSION: &str = "abf";
34
35#[derive(Debug, Clone, Deserialize)]
36pub(crate) struct ExportRequest {
37    /// The agent's id, slug or name (default: the caller's own).
38    #[serde(default)]
39    agent: Option<String>,
40    /// What to put in: `memory`, `history` (default: both).
41    #[serde(default)]
42    include: Option<Vec<String>>,
43    /// Also withhold anything shaped like a key or token. A saved file does by default.
44    #[serde(default)]
45    scrub: Option<bool>,
46    /// Where to write it, under the caller's working folder (default: `exports/<slug>-<time>.abf` there).
47    #[serde(default)]
48    to: Option<String>,
49    /// A move by file: mark the agent handed over, stop it here and write the file, so it starts nowhere here until
50    /// `Agents bring_back` (the file is then imported on the other computer, as a move). Not for an agent's own export:
51    /// it would keep running; its leader or a person does it. A failed export puts the mark back as it was.
52    #[serde(default)]
53    hand_over: bool,
54    /// Where the agent is going, for the mark (`Agents move`: the computer's name; default `a file`). Not an argument of
55    /// the tool: only the move sets it.
56    #[serde(skip)]
57    hand_over_to: Option<String>,
58}
59
60impl ExportRequest {
61    /// The export a move makes: the agent stopped, marked handed over to the computer `to`, and written to a file.
62    pub(super) fn for_move(agent: &str, to: &str) -> Self {
63        Self { agent: Some(agent.to_string()), include: None, scrub: None, to: None, hand_over: true, hand_over_to: Some(to.to_string()) }
64    }
65}
66
67pub(crate) async fn handle_agent_export(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<ExportRequest>) -> Response {
68    let caller = caller.map(|Extension(c)| c);
69    match run(&state, caller.as_ref(), req).await {
70        Ok(body) => Json(body).into_response(),
71        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
72    }
73}
74
75async fn run(state: &AppState, caller: Option<&Caller>, req: ExportRequest) -> Result<Value, Refusal> {
76    let actor = actor_of(state, caller, "export")?;
77    let named = req.agent.clone().unwrap_or_else(|| actor.uid().to_string());
78    match run_as(state, &actor, req).await {
79        Ok(body) => {
80            audit(state, &actor, &named, true, None, &format!("wrote {}", body["path"].as_str().unwrap_or("")));
81            Ok(body)
82        }
83        Err(r) => {
84            audit(state, &actor, &named, false, Some(&r.message), "refused");
85            Err(r)
86        }
87    }
88}
89
90fn audit(state: &AppState, actor: &Actor, target: &str, ok: bool, error: Option<&str>, note: &str) {
91    let request_id = uuid::Uuid::new_v4().to_string();
92    let block_id = state.reactive_handler.block_for_uid(actor.uid()).unwrap_or_default();
93    let reason = format!("{} (uid {}): {note}", actor.slug(), actor.uid());
94    state.reactive_handler.log_fleet_action_audit(Some(actor.slug()), target, &block_id, AUDIT_ACTION, ok, error, &request_id, Some(&reason));
95}
96
97pub(super) async fn run_as(state: &AppState, actor: &Actor, req: ExportRequest) -> Result<Value, Refusal> {
98    let internal = |e: String| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}"));
99    let (memory, history) = parse_include(req.include.as_deref())?;
100    let scrub_shape = req.scrub.unwrap_or(true);
101
102    let mstore = state.mstore.clone();
103    let asked = req.agent.clone().unwrap_or_else(|| actor.uid().to_string());
104    let (target, caller_def) = {
105        let (mstore, actor_uid) = (mstore.clone(), actor.uid().to_string());
106        tokio::task::spawn_blocking(move || {
107            let uid = crate::backend::agent_resolve::resolve_agent_named(&mstore, asked.trim()).map_err(|e| refuse(StatusCode::NOT_FOUND, format!("no agent '{}' on this machine: {e}", asked.trim())))?;
108            let target = mstore.agent_def_get(&uid).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}")))?;
109            let caller_def = mstore.agent_def_get(&actor_uid).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}")))?;
110            Ok::<_, Refusal>((target, caller_def))
111        })
112        .await
113        .map_err(|e| internal(e.to_string()))??
114    };
115    let target = target.ok_or_else(|| refuse(StatusCode::NOT_FOUND, "no such agent on this machine"))?;
116    let caller_def = caller_def.ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
117
118    if !actor.is_person() && target.id != caller_def.id && crate::backend::agent_seat::effective_seat_by_id(&state.mstore, &target.id).and_then(|s| s.lead).as_deref() != Some(caller_def.id.as_str()) {
119        return Err(refuse(
120            StatusCode::FORBIDDEN,
121            format!("Agents export saves your own conversation, or that of an agent you lead; {} is neither. Its conversation is shared through its own visibility setting.", target.name),
122        ));
123    }
124    // The file is written on this computer for the agent the person named, not for the agent that signs for them.
125    let writer = if actor.is_person() { &target } else { &caller_def };
126    if writer.runtime() != crate::backend::runtime_adapter::RuntimeKind::Host {
127        return Err(refuse(
128            StatusCode::FORBIDDEN,
129            "a container agent has no folder on this computer to write the file to; exporting from a container agent arrives with the container step of the move build. Ask an agent that runs natively, or the person in My Agents.",
130        ));
131    }
132
133    if req.hand_over && !actor.is_person() && target.id == actor.uid() {
134        return Err(refuse(
135            StatusCode::CONFLICT,
136            "an agent cannot hand itself over: it keeps running and receiving messages until it is stopped, so it would still be alive here when the file is imported elsewhere. Ask the agent that leads it, or the person in My Agents, to export it with hand_over: true.",
137        ));
138    }
139    // The mark goes on before the agent is stopped and the file is built, so no start or message can bring it back to life in between.
140    let _one_at_a_time = if req.hand_over { Some(claim_hand_over(&target)?) } else { None };
141    let prior = if req.hand_over { Some(raise_fence(state, actor, &target).await?) } else { None };
142    let written = write_archive(state, &target, writer, req.to.as_deref(), (memory, history, scrub_shape)).await;
143    let (file, report, bytes) = match written {
144        Ok(w) => w,
145        Err(r) => {
146            if let Some(prior) = prior {
147                let _ = state.mstore.agent_handover_set(&target.id, prior.as_ref());
148            }
149            return Err(r);
150        }
151    };
152
153    let signed = report.manifest.signature.is_some();
154    let manifest_hash = crate::backend::memory::record::sha256_hex(&report.manifest.signed_bytes());
155    let handed_over = if req.hand_over {
156        super::agent_handover::mark_handed_over(state, &target, req.hand_over_to.as_deref().unwrap_or("a file"), &manifest_hash)
157            .map_err(|e| internal(format!("the file is written, but the agent could not be marked as handed over: {e}")))?;
158        true
159    } else {
160        false
161    };
162    Ok(json!({
163        "handed_over": handed_over,
164        "manifest_hash": manifest_hash,
165        "path": file.to_string_lossy().replace('\\', "/"),
166        "bytes": bytes,
167        "agent": { "uid": report.manifest.agent.uid, "name": report.manifest.agent.name },
168        "parts": report.manifest.parts.iter().map(|p| json!({ "path": p.path, "bytes": p.size })).collect::<Vec<_>>(),
169        "memory_files": report.memory_files,
170        "sessions": report.sessions,
171        "signed": signed,
172        "key_shapes_withheld": scrub_shape,
173        "warnings": report.warnings,
174        "not_in_it": "Vault values and grants, API keys and account sign-ins, the agent's keys, its browser sign-ins, Global Memory, other agents, its working folder's files and the provider's own session file. The history is carried as it is: a secret someone pasted into the conversation that is not a value AgentMux holds is in the file.",
175    }))
176}
177
178/// Builds and writes the file: under the caller's working folder, from a frozen read of the agent's stores.
179async fn write_archive(
180    state: &AppState,
181    target: &crate::backend::storage::AgentDefinition,
182    caller_def: &crate::backend::storage::AgentDefinition,
183    to: Option<&str>,
184    (memory, history, scrub_shape): (bool, bool, bool),
185) -> Result<(PathBuf, build::Report, u64), Refusal> {
186    let internal = |e: String| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}"));
187    let base = PathBuf::from(crate::backend::project_instructions::effective_working_dir(&caller_def.working_directory, &caller_def.name));
188    let stamp = agentmux_common::time::now_ms();
189    let file = resolve_output(&base, to, &format!("{}-{stamp}.{EXTENSION}", target.slug))?;
190
191    let (instance_id, host_hint, key) = match crate::backend::storage::wan_identity::global().and_then(|w| w.instance_ensure(&crate::backend::reactive::registry::local_host_label()).ok()) {
192        Some(i) => (i.instance_id, i.host_hint, Some(i.private_key)),
193        None => (String::new(), String::new(), None),
194    };
195    let opts = Options { memory, history, scrub_shape, app_version: env!("CARGO_PKG_VERSION").to_string(), instance_id, host_hint };
196    let mstore = state.mstore.clone();
197    let id_store = state.id_store.clone();
198    let transcripts = state.global_transcript_store.clone();
199    let out_path = file.clone();
200    let build_target = target.clone();
201    let (report, bytes) = tokio::task::spawn_blocking(move || -> Result<_, String> {
202        let handle = std::fs::OpenOptions::new().write(true).create_new(true).open(&out_path).map_err(|e| format!("cannot create {}: {e}", out_path.display()))?;
203        let inputs = Inputs { mstore: &mstore, id_store: &id_store, transcripts: transcripts.as_deref() };
204        let sign = move |bytes: &[u8]| -> Option<([u8; 32], [u8; 64])> {
205            let seed = key?;
206            let signing = ed25519_dalek::SigningKey::from_bytes(&seed);
207            Some((signing.verifying_key().to_bytes(), ed25519_dalek::Signer::sign(&signing, bytes).to_bytes()))
208        };
209        let signer: Option<&dyn Fn(&[u8]) -> Option<([u8; 32], [u8; 64])>> = Some(&sign);
210        let built = build::build(BufWriter::new(handle), &build_target, &inputs, &opts, Limits::default(), signer);
211        match built {
212            Ok((report, out)) => {
213                let file = out.into_inner().map_err(|e| e.to_string())?;
214                file.sync_all().map_err(|e| e.to_string())?;
215                let bytes = file.metadata().map(|m| m.len()).unwrap_or(0);
216                Ok((report, bytes))
217            }
218            Err(e) => {
219                let _ = std::fs::remove_file(&out_path);
220                Err(e.to_string())
221            }
222        }
223    })
224    .await
225    .map_err(|e| internal(e.to_string()))?
226    .map_err(internal)?;
227    Ok((file, report, bytes))
228}
229
230/// A move by file marks the agent handed over first, then stops it through the normal stop path, so nothing can start it or
231/// reach a live process between the stop and the file, and nothing writes to its conversation after the file is made.
232/// Returns the mark it had before, to put back if the export fails. A refusal puts it back too.
233async fn raise_fence(state: &AppState, actor: &Actor, target: &crate::backend::storage::AgentDefinition) -> Result<Option<crate::registry::Handover>, Refusal> {
234    refuse_if_shutdown_unconfirmable(state, target)?;
235    let prior = state.mstore.agent_handover_get(&target.id).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}")))?;
236    if prior.as_ref().is_some_and(|m| m.state == crate::registry::Handover::MOVED) {
237        return Err(refuse(
238            StatusCode::CONFLICT,
239            format!("{} already moved to another computer and may be running there. Bring it back first (Agents bring_back with force: true, only if it is not running there), then hand it over again.", target.name),
240        ));
241    }
242    super::agent_handover::mark_handed_over(state, target, "a file", "").map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: the agent could not be marked as handed over: {e}")))?;
243    if let Err(r) = quiesce(state, actor, target).await {
244        let _ = state.mstore.agent_handover_set(&target.id, prior.as_ref());
245        return Err(r);
246    }
247    Ok(prior)
248}
249
250/// The agents a hand-over is under way for in this srv: a second one for the same agent would put back a mark the first
251/// had already settled, so it is refused while the first runs.
252static HAND_OVERS_IN_FLIGHT: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::LazyLock::new(Default::default);
253
254/// Held for the length of one hand-over; dropping it lets the next begin.
255pub(super) struct HandOverClaim(String);
256
257impl Drop for HandOverClaim {
258    fn drop(&mut self) {
259        HAND_OVERS_IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
260    }
261}
262
263/// Whether a hand-over of agent `uid` is under way in this srv: `bring_back` waits for it rather than clear the mark under it.
264pub(super) fn hand_over_in_flight(uid: &str) -> bool {
265    HAND_OVERS_IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()).contains(uid)
266}
267
268pub(super) fn claim_hand_over(target: &crate::backend::storage::AgentDefinition) -> Result<HandOverClaim, Refusal> {
269    if !HAND_OVERS_IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()).insert(target.id.clone()) {
270        return Err(refuse(StatusCode::CONFLICT, format!("{} is already being handed over: wait for that to finish.", target.name)));
271    }
272    Ok(HandOverClaim(target.id.clone()))
273}
274
275/// This build can confirm that a stopped agent has finished shutting down only for the controller most agents run on. An
276/// agent in a pane with another kind of controller (ACP, App Server, a plain subprocess) stops asynchronously with nothing
277/// to wait on, so a file made right after could lack its last output: refused until those controllers report it.
278fn refuse_if_shutdown_unconfirmable(state: &AppState, target: &crate::backend::storage::AgentDefinition) -> Result<(), Refusal> {
279    let Some(ctrl) = state.reactive_handler.block_for_uid(&target.id).and_then(|b| crate::backend::blockcontroller::get_controller(&b)) else {
280        return Ok(()); // no pane: nothing of it is running here
281    };
282    if ctrl.as_any().downcast_ref::<crate::backend::blockcontroller::persistent::PersistentSubprocessController>().is_some() {
283        return Ok(());
284    }
285    Err(refuse(
286        StatusCode::CONFLICT,
287        format!("{} runs on a provider whose shutdown this build cannot yet confirm, so a file made right after stopping it could miss its last output. Nothing was changed. Moving it arrives with the transfer step of the move build.", target.name),
288    ))
289}
290
291/// How long a stopped agent is given to finish shutting down before the export is refused.
292const TEARDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
293
294/// Waits until no pane of this process holds agent `uid`'s lease, which its process releases as the last step of its teardown.
295pub(super) async fn wait_for_teardown(uid: &str, limit: std::time::Duration) -> Result<(), ()> {
296    let deadline = std::time::Instant::now() + limit;
297    while crate::backend::blockcontroller::persistent::lifecycle::local_holder_of(uid, "").is_some() {
298        if std::time::Instant::now() >= deadline {
299            return Err(());
300        }
301        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
302    }
303    Ok(())
304}
305
306async fn quiesce(state: &AppState, actor: &Actor, target: &crate::backend::storage::AgentDefinition) -> Result<(), Refusal> {
307    let stopped = super::agent_lifecycle::stop(state, actor, &super::agent_lifecycle::LifecycleRequest::of(&target.id)).await?;
308    if stopped.get("pending").is_some_and(|p| !p.is_null()) {
309        return Err(refuse(
310            StatusCode::CONFLICT,
311            format!("{} has not stopped yet: its user has 30 seconds to keep it running. Try again once it has stopped; nothing was written.", target.name),
312        ));
313    }
314    // The stop returns when the kill is sent. The pane lets go of the agent's lease only once the process is gone, its output
315    // read to the end and the conversation's last segment closed, so the file is not built before then.
316    wait_for_teardown(&target.id, TEARDOWN_WAIT).await.map_err(|_| {
317        refuse(StatusCode::CONFLICT, format!("{} is still shutting down. Nothing was written; try again in a few seconds.", target.name))
318    })?;
319    // The stop above reaches this AgentMux's own panes only. An agent that runs in another AgentMux on this computer holds
320    // the host-wide lease; a file made now would leave it running there, so the export waits until it has stopped there.
321    crate::backend::agent_admission::check_before_spawn(
322        crate::backend::agent_admission::lease_store_for(state.mstore.shared_agent_registry()),
323        &target.id,
324        &target.name,
325        &state.boot_id,
326    )
327    .await
328    .map_err(|why| refuse(StatusCode::CONFLICT, format!("{} is running in another AgentMux on this computer, so it cannot be handed over from here: stop it there first. Nothing was written. ({why})", target.name)))?;
329    Ok(())
330}
331
332fn parse_include(include: Option<&[String]>) -> Result<(bool, bool), Refusal> {
333    let Some(list) = include else { return Ok((true, true)) };
334    let (mut memory, mut history) = (false, false);
335    for item in list {
336        match item.as_str() {
337            "memory" => memory = true,
338            "history" => history = true,
339            other => return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: include {other:?}: this build carries memory and history (the working folder's files and the provider's session file come with later steps)"))),
340        }
341    }
342    Ok((memory, history))
343}
344
345/// The file to write: `to` under `base` (relative, or absolute inside it), or `exports/<default_name>` there.
346/// Never an existing file, never a name with `..`, never through a link that leaves `base`.
347pub(crate) fn resolve_output(base: &Path, to: Option<&str>, default_name: &str) -> Result<PathBuf, Refusal> {
348    let bad = |m: String| refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: to: {m}"));
349    std::fs::create_dir_all(base).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: your working folder {} is not usable: {e}", base.display())))?;
350    let root = base.canonicalize().map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}")))?;
351    let wanted = match to.map(str::trim).filter(|t| !t.is_empty()) {
352        Some(t) => {
353            let p = Path::new(t);
354            if p.components().any(|c| matches!(c, Component::ParentDir)) {
355                return Err(bad("a path with .. is not allowed".to_string()));
356            }
357            if p.is_absolute() { p.to_path_buf() } else { root.join(p) }
358        }
359        None => root.join("exports").join(default_name),
360    };
361    if wanted.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() != Some(EXTENSION) {
362        return Err(bad(format!("the file ends in .{EXTENSION}")));
363    }
364    let Some(parent) = wanted.parent() else { return Err(bad("no folder to write in".to_string())) };
365    // The folder is made under the root only after the lexical check that it is under it.
366    let lexical_parent: PathBuf = parent.components().collect();
367    // The folder is named in any of its spellings: canonical (`\?\` on Windows), plain, or as it was given.
368    if !lexical_parent.starts_with(&root) && !lexical_parent.starts_with(plain(root.clone())) && !lexical_parent.starts_with(base) {
369        return Err(bad(format!("the file goes under your working folder, {}", root.display())));
370    }
371    // Nothing is made before the deepest folder that exists is known to be inside the root: a link in the working
372    // folder that leads out would otherwise get a folder made beyond it before the request was refused.
373    let mut existing = parent;
374    while std::fs::symlink_metadata(existing).is_err() {
375        match existing.parent() {
376            Some(up) => existing = up,
377            None => break,
378        }
379    }
380    let real_existing = existing.canonicalize().map_err(|_| bad(format!("{} is not a folder that can be written in", existing.display())))?;
381    if !real_existing.starts_with(&root) {
382        return Err(bad(format!("that folder leads outside your working folder, {}", root.display())));
383    }
384    std::fs::create_dir_all(parent).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: cannot make {}: {e}", parent.display())))?;
385    let real_parent = parent.canonicalize().map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents export: {e}")))?;
386    if !real_parent.starts_with(&root) {
387        return Err(bad(format!("that folder leads outside your working folder, {}", root.display())));
388    }
389    let name = wanted.file_name().ok_or_else(|| bad("no file name".to_string()))?;
390    let file = plain(real_parent.join(name));
391    if file.exists() {
392        return Err(refuse(StatusCode::CONFLICT, format!("{} exists; Agents export never overwrites: choose another name", file.display())));
393    }
394    Ok(file)
395}
396
397/// The archive to read: `file` under `base` (relative, or absolute inside it), an existing regular `.abf` file, reached by
398/// no `..` and no link that leaves `base`. The same folder `Agents export` writes to, so a file an agent or the person put
399/// there is the one it imports.
400pub(crate) fn resolve_input(base: &Path, file: &str) -> Result<PathBuf, (StatusCode, String)> {
401    let bad = |m: String| (StatusCode::BAD_REQUEST, format!("INVALID_ARG: file: {m}"));
402    let file = file.trim();
403    if file.is_empty() {
404        return Err(bad("give the archive: a name or path ending .abf under your working folder".to_string()));
405    }
406    let root = base.canonicalize().map_err(|_| bad(format!("your working folder {} does not exist yet, so there is no file in it", base.display())))?;
407    let p = Path::new(file);
408    if p.components().any(|c| matches!(c, Component::ParentDir)) {
409        return Err(bad("a path with .. is not allowed".to_string()));
410    }
411    let wanted = if p.is_absolute() { p.to_path_buf() } else { root.join(p) };
412    if wanted.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() != Some(EXTENSION) {
413        return Err(bad(format!("the file ends in .{EXTENSION}")));
414    }
415    let real = wanted.canonicalize().map_err(|_| (StatusCode::NOT_FOUND, format!("no file {}", wanted.display())))?;
416    if !real.starts_with(&root) {
417        return Err(bad(format!("the file is read from under your working folder, {}", root.display())));
418    }
419    if !real.is_file() {
420        return Err(bad(format!("{} is not a file", real.display())));
421    }
422    Ok(plain(real))
423}
424
425/// The path without the `\?\` prefix a canonical Windows path carries, which nothing a person reads should show.
426fn plain(path: PathBuf) -> PathBuf {
427    let text = path.to_string_lossy();
428    match text.strip_prefix(r"\\?\") {
429        Some(rest) if !rest.starts_with("UNC\\") => PathBuf::from(rest.to_string()),
430        _ => path,
431    }
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437
438    #[test]
439    fn the_file_goes_under_the_working_folder_and_nowhere_else() {
440        let dir = tempfile::tempdir().unwrap();
441        let base = dir.path().join("work");
442        let ok = resolve_output(&base, None, "a-1.abf").map_err(|r| r.message).unwrap();
443        assert!(ok.ends_with("exports/a-1.abf") || ok.ends_with("exports\\a-1.abf"), "{ok:?}");
444        assert!(resolve_output(&base, Some("keep/me.abf"), "x.abf").is_ok());
445        // The path a first export answered with (the plain spelling of the canonical folder) names a file in it too.
446        let named = plain(base.canonicalize().unwrap()).join("again.abf");
447        assert!(resolve_output(&base, Some(named.to_str().unwrap()), "x.abf").is_ok(), "{named:?}");
448        for bad in ["../out.abf", "a/../../out.abf", "notes.txt", "x.abf.exe", ""] {
449            let r = resolve_output(&base, Some(bad), "d.abf");
450            assert!(bad.is_empty() && r.is_ok() || r.is_err(), "{bad}");
451        }
452        let outside = dir.path().join("elsewhere").join("x.abf");
453        let err = resolve_output(&base, Some(outside.to_str().unwrap()), "d.abf").unwrap_err();
454        assert_eq!(err.status, StatusCode::BAD_REQUEST, "{}", err.message);
455    }
456
457    #[test]
458    fn an_existing_file_is_never_overwritten() {
459        let dir = tempfile::tempdir().unwrap();
460        let first = resolve_output(dir.path(), Some("a.abf"), "d.abf").map_err(|r| r.message).unwrap();
461        std::fs::write(&first, b"x").unwrap();
462        let err = resolve_output(dir.path(), Some("a.abf"), "d.abf").unwrap_err();
463        assert_eq!(err.status, StatusCode::CONFLICT);
464    }
465
466    #[cfg(unix)]
467    #[test]
468    fn a_folder_that_is_a_link_out_of_the_working_folder_is_refused() {
469        let dir = tempfile::tempdir().unwrap();
470        let base = dir.path().join("work");
471        std::fs::create_dir_all(&base).unwrap();
472        let outside = dir.path().join("outside");
473        std::fs::create_dir_all(&outside).unwrap();
474        std::os::unix::fs::symlink(&outside, base.join("link")).unwrap();
475        assert!(resolve_output(&base, Some("link/x.abf"), "d.abf").is_err());
476    }
477
478    #[cfg(unix)]
479    #[test]
480    fn a_new_folder_under_a_link_that_leaves_the_working_folder_is_not_made() {
481        let dir = tempfile::tempdir().unwrap();
482        let base = dir.path().join("work");
483        std::fs::create_dir_all(&base).unwrap();
484        let outside = dir.path().join("outside");
485        std::fs::create_dir_all(&outside).unwrap();
486        std::os::unix::fs::symlink(&outside, base.join("link")).unwrap();
487        assert!(resolve_output(&base, Some("link/newdir/x.abf"), "d.abf").is_err());
488        assert!(!outside.join("newdir").exists(), "refused before anything was made beyond the link");
489        // A link to nowhere is refused as well, and makes nothing.
490        std::os::unix::fs::symlink(dir.path().join("nowhere"), base.join("dangling")).unwrap();
491        assert!(resolve_output(&base, Some("dangling/x.abf"), "d.abf").is_err());
492        assert!(!dir.path().join("nowhere").exists());
493    }
494
495    #[test]
496    fn an_archive_is_read_only_from_under_the_working_folder() {
497        let dir = tempfile::tempdir().unwrap();
498        let base = dir.path().join("work");
499        std::fs::create_dir_all(base.join("in")).unwrap();
500        std::fs::write(base.join("in/a.abf"), b"x").unwrap();
501        std::fs::write(base.join("in/a.txt"), b"x").unwrap();
502        std::fs::write(dir.path().join("outside.abf"), b"x").unwrap();
503        assert!(resolve_input(&base, "in/a.abf").is_ok());
504        assert!(resolve_input(&base, base.join("in/a.abf").to_str().unwrap()).is_ok());
505        for (bad, status) in [
506            ("../outside.abf", StatusCode::BAD_REQUEST),
507            ("in/a.txt", StatusCode::BAD_REQUEST),
508            ("in", StatusCode::BAD_REQUEST),
509            ("in/none.abf", StatusCode::NOT_FOUND),
510            ("", StatusCode::BAD_REQUEST),
511        ] {
512            let err = resolve_input(&base, bad).unwrap_err();
513            assert_eq!(err.0, status, "{bad}: {}", err.1);
514        }
515        let outside = dir.path().join("outside.abf");
516        assert_eq!(resolve_input(&base, outside.to_str().unwrap()).unwrap_err().0, StatusCode::BAD_REQUEST);
517    }
518
519    #[test]
520    fn include_takes_memory_and_history_and_nothing_else() {
521        assert_eq!(parse_include(None).map_err(|r| r.message).unwrap(), (true, true));
522        assert_eq!(parse_include(Some(&["history".to_string()])).map_err(|r| r.message).unwrap(), (false, true));
523        assert!(parse_include(Some(&["workspace".to_string()])).is_err());
524    }
525}
526
527#[cfg(test)]
528#[path = "tests/agent_export_tests.rs"]
529mod handler_tests;