Repository navigation
(feat) add user actions: delete, reveal file ( to webui treemap) - #659
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #659 +/- ##
==========================================
+ Coverage 90.35% 90.60% +0.24%
==========================================
Files 72 75 +3
Lines 6556 6725 +169
==========================================
+ Hits 5924 6093 +169
Misses 631 631
Partials 1 1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
| mux.HandleFunc("/api/v1/status", ui.handleStatus) | ||
| mux.HandleFunc("GET /api/v1/nodes", ui.handleNodes) | ||
| mux.HandleFunc("GET /api/v1/tree", ui.handleTree) | ||
| mux.HandleFunc("DELETE /api/v1/nodes", ui.requireLocalAction(ui.handleDeleteNode)) |
There was a problem hiding this comment.
[MED] Read API is reachable via DNS rebinding
requireLocalAction correctly checks isLoopbackHost(r.Host), and the comment above isLocalRequest explains why (rebinding). But that check only guards these two mutating routes. /api/v1/status, GET /api/v1/nodes, GET /api/v1/tree, /api/v1/devices and /api/v1/events have no Host validation at all.
So a page on attacker.example whose DNS re-resolves to 127.0.0.1 can, after the TTL flips, read the entire scanned tree from the victim's machine — every file and directory name, sizes, and live scan progress paths. The browser considers it same-origin with attacker.example, so neither Sec-Fetch-Site nor Origin helps here; only the Host check does.
The browse-is-unauthenticated decision is defensible for a localhost-bound tool, but "anyone who can reach the port" shouldn't silently extend to "any website the user visits". Suggest hoisting the Host check to the whole mux:
mux := http.NewServeMux()
// ... register routes ...
return requireLoopbackHost(mux) // rejects non-loopback Host on every routeThat keeps browsing unauthenticated while closing the rebinding path.
| if r.URL.Query().Get("mode") == deleteModeTrash { | ||
| removeFunc = ui.trasher | ||
| } | ||
| if err := removeFunc(parent, node); err != nil { |
There was a problem hiding this comment.
[MED] Delete re-resolves a path captured at scan time (TOCTOU)
findNode resolves against the in-memory tree, then remove.ItemFromDir calls os.RemoveAll(item.GetPath()) — a path string recorded during the scan. Between scan and delete, anything about that path may have changed on disk.
To be precise about the limits: os.RemoveAll unlinks a final-component symlink rather than following it, so the trivial "swap the target for a symlink" case is not an escape. The exploitable shape is an ancestor swap — if any parent component of the recorded path is replaced with a symlink (feasible where the scan covers a directory another local user or a running process can write, e.g. a shared /tmp subtree), the deletion lands outside the scanned root.
This is pre-existing behaviour shared with the TUI, not something you introduced — but this PR makes it reachable from a browser click, and the web UI's confirmation dialog implies a stronger guarantee than the code gives. At minimum, an os.Lstat re-check that the resolved parent is still a non-symlink directory immediately before removal would close the practical window. A full fix would be openat-style traversal in pkg/remove, which is arguably its own issue.
| return | ||
| } | ||
| parent := node.GetParent() | ||
| if parent == nil { |
There was a problem hiding this comment.
[LOW] An entire scanned root can be deleted in multi-path mode
This guard only refuses when the node has no parent. With multiple scanned paths, gdu inserts a virtual top-level directory (ADR-0002, "multiple scanned roots share a virtual top-level dir"), so each scanned root does have a parent — the virtual dir. gdu --web /home/user /var/log therefore lets one confirmed click RemoveAll("/home/user").
The virtual dir also has no real path of its own, so what "deleting" it even means is ambiguous. Suggest:
if parent == nil || analyze.IsVirtualRootDir(parent) {
writeError(w, http.StatusBadRequest, "cannot delete a scanned root")
return
}(IsVirtualRootDir is already used in webui/tree.go.)
| return runDetached(name, args...) | ||
| } | ||
|
|
||
| func revealCommand(goos, path string) (name string, args []string) { |
There was a problem hiding this comment.
[LOW] Report-supplied paths can become launcher flags
For live scans, app.go absolutises the root, so path is always /… and safe. But ReadAnalysis (webui/webui.go) takes root paths verbatim from a JSON report, which is untrusted input — gdu -f report.json --web on a report someone sent you. A root path like -a or --new-window is then passed as the first argument to open / xdg-open / explorer and is interpreted as a flag rather than a path.
Impact is modest (one attacker-chosen argument, no shell involved — exec.Command doesn't invoke one), but it's cheap to close:
if !filepath.IsAbs(path) {
return fmt.Errorf("refusing to reveal non-absolute path %q", path)
}Note -- doesn't help uniformly here since explorer doesn't honour it, so an absolute-path assertion is the more portable guard.
| var body struct { | ||
| Path string `json:"path"` | ||
| } | ||
| if err := json.NewDecoder(r.Body).Decode(&body); err != nil { |
There was a problem hiding this comment.
[LOW] Unbounded request body on reveal
json.NewDecoder(r.Body) will read as much as the client sends. Token-gated, so the blast radius is small, but it's a one-liner:
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)| // Strip it from the visible address bar immediately after reading it, so | ||
| // it does not linger somewhere a shoulder-surfer, browser history entry, | ||
| // or copy-pasted URL could pick it up. | ||
| const [actionToken] = useState(() => { |
There was a problem hiding this comment.
[UX / correctness] Token is lost on reload, breaking actions for the rest of the session
The token is read from the URL once at mount and then stripped from the address bar (good — that part works). But it's held only in React state, so any reload, soft-navigation, or crash-and-recover loses it permanently: the URL no longer carries it, and no endpoint will re-issue it. From then on every reveal/delete returns a bare 403 ("actions are only available from the local web UI") with nothing telling the user that restarting gdu is the only way back.
Same root cause makes this PR-description promise not quite hold:
The dialog can suppress further confirmations for the rest of the browser session.
skipDeleteConfirm (line 114) is also plain state, so a reload resets the suppression too.
sessionStorage fits both cases well — it's scoped to the tab, survives reload, and dies with the tab, which matches "for the rest of the browser session" more literally than the current behaviour. If you'd rather not persist the token, then at least special-case the 403 in the UI with something like "action token lost — reload from the URL gdu printed".
(One more edge on the strip itself: it runs after React mounts, so if the SPA fails to boot — JS error, old cached bundle — the token stays in the address bar and browser history.)
| switch { | ||
| case noDelete: | ||
| return "deletion is disabled", http.StatusForbidden | ||
| case ui.IsFilteringFiles() && os.Getenv("GDU_ALLOW_DELETE_WITH_FILTER") != "1": |
There was a problem hiding this comment.
[info] Undocumented escape hatch
GDU_ALLOW_DELETE_WITH_FILTER=1 re-enables deletion during a filtered scan — a deliberate safety rail being switched off by an env var that appears nowhere in the docs. Worth adding to configuration.md and gdu.1.md alongside the flags this PR extends to the web UI.
Also: reveal is currently allowed under --no-delete. That's defensible (it's non-destructive), but --no-delete on a shared or kiosk machine arguably implies "no side effects on the host", and reveal spawns a GUI process there. Just flagging it as an intentional-or-not call.
|
@mikhail-angelov Do you want me to try to address the comments or would you like to do it yourself? |
i'll be glad if you do it (or I'll try to do it on weekend) |
Restores the delete/reveal endpoints, the loopback-only action security check, and the frontend workflow (delete confirmation modal, O/D shortcuts) that were split out of the read-only + Treemap PR per review feedback (#651). Rebase onto master once that PR merges so this becomes a standalone actions-only PR.
The X-GDU-Action header used to be a hardcoded "1", so it added no real protection beyond the loopback check. Generate a random token per server run (crypto/rand) instead, serve it to the frontend only over the local-only status endpoint/SSE stream, and require an exact constant-time match on delete/reveal requests. Also reject action requests whose Sec-Fetch-Site/Origin headers don't match this server's own origin, so a page on another site or another browser tab cannot trigger a mutating request even via a same-origin loopback connection.
Serving the action token in /api/v1/status meant any local user who could reach the port (not just the one who launched gdu) could read it with a plain curl request and forge delete/reveal calls, defeating the token's purpose entirely. Deliver it the way Jupyter Notebook does instead: generate it once at startup, append it as a query parameter to the URL that's printed to this process's own terminal and opened in the browser, and have the frontend read it from its own location once at load. The read-only endpoints (status, nodes, tree, devices, events) are untouched and stay exactly as unauthenticated as before - only the one piece of data that must stay private moves off the open API. Also set Referrer-Policy: no-referrer on the SPA response so the token-bearing URL can't leak via the Referer header if the page ever gains an outbound link.
…aster, rebuild dist Rebasing the actions branch onto master (which now has the squashed Treemap PR #651) silently dropped refreshNode/setLoadError/clearTree wiring during the 3-way merge of model.tsx, since master's version of that file diverged from the pre-split branch it was cherry-picked against. TreeMapView depends on both for post-delete refresh, so typecheck caught the gap immediately. Also rebuilds the frontend bundle so dist/ matches the merged source.
e6b2ce8 to
0c30546
Compare
literal IPs and the configured --web-listen hostname.
changed/symlink parents return 409. Regression test confirms outside files remain untouched.
longer be deleted. Regression test added.
launcher arguments are constructed. Regression test added.
decoding. Regression test added.
reload via sessionStorage; token is stripped before React loads. Embedded bundle rebuilt.
intentional Reveal behavior under --no-delete.
The parent Lstat check added for review issue #3 only catches a symlink in the immediate parent. os.Lstat declines to follow the final component of a path but still resolves every component above it, so swapping a *grandparent* resolves straight through to a real directory, reports IsDir, and passes. The attacker needs nothing beyond what the existing test already assumes - write access to the scanned root - so the guard was bypassed just by aiming one level deeper. TestDeleteEndpointRejectsSwappedAncestor covers that shape: before this change it returns 204 and deletes the file outside the tree. Both nodes and their scanned root are now fully resolved with EvalSymlinks and re-checked for containment, which catches a swap at any depth. Resolving both sides keeps a root legitimately reached through a symlink (macOS /tmp) from looking like an escape. A path that no longer resolves is allowed through, since os.RemoveAll is a no-op on it and deletion should stay idempotent when the item was removed in another window. This narrows the window to the microseconds between check and removal rather than closing it; doing that needs openat-style traversal in pkg/remove, which the terminal UI shares and which is worth its own change. Also takes the virtual-root lookup's read under the lock its three neighbours already use. Not reachable now that deleting a scanned root is refused - that was its only trigger - but it is the odd one out.
…ently isArchiveDescendant and isArchiveRoot each switched over the same two synthetic node types; a third archive type would have had to be added in both places. Extracted as isArchiveType. openPath, the revealPath field and handleReveal were three names for one operation, so the function becomes revealInFileManager. Its comment now also records why the absolute-path guard exists (report files are untrusted input) and why "--" is not used instead (explorer does not honour it). browserCommand and revealCommand are deliberately left separate: they differ on Windows, where a URL goes to rundll32 and a path goes to explorer, so merging them would mean parameterising the one case that differs.
The inline script in index.html stored the token before stripping it from the URL, so a sessionStorage throw (private-mode browser, storage disabled by policy) skipped the strip and left the token sitting in the address bar - precisely what the script exists to prevent. The strip now runs regardless, and the store is wrapped. The same wrapping is applied to the four accesses in model.tsx so a throw costs the actions rather than the whole app. A tab with no token now says so instead of firing a request that can only come back as a bare 403 with nothing pointing at the cause. Backspace is no longer a delete shortcut. Every desktop file manager binds it to "go up one level", so a user reaching for it here would expect to navigate, not to destroy the selected item; D and Delete are unchanged, and the help modal already listed only those two. Also extracts the useLatest hook duplicated between model.tsx and TreeMapView.tsx, and covers the skip-confirmation preference surviving a reload, which had no test.
CONTRIBUTING asks for configuration.md and gdu.1.md to follow a behaviour or flag change. This feature widened two flags without either being updated: --no-delete now also hides the web UI's delete action and makes the server reject the request, and --trash-command now also backs the web UI's "Move to Trash". The filter restriction is stated per frontend rather than as one rule: the terminal UI gates on time filters, while the web UI gates on any active filter, file-type filters included, because SetTimeFilter and the type filters both set FilteringFiles. Saying "file or time filters" for both read as parity that does not exist.
…lete TestDeleteNodeEndpointPropagatesRemovalError failed on Linux with 409 where it expected 500. Resolving the node itself needs search permission on the directory holding it, so the chmod-0 parent the test sets up made EvalSymlinks fail with EACCES, and an ordinary permission-denied removal was reported as a relocation instead of being left to os.RemoveAll. The same mistake was stricter than os.RemoveAll in the other direction: RemoveAll unlinks a final-component symlink rather than following it, so a link merely pointing outside the scanned tree was refused even though removing it only unlinks the link, which lives inside the tree. That made ordinary symlinks undeletable from the web UI - covered now by TestDeleteEndpointAllowsSymlinkPointingOutside, which fails with 409 before this change. Resolving the containing directory instead mirrors exactly what RemoveAll resolves, and still rejects an ancestor swapped at any depth: both existing symlink tests continue to pass. Verified on Linux in a container as a non-root user, since Docker's default root bypasses the permission check the test relies on.
|
Thank you for the great effort! |
Add reveal/delete actions to the web UI treemap
Adds two mutating actions to the treemap view, on top of the existing read-only web UI:
Security model
Browsing stays read-only and unauthenticated — anyone who can reach the port sees file names and sizes, so the server should stay bound to localhost (the default, unchanged).
Reveal and delete are more sensitive, so they require a per-run action token in addition to that:
Net effect: another local user (or ma reach the port can still browseread-only, but cannot forge a reveal/delete request without also having read this server process's own terminal output.