Skip to content

(feat) add user actions: delete, reveal file ( to webui treemap) - #659

Merged
dundee merged 20 commits into
dundee:masterfrom
mikhail-angelov:feat/add-user-actions-to-webui
Sep 14, 2026
Merged

dundee merged 20 commits into
dundee:masterfrom
mikhail-angelov:feat/add-user-actions-to-webui

Conversation

@mikhail-angelov

Copy link
Copy Markdown
Contributor

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:

  • Reveal (O) — opens the selected file/directory in the system file manager.
  • Delete (D) — permanently deletes the selected item after a confirmation dialog. The dialog can suppress further confirmations for the rest of the browser session.
  • The existing --no-delete flag and filtered-scan deletion restrictions from the terminal UI now apply to the web UI as well.
  • ? still shows the keyboard shortcuts help.

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:

  • On startup the server generates a random, cryptographically strong token unique to that process (webui/action_token.go).
  • The token is delivered exactly once, embedded in the URL the server prints and opens (e.g. http://127.0.0.1:8765/?token=...). ItAPI response.
  • The frontend reads the token from the URL on mount and immediately strips it out via history/URLSearchParams, so it doesn'y, get logged, or stay visible toanything else that can read the address bar. - Every reveal/delete request echoes -Action header; the server validatesit with a constant-time comparison. - As defense in depth, the server alsigin on these requests, rejectinganything that isn't same-origin — so a page on another origin or another browser tab can't trigger these actions even if it can reach th

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.

image image

@codecov

codecov Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.21965% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.60%. Comparing base (ebd2715) to head (fc5c786).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
webui/tree.go 82.35% 6 Missing ⚠️
webui/reveal.go 75.00% 2 Missing ⚠️
webui/handlers.go 98.70% 1 Missing ⚠️
webui/server.go 95.83% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dundee
dundee self-requested a review September 9, 2026 09:42
Comment thread webui/server.go Resolved
Comment thread webui/server.go
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))

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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 route

That keeps browsing unauthenticated while closing the rebinding path.

Comment thread webui/handlers.go
if r.URL.Query().Get("mode") == deleteModeTrash {
removeFunc = ui.trasher
}
if err := removeFunc(parent, node); err != nil {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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.

Comment thread webui/handlers.go Outdated
return
}
parent := node.GetParent()
if parent == nil {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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.)

Comment thread webui/reveal.go
return runDetached(name, args...)
}

func revealCommand(goos, path string) (name string, args []string) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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.

Comment thread webui/handlers.go
var body struct {
Path string `json:"path"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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)

Comment thread webui/frontend/src/model.tsx Outdated
// 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(() => {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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.)

Comment thread webui/handlers.go
switch {
case noDelete:
return "deletion is disabled", http.StatusForbidden
case ui.IsFilteringFiles() && os.Getenv("GDU_ALLOW_DELETE_WITH_FILTER") != "1":

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

[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.

@dundee

dundee commented Sep 10, 2026

Copy link
Copy Markdown
Owner

@mikhail-angelov Do you want me to try to address the comments or would you like to do it yourself?

@mikhail-angelov

Copy link
Copy Markdown
Contributor Author

@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.
@mikhail-angelov
mikhail-angelov force-pushed the feat/add-user-actions-to-webui branch from e6b2ce8 to 0c30546 Compare September 14, 2026 05:44
mikhail-angelov and others added 14 commits September 14, 2026 18:08
literal IPs and the configured --web-listen hostname.
changed/symlink parents return 409. Regression test confirms outside
files remain
untouched.
launcher arguments are constructed. 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.
@dundee
dundee merged commit 4b4203d into dundee:master Sep 14, 2026
10 checks passed
@dundee

dundee commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Thank you for the great effort!

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.

2 participants