Skip to main content

rightkit_document_workspace/
markdown_resources.rs

1//! Markdown reference inspection and pasted-asset staging (save, commit, roll back). Every
2//! function is synchronous; the host runs them off its IPC thread.
3
4use crate::error::{broker_error, WorkspaceError};
5use crate::grants::PathGrants;
6use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
7use rightkit_fs::atomic::create_dir_all_durable;
8use rightkit_fs::digest::sha256_bytes;
9use rightkit_fs::{
10    atomic_write_with_options, canonicalize_plain, contain, contain_lenient, numbered_candidates,
11    AtomicWriteOptions, FsError, ReplaceMode,
12};
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::io::Write;
16use std::path::{Component, Path, PathBuf};
17use std::sync::Mutex;
18
19const MAX_ASSET_BYTES: usize = 20 * 1024 * 1024;
20const MAX_MARKDOWN_TARGET_BYTES: u64 = 2 * 1024 * 1024;
21const MAX_INSPECTION_REQUESTS: usize = 128;
22const ALLOWED_MIMES: &[&str] = &["png", "jpeg", "webp", "gif", "svg"];
23
24#[derive(Debug, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct SaveMarkdownAssetRequest {
27    pub payload_base64: String,
28    pub hint_name: String,
29    pub mime_kind: String,
30    pub document_path: String,
31    #[serde(default)]
32    pub assets_folder: Option<String>,
33}
34
35#[derive(Debug, Serialize)]
36#[serde(rename_all = "camelCase")]
37pub struct SavedMarkdownAsset {
38    pub relative_path: String,
39    pub absolute_path: String,
40    pub reused_existing: bool,
41    pub byte_length: usize,
42    pub rollback_token: Option<String>,
43}
44
45#[derive(Debug, Deserialize)]
46#[serde(rename_all = "camelCase")]
47pub struct RollbackMarkdownAssetRequest {
48    pub rollback_token: String,
49}
50
51#[derive(Debug, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct CommitMarkdownAssetRequest {
54    pub rollback_token: String,
55}
56
57#[derive(Debug, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct MarkdownResourceRequest {
60    pub raw_url: String,
61    pub need_text: bool,
62}
63
64#[derive(Debug, Serialize)]
65#[serde(rename_all = "camelCase")]
66pub struct MarkdownResourceResult {
67    pub raw_url: String,
68    pub path_part: String,
69    pub exists: bool,
70    pub is_file: bool,
71    pub format: Option<String>,
72    pub granted_path: Option<String>,
73    pub text: Option<String>,
74    pub error: Option<String>,
75}
76
77/// Inspect explicitly referenced local resources only. This never enumerates a directory; each
78/// target remains contained within the opened document folder.
79pub fn inspect_markdown_resources(
80    grants: &dyn PathGrants,
81    document_path: &str,
82    requests: Vec<MarkdownResourceRequest>,
83) -> Result<Vec<MarkdownResourceResult>, WorkspaceError> {
84    check_inspection_request_count(requests.len())?;
85    let authorized = grants
86        .require_existing_file(document_path)
87        .map_err(broker_error)?;
88    let document = PathBuf::from(authorized);
89    let root = std::fs::canonicalize(
90        document
91            .parent()
92            .ok_or_else(|| WorkspaceError::Other("no-document-parent".to_string()))?,
93    )
94    .map_err(|e| WorkspaceError::Io(format!("canonicalize markdown root: {e}")))?;
95    Ok(requests
96        .into_iter()
97        .map(|request| inspect_resource(&root, request, grants))
98        .collect())
99}
100
101fn check_inspection_request_count(count: usize) -> Result<(), WorkspaceError> {
102    if count > MAX_INSPECTION_REQUESTS {
103        return Err(WorkspaceError::DocumentTooLarge(format!(
104            "markdown resource inspection exceeds {MAX_INSPECTION_REQUESTS} requests"
105        )));
106    }
107    Ok(())
108}
109
110fn inspect_resource(
111    root: &Path,
112    request: MarkdownResourceRequest,
113    grants: &dyn PathGrants,
114) -> MarkdownResourceResult {
115    let path_part = split_local_url(&request.raw_url);
116    let mut result = MarkdownResourceResult {
117        raw_url: request.raw_url,
118        path_part: path_part.clone(),
119        exists: false,
120        is_file: false,
121        format: None,
122        granted_path: None,
123        text: None,
124        error: None,
125    };
126    let relative = match safe_relative_reference(&path_part) {
127        Ok(path) => path,
128        Err(error) => {
129            result.error = Some(error);
130            return result;
131        }
132    };
133    let target = match std::fs::canonicalize(root.join(relative)) {
134        Ok(path) => path,
135        Err(_) => {
136            result.error = Some("missing-target".to_string());
137            return result;
138        }
139    };
140    if !target.starts_with(root) {
141        result.error = Some("path-escape".to_string());
142        return result;
143    }
144    let metadata = match std::fs::metadata(&target) {
145        Ok(meta) => meta,
146        Err(_) => {
147            result.error = Some("missing-target".to_string());
148            return result;
149        }
150    };
151    result.exists = true;
152    result.is_file = metadata.is_file();
153    if !metadata.is_file() {
154        result.error = Some("not-a-file".to_string());
155        return result;
156    }
157    let format = markdown_format(&target);
158    result.format = format.map(str::to_string);
159    if format.is_none() {
160        result.error = Some("unsupported-format".to_string());
161        return result;
162    }
163    if request.need_text && format.is_some() {
164        if metadata.len() > MAX_MARKDOWN_TARGET_BYTES {
165            result.error = Some("target-too-large".to_string());
166            return result;
167        }
168        match std::fs::read_to_string(&target) {
169            Ok(text) => result.text = Some(text),
170            Err(_) => {
171                result.error = Some("read-failed".to_string());
172                return result;
173            }
174        }
175    }
176    // Inspection can only extend a file grant for a Markdown document. This
177    // prevents this command from becoming a same-folder arbitrary-file grant.
178    match grants.grant_existing_file_path(&target) {
179        Ok(path) => result.granted_path = Some(path),
180        Err(_) => result.error = Some("grant-failed".to_string()),
181    }
182    result
183}
184
185fn split_local_url(raw: &str) -> String {
186    raw.split(['?', '#']).next().unwrap_or_default().to_string()
187}
188
189fn safe_relative_reference(raw: &str) -> Result<PathBuf, String> {
190    let decoded = percent_decode(raw)?;
191    if decoded.is_empty()
192        || decoded.contains('\0')
193        || decoded.starts_with('/')
194        || decoded.starts_with('\\')
195        || decoded.contains("://")
196        || decoded.as_bytes().get(1) == Some(&b':')
197    {
198        return Err("invalid-reference-path".to_string());
199    }
200    let path = Path::new(&decoded);
201    if path
202        .components()
203        .any(|part| !matches!(part, Component::Normal(_)))
204    {
205        return Err("invalid-reference-path".to_string());
206    }
207    Ok(path.to_path_buf())
208}
209
210/// Strict percent-decoder for a reference path: every `%` must start two hex digits and the decoded
211/// bytes must be valid UTF-8, otherwise the whole reference is refused (and `+` stays `+`).
212/// `rightkit_http::percent_decode_component` keeps a malformed escape as written and replaces
213/// invalid UTF-8 lossily, so it cannot answer "was this input well formed"; the hex digits come
214/// from the shared `rightkit_fs::digest::unhex`.
215fn percent_decode(raw: &str) -> Result<String, String> {
216    let bytes = raw.as_bytes();
217    let mut out = Vec::with_capacity(bytes.len());
218    let mut index = 0;
219    while index < bytes.len() {
220        if bytes[index] == b'%' {
221            let byte = raw
222                .get(index + 1..index + 3)
223                .and_then(rightkit_fs::digest::unhex)
224                .and_then(|decoded| decoded.first().copied())
225                .ok_or_else(|| "invalid-percent-encoding".to_string())?;
226            out.push(byte);
227            index += 3;
228        } else {
229            out.push(bytes[index]);
230            index += 1;
231        }
232    }
233    String::from_utf8(out).map_err(|_| "invalid-percent-encoding".to_string())
234}
235
236fn markdown_format(path: &Path) -> Option<&'static str> {
237    match path
238        .extension()
239        .and_then(|ext| ext.to_str())
240        .map(|ext| ext.to_ascii_lowercase())
241        .as_deref()
242    {
243        Some("md") => Some("md"),
244        Some("markdown") => Some("markdown"),
245        Some("mdx") => Some("mdx"),
246        _ => None,
247    }
248}
249
250#[derive(Debug)]
251struct PendingAsset {
252    path: PathBuf,
253    parent: PathBuf,
254    byte_length: u64,
255    digest: String,
256}
257
258/// Staged-asset transactions awaiting commit or rollback, keyed by rollback token.
259#[derive(Default)]
260pub struct MarkdownAssetTransactions {
261    pending: Mutex<HashMap<String, PendingAsset>>,
262}
263
264/// Validate and stage a pasted asset next to the document: decode, type and size checks, an
265/// assets folder contained in the document's folder, content-addressed dedupe, and a pending
266/// transaction the caller later commits or rolls back.
267pub fn save_markdown_asset(
268    req: SaveMarkdownAssetRequest,
269    grants: &dyn PathGrants,
270    transactions: &MarkdownAssetTransactions,
271) -> Result<SavedMarkdownAsset, WorkspaceError> {
272    let mime_kind = req.mime_kind.to_lowercase();
273    if !ALLOWED_MIMES.contains(&mime_kind.as_str()) {
274        return Err(WorkspaceError::Other(format!(
275            "mime-not-allowed: {mime_kind}"
276        )));
277    }
278    let bytes = BASE64
279        .decode(req.payload_base64.as_bytes())
280        .map_err(|e| WorkspaceError::Other(format!("base64-decode-failed: {e}")))?;
281    if bytes.len() > MAX_ASSET_BYTES {
282        return Err(WorkspaceError::Other(format!(
283            "size-limit: {} bytes exceeds {}",
284            bytes.len(),
285            MAX_ASSET_BYTES
286        )));
287    }
288    if mime_kind == "svg" && !is_safe_svg(&bytes) {
289        return Err(WorkspaceError::Other(
290            "svg-unsafe: forbidden element or attribute".to_string(),
291        ));
292    }
293
294    let authorized_doc = grants
295        .require_existing_file(&req.document_path)
296        .map_err(broker_error)?;
297    let doc_path = PathBuf::from(authorized_doc);
298    let doc_parent = doc_path
299        .parent()
300        .ok_or_else(|| WorkspaceError::Other("no-document-parent".to_string()))?;
301    let folder_name = req.assets_folder.unwrap_or_else(|| {
302        format!(
303            "{}.assets",
304            doc_path
305                .file_stem()
306                .and_then(|s| s.to_str())
307                .unwrap_or("document")
308        )
309    });
310    validate_relative_folder(&folder_name)?;
311
312    let canonical_parent = canonicalize_plain(doc_parent)
313        .map_err(|e| WorkspaceError::Io(format!("canonicalize document parent: {e}")))?;
314    // The assets folder may not exist yet: resolve it leniently (the deepest existing ancestor is
315    // followed through links and must stay inside the document's folder), create it, then resolve
316    // it again strictly so nothing that was created can lead out.
317    let planned_assets = contain_lenient(&canonical_parent, &folder_name).map_err(escape_error)?;
318    create_dir_all_durable(&planned_assets, false)
319        .map_err(|e| WorkspaceError::Io(format!("create assets dir: {}", fs_error_text(e))))?;
320    let canonical_assets = contain(&canonical_parent, &folder_name).map_err(escape_error)?;
321
322    let digest = sha256_bytes(&bytes);
323    let base_name = compute_file_name(&req.hint_name, &digest, &mime_kind);
324    let (target, reused_existing) = store_asset(&canonical_assets, &base_name, &bytes, &digest)?;
325    if reused_existing {
326        return Ok(SavedMarkdownAsset {
327            relative_path: relative_path(&canonical_parent, &target),
328            absolute_path: target.to_string_lossy().to_string(),
329            reused_existing: true,
330            byte_length: bytes.len(),
331            rollback_token: None,
332        });
333    }
334
335    let target_name = target
336        .file_name()
337        .map(PathBuf::from)
338        .ok_or_else(|| WorkspaceError::Other("asset target has no file name".to_string()))?;
339    let canonical_target = match contain(&canonical_assets, &target_name) {
340        Ok(path) => path,
341        Err(error) => {
342            let _ = std::fs::remove_file(&target);
343            return Err(escape_error(error));
344        }
345    };
346
347    let token = random_token()?;
348    transactions
349        .pending
350        .lock()
351        .map_err(|_| WorkspaceError::Other("asset transaction lock poisoned".to_string()))?
352        .insert(
353            token.clone(),
354            PendingAsset {
355                path: canonical_target.clone(),
356                parent: canonical_assets,
357                byte_length: bytes.len() as u64,
358                digest,
359            },
360        );
361    Ok(SavedMarkdownAsset {
362        relative_path: relative_path(&canonical_parent, &canonical_target),
363        absolute_path: canonical_target.to_string_lossy().to_string(),
364        reused_existing: false,
365        byte_length: bytes.len(),
366        rollback_token: Some(token),
367    })
368}
369
370/// Roll back a staged asset: re-stat, re-read and delete the file, refusing if it changed after
371/// creation. Consumes the token.
372pub fn rollback_markdown_asset(
373    transactions: &MarkdownAssetTransactions,
374    token: &str,
375) -> Result<bool, WorkspaceError> {
376    let Some(pending) = take_pending(transactions, token)? else {
377        return Ok(false);
378    };
379    let canonical_parent = canonicalize_plain(
380        pending
381            .path
382            .parent()
383            .ok_or_else(|| WorkspaceError::Other("rollback path has no parent".to_string()))?,
384    )
385    .map_err(|error| WorkspaceError::Io(format!("rollback parent: {error}")))?;
386    let canonical_path = canonicalize_plain(&pending.path)
387        .map_err(|error| WorkspaceError::Io(format!("rollback target: {error}")))?;
388    if canonical_parent != pending.parent || canonical_path != pending.path {
389        return Err(WorkspaceError::BrokerDenied(
390            "rollback-refused: asset path changed after creation".to_string(),
391        ));
392    }
393    let metadata = std::fs::metadata(&canonical_path)
394        .map_err(|error| WorkspaceError::Io(format!("rollback metadata: {error}")))?;
395    if !metadata.is_file() || metadata.len() != pending.byte_length {
396        return Err(WorkspaceError::Other(
397            "rollback-refused: asset length changed after creation".to_string(),
398        ));
399    }
400    let current = match std::fs::read(&canonical_path) {
401        Ok(bytes) => bytes,
402        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
403        Err(error) => return Err(WorkspaceError::Io(format!("rollback read: {error}"))),
404    };
405    let current_digest = sha256_bytes(&current);
406    if current_digest != pending.digest {
407        return Err(WorkspaceError::Other(
408            "rollback-refused: asset changed after creation".to_string(),
409        ));
410    }
411    std::fs::remove_file(&canonical_path)
412        .map_err(|e| WorkspaceError::Io(format!("rollback: {e}")))?;
413    Ok(true)
414}
415
416/// Commit a staged asset: the file stays and the token is consumed.
417pub fn commit_markdown_asset(
418    transactions: &MarkdownAssetTransactions,
419    token: &str,
420) -> Result<bool, WorkspaceError> {
421    Ok(take_pending(transactions, token)?.is_some())
422}
423
424fn take_pending(
425    transactions: &MarkdownAssetTransactions,
426    token: &str,
427) -> Result<Option<PendingAsset>, WorkspaceError> {
428    Ok(transactions
429        .pending
430        .lock()
431        .map_err(|_| WorkspaceError::Other("asset transaction lock poisoned".to_string()))?
432        .remove(token))
433}
434
435fn validate_relative_folder(folder: &str) -> Result<(), WorkspaceError> {
436    let path = Path::new(folder);
437    if folder.is_empty()
438        || path.is_absolute()
439        || path
440            .components()
441            .any(|part| !matches!(part, Component::Normal(_)))
442    {
443        return Err(WorkspaceError::Other(
444            "path-traversal: assets folder must be a relative child path".to_string(),
445        ));
446    }
447    Ok(())
448}
449
450/// The most candidate names tried for one asset: the base name, then `stem (1).ext` and on.
451const MAX_ASSET_CANDIDATES: usize = 999;
452
453/// Store `bytes` under the first free name of `numbered_candidates(base_name)` in `assets_dir`, or
454/// reuse the first existing file with identical content. A free name is claimed by an atomic
455/// no-replace write, so a concurrent writer that takes the name first is never overwritten: the
456/// name is inspected again (an identical asset it wrote is reused) and otherwise skipped.
457/// Returns the path and whether an existing file was reused.
458fn store_asset(
459    assets_dir: &Path,
460    base_name: &str,
461    bytes: &[u8],
462    digest: &str,
463) -> Result<(PathBuf, bool), WorkspaceError> {
464    for name in numbered_candidates(base_name, MAX_ASSET_CANDIDATES) {
465        let candidate = assets_dir.join(name);
466        for _ in 0..2 {
467            match std::fs::symlink_metadata(&candidate) {
468                Ok(meta) if !meta.file_type().is_file() => break,
469                Ok(_) => {
470                    let existing = std::fs::read(&candidate)
471                        .map_err(|e| WorkspaceError::Io(format!("read existing asset: {e}")))?;
472                    if sha256_bytes(&existing) == digest && existing == bytes {
473                        return Ok((candidate, true));
474                    }
475                    break;
476                }
477                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
478                    match write_new_asset(&candidate, bytes) {
479                        Ok(()) => return Ok((candidate, false)),
480                        // Someone created the name between the inspection and the write.
481                        Err(FsError::AlreadyExists(_)) => continue,
482                        Err(error) => {
483                            return Err(WorkspaceError::Io(format!(
484                                "write asset: {}",
485                                fs_error_text(error)
486                            )));
487                        }
488                    }
489                }
490                Err(error) => {
491                    return Err(WorkspaceError::Io(format!("inspect asset target: {error}")));
492                }
493            }
494        }
495    }
496    Err(WorkspaceError::Other(format!(
497        "asset-collision-limit: exhausted {MAX_ASSET_CANDIDATES} candidate names"
498    )))
499}
500
501/// Publish `bytes` at `path` only if nothing exists there: flushed temp file, then an atomic
502/// no-replace publish. A failed write leaves no partial asset behind.
503fn write_new_asset(path: &Path, bytes: &[u8]) -> Result<(), FsError> {
504    let options = AtomicWriteOptions {
505        replace: ReplaceMode::NoReplace,
506        ..AtomicWriteOptions::default()
507    };
508    atomic_write_with_options(path, options, |file| file.write_all(bytes))
509}
510
511/// The OS error text alone, without the temp path `FsError::Io` adds to its display.
512fn fs_error_text(error: FsError) -> String {
513    match error {
514        FsError::Io { source, .. } => source.to_string(),
515        other => other.to_string(),
516    }
517}
518
519/// A refused or unresolvable asset location: a path that leaves the document folder is a broker
520/// denial (as before); anything that could not be resolved is an I/O failure.
521fn escape_error(error: rightkit_fs::ContainError) -> WorkspaceError {
522    match error {
523        rightkit_fs::ContainError::Io(io) => {
524            WorkspaceError::Io(format!("resolve assets folder: {io}"))
525        }
526        _ => WorkspaceError::BrokerDenied(
527            "asset folder escapes the granted document directory".to_string(),
528        ),
529    }
530}
531
532fn is_safe_svg(bytes: &[u8]) -> bool {
533    let text = match std::str::from_utf8(bytes) {
534        Ok(text) => text,
535        Err(_) => return false,
536    };
537    let lower = text.to_ascii_lowercase();
538    let compact = lower
539        .chars()
540        .filter(|ch| !ch.is_ascii_whitespace() && !ch.is_ascii_control())
541        .collect::<String>();
542    if !lower.contains("<svg") {
543        return false;
544    }
545    !["<script", "<foreignobject", "<!entity"]
546        .iter()
547        .any(|needle| lower.contains(needle))
548        && !["javascript:", "data:text/html"]
549            .iter()
550            .any(|needle| compact.contains(needle))
551        && !has_inline_event_handler(&lower)
552}
553
554fn has_inline_event_handler(text: &str) -> bool {
555    let bytes = text.as_bytes();
556    let mut index = 0;
557    while index + 2 < bytes.len() {
558        let boundary =
559            index == 0 || bytes[index - 1].is_ascii_whitespace() || bytes[index - 1] == b'<';
560        if boundary && bytes[index] == b'o' && bytes[index + 1] == b'n' {
561            let mut cursor = index + 2;
562            let name_start = cursor;
563            while cursor < bytes.len() && bytes[cursor].is_ascii_alphabetic() {
564                cursor += 1;
565            }
566            if cursor > name_start {
567                while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
568                    cursor += 1;
569                }
570                if bytes.get(cursor) == Some(&b'=') {
571                    return true;
572                }
573            }
574        }
575        index += 1;
576    }
577    false
578}
579
580fn compute_file_name(hint: &str, digest: &str, mime: &str) -> String {
581    let safe = sanitize_hint(hint);
582    let stem = safe
583        .rsplit_once('.')
584        .map(|(stem, _)| stem)
585        .filter(|stem| !stem.is_empty())
586        .unwrap_or("asset");
587    format!("{}-{}.{}", stem, &digest[..12], extension_for_mime(mime))
588}
589
590fn sanitize_hint(name: &str) -> String {
591    let out = name
592        .chars()
593        .take(80)
594        .map(|ch| {
595            if ch.is_ascii_alphanumeric() || ch == '.' || ch == '_' || ch == '-' {
596                ch
597            } else {
598                '_'
599            }
600        })
601        .collect::<String>();
602    if out.is_empty() {
603        "asset".to_string()
604    } else {
605        out
606    }
607}
608
609fn extension_for_mime(mime: &str) -> &'static str {
610    match mime {
611        "png" => "png",
612        "jpeg" => "jpg",
613        "webp" => "webp",
614        "gif" => "gif",
615        "svg" => "svg",
616        _ => "bin",
617    }
618}
619
620fn random_token() -> Result<String, WorkspaceError> {
621    let mut bytes = [0_u8; 24];
622    getrandom::fill(&mut bytes)
623        .map_err(|e| WorkspaceError::Other(format!("asset token generation failed: {e}")))?;
624    Ok(rightkit_crypto::hex_encode(&bytes))
625}
626
627fn relative_path(base: &Path, target: &Path) -> String {
628    target
629        .strip_prefix(base)
630        .map(|path| path.to_string_lossy().replace('\\', "/"))
631        .unwrap_or_else(|_| target.to_string_lossy().replace('\\', "/"))
632}
633
634#[cfg(test)]
635mod tests {
636    use super::{
637        rollback_markdown_asset, save_markdown_asset, MarkdownAssetTransactions,
638        SaveMarkdownAssetRequest,
639    };
640    use crate::grants::testing::MemoryGrants;
641    use crate::grants::PathGrants;
642    use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
643    use std::fs;
644
645    struct TestDir(std::path::PathBuf);
646
647    impl TestDir {
648        fn new() -> Self {
649            let mut nonce = [0_u8; 12];
650            getrandom::fill(&mut nonce).unwrap();
651            let suffix = rightkit_crypto::hex_encode(&nonce);
652            let path = std::env::temp_dir().join(format!("rightkit-markdown-assets-{suffix}"));
653            fs::create_dir(&path).unwrap();
654            Self(path)
655        }
656
657        fn path(&self) -> &std::path::Path {
658            &self.0
659        }
660    }
661
662    impl Drop for TestDir {
663        fn drop(&mut self) {
664            let _ = fs::remove_dir_all(&self.0);
665        }
666    }
667
668    fn save_request(document_path: String, bytes: &[u8]) -> SaveMarkdownAssetRequest {
669        SaveMarkdownAssetRequest {
670            payload_base64: BASE64.encode(bytes),
671            hint_name: "diagram.png".to_string(),
672            mime_kind: "png".to_string(),
673            document_path,
674            assets_folder: Some("assets".to_string()),
675        }
676    }
677
678    #[test]
679    fn rollback_refuses_a_changed_file_and_consumes_authority() {
680        let dir = TestDir::new();
681        let document = dir.path().join("doc.md");
682        fs::write(&document, "# doc").unwrap();
683        let broker = MemoryGrants::default();
684        let granted = broker.grant_existing_file_path(&document).unwrap();
685        let transactions = MarkdownAssetTransactions::default();
686        let saved = save_markdown_asset(save_request(granted, b"original"), &broker, &transactions)
687            .unwrap();
688        fs::write(&saved.absolute_path, b"changed").unwrap();
689        let token = saved.rollback_token.unwrap();
690        assert!(rollback_markdown_asset(&transactions, &token).is_err());
691        assert_eq!(fs::read(&saved.absolute_path).unwrap(), b"changed");
692        assert!(!rollback_markdown_asset(&transactions, &token).unwrap());
693    }
694
695    #[cfg(unix)]
696    #[test]
697    fn symlink_asset_folder_escape_is_rejected() {
698        use std::os::unix::fs::symlink;
699
700        let dir = TestDir::new();
701        let outside = TestDir::new();
702        let document = dir.path().join("doc.md");
703        fs::write(&document, "# doc").unwrap();
704        symlink(outside.path(), dir.path().join("assets")).unwrap();
705        let broker = MemoryGrants::default();
706        let granted = broker.grant_existing_file_path(&document).unwrap();
707        let result = save_markdown_asset(
708            save_request(granted, b"escape"),
709            &broker,
710            &MarkdownAssetTransactions::default(),
711        );
712        assert!(result.is_err());
713        assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0);
714    }
715}