Skip to content

fix(server): keep requests inside the collection once links resolve - #751

Merged
LeMyst merged 1 commit into
cooklang:mainfrom
drawmeanelephant:fix/698-symlink-escape
Oct 18, 2026
Merged

LeMyst merged 1 commit into
cooklang:mainfrom
drawmeanelephant:fix/698-symlink-escape

Conversation

@drawmeanelephant

@drawmeanelephant drawmeanelephant commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #698

Summary

Every request-path check in the server is lexical (check_path /
is_request_path), so Link/Secret.cook through a Link -> /outside
symlink passed them. Two places then reached the file the link pointed
to: the handlers that opened the resolved path, and cooklang-find's
glob walk, which follows linked folders — so listings, search, feeds and
stats would also publish names (and contents) from outside the
collection.

Changes

  • util::inside_collection(base, path) canonicalizes path's nearest
    existing ancestor (so it also works for files a write would create)
    and compares it to the canonical base — one helper now, used by the
    API handlers, build_recipe_template, /api/static and the existing
    POST /new / rename paths (canonical_or_nearest moved to util
    beside it).
  • Reads answer exactly like a missing file. GET /api/recipes,
    /api/menus, /api/recipe_image and the recipe page return the same
    404 "… not found: …: Invalid recipe path: …" body get_recipe
    produces for a missing name, so an outside link reveals nothing.
    GET /api/recipes/raw likewise collapses "not there" and "not inside"
    into one 404 (the lexical check_path 400 for e.g. dotfiles is kept —
    it never depends on what exists).
  • Writes stay a plain 400, as the rename's refusal does: save,
    delete, picture upload, plan edits and /api/shopping_list/add.
  • POST /api/shopping_list is guest-reachable, so each entry is
    refused before it is read; /api/shopping_list/add refuses at the
    door rather than storing a path later reads would have to defend
    against, and aggregate_current_ingredient_names skips stored paths
    that resolve outside (a .shopping-list written before this fix can
    still hold one).
  • build_recipes_template prunes tree nodes that resolve outside when
    !static_mode (cook build keeps following links — there the
    collection and the links are the user's own), and all_recipes,
    list_menus, stats, the random-recipe pick, feeds and /api/search
    apply the same pruning/filtering. find_todays_menu filters its hit
    the same way on the server.
  • Links that stay inside the collection — an Alias dir or file link —
    still resolve: the check is on the canonical path, not on whether a
    link is involved.

Test plan

tests/server_symlinks_test.rs (cfg(unix)):

  • Reads through linked folders and linked files answer 404 on
    /api/recipes, /api/recipes/raw, /api/recipe_image and
    /api/static; the recipe page shows the same "Recipe not found" page
    as a missing file.
  • PUT/DELETE through a linked dir still answer 400 and change
    nothing outside.
  • Menus: GET /api/menus/… → 404; POST /api/plans/… and
    POST /api/shopping_list/add_menu → 400.
  • POST /api/shopping_list refuses a linked recipe with the same status
    as a missing one; add refuses 400.
  • /api/recipes, /api/menus, /api/search, /api/stats and the
    /directory/Linked page publish nothing that resolves outside.
  • In-collection symlinks still resolve.

Full cargo test --all-features green.

Generated with Devin

@LeMyst LeMyst left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is careful work. The endpoints it touches hold up:

  • raw/save/delete/edit/plan_edit through recipe_file
  • /api/recipes/{p}, /api/menus/{p}, add_menu, recipe_image
  • the /recipe page
  • /api/static

A symlinked recipe root is fine, because it is canonicalized at startup, and links that stay inside the collection still work. Some points remain, plus one decision for the maintainers.

1. Missed route, reachable by guests

POST /api/shopping_list (src/server/handlers/shopping_list.rs:60) only runs check_path, then extract_ingredients, and core's parse_source → find::get_recipe follows the link. The route is in OPEN_WRITES (src/server/auth/middleware.rs:25), so a signed-out guest can post [{"recipe":"Linked/Secret.cook"}] and get the outside recipe's ingredients back. Paths stored through /api/shopping_list/add (also check_path only) are followed later by the page and by compaction.

2. Listings and search still follow links

cooklang-find walks the tree with glob, which follows symlinked directories. So /api/recipes, /directory/Linked, /api/search, the feeds and /api/stats still list or read files outside the collection. Search hits reveal which outside files contain a word. It's also inconsistent for users: those recipes still appear in the index and in search, but their thumbnails now 404 and opening one fails.

3. Reads reveal whether a file exists

recipes.rs:136 (and the same pattern in menus.rs, recipe_image find_recipe and add_menu) answers 400 with a specific message. So GET /api/recipes/Linked/<guess>.cook returns 400 if the outside file exists and 404 if not. #698 asked for 403/404, and /api/static already answers a plain 404. Answering 404 "Recipe not found" for reads, and keeping 400 for writes as the rename does, would close that.

4. Two copies of the check

src/web/builders.rs:393 re-implements it with canonicalize and fails closed. inside_collection (common.rs:71) uses canonical_or_nearest and fails open when canonicalizing errors. One helper in util would give one rule. (inside_collection also re-canonicalizes base_path on every call although it is already canonical. That's cheap, just noting it.)

5. Decision for maintainers: no opt-out

Someone with Shared -> ~/Dropbox/recipes loses all of those recipes in the server, while cook build still follows the link. That probably needs a flag (e.g. --follow-symlinks) or at least a release note.

Tests

The tests are properly gated on unix and use with_isolated_config. There is no coverage yet for menus, add_menu, /edit, plan_edit or the shopping list.

This conflicts with #750 in recipe_image.rs find_recipe, since both rewrite it. The resolved order would be check_path → extension check (404) → get_recipe → inside_collection. It merges cleanly with #749.


🤖 Analysis and recommendations made by Claude (Anthropic's AI assistant), posted on behalf of @LeMyst.

@drawmeanelephant

Copy link
Copy Markdown
Contributor Author

Reworked along all of these lines:

  • POST /api/shopping_list: each entry is now containment-checked after check_path and refused before it is read. /api/shopping_list/add refuses outside paths at the door rather than storing them, and aggregate_current_ingredient_names (used by compact) also skips stored paths that resolve outside — a .shopping-list written before this could still hold one.
  • Reads indistinguishable from missing: GET /api/recipes, /api/menus, /api/recipe_image and the recipe page now return the identical 404 body get_recipe produces for a missing name (built via FetchError::InvalidPath so the wording can't drift). GET /api/recipes/raw collapses "missing" and "outside" into one 404; lexical check_path refusals keep their 400 since they don't depend on what exists. Writes (save, delete, picture upload, plan edits, add) keep the plain 400, as the rename does.
  • One helper: inside_collection and canonical_or_nearest now live in util, shared by the API handlers, build_recipe_template, /api/static, and the POST /new / rename paths that already canonicalized.
  • Listings/search/feeds/stats: build_tree's glob walk does follow linked folders, so prune_outside drops any tree node that resolves outside — applied in build_recipes_template (server only), all_recipes, list_menus, stats, the random pick and feeds; /api/search filters hits the same way, and find_todays_menu filters its result on the server.
  • Coverage: added menu GET/add_menu/plan_edit, shopping-list POST and add, listing/search/stats, linked-file static, and /directory/Linked cases to server_symlinks_test.rs — 7 tests, all green alongside the full cargo test --all-features.

On the opt-out question: I kept this strict with no --follow-symlinks flag — in-collection links still work since the check is on the canonical target, and an escape hatch felt like scope this PR doesn't need. Happy to add one if you'd rather have the toggle.

@LeMyst

LeMyst commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the rework. I checked it on 3abdb85 against a real collection containing:

  • a symlinked directory pointing out (Linked -> outside/dir)
  • a symlinked recipe pointing out (Leak.cook -> outside/file.cook)
  • a linked picture pointing out
  • links that stay inside, and a dangling link
  • a recipe and a menu that reference ./Linked/Secret and ./Leak
  • a symlinked root

I ran it as a guest with no users file, and again with a users.toml.

Most of it holds now:

  • Listings, /directory, search, the feeds, stats and random no longer show anything from outside. Searching for a word that only the outside file contains returns [].
  • Reads return the same 404 for a linked, missing or dangling path, so they no longer reveal whether a file exists.
  • Every write route refuses a linked path (save, delete, rename, image put/delete, plans, add_menu, /new into Linked/), and the outside files are byte-for-byte unchanged.
  • /api/static refuses linked pictures, while pictures linked from inside still serve.
  • Everything goes through one inside_collection helper.

The shopping list still reads outside the collection, in three ways:

1. A name without .cook gets past the check (guest-reachable)

POST /api/shopping_list with [{"recipe":"Leak"}] returns 200 with the outside file's ingredients, for a guest, with or without sign-in. The check at src/server/handlers/shopping_list.rs:64 runs on base.join("Leak"). That path doesn't exist, so canonical_or_nearest falls back to the base directory and the check passes. get_recipe then resolves Leak to Leak.cook, which is the link. /api/shopping_list/add (:453) and the compaction pass (:709) have the same gap.

Checking the resolved entry (entry.path() after get_recipe) instead of the joined name closes it.

2. References are followed through links

Posting a recipe that contains @./Linked/Secret{}, or a .menu that lists it, returns the outside ingredients. The recipe itself is inside, so the handler's check passes, and core's expansion (crates/core/src/shopping_list/mod.rs:958, find::get_recipe(self.base_path, &ref_path)) follows the link without a containment check. Compaction does the same: it kept items whose names exist only in the outside files.

3. Stored references show outside titles

/add stores included_references unchecked, and add_menu stores a menu's sub-entries the same way. GET /api/shopping_list/items then puts each one through name_by_title / recipe_title (:320-345, :421), so a guest sees the outside recipes' titles. That is also a way to test whether a given outside file exists.

Points 1 and 2 could both be fixed in one place with a "confined" option on core's find::get_recipe, checking the resolved path before it is read. It would cover the handler, the expansion and compaction together, and leave the CLI (which has no reason to confine) as it is. Otherwise, check inside_collection on the resolved entry in each handler and once more in expand.

Smaller points

  • A link out returns "Recipe not found" (capitalised, from the handler), while a missing file returns "recipe not found" (from core). Using the same wording for both would remove the last difference.
  • The 7 new server_symlinks_test tests pass. None of them uses an extension-less name or a reference, so a test for each case above would keep them fixed.
  • Keeping it strict with no opt-out is a reasonable default. Whether to add a flag is up to the maintainers.

fmt, clippy, cargo test --workspace and CI are all green. To be clear, all of the above also happens on main today, where links are followed everywhere, so this PR is already a clear improvement.


🤖 Analysis and recommendations made by Claude (Anthropic's AI assistant), posted on behalf of @LeMyst.

@drawmeanelephant

Copy link
Copy Markdown
Contributor Author

On 3fd8807, rebased past merged #750 — all three holes are closed now:

  1. Extension-less names: the joined-path check never saw them because Leak is nothing on the filesystem until cooklang-find tries Leak.cook. New find::get_recipe_inside does the lookup and canonicalizes the resolved entry against the collection; outside hits answer RecipeNotFound, same as a missing file.
  2. References: extraction is now confinable — ExtractOptions.confined routes the starting recipe, the expander and optional_selections through get_recipe_inside, and the server sets it on POST and on the compaction aggregation. @./Linked/Secret{} in a recipe or a menu expands to nothing.
  3. Stored included_references: recipe_title checks the resolved entry before reading it, so /api/shopping_list/items shows the file-stem, not an outside title; reference_scales doesn't read outside recipes for their servings either.

On the wording: the refusal now surfaces as core's recipe not found, matching your smaller point — no distinction between missing and out-of-bounds.

New tests in server_symlinks_test.rs: Leak/Leak.cook refused on POST and /add (verified red without confined), reference expansion through a linked recipe and a linked menu, and a pre-seeded .shopping-list carrying ./Linked/Secret.

@LeMyst

LeMyst commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks, the shopping list is closed now. On 3fd8807:

  • Leak, Leak.cook, Linked/Secret, Uses.cook and Plan.menu are all refused on POST and /add, for a guest with or without sign-in.
  • A stored ./Leak no longer feeds compaction.
  • The items list shows file stems instead of outside titles.
  • When get_recipe_inside is replaced with plain get_recipe, three of the new tests fail, so they really cover the fix.
  • Listings, reads, writes and /api/static still hold. The outside files are byte-for-byte unchanged, and links that stay inside still work.

A few places still read outside the collection. All of them do the same on main, so none of this is a regression, but they fit this PR's goal:

  1. GET /api/aisles/uncategorized lists outside files and their ingredients, to a guest, even with sign-in on. aisle_coverage (crates/core/src/doctor.rs:760, called from src/server/handlers/aisles.rs:587) walks build_tree without pruning. With Linked -> outside it returns:
    {"name":"zebrafoo","recipes":[{"path":"Linked/Secret.cook"…}]}
    {"name":"xylophonix","recipes":[{"path":"Leak.cook"…}]}
    
    prune_outside is in the CLI crate (src/web/builders.rs:48), so this needs either a pruning option in core's walk or filtering the result in the handler.
  2. add_menu still parses the outside recipe. resolve_recipe_info (shopping_list.rs:981, through src/util/recipe_info.rs:39) reads Linked/Secret.cook and stores that file's own references as sub-entries. After add_menu {"path":"Plan.menu"}, GET /api/shopping_list/items shows "included_references":["QuuxHiddenRef"], a name that appears only inside the outside file. Using get_recipe_inside there, or skipping an outside reference, would close it.
  3. Smaller: reference scaling still reads outside servings. This goes through ref_info_or_default (src/web/builders.rs:497, :1128) and load_menu → resolve_scales (menus.rs:156). With @./Linked/Secret{14%servings}:
    • the recipe page links ?servings=14, where a missing target gives ?scale=10;
    • GET /api/menus/… returns "scale":2.0, which reveals the outside file's servings: 7.
  4. Smaller: the two refusals still differ in wording. The POST check (shopping_list.rs:66-72) says Recipe not found: …, while core says recipe not found: …. So Leak.cook and a dangling Dangling.cook still answer differently. Using core's wording there, and having the tests compare the body as well as the status, would settle it.

The CLI still follows links (cook shopping-list Leak lists xylophonix). That matches the confined doc comment and seems right. A line in the docs or release notes saying the server no longer follows links out of the collection would help people with linked folders.

fmt, clippy and cargo test --workspace are clean. The one failure in the run was the known each_role_can_do_only_what_it_allows flake, which passes alone. CI is green, and it merges cleanly with main.


🤖 Analysis and recommendations made by Claude (Anthropic's AI assistant), posted on behalf of @LeMyst.

@drawmeanelephant

Copy link
Copy Markdown
Contributor Author

All four on dd86455:

  1. /api/aisles/uncategorized: CoverageRequest grows confined; core now has find::inside_base (the canonicalize check, shared with get_recipe_inside) and coverage() drops linked-out entries before they are read — so not even their contents are touched. The handler sets confined: true; the CLI's doctor pantry/aisle calls leave it off.
  2. add_menu: each menu reference is resolved and skipped when its entry lands outside (same warn-skip as the lexical is_outside_reference path), so the outside file's own references never reach included_references.
  3. Outside servings: two fixes composing — parse_menu (now taking base_path) drops the unit of a reference that resolves outside, so resolve_scales treats it as a raw multiplier and never reads the file; and ref_info_or_default_inside (new, next to ref_info_or_default) answers default info for a canonical-outside target at the recipe-page link and menu-page ref sites.
  4. Wording: the POST refusal now says recipe not found: {name}, core's spelling — and the test compares normalized response bodies between a link and a genuinely missing name, not just the status.

Three new server tests (uncategorized_ingredients_do_not_name_linked_files, a_menu_entry_through_a_link_keeps_none_of_its_references, a_reference_scaled_by_an_outside_recipes_servings_leaks_nothing), each verified red with the corresponding confinement removed — all three fail when confined/lands_outside are flipped off.

Also added the docs line: docs/server.md notes that the server doesn't follow links out of the recipe directory while the CLI does.

The path checks are lexical, so `Link/Secret.cook` through a
`Link -> /outside` symlink passed them and the handlers that then opened
the file — raw/save/delete, the editor, the menu and recipe pages,
`/api/recipe_image`, and `ServeDir` under `/api/static` — read, wrote or
removed whatever the link pointed to. The rename already refused this
(#549 covered creation); the rest now check the canonical path too.

`handlers::common::inside_collection` canonicalizes the nearest existing
ancestor, so it covers files that do not exist yet; `recipe_file` refuses
there for every caller, the `cooklang-find` entry lookups check the
resolved path, and `/api/static`'s middleware joins the decoded request
path and checks it before `ServeDir` follows any link. A link that stays
inside the collection still resolves; `cook build` keeps following links
out, since there the collection and the links are the user's own.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@drawmeanelephant

Copy link
Copy Markdown
Contributor Author

Rebased to 167f765 past the #734 merge — the collision was in src/doctor.rs, where its base_dir: None (resolved -b already in ctx) met the new confined field. Kept #734's structure and gave the CLI's coverage calls ..Default::default(), so confined stays server-only. Both suites pass.

@LeMyst
LeMyst merged commit 7ad607f into cooklang:main Oct 18, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recipe endpoints and /api/static follow symlinks out of the collection

2 participants