Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: reclaim quarantined profiles on demand with pinchtab profiles prune (PIN-194)

Luigi Agostic5bd812e2c23
diff --git a/cmd/pinchtab/cmd_cli_management.go b/cmd/pinchtab/cmd_cli_management.go
index 7c6b098e..dccd5c1b 100644
--- a/cmd/pinchtab/cmd_cli_management.go
+++ b/cmd/pinchtab/cmd_cli_management.go
@@ -38,6 +38,16 @@ var profilesCmd = &cobra.Command{
},
}
+var profilesPruneCmd = &cobra.Command{
+ Use: "prune",
+ Short: "Reclaim disk from quarantined profiles (lists only unless --confirm)",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.ProfilesPrune(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
var activityCmd = &cobra.Command{
Use: "activity",
Short: "List recorded activity events",
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 7a9c7906..662f6f35 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -56,6 +56,7 @@ func registerManagementCommands() {
instanceCmd.AddCommand(startInstanceCmd, instanceNavigateCmd, instanceStopCmd, instanceRestartCmd, instanceLogsCmd)
activityCmd.AddCommand(activityTabCmd)
+ profilesCmd.AddCommand(profilesPruneCmd)
configureManagementFlags()
@@ -425,6 +426,10 @@ func configureManagementFlags() {
instancesCmd.Flags().Bool("json", false, "Output full JSON response instead of terse status")
profilesCmd.Flags().Bool("json", false, "Output full JSON response instead of terse status")
+
+ profilesPruneCmd.Flags().Bool("confirm", false, "Actually remove the quarantined profiles (without it, nothing is deleted)")
+ profilesPruneCmd.Flags().String("profile", "", "Reclaim only this quarantined profile directory (default: all of them)")
+ profilesPruneCmd.Flags().Bool("json", false, "Output full JSON response instead of terse status")
}
func setCommandGroup(groupID string, cmds ...*cobra.Command) {
diff --git a/docs/commands.md b/docs/commands.md
index 96f0dd17..3adf260c 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -327,11 +327,55 @@ pinchtab instance stop <id> # Stop an instance
pinchtab instance logs <id> # Show instance logs
pinchtab instance navigate <id> <url> # Open a tab in an instance and navigate it
pinchtab profiles # List profiles
+pinchtab profiles prune # List reclaimable quarantined profiles (removes nothing)
+pinchtab profiles prune --confirm # Remove them and report the disk freed
+pinchtab profiles prune --profile <dir> # Reclaim just one quarantined directory
pinchtab activity # List recorded activity events
pinchtab activity tab <tab-id> # Filter activity by tab
pinchtab health # Check server health
```
+### Reclaiming quarantined profiles
+
+When a profile's browser data becomes unreadable, PinchTab renames the directory to
+`<profile>.quarantine-<timestamp>` and starts the profile again from an empty one. Those
+directories are never read afterwards, so they are pure disk cost.
+
+Two things remove them, and they answer different questions:
+
+- The **automatic prune** bounds accumulation *per profile, at quarantine time*. Each time a
+ profile is quarantined, older quarantined copies **of that same profile** are removed,
+ keeping `profiles.quarantineKeep` of them (default 1). It only ever runs as a side effect
+ of a new quarantine, so a profile that is quarantined once and never again keeps its copy
+ indefinitely, and `profiles.quarantineKeep: 0` — the documented way to keep everything —
+ switches it off entirely.
+- **`pinchtab profiles prune`** reclaims *on demand, across all profiles*. It is the answer
+ to "give me the disk back now", including for quarantines the automatic prune will never
+ revisit. It ignores `quarantineKeep` completely, so keeping everything automatically still
+ leaves an explicit way to reclaim.
+
+Nothing is scheduled and nothing runs at startup; the on-demand path only runs when you ask.
+
+The bare command is a dry run — it prints what it would remove and the total it would free,
+and deletes nothing, so it is safe for an agent to run:
+
+```bash
+$ pinchtab profiles prune
+default.quarantine-1748100001 412.6 MB
+work.quarantine-1748100002 1.1 GB
+
+2 quarantined profile(s), 1.5 GB reclaimable. Nothing was removed; re-run with --confirm.
+```
+
+Only quarantined directories are eligible: live profiles are never removed, whatever you
+pass. `--profile` names a quarantined directory, never a filesystem path — a path is
+refused. To delete a live profile, use the profile delete route instead; this command
+cannot reach one.
+
+Over HTTP the same operation is `POST /profiles/prune`, with `{"confirm": true}` to remove
+and an optional `"profile"` to narrow it. Every removal is logged with its path and the
+bytes it freed.
+
## Configuration And Security
```bash
diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.go
index 4c49ca71..0eef06e5 100644
--- a/internal/bridge/profile_lock.go
+++ b/internal/bridge/profile_lock.go
@@ -161,15 +161,19 @@ type QuarantineRemoval struct {
const KeepAllQuarantinedProfiles = 0
// PruneQuarantinedProfiles keeps the newest `keep` quarantined siblings of one profile
-// and removes the rest, returning what it reclaimed.
+// and removes the rest, returning what it reclaimed. It carries the AUTOMATIC retention
+// policy — a keep count of zero or less means keep everything — which is why the
+// on-demand reclaim below does not go through it: there is no keep value that means
+// "remove them all", so remove-all is expressed by asking removeQuarantinedProfiles for
+// an unranked selection rather than by a sentinel keep count. Both end at the same
+// deleter.
//
-// It is the only deleter that applies the quarantine PREDICATE and the sibling SCOPE,
-// which is the property a user-invoked reclaim needs from it. It is not the only code
-// that can remove a quarantine directory: DELETE /profiles/{id} resolves an id through
-// the profile listing — where a quarantine appears under its own id — and calls
-// ProfileManager.Delete, which removes the directory by name with neither guard. That
-// route is authenticated and audit-logged and is arguably the reclaim a user wants, so
-// the distinction to preserve is which deleter is scoped, not which one exists.
+// It is not the only code that can remove a quarantine directory: DELETE /profiles/{id}
+// resolves an id through the profile listing — where a quarantine appears under its own
+// id — and calls ProfileManager.Delete, which removes the directory by name with neither
+// guard. That route is authenticated and audit-logged and is arguably the reclaim a user
+// wants, so the distinction to preserve is which deleter is scoped, not which one exists.
+// TestOnlyOneFunctionRemovesADirectoryUnderTheProfilesBase is the census of that set.
//
// A user who names a profile exactly "<other profile>.quarantine-<digits>" is
// indistinguishable on disk from a real quarantine; nothing here can tell them apart,
@@ -192,6 +196,13 @@ func PruneQuarantinedProfiles(profileDir, justCreated string, keep int) ([]Quara
if err != nil {
return nil, err
}
+ return removeQuarantinedProfiles(siblingsBeyondKeep(siblings, justCreated, keep)), nil
+}
+
+// siblingsBeyondKeep ranks one profile's quarantined siblings newest first and names the
+// ones the keep count does not cover. Ranking is separated from the deletion so the
+// on-demand reclaim can reach the same deleter with no ranking at all.
+func siblingsBeyondKeep(siblings []quarantinedSibling, justCreated string, keep int) []string {
sort.Slice(siblings, func(i, j int) bool { return siblings[i].stamp > siblings[j].stamp })
// justCreated reserves a slot rather than being ranked, which is what makes the
@@ -204,7 +215,7 @@ func PruneQuarantinedProfiles(profileDir, justCreated string, keep int) ([]Quara
}
}
- var removals []QuarantineRemoval
+ var doomed []string
for _, sibling := range siblings {
if sibling.path == justCreated {
continue
@@ -213,14 +224,100 @@ func PruneQuarantinedProfiles(profileDir, justCreated string, keep int) ([]Quara
budget--
continue
}
- reclaimed := dirBytes(sibling.path)
- if err := os.RemoveAll(sibling.path); err != nil {
- slog.Warn("could not prune quarantined profile", "profile", sibling.path, "err", err)
+ doomed = append(doomed, sibling.path)
+ }
+ return doomed
+}
+
+// removeQuarantinedProfiles is the one function that deletes a quarantined profile
+// directory. It re-applies IsQuarantinedProfileDir to every path it is handed rather
+// than trusting its caller to have filtered: the callers differ in how they select
+// (ranked siblings of one profile, or every quarantine under the base), and a live
+// profile must be unreachable however the selection is shaped, so the guard belongs
+// where the deletion is.
+func removeQuarantinedProfiles(paths []string) []QuarantineRemoval {
+ var removals []QuarantineRemoval
+ for _, path := range paths {
+ if !IsQuarantinedProfileDir(filepath.Base(path)) {
+ slog.Warn("refused to remove a profile that is not quarantined", "profile", path)
+ continue
+ }
+ reclaimed := dirBytes(path)
+ if err := os.RemoveAll(path); err != nil {
+ slog.Warn("could not remove quarantined profile", "profile", path, "err", err)
continue
}
- removals = append(removals, QuarantineRemoval{Path: sibling.path, Bytes: reclaimed})
+ slog.Info("removed quarantined profile", "profile", path, "bytes", reclaimed)
+ removals = append(removals, QuarantineRemoval{Path: path, Bytes: reclaimed})
+ }
+ return removals
+}
+
+// ReclaimableQuarantinedProfiles reports what a reclaim would remove and what it would
+// free, removing nothing. It is the dry run the bare command depends on.
+func ReclaimableQuarantinedProfiles(baseDir, only string) ([]QuarantineRemoval, error) {
+ paths, err := quarantinedProfileSelection(baseDir, only)
+ if err != nil {
+ return nil, err
+ }
+ reclaimable := make([]QuarantineRemoval, 0, len(paths))
+ for _, path := range paths {
+ reclaimable = append(reclaimable, QuarantineRemoval{Path: path, Bytes: dirBytes(path)})
+ }
+ return reclaimable, nil
+}
+
+// ReclaimQuarantinedProfiles removes the quarantined directories a reclaim selects,
+// on demand and with no retention policy: this is the half PruneQuarantinedProfiles
+// cannot express, and it stays reachable when quarantineKeep is set to keep everything.
+func ReclaimQuarantinedProfiles(baseDir, only string) ([]QuarantineRemoval, error) {
+ paths, err := quarantinedProfileSelection(baseDir, only)
+ if err != nil {
+ return nil, err
+ }
+ return removeQuarantinedProfiles(paths), nil
+}
+
+// quarantinedProfileSelection names the quarantined directories directly under baseDir,
+// optionally narrowed to one of them.
+//
+// `only` is matched against the names of directories already enumerated and already
+// found quarantined; it is never joined onto baseDir. That is what makes a traversal
+// impossible rather than merely refused — caller text cannot become a path component
+// here, so no amount of "../" reaches outside the profile root. The explicit refusal
+// below exists so a caller that sends a path gets told that, instead of a bare not-found.
+func quarantinedProfileSelection(baseDir, only string) ([]string, error) {
+ baseDir = strings.TrimSpace(baseDir)
+ if baseDir == "" {
+ return nil, fmt.Errorf("no profiles directory configured")
+ }
+ only = strings.TrimSpace(only)
+ if only != "" && only != filepath.Base(only) {
+ return nil, fmt.Errorf("%q is a path, not a quarantined profile name", only)
+ }
+
+ entries, err := os.ReadDir(baseDir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("read profiles dir: %w", err)
+ }
+
+ var paths []string
+ for _, entry := range entries {
+ if !entry.IsDir() || !IsQuarantinedProfileDir(entry.Name()) {
+ continue
+ }
+ if only != "" && entry.Name() != only {
+ continue
+ }
+ paths = append(paths, filepath.Join(baseDir, entry.Name()))
+ }
+ if only != "" && len(paths) == 0 {
+ return nil, fmt.Errorf("no quarantined profile named %q", only)
}
- return removals, nil
+ return paths, nil
}
type quarantinedSibling struct {
diff --git a/internal/bridge/quarantine_reclaim_test.go b/internal/bridge/quarantine_reclaim_test.go
new file mode 100644
index 00000000..997d555b
--- /dev/null
+++ b/internal/bridge/quarantine_reclaim_test.go
@@ -0,0 +1,420 @@
+package bridge
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/srccensus"
+)
+
+func reclaimFixture(t *testing.T) string {
+ t.Helper()
+
+ base := t.TempDir()
+ writeProfileDir(t, filepath.Join(base, "default"), 32)
+ writeProfileDir(t, filepath.Join(base, "work"), 32)
+ writeProfileDir(t, quarantinePathAt(filepath.Join(base, "default"), 1700000001), 64)
+ writeProfileDir(t, quarantinePathAt(filepath.Join(base, "default"), 1700000002), 128)
+ writeProfileDir(t, quarantinePathAt(filepath.Join(base, "work"), 1700000003), 256)
+ return base
+}
+
+func removalNames(removals []QuarantineRemoval) []string {
+ var names []string
+ for _, removal := range removals {
+ names = append(names, filepath.Base(removal.Path))
+ }
+ return names
+}
+
+func totalBytes(removals []QuarantineRemoval) int64 {
+ var total int64
+ for _, removal := range removals {
+ total += removal.Bytes
+ }
+ return total
+}
+
+// The reclaim the automatic prune cannot express: every quarantined directory under the
+// base goes, across profiles, with no keep count. It reaches quarantines whose profile
+// never quarantines again — the ones the sibling-scoped prune leaves on disk for ever.
+func TestReclaimRemovesEveryQuarantinedProfileAndReportsWhatItFreed(t *testing.T) {
+ base := reclaimFixture(t)
+
+ removed, err := ReclaimQuarantinedProfiles(base, "")
+ if err != nil {
+ t.Fatalf("ReclaimQuarantinedProfiles() error = %v", err)
+ }
+
+ if len(removed) != 3 {
+ t.Fatalf("removed = %v, want all three quarantined directories", removalNames(removed))
+ }
+ if got := totalBytes(removed); got != 64+128+256 {
+ t.Errorf("reclaimed bytes = %d, want %d", got, 64+128+256)
+ }
+ if got := dirNames(t, base); strings.Join(got, ",") != "default,work" {
+ t.Errorf("survivors = %v, want only the two live profiles", got)
+ }
+}
+
+// The bare invocation is the rule an agent depends on, so the assertion is the negative
+// one: the directories are still there afterwards, byte for byte. A test that only
+// checked the reported total would pass on an implementation that deleted them.
+func TestReclaimableReportsTheBacklogWithoutRemovingAnything(t *testing.T) {
+ base := reclaimFixture(t)
+ before := dirNames(t, base)
+
+ reclaimable, err := ReclaimableQuarantinedProfiles(base, "")
+ if err != nil {
+ t.Fatalf("ReclaimableQuarantinedProfiles() error = %v", err)
+ }
+
+ if len(reclaimable) != 3 {
+ t.Fatalf("reclaimable = %v, want the three quarantined directories", removalNames(reclaimable))
+ }
+ if got := totalBytes(reclaimable); got != 64+128+256 {
+ t.Errorf("reclaimable bytes = %d, want %d", got, 64+128+256)
+ }
+ if got := dirNames(t, base); strings.Join(got, ",") != strings.Join(before, ",") {
+ t.Fatalf("directories after the dry run = %v, want the untouched %v", got, before)
+ }
+ for _, removal := range reclaimable {
+ if _, err := os.Stat(filepath.Join(removal.Path, "State")); err != nil {
+ t.Errorf("%s lost its contents to a dry run: %v", removal.Path, err)
+ }
+ }
+}
+
+// quarantineKeep: 0 is the documented way to keep every quarantined copy, and it is the
+// configuration with no other remedy — the automatic prune returns having done nothing,
+// for ever. Reclaim must stay reachable there, which is why it does not take a keep count
+// at all. Both halves are asserted on ONE tree so the comparison is between the two
+// paths and not between two fixtures.
+func TestReclaimStillWorksWhenTheAutomaticPruneIsSetToKeepEverything(t *testing.T) {
+ base := reclaimFixture(t)
+ profileDir := filepath.Join(base, "default")
+
+ pruned, err := PruneQuarantinedProfiles(profileDir, "", KeepAllQuarantinedProfiles)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(pruned) != 0 {
+ t.Fatalf("the automatic prune removed %v under keep-everything", removalNames(pruned))
+ }
+ if len(dirNames(t, base)) != 5 {
+ t.Fatalf("keep-everything changed the tree: %v", dirNames(t, base))
+ }
+
+ removed, err := ReclaimQuarantinedProfiles(base, "")
+ if err != nil {
+ t.Fatalf("ReclaimQuarantinedProfiles() error = %v", err)
+ }
+ if len(removed) != 3 {
+ t.Fatalf("reclaim removed %v under keep-everything, want all three", removalNames(removed))
+ }
+}
+
+// A live profile must be unreachable however the request is shaped. Two live profiles sit
+// beside three quarantines here; what excludes them is IsQuarantinedProfileDir, applied
+// both when the selection is built and again inside the deleter.
+func TestReclaimLeavesLiveProfilesAlone(t *testing.T) {
+ base := reclaimFixture(t)
+
+ if _, err := ReclaimQuarantinedProfiles(base, ""); err != nil {
+ t.Fatalf("ReclaimQuarantinedProfiles() error = %v", err)
+ }
+
+ for _, live := range []string{"default", "work"} {
+ if _, err := os.Stat(filepath.Join(base, live, "State")); err != nil {
+ t.Errorf("live profile %q was removed by a reclaim: %v", live, err)
+ }
+ }
+}
+
+// A user may name a profile "<something>.quarantine-<digits>" and that directory is
+// indistinguishable on disk from a real quarantine — same name shape, same contents, no
+// marker to tell them apart. So it IS reclaimed, and this test states that rather than
+// pretending otherwise. What makes it acceptable: the name is the only thing quarantine
+// itself writes, the product never reads a directory with that name as a profile (the
+// listing flags it quarantined), and reclaim is explicit and confirmed. The exposure is
+// bounded to a user who chose a name the product reserves.
+func TestReclaimTakesALookalikeProfileAndSaysSo(t *testing.T) {
+ base := t.TempDir()
+ writeProfileDir(t, filepath.Join(base, "default"), 32)
+ lookalike := filepath.Join(base, "mine.quarantine-1700000009")
+ writeProfileDir(t, lookalike, 16)
+
+ removed, err := ReclaimQuarantinedProfiles(base, "")
+ if err != nil {
+ t.Fatalf("ReclaimQuarantinedProfiles() error = %v", err)
+ }
+
+ if len(removed) != 1 || removed[0].Path != lookalike {
+ t.Fatalf("removed = %v, want exactly the lookalike", removalNames(removed))
+ }
+ if _, err := os.Stat(filepath.Join(base, "default", "State")); err != nil {
+ t.Errorf("the live profile beside the lookalike was removed: %v", err)
+ }
+ if IsQuarantinedProfileDir("mine") {
+ t.Error("a plain profile name reads as quarantined, so the predicate no longer bounds this")
+ }
+}
+
+// Caller text never becomes a path component: `only` is matched against directories that
+// have already been enumerated and already passed the predicate. A path is refused by
+// name so the caller is told what is wrong, but even without that refusal there is no
+// join for a traversal to escape through.
+func TestReclaimRefusesAPathInsteadOfAProfileName(t *testing.T) {
+ base := reclaimFixture(t)
+ outside := filepath.Join(t.TempDir(), "victim")
+ writeProfileDir(t, outside, 8)
+
+ for _, name := range []string{
+ "../victim",
+ "../../etc",
+ outside,
+ "default.quarantine-1700000001/Default",
+ } {
+ t.Run(name, func(t *testing.T) {
+ _, err := ReclaimQuarantinedProfiles(base, name)
+ if err == nil {
+ t.Fatalf("reclaim accepted %q as a profile name", name)
+ }
+ // Refused AS A PATH, not as a name that happened to match nothing. Both
+ // end in a refusal, so without this the message branch is unpinned: a
+ // caller that sent a path would be told its profile does not exist and go
+ // looking for the wrong thing.
+ if !strings.Contains(err.Error(), "is a path, not a quarantined profile name") {
+ t.Errorf("refusal of %q is %q, want it to say the input is a path", name, err)
+ }
+ if _, err := ReclaimableQuarantinedProfiles(base, name); err == nil {
+ t.Errorf("the dry run accepted %q as a profile name", name)
+ }
+ })
+ }
+
+ if _, err := os.Stat(filepath.Join(outside, "State")); err != nil {
+ t.Errorf("a directory outside the profiles base was removed: %v", err)
+ }
+ if len(dirNames(t, base)) != 5 {
+ t.Errorf("a refused request still changed the tree: %v", dirNames(t, base))
+ }
+}
+
+func TestReclaimNarrowedToOneProfileLeavesTheOtherQuarantinesAlone(t *testing.T) {
+ base := reclaimFixture(t)
+
+ removed, err := ReclaimQuarantinedProfiles(base, "work.quarantine-1700000003")
+ if err != nil {
+ t.Fatalf("ReclaimQuarantinedProfiles() error = %v", err)
+ }
+
+ if len(removed) != 1 || filepath.Base(removed[0].Path) != "work.quarantine-1700000003" {
+ t.Fatalf("removed = %v, want only the named quarantine", removalNames(removed))
+ }
+ if got := len(dirNames(t, base)); got != 4 {
+ t.Errorf("tree has %d entries, want 4: %v", got, dirNames(t, base))
+ }
+}
+
+func TestReclaimRefusesToNameALiveProfile(t *testing.T) {
+ base := reclaimFixture(t)
+
+ if _, err := ReclaimQuarantinedProfiles(base, "default"); err == nil {
+ t.Fatal("reclaim accepted a live profile name")
+ }
+ if _, err := os.Stat(filepath.Join(base, "default", "State")); err != nil {
+ t.Errorf("the live profile named in a refused request was removed: %v", err)
+ }
+}
+
+// The deleter re-applies the predicate rather than trusting the selection it is handed,
+// because the two callers select differently and only this check is common to both. Test
+// it directly: hand it a live profile the way a future third caller might.
+func TestTheQuarantineDeleterRefusesAnythingNotQuarantined(t *testing.T) {
+ base := t.TempDir()
+ live := filepath.Join(base, "default")
+ writeProfileDir(t, live, 32)
+ quarantined := quarantinePathAt(live, 1700000001)
+ writeProfileDir(t, quarantined, 64)
+
+ removed := removeQuarantinedProfiles([]string{live, quarantined})
+
+ if len(removed) != 1 || removed[0].Path != quarantined {
+ t.Fatalf("removed = %v, want only the quarantined directory", removalNames(removed))
+ }
+ if _, err := os.Stat(filepath.Join(live, "State")); err != nil {
+ t.Fatalf("the deleter removed a live profile handed to it directly: %v", err)
+ }
+}
+
+// directoryRemover is one file that removes a directory with os.RemoveAll, the functions
+// in it that do so, and — the answer this census exists to record — whether it applies
+// the quarantine predicate to what it removes.
+//
+// "One owner of the pattern and two owners of the deletion" is the state that lets a
+// later change delete the wrong thing with every test still green, so the count of
+// quarantine-gated deleters is asserted rather than described. The scope is the whole
+// module, not the packages that look relevant: a new deleter under the profiles base is
+// exactly the thing a hand-listed scope cannot see.
+type directoryRemover struct {
+ path string
+ funcs []string
+ underProfilesBase bool
+ quarantineGated bool
+ route string
+ why string
+}
+
+var directoryRemovers = []directoryRemover{
+ {
+ path: "internal/bridge/profile_lock.go",
+ funcs: []string{"removeQuarantinedProfiles"},
+ underProfilesBase: true,
+ quarantineGated: true,
+ route: "POST /profiles/prune with confirm; and quarantineCorruptedProfile via PruneQuarantinedProfiles",
+ why: "the one deleter that applies IsQuarantinedProfileDir to the path it is about to remove, whichever caller selected it",
+ },
+ {
+ path: "internal/profiles/profiles_crud.go",
+ funcs: []string{"remove", "Import", "resetProfileDir"},
+ underProfilesBase: true,
+ quarantineGated: false,
+ route: "DELETE /profiles/{id} (remove, via Delete and ForceDelete), POST /profiles/import (Import), POST /profiles/{id}/reset (resetProfileDir)",
+ why: "remove is id-addressed and in-use-gated but NOT eligibility-gated, so it can reach a live profile by design — that is why a reclaim must never route through it; Import only rolls back the destination it just created; resetProfileDir removes named caches inside one profile, never the profile directory",
+ },
+ {
+ path: "internal/orchestrator/instance_stop.go",
+ funcs: []string{"cleanupStoppedProfile", "markStopped"},
+ underProfilesBase: true,
+ quarantineGated: false,
+ route: "instance stop",
+ why: "cleanupStoppedProfile is gated on the instance- name prefix, which quarantine never produces; markStopped removes the instance state dir, which is not a profile",
+ },
+ {
+ path: "internal/bridge/bridge_lifecycle.go",
+ funcs: []string{"Cleanup", "RestartBrowser"},
+ underProfilesBase: false,
+ route: "bridge shutdown and browser restart",
+ why: "removes b.tempProfileDir, a temp-dir path this process created; never under the configured profiles base",
+ },
+ {
+ path: "internal/bridge/cleanup.go",
+ funcs: []string{"CleanupOrphanedChromeProcesses"},
+ underProfilesBase: false,
+ route: "startup",
+ why: "sweeps os.TempDir() for pinchtab-profile-* leftovers; reads the temp dir, not the profiles base",
+ },
+ {
+ path: "internal/handlers/upload.go",
+ funcs: []string{"HandleUpload", "CleanupStaleUploads"},
+ underProfilesBase: false,
+ route: "POST /upload and its stale sweep",
+ why: "scoped to the upload staging dir under the state dir",
+ },
+ {
+ path: "internal/handlers/record.go",
+ funcs: []string{"cleanup", "stop"},
+ underProfilesBase: false,
+ route: "recording stop",
+ why: "removes the recorder's own temp dir",
+ },
+ {
+ path: "internal/browsers/chrome/cdp_probe.go",
+ funcs: []string{"LaunchAndProbe"},
+ underProfilesBase: false,
+ route: "browser capability probe",
+ why: "removes the throwaway user-data-dir the probe itself created under os.MkdirTemp",
+ },
+ {
+ path: "internal/testbrowser/profile.go",
+ funcs: []string{"removeProfileDir"},
+ underProfilesBase: false,
+ route: "test harness only",
+ why: "removes a t.TempDir-rooted browser profile built for one test",
+ },
+ {
+ path: "tests/tools/runner/internal/e2e/provider.go",
+ funcs: []string{"cleanup", "prepareCloakOverrides", "prepareGhostChromeOverrides"},
+ underProfilesBase: false,
+ route: "e2e runner",
+ why: "removes provider override dirs the runner created under os.MkdirTemp",
+ },
+}
+
+func TestExactlyOneDeleterAppliesTheQuarantinePredicate(t *testing.T) {
+ gated := []string{}
+ for _, remover := range directoryRemovers {
+ if remover.why == "" || remover.route == "" {
+ t.Errorf("%s is censused with no reason and no route, so it records nothing", remover.path)
+ }
+ if remover.quarantineGated {
+ gated = append(gated, remover.path)
+ if !remover.underProfilesBase {
+ t.Errorf("%s is marked quarantine-gated but not under the profiles base", remover.path)
+ }
+ }
+ }
+ if len(gated) != 1 {
+ t.Fatalf("quarantine-gated deleters = %v, want exactly one owner of the deletion", gated)
+ }
+}
+
+// The module-wide half: a new file that removes a directory anywhere in the module must
+// be classified here before it can land. Scope is derived from the tree rather than from
+// the table, so the table cannot narrow what is checked.
+func TestEveryDirectoryRemoverInTheModuleIsCensused(t *testing.T) {
+ censused := map[string]bool{}
+ for _, remover := range directoryRemovers {
+ censused[remover.path] = false
+ }
+
+ for _, file := range srccensus.Tree(t, "../..", 200) {
+ if !strings.Contains(file.Text, "os.RemoveAll(") {
+ continue
+ }
+ if _, listed := censused[file.Name]; !listed {
+ t.Errorf("%s removes a directory with os.RemoveAll and is not censused — add it to directoryRemovers saying whether it applies the quarantine predicate and why that is safe", file.Name)
+ continue
+ }
+ censused[file.Name] = true
+ }
+
+ for path, found := range censused {
+ if !found {
+ t.Errorf("%s is censused as a directory remover but no longer calls os.RemoveAll; drop the entry rather than leaving a stale reason", path)
+ }
+ }
+}
+
+// The function-level half, for the packages that CAN reach the profiles base: every
+// os.RemoveAll site is attributed to a function the census names. A file-level table
+// would keep passing while a new function inside a listed file grew its own deletion.
+func TestEveryRemoverFunctionUnderTheProfilesBaseIsNamed(t *testing.T) {
+ for _, pkg := range []struct{ dir, prefix string }{
+ {".", "internal/bridge/"},
+ {"../profiles", "internal/profiles/"},
+ {"../orchestrator", "internal/orchestrator/"},
+ } {
+ loaded := srccensus.Load(t, pkg.dir, 3)
+ sites := loaded.Calls(t, "os.RemoveAll")
+ for _, site := range sites {
+ named := false
+ for _, remover := range directoryRemovers {
+ if remover.path != pkg.prefix+site.File {
+ continue
+ }
+ for _, fn := range remover.funcs {
+ if fn == site.Func {
+ named = true
+ }
+ }
+ }
+ if !named {
+ t.Errorf("%s removes a directory at %s and is not named in the census entry for %s", site.Func, site, pkg.prefix+site.File)
+ }
+ }
+ }
+}
diff --git a/internal/cli/actions/actions_profiles_prune_test.go b/internal/cli/actions/actions_profiles_prune_test.go
new file mode 100644
index 00000000..9c75d90e
--- /dev/null
+++ b/internal/cli/actions/actions_profiles_prune_test.go
@@ -0,0 +1,130 @@
+package actions
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func newPruneTestCmd(args ...string) *cobra.Command {
+ cmd := &cobra.Command{Use: "prune"}
+ cmd.Flags().Bool("confirm", false, "")
+ cmd.Flags().String("profile", "", "")
+ cmd.Flags().Bool("json", false, "")
+ _ = cmd.ParseFlags(args)
+ return cmd
+}
+
+// pruneStub answers /profiles/prune and records the body it was sent, so the assertions
+// can be about what the CLI ASKED for rather than only what it printed.
+func pruneStub(t *testing.T, response string, sent *pruneQuarantinedBody, hits *atomic.Int32) *httptest.Server {
+ t.Helper()
+
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/profiles/prune" {
+ t.Errorf("CLI requested %s, want /profiles/prune", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ hits.Add(1)
+ body, _ := io.ReadAll(r.Body)
+ if err := json.Unmarshal(body, sent); err != nil {
+ t.Errorf("CLI sent a body that is not the documented shape (%v): %s", err, body)
+ }
+ _, _ = w.Write([]byte(response))
+ }))
+}
+
+type pruneQuarantinedBody struct {
+ Confirm bool `json:"confirm"`
+ Profile string `json:"profile"`
+}
+
+// Without --confirm the CLI must send confirm:false. The server decides what that means,
+// but a CLI that sent true would delete on the invocation documented as a dry run, and no
+// assertion about printed text could see it.
+func TestProfilesPruneWithoutConfirmAsksForADryRun(t *testing.T) {
+ var sent pruneQuarantinedBody
+ var hits atomic.Int32
+ srv := pruneStub(t, `{"removed":false,"count":2,"totalBytes":1500,"profiles":[
+ {"name":"default.quarantine-1700000001","bytes":500},
+ {"name":"work.quarantine-1700000002","bytes":1000}]}`, &sent, &hits)
+ defer srv.Close()
+
+ out := captureStdout(t, func() {
+ ProfilesPrune(srv.Client(), srv.URL, "", newPruneTestCmd())
+ })
+
+ if hits.Load() != 1 {
+ t.Fatalf("server saw %d requests, want 1", hits.Load())
+ }
+ if sent.Confirm {
+ t.Error("the bare command sent confirm:true, so it would delete on the invocation documented as a dry run")
+ }
+ if !strings.Contains(out, "re-run with --confirm") {
+ t.Errorf("dry-run output does not say how to actually reclaim: %q", out)
+ }
+ if strings.Contains(out, "Reclaimed") {
+ t.Errorf("dry-run output claims it reclaimed something: %q", out)
+ }
+ if !strings.Contains(out, "1.5 KB reclaimable") {
+ t.Errorf("dry-run output does not report the reclaimable total: %q", out)
+ }
+}
+
+func TestProfilesPruneWithConfirmAsksForRemovalAndReportsWhatWasFreed(t *testing.T) {
+ var sent pruneQuarantinedBody
+ var hits atomic.Int32
+ srv := pruneStub(t, `{"removed":true,"count":1,"totalBytes":2048,"profiles":[
+ {"name":"default.quarantine-1700000001","bytes":2048}]}`, &sent, &hits)
+ defer srv.Close()
+
+ out := captureStdout(t, func() {
+ ProfilesPrune(srv.Client(), srv.URL, "", newPruneTestCmd("--confirm"))
+ })
+
+ if !sent.Confirm {
+ t.Error("--confirm did not reach the request body, so the server would answer a dry run")
+ }
+ if !strings.Contains(out, "Reclaimed 1 quarantined profile(s), 2.0 KB freed") {
+ t.Errorf("output does not report what was freed: %q", out)
+ }
+}
+
+func TestProfilesPruneForwardsTheNamedProfile(t *testing.T) {
+ var sent pruneQuarantinedBody
+ var hits atomic.Int32
+ srv := pruneStub(t, `{"removed":true,"count":1,"totalBytes":10,"profiles":[{"name":"work.quarantine-1700000002","bytes":10}]}`, &sent, &hits)
+ defer srv.Close()
+
+ captureStdout(t, func() {
+ ProfilesPrune(srv.Client(), srv.URL, "", newPruneTestCmd("--confirm", "--profile", "work.quarantine-1700000002"))
+ })
+
+ if sent.Profile != "work.quarantine-1700000002" {
+ t.Errorf("request carried profile %q, want the name the user passed — a dropped selector reclaims everything instead of one directory", sent.Profile)
+ }
+}
+
+// An empty backlog is the common case on a healthy machine and must not print an empty
+// list that reads as an error.
+func TestProfilesPruneSaysSoWhenThereIsNothingToReclaim(t *testing.T) {
+ var sent pruneQuarantinedBody
+ var hits atomic.Int32
+ srv := pruneStub(t, `{"removed":false,"count":0,"totalBytes":0,"profiles":[]}`, &sent, &hits)
+ defer srv.Close()
+
+ out := captureStdout(t, func() {
+ ProfilesPrune(srv.Client(), srv.URL, "", newPruneTestCmd())
+ })
+
+ if !strings.Contains(out, "No quarantined profiles to reclaim") {
+ t.Errorf("output = %q, want it to say there is nothing to reclaim", out)
+ }
+}
diff --git a/internal/cli/actions/actions_system.go b/internal/cli/actions/actions_system.go
index 47b05a6e..0fc74a3f 100644
--- a/internal/cli/actions/actions_system.go
+++ b/internal/cli/actions/actions_system.go
@@ -111,6 +111,50 @@ func Profiles(client *http.Client, base, token string, cmd *cobra.Command) {
fmt.Print(formatProfileList(profiles))
}
+// ProfilesPrune reclaims quarantine backlog. Without --confirm it reports what would go
+// and frees nothing, so the bare invocation is safe for an agent to run.
+func ProfilesPrune(client *http.Client, base, token string, cmd *cobra.Command) {
+ confirm, _ := cmd.Flags().GetBool("confirm")
+ profile, _ := cmd.Flags().GetString("profile")
+ body := map[string]any{"confirm": confirm}
+ if profile != "" {
+ body["profile"] = profile
+ }
+
+ if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ apiclient.DoPost(client, base, token, "/profiles/prune", body)
+ return
+ }
+
+ raw := apiclient.DoPostRaw(client, base, token, "/profiles/prune", body)
+ var resp struct {
+ Removed bool `json:"removed"`
+ Count int `json:"count"`
+ TotalBytes int64 `json:"totalBytes"`
+ Profiles []struct {
+ Name string `json:"name"`
+ Bytes int64 `json:"bytes"`
+ } `json:"profiles"`
+ }
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse prune response: %v\n", err)
+ os.Exit(1)
+ }
+
+ if resp.Count == 0 {
+ fmt.Println("No quarantined profiles to reclaim")
+ return
+ }
+ for _, prof := range resp.Profiles {
+ fmt.Printf("%s\t%s\n", prof.Name, formatBytes(prof.Bytes))
+ }
+ if resp.Removed {
+ fmt.Printf("\nReclaimed %d quarantined profile(s), %s freed\n", resp.Count, formatBytes(resp.TotalBytes))
+ return
+ }
+ fmt.Printf("\n%d quarantined profile(s), %s reclaimable. Nothing was removed; re-run with --confirm.\n", resp.Count, formatBytes(resp.TotalBytes))
+}
+
// formatProfileList lists user profiles first, then the quarantined
// directories under a heading carrying their count and combined size, so an
// operator sees what quarantine is holding without inferring it from names.
diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.go
index c7321795..b214ff14 100644
--- a/internal/profiles/handlers.go
+++ b/internal/profiles/handlers.go
@@ -3,7 +3,9 @@ package profiles
import (
"errors"
"fmt"
+ "io"
"net/http"
+ "path/filepath"
"strconv"
"time"
@@ -76,6 +78,7 @@ func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /profiles/{id}", pm.handleGetByID)
mux.HandleFunc("POST /profiles/import", pm.handleImport)
+ mux.HandleFunc("POST /profiles/prune", pm.handlePruneQuarantined)
mux.HandleFunc("PATCH /profiles/meta", pm.handleUpdateMeta)
mux.HandleFunc("POST /profiles/{id}/reset", pm.handleResetByIDOrName)
mux.HandleFunc("GET /profiles/{id}/logs", pm.handleLogsByIDOrName)
@@ -221,6 +224,87 @@ func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request)
httpx.Error(w, 404, fmt.Errorf("profile %q not found", id))
}
+type pruneQuarantinedRequest struct {
+ Profile string `json:"profile"`
+ Confirm bool `json:"confirm"`
+}
+
+// handlePruneQuarantined reclaims quarantine backlog on demand. It is destructive only
+// on an explicit confirm: without one it answers what it WOULD remove, because an agent
+// piping this command must not free disk by accident.
+//
+// It reaches bridge's quarantine deleter, never pm.Delete: that one resolves a name
+// through the profile listing and removes whatever it finds with no eligibility rule, so
+// routing a reclaim through it would make this a second, looser way to remove a live
+// profile. TestReclaimNeverReachesTheUnguardedProfileDeleter holds that.
+func (pm *ProfileManager) handlePruneQuarantined(w http.ResponseWriter, r *http.Request) {
+ req, err := decodePruneRequest(w, r)
+ if err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
+ }
+
+ if !req.Confirm {
+ reclaimable, err := bridge.ReclaimableQuarantinedProfiles(pm.baseDir, req.Profile)
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ httpx.JSON(w, 200, quarantineReclaimResponse(reclaimable, false))
+ return
+ }
+
+ removed, err := bridge.ReclaimQuarantinedProfiles(pm.baseDir, req.Profile)
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ authn.AuditLog(r, "profiles.quarantine.reclaimed", "count", len(removed), "bytes", totalReclaimedBytes(removed))
+ httpx.JSON(w, 200, quarantineReclaimResponse(removed, true))
+}
+
+// decodePruneRequest accepts the selection from the body or the query string, and treats
+// an absent body as the bare invocation rather than a malformed one — the dry run is what
+// a caller sending nothing is asking for.
+func decodePruneRequest(w http.ResponseWriter, r *http.Request) (pruneQuarantinedRequest, error) {
+ var req pruneQuarantinedRequest
+ if err := httpx.DecodeJSONBody(w, r, 0, &req); err != nil && !errors.Is(err, io.EOF) {
+ return req, err
+ }
+ if req.Profile == "" {
+ req.Profile = r.URL.Query().Get("profile")
+ }
+ if r.URL.Query().Get("confirm") == "true" {
+ req.Confirm = true
+ }
+ return req, nil
+}
+
+func quarantineReclaimResponse(removals []bridge.QuarantineRemoval, removed bool) map[string]any {
+ profiles := make([]map[string]any, 0, len(removals))
+ for _, removal := range removals {
+ profiles = append(profiles, map[string]any{
+ "name": filepath.Base(removal.Path),
+ "path": removal.Path,
+ "bytes": removal.Bytes,
+ })
+ }
+ return map[string]any{
+ "removed": removed,
+ "count": len(removals),
+ "totalBytes": totalReclaimedBytes(removals),
+ "profiles": profiles,
+ }
+}
+
+func totalReclaimedBytes(removals []bridge.QuarantineRemoval) int64 {
+ var total int64
+ for _, removal := range removals {
+ total += removal.Bytes
+ }
+ return total
+}
+
func (pm *ProfileManager) handleDeleteByID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
diff --git a/internal/profiles/quarantine_reclaim_test.go b/internal/profiles/quarantine_reclaim_test.go
new file mode 100644
index 00000000..70dd5574
--- /dev/null
+++ b/internal/profiles/quarantine_reclaim_test.go
@@ -0,0 +1,328 @@
+package profiles
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/srccensus"
+)
+
+type pruneResult struct {
+ Removed bool `json:"removed"`
+ Count int `json:"count"`
+ TotalBytes int64 `json:"totalBytes"`
+ Profiles []struct {
+ Name string `json:"name"`
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ } `json:"profiles"`
+}
+
+func writeSizedProfile(t *testing.T, baseDir, name string, bytes int) {
+ t.Helper()
+
+ dir := filepath.Join(baseDir, name, "Default")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "State"), make([]byte, bytes), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func reclaimBase(t *testing.T) string {
+ t.Helper()
+
+ base := t.TempDir()
+ writeSizedProfile(t, base, "default", 100)
+ writeSizedProfile(t, base, "default.quarantine-1700000001", 200)
+ writeSizedProfile(t, base, "work.quarantine-1700000002", 300)
+ return base
+}
+
+func postPrune(t *testing.T, pm *ProfileManager, target string, body string) (int, pruneResult) {
+ t.Helper()
+
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ req := httptest.NewRequest(http.MethodPost, target, http.NoBody)
+ if body != "" {
+ req = httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
+ }
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, req)
+
+ var out pruneResult
+ if rec.Code == http.StatusOK {
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+ t.Fatalf("prune response is not the documented shape (%v): %s", err, rec.Body.String())
+ }
+ }
+ return rec.Code, out
+}
+
+func quarantineDirsOnDisk(t *testing.T, base string) []string {
+ t.Helper()
+
+ entries, err := os.ReadDir(base)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, entry := range entries {
+ if entry.IsDir() && bridge.IsQuarantinedProfileDir(entry.Name()) {
+ names = append(names, entry.Name())
+ }
+ }
+ return names
+}
+
+// The bare invocation reports and deletes nothing. The assertion that matters is the
+// negative one — the directories are still on disk with their contents — because a
+// handler that deleted while reporting the same total would pass a total-only check.
+func TestBarePruneReportsTheBacklogAndDeletesNothing(t *testing.T) {
+ base := reclaimBase(t)
+ pm := NewProfileManager(base)
+
+ code, out := postPrune(t, pm, "/profiles/prune", "")
+
+ if code != http.StatusOK {
+ t.Fatalf("POST /profiles/prune = %d, want 200", code)
+ }
+ if out.Removed {
+ t.Error("the bare invocation reported removed=true")
+ }
+ if out.Count != 2 {
+ t.Fatalf("count = %d, want the two quarantined profiles: %+v", out.Count, out.Profiles)
+ }
+ if out.TotalBytes != 500 {
+ t.Errorf("totalBytes = %d, want 500", out.TotalBytes)
+ }
+
+ if got := quarantineDirsOnDisk(t, base); len(got) != 2 {
+ t.Fatalf("quarantined directories after a bare prune = %v, want both still there", got)
+ }
+ for _, prof := range out.Profiles {
+ if _, err := os.Stat(filepath.Join(prof.Path, "Default", "State")); err != nil {
+ t.Errorf("%s lost its contents to a bare prune: %v", prof.Name, err)
+ }
+ }
+}
+
+// Real directories on disk, not a mock: the reclaimed total is the bytes the files
+// actually held, and the tree afterwards holds only the live profile.
+func TestConfirmedPruneRemovesTheQuarantinedDirectoriesAndReportsWhatItFreed(t *testing.T) {
+ base := reclaimBase(t)
+ pm := NewProfileManager(base)
+
+ code, out := postPrune(t, pm, "/profiles/prune", `{"confirm":true}`)
+
+ if code != http.StatusOK {
+ t.Fatalf("POST /profiles/prune = %d, want 200", code)
+ }
+ if !out.Removed || out.Count != 2 {
+ t.Fatalf("removed = %v count = %d, want both quarantines removed", out.Removed, out.Count)
+ }
+ if out.TotalBytes != 500 {
+ t.Errorf("totalBytes = %d, want 500", out.TotalBytes)
+ }
+ if got := quarantineDirsOnDisk(t, base); len(got) != 0 {
+ t.Fatalf("quarantined directories after a confirmed prune = %v, want none", got)
+ }
+ if _, err := os.Stat(filepath.Join(base, "default", "Default", "State")); err != nil {
+ t.Errorf("the live profile was removed by a prune: %v", err)
+ }
+}
+
+func TestConfirmMayAlsoArriveOnTheQueryString(t *testing.T) {
+ base := reclaimBase(t)
+ pm := NewProfileManager(base)
+
+ code, out := postPrune(t, pm, "/profiles/prune?confirm=true", "")
+
+ if code != http.StatusOK || !out.Removed {
+ t.Fatalf("POST /profiles/prune?confirm=true = %d removed=%v, want a confirmed removal", code, out.Removed)
+ }
+ if got := quarantineDirsOnDisk(t, base); len(got) != 0 {
+ t.Errorf("quarantined directories = %v, want none", got)
+ }
+}
+
+// A live profile is unreachable however the request is shaped. Naming one is refused
+// because the selector is matched against directories that already passed the quarantine
+// predicate, so a live name simply is not in the set.
+func TestPruneRefusesToNameALiveProfile(t *testing.T) {
+ base := reclaimBase(t)
+ pm := NewProfileManager(base)
+
+ code, _ := postPrune(t, pm, "/profiles/prune", `{"confirm":true,"profile":"default"}`)
+
+ if code != http.StatusBadRequest {
+ t.Fatalf("naming a live profile = %d, want 400", code)
+ }
+ if _, err := os.Stat(filepath.Join(base, "default", "Default", "State")); err != nil {
+ t.Fatalf("the live profile named in a refused prune was removed: %v", err)
+ }
+ if got := quarantineDirsOnDisk(t, base); len(got) != 2 {
+ t.Errorf("a refused prune still changed the tree: %v", got)
+ }
+}
+
+// The caller names a profile or asks for all of them, never a filesystem path.
+func TestPruneRefusesAPathOutsideTheProfileRoot(t *testing.T) {
+ outsideRoot := t.TempDir()
+ writeSizedProfile(t, outsideRoot, "victim.quarantine-1700000009", 64)
+
+ for _, name := range []string{
+ "../victim.quarantine-1700000009",
+ "../../etc",
+ filepath.Join(outsideRoot, "victim.quarantine-1700000009"),
+ } {
+ t.Run(name, func(t *testing.T) {
+ base := reclaimBase(t)
+ pm := NewProfileManager(base)
+
+ body, err := json.Marshal(map[string]any{"confirm": true, "profile": name})
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, _ := postPrune(t, pm, "/profiles/prune", string(body))
+
+ if code != http.StatusBadRequest {
+ t.Fatalf("prune of %q = %d, want 400", name, code)
+ }
+ if got := quarantineDirsOnDisk(t, base); len(got) != 2 {
+ t.Errorf("a refused prune still changed the tree: %v", got)
+ }
+ })
+ }
+
+ if _, err := os.Stat(filepath.Join(outsideRoot, "victim.quarantine-1700000009", "Default", "State")); err != nil {
+ t.Fatalf("a directory outside the profiles base was removed: %v", err)
+ }
+}
+
+// A profile whose own name ends in the quarantine suffix IS reclaimed — it is
+// byte-identical on disk to a real quarantine and nothing can tell them apart. What
+// bounds it: the shape is one the product reserves and writes itself, the listing already
+// shows such a directory as quarantined so the user sees it before confirming, and the
+// removal only happens on an explicit confirm.
+func TestPruneTakesALookalikeProfileAndTheListingWarnedAboutIt(t *testing.T) {
+ base := t.TempDir()
+ writeSizedProfile(t, base, "default", 100)
+ writeSizedProfile(t, base, "mine.quarantine-1700000009", 64)
+ pm := NewProfileManager(base)
+
+ listed := findListed(listProfiles(t, pm, ""), "mine.quarantine-1700000009")
+ if listed == nil {
+ t.Fatal("the lookalike is absent from the listing, so a user could not see it before confirming")
+ }
+ if listed["quarantined"] != true {
+ t.Errorf("the lookalike lists as quarantined = %v, want true — the warning a user gets is the listing", listed["quarantined"])
+ }
+
+ code, out := postPrune(t, pm, "/profiles/prune", `{"confirm":true}`)
+
+ if code != http.StatusOK || out.Count != 1 {
+ t.Fatalf("prune = %d count = %d, want the lookalike removed", code, out.Count)
+ }
+ if _, err := os.Stat(filepath.Join(base, "default", "Default", "State")); err != nil {
+ t.Errorf("the live profile beside the lookalike was removed: %v", err)
+ }
+}
+
+// After a reclaim the listing and the health count must agree with the disk. The health
+// envelope counts p.Quarantined over profileLister.List(), an interface with List as its
+// ONLY method, so it cannot read anything but what is asserted here.
+func TestTheListingAndTheHealthCountAgreeWithTheDiskAfterAReclaim(t *testing.T) {
+ base := reclaimBase(t)
+ pm := NewProfileManager(base)
+
+ if code, _ := postPrune(t, pm, "/profiles/prune", `{"confirm":true}`); code != http.StatusOK {
+ t.Fatalf("prune = %d, want 200", code)
+ }
+
+ onDisk := len(quarantineDirsOnDisk(t, base))
+
+ listed := listProfiles(t, pm, "?all=true")
+ listedQuarantined := 0
+ for _, entry := range listed {
+ if entry["quarantined"] == true {
+ listedQuarantined++
+ }
+ }
+
+ infos, err := pm.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ healthQuarantined := 0
+ for _, info := range infos {
+ if info.Quarantined {
+ healthQuarantined++
+ }
+ }
+
+ if onDisk != 0 || listedQuarantined != onDisk || healthQuarantined != onDisk {
+ t.Errorf("after a reclaim disk = %d, listing = %d, health = %d; all three must agree", onDisk, listedQuarantined, healthQuarantined)
+ }
+ if len(listed) != 1 {
+ t.Errorf("listing has %d entries, want just the live profile: %v", len(listed), listed)
+ }
+}
+
+// Exposing ProfileManager.Delete as the reclaim route is the short path the card forbids:
+// it resolves a name through the profile listing and removes what it finds with no
+// eligibility rule, so a reclaim routed through it becomes a second, looser way to reach
+// a live profile. A prose prohibition is one the next contributor takes anyway, so it is
+// asserted here — implement it and this reddens by name.
+func TestReclaimNeverReachesTheUnguardedProfileDeleter(t *testing.T) {
+ pkg := srccensus.Load(t, ".", 5)
+
+ fn, ok := pkg.Func("handlePruneQuarantined")
+ if !ok {
+ t.Fatal("handlePruneQuarantined not found; the reclaim route was renamed and this census is reading nothing")
+ }
+
+ // Both spellings of each: the AST callee for a method call carries the receiver name,
+ // so banning the bare identifier alone would match a free function and miss pm.Delete
+ // — which is the call this census exists to catch.
+ banned := []string{
+ "pm.Delete", "Delete",
+ "pm.ForceDelete", "ForceDelete",
+ "pm.remove", "remove",
+ "pm.findProfileDirByName", "findProfileDirByName",
+ "pm.resolveIDOnly", "resolveIDOnly",
+ "os.RemoveAll",
+ }
+ for _, name := range banned {
+ for _, site := range pkg.CallsAllowingNone(name) {
+ if pkg.Contains(fn, site) {
+ t.Errorf("the reclaim route calls %s at %s — that reaches a directory with no quarantine predicate, which is exactly the second, looser deleter this route must not become", name, site)
+ }
+ }
+ }
+
+ // The floor under the receiver-qualified half: pm.Delete must still be the spelling
+ // this package uses, or the ban above is checking a name nothing is called by. Calls
+ // fails when it matches nothing, so renaming the receiver reddens here instead of
+ // quietly disarming the census.
+ pkg.Calls(t, "pm.Delete")
+
+ reached := false
+ for _, site := range pkg.CallsAllowingNone("bridge.ReclaimQuarantinedProfiles") {
+ if pkg.Contains(fn, site) {
+ reached = true
+ }
+ }
+ if !reached {
+ t.Error("the reclaim route no longer calls bridge.ReclaimQuarantinedProfiles, so it removes quarantined profiles some other way and the predicate is not shared")
+ }
+}