From b2b12ee55dc2805955ee16d419dcff9bcff79a69 Mon Sep 17 00:00:00 2001 From: w3cj Date: Sun, 8 Nov 2026 16:34:40 -0700 Subject: [PATCH] feat(gitprotect): protect every repo nested in a VM's folder A VM over a folder of repos now protects each nested git repo, not only the folder's own: one walk (hostsafety.Walk, at most 4 folders down and 100 repos, no symlinks, one device) finds them, and each is locked on macOS, pinned on Linux or watched where Linux can't pin, scanned within its own top folder and the mount. A repo counts as covered only when a scan locks its git dir; git dirs follow git's own rule, .git is matched without case on macOS, and a recorded repo stays protected while anything is at its .git. Repos the walk can't protect, that appear, that leave or that look like bare repos are named, with the config keys and hooks a VM-made repo would run. Existing VMs get a one-time notice and opt in with devvm git-protect on. Ownership fails closed under one host lock, so a VM never unlocks what another protects; one scan budget covers every repo, and launches into a running VM check only the top repo. devvm doctor gives a tip to set safe.bareRepository=explicit, reading the user's GIT_CONFIG_GLOBAL when set. Refs #3. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/content/docs/contributing/structure.md | 1 + docs/content/docs/internals/design.md | 28 +- docs/content/docs/internals/git-protection.md | 49 +- docs/content/docs/internals/install.md | 6 +- docs/content/docs/safety/attack-vectors.md | 1 + docs/content/docs/safety/git-protection.md | 39 +- docs/content/docs/using/vms.md | 4 +- internal/backend/backend.go | 5 + internal/backend/lima/pins.go | 36 +- internal/backend/lima/pins_test.go | 42 +- internal/backend/lima/start_test.go | 7 +- internal/cli/doctor.go | 40 +- internal/cli/doctor_test.go | 4 +- internal/cli/json_test.go | 4 +- internal/cli/script_test.go | 4 + internal/gitprotect/gitprotect.go | 225 +++++- internal/gitprotect/gitprotect_test.go | 2 +- internal/gitprotect/nested.go | 237 ++++++ internal/gitprotect/nested_test.go | 682 ++++++++++++++++++ internal/gitprotect/pins.go | 78 +- internal/gitprotect/report.go | 115 ++- internal/gitprotect/report_test.go | 25 +- internal/gitprotect/repos.go | 207 ++++++ internal/gitprotect/scan.go | 140 +++- internal/gitprotect/watch.go | 111 ++- internal/hostgit/hostgit.go | 50 ++ internal/hostgit/hostgit_test.go | 59 ++ internal/hostsafety/hostsafety.go | 249 ++++++- internal/hostsafety/hostsafety_test.go | 124 +++- internal/msg/docs.go | 17 + internal/msg/messages_gen.go | 102 +++ internal/paths/dirs.go | 6 + internal/paths/vm.go | 12 +- internal/paths/vm_test.go | 7 +- internal/platform/folder_darwin.go | 4 + internal/platform/folder_linux.go | 4 + internal/platform/folder_other.go | 4 + internal/structure/owners_doc_test.go | 5 + internal/structure/structure_test.go | 4 +- internal/vm/clone.go | 5 +- internal/vm/env.go | 21 +- internal/vm/inventory.go | 31 + internal/vm/inventory_test.go | 45 ++ internal/vm/settings.go | 9 +- internal/vm/start.go | 38 +- internal/vm/sync.go | 12 +- internal/vm/teardown_test.go | 2 +- locales/en.toml | 70 ++ testdata/script/doctor.txtar | 14 +- testdata/script/git_nested.txtar | 85 +++ testdata/script/publish.txtar | 20 +- testdata/script/qemu.txtar | 10 +- tests/e2e/gitpins_test.go | 23 +- tests/e2e/nestedrepos_test.go | 164 +++++ tests/e2e/project_test.go | 1 + 56 files changed, 3029 insertions(+), 262 deletions(-) create mode 100644 internal/gitprotect/nested.go create mode 100644 internal/gitprotect/nested_test.go create mode 100644 internal/gitprotect/repos.go create mode 100644 testdata/script/git_nested.txtar create mode 100644 tests/e2e/nestedrepos_test.go diff --git a/AGENTS.md b/AGENTS.md index a3295f16..c10b8971 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch | `internal/cli/` | the command line: Cobra commands, one file each (doctor's check of Linux's pins in `pins.go`), each carrying its own docs page, help group and why it has no `--json` (its `about`); the run's services (`app.go`), argument and flag checks (usage errors), help, `--json`, the CLI tests and `docgen/` (the CLI reference); `doc.go` maps the package | | `internal/vm/` | what each command does to a folder's VM, below the command line: `Env` and its parts, the one start, the finder, the inventory, `Launch`, the agents' store, logins and saves, `Lifecycle` and the one remake, `Housekeeping`, `Settings`, `Net`, `Links`; `doc.go` maps the package and its owners | | `internal/shell/`, `internal/vmname/` | stdlib leaves: quoting for a POSIX shell (`Quote`, `QuoteJoin`) and its variables' names (`EnvName`); a project VM's name grammar (`Prefix`, `HashLen`, `IsVM`, `HashOf`, `SlugOf`, a remake's `Aside`) | -| `internal/project/`, `internal/gitprotect/`, `internal/hostsafety/`, `internal/hostgit/` | a project folder (VM name, link targets, unsafe folders, parents); `.git` protection (one `scan` per check, a `Locker` per host: `Flags` on macOS, `Binds` on Linux, which the start pins, else `Watch`; the reports' table); the folder's other host checks (set-id files, skipping `.git`, once stopped; an SSH origin); every host git command devvm runs (no fsmonitor, hooks or filters, ssh only, no `GIT_*` of the environment, no prompts) | +| `internal/project/`, `internal/gitprotect/`, `internal/hostsafety/`, `internal/hostgit/` | a project folder (VM name, link targets, unsafe folders, parents); `.git` protection (one `scan` per check, a `Locker` per host: `Flags` on macOS, `Binds` on Linux, which the start pins, else `Watch`; the reports' table); the folder's other host checks (one `Walk`, once stopped: set-id files and nested repos, skipping `.git`; an SSH origin); every host git command devvm runs (no fsmonitor, hooks or filters, ssh only, no `GIT_*` of the environment, no prompts) | | `internal/sshconfig/`, `internal/sshagent/` | the ssh config for running VMs by name, the `~/.ssh/config` Include line; each VM's SSH agent choice, devvm's own agent and its keys | | `internal/build/`, `internal/image/` | building and rebuilding images, their records; image keys and names (pure), and the shared tools' registry (`SharedTools`: one entry per toolchain, its members, detection, installer, guest environment, `PATH` folders and version files; the structure test's `names`) | | `internal/fetch/` | every HTTP client (stdlib): `NewClient` (timeout, `HTTPSOnly`/`SameScheme`), `Retry`/`Transient`, `ReadCapped`, `Get`, `Resolve` (where a HEAD's redirects end), `Download` (checks the SHA-256, capped) | diff --git a/docs/content/docs/contributing/structure.md b/docs/content/docs/contributing/structure.md index 2a60693e..5e2aee0e 100644 --- a/docs/content/docs/contributing/structure.md +++ b/docs/content/docs/contributing/structure.md @@ -65,6 +65,7 @@ An owner gets a check only when a second copy would be a bug or a security hole, | the structure test's `owners`, the toolchains | `internal/image`, whose `SharedTools` holds every fact devvm keeps of each toolchain: its members, the files that call for it, its installer, its guest environment, its `PATH` folders and its version files. A string literal that is a toolchain's name or a member's, whole, fails, so code elsewhere asks the table, and a new toolchain is an entry there ([adding a toolchain](extending.md#adding-a-toolchain)) | `internal/stubtest`, and tests | | the structure test's `owners`, image names | `internal/image`, whose `Name` is an image's name and splits it into its layers (`Layers`, `Parent`, `Has`), whose `NameOf` joins layers into one, and whose `ParseName` reads the name the user gives, which `build.Names`' `Parse` checks against the layers there are. `devvm build`, `devvm rebuild` and `devvm images rm` read their names there once, and the rest of devvm passes the `image.Name` on | tests | | the structure test's `owners`, `state.ReadHash` and `project.Parents` | the finder in `internal/vm/finder.go`, whose `target` finds the VM every command acts on: the folder's own, the nearest parent folder's under `--here` and `--parent` (`resolveFolder`), or one named (`devvm rm VM`). It finds a folder's VM by the state that records the folder (`finder.state`, by the path's hash first, then `recorded`), offers to move a VM whose folder moved there (`moveHere` in `internal/vm/move.go`, the match `here.movedFrom`), and names a new VM by the first of the folder's names whose VM folder is free (`newName`, `project.Nth`). Its `need` says what the command needs of the VM, and `need.check` is the one place that refuses one that isn't there, one made for an earlier folder at its path, one whose remake didn't finish and one whose creation didn't, the last with `refuseUnfinished`, which every start (`starter.bringUp` in `internal/vm/start.go`) makes too. It reads the folder devvm runs in only then, so the commands that act on no folder's VM run in a folder that's gone. The VM it finds is a `target` (`internal/vm/target.go`). It holds what the VM's backend told the finder, which each start and stop of the VM then updates, and it runs what a command does with that VM: `exec`, `shell`, `stop`, `running`, `ownSSH` and the name of its ssh config entry | `internal/state`, and tests | +| the structure test's `owners`, `hostsafety.Walk` | the start in `internal/vm/start.go`, whose `starter.walk` walks a VM's project folder once for each check of the folder on the host, for the git repos nested in it, which `.git` protection goes by (`gitprotect.Protector.Nested`), and on Linux hosts its set-id files, so a check never walks the folder twice. It walks when a VM is made and when a check finds it stopped, at a launch or at `devvm stop` (`starter.hostChecks`), and at `devvm git-protect` on a stopped VM, never at a launch into a running VM | `internal/hostsafety`, and tests | | the structure test's `owners`, `state.ReadAll` | the inventory in `internal/vm/inventory.go`, which reads every VM's state (`ReadStates`), and with `ReadInventory` the backends' lists too, each within its wait, for every listing of VMs: `devvm ls`, `devvm space`, `devvm images` and `devvm gc`, the ssh config, `devvm gc --orphans`, the links, `devvm secret`'s list, finding a VM by its name and the mounts that devvm's SSH agent checks a key against. Its one failure policy is that a backend that can't list fails a listing (`Inventory.Err`) only when some VM's state names it, and that a state that can't be read is a row of its own, which the readers leave out and `ToolsInUse` and `Mounts` fail on. `state.VMNames`, which fails on such a state, stays for the readers below `internal/vm`: `netpolicy`, `ports` and `sshconfig.ChooseAlias` | `internal/state`, and tests | | the structure test's `owners`, `paths.Dirs.AgentSettings` and `paths.Dirs.AgentLogins` | devvm's agent store: `agentStore` in `internal/vm/agents.go` for the agents' settings, which the mounts, the setup's copies, a remake's home and `devvm agent import` take, and `secrets.LoginFile` in `internal/secrets/secrets.go` for their logins, which the setup's copies and the proxy read, so nothing reads an agent's files from the home folder but `vm.AgentImport` | `internal/paths`, and tests | | the structure test's `owners`, paths in devvm's folders | `internal/paths`, whose `Dirs` and `VM` name every file and folder devvm keeps, so the layout, its golden listing in `testdata/script/layout.txtar` and a VM's teardown miss none. A `filepath.Join` onto a `Data` or `Config` field fails, and so does an `os.MkdirTemp` or `os.CreateTemp` there whose name is a literal; a name from `paths`, such as `paths.ToolsBuildPrefix`, passes | tests | diff --git a/docs/content/docs/internals/design.md b/docs/content/docs/internals/design.md index ba36c89f..754deeac 100644 --- a/docs/content/docs/internals/design.md +++ b/docs/content/docs/internals/design.md @@ -475,7 +475,7 @@ macOS locks `.git`'s hooks and config with the user-immutable flag, which Linux - **A file with another name (a hard link):** fixed. A bind covers one name, and the guest could write the file through another, so a regular file to pin, or one in a folder to pin, with more than one name is refused at the start (`git_pin_linked`), and one that gets another name while the VM runs isn't pinned again and is named. - **A VM that's on running without its pins:** fixed, reported. Each launch of a running VM and `devvm stop` read QEMU's mounts and name each pin it lacks, `.git` and the git folders as mount points and the rest read-only (`git_pins_missing`). - **A pin reaching this machine's mounts:** ruled out. The namespace's mounts are private, and a mount namespace owned by a user namespace gets none of its pins back to its parent's (checked on Fedora: this machine's `mountinfo` has none of them while the VM runs). -- **What's pinned, from the guest's index:** ruled out. The VM writes the index, so it can add submodules, but devvm pins only real git folders inside the project folder (`isGitDir`), so the worst it can do is make a folder of its own project read-only to itself. +- **What's pinned, from the guest's index:** ruled out. The VM writes the index, so it can add submodules, but devvm pins only real git folders inside the project folder (`hostsafety.IsGitDir`), so the worst it can do is make a folder of its own project read-only to itself. - **`DEVVM_QEMU_PINS`:** ruled out. devvm sets it for the start alone, `_qemu` checks that the folder is absolute and clean and that every path is relative and below it, and devvm takes it out of QEMU's environment. - **An AppArmor profile for Ubuntu:** ruled out for now. A profile with the `userns` rule for devvm's binary, in a folder you can write, would let any program running as you put itself there and get what Ubuntu's restriction holds back, so devvm offers none, and Ubuntu with the restriction on only watches `.git`. - **`.git/commondir`:** listed. A file has to be there to be pinned, and devvm puts nothing in `.git` that git doesn't, so the VM can still make one, which devvm reports at each check, as on macOS. @@ -484,6 +484,31 @@ macOS locks `.git`'s hooks and config with the user-immutable flag, which Linux **End-to-end checks** (`tests/e2e`, the `project` section on a Linux host, run on Fedora 43 and Debian 13): QEMU runs in a namespace with `.git/config` and `.git/hooks` mounted read-only, with no capability and no-new-privileges; root in the VM can't add a hook, change, replace or remove the config, rename `.git` or move the hooks folder; git in the VM commits; `git config` on this machine reaches the VM, and the new config is read-only in the VM again; a submodule the VM adds is named by devvm stop, nothing of the namespace outlives the stop, and the next start pins the submodule's config but not a folder that isn't a git folder; `devvm git-protect off` on a running VM applies at its next start, which pins nothing; strict sets `diff.ignoreSubmodules`, and on pins again. Unit tests: `TestRunPinned` (a file renamed over a pinned one is pinned again and recorded; a hard link refuses the start), `TestPinsInNamespace`, `TestKeep` and `TestProbePin` on a Linux host, `TestPinsOrder`, `TestPinsRefused`, `TestStartPins`, `TestPins`, `TestBindsWatch`, `TestReportPinEvents` (a path's repeats in one line, each record it can't trust named), `TestRecordPinEvent`, `TestPinWaits` (a folder it can't watch fails the watch) and `TestPinsMissing` (`.git` not a mount point, a config not read-only). +## Nested repos + +A folder often holds git repos of its own besides its submodules, such as a workspace of several repos with no repo at its top. Every one of them is in the VM's mount, so `.git` protection covers each as it covers the folder's own repo ([nested repos](git-protection.md#nested-repos)). Two other designs were weighed. Refusing such folders, or warning only, leaves the most common multi-repo layout without protection. A `--clone` of every repo keeps the VM out of the working trees altogether, but it needs answers about discovery, remotes, seeding and the finder first, so it isn't built. + +**The guarantee:** in a VM made by this devvm, or one `devvm git-protect on` set, nothing in the VM can change the hooks and config of a nested repo that a walk of the stopped VM's folder found, with the same locks, pins and watch as the folder's own repo, and with the same reports at each check. It holds from the check that found the repo: a repo the VM makes while it runs, or a folder of its own the VM puts in a protected repo's place on Linux, is git's to use on this machine until the next stopped check names it, and what the walk can't find or the bound leaves out is named, or counted, not protected. A VM an earlier devvm made keeps protecting only its own repo until `devvm git-protect on`, because locking a repo's config breaks `git config` there, which the user didn't ask for. It's told once. + +**What could break it:** the walk finding the wrong folders or too many; a lock or a read outside the mount through a nested repo's paths, which now have two bounds, the repo's top folder and the mount; the VM hiding a nested repo behind another one's protection; two VMs protecting one repo, where one's unlock would take the other's locks off; strict's `diff.ignoreSubmodules`, which unlocks a config to write it; and the cost of a check, which the VM can raise by making repos. + +**Threat check** (the security-audit skill, guidance mode, its local IPC companion's local-file and race classes, with two independent reviews of the change, the second adversarial, which proved its two highs with real host git running a VM-planted `core.fsmonitor`). Leads, each fixed, ruled out or listed: + +- **A nested repo hidden behind another's protection:** fixed. The first version left a nested repo to any repo whose scan locked its git folder as a submodule's, and the VM writes the index that names submodules, so a gitlink with a `.git` file naming `b/.git` hid `b`'s own submodules and worktrees from every scan (`TestNestedGitlinkCantHide`). The second left one to any repo whose `.git` its git folder was below, so a `src/.git` file naming a `.git/evil` the VM made, or a `.git/modules/x` whose `commondir` leads to one, was neither locked nor named. A repo is now left to another only when its git folder is one that repo's scan locks whole: its `.git`, a git folder under `.git/modules` that reads its own config, or a linked worktree whose `commondir` leads back. Anything else is scanned on its own and named (`TestNestedIntoTopGit`). +- **A protected nested repo made to look gone:** fixed. devvm took a folder for a repo by a narrower test than git's, which also takes a `HEAD` with a `commondir`, and `objects` and `refs` that are files, so the VM could rename a protected repo's `objects` and `refs`, add a `commondir` to a git folder of its own, or rename `.git` to `.GIT` on macOS, or make it unreadable, and devvm dropped the repo as gone while git still used it, its pins and watch with it. The walk now takes anything named `.git`, any case on macOS, `hostsafety.IsGitDir` follows git's test, and a recorded repo stays while anything is at its `.git` (`TestNestedNotGone`, `TestIsGitDir`). `git_nested_gone` is a warning. +- **A bare repo the VM makes:** listed, named. git takes a folder shaped like a git folder for a bare repo, and its config can name a work tree, so git run below one runs its `core.fsmonitor`. devvm names the ones it finds, and `devvm doctor` gives a tip until git's `safe.bareRepository` is `explicit` (git 2.38 and newer), which refuses them; devvm never changes your git config. +- **A path outside the mount:** ruled out. Every lock, unlock and pin goes through `realInDir`, which takes the mount as its bound and refuses a path with a symlink in it below the mount, so a nested repo whose folder became a symlink is reported, not locked (`TestLockNeverThroughSymlinks`, `TestRealInDirPins`). The walk follows no symlink and stays on the mount's file system. The state records nested repos by local relative paths only. +- **Two VMs, one repo:** fixed. On macOS both VMs set the same flag, so an unlock leaves what another VM's protection still covers, and names that VM (`TestNestedUnlockKept`, the `git_nested` script's nested VM). Strict's `diff.ignoreSubmodules` first left a kept config unlocked for a moment, which a running VM could race, and on a failure could leave it unlocked for good, so strict and off now skip a kept config, and a failure locks again each config that was locked before (`TestStrictKept`). The ownership check fails closed: a state that can't be read keeps every path in the folder its state's folder is named after, and a VMs' folder that can't be read keeps everything (`TestGitKeeper`). Locking and recording, and unlocking, take one host lock (`paths.Dirs.GitLock`), so two commands at once can't unlock what the other just locked. A repo devvm stops protecting keeps its record in `made.left`, so its locks come off with the rest, and one that left the folder is named, as only `chflags` reaches it then (`TestNestedLeftUnlocked`). +- **A repo whose git folder is outside the folder:** named. Its `.git` file is locked, and the VM can't reach where it leads, but another project's VM may write it, as for a submodule's (`git_nested_gitdir_outside`). +- **The watch hiding a change:** fixed. The watch records a new or gone nested repo's sums without naming them, and it first skipped every path under such a repo's folder, so a repo nested in it went unwatched for a check. It now skips only the paths whose deepest repo is that one (`TestRepoOf`). +- **The bound used to hide a repo:** fixed. The VM can make up to 100 repos cheaply, and the walk keeps the first 100, so the count past the bound is now named at every check, with the first ten of them, not only when it grows, as the VM could keep the count and change which repos are past it. The `.git` the walk sees where it doesn't look for repos, which a set-id walk on Linux sees, and the folders on other disks it doesn't enter, are counted and named. +- **Cost:** fixed, and listed. A scan followed gitlinks that led back to a git folder it had followed, through a symlinked folder, up to eight deep, so the VM could make it run git without end; it now follows each git folder once, and one check's scans follow 1,000 in all, across every repo, and name a repo past that (`TestEmbeddedOnce`, `TestScanBudget`). A launch into a running VM scans no nested repo, so it costs what it did before them. A check scans eight repos at once, so 50 nested repos take under a second on an M3 Max, walk and locks included (`BenchmarkNestedCheck`). Listed: the watch's bounds grow with the repos, at most 2,000 sums for the folder's own repo and 200 for each nested one, each file read up to 16 MiB, so a VM that fills them makes a stopped check slow; a hooks folder filled to blind the watch is named at every check (`git_watch_blind`). +- **A nested repo's folder renamed on Linux:** listed, reported. A pin makes `.git` a mount point, which the guest can't rename, but a nested repo's own folder isn't one, so the guest can rename `ws/a`, `.git` and all, and put another repo in its place, which git on this machine then reads until the next check names it (`git_replaced`). Pinning every folder down to each nested repo would refuse the VM's own moves of those folders. macOS has the same gap for every repo, the folder's own included. +- **A repo the VM makes while it runs:** listed, reported. devvm can't lock what it hasn't found, so a repo the VM clones while it runs is git's repo for its folder from then on, shell prompts and editors included, and the VM's until the next stopped check names it, with the config keys and hooks in it that run programs (`git_nested_appeared_runs`), and locks it as it is. One deeper than four folders or under a skipped name is never named, only counted where a set-id walk sees it. +- **The pins' file:** ruled out. A VM with many nested repos has more pins than one environment variable holds (`MAX_ARG_STRLEN` is 128 KiB), so the start writes them to `run/git-pins.json` in the VM's folder, private and whole, which the VM can't reach, and `devvm _qemu` reads it through no symlink, capped, and checks it again (`TestPinsOrder`, `TestPinsRefused`). The keeper's inotify watches are a few folders for each repo, far below the kernel's limit for 100 repos. + +**End-to-end checks** (`tests/e2e`, the `project` section): a folder of two repos without one of its own gets a VM whose root can't add a hook or change the config of either repo, on macOS and on a Linux host that pins; on a Linux host that can't pin, `devvm stop` names the config the VM changed; `devvm rm` takes the locks off both; a repo whose `.git` file names a git folder the VM made under the folder's own `.git` is named at `devvm stop`; and a protected repo whose objects and refs the VM renamed, with a `commondir` to a git folder of its own, or whose `.git` it renamed to `.GIT` on macOS, stays protected. Unit tests: `TestWalkRepos`, `TestIsGitDir`, `TestNestedIntoTopGit`, `TestNestedNotGone`, `TestScanBudget`, `TestRunsProgram`, `TestNestedLeftUnlocked`, `TestGitKeeper`, `TestBareExplicit`, `TestNestedProtected`, `TestNestedNoTopRepo`, `TestNestedExistingVM`, `TestNestedWatch`, `TestNestedPins`, `TestNestedGitdirInside`, `TestKeeps`, `TestMadeJSON` and the 0.1.0 fixture's tests, whose state reads as a VM whose protection covers its own repo alone. + ## A VM made again `devvm layer add` and `devvm layer rm` make a VM again from a new image, and `devvm update` from its own image's new build, while keeping devvm's state for it and its home folder ([making a VM again](overview.md#making-a-vm-again)). All three use the one remake, and three choices shape it. @@ -609,6 +634,7 @@ User-facing limits are in [Known limits](../using/limits.md), and what devvm lea - **`--from`:** a moved tag is noticed only at the next build, not when listing images; devvm doesn't log in to registries, so private images work only through Docker; registries over plain HTTP (`localhost:5000`) aren't supported. - **Alpine:** `rc-status` as a normal user shows `acpid` and `syslog` as crashed, as their pid files are root's (`sudo rc-status` is clean). - **Free-space floors:** the free space devvm wants before each build and new VM ([free space](../using/ports-size.md#free-space)) is set by Lima's own package, and for shared tool images in `internal/backend/disk.go`, where the comments give what each number was measured from. The measurements are free space, read with statfs before, during and after each step, in e2e runs on macOS with Lima `vz`, and for shared tool images also with devvm's data folder on a tmpfs of its own on Linux. On Linux hosts, Lima's numbers add a copy of base's disk to an image's and a tools build's, but they haven't been measured there yet. A `--from` base converts its image in the host's temporary folder, which devvm doesn't check, because on Linux that's often a small tmpfs. +- **Workspace clones, not built:** `--clone` needs the folder to be the top of one repo, so a folder of repos either mounts them all, protected as [nested repos](#nested-repos), or needs a `--clone` VM for each. A clone of every repo at its own path in one VM waits on how far to look for repos, which branches to copy, the commands that fetch and add them, and whether `devvm` in one of them uses the folder's VM. - **x86_64 hosts** are untested on real hardware; on Intel Macs, `--from`'s kernel is untested with `vz`. - **Linux hosts:** the QEMU wrapper depends on the shape of Lima's `-netdev user,id=net0,…` argument. If Lima changes it, the wrapper refuses to start QEMU rather than run it unrestricted. - **Network tiers, not built:** diff --git a/docs/content/docs/internals/git-protection.md b/docs/content/docs/internals/git-protection.md index 1a12e881..3f9bd62f 100644 --- a/docs/content/docs/internals/git-protection.md +++ b/docs/content/docs/internals/git-protection.md @@ -10,14 +10,14 @@ On macOS devvm locks with the user-immutable flag (`chflags uchg`), which even r On Linux devvm makes the same paths read-only in the user and mount namespace it runs the VM's QEMU in ([on Linux hosts](#on-linux-hosts)), so the VM, which reaches the folder only through QEMU, can't change them. -Each check reads `.git` once, finding its git folders, submodules, what it would lock, what the locked files hand over and what points git elsewhere, and then locks, unlocks, watches and reports from what it found. The host's locker does the locking: the flag on macOS, and on Linux nothing at the check itself, because the VM's next start makes the paths read-only. A Linux host whose kernel refuses devvm the namespace locks nothing, and devvm [watches](#the-watch) `.git` there instead. +Each check reads each repo's `.git` once, the folder's own and those nested in it, finding its git folders, submodules, what it would lock, what the locked files hand over and what points git elsewhere, and then locks, unlocks, watches and reports from what it found. The host's locker does the locking: the flag on macOS, and on Linux nothing at the check itself, because the VM's next start makes the paths read-only. A Linux host whose kernel refuses devvm the namespace locks nothing, and devvm [watches](#the-watch) `.git` there instead. ## What's locked -devvm locks these paths: +devvm locks these paths, of the folder's own repo and of each [nested repo](#nested-repos) it protects: - `.git/hooks` and `.git/config`. A repo without a `hooks` folder gets an empty one, locked, so the VM can't make one. -- The same paths for each submodule devvm finds, submodules of submodules included. Those are the git folders under `.git/modules`, and those in the working tree, which are `sub/.git` or the folder that a `sub/.git` file points to. devvm finds the submodules from the index, which it reads with `core.fsmonitor` off. It takes a folder for a git folder only when it has what git looks for in one, which is a `HEAD` next to `objects` and `refs` folders. The VM can point a `sub/.git` file at any folder in the project, such as `src`, and locking that folder's `hooks` and `config` would lock your own files, so devvm locks and creates nothing in a folder that fails the check and reports it instead. +- The same paths for each submodule devvm finds, submodules of submodules included. Those are the git folders under `.git/modules`, and those in the working tree, which are `sub/.git` or the folder that a `sub/.git` file points to. devvm finds the submodules from the index, which it reads with `core.fsmonitor` off. It takes a folder for a git folder only when it has what git looks for in one, which is a `HEAD`, and `objects` and `refs` in the folder or in the folder its `commondir` names, as git's own test has it. The VM can point a `sub/.git` file at any folder in the project, such as `src`, and locking that folder's `hooks` and `config` would lock your own files, so devvm locks and creates nothing in a folder that fails the check and reports it instead. - `.git/config.worktree`, when `extensions.worktreeConfig` is on. devvm creates it empty if it's missing. - What linked worktrees elsewhere on your machine read from here, which is `.git/worktrees//commondir` and `config.worktree`. - The project folder's `.git` file, if the project folder is itself a linked worktree. The repo it points to is outside the VM. @@ -39,7 +39,8 @@ devvm never locks or creates anything through a symlink, because the VM could pl Every launch of an existing VM, every export of its agents' history, and `devvm stop` check `.git` again. devvm reports each of these once: - A `.git` that was replaced since devvm locked it (`git_replaced`). devvm then does nothing else, so check the new `.git`, and look for the old one, renamed. -- A repo that appeared in the folder after the VM was made (`git_appeared`), which devvm then locks. +- A repo that appeared in the folder after the VM was made (`git_appeared`), which devvm then locks, and a nested repo that appeared since the last check (`git_nested_appeared`). +- A nested repo devvm protected that's gone (`git_nested_gone`). - A submodule git folder that appeared, in the working tree or under `.git/modules` (`git_embedded_new`), which devvm then locks. devvm compares with the git folders it recorded last time, so `devvm git-protect on` after a VM was made without protection names none: it locks `.git` as it is then, as trusted. - Hooks in a hooks folder that wasn't locked, because it wasn't there to lock or belongs to a new submodule (`git_hooks_unlocked`). @@ -50,13 +51,45 @@ devvm also reports these, the first two on every launch and the last two when th - Includes and hook links into the project folder (`git_include_inside`, `git_hook_link_inside`), which [not covered](../safety/git-protection.md#not-covered) describes. - Submodules whose git folder, in the working tree, isn't a git folder (`git_gitdir_not_git`), which devvm doesn't lock. +## Nested repos + +devvm protects each git repo nested in the project folder as it protects the folder's own: it locks the same paths of each, checks each at every launch, pins each on Linux and watches each where the host can't lock ([nested repos](../safety/git-protection.md#nested-repos)). + +### The walk + +devvm finds the nested repos by walking the project folder when it creates the VM, at each launch that finds the VM stopped and at `devvm stop`, at `devvm git-protect` on a stopped VM, and when `devvm clone off` mounts the folder again. It's one walk that also finds the set-id files on a Linux host (`hostsafety.Walk`, which only `starter.walk` calls), and a launch into a running VM never walks. The walk stays on the project folder's file system, follows no symlink and never enters a `.git` folder, so it never finds the repos of `.git/modules`, which are the folder's own repo's to protect. It takes a folder for a repo when the folder has anything named `.git`, a folder, a file, which a linked worktree or a repo with its git folder elsewhere has, a symlink or anything else, whether git takes it for a repo's now or not, because the VM can make it one at any time. On macOS, whose file systems fold case, `.GIT` is `.git` to git, so the walk takes any case of the name there (`platform.FoldsCase`). It looks for repos at most four folders below the project folder, and not in `node_modules`, `vendor`, `.venv`, `__pycache__` or `.terraform`, which package managers and build tools fill with what they fetch, so on macOS, where there are no set-id files to look for, the walk doesn't enter those folders at all. On Linux it walks them for set-id files anyway, and counts the `.git` it sees there and below four folders (`git_nested_skipped`). It counts the folders it doesn't enter because they're on another file system (`git_nested_devices`). It keeps the first 100 repos it finds, in the walk's order, and counts the rest, keeping the names of the first ten of those (`git_nested_past_bound`). + +The walk also names each folder up to four folders down that git could take for a bare repo (`git_nested_bare`), one shaped like a git folder by git's own test (`hostsafety.IsGitDir`): a `HEAD`, and `objects` and `refs`, files or folders, in the folder or in the folder its `commondir` names. A git folder that a repo's scan locks, or that a nested repo's `.git` file names, isn't named. `devvm doctor` reads `safe.bareRepository` from git's global and system config (`hostsafety.BareExplicit`), the files that `GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` name included, which it reads by name (`hostgit.UserConfig`) because devvm's host git ignores every `GIT_*` variable, and it gives a tip unless the setting is `explicit` (`doctor_git_bare`). + +A check takes the repos the walk found, the ones the VM's state records first. A recorded repo stays protected, whether the walk found it or not, while its folder is a real folder of the project with anything at its `.git`, because the VM can make a `.git` that the walk or git's own test passes over while git still takes it: objects and refs renamed with a `commondir` that leads to a git folder of its own, a `.GIT`, or a `.git` it can't read, which devvm can't lock and names (`git_not_locked`). A check without a walk, such as `devvm rm` and the start that pins, takes the repos the state records. A launch into a running VM checks the folder's own repo alone and keeps the nested repos' records as they are, because it locks nothing and the VM can change them until it stops, so it never pays for scanning them, and the check of a running VM's pins goes by those records without scanning them. devvm scans each repo as it scans the folder's own, eight at once, because each scan runs a few host git commands: a check of a stopped VM with 50 nested repos, the walk and the locks included, takes under a second on an M3 Max. + +### Two bounds + +Each repo has two bounds. Its own top folder is where its `.git` is, where `.git/modules` and a relative `core.hooksPath` are read from, and where its submodules' folders are. The project folder, which the VM mounts, is what the VM can write, so it's the bound for everything else: devvm locks only a real path in the project folder, through no symlink, an include or a hooks path leads inside when it leads into the project folder, and a submodule's git folder outside the project folder is one devvm can't lock (`git_gitdir_outside`). A nested repo's hooks path that leads into a sibling repo is inside, because the VM can write it. + +A nested repo is left to another repo only when that repo's scan locks its git folder whole (`snapshot.covered`): the git folder is that repo's `.git`, one under its `.git/modules` that reads its config from itself, with no `commondir` that leads elsewhere, or one of its linked worktrees under `.git/worktrees` whose `commondir` leads back. Anything else below a `.git`, such as a `.git/evil` the VM made for a `src/.git` file to name, isn't locked by anything, so the repo is scanned on its own, and named as one that appeared and as one devvm doesn't protect. A submodule in the working tree is scanned as a repo of its own as well as its parent's submodule, because the index that names it is the VM's to write: a gitlink the VM adds, whose `.git` file names a nested repo's git folder, would otherwise hide that repo's own submodules and worktrees behind a scan from the wrong folder. Locking a path twice changes nothing, and unlocking goes by path once. A nested repo whose `.git` is a file is locked as the folder's own is when it's a linked worktree, by its `.git` file. When the git folder that file names is in the project folder and no repo's scan locks it, devvm names the repo as one it doesn't protect, and when it's outside the project folder, it names the repo as one whose git folder it can't lock (`git_nested_gitdir_outside`), as it does a submodule's. + +A scan follows each submodule git folder once, by its resolved path, and one check's scans follow at most 1,000 of them across every repo, so gitlinks that the VM points back at a git folder already followed, or through a symlinked folder at the repo itself, or many repos full of submodules, can't make a check run git without end. A repo whose scan stopped there is named at every check (`git_scan_bounded`). + +### What's recorded + +The VM's state records each protected nested repo in the `git` section's `made.repos`, by its folder relative to the project folder, with the same fields as the folder's own repo: `.git`'s identity, the git folders locked besides `.git`, and a hash of what its locked files hand over. `made.nested` is set once the VM protects its nested repos, which a new VM does, and so do `devvm git-protect on` and `strict`, and the watch on a Linux host that can't lock. A nested repo without a record is scanned for the first time, which records it as a new VM's repo is recorded, without reporting its git folders. At a check of a VM whose `made.nested` is set, devvm also reports it as one that appeared, such as a repo the VM cloned while it ran, naming each key of its config that runs a program or reads another config (`core.fsmonitor`, `core.hooksPath`, `core.sshCommand`, `core.pager`, filters, aliases that start with `!`, includes and the like) and each hook that isn't one of git's samples (`git_nested_appeared_runs`, else `git_nested_appeared`), because it locks the repo as it is. A recorded repo with nothing at its `.git`, or whose folder isn't a real folder of the project any more, is reported (`git_nested_gone`), and a recorded repo whose `.git` is another one is reported as the folder's own is (`git_replaced`). The record of a repo devvm stops protecting, as it's gone or another repo's protection covers it, moves to `made.left`, so `devvm rm` and `devvm git-protect off` take its locks off with the rest, and name one that isn't in the folder any more (`git_locks_left`), whose locks only `chflags` can take off. + +A VM an earlier devvm made has no `made.nested`, so it protects only the folder's own repo. The first check of it that finds nested repos names them once (`git_nested_protectable`, recorded as `nested_noticed`), and `devvm git-protect on` protects them. The nested repos that a check finds and the protection doesn't cover are recorded in `nested`, with `nested_more` for how many more the walk counted, and named (`git_nested_unprotected`, `git_nested_past_bound`): on a host that locks, all of them when devvm creates the VM and at `devvm git-protect on` or `strict`, and at a check of a stopped VM those it hadn't recorded, and how many are past the bound at every check, because the VM could keep their count and change which they are. On a Linux host that can't lock, each launch names those the last walk recorded, after `git_unprotected`, which a folder without a `.git` of its own gets too when it has nested repos, and `devvm git-protect off` quiets both. + +Strict sets `diff.ignoreSubmodules = all` in the config of each protected repo that has a `.git` folder, and `devvm git-protect on` and `off` take it out of each. + +### Two VMs, one repo + +A nested repo with a VM of its own is protected by two VMs, the parent folder's and its own. On macOS both set the same flag on the same files, so when one VM's protection comes off, at `devvm rm` or `devvm git-protect off`, devvm leaves locked every path that another VM's protection still covers (`gitprotect.Keeps`: a git folder it recorded locking, of its own repo or of a nested one), and names that VM (`git_kept_locked`). The inventory reads every VM's state for that (`Inventory.GitKeeper`). It fails closed: a state it can't read keeps locked every path in the folder whose hash names that state's folder (`project.Hash`), and when it can't read the VMs' folder at all, everything stays locked, each named with the state to fix (`git_kept_unread`). Locking a VM's repos and recording them, and unlocking another's, take the host's lock of `.git` protection first (`paths.Dirs.GitLock`, before any VM's own lock), so one VM's unlock never runs between another's locks and their record. `devvm git-protect strict`, `on` and `off` never unlock a config another VM keeps locked to set or take out `diff.ignoreSubmodules`, because that VM, running, could race the unlocked file, and they name that VM instead. When setting it fails, devvm locks again each config it unlocked that was locked before. On Linux each VM's pins are in its own QEMU's namespace, and the watch locks nothing, so neither needs this. + ## On Linux hosts -Linux hosts have no immutable flag that a user can set, so devvm makes what it locks read-only where the VM sees it, in the VM's QEMU process, which serves the project folder to the guest over 9p. Lima starts QEMU through devvm's wrapper (`devvm _qemu exec`), and a start of a VM that's on or strict gives the wrapper what to pin (`DEVVM_QEMU_PINS`): `.git` and each git folder it locks besides, which stay writable, and every path of [what's locked](#whats-locked) that's there, which become read-only. They're the paths the check before the start found and checked, each a real path in the project folder with no symlink, and the check made a missing hooks folder and `config.worktree` first, so each has a place to pin. devvm then starts `devvm _qemu pinned` in a user and mount namespace of its own, as you, with only `CAP_SYS_ADMIN`, and only in that namespace. It makes the namespace's mounts private, so nothing it mounts reaches this machine's, and pins each path in order, a folder before what's under it. It opens each path once, by the kernel, below the project folder and through no symlink (`openat2` with `RESOLVE_BENEATH` and `RESOLVE_NO_SYMLINKS`), refuses anything but a file or a folder, and refuses a file with another name, or a folder holding a regular file with one, because a bind covers one name and macOS's flag covers the file itself (`git_pin_linked`, which the check before the start names first). Then it binds what it opened over itself with `open_tree`, `mount_setattr` and `move_mount`, which act on that file descriptor and never on a path again, because `mount(2)` would follow a symlink that the VM planted. A path it can't pin, or folders it can't watch, stop the start (`qemu_pins_failed`), so the VM never runs unlocked. Then it starts `devvm _qemu drop` as its child, which clears every capability it has, ambient, permitted, effective and inheritable, sets no-new-privileges and replaces itself with QEMU, which runs as you with no capability at all. Its bounding set stays whole, which only `CAP_SETPCAP` could change, and gives nothing with no new privileges. QEMU is killed if `devvm _qemu pinned` ends (`PR_SET_PDEATHSIG`), which runs as long as QEMU does, keeping the pins, so QEMU never outlives what keeps them. `devvm _qemu exec` waits for both and passes them the signals Lima sends, and if it's killed, QEMU is killed with it, an unclean stop for the guest, as if its power went. +Linux hosts have no immutable flag that a user can set, so devvm makes what it locks read-only where the VM sees it, in the VM's QEMU process, which serves the project folder to the guest over 9p. Lima starts QEMU through devvm's wrapper (`devvm _qemu exec`), and a start of a VM that's on or strict gives the wrapper what to pin in a file of its own, `run/git-pins.json` in the VM's folder, written private, which `DEVVM_QEMU_PINS` names, because a VM with many nested repos has more pins than one environment variable holds. The wrapper reads the file through no symlink, and it pins, for the folder's own repo and each nested repo the VM's state records protecting, `.git` and each git folder it locks besides, which stay writable, and every path of [what's locked](#whats-locked) that's there, which become read-only. They're the paths the check before the start found and checked, each a real path in the project folder with no symlink, and the check made a missing hooks folder and `config.worktree` first, so each has a place to pin. devvm then starts `devvm _qemu pinned` in a user and mount namespace of its own, as you, with only `CAP_SYS_ADMIN`, and only in that namespace. It makes the namespace's mounts private, so nothing it mounts reaches this machine's, and pins each path in order, a folder before what's under it. It opens each path once, by the kernel, below the project folder and through no symlink (`openat2` with `RESOLVE_BENEATH` and `RESOLVE_NO_SYMLINKS`), refuses anything but a file or a folder, and refuses a file with another name, or a folder holding a regular file with one, because a bind covers one name and macOS's flag covers the file itself (`git_pin_linked`, which the check before the start names first). Then it binds what it opened over itself with `open_tree`, `mount_setattr` and `move_mount`, which act on that file descriptor and never on a path again, because `mount(2)` would follow a symlink that the VM planted. A path it can't pin, or folders it can't watch, stop the start (`qemu_pins_failed`), so the VM never runs unlocked. Then it starts `devvm _qemu drop` as its child, which clears every capability it has, ambient, permitted, effective and inheritable, sets no-new-privileges and replaces itself with QEMU, which runs as you with no capability at all. Its bounding set stays whole, which only `CAP_SETPCAP` could change, and gives nothing with no new privileges. QEMU is killed if `devvm _qemu pinned` ends (`PR_SET_PDEATHSIG`), which runs as long as QEMU does, keeping the pins, so QEMU never outlives what keeps them. `devvm _qemu exec` waits for both and passes them the signals Lima sends, and if it's killed, QEMU is killed with it, an unclean stop for the guest, as if its power went. The guest reaches the project folder only through QEMU, so a write to a pinned path gets `EROFS`, and a rename or a removal of one, `.git` itself included, gets `EBUSY`, because it's a mount point. A mount can't be undone from the guest, and QEMU, which has no capability, can't undo it either. A bind mount over a folder is a file system of its own to the guest, so a rename between the working tree and `.git` gets `EXDEV`. The namespace ends with QEMU, so nothing persists once the VM stops, and nothing changes on this machine's side, where git works as usual. -A git command on this machine that writes `.git/config` writes a new file and renames it over the old one, and the new file isn't pinned in the namespace. `devvm _qemu pinned` watches each pinned path's folder with inotify, and pins again whatever lost its pin as soon as one changes, and every two seconds besides. Until then the guest can write the new file, rename it away and put its own in its place, which then gets the pin, open it for writing, a handle the pin doesn't take back, or give it another name. So each pin it makes again, and each it can't, it records in the VM's run folder (`run/git-pins.jsonl`), a JSON object a line, after a first line that says it keeps the pins from then on, which it writes before QEMU starts and without which QEMU doesn't start (`qemu_pins_failed`). The next check of the stopped VM, at `devvm stop` or at the next launch, names them before anything else, one line for each path and kind however often it happened (`git_pin_again`, `git_pin_linked_run`, `git_pin_lost`), then removes the file. An event `devvm _qemu pinned` can't add goes to Lima's log, with a warning, and to the file as a mark if it still takes one. A record the check can't trust is named (`git_pins_unrecorded`): one it can't read, which it keeps, a line that isn't an event, a mark, or a file that doesn't start with a run's first line, as when it was removed while the VM ran and made again. The check also sums what a lock covers, as the [watch](#the-watch) does, and names what changed since the VM's last check, so a file the guest changed in that window, or through a handle it kept, is named too. macOS's flag has no window, because a locked config can't be replaced on the host either. +A git command on this machine that writes `.git/config` writes a new file and renames it over the old one, and the new file isn't pinned in the namespace. `devvm _qemu pinned` watches each pinned path's folder with inotify, a few folders for each repo, so the 100 nested repos devvm protects at most stay far below the kernel's limit of watches, and it pins again whatever lost its pin as soon as one changes, and every two seconds besides. Until then the guest can write the new file, rename it away and put its own in its place, which then gets the pin, open it for writing, a handle the pin doesn't take back, or give it another name. So each pin it makes again, and each it can't, it records in the VM's run folder (`run/git-pins.jsonl`), a JSON object a line, after a first line that says it keeps the pins from then on, which it writes before QEMU starts and without which QEMU doesn't start (`qemu_pins_failed`). The next check of the stopped VM, at `devvm stop` or at the next launch, names them before anything else, one line for each path and kind however often it happened (`git_pin_again`, `git_pin_linked_run`, `git_pin_lost`), then removes the file. An event `devvm _qemu pinned` can't add goes to Lima's log, with a warning, and to the file as a mark if it still takes one. A record the check can't trust is named (`git_pins_unrecorded`): one it can't read, which it keeps, a line that isn't an event, a mark, or a file that doesn't start with a run's first line, as when it was removed while the VM ran and made again. The check also sums what a lock covers, as the [watch](#the-watch) does, and names what changed since the VM's last check, so a file the guest changed in that window, or through a handle it kept, is named too. macOS's flag has no window, because a locked config can't be replaced on the host either. Each launch of a running VM that's on, and `devvm stop` before it stops it, read QEMU's mounts (`/proc//mountinfo`, QEMU's pid from Lima's `qemu.pid`) and name what of `.git` and of the git folders it locked QEMU lacks (`git_pins_missing`): `.git` and each git folder that isn't a mount point of its own, and each read-only path that QEMU doesn't see read-only,, such as all of them for a VM that `limactl start` started. A VM that's on whose `.git` has nothing devvm can pin, such as one whose `.git` is a symlink, is named at its start (`git_pins_none`). @@ -68,7 +101,7 @@ devvm doesn't pin `.git/commondir` against the VM making one, which would point Where the host can't pin, devvm locks nothing, and every VM that mounts its folder gets `off` as its mode. devvm watches the paths it would lock instead, and names what changed after the fact (`git_changed`), which [Linux hosts](../safety/git-protection.md#when-devvm-names-a-change) tells the user how to check. -devvm hashes the same paths that [what's locked](#whats-locked) lists, found in the same way, and `.git/commondir`, there or not, the files that `include.path` and `includeIf.*.path` lead to in the project folder, and the folder that `core.hooksPath` names in it. For a hooks folder, it hashes each entry below it, except git's `.sample` files, which git never runs, starting with the entries at its top that have a hook's name (githooks(5)), which git runs, and then the rest. It hashes a regular file's contents with SHA-256, opened with `O_NOFOLLOW` and `O_NONBLOCK` and checked to be a regular file once it's open (`internal/safefile`). It records a symlink by where it points, and a path under a symlink, such as `.git/config` when `.git` is a symlink, by that fact. When the link resolves to a file or folder inside the project folder, it adds that file's hash, or a hash of that folder's hashes, and it never follows a link out of the project folder. Anything else, such as a FIFO, is recorded by its type. The work is bounded: past 1,000 entries, a hooks folder is recorded by that count, its inode and its change time, a file larger than 16 MiB by its size, inode and change time, and a watch keeps at most 2,000 hashes. The VM can't set a change time back over 9p, so a change that keeps a large file's size is still named. Each check names, in its own warning (`git_watch_blind`), every path that is a symlink or under one, past a bound, or past the 2,000, because the watch can't see every change there. +devvm hashes the same paths that [what's locked](#whats-locked) lists, found in the same way, and `.git/commondir`, there or not, the files that `include.path` and `includeIf.*.path` lead to in the project folder, and the folder that `core.hooksPath` names in it. For a hooks folder, it hashes each entry below it, except git's `.sample` files, which git never runs, starting with the entries at its top that have a hook's name (githooks(5)), which git runs, and then the rest. It hashes a regular file's contents with SHA-256, opened with `O_NOFOLLOW` and `O_NONBLOCK` and checked to be a regular file once it's open (`internal/safefile`). It records a symlink by where it points, and a path under a symlink, such as `.git/config` when `.git` is a symlink, by that fact. When the link resolves to a file or folder inside the project folder, it adds that file's hash, or a hash of that folder's hashes, and it never follows a link out of the project folder. Anything else, such as a FIFO, is recorded by its type. The work is bounded: past 1,000 entries, a hooks folder is recorded by that count, its inode and its change time, a file larger than 16 MiB by its size, inode and change time, and a watch keeps at most 2,000 hashes of the folder's own repo and 200 of each nested repo, so a folder with many nested repos never overflows it. The VM can't set a change time back over 9p, so a change that keeps a large file's size is still named. Each check names, in its own warning (`git_watch_blind`), every path that is a symlink or under one, past a bound, or past the 2,000, because the watch can't see every change there. The same checks first run what a lock's check reports, without locking (`protect` with `watching`): a `.git` replaced since the last check (`git_replaced`), after which the next check compares with the new one, a `commondir` (`git_commondir`), linked worktrees whose `commondir` leads elsewhere, a repo or submodule git folder that appeared, a submodule's folder that isn't a git folder (`git_gitdir_not_git`), which the watch doesn't hash as one and where devvm creates nothing, and includes, hook links and `core.hooksPath` into the project folder. They don't report hooks in folders that aren't locked, because nothing is, and the watch names their changes. `.git`'s identity and the git folders and delegations found are recorded in the `git` section's `made`, as a lock's check records them. A VM whose `made` isn't set yet reports as a new VM does. @@ -100,6 +133,6 @@ A `--clone` VM's push adds `--no-verify`, `--no-recurse-submodules` and `--no-si Before a `--clone` VM is made, and again before its push, devvm checks that what git reads in the folder is the repo's own, so the push can't copy another repo into the VM. The folder's `.git` is a folder with no `commondir`, or it's the `.git` file of a linked worktree whose link git made both ways. That `.git` file names `/.git/worktrees/`, that entry's `gitdir` file names the folder's `.git` back, and its `commondir` leads to that `/.git`, which has no `commondir` of its own. Neither the git dir nor the common dir has `objects/info/alternates`, or a `packed-refs` or `reftable` that's a symlink, or anything in `objects` or `refs` that's a symlink, such as a pack folder or a loose object's folder that leads to another repo's objects. Then `git rev-parse --absolute-git-dir --git-common-dir` must name the same two folders. A worktree's push sends only its branch and that branch's upstream, when the upstream is one ref, so the repo's other branches stay on this machine. A `branch..merge` that's a pattern, such as `refs/heads/*`, would make the upstream push every branch, so devvm then pushes only the branch. -devvm finds the hook and filter names to turn off with one `git config` before each command, so a VM that keeps swapping the repo's config could show that `git config` one config and the command another. Every hook event is turned off by its name as well, which covers config hooks on git that has the event setting, so the gap is a filter that the swap hides, which `git status` could then run on a file whose stat changed. It needs a VM that writes the repo's `.git`, so on macOS, where `.git/config` is locked, it needs a repo devvm doesn't lock, such as one nested in a parent folder's mount. +devvm finds the hook and filter names to turn off with one `git config` before each command, so a VM that keeps swapping the repo's config could show that `git config` one config and the command another. Every hook event is turned off by its name as well, which covers config hooks on git that has the event setting, so the gap is a filter that the swap hides, which `git status` could then run on a file whose stat changed. It needs a VM that writes the repo's `.git`, so on macOS, where `.git/config` is locked, it needs a repo devvm doesn't lock, such as a nested repo past the walk's bounds ([nested repos](#nested-repos)). Two things a repo's config can still do, and neither runs code. An `include.path` can make devvm's `git config --get user.name` read your name and email from another file in git's config format, which then go into the VM as its git identity. A config file or included file that is a FIFO makes git, and so devvm, wait until you press Ctrl+C. diff --git a/docs/content/docs/internals/install.md b/docs/content/docs/internals/install.md index 8b199faf..82f6e729 100644 --- a/docs/content/docs/internals/install.md +++ b/docs/content/docs/internals/install.md @@ -72,7 +72,9 @@ It warns in these cases: - this machine has less than the 8 GiB of memory or the 4 CPUs that devvm recommends ([requirements](../getting-started/install.md#requirements)), - a line of your policy files isn't a rule, which VMs' proxies skip ([rules](../safety/network.md#rules)). -Then it says devvm has everything it needs, or it fails. The warnings never make it fail, so a small machine with everything installed passes. +It also gives a tip, which isn't a warning, when `safe.bareRepository` isn't `explicit` in your global or system git config, or in the files that `GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` name: git then takes any folder shaped like a git folder for a bare repo, so a VM can make one that git run below it uses ([bare repos](../safety/git-protection.md#bare-repos)). doctor only reads the setting. + +Then it says devvm has everything it needs, or it fails. The warnings and tips never make it fail, so a small machine with everything installed passes. ## devvm doctor --json @@ -81,6 +83,7 @@ Then it says devvm has everything it needs, or it fails. The warnings never make - `backend` is the backend that doctor checked, `lima`, which every new VM gets. - `problems` has what that backend is missing, each with its `key`, the `fix` command, and the `message` that `devvm doctor` prints for it. The `fix` is a command whose words are separated by spaces, without shell syntax, or `null` when there's none to run, for example when virtualization is turned off in the firmware. - `warnings` has the messages of doctor's warnings, which have no keys, because there's nothing for a script to fix. They're about another devvm on `PATH`, low free space, a machine with less than 8 GiB of memory or fewer than 4 CPUs, and each line of `~/.config/devvm/policy`, `~/.config/devvm/layers/*.policy` and `~/.local/share/devvm/vms/*/policy` that isn't a rule (`policy_not_rule`). +- `tips` has the messages of doctor's tips, which aren't problems: git's `safe.bareRepository` (`doctor_git_bare`). - `docker` says whether Docker is installed, which only `--from` with an image that only Docker has needs. - `features` has, for each backend, how it has each feature, as `native`, `emulated`, `unreviewed` or `none`. The example below shows two of Lima's features. @@ -96,6 +99,7 @@ Then it says devvm has everything it needs, or it fails. The warnings never make } ], "warnings": [], + "tips": [], "docker": true, "features": { "lima": { diff --git a/docs/content/docs/safety/attack-vectors.md b/docs/content/docs/safety/attack-vectors.md index c657e709..b75edb76 100644 --- a/docs/content/docs/safety/attack-vectors.md +++ b/docs/content/docs/safety/attack-vectors.md @@ -93,6 +93,7 @@ The attacks in this section run the attacker's code, and devvm doesn't stop that - **Submodules with their own config.** The VM writes `.git/index` to commit, so it can add a submodule whose config sets `core.fsmonitor`. Host `git status` reads that config before devvm's next launch finds the submodule and locks it. [`devvm git-protect strict`](git-protection.md#strict) stops `git status` and `git diff` from looking inside submodules, but `git submodule` commands still enter them, so use `--clone` for a repo with submodules you don't trust. - **Replacing `.git`.** The VM can rename `.git` and put a new one in its place, or add a `commondir` that points git at another config. devvm reports these on each launch but doesn't prevent them, so check what it names before you run git in the folder ([what a lock can't stop](../internals/git-protection.md#what-a-lock-cant-stop)). +- **Nested repos.** devvm protects the git repos nested in the folder, but the VM can clone a new one while it runs, or move a protected one aside and put another in its place, and git on this machine runs its config before devvm's next check names it. devvm also doesn't protect a nested repo deeper than four folders, in a folder such as `node_modules`, or past the first 100, which it counts and names ([nested repos](git-protection.md#nested-repos)). ### Network diff --git a/docs/content/docs/safety/git-protection.md b/docs/content/docs/safety/git-protection.md index be77579d..6dad5e96 100644 --- a/docs/content/docs/safety/git-protection.md +++ b/docs/content/docs/safety/git-protection.md @@ -4,7 +4,7 @@ explainer: Keep code in the VM out of your .git weight: 2 --- -The project folder is read-write in the VM, so without protection anything in the VM could add a git hook, or set `core.fsmonitor`, `core.hooksPath` or `core.sshCommand` in `.git/config`, and your next git command on this machine would run it. On macOS, devvm locks the git hooks and config with a flag that even root in the VM can't clear, so nothing the VM does runs through them on this machine. On Linux, devvm makes them read-only in the VM's own view of the folder, which root in the VM can't change either ([Linux hosts](#linux-hosts)). +The project folder is read-write in the VM, so without protection anything in the VM could add a git hook, or set `core.fsmonitor`, `core.hooksPath` or `core.sshCommand` in `.git/config`, and your next git command on this machine would run it. On macOS, devvm locks the git hooks and config with a flag that even root in the VM can't clear, so nothing the VM does runs through them on this machine. On Linux, devvm makes them read-only in the VM's own view of the folder, which root in the VM can't change either ([Linux hosts](#linux-hosts)). It does the same for each git repo nested in the folder that it has found, such as the repos of a folder that holds several, but a repo the VM makes while it runs is git's to use before devvm finds it ([nested repos](#nested-repos)). Every new VM gets `.git` protection. `--no-git-protect` creates a VM without it, and [`devvm git-protect`](#turning-it-on-or-off) changes it later. [How it works › .git protection](../internals/git-protection.md) lists what devvm locks and when it checks the locks again. @@ -52,7 +52,8 @@ The VM can add a submodule at any time, and `git status` and `git diff` on this Every launch of an existing VM, and `devvm stop`, check `.git` again, and devvm reports what it finds there that it didn't lock. When it names one of these, check it before you run git in the folder, because git on this machine would run what the VM put there: -- **A repo that appeared** in the folder after its VM was made. devvm locks it from then on, but if you didn't make it, check its hooks and config. +- **A repo that appeared** in the folder after its VM was made, the folder's own or a [nested one](#nested-repos). devvm locks it from then on, but if you didn't make it, check its hooks and config. +- **A nested repo that's gone or moved,** which the VM could have moved aside to put another in its place. - **Hooks in a folder devvm hadn't locked,** because the folder wasn't there to lock or belongs to a new submodule. - **A submodule whose git folder isn't one.** The VM can name any folder in the project as a submodule's git folder, such as your `src`, so devvm locks nothing in a folder that doesn't look like a git folder, and names the submodule instead. - **A path that's a symlink or under one.** devvm never locks anything through a symlink, because the VM could point one at a file elsewhere on this machine, so it leaves that path unlocked. @@ -60,6 +61,28 @@ Every launch of an existing VM, and `devvm stop`, check `.git` again, and devvm [How it works › .git protection](../internals/git-protection.md#on-each-launch) lists every check. +## Nested repos + +A folder can hold git repos of its own besides its submodules, such as `ws/repo-a` and `ws/repo-b` in a folder `ws`, whether `ws` is a repo itself or only a folder of repos. The VM can write all of them, and git on this machine runs what their `.git` holds when you run git there, so devvm protects each one it finds as it protects the folder's own `.git`: it locks them on macOS, makes them read-only in the VM on Linux, and watches them on a Linux host that can't lock. It finds them when it creates the VM, at each launch that finds the VM stopped and at `devvm stop`, by looking up to four folders below the project folder for anything named `.git` (on macOS, `.GIT` as well). It doesn't look in the folders that package managers and build tools fill, `node_modules`, `vendor`, `.venv`, `__pycache__` and `.terraform`, nor in a folder on another disk, and it protects the first 100 it finds and names the rest, at every check. A launch into a running VM doesn't look again, and it doesn't check the nested repos either, so they're checked at the next launch that finds the VM stopped, or at `devvm stop`. + +What [still works](#what-still-works) and what doesn't is the same in a nested repo as in the folder's own: `git config`, `git remote add` and hook installers fail there on macOS, so run them with protection off. devvm keeps protecting a nested repo for as long as anything is at its `.git`, even when that `.git` no longer looks like a repo's, because the VM can change it back at any time. + +devvm can't protect a repo before it has found it. A repo the VM makes in the folder while it runs, by cloning one or by making a `.git` in a folder of yours, is git's repo for that folder from the moment it's there: your `git status` in the folder, and the shell prompts and editors that run git as you open it, run what its config says. devvm names such a repo only at the next launch that finds the VM stopped, or at `devvm stop`, with the settings in its config and the hooks that run programs, and then locks it as it is, so check what it names before you run git there. A repo the VM makes more than four folders down, or in a folder devvm doesn't look in, is never named, only counted where devvm walks the folder for set-id files on Linux. On Linux the VM can also move a nested repo's folder aside and put another repo in its place while it runs, which devvm names only if it's still in place when the VM stops ([Linux hosts](#linux-hosts)). So when you run git in a folder of a VM's project while the VM runs, the protection holds only for the repos devvm has already found. + +### Bare repos + +git also takes a folder shaped like a git folder, with a `HEAD`, `objects` and `refs`, for a bare repo, and its config can name a work tree, so git run in a folder below one uses it, `core.fsmonitor` and all. The VM can make one anywhere in the folder. devvm names the ones it finds up to four folders down that aren't a repo's own git folder, and `devvm doctor` gives a tip when git on this machine takes a bare repo it isn't told to use. git 2.38 and newer can refuse that: `git config --global safe.bareRepository explicit` makes git use a bare repo only when you name it, with `--git-dir` or `GIT_DIR`. devvm only checks the setting, and never changes your git config. + +### VMs an earlier devvm made + +A VM that an earlier devvm made protects only the folder's own repo. The first time devvm finds nested repos in its folder, it names them once and tells you to run `devvm git-protect on`, which protects them all from then on. Until you do, devvm names each nested repo it finds that it hadn't named before. + +### Two VMs, one repo + +A nested repo can have a VM of its own, and then two VMs protect it. On macOS, the flag that locks it is the same for both, so `devvm rm` or `devvm git-protect off` for one VM leaves locked what the other VM still protects, and names that VM. Run `devvm git-protect off` for the other VM too when you want the locks off. When devvm can't read another VM's state, it leaves locked what that VM may protect, and names the state to fix. On Linux, each VM has its own read-only view, so each protects the repo from its own VM. + +A nested repo devvm stopped protecting, because it's gone or moved, keeps its locks until devvm takes them off with the rest, at `devvm rm` or `devvm git-protect off`. When it's no longer in the folder, devvm can't find it to unlock it, so it names it, and `chflags -R nouchg` on its `.git/hooks` and `.git/config` takes the locks off. + ## Not covered The lock covers `.git`, and the VM can still put things elsewhere that git on this machine runs. devvm tells you about each of these, so read what it reports before you run git in the folder, and use [`--clone`](../using/clone.md) for a repo you don't trust. @@ -68,10 +91,12 @@ The lock covers `.git`, and the VM can still put things elsewhere that git on th - **What the locked files hand over to the project folder**, which is an `include.path` or `includeIf.*.path` that leads into it, or a hook that's a symlink into it. The VM can edit those files, and git on this machine reads or runs them. devvm warns about them when it creates the VM, and on a launch after they change. - **Submodules whose git folder is outside the project.** devvm can't lock that folder, because another project's VM may write it, and `git status` on this machine reads its config. devvm names these submodules when it creates the VM. - **A replaced `.git`.** The VM can rename `.git` and put a new one in its place, or point git at another config. devvm reports this on each launch but doesn't undo it ([what a lock can't stop](../internals/git-protection.md#what-a-lock-cant-stop)). +- **Some of the git repos nested in the folder.** devvm protects each repo it finds below the project folder ([nested repos](#nested-repos)), but not one more than four folders down, one in a folder that a package manager fills, such as `node_modules`, one on another disk, or one past the first 100. It doesn't lock the git folder that a nested repo's `.git` file names unless that's another repo's that devvm locks, and a git folder outside the project folder it can't lock at all. The VM can set `core.fsmonitor` in such a repo's config, and your next `git status` there runs it. devvm names the ones it finds and doesn't protect, and counts those on other disks, so check them before you run git there, or move them out of the folder. +- **A repo the VM makes while it runs**, and a [bare repo](#bare-repos) it makes. git on this machine uses either as soon as it's there, and devvm finds it only once the VM stops ([nested repos](#nested-repos)). ## Linux hosts -On Linux, devvm runs each VM's QEMU in a user namespace of its own, without root, and there it makes the paths that macOS's flag would lock read-only: the hooks and config of `.git` and of its submodules, and the rest of [what's locked](../internals/git-protection.md#whats-locked). The VM reaches the project folder only through QEMU, so root in the VM gets `Read-only file system` when it writes one of them, and `Device or resource busy` when it renames or removes one, or renames `.git` itself. Nothing changes on this machine: your own git commands write `.git/config` as usual, and the read-only view ends when the VM stops. `devvm git-protect` works as it does on macOS, and a change to a running VM's protection applies at its next start. +On Linux, devvm runs each VM's QEMU in a user namespace of its own, without root, and there it makes the paths that macOS's flag would lock read-only: the hooks and config of `.git` and of its submodules, and the rest of [what's locked](../internals/git-protection.md#whats-locked). The VM reaches the project folder only through QEMU, so root in the VM gets `Read-only file system` when it writes one of them, and `Device or resource busy` when it renames or removes one, or renames `.git` itself. A [nested repo](#nested-repos)'s own folder isn't pinned, so the VM can still rename the folder, `.git` and all, and put another repo in its place, which devvm reports at the next check as a replaced `.git`. Nothing changes on this machine: your own git commands write `.git/config` as usual, and the read-only view ends when the VM stops. `devvm git-protect` works as it does on macOS, and a change to a running VM's protection applies at its next start. Start VMs with devvm. A VM that `limactl start` starts runs without the read-only view, and so does one whose view went for another reason, so each launch of a running VM, and `devvm stop`, check that the VM still can't rename `.git` and still sees its hooks and config read-only, and name what it doesn't: run `devvm restart` then. If devvm's own process that runs the VM ends, the VM ends with it at once, as if you pulled its power, so it never runs without the view. @@ -107,11 +132,11 @@ Ubuntu 23.10 and newer set `kernel.apparmor_restrict_unprivileged_userns` to 1, ### The warning at each launch -On a Linux host that can't lock, each launch of a VM that mounts a folder with a `.git` warns that the VM can change its hooks and config, which run on this machine. That includes the launch that creates the VM, and launches of a VM that's already running. Once you've read the warning and decided to go on without protection, run `devvm git-protect off` in the folder. devvm records that you chose it and stops warning for that VM, but it still names the changes that the next section describes. A VM that you create with `--no-git-protect` doesn't warn either, and a `--clone` VM never warns, because it mounts no `.git`. +On a Linux host that can't lock, each launch of a VM that mounts a folder with a `.git`, or with [nested repos](#nested-repos), warns that the VM can change their hooks and config, which run on this machine, and names the nested repos devvm doesn't watch. That includes the launch that creates the VM, and launches of a VM that's already running. Once you've read the warning and decided to go on without protection, run `devvm git-protect off` in the folder. devvm records that you chose it and stops warning for that VM, but it still names the changes that the next section describes. A VM that you create with `--no-git-protect` doesn't warn either, and a `--clone` VM never warns, because it mounts no `.git`. ### When devvm names a change -On a Linux host that can't lock, devvm can't stop the VM from changing `.git`, and on one that locks, the VM can change a file that git on this machine [replaced](#when-git-on-this-machine-replaces-a-locked-file), but devvm notices the change afterwards on both. When devvm creates a VM, it records a hash of each path that a lock would cover on macOS, which are the hooks in `.git/hooks`, `.git/config` and the rest of [what's locked](../internals/git-protection.md#whats-locked), submodules' included. It also hashes `.git/commondir`, whether it's there or not, and what the config hands over to the project folder: the files that an `include.path` leads to, and the hooks folder that `core.hooksPath` names, such as husky's `.husky`. Each launch that finds the VM stopped, and `devvm stop`, hash them again and name every path that changed since the last check, such as `.git/config` and `.git/hooks/pre-commit`. A warning names ten paths at most, and then how many more changed. The same checks report what a lock can't stop either, as they do on macOS: a `.git` that was replaced, a `commondir`, a repo or submodule that appeared, and includes, hook links and a `core.hooksPath` into the project folder ([not covered](#not-covered)). A launch of a VM that's already running checks nothing, so run `devvm stop` when you want the check. A VM that devvm has no hashes for yet, such as one that an older devvm made, records them at its first check and names nothing. +On a Linux host that can't lock, devvm can't stop the VM from changing `.git`, and on one that locks, the VM can change a file that git on this machine [replaced](#when-git-on-this-machine-replaces-a-locked-file), but devvm notices the change afterwards on both. When devvm creates a VM, it records a hash of each path that a lock would cover on macOS, which are the hooks in `.git/hooks`, `.git/config` and the rest of [what's locked](../internals/git-protection.md#whats-locked), submodules' and [nested repos'](#nested-repos) included. It also hashes `.git/commondir`, whether it's there or not, and what the config hands over to the project folder: the files that an `include.path` leads to, and the hooks folder that `core.hooksPath` names, such as husky's `.husky`. Each launch that finds the VM stopped, and `devvm stop`, hash them again and name every path that changed since the last check, such as `.git/config` and `.git/hooks/pre-commit`. A warning names ten paths at most, and then how many more changed. The same checks report what a lock can't stop either, as they do on macOS: a `.git` that was replaced, a `commondir`, a repo or submodule that appeared, and includes, hook links and a `core.hooksPath` into the project folder ([not covered](#not-covered)). A launch of a VM that's already running checks nothing, so run `devvm stop` when you want the check. A VM that devvm has no hashes for yet, such as one that an older devvm made, records them at its first check and names nothing. devvm names a change only after it happened, so git on this machine may already have run a changed hook or read a changed config. devvm can't tell who made a change, so it also names your own, such as a `git remote add` or `git push -u` that you ran on this machine. When it names a path that you didn't change, check it before you run git in the folder: @@ -126,7 +151,7 @@ The watch isn't a security boundary, and it doesn't stop anything. It compares w - **A symlink, or a path under one,** such as a hook that's a symlink, or a `.git` that's a symlink. devvm never follows a symlink out of the project folder, so it can't see changes to what such a link points to. For a link that stays inside the project folder, it hashes what the link leads to as well. - **A file larger than 16 MiB,** which devvm records by its size, inode and change time, so it notices a change that keeps the size but can't hash the file. -- **A hooks folder with more than 1,000 entries,** which devvm records by its count and change time. It always hashes the hooks that git runs, at the folder's top, before the rest. -- **What's past 2,000 paths in all,** across every git folder and hooks folder of the repo. +- **A hooks folder with more than 1,000 entries,** which devvm records by its count and change time. It always hashes the hooks that git runs, at the folder's top, before the rest. The VM can fill a hooks folder to blind the watch, the folder's own or a nested repo's, so devvm names such a folder at every check. +- **What's past 2,000 paths in all,** across every git folder and hooks folder of the folder's own repo, or past 200 paths of each [nested repo](#nested-repos). A repo rarely has any of these, so when devvm names one that you didn't make, check what it holds, and use [`--clone`](../using/clone.md) for that repo. diff --git a/docs/content/docs/using/vms.md b/docs/content/docs/using/vms.md index 4de7f85c..1c70f102 100644 --- a/docs/content/docs/using/vms.md +++ b/docs/content/docs/using/vms.md @@ -8,7 +8,7 @@ This page covers a VM from the time devvm makes it until you delete it: opening, ## Opening a VM -devvm makes a new VM from its image of base and the layers you chose, building the image first if it isn't built yet, then starts the VM and opens a shell in it in devvm's place, so devvm ends when the shell does. The VM mounts only the project folder, read-write, and the shared tools and its [agents' config folders](coding-agents.md), read-only, or with `--clone` it gets its own clone of the repo instead of the folder. On macOS, devvm also locks the folder's `.git` hooks and config against changes from the VM ([.git protection](../safety/git-protection.md)). For a VM that exists, devvm starts it if it's stopped and opens it as it is. +devvm makes a new VM from its image of base and the layers you chose, building the image first if it isn't built yet, then starts the VM and opens a shell in it in devvm's place, so devvm ends when the shell does. The VM mounts only the project folder, read-write, and the shared tools and its [agents' config folders](coding-agents.md), read-only, or with `--clone` it gets its own clone of the repo instead of the folder. On macOS, devvm also locks the `.git` hooks and config of the folder and of the repos nested in it against changes from the VM ([.git protection](../safety/git-protection.md)). For a VM that exists, devvm starts it if it's stopped and opens it as it is. A VM is running or stopped from the time devvm makes it until you delete it. @@ -99,7 +99,7 @@ Every command that acts on this folder's VM, `devvm` included, takes `--here` an ## A nested project replaced -A project with a VM of its own inside a folder with another VM, such as a nested repo, is in both VMs, because the parent folder's VM mounts everything inside its folder. Code in the parent folder's VM can change the nested project's files, `.git` included wherever [`.git` protection](../safety/git-protection.md) doesn't cover it, and it can move the nested project folder aside and put a link in its place, or another folder. On Linux, if devvm then started the nested project's VM, the VM would mount whatever the link points to, such as your home folder. On macOS the VM mounts the project folder itself, wherever it was moved, and never what a link at its path points to. On both, devvm checks the nested project folder just before it starts the VM and again once the VM runs. If the folder is now a link, sits below a link, or is another folder, devvm doesn't start the VM, or it stops the VM again, and it tells you which. Find what replaced the folder, move the project folder back to its path, and run the command again. Replacing the folder while the VM runs never shows the VM what the link points to. On Linux the VM keeps the folder it mounted when it started, and on macOS the VM gets "Operation not permitted" for its project folder, as it does when the folder was moved aside while the VM started and put back later, so run `devvm restart` once the folder is back. To keep a nested project out of the parent folder's VM altogether, move it out of the parent folder. +A project with a VM of its own inside a folder with another VM, such as a nested repo, is in both VMs, because the parent folder's VM mounts everything inside its folder. Code in the parent folder's VM can change the nested project's files, though not the hooks and config of its `.git` while the parent folder's VM protects it, as [`.git` protection](../safety/git-protection.md#nested-repos) does for the repos nested in a VM's folder. It can also move the nested project folder aside and put a link in its place, or another folder. On Linux, if devvm then started the nested project's VM, the VM would mount whatever the link points to, such as your home folder. On macOS the VM mounts the project folder itself, wherever it was moved, and never what a link at its path points to. On both, devvm checks the nested project folder just before it starts the VM and again once the VM runs. If the folder is now a link, sits below a link, or is another folder, devvm doesn't start the VM, or it stops the VM again, and it tells you which. Find what replaced the folder, move the project folder back to its path, and run the command again. Replacing the folder while the VM runs never shows the VM what the link points to. On Linux the VM keeps the folder it mounted when it started, and on macOS the VM gets "Operation not permitted" for its project folder, as it does when the folder was moved aside while the VM started and put back later, so run `devvm restart` once the folder is back. To keep a nested project out of the parent folder's VM altogether, move it out of the parent folder. Each time `devvm` makes or opens the nested project's VM, it warns once and names the VM of the nearest parent folder that mounts the project. It warns whether that VM runs or not, because the VM can write to the folder whenever it runs. A `--clone` VM mounts nothing, so devvm doesn't warn when you open one, and a parent folder's `--clone` VM never counts. The other commands, `devvm restart` included, don't warn. diff --git a/internal/backend/backend.go b/internal/backend/backend.go index 3ffdff5d..f672b31c 100644 --- a/internal/backend/backend.go +++ b/internal/backend/backend.go @@ -513,6 +513,11 @@ type Pins struct { // start when it can't), then one each time a pin changed while the VM // ran; "" for none. Events string + // File is a file of devvm's own, in the VM's folder, that a backend + // whose pinning process reads the pins from a file writes them to: + // a VM with many nested repos has more than an environment variable + // holds. + File string } // A PinEvent is a pin that changed while the VM ran: a path, relative to diff --git a/internal/backend/lima/pins.go b/internal/backend/lima/pins.go index 38305b3b..d8fb65d9 100644 --- a/internal/backend/lima/pins.go +++ b/internal/backend/lima/pins.go @@ -14,6 +14,8 @@ import ( "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/platform" + "github.com/devvmhq/devvm/internal/safefile" + "github.com/devvmhq/devvm/internal/state" ) // On a Linux host, a start with pins (backend.Confinement.Pins: .git's @@ -31,10 +33,15 @@ import ( // which watches each pinned path's folder, pins it again, and records // that in the pins' events file, which .git protection reports. -// PinsEnv names the variable holding what QEMU's namespace pins -// (encodePins); unset or empty, QEMU runs in devvm's. +// PinsEnv names the variable holding the file that says what QEMU's +// namespace pins (backend.Pins.File, written by encodePins); unset or +// empty, QEMU runs in devvm's. const PinsEnv = "DEVVM_QEMU_PINS" +// maxPinsFile bounds the pins file decodePins reads: 100 nested repos' +// pins take a few hundred KiB at most. +const maxPinsFile = 8 << 20 + // NetEnv names the variable that says how QEMU's network is restricted: // open for a VM on Lima's own network, whose arguments QEMU gets as Lima // gives them; anything else, restrict=on (RestrictNetdev). @@ -109,21 +116,36 @@ func (s pinSet) pins() []platform.Pin { return out } -// encodePins is p as PinsEnv holds it, checked first. +// encodePins writes p, checked first, to its file (p.File), private, and +// returns the file, as PinsEnv holds it. func encodePins(p backend.Pins) (string, error) { s := pinsOf(p) if err := s.check(); err != nil { return "", err } + if !filepath.IsAbs(p.File) { + return "", msg.QEMUPinsInvalid(p.File) + } b, err := json.Marshal(s) - return string(b), err + if err != nil { + return "", err + } + return p.File, state.WriteFileMode(p.File, b, 0o600) } -// decodePins reads what encodePins wrote, checking it again. +// decodePins reads what encodePins wrote to the file v, a regular file +// read through no symlink, checking it again. func decodePins(v string) (pinSet, error) { + if !filepath.IsAbs(v) { + return pinSet{}, msg.QEMUPinsInvalid(PinsEnv) + } + b, err := safefile.Read(v, maxPinsFile, safefile.Opts{}) + if err != nil { + return pinSet{}, msg.QEMUPinsInvalid(v).Because(err) + } var s pinSet - if err := json.Unmarshal([]byte(v), &s); err != nil { - return pinSet{}, msg.QEMUPinsInvalid(PinsEnv).Because(err) + if err := json.Unmarshal(b, &s); err != nil { + return pinSet{}, msg.QEMUPinsInvalid(v).Because(err) } return s, s.check() } diff --git a/internal/backend/lima/pins_test.go b/internal/backend/lima/pins_test.go index e2e1cd0d..bb47d5b7 100644 --- a/internal/backend/lima/pins_test.go +++ b/internal/backend/lima/pins_test.go @@ -44,19 +44,35 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) //nolint:forbidigo // the test binary } +// pinsFile writes data, a set of pins as encodePins writes them, to a +// file of the test's own, and returns it, as PinsEnv holds it. +func pinsFile(t *testing.T, data string) string { + t.Helper() + f := filepath.Join(t.TempDir(), "git-pins.json") + if err := os.WriteFile(f, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + return f +} + // Pins go folders first, so a folder's pin never hides one below it, and -// what _qemu reads back is what was written, its events file included. +// what _qemu reads back is what was written, private, its events file +// included. func TestPinsOrder(t *testing.T) { p := backend.Pins{ Root: "/p", Fixed: []string{".git/modules/a", ".git", "sub/.git"}, ReadOnly: []string{".git/modules/a/config", ".git/config", ".git/hooks", "sub/.git/hooks"}, Events: "/d/git-pins.jsonl", + File: filepath.Join(t.TempDir(), "git-pins.json"), } v, err := encodePins(p) if err != nil { t.Fatal(err) } + if fi, err := os.Stat(v); err != nil || v != p.File || fi.Mode().Perm() != 0o600 { + t.Errorf("file %s: %v", v, err) + } s, err := decodePins(v) if err != nil { t.Fatal(err) @@ -92,12 +108,26 @@ func TestPinsRefused(t *testing.T) { {Root: "/p", Fixed: []string{".."}}, {Root: "/p", ReadOnly: []string{".git/config"}, Events: "events"}, {Root: "/p"}, + {Root: "/p", ReadOnly: []string{".git/config"}, File: "git-pins.json"}, } { + if p.File == "" { + p.File = filepath.Join(t.TempDir(), "git-pins.json") + } if _, err := encodePins(p); !errors.As(err, new(msg.M)) { t.Errorf("%+v: %v", p, err) } } for _, v := range []string{"", "x", `{"root":"/p","pins":[{"path":"../x"}]}`, `{"root":"/p","pins":[]}`} { + if _, err := decodePins(pinsFile(t, v)); err == nil { + t.Errorf("%q read", v) + } + } + // A file that isn't absolute, isn't there, or is a symlink. + link := filepath.Join(t.TempDir(), "link") + if err := os.Symlink(pinsFile(t, `{"root":"/p","pins":[{"path":".git"}]}`), link); err != nil { + t.Fatal(err) + } + for _, v := range []string{"", "git-pins.json", "/no/git-pins.json", link} { if _, err := decodePins(v); err == nil { t.Errorf("%q read", v) } @@ -107,7 +137,7 @@ func TestPinsRefused(t *testing.T) { // Without pins it can read, or off Linux, nothing pins and QEMU doesn't // start: _qemu exec and pinned refuse, and so does the probe. func TestPinsRefuseToStart(t *testing.T) { - t.Setenv(PinsEnv, `{"root":"/p","pins":[{"path":"../x"}]}`) + t.Setenv(PinsEnv, pinsFile(t, `{"root":"/p","pins":[{"path":"../x"}]}`)) var m msg.M if err := runPinned("/no/devvm", "/no/qemu", nil); !errors.As(err, &m) || m.ID() != "qemu_pins_invalid" { t.Errorf("exec: %v", err) @@ -124,7 +154,7 @@ func TestPinsRefuseToStart(t *testing.T) { t.Fatal(err) } for _, root := range []string{filepath.Join(dir, "gone"), filepath.Join(dir, "link")} { - v, err := encodePins(backend.Pins{Root: root, ReadOnly: []string{".git/config"}}) + v, err := encodePins(backend.Pins{Root: root, ReadOnly: []string{".git/config"}, File: filepath.Join(t.TempDir(), "git-pins.json")}) if err != nil { t.Fatal(err) } @@ -134,7 +164,7 @@ func TestPinsRefuseToStart(t *testing.T) { } } // An events file it can't write: what changes would go unrecorded. - v, err := encodePins(backend.Pins{Root: dir, ReadOnly: []string{".git/config"}, Events: filepath.Join(dir, "gone", "git-pins.jsonl")}) + v, err := encodePins(backend.Pins{Root: dir, ReadOnly: []string{".git/config"}, Events: filepath.Join(dir, "gone", "git-pins.jsonl"), File: filepath.Join(t.TempDir(), "git-pins.json")}) if err != nil { t.Fatal(err) } @@ -149,7 +179,7 @@ func TestPinsRefuseToStart(t *testing.T) { if err := probePins("/no/devvm"); !errors.Is(err, errors.ErrUnsupported) { t.Errorf("probe off Linux: %v", err) } - t.Setenv(PinsEnv, `{"root":"/p","pins":[{"path":".git"}]}`) + t.Setenv(PinsEnv, pinsFile(t, `{"root":"/p","pins":[{"path":".git"}]}`)) if err := runPinned("/no/devvm", "/no/qemu", nil); err == nil { t.Error("a namespace off Linux") } @@ -248,7 +278,7 @@ func pinnedProject(t *testing.T) (dir, events string) { } } events = filepath.Join(t.TempDir(), "git-pins.jsonl") - v, err := encodePins(backend.Pins{Root: dir, Fixed: []string{".git"}, ReadOnly: []string{".git/config", ".git/hooks"}, Events: events}) + v, err := encodePins(backend.Pins{Root: dir, Fixed: []string{".git"}, ReadOnly: []string{".git/config", ".git/hooks"}, Events: events, File: filepath.Join(t.TempDir(), "git-pins.json")}) if err != nil { t.Fatal(err) } diff --git a/internal/backend/lima/start_test.go b/internal/backend/lima/start_test.go index cce17ed9..c4de4be2 100644 --- a/internal/backend/lima/start_test.go +++ b/internal/backend/lima/start_test.go @@ -54,7 +54,7 @@ func TestStartConfined(t *testing.T) { open := proxy open.Net = backend.NetDirect pinned := proxy - pinned.Pins = backend.Pins{Root: "/p", Fixed: []string{".git"}, ReadOnly: []string{".git/config", ".git/hooks"}} + pinned.Pins = backend.Pins{Root: "/p", Fixed: []string{".git"}, ReadOnly: []string{".git/config", ".git/hooks"}, File: filepath.Join(t.TempDir(), "git-pins.json")} for _, tc := range []struct { name, os string c backend.Confinement @@ -171,8 +171,11 @@ func TestStartConfined(t *testing.T) { if n, _ := envOf(s, NetEnv); tc.qemu && n != tc.net { t.Errorf("%s=%q, want %q", NetEnv, n, tc.net) } - if p, _ := envOf(s, PinsEnv); tc.qemu && p != tc.pins { + // The pins go in their file, which the variable names. + if p, _ := envOf(s, PinsEnv); tc.qemu && (p == "") != (tc.pins == "") { t.Errorf("%s=%q, want %q", PinsEnv, p, tc.pins) + } else if b, _ := os.ReadFile(p); tc.qemu && p != "" && (p != tc.c.Pins.File || string(b) != tc.pins) { //nolint:gosec // the test's own + t.Errorf("%s=%q holds %s, want %s", PinsEnv, p, b, tc.pins) } // Lima propagates the host's proxy settings only to a VM on its // own network without devvm's proxy. diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go index d2052229..f2c28a1a 100644 --- a/internal/cli/doctor.go +++ b/internal/cli/doctor.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/devvmhq/devvm/internal/backend" + "github.com/devvmhq/devvm/internal/hostsafety" "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/netpolicy" "github.com/devvmhq/devvm/internal/paths" @@ -45,10 +46,11 @@ func newDoctorCmd(a *app) *cobra.Command { return failed(err, msg.DoctorFailed) } d := doctor{ - Path: onPath{LookPath: exec.LookPath, Executable: os.Executable}, - Free: reg.Host.FreeSpace, - Host: func() (vm.Host, error) { return vm.ThisHost(reg.Host) }, - Dirs: a.dirs, + GitBare: func() bool { return hostsafety.BareExplicit(cmd.Context()) }, + Path: onPath{LookPath: exec.LookPath, Executable: os.Executable}, + Free: reg.Host.FreeSpace, + Host: func() (vm.Host, error) { return vm.ThisHost(reg.Host) }, + Dirs: a.dirs, Policies: func() []msg.M { dirs, err := a.dirs() if err != nil { @@ -83,13 +85,16 @@ func newDoctorCmd(a *app) *cobra.Command { } // doctorOutput is devvm doctor --json: the backend new VMs get and what -// it's missing, doctor's warnings, whether Docker is installed, and every -// backend's features. +// it's missing, doctor's warnings and tips, whether Docker is installed, +// and every backend's features. type doctorOutput struct { Backend string `json:"backend"` Problems []problemJSON `json:"problems"` Warnings []string `json:"warnings"` - Docker bool `json:"docker"` + // Tips is doctor's advice, which isn't a problem: git's + // safe.bareRepository. + Tips []string `json:"tips"` + Docker bool `json:"docker"` // Features is, for each backend, how it has each feature: native, // emulated, unreviewed or none. Features map[string]map[string]string `json:"features"` @@ -118,7 +123,7 @@ type problemJSON struct { func (d doctor) report(ctx context.Context, text func(msg.M) string, all []backend.Backend, b backend.Backend) doctorOutput { out := doctorOutput{ Backend: b.Name(), - Problems: []problemJSON{}, Warnings: []string{}, Features: map[string]map[string]string{}, + Problems: []problemJSON{}, Warnings: []string{}, Tips: []string{}, Features: map[string]map[string]string{}, } for _, p := range b.Problems(ctx) { j := problemJSON{Key: p.Key, Message: text(p.Msg)} @@ -130,6 +135,9 @@ func (d doctor) report(ctx context.Context, text func(msg.M) string, all []backe for _, m := range d.warnings(b) { out.Warnings = append(out.Warnings, text(m)) } + for _, m := range d.tips() { + out.Tips = append(out.Tips, text(m)) + } _, err := exec.LookPath("docker") out.Docker = err == nil for _, be := range all { @@ -169,6 +177,16 @@ func (d doctor) warnings(b backend.Backend) []msg.M { return ms } +// tips are doctor's advice, which it says rather than warns, as nothing +// is wrong: git's safe.bareRepository, which hardens git on this machine +// against a bare repo a VM makes. +func (d doctor) tips() []msg.M { + if d.GitBare != nil && !d.GitBare() { + return []msg.M{msg.DoctorGitBare()} + } + return nil +} + // The host devvm recommends: base asks for 4 CPUs and 8 GiB. const ( recommendedCPUs = 4 @@ -195,6 +213,9 @@ type doctor struct { // Pins is the check of whether this Linux host locks .git, and why // not. Pins pinsCheck + // GitBare reports whether this machine's git takes a bare repo only + // when it's named (hostsafety.BareExplicit); nil checks nothing. + GitBare func() bool } // known is what the daily release check last found, if anything. @@ -220,6 +241,9 @@ func (d doctor) run(ctx context.Context, u *ui.UI, b backend.Backend) error { u.Say(msg.DockerMissing()) } sayProxyCA(u, d.Dirs) + for _, m := range d.tips() { + u.Say(m) + } for _, m := range d.warnings(b) { u.Warn(m) } diff --git a/internal/cli/doctor_test.go b/internal/cli/doctor_test.go index 548050d4..96ccb399 100644 --- a/internal/cli/doctor_test.go +++ b/internal/cli/doctor_test.go @@ -109,6 +109,7 @@ func TestDoctorReport(t *testing.T) { Host: func() (vm.Host, error) { return vm.Host{CPUs: 2, MemoryGiB: 16}, nil }, Policies: func() []msg.M { return []msg.M{msg.PolicyNotRule("/p", "2", "a b")} }, Folders: func() []msg.M { return []msg.M{msg.VMFolderStateless("/vms/0123456789abcd")} }, + GitBare: func() bool { return false }, } r := d.report(t.Context(), msg.M.Names, []backend.Backend{b}, b) fix := "brew install lima" @@ -117,7 +118,8 @@ func TestDoctorReport(t *testing.T) { r.Problems[0].Message != want[0].Message || r.Problems[1].Key != "kvm" { t.Errorf("problems %+v, want %+v", r.Problems, want) } - if !slices.Equal(r.Warnings, []string{"host_cpus_few have=2 want=4", "policy_not_rule file=/p line=2 rule=a b", "vm_folder_stateless path=/vms/0123456789abcd"}) || r.Backend != "lima" { + if !slices.Equal(r.Warnings, []string{"host_cpus_few have=2 want=4", "policy_not_rule file=/p line=2 rule=a b", "vm_folder_stateless path=/vms/0123456789abcd"}) || r.Backend != "lima" || + !slices.Equal(r.Tips, []string{"doctor_git_bare"}) { t.Errorf("warnings %q, backend %q", r.Warnings, r.Backend) } if r.Features["lima"]["ssh"] != "native" || r.Features["lima"]["disk"] != "none" { diff --git a/internal/cli/json_test.go b/internal/cli/json_test.go index e158fff5..c07d24c6 100644 --- a/internal/cli/json_test.go +++ b/internal/cli/json_test.go @@ -71,12 +71,12 @@ func machineShapes() []shapeCase { "doctor", doctorOutput{ Backend: "lima", Problems: []problemJSON{{Key: "lima", Fix: &fix, Message: "m"}, {Key: "kvm", Message: "m"}}, - Warnings: []string{"w"}, Docker: yes, Features: map[string]map[string]string{"lima": {"ssh": "native"}}, + Warnings: []string{"w"}, Tips: []string{"t"}, Docker: yes, Features: map[string]map[string]string{"lima": {"ssh": "native"}}, Release: &releaseJSON{Latest: "0.2.0", Checked: "2026-11-05T00:00:00Z"}, }, []string{ "backend: string", "docker: bool", "features.lima.ssh: string", "problems[].fix: string", "problems[].key: string", - "problems[].message: string", "release.checked: string", "release.latest: string", "warnings[]: string", + "problems[].message: string", "release.checked: string", "release.latest: string", "tips[]: string", "warnings[]: string", }, }, { diff --git a/internal/cli/script_test.go b/internal/cli/script_test.go index 099a3783..e942b6f8 100644 --- a/internal/cli/script_test.go +++ b/internal/cli/script_test.go @@ -204,6 +204,10 @@ func sandbox(env *testscript.Env, bin, stubs string) error { if err := os.WriteFile(filepath.Join(root, "data", "devvm", "settings.json"), []byte(`{"features": []}`+"\n"), 0o600); err != nil { return err } + // git takes a bare repo only when it's named, as devvm doctor asks. + if err := os.WriteFile(filepath.Join(root, "home", ".gitconfig"), []byte("[safe]\n\tbareRepository = explicit\n"), 0o600); err != nil { + return err + } // Ubuntu's cloud images: a dated release in a folder, as Ubuntu // published and signed it (internal/ubuntu's fixture), never the // network. diff --git a/internal/gitprotect/gitprotect.go b/internal/gitprotect/gitprotect.go index a4fbadf5..b09a18d7 100644 --- a/internal/gitprotect/gitprotect.go +++ b/internal/gitprotect/gitprotect.go @@ -22,11 +22,14 @@ import ( "context" "errors" "io/fs" + "maps" "os" "path/filepath" + "slices" "strings" "github.com/devvmhq/devvm/internal/hostgit" + "github.com/devvmhq/devvm/internal/hostsafety" "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/state" @@ -48,13 +51,48 @@ type InVM struct { Next string `json:"next,omitempty"` // the mode chosen while the VM ran, set when it's next stopped Made Made `json:"made,omitzero"` Watched Watched `json:"watched,omitzero"` + // Nested is the git repos nested in the folder that the last walk + // found (Protector.Nested) and the protection doesn't cover + // (uncovered), relative to the folder, and NestedMore how many more + // the walk counted past its bound: launches name them, as the VM can + // change their .git. + Nested []string `json:"nested,omitempty"` + NestedMore int `json:"nested_more,omitempty"` + NestedPast []string `json:"nested_past,omitempty"` // the first of those NestedMore counts + // Bare, Skipped and Devices are what else the last walk found + // (hostsafety.Repos), which checks name when it's new. + Bare []string `json:"bare,omitempty"` + Skipped int `json:"skipped,omitempty"` + Devices int `json:"devices,omitempty"` + // NestedNoticed is set once a VM whose protection doesn't cover its + // nested repos (Made.Nested unset) was told it can (git_nested_protectable). + NestedNoticed bool `json:"nested_noticed,omitempty"` } -// Made is what protecting a VM's .git found, and checks compare with. +// Made is what protecting a VM's .git found, and checks compare with: +// of the folder's own repo, and of each repo nested in it that it +// protects. type Made struct { // Protected is set once its protection was set up as a new VM's // (NewVM) or turned on: until then, there's nothing to compare with. Protected bool `json:"protected,omitempty"` + Repo // the folder's own repo's, as its fields + // Nested is set once the repos nested in the folder are protected + // too: by a new VM, devvm git-protect on or strict, or the watch. A + // VM an older devvm made protects only its own until then. + Nested bool `json:"nested,omitempty"` + // Repos is each nested repo's, by its top folder relative to the + // project folder. A repo without one is scanned the first time, which + // records it without reporting. + Repos map[string]Repo `json:"repos,omitempty"` + // Left is the nested repos it stopped protecting, as they're gone or + // another repo's protection covers them, whose locks may still be on: + // Unlock takes them off too, and names those not in the folder. + Left map[string]Repo `json:"left,omitempty"` +} + +// Repo is what protecting one repo's .git found. +type Repo struct { // GitID is .git's identity (platform.FolderID) when it was last // locked. GitID string `json:"git_id,omitempty"` @@ -104,13 +142,28 @@ type Protector struct { Locker Locker // Reporter is where it warns. msg.Reporter + // Nested is the git repos nested in the folder, as the walk of a + // stopped VM's folder found them (hostsafety.Walk), which the caller + // sets; nil when it didn't walk, as for a running VM, whose recorded + // repos are protected. + Nested *hostsafety.Repos + // Kept says, for the VM vm, whether another VM keeps a path locked + // too, as its own protection covers it (Keeps), or may (its state + // can't be read): the warning that names it (git_kept_locked, + // git_kept_unread), or a zero msg.M for none. Unlock and strict leave + // such a path locked. nil keeps none. + Kept func(vm string) func(path string) msg.M + // Serial runs f holding the host's lock of .git protection + // (paths.Dirs.GitLock), so one VM's unlock never runs between + // another's locks and their record; nil runs f alone. + Serial func(ctx context.Context, f func() error) error } // New returns the protector for the project folder dir, ~ in git's paths // being home (paths.Dirs.Home), locking with l (HostLocker), warning // through r. func New(dir, home string, l Locker, r msg.Reporter) *Protector { - return &Protector{tree: tree{Dir: dir, Home: home}, Locker: l, Reporter: r} + return &Protector{tree: tree{Dir: dir, Root: dir, Home: home}, Locker: l, Reporter: r} } // NewSection is the protection a new VM gets, recorded before its @@ -149,17 +202,35 @@ func (p *Protector) NewVM(ctx context.Context, vm *state.VM) error { // the locker leaves a window the guest could use (Locker.Watches), sums // what a lock covers once the VM is stopped, naming what changed since // was, as a host without locks does (watcher.watch). A zero was records -// the sums without naming anything: .git as it is now, as trusted. +// the sums without naming anything: .git as it is now, as trusted. The +// repos nested in the folder are protected too once the VM's protection +// covers them (Made.Nested), which a new VM's and devvm git-protect's +// does. func (p *Protector) lockAndWatch(ctx context.Context, vm *state.VM, g InVM, w why, h how, was Watched, set func(*InVM)) error { - snap := p.scan(ctx) - made := p.protect(ctx, snap, g, w, h) - if err := record(ctx, vm, func(g *InVM) { set(g); g.Made = made }); err != nil { + // A running VM's check is the folder's own repo's alone: it locks + // nothing, so its nested repos wait for the next stopped one, which a + // launch into a running VM never pays for. + nested := g.Made.Nested || w != whyCheck + c := p.repos(g.Made, nested && h != later, p.Nested) + var snaps []snapshot + var made Made + // The locks and their record, under the host's lock: another VM's + // unlock goes by the record. + err := serial(ctx, p.Serial, func() error { + snaps = scanAll(ctx, c.trees) + made = p.protect(ctx, vm.Name(), snaps, g, w, h, c) + return record(ctx, vm, func(g *InVM) { set(g); g.Made = made }) + }) + if err != nil { + return err + } + if err := p.nested(ctx, vm, snaps, w); err != nil { return err } if h != lockNow || !p.Locker.Watches() { return nil } - return watcher{p}.watch(ctx, vm, snap, was) + return watcher{p}.watch(ctx, vm, snaps, was, unwatched(g.Made, made, c.gone)) } // Modes of .git protection, as devvm git-protect takes them. Strict is on, @@ -190,10 +261,11 @@ func SetNext(ctx context.Context, vm *state.VM, mode string) error { } // Set changes the protection of a stopped VM: on and strict lock .git as -// it is now, as trusted, and report what a lock can't cover; strict also -// sets diff.ignoreSubmodules=all in the locked .git/config, which on and -// off take out again; off unlocks. On and strict need a host that locks. -// Once it's set, a mode saved for the VM's next stop (SetNext) is +// it is now, as trusted, the repos nested in the folder's included, and +// report what a lock can't cover; strict also sets +// diff.ignoreSubmodules=all in each repo's locked .git/config, which on +// and off take out again; off unlocks. On and strict need a host that +// locks. Once it's set, a mode saved for the VM's next stop (SetNext) is // dropped: both are recorded at once, with the mode as the user's choice // (Chosen). func (p *Protector) Set(ctx context.Context, vm *state.VM, mode string) error { @@ -205,21 +277,17 @@ func (p *Protector) Set(ctx context.Context, vm *state.VM, mode string) error { if mode == Off { p.Unlock(ctx, vm) if was == Strict { - if err := p.ignoreSubmodules(ctx, false); err != nil { + if err := p.strict(ctx, vm.Name(), p.recorded(g.Made), false); err != nil { return err } } - return record(ctx, vm, func(g *InVM) { g.Mode, g.Chosen, g.Next = Off, true, "" }) + return record(ctx, vm, func(g *InVM) { g.Mode, g.Chosen, g.Next, g.Made.Left = Off, true, "", nil }) } if !p.Locker.Locks() { return msg.GitProtectOnNeedsLocks() } if mode == Strict || was == Strict { - if err := p.ignoreSubmodules(ctx, mode == Strict); err != nil { - // Locked as it was. - if cfg := filepath.Join(p.git(), "config"); was != Off && isFile(cfg) && p.realInDir(cfg) { - p.flag(ctx, true, cfg) - } + if err := p.strict(ctx, vm.Name(), p.repos(g.Made, true, p.Nested).trees, mode == Strict); err != nil { return err } } @@ -227,12 +295,50 @@ func (p *Protector) Set(ctx context.Context, vm *state.VM, mode string) error { return p.lockAndWatch(ctx, vm, g, whyOn, lockNow, Watched{}, func(g *InVM) { g.Mode, g.Chosen, g.Next = mode, true, "" }) } -// ignoreSubmodules sets diff.ignoreSubmodules=all in .git/config, or takes -// it out, unlocking the file for the moment (protect locks it again). -func (p *Protector) ignoreSubmodules(ctx context.Context, on bool) error { - cfg := filepath.Join(p.git(), "config") +// strict sets diff.ignoreSubmodules=all in the .git/config of each of +// trees that has a .git folder, or takes it out (ignoreSubmodules), for +// the VM vm: never in a config another VM's protection keeps locked too +// (Kept), which unlocking would leave that VM's to race, and which it +// names. When setting one fails, the configs it unlocked that were locked +// are locked again. +func (p *Protector) strict(ctx context.Context, vm string, trees []tree, on bool) error { + kept := keeper(p.Kept, vm) + keepers := map[string]msg.M{} + var relock []string + for _, t := range trees { + cfg := filepath.Join(t.git(), "config") + if t.Root != p.Dir && (!isDir(t.git()) || isLink(t.git())) { + continue + } + if k := kept(cfg); k.ID() != "" { + keepers[k.String()] = k + continue + } + if p.Locker.Locked(cfg) { + relock = append(relock, cfg) + } + if err := p.ignoreSubmodules(ctx, t, on); err != nil { + for _, c := range relock { + if isFile(c) && p.realInDir(c) { + p.flag(ctx, true, c) + } + } + return err + } + } + for _, k := range slices.Sorted(maps.Keys(keepers)) { + p.Warn(keepers[k]) + } + return nil +} + +// ignoreSubmodules sets diff.ignoreSubmodules=all in t's .git/config, or +// takes it out, unlocking the file for the moment (protect locks it +// again). +func (p *Protector) ignoreSubmodules(ctx context.Context, t tree, on bool) error { + cfg := filepath.Join(t.git(), "config") if !isFile(cfg) || !p.realInDir(cfg) { - if on && exists(p.git()) { + if on && exists(t.git()) { return msg.GitConfigFailed(cfg) } return nil @@ -293,30 +399,85 @@ func (p *Protector) Check(ctx context.Context, vm *state.VM, running bool) error } // Unlock takes the locks off, for a VM that's being deleted or turned -// off: what's to lock now, and the hooks and config of every git dir its -// state records locking (vm; nil for none), which the VM may since have -// dropped from its index. Like locking, it never acts through a symlink. +// off: of the folder's own repo and of each nested repo its state records +// protecting (vm; nil for none), what's to lock now, and the hooks and +// config of every git dir its state records locking, which the VM may +// since have dropped from its index. A path another VM's protection +// keeps locked too (Kept) stays locked, and that VM is named. Like +// locking, it never acts through a symlink. func (p *Protector) Unlock(ctx context.Context, vm *state.VM) { if !p.Locker.Locks() { return } - todo := p.scan(ctx).paths + var g InVM + name := "" if vm != nil { - g, _ := Of(vm) - for _, d := range p.abs(g.Made.GitDirs) { + g, _ = Of(vm) + name = vm.Name() + } + _ = serial(ctx, p.Serial, func() error { + p.unlock(ctx, name, g.Made) + return nil + }) +} + +// unlock is Unlock's, under the host's lock: of the repos made records, +// those it protects and those it stopped protecting but may have left +// locked (Made.Left), the git dirs it recorded locking too. Those of the +// latter that aren't in the folder any more are named. +func (p *Protector) unlock(ctx context.Context, vm string, made Made) { + trees := p.recorded(made) + repos := append([]Repo{made.Repo}, slices.Collect(maps.Values(made.Repos))...) + var lost []string + for _, rel := range slices.Sorted(maps.Keys(made.Left)) { + repos = append(repos, made.Left[rel]) + if r := p.repoAt(rel); filepath.IsLocal(rel) && exists(r.Root) { + trees = append(trees, r) + } else { + lost = append(lost, rel) + } + } + var todo []string + for _, s := range scanAll(ctx, trees) { + todo = append(todo, s.paths...) + } + for _, r := range repos { + for _, d := range p.abs(r.GitDirs) { todo = append(todo, filepath.Join(d, "hooks"), filepath.Join(d, "config")) } } + kept := keeper(p.Kept, vm) + keepers := map[string]msg.M{} done := map[string]bool{} for _, path := range todo { if done[path] { continue } done[path] = true + if k := kept(path); k.ID() != "" { + keepers[k.String()] = k + continue + } if _, err := os.Lstat(path); err == nil && p.realInDir(path) { p.flag(ctx, false, path) } } + for _, k := range slices.Sorted(maps.Keys(keepers)) { + p.Warn(keepers[k]) + } + if _, flags := p.Locker.(Flags); flags && len(lost) > 0 { + l, _ := listed(lost) + p.Warn(msg.GitLocksLeft(l)) + } +} + +// serial runs f under the host's lock of .git protection, with s +// (Protector.Serial), or alone when it's nil. +func serial(ctx context.Context, s func(context.Context, func() error) error, f func() error) error { + if s == nil { + return f() + } + return s(ctx, f) } // lock locks the paths to protect (s.paths), which only happens while @@ -339,8 +500,12 @@ func (p *Protector) lock(ctx context.Context, s snapshot) { _ = os.Mkdir(path, 0o700) } } - if _, err := os.Lstat(path); err == nil { + switch _, err := os.Lstat(path); { + case err == nil: p.flag(ctx, true, path) + case !errors.Is(err, fs.ErrNotExist): + // One the VM made unreadable can't be locked, nor known gone. + p.Warn(msg.GitNotLocked(path)) } } } diff --git a/internal/gitprotect/gitprotect_test.go b/internal/gitprotect/gitprotect_test.go index 561dedd7..c9c8dcbc 100644 --- a/internal/gitprotect/gitprotect_test.go +++ b/internal/gitprotect/gitprotect_test.go @@ -39,7 +39,7 @@ func newFixture(t *testing.T, name string) *fixture { f := &fixture{t: t, root: root, dir: filepath.Join(root, name), immutable: map[string]bool{}} mkdirs(t, f.dir) f.p = &Protector{ - tree: tree{Dir: f.dir, Home: filepath.Join(root, "home")}, + tree: tree{Dir: f.dir, Root: f.dir, Home: filepath.Join(root, "home")}, Reporter: &msg.Fake{OnWarn: f.warns.Add}, } f.canLock(true) diff --git a/internal/gitprotect/nested.go b/internal/gitprotect/nested.go new file mode 100644 index 00000000..513f1ba7 --- /dev/null +++ b/internal/gitprotect/nested.go @@ -0,0 +1,237 @@ +package gitprotect + +import ( + "bytes" + "context" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/devvmhq/devvm/internal/hostsafety" + "github.com/devvmhq/devvm/internal/msg" + "github.com/devvmhq/devvm/internal/state" +) + +// A folder can hold git repos of its own below its own repo, or without +// one: a folder of repos. The walk of a stopped VM's folder finds them +// (Protector.Nested), and a VM whose protection covers them (Made.Nested) +// protects each as it does the folder's own (repos.go). Those it doesn't +// cover are named, as the VM can change their hooks and config, and git +// on this machine runs them when the user runs git there: a VM's nested +// repos past the walk's bound, those whose .git leads to a git dir in the +// folder that nothing locks, and all of them for a VM an older devvm made, +// whose protection covers its own repo alone until devvm git-protect on. + +// nested records the repos nested in the folder that the walk found +// (p.Nested) and the protection, as of the scans snaps, doesn't cover +// (uncovered), and names them where the host locks: all of them when the +// protection was just set up (a new VM, devvm git-protect), those not +// named before at a check. A VM whose protection doesn't cover its nested +// repos is told once that devvm git-protect on protects them +// (git_nested_protectable). On a host without locks, WarnUnprotected +// names them at each launch instead. Without a walk, nothing changes. +func (p *Protector) nested(ctx context.Context, vm *state.VM, snaps []snapshot, w why) error { + if p.Nested == nil { + return nil + } + n := p.Nested + inside, outside := uncovered(p.Dir, snaps, n.Dirs) + un := slices.Clone(inside) + for _, o := range outside { + un = append(un, o[0]) + } + was, _ := Of(vm) + // Named once each: at a check, those not named before. + fresh := func(now, before []string) []string { + if w != whyCheck { + return now + } + return slices.DeleteFunc(slices.Clone(now), func(d string) bool { return slices.Contains(before, d) }) + } + notice := p.Locker.Locks() && w == whyCheck && !was.Made.Nested && !was.NestedNoticed && len(un) > 0 + switch { + case notice: + p.warnNested(un, func(l string, c int) msg.M { + if c == 0 { + return msg.GitNestedProtectable(l, vm.Name()) + } + return msg.GitNestedProtectableMore(c, l, vm.Name()) + }) + case p.Locker.Locks(): + p.warnNested(fresh(inside, was.Nested), unprotected(vm.Name())) + for _, o := range outside { + if w != whyCheck || !slices.Contains(was.Nested, o[0]) { + p.Warn(msg.GitNestedGitdirOutside(o[1], o[0])) + } + } + } + bare := p.bare(snaps, n) + p.warnFound(vm.Name(), was, w, fresh(bare, was.Bare)) + if p.Locker.Locks() { + p.warnPast(vm.Name(), n.More, n.Past) + } + return record(ctx, vm, func(g *InVM) { + g.Nested, g.NestedMore, g.NestedPast = un, n.More, n.Past + g.NestedNoticed = g.NestedNoticed || notice + g.Bare, g.Skipped, g.Devices = bare, n.Skipped, n.Devices + }) +} + +// bare is the folders shaped like git dirs that the walk found (n.Bare) +// but a repo's: not a git dir a scan in snaps locks, as a repo's own or a +// submodule's, or one a nested repo's .git leads to, such as a separate +// git dir, which the repo's own warnings name. +func (t tree) bare(snaps []snapshot, n *hostsafety.Repos) []string { + var known []string + for _, s := range snaps { + known = append(known, s.covered...) + for _, d := range s.emb.inside { + known = append(known, resolved(d)) + } + } + for _, rel := range n.Dirs { + known = append(known, resolved(repoGitDir(filepath.Join(t.Dir, rel)))) + } + return slices.DeleteFunc(slices.Clone(n.Bare), func(rel string) bool { + r := resolved(filepath.Join(t.Dir, rel)) + return r != "" && slices.Contains(known, r) + }) +} + +// warnFound names, on any host, what the walk found that devvm doesn't +// protect: the folders shaped like git dirs in bare, and the repos it +// counted where it doesn't look for them and the folders on other file +// systems, all of them when the protection was just set up (w), and at a +// check when the count changed from was's. +func (p *Protector) warnFound(vm string, was InVM, w why, bare []string) { + n := p.Nested + if len(bare) > 0 { + l, _ := listed(bare) + p.Warn(msg.GitNestedBare(l, vm)) + } + if n.Skipped > 0 && (w != whyCheck || n.Skipped != was.Skipped) { + p.Warn(msg.GitNestedSkipped(n.Skipped, vm)) + } + if n.Devices > 0 && (w != whyCheck || n.Devices != was.Devices) { + p.Warn(msg.GitNestedDevices(n.Devices, vm)) + } +} + +// warnPast names the nested repos past the walk's bound, more of them, +// the first of them past: at every check, as the VM could keep their +// count and change which they are. +func (p *Protector) warnPast(vm string, more int, past []string) { + if more > 0 { + l, _ := listed(past) + p.Warn(msg.GitNestedPastBound(more, l, vm)) + } +} + +// unprotected is the warning that names the nested repos l, and n more, +// that the VM vm's protection doesn't cover. +func unprotected(vm string) func(l string, n int) msg.M { + return func(l string, n int) msg.M { + if n == 0 { + return msg.GitNestedUnprotected(l, vm) + } + return msg.GitNestedUnprotectedMore(n, l, vm) + } +} + +// warnNested names nested repos, the folders rel to the project folder, +// at most maxListed of them, in the warning m makes of them and how many +// more there are; none, nothing. +func (p *Protector) warnNested(rel []string, m func(l string, n int) msg.M) { + if len(rel) == 0 { + return + } + l, more := listed(rel) + p.Warn(m(l, more)) +} + +// programs is what in the .git the scan s found runs programs on this +// machine when git runs there: each key of its config that names a +// program, an include, or an alias that runs a shell command (! first), +// as git lists it, and each hook in its hooks folder that isn't one of +// git's samples, as hooks/NAME. +func programs(ctx context.Context, s snapshot) []string { + var out []string + g, common := s.git, s.git + if d := repoGitDir(s.tree.Root); d != "" { + g, common = d, d // where a .git file or symlink leads + } + if c, ok := commonOf(g); ok { + common = c // where git reads the config, through a commondir + } + list := git(ctx, "config", "--file", filepath.Join(common, "config"), "--list", "-z") + for rec := range bytes.SplitSeq(list, []byte{0}) { + k, v, _ := bytes.Cut(rec, []byte{'\n'}) + if key := string(k); runsProgram(key, string(v)) && !slices.Contains(out, key) { + out = append(out, key) + } + } + var entries []os.DirEntry + if f, err := os.Open(filepath.Join(common, "hooks")); err == nil { //nolint:gosec,forbidigo // a folder, for its first names alone: no file in it is read + entries, _ = f.ReadDir(maxWatchEntries) + _ = f.Close() + } + slices.SortFunc(entries, func(a, b os.DirEntry) int { return strings.Compare(a.Name(), b.Name()) }) + for _, e := range entries { + if !e.IsDir() && !strings.HasSuffix(e.Name(), ".sample") { + out = append(out, "hooks/"+e.Name()) + } + } + return out +} + +// runsProgram reports whether the config key, as git lists it (its +// section and name in lowercase), with value v, makes git run a program, +// or read another config: what git on this machine could run of a repo +// the VM made. +func runsProgram(key, v string) bool { + section, name, _ := strings.Cut(key, ".") + sub, last := "", name + if i := strings.LastIndex(name, "."); i >= 0 { + sub, last = name[:i], name[i+1:] + } + switch { + case section == "alias": + return strings.HasPrefix(strings.TrimSpace(v), "!") + case section == "include" || section == "includeif": + return last == "path" + case section == "filter": + return slices.Contains([]string{"clean", "smudge", "process"}, last) + case section == "diff" && sub != "": + return last == "textconv" || last == "command" + case section == "merge" && sub != "": + return last == "driver" + case section == "gpg": + return last == "program" + } + return slices.Contains([]string{ + "core.fsmonitor", "core.hookspath", "core.sshcommand", "core.pager", "core.editor", "core.askpass", + "sequence.editor", "diff.external", "credential.helper", "uploadpack.packobjectshook", + }, key) || section == "credential" && last == "helper" +} + +// repoGitDir returns the git dir of the repo whose top folder is dir, +// resolved: its .git folder, the git dir its .git file names (gitdirOf), +// or where its .git symlink leads; "" when there's none. +func repoGitDir(dir string) string { + g := filepath.Join(dir, ".git") + fi, err := os.Lstat(g) + switch { + case err != nil: + return "" + case fi.IsDir(): + return g + case fi.Mode().IsRegular(): + return gitdirOf(g, dir) + } + r, err := filepath.EvalSymlinks(g) + if err != nil || !isDir(r) { + return "" + } + return r +} diff --git a/internal/gitprotect/nested_test.go b/internal/gitprotect/nested_test.go new file mode 100644 index 00000000..bb90e37e --- /dev/null +++ b/internal/gitprotect/nested_test.go @@ -0,0 +1,682 @@ +package gitprotect + +import ( + "encoding/json" + "maps" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/devvmhq/devvm/internal/hostsafety" + "github.com/devvmhq/devvm/internal/msg" + "github.com/devvmhq/devvm/internal/paths" + "github.com/devvmhq/devvm/internal/platform" + "github.com/devvmhq/devvm/internal/state" +) + +// walked gives the fixture's protector what the walk finds now, as a +// stopped VM's launch does. +func (f *fixture) walked() { + found := hostsafety.Walk(f.dir, false) + f.p.Nested = &found.Repos +} + +// repo makes a git repo at rel in the project folder. +func (f *fixture) repo(rel string) { + f.t.Helper() + mkdirs(f.t, f.path(rel)) + f.git(f.path(rel), "init", "-q") +} + +// recordedRepos are the nested repos the VM's state records protecting. +func (f *fixture) recordedRepos() []string { + return slices.Sorted(maps.Keys(f.section().Made.Repos)) +} + +// Each repo nested in a new VM's folder is protected as its own repo is: +// locked, recorded, and checked again at each check, which names one that +// appeared since, and one that's gone. Submodules under .git/modules and +// the repo's own linked worktrees are its own repo's to protect; a +// submodule in the working tree is scanned as a repo of its own too, as +// the index that names it is the VM's to write. +func TestNestedProtected(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + embeddedRepo(f) + f.git(f.dir, "worktree", "add", "-q", f.path("wt")) + f.repo("ws/a") + f.walked() + if !slices.Equal(f.p.Nested.Dirs, []string{"rel", "sub", "ws/a", "wt"}) { + t.Fatalf("walk: %q", f.p.Nested.Dirs) + } + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + if f.warned("git_nested") || !f.locked(f.path("ws/a/.git/config")) || !f.locked(f.path("ws/a/.git/hooks")) { + t.Errorf("new VM: %q, locks %q", f.warns.Names(), f.flags) + } + if got := f.recordedRepos(); !slices.Equal(got, []string{"rel", "sub", "ws/a"}) || !f.section().Made.Nested { + t.Errorf("recorded %q", got) + } + f.walked() + f.checked(false) + if len(f.warns.Names()) > 0 || !f.locked(f.path("ws/a/.git/config")) { + t.Errorf("again: %q, locks %q", f.warns.Names(), f.flags) + } + // One the VM made while it ran. + f.repo("ws/b") + f.walked() + f.checked(false) + if !slices.Equal(f.warns.Names(), []string{"git_nested_appeared repo=ws/b vm=" + f.vm.Name()}) || !f.locked(f.path("ws/b/.git/config")) { + t.Errorf("appeared: %q, locks %q", f.warns.Names(), f.flags) + } + // A running VM's check walks nothing: what's recorded is checked, and + // nothing locked. + f.p.Nested = nil + f.checked(true) + if len(f.warns.Names()) > 0 || len(f.flags) > 0 || !slices.Equal(f.recordedRepos(), []string{"rel", "sub", "ws/a", "ws/b"}) { + t.Errorf("running: %q, locks %q, %q", f.warns.Names(), f.flags, f.recordedRepos()) + } + // One replaced, and one gone. + if err := os.Rename(f.path("ws/a/.git"), f.path("ws/a/.git-old")); err != nil { + t.Fatal(err) + } + f.git(f.path("ws/a"), "init", "-q") + if err := os.RemoveAll(f.path("ws/b")); err != nil { + t.Fatal(err) + } + f.walked() + f.checked(false) + // The old .git, a git dir that isn't a .git now, is named too: git + // run below it would take it for its repo. + want := []string{ + "git_replaced git=" + f.path("ws/a/.git"), "git_nested_gone repo=ws/b vm=" + f.vm.Name(), + "git_nested_bare dirs=ws/a/.git-old vm=" + f.vm.Name(), + } + if !slices.Equal(f.warns.Names(), want) || !slices.Equal(f.recordedRepos(), []string{"rel", "sub", "ws/a"}) { + t.Errorf("replaced and gone: %q, %q", f.warns.Names(), f.recordedRepos()) + } +} + +// A folder of repos without one of its own: each is protected; devvm +// git-protect off unlocks them, and on locks them again; strict keeps +// host git out of their submodules too. +func TestNestedNoTopRepo(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.repo("a") + f.repo("b") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + if len(f.warns.Names()) > 0 || !f.locked(f.path("a/.git/config")) || !f.locked(f.path("b/.git/config")) { + t.Errorf("new VM: %q, locks %q", f.warns.Names(), f.flags) + } + f.p.Nested = nil + f.set(Off) + if !slices.Contains(f.flags, "nouchg "+f.path("b/.git/config")) { + t.Errorf("off: %q", f.flags) + } + f.walked() + f.set(Strict) + if !f.locked(f.path("a/.git/config")) { + t.Errorf("strict: %q", f.flags) + } + for _, r := range []string{"a", "b"} { + out := f.git(f.path(r), "config", "--file", ".git/config", "diff.ignoreSubmodules") + if out != "all" { + t.Errorf("%s: diff.ignoreSubmodules %q", r, out) + } + } + // Past the walk's bound, what isn't protected is counted. + f.p.Nested.More, f.p.Nested.Past = 3, []string{"x", "y", "z"} + f.set(On) + if !slices.Equal(f.warns.Names(), []string{"git_nested_past_bound count=3 repos=x, y, z vm=" + f.vm.Name()}) { + t.Errorf("past the bound: %q", f.warns.Names()) + } +} + +// A VM an older devvm made protects its own repo alone: the first check +// that finds nested repos says once that devvm git-protect on protects +// them, and later ones name a repo that appeared since; on protects them +// all. +func TestNestedExistingVM(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + f.git(f.dir, "init", "-q") + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + if err := record(t.Context(), f.vm, func(g *InVM) { g.Made.Nested = false }); err != nil { + t.Fatal(err) + } + f.repo("a") + f.walked() + f.checked(false) + if !slices.Equal(f.warns.Names(), []string{"git_nested_protectable repos=a vm=" + f.vm.Name()}) || f.locked(f.path("a/.git/config")) { + t.Errorf("first check: %q, locks %q", f.warns.Names(), f.flags) + } + f.checked(false) + if len(f.warns.Names()) > 0 { + t.Errorf("again: %q", f.warns.Names()) + } + f.repo("c") + f.walked() + f.checked(false) + if !slices.Equal(f.warns.Names(), []string{"git_nested_unprotected repos=c vm=" + f.vm.Name()}) { + t.Errorf("one more: %q", f.warns.Names()) + } + f.set(On) + if len(f.warns.Names()) > 0 || !f.locked(f.path("a/.git/config")) || !f.locked(f.path("c/.git/config")) { + t.Errorf("on: %q, locks %q", f.warns.Names(), f.flags) + } + if g := f.section(); !g.Made.Nested || len(g.Nested) > 0 { + t.Errorf("on: %+v", g) + } +} + +// Unlock leaves what another VM's protection keeps locked too, and names +// that VM; the rest it unlocks. +func TestNestedUnlockKept(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.repo("a") + f.repo("b") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + f.p.Kept = func(vm string) func(string) msg.M { + if vm != f.vm.Name() { + t.Errorf("kept asked for %s", vm) + } + return func(path string) msg.M { + if strings.HasPrefix(path, f.path("a")+"/") { + return msg.GitKeptLocked("devvm-a-0123456789abcd") + } + return msg.M{} + } + } + f.flags = nil + f.warns.Reset() + f.p.Unlock(t.Context(), f.vm) + if slices.ContainsFunc(f.flags, func(s string) bool { return strings.Contains(s, "/ws/a/") }) || + !slices.Contains(f.flags, "nouchg "+f.path("b/.git/config")) { + t.Errorf("unlocked %q", f.flags) + } + if !slices.Equal(f.warns.Names(), []string{"git_kept_locked vm=devvm-a-0123456789abcd"}) { + t.Errorf("warned %q", f.warns.Names()) + } +} + +// The VM can't hide a nested repo behind a gitlink it adds to the +// folder's own index, whose .git file names the nested repo's git dir: +// the nested repo is still scanned, recorded and locked on its own. +func TestNestedGitlinkCantHide(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + f.git(f.dir, "init", "-q") + f.repo("b") + f.git(f.path("b"), "commit", "-q", "--allow-empty", "-m", "b") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + mkdirs(t, f.path("z")) + write(t, f.path("z/.git"), "gitdir: ../b/.git\n") + f.git(f.dir, "update-index", "--add", "--cacheinfo", "160000,"+f.git(f.path("b"), "rev-parse", "HEAD")+",z") + f.walked() + f.checked(false) + if !slices.Contains(f.recordedRepos(), "b") || !f.locked(f.path("b/.git/config")) || f.warned("git_nested_gone") { + t.Errorf("hidden: %q, %q, locks %q", f.recordedRepos(), f.warns.Names(), f.flags) + } +} + +// evilGitDir makes dir a git dir whose config runs ./evil as git's +// fsmonitor: what a VM plants. +func (f *fixture) evilGitDir(dir string) { + f.t.Helper() + mkdirs(f.t, filepath.Join(dir, "objects"), filepath.Join(dir, "refs")) + write(f.t, filepath.Join(dir, "HEAD"), "ref: refs/heads/main\n") + write(f.t, filepath.Join(dir, "config"), "[core]\n\tfsmonitor = ./evil\n") +} + +// A repo the VM makes whose .git file leads to a git dir it made below +// the folder's own .git, or to one under .git/modules that reads its +// config from elsewhere (commondir), isn't left to the folder's own +// repo, whose locks don't cover it: it's named as one that appeared, +// with its fsmonitor, and as one devvm doesn't protect. +func TestNestedIntoTopGit(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + f.git(f.dir, "init", "-q") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + f.evilGitDir(f.path(".git/evil")) + mkdirs(t, f.path("src"), f.path(".git/modules/x"), f.path("lib")) + write(t, f.path("src/.git"), "gitdir: ../.git/evil\n") + write(t, f.path(".git/modules/x/HEAD"), "ref: refs/heads/main\n") + write(t, f.path(".git/modules/x/commondir"), "../../evil\n") + write(t, f.path("lib/.git"), "gitdir: ../.git/modules/x\n") + f.walked() + f.checked(false) + for _, w := range []string{ + "git_nested_appeared_runs repo=lib runs=core.fsmonitor vm=" + f.vm.Name(), + "git_nested_appeared_runs repo=src runs=core.fsmonitor vm=" + f.vm.Name(), + "git_nested_unprotected repos=lib, src vm=" + f.vm.Name(), + } { + if !f.warned(w) { + t.Errorf("not warned %s: %q", w, f.warns.Names()) + } + } + if got := f.recordedRepos(); !slices.Equal(got, []string{"lib", "src"}) { + t.Errorf("recorded %q", got) + } +} + +// A linked worktree under the folder's own .git that's a symlink to a +// folder the VM made, whose commondir leads back, covers nothing: no lock +// reaches its commondir, which the VM can point elsewhere later, so a +// repo whose .git file names it is named. +func TestNestedSymlinkedWorktree(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + f.git(f.dir, "init", "-q") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + mkdirs(t, f.path("x"), f.path(".git/worktrees"), f.path("src")) + write(t, f.path("x/HEAD"), "ref: refs/heads/main\n") + write(t, f.path("x/commondir"), f.path(".git")+"\n") + symlink(t, f.path("x"), f.path(".git/worktrees/evil")) + write(t, f.path("src/.git"), "gitdir: ../.git/worktrees/evil\n") + f.walked() + f.checked(false) + for _, w := range []string{"git_nested_appeared repo=src", "git_nested_unprotected repos=src"} { + if !f.warned(w) { + t.Errorf("not warned %s: %q", w, f.warns.Names()) + } + } +} + +// The VM can't make a protected nested repo gone while git still takes +// its .git: with its objects and refs renamed and a commondir to a git +// dir it made, a .GIT where names fold case, or a .git it can't read, +// the repo stays recorded and checked. +func TestNestedNotGone(t *testing.T) { + needGit(t) + for _, tc := range []struct { + name string + do func(f *fixture) + }{ + {"commondir", func(f *fixture) { + f.evilGitDir(f.path("evil")) + for _, d := range []string{"objects", "refs"} { + if err := os.Rename(f.path("a/.git/"+d), f.path("a/.git/"+d+"-old")); err != nil { + f.t.Fatal(err) + } + } + write(f.t, f.path("a/.git/commondir"), "../../evil\n") + }}, + {".GIT", func(f *fixture) { + if !platform.FoldsCase { + f.t.Skip("names don't fold case here") + } + if err := os.Rename(f.path("a/.git"), f.path("a/.GIT")); err != nil { + f.t.Fatal(err) + } + }}, + {"unreadable", func(f *fixture) { + if err := os.Chmod(f.path("a/.git"), 0); err != nil { + f.t.Fatal(err) + } + f.t.Cleanup(func() { _ = os.Chmod(f.path("a/.git"), 0o700) }) //nolint:gosec // the test's own folder, put back + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t, "ws") + f.repo("a") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + tc.do(f) + f.walked() + f.checked(false) + if f.warned("git_nested_gone") || !slices.Equal(f.recordedRepos(), []string{"a"}) { + t.Errorf("gone: %q, %q", f.warns.Names(), f.recordedRepos()) + } + }) + } +} + +// A check's scans share one budget of submodule git dirs: past it, a +// scan follows no more, and its repo is named. +func TestScanBudget(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + embeddedRepo(f) + b := newBudget() + b.left.Store(0) + tr := f.p.tree + tr.budget = b + if s := tr.scan(t.Context()); !s.emb.bounded || len(s.emb.inside) > 0 { + t.Errorf("past the budget: %+v", s.emb) + } + s := f.p.scan(t.Context()) + if s.emb.bounded { + t.Error("bounded without a budget") + } + f.p.protectRepo(t.Context(), &run{why: whyCheck, how: later, top: true, s: snapshot{tree: tr, git: s.git, exists: true, emb: embeds{bounded: true}}}) + if !f.warned("git_scan_bounded git=" + f.path(".git")) { + t.Errorf("warned %q", f.warns.Names()) + } +} + +// What a repo the VM made runs on this machine: config keys that name a +// program or another config, aliases that run a shell, and hooks. +func TestRunsProgram(t *testing.T) { + for kv, want := range map[[2]string]bool{ + {"core.fsmonitor", "x"}: true, {"core.hookspath", "x"}: true, {"core.sshcommand", "x"}: true, + {"core.pager", "x"}: true, {"filter.lfs.clean", "x"}: true, {"filter.lfs.required", "true"}: false, + {"alias.st", "status"}: false, {"alias.x", "!sh -c evil"}: true, {"include.path", "x"}: true, + {"includeif.gitdir:/x.path", "y"}: true, {"diff.foo.textconv", "x"}: true, {"merge.foo.driver", "x"}: true, + {"credential.https://h.helper", "x"}: true, {"user.name", "x"}: false, {"core.bare", "false"}: false, + } { + if got := runsProgram(kv[0], kv[1]); got != want { + t.Errorf("%s=%s: %v", kv[0], kv[1], got) + } + } +} + +// A nested repo devvm stopped protecting, as it's gone, is still unlocked +// by devvm rm and devvm git-protect off; one that isn't in the folder any +// more is named, as its locks stay wherever it went. +func TestNestedLeftUnlocked(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.repo("a") + f.repo("b") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + if err := os.Rename(f.path("b"), f.path("b-moved")); err != nil { + t.Fatal(err) + } + if err := os.Rename(f.path("b-moved/.git"), f.path("b-moved/git-kept")); err != nil { + t.Fatal(err) + } + f.walked() + f.checked(false) + if g := f.section(); len(g.Made.Left) != 1 || g.Made.Left["b"].GitID == "" { + t.Fatalf("left %+v", g.Made.Left) + } + f.flags = nil + f.warns.Reset() + f.p.Unlock(t.Context(), f.vm) + if !slices.Contains(f.flags, "nouchg "+f.path("a/.git/config")) || !f.warned("git_locks_left repos=b") { + t.Errorf("unlock: %q, %q", f.flags, f.warns.Names()) + } +} + +// Gitlinks that lead back to a git dir already followed, through a +// symlinked folder, are followed once. +func TestEmbeddedOnce(t *testing.T) { + needGit(t) + f := newFixture(t, "p") + embeddedRepo(f) + symlink(t, ".", f.path("loop")) + mkdirs(t, f.path("again")) + write(t, f.path("again/.git"), "gitdir: ../sub/.git\n") + head := f.git(f.dir, "rev-parse", "HEAD") + for _, l := range []string{"loop", "again"} { + f.git(f.dir, "update-index", "--add", "--cacheinfo", "160000,"+head+","+l) + } + if e := f.p.embedded(t.Context()); len(e.inside) != 2 { + t.Errorf("inside %q", e.inside) + } +} + +// devvm git-protect strict and off leave a config another VM keeps +// locked as it is, and name that VM. +func TestStrictKept(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.repo("a") + f.repo("b") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + f.p.Kept = func(string) func(string) msg.M { + return func(path string) msg.M { + if strings.HasPrefix(path, f.path("b")+"/") { + return msg.GitKeptLocked("devvm-b-0123456789abcd") + } + return msg.M{} + } + } + f.set(Strict) + if slices.Contains(f.flags, "nouchg "+f.path("b/.git/config")) || !slices.Contains(f.flags, "nouchg "+f.path("a/.git/config")) { + t.Errorf("strict: %q", f.flags) + } + if !f.warned("git_kept_locked vm=devvm-b-0123456789abcd") { + t.Errorf("strict: %q", f.warns.Names()) + } + if out := f.git(f.path("a"), "config", "--file", ".git/config", "diff.ignoreSubmodules"); out != "all" { + t.Errorf("a: %q", out) + } +} + +// A VM's protection keeps the git dirs it locked: its own repo's, its +// submodules', and its nested repos', while it's on or strict. +func TestKeeps(t *testing.T) { + f := newFixture(t, "ws") + g := InVM{Mode: On, Made: Made{ + Protected: true, Repo: Repo{GitDirs: []string{"sub/.git"}}, Nested: true, + Repos: map[string]Repo{"a": {GitDirs: []string{"a/m/.git"}}}, + }} + if err := f.vm.Update(t.Context(), func(st *state.VM) error { return Set(st, g) }); err != nil { + t.Fatal(err) + } + for path, want := range map[string]bool{ + f.path(".git/config"): true, f.path("sub/.git/hooks"): true, f.path("a/.git/config"): true, + f.path("a/m/.git/config"): true, f.path("a/src"): false, f.path("b/.git/config"): false, + } { + if got := Keeps(f.vm, path); got != want { + t.Errorf("%s: %v", path, got) + } + } + g.Mode = Off + if err := f.vm.Update(t.Context(), func(st *state.VM) error { return Set(st, g) }); err != nil { + t.Fatal(err) + } + if Keeps(f.vm, f.path(".git/config")) { + t.Error("off keeps") + } +} + +// Nested repos are recorded under repos, by their folder; the folder's +// own repo's fields stay where 0.1.0 had them. +func TestMadeJSON(t *testing.T) { + m := Made{Protected: true, Repo: Repo{GitID: "1:2", GitDirs: []string{"s"}}, Nested: true, Repos: map[string]Repo{"a": {GitID: "3:4"}}} + b, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + const want = `{"protected":true,"git_id":"1:2","git_dirs":["s"],"nested":true,"repos":{"a":{"git_id":"3:4"}}}` + if string(b) != want { + t.Errorf("%s", b) + } + var back Made + if err := json.Unmarshal([]byte(`{"protected":true,"git_id":"1:2","delegations":"d"}`), &back); err != nil || + back.GitID != "1:2" || back.Delegations != "d" || back.Nested || back.Repos != nil { + t.Errorf("0.1.0's: %+v, %v", back, err) + } +} + +// On a host without locks, nested repos are watched from the first check, +// an existing VM's included, which records them without naming them; the +// launches warn that the VM can change .git, even without a repo of the +// folder's own. +func TestNestedWatch(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.canLock(false) + f.repo("a") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + if len(f.warns.Names()) > 0 || f.section().Watched.Sums["a/.git/config"] == "" { + t.Errorf("new VM: %q, %v", f.warns.Names(), f.section().Watched.Sums) + } + f.p.WarnUnprotected(f.vm) + if !slices.Equal(f.warns.Names(), []string{"git_unprotected vm=" + f.vm.Name()}) { + t.Errorf("launch: %q", f.warns.Names()) + } + f.git(f.path("a"), "config", "core.fsmonitor", "./evil") + f.repo("b") + f.walked() + if w := f.check(); !slices.Equal(w, []string{"git_nested_appeared repo=b vm=" + f.vm.Name(), "git_changed paths=a/.git/config vm=" + f.vm.Name()}) { + t.Errorf("changed: %q", w) + } + // One an older devvm watched records its nested repos without naming. + if err := record(t.Context(), f.vm, func(g *InVM) { g.Made.Nested, g.Made.Repos = false, nil }); err != nil { + t.Fatal(err) + } + f.walked() + if w := f.check(); len(w) > 0 || !slices.Equal(f.recordedRepos(), []string{"a", "b"}) { + t.Errorf("older: %q, %q", w, f.recordedRepos()) + } +} + +// The start pins each nested repo the VM protects, as its own; a running +// VM missing one's pins is named. +func TestNestedPins(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.p.Locker = Binds{} + f.repo("a") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + fixed, readOnly, err := f.p.Pins(t.Context(), f.vm) + if err != nil || !slices.Equal(fixed, []string{"a/.git"}) || !slices.Contains(readOnly, "a/.git/config") { + t.Errorf("pins %q %q %v", fixed, readOnly, err) + } + missing := f.p.PinsMissing(t.Context(), f.vm, []string{}, []string{}) + if !slices.Contains(missing, f.path("a/.git")) || !slices.Contains(missing, f.path("a/.git/config")) { + t.Errorf("missing %q", missing) + } +} + +// A nested repo whose .git file names a git dir in the folder that no +// repo's protection covers is named; one whose git dir another nested +// repo's covers is left to it. +func TestNestedGitdirInside(t *testing.T) { + needGit(t) + f := newFixture(t, "ws") + f.repo("a") + mkdirs(t, f.path("b"), f.path("c"), f.path("store")) + f.git(f.path("b"), "init", "-q", "--separate-git-dir="+f.path("store/b.git")) + write(t, f.path("c/.git"), "gitdir: "+f.path("a/.git")+"\n") + f.walked() + if err := f.newVM(false); err != nil { + t.Fatal(err) + } + if !slices.Equal(f.warns.Names(), []string{"git_nested_unprotected repos=b vm=" + f.vm.Name()}) { + t.Errorf("warned %q", f.warns.Names()) + } + if got := f.recordedRepos(); !slices.Equal(got, []string{"a", "b"}) || !f.locked(f.path("b/.git")) { + t.Errorf("recorded %q, locks %q", got, f.flags) + } +} + +// BenchmarkNestedCheck is a check of a stopped VM whose folder holds 50 +// repos, each with a commit, its walk included, with this host's own +// locker (chflags on macOS): go test ./internal/gitprotect -run '^$' +// -bench NestedCheck -benchtime 5x. +func BenchmarkNestedCheck(b *testing.B) { + if _, err := exec.LookPath("git"); err != nil { + b.Skip("no git") + } + root, err := filepath.EvalSymlinks(b.TempDir()) + if err != nil { + b.Fatal(err) + } + dir := filepath.Join(root, "ws") + b.Cleanup(func() { _ = exec.Command("chflags", "-R", "nouchg", root).Run() }) //nolint:noctx,gosec // cleanup, of the benchmark's own folder + for i := range 50 { + r := filepath.Join(dir, "repo"+strconv.Itoa(i)) + for _, args := range [][]string{{"init", "-q", r}, {"-C", r, "-c", "user.email=a@b", "-c", "user.name=a", "commit", "-q", "--allow-empty", "-m", "x"}} { + if out, err := exec.CommandContext(b.Context(), "git", args...).CombinedOutput(); err != nil { //nolint:gosec // the benchmark's own + b.Fatalf("git %v: %v\n%s", args, err, out) + } + } + } + p := New(dir, root, HostLocker(false), &msg.Fake{}) + vm, err := state.New(paths.Dirs{Data: filepath.Join(root, "data")}, "devvm-ws-0123456789abcd") + if err != nil { + b.Fatal(err) + } + vm.Image, vm.Dir, vm.Backend = "base", dir, "fake" + if err := vm.Create(b.Context(), nil); err != nil { + b.Fatal(err) + } + if err := record(b.Context(), vm, func(g *InVM) { g.Mode = p.NewSection(false).Mode }); err != nil { + b.Fatal(err) + } + found := hostsafety.Walk(dir, false) + p.Nested = &found.Repos + if err := p.NewVM(b.Context(), vm); err != nil { + b.Fatal(err) + } + b.ResetTimer() + for b.Loop() { + found := hostsafety.Walk(dir, false) + p.Nested = &found.Repos + if err := p.Check(b.Context(), vm, false); err != nil { + b.Fatal(err) + } + } +} + +// A path is in the deepest repo whose folder it's below, so a repo the +// watch skips, as it's new or gone, never hides one nested in it. +func TestRepoOf(t *testing.T) { + roots := []string{"b", "b/c", "d"} + for path, want := range map[string]string{ + "b/.git/config": "b", "b/c/.git/config": "b/c", ".git/config": "", "bc/.git/config": "", "d/x": "d", + } { + if got := repoOf(path, roots); got != want { + t.Errorf("%s: %q, want %q", path, got, want) + } + } +} + +// A repo's git dir: its .git folder, what its .git file names, where its +// .git symlink leads, or none. +func TestRepoGitDir(t *testing.T) { + f := newFixture(t, "p") + mkdirs(t, f.path("a/.git"), f.path("b"), f.path("c"), f.path("store/x"), f.path("none")) + write(t, f.path("b/.git"), "gitdir: ../store/x\n") + symlink(t, f.path("store/x"), f.path("c/.git")) + for dir, want := range map[string]string{ + "a": f.path("a/.git"), "b": f.path("store/x"), "c": f.path("store/x"), "none": "", + } { + if got := repoGitDir(f.path(dir)); got != want { + t.Errorf("%s: %q, want %q", dir, got, want) + } + } +} diff --git a/internal/gitprotect/pins.go b/internal/gitprotect/pins.go index a03f62ef..bc183ecc 100644 --- a/internal/gitprotect/pins.go +++ b/internal/gitprotect/pins.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "io/fs" + "maps" "os" "path/filepath" "slices" @@ -26,8 +27,9 @@ import ( // (backend.PinEvent) and ReportPinEvents names, as the watch names what // changed. A running VM's pins are checked as it runs (PinsMissing). -// Pins are what the start of the VM vm pins for its locks (Binds), none -// unless its mode is on or strict, each relative to the project folder and +// Pins are what the start of the VM vm pins for its locks (Binds), in the +// folder's own repo and each nested repo its state records protecting, +// none unless its mode is on or strict, each relative to the project folder and // a real path in it (realInDir), as lock takes them: .git, when it's a // folder, and the git dirs a lock covers besides (fixed), which the guest // can write in but not rename or remove, and each path a lock covers that @@ -36,27 +38,58 @@ import ( // a hook in a hooks folder to pin, with another name is refused // (git_pin_linked): its other name would stay the guest's to change. func (p *Protector) Pins(ctx context.Context, vm *state.VM) (fixed, readOnly []string, err error) { - if m := Mode(vm); m != On && m != Strict { + g, _ := Of(vm) + if g.Mode != On && g.Mode != Strict { return nil, nil, nil } - s := p.scan(ctx) - for _, d := range append([]string{s.git}, s.dirs...) { - if isDir(d) && p.realInDir(d) { - fixed = append(fixed, relTo(p.Dir, d)) + return p.pinsOf(vm.Name(), scanAll(ctx, p.recorded(g.Made))) +} + +// pinsOf is what to pin of the repos snaps scanned, as Pins has it, for +// the VM vm. +func (t tree) pinsOf(vm string, snaps []snapshot) (fixed, readOnly []string, err error) { + for _, s := range snaps { + for _, d := range append([]string{s.git}, s.dirs...) { + if isDir(d) && t.realInDir(d) { + fixed = append(fixed, relTo(t.Dir, d)) + } } - } - for _, path := range s.paths { - if _, err := os.Lstat(path); err != nil || !p.realInDir(path) { - continue + for _, path := range s.paths { + if _, err := os.Lstat(path); err != nil || !t.realInDir(path) { + continue + } + if l, ok := linkedFile(path); ok { + return nil, nil, msg.GitPinLinked(l, vm) + } + readOnly = append(readOnly, relTo(t.Dir, path)) } - if l, ok := linkedFile(path); ok { - return nil, nil, msg.GitPinLinked(l, vm.Name()) - } - readOnly = append(readOnly, relTo(p.Dir, path)) } return fixed, readOnly, nil } +// recordedPins is what a running VM's start pinned of the nested repos +// made records, as far as their records tell without scanning them: each +// git dir, fixed, and its hooks and config, read-only. +func (t tree) recordedPins(made Made) (fixed, readOnly []string) { + for _, rel := range slices.Sorted(maps.Keys(made.Repos)) { + if !filepath.IsLocal(rel) { + continue + } + for _, d := range append([]string{t.repoAt(rel).git()}, t.abs(made.Repos[rel].GitDirs)...) { + if !isDir(d) || !t.realInDir(d) { + continue + } + fixed = append(fixed, relTo(t.Dir, d)) + for _, f := range []string{"hooks", "config"} { + if _, err := os.Lstat(filepath.Join(d, f)); err == nil { + readOnly = append(readOnly, relTo(t.Dir, filepath.Join(d, f))) + } + } + } + } + return fixed, readOnly +} + // linkedFile is path, or the file in it, a folder, that has another name // (platform.Links), and whether there's one. func linkedFile(path string) (string, bool) { @@ -158,12 +191,23 @@ func (p *Protector) PinsMissing(ctx context.Context, vm *state.VM, readOnly, mou if readOnly == nil || mounted == nil { return nil } - fixed, want, err := p.Pins(ctx, vm) + g, _ := Of(vm) + if g.Mode != On && g.Mode != Strict { + return nil + } + // The folder's own repo scanned, the nested ones as recorded: a + // launch into a running VM scans no nested repo. + fixed, want, err := p.pinsOf(vm.Name(), scanAll(ctx, []tree{p.tree})) if err != nil { return nil } - g, _ := Of(vm) + nf, nr := p.recordedPins(g.Made) + fixed, want = append(fixed, nf...), append(want, nr...) known := append([]string{".git"}, g.Made.GitDirs...) + for rel, r := range g.Made.Repos { + known = append(known, filepath.Join(rel, ".git")) + known = append(known, r.GitDirs...) + } mine := func(rel string) bool { return slices.ContainsFunc(known, func(d string) bool { return rel == d || strings.HasPrefix(rel, d+"/") }) } diff --git a/internal/gitprotect/report.go b/internal/gitprotect/report.go index 0c18150d..c7bc2ad5 100644 --- a/internal/gitprotect/report.go +++ b/internal/gitprotect/report.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "maps" "slices" "strconv" @@ -28,15 +29,18 @@ const ( watching // a host without locks: report, record .git's identity, lock nothing ) -// run is one protect: what it runs for, how it treats the locks, what -// the last one recorded, what the scan found, and the sum of its -// delegations. +// run is one repo's protect: what it runs for, how it treats the locks, +// what the last one recorded of the repo, whether it had protected it +// (Made.Protected, or a nested repo's record), whether it's the folder's +// own repo, what the scan found, and the sum of its delegations. type run struct { - why why - how how - was Made - s snapshot - sum string + why why + how how + was Repo + protected bool + top bool + s snapshot + sum string } // report is something protect tells: when says whether a run tells it, @@ -53,6 +57,10 @@ type report struct { // locked, so the hooks in folders a lock would cover aren't news: the // watch names their changes. var reports = []report{ + { // submodules past what one check follows, on every run + when: func(r *run) bool { return r.s.emb.bounded }, + report: func(p *Protector, r *run) { p.Warn(msg.GitScanBounded(r.s.git)) }, + }, { // commondir points git elsewhere for config and hooks, on every run when: func(r *run) bool { return r.s.commondir }, report: func(p *Protector, r *run) { p.Warn(msg.GitCommondir(r.s.git, r.s.target)) }, @@ -65,12 +73,13 @@ var reports = []report{ } }, }, - { // a repo made since the VM was - when: func(r *run) bool { return r.why == whyCheck && r.was.GitID == "" }, + { // the folder's own repo, made since the VM was (a nested one's + // is git_nested_appeared, from protect) + when: func(r *run) bool { return r.top && r.why == whyCheck && r.was.GitID == "" }, report: func(p *Protector, _ *run) { p.Warn(msg.GitAppeared()) }, }, { // git dirs that appeared since the last time, once there was one - when: func(r *run) bool { return r.why != whyNew && r.was.Protected }, + when: func(r *run) bool { return r.why != whyNew && r.protected }, report: func(p *Protector, r *run) { seen := p.abs(r.was.GitDirs) for _, d := range r.s.dirs { @@ -100,14 +109,82 @@ var reports = []report{ }, } -// protect locks .git, as h says, and reports what a lock can't stop -// (reports); it returns what it found (g's Made, as it is now), for the -// caller to record with the mode it set. Before anything else, a check -// whose .git replaced the one it locked reports that alone. -func (p *Protector) protect(ctx context.Context, s snapshot, rec InVM, w why, h how) Made { +// protect locks each repo the scans in snaps found, as h says, and +// reports what a lock can't stop (protectRepo); it returns what it found +// (rec's Made, as it is now), for the caller to record with the mode it +// set. A nested repo without a record is scanned for the first time, as a +// new VM's (whyNew); at a check of a VM that protected its nested repos, +// it's one that appeared since (git_nested_appeared). A recorded one the +// walk found gone is named (git_nested_gone), and its record moves to +// Made.Left, as does that of one whose git dir another repo's protection +// now covers, so the locks it may have left are taken off with the rest. +// A running VM's check scans the folder's own repo alone, and keeps the +// nested repos' records as they are. +func (p *Protector) protect(ctx context.Context, vm string, snaps []snapshot, rec InVM, w why, h how, c repoSet) Made { was := rec.Made + made := Made{Protected: true, Nested: was.Nested || w != whyCheck, Left: maps.Clone(was.Left)} + if h == later { + made.Repos = maps.Clone(was.Repos) + } + for _, s := range snaps { + if s.tree.Root == p.Dir { + made.Repo = p.protectRepo(ctx, &run{why: w, how: h, was: was.Repo, protected: was.Protected, top: true, s: s}) + continue + } + rel := relTo(p.Dir, s.tree.Root) + r, ok := was.Repos[rel] + wi := w + if !ok { + wi = whyNew + if w == whyCheck && was.Nested && s.exists { + p.warnAppeared(ctx, s, rel, vm) + } + } + if made.Repos == nil { + made.Repos = map[string]Repo{} + } + made.Repos[rel] = p.protectRepo(ctx, &run{why: wi, how: h, was: r, protected: ok, s: s}) + delete(made.Left, rel) + } + for _, rel := range c.gone { + p.Warn(msg.GitNestedGone(rel, vm)) + } + if h != later { + for rel, r := range was.Repos { + if _, ok := made.Repos[rel]; !ok { + if made.Left == nil { + made.Left = map[string]Repo{} + } + made.Left[rel] = r + } + } + } + return made +} + +// warnAppeared names a nested repo that appeared since the last check, +// scanned as s, at rel, with what in its config and hooks runs programs +// on this machine (programs), which devvm locks as it is. +func (p *Protector) warnAppeared(ctx context.Context, s snapshot, rel, vm string) { + if runs := programs(ctx, s); len(runs) > 0 { + l, _ := listed(runs) + p.Warn(msg.GitNestedAppearedRuns(rel, l, vm)) + return + } + p.Warn(msg.GitNestedAppeared(rel, vm)) +} + +// protectRepo locks one repo's .git, as r.how says, and reports what a +// lock can't stop (reports); it returns what it found of the repo. Before +// anything else, a check whose .git replaced the one it locked reports +// that alone. +func (p *Protector) protectRepo(ctx context.Context, r *run) Repo { + was, s, w, h := r.was, r.s, r.why, r.how if !s.exists { - return Made{Protected: true, GitDirs: was.GitDirs, Delegations: was.Delegations} + if !r.top { + return was + } + return Repo{GitDirs: was.GitDirs, Delegations: was.Delegations} } if w == whyCheck && was.GitID != "" && was.GitID != s.id { p.Warn(msg.GitReplaced(s.git)) @@ -117,13 +194,13 @@ func (p *Protector) protect(ctx context.Context, s snapshot, rec InVM, w why, h } return was } - r := &run{why: w, how: h, was: was, s: s, sum: delegationsSum(s.ds)} + r.sum = delegationsSum(s.ds) for _, rep := range reports { if rep.when(r) { rep.report(p, r) } } - made := Made{Protected: true, GitID: was.GitID, GitDirs: p.rel(s.dirs), Delegations: r.sum} + made := Repo{GitID: was.GitID, GitDirs: p.rel(s.dirs), Delegations: r.sum} switch h { case lockNow: p.lock(ctx, s) diff --git a/internal/gitprotect/report_test.go b/internal/gitprotect/report_test.go index 9b79f17f..0b52a130 100644 --- a/internal/gitprotect/report_test.go +++ b/internal/gitprotect/report_test.go @@ -40,7 +40,8 @@ func reportsFixture(t *testing.T) (*fixture, snapshot) { mkdirs(t, f.path(".git/hooks")) write(t, f.path(".git/hooks/pre-commit"), "#!/bin/sh\n") s := snapshot{ - git: f.path(".git"), exists: true, id: folderID(f.path(".git")), + tree: f.p.tree, + git: f.path(".git"), exists: true, id: folderID(f.path(".git")), commondir: true, target: "../x", strays: []string{f.path(".git/worktrees/w")}, dirs: []string{f.path("sub/.git")}, @@ -95,9 +96,9 @@ func TestReports(t *testing.T) { } was := Made{} if tc.set { - was = Made{Protected: true, GitID: s.id, Delegations: delegationsSum(s.ds)} + was = Made{Protected: true, Repo: Repo{GitID: s.id, Delegations: delegationsSum(s.ds)}} } - made := f.p.protect(t.Context(), s, InVM{Made: was}, tc.why, tc.how) + made := f.protectOne(s, was, tc.why, tc.how) var want []string for _, g := range strings.Fields(tc.want) { for _, m := range groups[g] { @@ -111,7 +112,7 @@ func TestReports(t *testing.T) { if tc.how == later { gitID = was.GitID } - if want := (Made{Protected: true, GitID: gitID, GitDirs: []string{"sub/.git"}, Delegations: delegationsSum(s.ds)}); !madeEqual(made, want) { + if want := (Made{Protected: true, Nested: tc.why != whyCheck, Repo: Repo{GitID: gitID, GitDirs: []string{"sub/.git"}, Delegations: delegationsSum(s.ds)}}); !madeEqual(made, want) { t.Errorf("made %+v, want %+v", made, want) } if locked := f.locked(s.paths[0]); locked != (tc.how == lockNow) { @@ -126,23 +127,29 @@ func TestReports(t *testing.T) { // to compare the next check with); without a .git, nothing is reported. func TestReportsReplacedAndMissing(t *testing.T) { f, s := reportsFixture(t) - was := Made{Protected: true, GitID: "1:2", GitDirs: []string{"x"}, Delegations: "d"} - if made := f.p.protect(t.Context(), s, InVM{Made: was}, whyCheck, lockNow); !madeEqual(made, was) || + was := Made{Protected: true, Repo: Repo{GitID: "1:2", GitDirs: []string{"x"}, Delegations: "d"}} + if made := f.protectOne(s, was, whyCheck, lockNow); !madeEqual(made, was) || !slices.Equal(f.warns.Names(), []string{msg.GitReplaced(s.git).Names()}) || len(f.flags) > 0 { t.Errorf("replaced: made %+v, warned %q, locks %q", made, f.warns.Names(), f.flags) } f.canLock(false) - if made := f.p.protect(t.Context(), s, InVM{Made: was}, whyCheck, watching); made.GitID != s.id { + if made := f.protectOne(s, was, whyCheck, watching); made.GitID != s.id { t.Errorf("replaced, watching: made %+v", made) } f.warns.Reset() s.exists = false - if made := f.p.protect(t.Context(), s, InVM{Made: was}, whyNew, lockNow); !madeEqual(made, Made{Protected: true, GitDirs: was.GitDirs, Delegations: "d"}) || + if made := f.protectOne(s, was, whyNew, lockNow); !madeEqual(made, Made{Protected: true, Nested: true, Repo: Repo{GitDirs: was.GitDirs, Delegations: "d"}}) || len(f.warns.Names()) > 0 { t.Errorf("no .git: made %+v, warned %q", made, f.warns.Names()) } } +// protectOne is protect of the folder's own repo alone, its scan s, +// recorded as was. +func (f *fixture) protectOne(s snapshot, was Made, w why, h how) Made { + return f.p.protect(f.t.Context(), f.vm.Name(), []snapshot{s}, InVM{Made: was}, w, h, repoSet{trees: []tree{f.p.tree}}) +} + func madeEqual(a, b Made) bool { - return a.Protected == b.Protected && a.GitID == b.GitID && slices.Equal(a.GitDirs, b.GitDirs) && a.Delegations == b.Delegations + return a.Protected == b.Protected && a.Nested == b.Nested && a.GitID == b.GitID && slices.Equal(a.GitDirs, b.GitDirs) && a.Delegations == b.Delegations } diff --git a/internal/gitprotect/repos.go b/internal/gitprotect/repos.go new file mode 100644 index 00000000..1067b54e --- /dev/null +++ b/internal/gitprotect/repos.go @@ -0,0 +1,207 @@ +package gitprotect + +import ( + "context" + "maps" + "os" + "path/filepath" + "slices" + "sync" + + "github.com/devvmhq/devvm/internal/hostsafety" + "github.com/devvmhq/devvm/internal/msg" + "github.com/devvmhq/devvm/internal/paths" + "github.com/devvmhq/devvm/internal/state" +) + +// A VM's protection covers each repo in its folder: the folder's own, and, +// once Made.Nested is set, each repo nested in it, a tree of its own whose +// top folder is below the folder. A check of a stopped VM takes the +// nested repos the walk found (Protector.Nested), the ones it recorded +// first; any other check takes those it recorded, so a launch into a +// running VM never walks. Each repo is scanned (scanAll), at most scanners +// at once, and a nested repo whose git dir another repo's protection +// covers, such as a submodule's, is left to that one. + +// scanners is how many repos scanAll scans at once: each scan runs a few +// host git commands. +const scanners = 8 + +// repoSet is the repos a check protects: the folder's own first, then +// the nested ones; and the nested repos recorded that the walk found +// gone. +type repoSet struct { + trees []tree + gone []string +} + +// repoAt is the tree of the repo nested at rel, relative to the folder t +// is the own repo of. +func (t tree) repoAt(rel string) tree { + return tree{Dir: t.Dir, Root: filepath.Join(t.Dir, rel), Home: t.Home} +} + +// recorded is the folder's own repo t and the nested repos made records. +func (t tree) recorded(made Made) []tree { + out := []tree{t} + for _, rel := range slices.Sorted(maps.Keys(made.Repos)) { + if filepath.IsLocal(rel) && rel != "." { + out = append(out, t.repoAt(rel)) + } + } + return out +} + +// repos is what a check protects, with the nested repos when nested: +// those made records and the walk found (walked; nil when it didn't walk, +// which takes the recorded ones), then the ones it found besides, at most +// hostsafety.MaxRepos in all. A recorded repo is kept, whether the walk +// found it or not, while its folder is a real folder of the project with +// anything at its .git: the VM can make a repo's .git one the walk passes +// over, and git still takes it (renamed objects and refs with a +// commondir, a .GIT, a folder it can't read). Only one with nothing at +// its .git, or whose folder isn't real, is gone. +func (t tree) repos(made Made, nested bool, walked *hostsafety.Repos) repoSet { + switch { + case !nested: + return repoSet{trees: []tree{t}} + case walked == nil: + return repoSet{trees: t.recorded(made)} + } + found := map[string]bool{} + for _, d := range walked.Dirs { + found[d] = true + } + set := repoSet{trees: []tree{t}} + for _, r := range t.recorded(made)[1:] { + rel := relTo(t.Dir, r.Root) + if _, err := os.Lstat(r.git()); err == nil && t.realInDir(r.Root) { + set.trees = append(set.trees, r) + found[rel] = false + continue + } + set.gone = append(set.gone, rel) + } + for _, d := range walked.Dirs { + if len(set.trees)-1 >= hostsafety.MaxRepos { + break + } + if found[d] { + set.trees = append(set.trees, t.repoAt(d)) + } + } + return set +} + +// scanAll scans each of trees, the folder's own repo first, at most +// scanners at once and within one budget of submodule git dirs, and +// leaves out a nested repo whose git dir another one's protection covers +// (covers). +func scanAll(ctx context.Context, trees []tree) []snapshot { + snaps := make([]snapshot, len(trees)) + sem := make(chan struct{}, scanners) + b := newBudget() + var wg sync.WaitGroup + for i, t := range trees { + t.budget = b + wg.Go(func() { + sem <- struct{}{} + defer func() { <-sem }() + snaps[i] = t.scan(ctx) + }) + } + wg.Wait() + out := snaps[:min(1, len(snaps))] + for i := 1; i < len(snaps); i++ { + d := repoGitDir(snaps[i].tree.Root) + other := slices.ContainsFunc(snaps, func(s snapshot) bool { return s.tree.Root != snaps[i].tree.Root && covers(s, d) }) + if !other { + out = append(out, snaps[i]) + } + } + return out +} + +// covers reports whether the scan s's protection covers the git dir d, +// which is one the scan locks whole (snapshot.covered): s's .git, a git +// dir under its .git/modules that reads its own config, or one of its +// linked worktrees whose commondir leads back. Anything else below .git, +// such as a .git/evil the VM made, isn't, and neither is a submodule's +// git dir in the working tree: the index that names it is the VM's to +// write, so a nested repo it names is scanned as a repo of its own. +func covers(s snapshot, d string) bool { + r := resolved(d) + return r != "" && s.exists && slices.Contains(s.covered, r) +} + +// uncovered is the nested repos rel, relative to the folder dir, whose git +// dir no scan in snaps covers (covers), or locks as a submodule's (one +// that reads its own config): a repo the protection doesn't protect, or +// whose .git file or symlink leads to a git dir in the folder that +// nothing locks, in inside; and in outside, each whose .git leads out of +// the folder, by its folder and the git dir, which devvm can't lock and +// another VM may write, as a submodule's (git_gitdir_outside). +func uncovered(dir string, snaps []snapshot, rel []string) (inside []string, outside [][2]string) { + for _, r := range rel { + d := repoGitDir(filepath.Join(dir, r)) + ok := slices.ContainsFunc(snaps, func(s snapshot) bool { + if covers(s, d) { + return true + } + c, own := commonOf(d) + return d != "" && own && c == resolved(d) && slices.Contains(s.emb.inside, d) + }) + switch { + case ok: + case d != "" && !paths.Below(d, dir): + outside = append(outside, [2]string{r, d}) + default: + inside = append(inside, r) + } + } + return inside, outside +} + +// unwatched is the nested repos whose sums the watch records without +// naming them: those now records that was didn't, scanned for the first +// time, and those gone, which git_nested_gone names. +func unwatched(was, now Made, gone []string) []string { + out := slices.Clone(gone) + for rel := range now.Repos { + if _, ok := was.Repos[rel]; !ok { + out = append(out, rel) + } + } + return out +} + +// keeper is kept (Protector.Kept) for the VM vm, or one that keeps +// nothing. +func keeper(kept func(vm string) func(path string) msg.M, vm string) func(path string) msg.M { + if kept != nil { + if k := kept(vm); k != nil { + return k + } + } + return func(string) msg.M { return msg.M{} } +} + +// Keeps reports whether the VM st's .git protection keeps path locked: +// it's on or strict, it was set up, and path is a git dir it locked, or +// in one: its folder's .git, the git dirs it recorded locking besides, +// and those of the nested repos it protects. Another VM's Unlock leaves +// such a path locked (Protector.Kept). +func Keeps(st *state.VM, path string) bool { + g, err := Of(st) + if err != nil || g.Mode != On && g.Mode != Strict || !g.Made.Protected || st.Dir == "" { + return false + } + t := tree{Dir: st.Dir, Root: st.Dir} + dirs := []string{t.git()} + dirs = append(dirs, t.abs(g.Made.GitDirs)...) + for rel, r := range g.Made.Repos { + dirs = append(dirs, t.repoAt(rel).git()) + dirs = append(dirs, t.abs(r.GitDirs)...) + } + return slices.ContainsFunc(dirs, func(d string) bool { return paths.Within(path, d) }) +} diff --git a/internal/gitprotect/scan.go b/internal/gitprotect/scan.go index cf059576..8635d5b7 100644 --- a/internal/gitprotect/scan.go +++ b/internal/gitprotect/scan.go @@ -6,21 +6,54 @@ import ( "io/fs" "os" "path/filepath" + "slices" "strings" + "sync/atomic" + "github.com/devvmhq/devvm/internal/hostsafety" "github.com/devvmhq/devvm/internal/paths" "github.com/devvmhq/devvm/internal/safefile" ) -// tree is a project folder whose .git the protection finds (scan). +// tree is a repo in a project folder whose .git the protection finds +// (scan): the folder's own, or one nested in it. It has two bounds. Its +// own top folder, Root, is where its .git, .git/modules and a relative +// core.hooksPath are; the project folder, Dir, which the VM mounts, is +// what the VM can write, so what's in it counts as inside (realInDir, +// into, hooksPathInside) and a submodule's git dir outside it can't be +// locked (embeddedIn). type tree struct { Dir string // the project folder, a physical path + Root string // the repo's top folder: Dir, or a folder below it Home string // for ~ in git's paths + // budget is the submodule git dirs the check's scans may still follow, + // shared by every repo they scan (scanAll); nil for this scan's own + // maxEmbedded alone. + budget *budget } -// snapshot is what one scan of the project's .git found: what locking, +// budget is how many submodule git dirs one check's scans follow in all, +// so the VM can't make a check slow with many repos full of them. +type budget struct{ left atomic.Int64 } + +// newBudget is the budget of one check: maxChecked git dirs. +func newBudget() *budget { + b := &budget{} + b.left.Store(maxChecked) + return b +} + +// take takes one from the budget, and reports whether there was one. +func (b *budget) take() bool { return b == nil || b.left.Add(-1) >= 0 } + +// maxChecked is how many submodule git dirs one check follows across +// every repo it scans. +const maxChecked = 1000 + +// snapshot is what one scan of a repo's .git found: what locking, // unlocking, the watch and the reports all go by, found once per check. type snapshot struct { + tree tree // the repo it scanned git string // .git exists bool // whether there's anything at .git id string // .git's identity (folderID) @@ -36,12 +69,16 @@ type snapshot struct { // hooksPath is core.hooksPath as written, when it leads into the // project folder (hooksPathInside); else "". hooksPath string + // covered is the git dirs, resolved, whose hooks and config this scan + // protects whole (coveredDirs), which a nested repo's .git can be left + // to. + covered []string } // scan finds what the protection goes by. func (t tree) scan(ctx context.Context) snapshot { g := t.git() - s := snapshot{git: g, exists: exists(g), id: folderID(g)} + s := snapshot{tree: t, git: g, exists: exists(g), id: folderID(g)} if isDir(g) && exists(filepath.Join(g, "commondir")) { target, _ := gitFile(filepath.Join(g, "commondir")) s.commondir, s.target = true, strings.TrimSpace(string(target)) @@ -54,10 +91,55 @@ func (t tree) scan(ctx context.Context) snapshot { if hp := gitConfig(ctx, filepath.Join(g, "config"), "core.hooksPath"); hp != "" && t.hooksPathInside(hp) { s.hooksPath = hp } + s.covered = t.coveredDirs(s.strays) return s } -func (t tree) git() string { return filepath.Join(t.Dir, ".git") } +// coveredDirs are the git dirs, resolved, whose hooks and config the +// repo's locks cover whole: .git, the git dirs under .git/modules that +// read their config from themselves (no commondir that leads elsewhere), +// and the linked worktrees under them whose commondir leads back (not in +// strays), each a real folder whose commondir a lock can reach. A git dir +// the VM made elsewhere under .git, such as .git/evil, or a worktree that +// is a symlink to one, isn't one: nothing locks it. +func (t tree) coveredDirs(strays []string) []string { + g := t.git() + if !isDir(g) { + return nil + } + var out []string + add := func(d string) { + if r, err := filepath.EvalSymlinks(d); err == nil { + out = append(out, r) + } + } + add(g) + for _, d := range t.gitDirs() { + if c, ok := commonOf(d); d != g && ok && c == resolved(d) { + add(d) + } + for _, w := range worktrees(d) { + // A worktree that's a symlink, or whose commondir is under one, + // can't be locked (realInDir), so the VM can point it anywhere + // once the check is done: what names it isn't covered. + if !slices.Contains(strays, w) && !isLink(w) && t.realInDir(filepath.Join(w, "commondir")) { + add(w) + } + } + } + return out +} + +// resolved is path with its symlinks resolved, or "" when it can't be. +func resolved(path string) string { + r, err := filepath.EvalSymlinks(path) + if err != nil { + return "" + } + return r +} + +func (t tree) git() string { return filepath.Join(t.Root, ".git") } // lockedDirs are the git dirs protect locks besides .git: those under // .git/modules (gitDirs) and the submodules' in the working tree. @@ -92,7 +174,7 @@ func (t tree) rel(dirs []string) []string { } // gitDirs returns the repo's git dirs: .git and its submodules', anything -// under .git/modules that git would take for one (isGitDir). +// under .git/modules that git would take for one (hostsafety.IsGitDir). func (t tree) gitDirs() []string { g := t.git() if !isDir(g) { @@ -103,7 +185,7 @@ func (t tree) gitDirs() []string { if err != nil || d.Name() != "HEAD" { return nil //nolint:nilerr // unreadable: skipped, like find } - if dir := filepath.Dir(path); isGitDir(dir) { + if dir := filepath.Dir(path); hostsafety.IsGitDir(dir) { dirs = append(dirs, dir) } return nil @@ -114,11 +196,15 @@ func (t tree) gitDirs() []string { // embeds are the submodule git dirs of the repo's working tree: inside // the project folder, or (with the submodule's folder) outside it; and // the folders inside it that a submodule names as its git dir but that -// aren't one (isGitDir), which nothing locks. +// aren't one (hostsafety.IsGitDir), which nothing locks. type embeds struct { inside []string - outside [][2]string // the submodule's folder, its git dir - notGit [][2]string // the submodule's folder, the folder it names + outside [][2]string // the submodule's folder, its git dir + notGit [][2]string // the submodule's folder, the folder it names + seen map[string]bool // the git dirs followed, resolved + // bounded is set when the scan stopped following them, past + // maxEmbedded or the check's budget (git_scan_bounded). + bounded bool } // embedded finds the submodules whose git dir is in the working tree: a @@ -132,11 +218,18 @@ func (t tree) embedded(ctx context.Context) embeds { var e embeds g := t.git() if isDir(g) && !isLink(g) { - t.embeddedIn(ctx, &e, g, t.Dir, 0) + e.seen = map[string]bool{} + if r, err := filepath.EvalSymlinks(g); err == nil { + e.seen[r] = true + } + t.embeddedIn(ctx, &e, g, t.Root, 0) } return e } +// maxEmbedded is how many submodule git dirs one repo's scan follows. +const maxEmbedded = 1000 + func (t tree) embeddedIn(ctx context.Context, e *embeds, gitDir, worktree string, depth int) { if depth >= maxDepth { return @@ -168,14 +261,25 @@ func (t tree) embeddedIn(ctx context.Context, e *embeds, gitDir, worktree string e.outside = append(e.outside, [2]string{w, d}) continue } - if !isGitDir(d) { + if !hostsafety.IsGitDir(d) { // The VM can point a .git file, or make a .git folder, at // any folder in the project: locking its hooks would lock // the project's own files. e.notGit = append(e.notGit, [2]string{w, d}) continue } - if !paths.Below(d, filepath.Join(t.Dir, ".git", "modules")) { // gitDirs has those + // Each git dir once: the VM can make gitlinks that lead back to + // their own git dir, or through a symlinked folder to one seen. + r, err := filepath.EvalSymlinks(d) + if err != nil || e.seen[r] { + continue + } + if len(e.seen) >= maxEmbedded || !t.budget.take() { + e.bounded = true + return + } + e.seen[r] = true + if !paths.Below(d, filepath.Join(t.git(), "modules")) { // gitDirs has those e.inside = append(e.inside, d) } t.embeddedIn(ctx, e, d, w, depth+1) @@ -326,18 +430,6 @@ func (t tree) realInDir(path string) bool { return err == nil && r == parent } -// isGitDir reports whether dir is what git would take for a git dir: a -// HEAD (a file, or a symlink, which git still accepts) next to objects -// and refs folders. A submodule's .git file can name any folder, so only -// one that passes has its hooks and config locked. -func isGitDir(dir string) bool { - fi, err := os.Lstat(filepath.Join(dir, "HEAD")) - if err != nil || !fi.Mode().IsRegular() && fi.Mode()&fs.ModeSymlink == 0 { - return false - } - return isDir(filepath.Join(dir, "objects")) && isDir(filepath.Join(dir, "refs")) -} - // worktrees returns a git dir's linked worktrees' folders, as the glob // worktrees/*/ has them: folders and links to folders, sorted, without // hidden ones. diff --git a/internal/gitprotect/watch.go b/internal/gitprotect/watch.go index b23cbc06..80e5dc28 100644 --- a/internal/gitprotect/watch.go +++ b/internal/gitprotect/watch.go @@ -47,26 +47,33 @@ type Watched struct { const ( maxWatchEntries = 1000 // entries of one hooks folder maxWatchBytes = 16 << 20 // bytes of one file - maxWatchTotal = 2000 // sums of one watch + maxWatchTotal = 2000 // sums of the folder's own repo + maxWatchNested = 200 // sums of each repo nested in it maxListed = 10 // paths one warning names ) // WarnUnprotected warns, at each launch of the VM vm on a host without // locks, that it can change the hooks and config of the folder's .git, -// which git on this machine runs: unless the folder has no .git, or the -// user chose off (Chosen), which says they know. On a Linux host that -// locks now (Binds), a VM left off because the host couldn't lock when it -// was made, or by a devvm that didn't record the choice, is told it can -// be. +// which git on this machine runs, and names the repos nested in the +// folder that the last walk found (InVM.Nested): unless the folder has +// neither, or the user chose off (Chosen), which says they know. On a +// Linux host that locks now (Binds), a VM left off because the host +// couldn't lock when it was made, or by a devvm that didn't record the +// choice, is told it can be. func (p *Protector) WarnUnprotected(vm *state.VM) { g, _ := Of(vm) - if g.Mode == Clone || g.Mode == Off && g.Chosen || !exists(p.git()) { + repos := exists(p.git()) || len(g.Made.Repos) > 0 + if g.Mode == Clone || g.Mode == Off && g.Chosen || !repos && len(g.Nested) == 0 { return } _, binds := p.Locker.(Binds) switch { case !p.Locker.Locks(): - p.Warn(msg.GitUnprotected(vm.Name())) + if repos { + p.Warn(msg.GitUnprotected(vm.Name())) + } + p.warnNested(g.Nested, unprotected(vm.Name())) + p.warnPast(vm.Name(), g.NestedMore, g.NestedPast) case binds && g.Mode == Off: p.Warn(msg.GitProtectAvailable(vm.Name())) } @@ -84,22 +91,37 @@ func (w watcher) check(ctx context.Context, vm *state.VM, g InVM) error { if !g.Made.Protected { why = whyNew } - snap := w.scan(ctx) - made := w.protect(ctx, snap, g, why, watching) + // Watching changes nothing in the folder, so its nested repos are + // watched from the first check: each is recorded without naming. + c := w.repos(g.Made, true, w.Nested) + snaps := scanAll(ctx, c.trees) + made := w.protect(ctx, vm.Name(), snaps, g, why, watching, c) + made.Nested = true if err := record(ctx, vm, func(g *InVM) { g.Made = made }); err != nil { return err } - return w.watch(ctx, vm, snap, g.Watched) + if err := w.nested(ctx, vm, snaps, why); err != nil { + return err + } + return w.watch(ctx, vm, snaps, g.Watched, unwatched(g.Made, made, c.gone)) } -// watch sums what a lock would cover, names what changed since the last -// check, once there was one, and what it can't fully watch, at every -// check, and records the sums. -func (w watcher) watch(ctx context.Context, vm *state.VM, snap snapshot, was Watched) error { - s := w.sums(snap) +// watch sums what a lock would cover in each repo snaps scanned, names +// what changed since the last check, once there was one, but in the +// nested repos skip (scanned for the first time, or gone), and what it +// can't fully watch, at every check, and records the sums. +func (w watcher) watch(ctx context.Context, vm *state.VM, snaps []snapshot, was Watched, skip []string) error { + s := w.sums(snaps) now := Watched{Scanned: true, Sums: s.sums} if was.Scanned { - if changed := changedPaths(was.Sums, now.Sums); len(changed) > 0 { + roots := slices.Clone(skip) + for _, s := range snaps { + roots = append(roots, relTo(w.Dir, s.tree.Root)) + } + changed := slices.DeleteFunc(changedPaths(was.Sums, now.Sums), func(path string) bool { + return slices.Contains(skip, repoOf(path, roots)) + }) + if len(changed) > 0 { l, more := listed(changed) if more == 0 { w.Warn(msg.GitChanged(l, vm.Name())) @@ -118,6 +140,18 @@ func (w watcher) watch(ctx context.Context, vm *state.VM, snap snapshot, was Wat return record(ctx, vm, func(g *InVM) { g.Watched = now }) } +// repoOf is the deepest of roots, repos' top folders relative to the +// project folder, that path, relative to it too, is in; "" for none. +func repoOf(path string, roots []string) string { + best := "" + for _, r := range roots { + if strings.HasPrefix(path, r+"/") && len(r) > len(best) { + best = r + } + } + return best +} + // listed is paths as a warning names them: at most maxListed, joined, and // how many more there are. func listed(paths []string) (string, int) { @@ -145,13 +179,32 @@ func changedPaths(was, now map[string]string) []string { return out } -// sums sums each path a lock would cover (paths), each file in its hooks -// folders, .git/commondir, there or not, and what the config hands over -// to the project folder (watchedDelegations), by path relative to the -// project folder. It never reads through a symlink that leads out of the +// sums sums, in each repo snaps scanned, each path a lock would cover +// (paths), each file in its hooks folders, .git/commondir, there or not, +// and what the config hands over to the project folder +// (watchedDelegations), by path relative to the project folder, at most +// maxWatchTotal for the folder's own repo and maxWatchNested for each +// nested one. It never reads through a symlink that leads out of the // project folder. -func (w watcher) sums(snap snapshot) summer { - s := summer{top: w.Dir, real: w.realInDir, sums: map[string]string{}} +func (w watcher) sums(snaps []snapshot) summer { + all := summer{sums: map[string]string{}} + for _, snap := range snaps { + s := w.repoSums(snap) + maps.Copy(all.sums, s.sums) + all.blind = append(all.blind, s.blind...) + } + slices.Sort(all.blind) + all.blind = slices.Compact(all.blind) + return all +} + +// repoSums is sums of one repo. +func (w watcher) repoSums(snap snapshot) summer { + bound := maxWatchNested + if snap.tree.Root == w.Dir { + bound = maxWatchTotal + } + s := summer{top: w.Dir, real: w.realInDir, max: bound, sums: map[string]string{}} todo := slices.Clone(snap.paths) if !isFile(snap.git) { todo = append(todo, filepath.Join(snap.git, "commondir")) @@ -183,7 +236,7 @@ func (w watcher) watchedDelegations(snap snapshot) []string { if hp := snap.hooksPath; hp != "" { hp = expandHome(w.Home, hp) if !filepath.IsAbs(hp) { - hp = filepath.Join(w.Dir, hp) + hp = filepath.Join(snap.tree.Root, hp) } out = append(out, filepath.Clean(hp)) } @@ -192,10 +245,11 @@ func (w watcher) watchedDelegations(snap snapshot) []string { // summer sums a watch's paths, bounded, and keeps those it can't watch // fully (blind): a symlink or a path under one, a file past maxWatchBytes, -// a folder past maxWatchEntries, a path past maxWatchTotal. +// a folder past maxWatchEntries, a path past max. type summer struct { top string // the project folder real func(path string) bool + max int // how many sums it keeps: maxWatchTotal or maxWatchNested sums map[string]string blind []string } @@ -220,10 +274,9 @@ func (s *summer) add(path string) { } } -// put records a sum, or past maxWatchTotal, the path as one it can't -// watch. +// put records a sum, or past max, the path as one it can't watch. func (s *summer) put(rel, sum string) { - if len(s.sums) >= maxWatchTotal { + if len(s.sums) >= s.max { s.blind = append(s.blind, rel) return } @@ -252,7 +305,7 @@ func (s *summer) within(path string) string { case err != nil: return "" case fi.IsDir(): - inner := summer{top: s.top, real: s.real, sums: map[string]string{}} + inner := summer{top: s.top, real: s.real, max: s.max, sums: map[string]string{}} inner.hooks(r) h := sha256.New() for _, k := range slices.Sorted(maps.Keys(inner.sums)) { diff --git a/internal/hostgit/hostgit.go b/internal/hostgit/hostgit.go index 75c67dd1..830e168f 100644 --- a/internal/hostgit/hostgit.go +++ b/internal/hostgit/hostgit.go @@ -141,6 +141,56 @@ func split(key string) (section, name string, ok bool) { return section, rest[:i], true } +// UserFiles are the user's own config files that git reads when the +// environment devvm runs in names them, which Command's git ignores with +// the rest of GIT_*: GIT_CONFIG_GLOBAL's in place of ~/.gitconfig, and +// GIT_CONFIG_SYSTEM's in place of the system's, or no system config +// (nosystem) with GIT_CONFIG_NOSYSTEM. A path that isn't absolute, or a +// file that isn't there, counts as unset (""). +type UserFiles struct { + Global, System string + NoSystem bool +} + +// UserFilesOf is the user's config files that getenv (os.Getenv) names. +func UserFilesOf(getenv func(string) string) UserFiles { + file := func(name string) string { + p := getenv(name) + if fi, err := os.Stat(p); p == "" || !filepath.IsAbs(p) || err != nil || !fi.Mode().IsRegular() { + return "" + } + return p + } + no, _ := strconv.ParseBool(getenv("GIT_CONFIG_NOSYSTEM")) + return UserFiles{Global: file("GIT_CONFIG_GLOBAL"), System: file("GIT_CONFIG_SYSTEM"), NoSystem: no} +} + +// UserConfig returns key's value in the user's global config, else in the +// system's, as git reads them for the user (UserFilesOf the environment): +// a file the environment names is read by name (--file), so no other +// GIT_* reaches git; and whether either has it. It reads only. +func UserConfig(ctx context.Context, key string) (string, bool) { + f := UserFilesOf(os.Getenv) + global, system := []string{"--global"}, []string{"--system"} + if f.Global != "" { + global = []string{"--file", f.Global} + } + if f.System != "" { + system = []string{"--file", f.System} + } + scopes := [][]string{global} + if !f.NoSystem { + scopes = append(scopes, system) + } + for _, s := range scopes { + out, err := Output(ctx, append(append([]string{"config"}, s...), "--get", key)...) + if err == nil { + return strings.TrimRight(string(out), "\n"), true + } + } + return "", false +} + // environ is env without git's own variables (GIT_*), which would point // git at another repo, worktree, index, object store or config, or at // other programs, whatever devvm runs in (a hook, a rebase's exec); and diff --git a/internal/hostgit/hostgit_test.go b/internal/hostgit/hostgit_test.go index 180bfa07..55ab445a 100644 --- a/internal/hostgit/hostgit_test.go +++ b/internal/hostgit/hostgit_test.go @@ -306,3 +306,62 @@ func TestStatusNoSubmodules(t *testing.T) { t.Error("ran the submodule's filter") } } + +// The user's config files the environment names: only an absolute path to +// a file that's there, else unset; GIT_CONFIG_NOSYSTEM as git reads it. +func TestUserFilesOf(t *testing.T) { + d := t.TempDir() + f := filepath.Join(d, "gitconfig") + if err := os.WriteFile(f, nil, 0o600); err != nil { + t.Fatal(err) + } + for env, want := range map[[3]string]UserFiles{ + {f, f, "1"}: {Global: f, System: f, NoSystem: true}, + {"gitconfig", d, "no"}: {}, + {filepath.Join(d, "none"), "", ""}: {}, + } { + got := UserFilesOf(func(k string) string { + return map[string]string{"GIT_CONFIG_GLOBAL": env[0], "GIT_CONFIG_SYSTEM": env[1], "GIT_CONFIG_NOSYSTEM": env[2]}[k] + }) + if got != want { + t.Errorf("%q: %+v, want %+v", env, got, want) + } + } +} + +// UserConfig reads the global file GIT_CONFIG_GLOBAL names, then the +// system's, which GIT_CONFIG_NOSYSTEM leaves out; else ~/.gitconfig. +func TestUserConfig(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("no git") + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + write := func(name, data string) string { + p := filepath.Join(home, name) + if err := os.WriteFile(p, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + return p + } + write(".gitconfig", "[e2e]\n\tk = home\n") + global := write("global", "[e2e]\n\tk = global\n") + system := write("system", "[e2e]\n\ts = system\n") + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + if v, ok := UserConfig(t.Context(), "e2e.k"); !ok || v != "home" { + t.Errorf("default: %q %v", v, ok) + } + t.Setenv("GIT_CONFIG_GLOBAL", global) + if v, _ := UserConfig(t.Context(), "e2e.k"); v != "global" { + t.Errorf("GIT_CONFIG_GLOBAL: %q", v) + } + t.Setenv("GIT_CONFIG_SYSTEM", system) + if _, ok := UserConfig(t.Context(), "e2e.s"); ok { + t.Error("read the system's with GIT_CONFIG_NOSYSTEM") + } + t.Setenv("GIT_CONFIG_NOSYSTEM", "") + if v, _ := UserConfig(t.Context(), "e2e.s"); v != "system" { + t.Errorf("GIT_CONFIG_SYSTEM: %q", v) + } +} diff --git a/internal/hostsafety/hostsafety.go b/internal/hostsafety/hostsafety.go index 3d6284fd..8ed27396 100644 --- a/internal/hostsafety/hostsafety.go +++ b/internal/hostsafety/hostsafety.go @@ -1,7 +1,8 @@ // Package hostsafety checks a project folder, on the host, for what a VM -// that mounts it could leave there or can't do from it: set-id files, -// whose bits reach Linux hosts, and an origin remote over SSH, which a VM -// without an SSH agent can't reach. gitprotect, beside it, guards .git. +// that mounts it could leave there or can't do from it, in one walk of +// the folder (Walk): set-id files, whose bits reach Linux hosts, and the +// git repos nested in it, which gitprotect, beside it, guards; and an +// origin remote over SSH, which a VM without an SSH agent can't reach. package hostsafety import ( @@ -10,13 +11,15 @@ import ( "io/fs" "os" "path/filepath" + "slices" "strings" "github.com/devvmhq/devvm/internal/hostgit" "github.com/devvmhq/devvm/internal/platform" + "github.com/devvmhq/devvm/internal/safefile" ) -// setIDMax is how many set-id files SetIDFiles returns at most. +// setIDMax is how many set-id files Walk returns at most. const setIDMax = 5 // SetIDFile is a file with the set-user-id or set-group-id bit; Root when @@ -32,47 +35,215 @@ func rootSetID(m fs.FileMode, uid, gid uint32) bool { return m&fs.ModeSetuid != 0 && uid == 0 || m&fs.ModeSetgid != 0 && gid == 0 } -// SetIDFiles returns up to five files in dir, on its file system, with the -// set-user-id or set-group-id bit. On Linux hosts a VM's set-id bits reach -// the host, and a set-user-id file runs as its owner for anyone who runs -// it: the user, or root. Every .git folder is skipped: nothing runs a file -// in one by its path, and .git holds most of a big project's files. The -// walk reads each file's metadata, a second or so for 200,000 files, so -// it runs once the VM is stopped and when a VM is made, never at a launch -// into a running VM. -func SetIDFiles(dir string) []SetIDFile { - var files []SetIDFile +// The walk's bounds for repos: it looks for them at most RepoDepth +// folders below the project folder, and returns at most MaxRepos of them, +// counting the rest and keeping the names of the first MaxPast of those. +const ( + RepoDepth = 4 + MaxRepos = 100 + MaxPast = 10 +) + +// Found is what one walk of a project folder found (Walk): its set-id +// files, when asked for, and the git repos nested in it. +type Found struct { + SetID []SetIDFile + Repos Repos +} + +// Repos are the git repos nested in a project folder, below its own: each +// folder with anything named .git (IsGitName), a folder, a file, which a +// linked worktree or a separate git dir has, a symlink or anything else, +// as the VM can make any of them into one git takes, by its path relative +// to the project folder, in the walk's order, at most MaxRepos. +type Repos struct { + Dirs []string + More int // how many more it found + Past []string // the first MaxPast of those, to name + // Bare is the folders shaped like a git dir (IsGitDir) that aren't a + // .git, at most MaxRepos: git run in a folder below one can take it + // for its repo, a bare repo whose config can name a work tree. + Bare []string + // Skipped is how many .git the walk saw where it doesn't look for + // repos (deeper than RepoDepth, or in noRepos), which it sees only + // where it walks for set-id files, and Devices how many folders it + // didn't enter as they're on another file system. + Skipped int + Devices int +} + +// IsGitName reports whether name is .git as git finds it here: whatever +// its case on a file system that folds case (platform.FoldsCase), where +// .GIT is .git. +func IsGitName(name string) bool { + return name == ".git" || platform.FoldsCase && strings.EqualFold(name, ".git") +} + +// Walk walks dir once, on its file system, following no symlink, for +// what a VM that mounts it could leave there: the git repos nested in it +// (Repos), and with setID, up to five set-id files. On Linux hosts a VM's +// set-id bits reach the host, and a set-user-id file runs as its owner +// for anyone who runs it: the user, or root. Every .git folder is +// skipped: nothing runs a file in one by its path, git's own repos in it +// (submodules') are gitprotect's to find, and .git holds most of a big +// project's files. Repos are looked for at most RepoDepth folders down, +// and not in the folders of packages and build tools (noRepos), which +// rarely hold a repo anyone runs git in, so a walk without setID stops +// there. With it, the walk reads each file's metadata, a second or so for +// 200,000 files, so it runs once the VM is stopped and when a VM is made, +// never at a launch into a running VM. +func Walk(dir string, setID bool) Found { root, err := os.Stat(dir) if err != nil { + return Found{} + } + w := walker{dir: dir, root: root, setID: setID} + _ = filepath.WalkDir(dir, w.visit) + return w.found +} + +// walker is one Walk's state. +type walker struct { + dir string + root fs.FileInfo + setID bool // set-id files are still to find + found Found +} + +func (w *walker) visit(path string, d fs.DirEntry, err error) error { + if err != nil || path == w.dir { + return nil //nolint:nilerr // an unreadable folder: skip it, like find + } + rel := strings.TrimPrefix(path, w.dir+"/") + if IsGitName(d.Name()) { + w.repo(rel) + if d.IsDir() { + return filepath.SkipDir + } return nil } - _ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return nil //nolint:nilerr // an unreadable folder: skip it, like find + if d.IsDir() { + return w.folder(path, rel, d) + } + if w.setID && d.Type().IsRegular() { + w.setIDFile(path, d) + } + return nil +} + +// folder is visit's for a folder: one on another file system is counted +// and not entered, one shaped like a git dir is named (Repos.Bare), and +// with no set-id files to find, one where no repo is looked for isn't +// entered. +func (w *walker) folder(path, rel string, d fs.DirEntry) error { + r := &w.found.Repos + if fi, err := d.Info(); err == nil && !platform.SameDevice(w.root, fi) { + r.Devices++ + return filepath.SkipDir + } + if reposIn(rel) && len(r.Bare) < MaxRepos && IsGitDir(path) { + r.Bare = append(r.Bare, rel) + } + if !w.setID && !reposIn(rel) { + return filepath.SkipDir + } + return nil +} + +// repo records the folder of a .git at rel, whatever it is, when the walk +// looks for repos there, but not the project folder's own: git takes a +// .git that isn't a repo's yet for none and looks above it, but the VM can +// make it one at any time. +func (w *walker) repo(rel string) { + folder := filepath.Dir(rel) + r := &w.found.Repos + switch { + case folder == ".": + case !reposIn(folder): + r.Skipped++ + case len(r.Dirs) < MaxRepos: + r.Dirs = append(r.Dirs, folder) + default: + r.More++ + if len(r.Past) < MaxPast { + r.Past = append(r.Past, folder) } - if d.IsDir() { - if path != dir && d.Name() == ".git" { - return filepath.SkipDir - } - if fi, err := d.Info(); err == nil && path != dir && !platform.SameDevice(root, fi) { - return filepath.SkipDir - } - return nil + } +} + +// reposIn reports whether the walk looks for a repo's .git in the folder +// rel, relative to the project folder: it's at most RepoDepth folders +// down, and neither it nor a folder above it is one of noRepos. +func reposIn(rel string) bool { + parts := strings.Split(rel, "/") + if len(parts) > RepoDepth { + return false + } + return !slices.ContainsFunc(parts, noRepos) +} + +// noRepos reports whether a folder is one the walk doesn't look for repos +// in, for speed: packages and build tools' own, which they fill with +// what they fetch. +func noRepos(name string) bool { + switch name { + case "node_modules", "vendor", ".venv", "__pycache__", ".terraform": + return true + } + return false +} + +// setIDFile records the file at path when it has a set-id bit, up to +// setIDMax. +func (w *walker) setIDFile(path string, d fs.DirEntry) { + fi, err := d.Info() + if err != nil || fi.Mode()&(fs.ModeSetuid|fs.ModeSetgid) == 0 { + return + } + uid, gid, ok := platform.Owner(fi) + w.found.SetID = append(w.found.SetID, SetIDFile{Path: path, Root: ok && rootSetID(fi.Mode(), uid, gid)}) + if len(w.found.SetID) == setIDMax { + w.setID = false + } +} + +// IsGitDir reports whether dir is what git could take for a git dir, as +// git's own is_git_directory has it: a HEAD (a file, or a symlink) and +// objects and refs, files or folders, in its common dir, the folder its +// commondir file names (relative to dir), or else dir itself. It takes +// more than git would, never less: git also checks HEAD's contents and +// that objects and refs can be searched, which the VM can change at any +// time. A .git file can name any folder, so gitprotect locks the hooks +// and config only of one that passes. +func IsGitDir(dir string) bool { + fi, err := os.Lstat(filepath.Join(dir, "HEAD")) + if err != nil || !fi.Mode().IsRegular() && fi.Mode()&fs.ModeSymlink == 0 { + return false + } + common := dir + if c, err := safefile.Read(filepath.Join(dir, "commondir"), maxCommondir, safefile.Opts{Follow: true}); err == nil { + common = strings.TrimRight(string(c), "\n") + if !filepath.IsAbs(common) { + common = filepath.Join(dir, common) } - if !d.Type().IsRegular() { - return nil - } - fi, err := d.Info() - if err == nil && fi.Mode()&(fs.ModeSetuid|fs.ModeSetgid) != 0 { - uid, gid, ok := platform.Owner(fi) - files = append(files, SetIDFile{Path: path, Root: ok && rootSetID(fi.Mode(), uid, gid)}) - } - if len(files) == setIDMax { - return filepath.SkipAll - } - return nil - }) - return files + } + return exists(filepath.Join(common, "objects")) && exists(filepath.Join(common, "refs")) +} + +// maxCommondir is the most of a commondir file IsGitDir reads. +const maxCommondir = 4096 + +func exists(path string) bool { _, err := os.Stat(path); return err == nil } + +// BareExplicit reports whether git on this machine takes a bare repo only +// when it's named (safe.bareRepository=explicit, git 2.38 and newer), in +// your global config or the system's, the files GIT_CONFIG_GLOBAL and +// GIT_CONFIG_SYSTEM name included (hostgit.UserConfig): else git run in +// a folder below one shaped like a git dir, which a VM can make in its +// folder, takes it for its repo, config and all. It only reads. +func BareExplicit(ctx context.Context) bool { + v, _ := hostgit.UserConfig(ctx, "safe.bareRepository") + return strings.EqualFold(strings.TrimSpace(v), "explicit") } // SSHRemote reports whether dir's repo fetches origin over SSH, which a VM diff --git a/internal/hostsafety/hostsafety_test.go b/internal/hostsafety/hostsafety_test.go index f4a21f7d..293a7988 100644 --- a/internal/hostsafety/hostsafety_test.go +++ b/internal/hostsafety/hostsafety_test.go @@ -6,7 +6,10 @@ import ( "os/exec" "path/filepath" "slices" + "strconv" "testing" + + "github.com/devvmhq/devvm/internal/platform" ) func touch(t *testing.T, paths ...string) { @@ -27,6 +30,86 @@ func mkdirs(t *testing.T, dirs ...string) { } } +func setIDFiles(dir string) []SetIDFile { return Walk(dir, true).SetID } + +// gitDir makes dir a git dir, as IsGitDir has it. +func gitDir(t *testing.T, dir string) { + t.Helper() + mkdirs(t, filepath.Join(dir, "objects"), filepath.Join(dir, "refs")) + touch(t, filepath.Join(dir, "HEAD")) +} + +// The walk finds the folders nested in the folder, below its own, with +// anything named .git, at most RepoDepth folders down and MaxRepos of +// them, and counts the rest; never through a symlink, in a .git folder or +// in a package manager's folder, where a set-id walk counts them. +func TestWalkRepos(t *testing.T) { + d := t.TempDir() + gitDir(t, filepath.Join(d, ".git")) + for _, r := range []string{"a", "a/inner", "b/c/d/e", "deep/1/2/3/4", "node_modules/x", "x/vendor/y"} { + gitDir(t, filepath.Join(d, r, ".git")) + } + // A linked worktree's .git file, a .git symlink and a .git folder that + // isn't a git dir yet count, but not a repo in .git. + mkdirs(t, filepath.Join(d, "wt"), filepath.Join(d, "fake", ".git"), filepath.Join(d, ".git", "modules", "m")) + touch(t, filepath.Join(d, "wt", ".git")) + gitDir(t, filepath.Join(d, ".git", "modules", "m", ".git")) + mkdirs(t, filepath.Join(d, "ln")) + if err := os.Symlink(filepath.Join(d, "a", ".git"), filepath.Join(d, "ln", ".git")); err != nil { + t.Fatal(err) + } + // A symlink to a repo isn't followed. + if err := os.Symlink(filepath.Join(d, "a"), filepath.Join(d, "linked")); err != nil { + t.Fatal(err) + } + // A folder shaped like a git dir, not a .git, is named as one. + gitDir(t, filepath.Join(d, "shadow")) + want := []string{"a", "a/inner", "b/c/d/e", "fake", "ln", "wt"} + for _, setID := range []bool{false, true} { + got := Walk(d, setID).Repos + if !slices.Equal(got.Dirs, want) || got.More != 0 || !slices.Equal(got.Bare, []string{"shadow"}) { + t.Errorf("setID %v: Repos = %+v, want %v", setID, got, want) + } + if skipped := map[bool]int{false: 0, true: 3}[setID]; got.Skipped != skipped { + t.Errorf("setID %v: skipped %d, want %d", setID, got.Skipped, skipped) + } + } + // Past MaxRepos, they're counted, the first of them named. + for i := range MaxRepos + 2 { + gitDir(t, filepath.Join(d, "many", strconv.Itoa(i), ".git")) + } + got := Walk(d, false).Repos + if len(got.Dirs) != MaxRepos || got.More != len(want)+2 || len(got.Past) != min(got.More, MaxPast) { + t.Errorf("past the bound: %d repos, %d more, %q", len(got.Dirs), got.More, got.Past) + } + if got := Walk(filepath.Join(d, "none"), true); got.Repos.Dirs != nil || got.SetID != nil { + t.Errorf("no folder: %+v", got) + } +} + +// git takes for a git dir a folder with a HEAD and objects and refs, which +// may be files, there or in the folder its commondir names; a .GIT is a +// .git where names fold case. +func TestIsGitDir(t *testing.T) { + d := t.TempDir() + gitDir(t, filepath.Join(d, "plain")) + mkdirs(t, filepath.Join(d, "files"), filepath.Join(d, "common"), filepath.Join(d, "none")) + touch(t, filepath.Join(d, "files", "HEAD"), filepath.Join(d, "files", "objects"), filepath.Join(d, "files", "refs")) + touch(t, filepath.Join(d, "common", "HEAD")) + if err := os.WriteFile(filepath.Join(d, "common", "commondir"), []byte("../plain\n"), 0o600); err != nil { + t.Fatal(err) + } + touch(t, filepath.Join(d, "none", "HEAD")) + for dir, want := range map[string]bool{"plain": true, "files": true, "common": true, "none": false} { + if got := IsGitDir(filepath.Join(d, dir)); got != want { + t.Errorf("%s: %v", dir, got) + } + } + if IsGitName(".GIT") != platform.FoldsCase || !IsGitName(".git") || IsGitName(".gitx") { + t.Error("IsGitName") + } +} + func TestSetIDFiles(t *testing.T) { d := t.TempDir() mkdirs(t, filepath.Join(d, "sub")) @@ -35,19 +118,19 @@ func TestSetIDFiles(t *testing.T) { if err := os.Chmod(tool, fs.ModeSetuid|0o755); err != nil { t.Fatal(err) } - if got := SetIDFiles(d); !slices.Equal(got, []SetIDFile{{Path: tool, Root: os.Getuid() == 0}}) { + if got := setIDFiles(d); !slices.Equal(got, []SetIDFile{{Path: tool, Root: os.Getuid() == 0}}) { t.Errorf("SetIDFiles = %v, want %s", got, tool) } if err := os.Chmod(tool, fs.ModeSetgid|0o755); err != nil { t.Fatal(err) } - if got := SetIDFiles(d); len(got) != 1 { + if got := setIDFiles(d); len(got) != 1 { t.Errorf("set-group-id: SetIDFiles = %v", got) } if err := os.Chmod(tool, 0o755); err != nil { //nolint:gosec // the test's own file t.Fatal(err) } - if got := SetIDFiles(d); got != nil { + if got := setIDFiles(d); got != nil { t.Errorf("none: SetIDFiles = %v", got) } // None in a .git folder, the project's or a submodule's, counts. @@ -59,7 +142,7 @@ func TestSetIDFiles(t *testing.T) { t.Fatal(err) } } - if got := SetIDFiles(d); got != nil { + if got := setIDFiles(d); got != nil { t.Errorf("in .git: SetIDFiles = %v", got) } // At most five. @@ -70,10 +153,10 @@ func TestSetIDFiles(t *testing.T) { t.Fatal(err) } } - if got := SetIDFiles(d); len(got) != setIDMax { + if got := setIDFiles(d); len(got) != setIDMax { t.Errorf("SetIDFiles = %d files, want %d", len(got), setIDMax) } - if got := SetIDFiles(filepath.Join(d, "none")); got != nil { + if got := setIDFiles(filepath.Join(d, "none")); got != nil { t.Errorf("no folder: SetIDFiles = %v", got) } } @@ -99,6 +182,35 @@ func TestRootSetID(t *testing.T) { } } +// BareExplicit reads safe.bareRepository from your global config. +func TestBareExplicit(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("no git") + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + if BareExplicit(t.Context()) { + t.Skip("this machine's system config sets it") + } + // Your own global file, as GIT_CONFIG_GLOBAL names it. + own := filepath.Join(home, "own.gitconfig") + if err := os.WriteFile(own, []byte("[safe]\n\tbareRepository = explicit\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("GIT_CONFIG_GLOBAL", own) + if !BareExplicit(t.Context()) { + t.Error("GIT_CONFIG_GLOBAL's not read") + } + t.Setenv("GIT_CONFIG_GLOBAL", "") + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[safe]\n\tbareRepository = explicit\n"), 0o600); err != nil { + t.Fatal(err) + } + if !BareExplicit(t.Context()) { + t.Error("explicit not read") + } +} + func TestSSHRemote(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("no git") diff --git a/internal/msg/docs.go b/internal/msg/docs.go index ba018d11..9762c268 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -175,6 +175,7 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "ca_folder_unreadable": "using/settings#a-companys-ca", "doctor_proxy_ca": "using/troubleshooting#tls-errors-behind-a-company-proxy", "doctor_pins_apparmor": "safety/git-protection#ubuntu", + "doctor_git_bare": "safety/git-protection#bare-repos", "doctor_pins_sysctl": "safety/git-protection#when-linux-cant-lock", "doctor_pins_max": "safety/git-protection#when-linux-cant-lock", "doctor_pins_failed": "safety/git-protection#when-linux-cant-lock", @@ -273,6 +274,22 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "git_changed_more": "safety/git-protection#when-devvm-names-a-change", "git_watch_blind": "safety/git-protection#what-the-watch-cant-see", "git_watch_blind_more": "safety/git-protection#what-the-watch-cant-see", + "git_nested_unprotected": "safety/git-protection#not-covered", + "git_nested_unprotected_more": "safety/git-protection#not-covered", + "git_nested_past_bound": "safety/git-protection#nested-repos", + "git_nested_protectable": "safety/git-protection#nested-repos", + "git_nested_protectable_more": "safety/git-protection#nested-repos", + "git_nested_appeared": "safety/git-protection#when-devvm-reports-git", + "git_nested_gone": "safety/git-protection#when-devvm-reports-git", + "git_kept_locked": "safety/git-protection#nested-repos", + "git_nested_appeared_runs": "safety/git-protection#when-devvm-reports-git", + "git_nested_gitdir_outside": "safety/git-protection#not-covered", + "git_nested_bare": "safety/git-protection#bare-repos", + "git_nested_skipped": "safety/git-protection#not-covered", + "git_nested_devices": "safety/git-protection#not-covered", + "git_scan_bounded": "safety/git-protection#not-covered", + "git_kept_unread": "safety/git-protection#nested-repos", + "git_locks_left": "safety/git-protection#nested-repos", "git_protect_on_needs_locks": "safety/git-protection#when-linux-cant-lock", "git_protect_available": "safety/git-protection#linux-hosts", "git_protect_next_stop": "safety/git-protection#turning-it-on-or-off", diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 6238c589..8a2f0fa6 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -1149,6 +1149,11 @@ func DoctorFailed(reason string) M { return M{id: "doctor_failed", vals: []val{{"reason", reason}}} } +// DoctorGitBare is [doctor_git_bare]: "Tip: run git config --global safe.bareRepository explicit, so git on this machine uses a bare repo only when you name it. Then a folder that a VM makes look like a git folder can't take over git in the folders below it." +func DoctorGitBare() M { + return M{id: "doctor_git_bare"} +} + // DoctorLatestRelease is [doctor_latest_release]: "The newest devvm release is {{.latest}}, as of {{.date}}." func DoctorLatestRelease(date string, latest string) M { return M{id: "doctor_latest_release", vals: []val{{"date", date}, {"latest", latest}}} @@ -1509,6 +1514,16 @@ func GitIncludeInside(config string, path string) M { return M{id: "git_include_inside", vals: []val{{"config", config}, {"path", path}}} } +// GitKeptLocked is [git_kept_locked]: "Some of .git's locks stay on, as {{.vm}}'s .git protection covers the same repos. Run devvm git-protect off in that VM's folder to take them off too." +func GitKeptLocked(vm string) M { + return M{id: "git_kept_locked", vals: []val{{"vm", vm}}} +} + +// GitKeptUnread is [git_kept_unread]: "Some of .git's locks stay on, as devvm can't read {{.state}}, the state of a VM that may protect the same repos. Fix or remove that VM's state, then run this again." +func GitKeptUnread(state string) M { + return M{id: "git_kept_unread", vals: []val{{"state", state}}} +} + // GitLockLater is [git_lock_later]: "This folder has no .git yet. devvm locks it for {{.vm}} when one appears." func GitLockLater(vm string) M { return M{id: "git_lock_later", vals: []val{{"vm", vm}}} @@ -1529,6 +1544,71 @@ func GitLockedStrict(vm string) M { return M{id: "git_locked_strict", vals: []val{{"vm", vm}}} } +// GitLocksLeft is [git_locks_left]: "WARNING: devvm locked the .git of the git repos at {{.repos}}, which aren't in this folder any more, so it can't take their locks off. If you moved them, run chflags -R nouchg on their .git/hooks and .git/config." +func GitLocksLeft(repos string) M { + return M{id: "git_locks_left", vals: []val{{"repos", repos}}} +} + +// GitNestedAppeared is [git_nested_appeared]: "WARNING: A git repo appeared at {{.repo}} while {{.vm}} could write this folder, so the VM may have made it. devvm protects it from now on, but check its hooks and config before you run git there." +func GitNestedAppeared(repo string, vm string) M { + return M{id: "git_nested_appeared", vals: []val{{"repo", repo}, {"vm", vm}}} +} + +// GitNestedAppearedRuns is [git_nested_appeared_runs]: "WARNING: A git repo appeared at {{.repo}} while {{.vm}} could write this folder, and its {{.runs}} run programs on this machine. devvm protects it as it is from now on, so check them before you run git there." +func GitNestedAppearedRuns(repo string, runs string, vm string) M { + return M{id: "git_nested_appeared_runs", vals: []val{{"repo", repo}, {"runs", runs}, {"vm", vm}}} +} + +// GitNestedBare is [git_nested_bare]: "WARNING: {{.dirs}} in this folder look like git folders, which git run below them can take for its repo, and {{.vm}} can change them. Check them before you run git there, and see devvm doctor for git's safe.bareRepository." +func GitNestedBare(dirs string, vm string) M { + return M{id: "git_nested_bare", vals: []val{{"dirs", dirs}, {"vm", vm}}} +} + +// GitNestedDevices is [git_nested_devices]: "WARNING: devvm doesn't look for git repos in {{.count}} folders of this folder that are on another disk, so {{.vm}} can change the hooks and config of any repo there. Check them before you run git there." +func GitNestedDevices(count int, vm string) M { + return M{id: "git_nested_devices", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"vm", vm}}} +} + +// GitNestedGitdirOutside is [git_nested_gitdir_outside]: "The git repo at {{.repo}} keeps its git folder outside the project, at {{.git}}, so devvm can't lock it. git on this machine still reads its config there." +func GitNestedGitdirOutside(git string, repo string) M { + return M{id: "git_nested_gitdir_outside", vals: []val{{"git", git}, {"repo", repo}}} +} + +// GitNestedGone is [git_nested_gone]: "WARNING: The git repo at {{.repo}} that devvm protected is gone or moved, perhaps by {{.vm}}. If you didn't move it, check where it went before you run git there." +func GitNestedGone(repo string, vm string) M { + return M{id: "git_nested_gone", vals: []val{{"repo", repo}, {"vm", vm}}} +} + +// GitNestedPastBound is [git_nested_past_bound]: "WARNING: .git protection covers the first 100 git repos nested in this folder, and not {{.count}} more, such as {{.repos}}, so {{.vm}} can change their hooks and config, which git on this machine runs. Move the repos you don't use out of this folder." +func GitNestedPastBound(count int, repos string, vm string) M { + return M{id: "git_nested_past_bound", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"repos", repos}, {"vm", vm}}} +} + +// GitNestedProtectable is [git_nested_protectable]: "WARNING: {{.vm}}'s .git protection doesn't cover the git repos nested in this folder at {{.repos}}, so the VM can change their hooks and config, which git on this machine runs. Run devvm git-protect on to protect them too, as devvm does for new VMs." +func GitNestedProtectable(repos string, vm string) M { + return M{id: "git_nested_protectable", vals: []val{{"repos", repos}, {"vm", vm}}} +} + +// GitNestedProtectableMore is [git_nested_protectable_more]: "WARNING: {{.vm}}'s .git protection doesn't cover the git repos nested in this folder at {{.repos}} and {{.count}} more folders, so the VM can change their hooks and config, which git on this machine runs. Run devvm git-protect on to protect them too, as devvm does for new VMs." +func GitNestedProtectableMore(count int, repos string, vm string) M { + return M{id: "git_nested_protectable_more", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"repos", repos}, {"vm", vm}}} +} + +// GitNestedSkipped is [git_nested_skipped]: "WARNING: devvm doesn't protect {{.count}} git repos in this folder, as they're deeper than four folders or in folders such as node_modules, so {{.vm}} can change their hooks and config. Check them before you run git there." +func GitNestedSkipped(count int, vm string) M { + return M{id: "git_nested_skipped", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"vm", vm}}} +} + +// GitNestedUnprotected is [git_nested_unprotected]: "WARNING: .git protection doesn't cover the git repos nested in this folder at {{.repos}}, so {{.vm}} can change their hooks and config, which git on this machine runs. Check them before you run git there." +func GitNestedUnprotected(repos string, vm string) M { + return M{id: "git_nested_unprotected", vals: []val{{"repos", repos}, {"vm", vm}}} +} + +// GitNestedUnprotectedMore is [git_nested_unprotected_more]: "WARNING: .git protection doesn't cover the git repos nested in this folder at {{.repos}} and {{.count}} more folders, so {{.vm}} can change their hooks and config, which git on this machine runs. Check them before you run git there." +func GitNestedUnprotectedMore(count int, repos string, vm string) M { + return M{id: "git_nested_unprotected_more", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"repos", repos}, {"vm", vm}}} +} + // GitNotLocked is [git_not_locked]: "WARNING: If you didn't make {{.path}}, check it before you run git here. It's a symlink or under one, so devvm can't lock it." func GitNotLocked(path string) M { return M{id: "git_not_locked", vals: []val{{"path", path}}} @@ -1604,6 +1684,11 @@ func GitReplaced(git string) M { return M{id: "git_replaced", vals: []val{{"git", git}}} } +// GitScanBounded is [git_scan_bounded]: "WARNING: devvm stopped following the submodules of {{.git}} after 1,000 git folders, so it doesn't lock the rest. Check them before you run git there, or move the repos you don't use out of this folder." +func GitScanBounded(git string) M { + return M{id: "git_scan_bounded", vals: []val{{"git", git}}} +} + // GitUnlocked is [git_unlocked]: "devvm unlocked .git, so {{.vm}} can change its hooks and config, which run on this machine. To lock it again, run devvm git-protect on." func GitUnlocked(vm string) M { return M{id: "git_unlocked", vals: []val{{"vm", vm}}} @@ -4605,6 +4690,7 @@ var specs = map[string]spec{ "docker_missing": {}, "docker_only": {fields: []string{"from"}}, "doctor_failed": {fields: []string{"reason"}}, + "doctor_git_bare": {}, "doctor_latest_release": {fields: []string{"date", "latest"}}, "doctor_ok": {fields: []string{"backend", "version"}}, "doctor_pins_apparmor": {}, @@ -4677,10 +4763,25 @@ var specs = map[string]spec{ "git_hooks_path": {fields: []string{"path"}}, "git_hooks_unlocked": {fields: []string{"hooks"}}, "git_include_inside": {fields: []string{"config", "path"}}, + "git_kept_locked": {fields: []string{"vm"}}, + "git_kept_unread": {fields: []string{"state"}}, "git_lock_later": {fields: []string{"vm"}}, "git_lock_raced": {fields: []string{"path"}}, "git_locked": {fields: []string{"vm"}}, "git_locked_strict": {fields: []string{"vm"}}, + "git_locks_left": {fields: []string{"repos"}}, + "git_nested_appeared": {fields: []string{"repo", "vm"}}, + "git_nested_appeared_runs": {fields: []string{"repo", "runs", "vm"}}, + "git_nested_bare": {fields: []string{"dirs", "vm"}}, + "git_nested_devices": {plural: true, fields: []string{"count", "vm"}}, + "git_nested_gitdir_outside": {fields: []string{"git", "repo"}}, + "git_nested_gone": {fields: []string{"repo", "vm"}}, + "git_nested_past_bound": {plural: true, fields: []string{"count", "repos", "vm"}}, + "git_nested_protectable": {fields: []string{"repos", "vm"}}, + "git_nested_protectable_more": {plural: true, fields: []string{"count", "repos", "vm"}}, + "git_nested_skipped": {plural: true, fields: []string{"count", "vm"}}, + "git_nested_unprotected": {fields: []string{"repos", "vm"}}, + "git_nested_unprotected_more": {plural: true, fields: []string{"count", "repos", "vm"}}, "git_not_locked": {fields: []string{"path"}}, "git_pin_again": {fields: []string{"path", "vm"}}, "git_pin_events_kept": {fields: []string{"file"}}, @@ -4696,6 +4797,7 @@ var specs = map[string]spec{ "git_protect_next_stop": {fields: []string{"mode", "vm"}}, "git_protect_on_needs_locks": {}, "git_replaced": {fields: []string{"git"}}, + "git_scan_bounded": {fields: []string{"git"}}, "git_unlocked": {fields: []string{"vm"}}, "git_unprotected": {fields: []string{"vm"}}, "git_unprotected_quiet": {fields: []string{"vm"}}, diff --git a/internal/paths/dirs.go b/internal/paths/dirs.go index 93be5d99..88e47772 100644 --- a/internal/paths/dirs.go +++ b/internal/paths/dirs.go @@ -178,6 +178,12 @@ func (d Dirs) Run() string { return filepath.Join(d.Data, "run") } // after the VM's own lock (VM.Lock), never before. func (d Dirs) ClaimsLock() string { return filepath.Join(d.Run(), "claims.lock") } +// GitLock is held while .git protection locks a VM's repos and records +// them, and while it unlocks them, so one VM's unlock never runs between +// another's locks and their record. It's taken before a VM's own lock +// (VM.Lock), never after. +func (d Dirs) GitLock() string { return filepath.Join(d.Run(), "git.lock") } + // CreateLock is the creation lock of the project folder whose hash is // hash (project.Hash): held while a devvm makes the folder's VM, from // when it finds the folder has none until the VM's creation is recorded. diff --git a/internal/paths/vm.go b/internal/paths/vm.go index 90df1268..d11652c1 100644 --- a/internal/paths/vm.go +++ b/internal/paths/vm.go @@ -54,11 +54,13 @@ func (v VM) ProxyConfig() string { return filepath.Join(v.Run(), "proxy.json") } // and .status, the status file it writes once it listens. func (v VM) Proxy(ext string) string { return filepath.Join(v.Run(), "proxy"+ext) } -// GitPins is what a Linux host's QEMU namespace records of the pins it -// lost and made again while the VM ran (a git command on the host -// replaced a pinned file, a hard link), one JSON object a line, which -// .git protection reports once the VM stops. -func (v VM) GitPins() string { return filepath.Join(v.Run(), "git-pins.jsonl") } +// GitPins is a file of a Linux host's pins in QEMU's namespace, by ext: +// .jsonl, what the namespace records of the pins it lost and made again +// while the VM ran (a git command on the host replaced a pinned file, a +// hard link), one JSON object a line, which .git protection reports once +// the VM stops; .json, what the start pins, which devvm _qemu reads +// (backend.Pins.File), written private at each start that pins. +func (v VM) GitPins(ext string) string { return filepath.Join(v.Run(), "git-pins"+ext) } // CA is the folder of the VM's own CA, which its proxy intercepts with // and which only it trusts. diff --git a/internal/paths/vm_test.go b/internal/paths/vm_test.go index 950cc491..0ec97f31 100644 --- a/internal/paths/vm_test.go +++ b/internal/paths/vm_test.go @@ -19,7 +19,8 @@ func TestVMFiles(t *testing.T) { v.Proxy(".pid"): "run/proxy.pid", v.ProxyConfig(): "run/proxy.json", v.Proxy(".status"): "run/proxy.status", - v.GitPins(): "run/git-pins.jsonl", + v.GitPins(".jsonl"): "run/git-pins.jsonl", + v.GitPins(".json"): "run/git-pins.json", v.Profile(): "run/sandbox.sb", v.BuildProxy(): "run/build-proxy", v.Started(): "run/started", @@ -40,8 +41,8 @@ func TestVMFiles(t *testing.T) { v.CA().NextKey(): "run/ca/next.key", filepath.Join(v.Dir, "other"): "other", } - if len(want) != 28 { - t.Fatalf("%d paths, want 28: two are the same", len(want)) + if len(want) != 29 { + t.Fatalf("%d paths, want 29: two are the same", len(want)) } for got, rel := range want { if got != filepath.Join("/d/vms/0123456789abcd", rel) { diff --git a/internal/platform/folder_darwin.go b/internal/platform/folder_darwin.go index 12fd472f..58860288 100644 --- a/internal/platform/folder_darwin.go +++ b/internal/platform/folder_darwin.go @@ -41,6 +41,10 @@ func UniqueFolderID(path, id string) bool { // (Chflags, Immutable): macOS's uchg, which the user sets without root. const HasImmutableFlag = true +// FoldsCase reports whether file names here may match whatever their +// case: macOS's APFS and HFS+ do by default, so .GIT is .git to git. +const FoldsCase = true + // Chflags sets file flags (uchg, nouchg) on path and everything under it, // following no symlink, path itself included: chflags -R -P. func Chflags(ctx context.Context, flags, path string) error { diff --git a/internal/platform/folder_linux.go b/internal/platform/folder_linux.go index 7c15a937..0f734aef 100644 --- a/internal/platform/folder_linux.go +++ b/internal/platform/folder_linux.go @@ -57,6 +57,10 @@ func uniqueFS(fsType int64) bool { // Linux's immutable attribute needs root. const HasImmutableFlag = false +// FoldsCase reports whether file names here may match whatever their +// case: not on Linux's file systems, as devvm's project folders use them. +const FoldsCase = false + // Chflags sets file flags: Linux has no unprivileged immutable flag. func Chflags(context.Context, string, string) error { return errors.ErrUnsupported } diff --git a/internal/platform/folder_other.go b/internal/platform/folder_other.go index 2bff382d..feac60d9 100644 --- a/internal/platform/folder_other.go +++ b/internal/platform/folder_other.go @@ -18,6 +18,10 @@ func UniqueFolderID(_, _ string) bool { return false } // not this one. const HasImmutableFlag = false +// FoldsCase reports whether file names here may match whatever their +// case: taken to on this system, so a .GIT counts as .git. +const FoldsCase = true + // Chflags sets file flags: not on this system. func Chflags(context.Context, string, string) error { return errors.ErrUnsupported } diff --git a/internal/structure/owners_doc_test.go b/internal/structure/owners_doc_test.go index 53710df3..c761b4aa 100644 --- a/internal/structure/owners_doc_test.go +++ b/internal/structure/owners_doc_test.go @@ -124,6 +124,11 @@ func ownerDocs() []ownerDoc { owner: "the finder in `internal/vm/finder.go`, whose `target` finds the VM every command acts on: the folder's own, the nearest parent folder's under `--here` and `--parent` (`resolveFolder`), or one named (`devvm rm VM`). It finds a folder's VM by the state that records the folder (`finder.state`, by the path's hash first, then `recorded`), offers to move a VM whose folder moved there (`moveHere` in `internal/vm/move.go`, the match `here.movedFrom`), and names a new VM by the first of the folder's names whose VM folder is free (`newName`, `project.Nth`). Its `need` says what the command needs of the VM, and `need.check` is the one place that refuses one that isn't there, one made for an earlier folder at its path, one whose remake didn't finish and one whose creation didn't, the last with `refuseUnfinished`, which every start (`starter.bringUp` in `internal/vm/start.go`) makes too. It reads the folder devvm runs in only then, so the commands that act on no folder's VM run in a folder that's gone. The VM it finds is a `target` (`internal/vm/target.go`). It holds what the VM's backend told the finder, which each start and stop of the VM then updates, and it runs what a command does with that VM: `exec`, `shell`, `stop`, `running`, `ownSSH` and the name of its ssh config entry", elsewhere: "`internal/state`, and tests", }, + { + check: "the structure test's `owners`, `hostsafety.Walk`", + owner: "the start in `internal/vm/start.go`, whose `starter.walk` walks a VM's project folder once for each check of the folder on the host, for the git repos nested in it, which `.git` protection goes by (`gitprotect.Protector.Nested`), and on Linux hosts its set-id files, so a check never walks the folder twice. It walks when a VM is made and when a check finds it stopped, at a launch or at `devvm stop` (`starter.hostChecks`), and at `devvm git-protect` on a stopped VM, never at a launch into a running VM", + elsewhere: "`internal/hostsafety`, and tests", + }, { check: "the structure test's `owners`, `state.ReadAll`", owner: "the inventory in `internal/vm/inventory.go`, which reads every VM's state (`ReadStates`), and with `ReadInventory` the backends' lists too, each within its wait, for every listing of VMs: `devvm ls`, `devvm space`, `devvm images` and `devvm gc`, the ssh config, `devvm gc --orphans`, the links, `devvm secret`'s list, finding a VM by its name and the mounts that devvm's SSH agent checks a key against. Its one failure policy is that a backend that can't list fails a listing (`Inventory.Err`) only when some VM's state names it, and that a state that can't be read is a row of its own, which the readers leave out and `ToolsInUse` and `Mounts` fail on. `state.VMNames`, which fails on such a state, stays for the readers below `internal/vm`: `netpolicy`, `ports` and `sshconfig.ChooseAlias`", diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index 1ff1f8ef..e844c98c 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -33,7 +33,7 @@ func devvm() rules { // fake's own types each implement. maxMethods: 24, largeTypes: map[string]large{ - "internal/paths.Dirs": {60, "one method per folder or file devvm uses: a list (a VM's own files are paths.VM's)"}, + "internal/paths.Dirs": {61, "one method per folder or file devvm uses: a list (a VM's own files are paths.VM's)"}, "internal/ui.UI": {46, "the one terminal: messages and where they go, as text or names, the logo, errors with the caller's exit code, prompts and their refusals, whether the picker shows, status line, tables, run log and how many are kept, cleanups, signals"}, }, allowedVars: devvmVars(), @@ -61,7 +61,9 @@ func devvm() rules { // devvm's agent store alone holds what VMs get of the agents: // agentStore its settings, secrets.LoginFile its logins, so // nothing reads them from the home folder. + // The start alone walks a project folder, once per check. callers: map[string]string{ + "internal/hostsafety.Walk": "internal/vm/start.go", "internal/state.ReadHash": "internal/vm/finder.go", "internal/project.Parents": "internal/vm/finder.go", "internal/state.ReadAll": "internal/vm/inventory.go", diff --git a/internal/vm/clone.go b/internal/vm/clone.go index c2703f12..54168d71 100644 --- a/internal/vm/clone.go +++ b/internal/vm/clone.go @@ -760,7 +760,10 @@ func (e remaking) leftBehind(ctx context.Context, t *target, clone string) error // section keeps the remote's name, for putBack (unmountFolder). func (e remaking) mountFolder(ctx context.Context, t *target) error { e.clones.removeRemote(ctx, t.f.Dir, t.f.Name, sectionOf[cloneInVM](t.st, cloneSection).Made.Remote) - return e.Protector(t.f.Dir).NewVM(ctx, t.st) + p := e.Protector(t.f.Dir) + found := e.starter.walk(t.f.Dir, false) + p.Nested = &found.Repos + return p.NewVM(ctx, t.st) } // unmountFolder undoes mountFolder, once putBack has deleted the new diff --git a/internal/vm/env.go b/internal/vm/env.go index 8634fed5..2f193d10 100644 --- a/internal/vm/env.go +++ b/internal/vm/env.go @@ -160,7 +160,26 @@ func NewEnv(d paths.Dirs, assets fs.FS, self, version string, reg *backend.Regis PortInUse: platform.PortInUse, Forwarders: vmssh.NewForwards(d, reg.Review, self), PublicImage: from.NewLookup(d, r, tl.Proxy).Public, FreeSpace: reg.Host.FreeSpace, } locker := sync.OnceValue(func() gitprotect.Locker { return gitprotect.HostLocker(canPin(reg)) }) - e.Protector = func(dir string) *gitprotect.Protector { return gitprotect.New(dir, d.Home, locker(), e.Reporter) } + e.Protector = func(dir string) *gitprotect.Protector { + p := gitprotect.New(dir, d.Home, locker(), e.Reporter) + p.Kept = func(vm string) func(string) msg.M { + inv, err := ReadStates(d) + if err != nil { + // What another VM protects, devvm can't tell: all stays. + return func(string) msg.M { return msg.GitKeptUnread(d.VMs()).Because(err) } + } + return inv.GitKeeper(vm) + } + p.Serial = func(ctx context.Context, f func() error) error { + unlock, err := platform.LockFile(ctx, d.GitLock()) + if err != nil { + return err + } + defer unlock() + return f() + } + return p + } e.Links = func(st *state.VM) ([]GuestLink, error) { return guestLinks(d, st) } e.Agent = sshagent.New(d, e.mounts, r) return wire(e) diff --git a/internal/vm/inventory.go b/internal/vm/inventory.go index 1aadd11a..5f9cdafb 100644 --- a/internal/vm/inventory.go +++ b/internal/vm/inventory.go @@ -4,10 +4,13 @@ import ( "cmp" "context" "maps" + "path/filepath" "slices" "time" "github.com/devvmhq/devvm/internal/backend" + "github.com/devvmhq/devvm/internal/gitprotect" + "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/paths" "github.com/devvmhq/devvm/internal/platform" "github.com/devvmhq/devvm/internal/project" @@ -223,6 +226,34 @@ func (inv *Inventory) States() []*state.VM { return out } +// GitKeeper is, for the VM self, whether another VM's .git protection +// keeps a path locked too (gitprotect.Keeps), as the warning that says +// so, or a zero msg.M, so self's unlock leaves the path locked +// (gitprotect.Protector.Kept). A parent folder's VM protects the repos +// nested in its folder, and a nested repo's own VM its own. A state that +// can't be read keeps every path in the folder whose hash names its +// folder (project.Hash), as it may protect them: what it protects, devvm +// can't tell. +func (inv *Inventory) GitKeeper(self string) func(path string) msg.M { + states := inv.States() + unread := inv.Unreadable() + return func(path string) msg.M { + for _, st := range states { + if st.Name() != self && gitprotect.Keeps(st, path) { + return msg.GitKeptLocked(st.Name()) + } + } + for _, k := range unread { + for d := path; d != "/" && d != "."; d = filepath.Dir(d) { + if project.Hash(d) == k.Hash { + return msg.GitKeptUnread(k.Path) + } + } + } + return msg.M{} + } +} + // Unreadable are the VMs whose vm.json can't be read. func (inv *Inventory) Unreadable() []Known { var out []Known diff --git a/internal/vm/inventory_test.go b/internal/vm/inventory_test.go index 9b562ccb..a6360c5c 100644 --- a/internal/vm/inventory_test.go +++ b/internal/vm/inventory_test.go @@ -12,9 +12,11 @@ import ( "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/backend/backendtest" + "github.com/devvmhq/devvm/internal/gitprotect" "github.com/devvmhq/devvm/internal/msg" "github.com/devvmhq/devvm/internal/paths" "github.com/devvmhq/devvm/internal/platform" + "github.com/devvmhq/devvm/internal/project" "github.com/devvmhq/devvm/internal/sshagent" "github.com/devvmhq/devvm/internal/state" "github.com/devvmhq/devvm/internal/tools" @@ -351,3 +353,46 @@ func TestFolderWithin(t *testing.T) { t.Errorf("an answer in time = %v", got) } } + +// A VM's unlock leaves what another VM's .git protection covers, and what +// a VM whose state can't be read may: every path in the folder its state's +// folder is named after. +func TestGitKeeper(t *testing.T) { + d := paths.Dirs{Data: t.TempDir()} + parent, err := state.New(d, "devvm-ws-0123456789abcd") + if err != nil { + t.Fatal(err) + } + parent.Image, parent.Dir, parent.Backend = "base", "/p/ws", "fake" + if err := parent.Create(t.Context(), nil); err != nil { + t.Fatal(err) + } + g := gitprotect.InVM{Mode: gitprotect.On, Made: gitprotect.Made{Protected: true, Nested: true, Repos: map[string]gitprotect.Repo{"a": {}}}} + if err := parent.Update(t.Context(), func(st *state.VM) error { return gitprotect.Set(st, g) }); err != nil { + t.Fatal(err) + } + broken := d.VMDir(project.Hash("/q/other")) + if err := os.MkdirAll(broken, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(paths.VM{Dir: broken}.State(), []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + inv, err := ReadStates(d) + if err != nil { + t.Fatal(err) + } + k := inv.GitKeeper("devvm-a-0123456789abce") + for path, want := range map[string]string{ + "/p/ws/a/.git/config": "git_kept_locked vm=devvm-ws-0123456789abcd", + "/p/ws/b/.git/config": "", + "/q/other/x/.git/config": "git_kept_unread state=" + paths.VM{Dir: broken}.State(), + } { + if got := k(path); got.ID() != "" && got.Names() != want || got.ID() == "" && want != "" { + t.Errorf("%s: %q, want %q", path, got.Names(), want) + } + } + if inv.GitKeeper("devvm-ws-0123456789abcd")("/p/ws/a/.git/config").ID() != "" { + t.Error("its own protection keeps it") + } +} diff --git a/internal/vm/settings.go b/internal/vm/settings.go index 1563adb9..f1f30c77 100644 --- a/internal/vm/settings.go +++ b/internal/vm/settings.go @@ -72,6 +72,12 @@ func (e Settings) SetGitProtect(ctx context.Context, mode string) error { return e.restartOr(ctx, vm, e.Info, msg.GitProtectNextStop(mode, vm)) } } + // The VM is stopped, or the host has no locks to race: on and strict + // name the nested repos the protection doesn't cover. + if mode != gitprotect.Off { + found := e.starter.walk(t.f.Dir, false) + p.Nested = &found.Repos + } return setGitProtect(ctx, e.Env, p, t, mode) } @@ -82,12 +88,13 @@ func setGitProtect(ctx context.Context, e *Env, p *gitprotect.Protector, t *targ if err := p.Set(ctx, t.st, mode); err != nil { return err } + g, _ := gitprotect.Of(t.st) switch _, err := os.Lstat(filepath.Join(t.f.Dir, ".git")); { case mode == gitprotect.Off && !p.Locker.Locks(): e.Info(msg.GitUnprotectedQuiet(vm)) case mode == gitprotect.Off: e.Info(msg.GitUnlocked(vm)) - case err != nil: + case err != nil && len(g.Made.Repos) == 0: e.Info(msg.GitLockLater(vm)) case mode == gitprotect.Strict: e.Info(msg.GitLockedStrict(vm)) diff --git a/internal/vm/start.go b/internal/vm/start.go index 5aca1e76..fbf69069 100644 --- a/internal/vm/start.go +++ b/internal/vm/start.go @@ -411,13 +411,19 @@ func (s starter) refuse(b backend.Backend, vm string, fs []backend.Feature) erro // without locks, what changed of what a lock would cover), and once it's // stopped, what its pins recorded first (gitprotect's ReportPinEvents); // then the protection chosen while it ran is set, and its set-id files -// are named (not while it runs: the walk is slow). devvm stop does the -// latter too. +// are named. Both a new VM's checks and a stopped one's go by one walk of +// the folder (walk), which finds its nested repos too (not while it runs: +// the walk is slow). devvm stop does the latter too. func (s starter) hostChecks(ctx context.Context, t *target, running, made bool) error { if isClone(t.st) { return nil } p := s.Protector(t.f.Dir) + var found hostsafety.Found + if made || !running { + found = s.walk(t.f.Dir, s.OS == "linux") + p.Nested = &found.Repos + } if made { if err := p.NewVM(ctx, t.st); err != nil { return err @@ -426,13 +432,13 @@ func (s starter) hostChecks(ctx context.Context, t *target, running, made bool) s.Warn(msg.SSHRemoteHint(t.f.Name)) } // Files an earlier VM of this folder made are named too. - s.checkSetID(t.f.Dir) + s.warnSetID(found.SetID) return nil } if !running { // What the VM's runs recorded of its pins, now it's stopped, named // even when the check that follows refuses. - p.ReportPinEvents(s.Dirs.VM(t.f.Name).GitPins(), t.f.Name) + p.ReportPinEvents(s.Dirs.VM(t.f.Name).GitPins(".jsonl"), t.f.Name) } if err := p.Check(ctx, t.st, running); err != nil { return err @@ -445,19 +451,22 @@ func (s starter) hostChecks(ctx context.Context, t *target, running, made bool) return err } } - s.checkSetID(t.f.Dir) + s.warnSetID(found.SetID) return nil } -// checkSetID names set-id files in the folder on Linux hosts, where they -// reach the host (macOS's virtiofs drops the bits): those running as root -// apart. -func (s starter) checkSetID(dir string) { - if s.OS != "linux" { - return - } +// walk walks the VM's project folder dir once (hostsafety.Walk), for the +// git repos nested in it, and with setID, its set-id files: on Linux +// hosts, where their bits reach the host (macOS's virtiofs drops them). +func (s starter) walk(dir string, setID bool) hostsafety.Found { + return hostsafety.Walk(dir, setID) +} + +// warnSetID names the set-id files the walk found in the folder, those +// running as root apart. +func (s starter) warnSetID(files []hostsafety.SetIDFile) { var root, other []string - for _, f := range hostsafety.SetIDFiles(dir) { + for _, f := range files { if f.Root { root = append(root, f.Path) } else { @@ -596,7 +605,8 @@ func (s starter) pins(ctx context.Context, t *target) (backend.Pins, error) { if err != nil { return backend.Pins{}, err } - p := backend.Pins{Root: t.f.Dir, Fixed: fixed, ReadOnly: readOnly, Events: s.Dirs.VM(t.f.Name).GitPins()} + v := s.Dirs.VM(t.f.Name) + p := backend.Pins{Root: t.f.Dir, Fixed: fixed, ReadOnly: readOnly, Events: v.GitPins(".jsonl"), File: v.GitPins(".json")} if _, err := os.Lstat(filepath.Join(t.f.Dir, ".git")); err == nil && len(readOnly) == 0 { s.Warn(msg.GitPinsNone(t.f.Name)) } diff --git a/internal/vm/sync.go b/internal/vm/sync.go index 66ef3ccd..2bb46c8f 100644 --- a/internal/vm/sync.go +++ b/internal/vm/sync.go @@ -582,8 +582,18 @@ func hostTZ() string { return strings.TrimSpace(string(b)) } -// gitConfig is git's setting for key in dir, or "". +// gitConfig is git's setting for key in dir, or "". When devvm's +// environment names the user's own config files (GIT_CONFIG_GLOBAL and +// the rest), which host git ignores, it's the repo's own setting, else +// theirs, read by name (hostgit.UserConfig). func gitConfig(ctx context.Context, dir, key string) string { + if f := hostgit.UserFilesOf(os.Getenv); f != (hostgit.UserFiles{}) { + if out, err := hostgit.Output(ctx, "-C", dir, "config", "--local", "--get", key); err == nil { + return strings.TrimRight(string(out), "\n") + } + v, _ := hostgit.UserConfig(ctx, key) + return v + } cmd := hostgit.Command(ctx, "config", "--get", key) cmd.Dir = dir out, err := cmd.Output() diff --git a/internal/vm/teardown_test.go b/internal/vm/teardown_test.go index cb5af62a..7d350c1d 100644 --- a/internal/vm/teardown_test.go +++ b/internal/vm/teardown_test.go @@ -21,7 +21,7 @@ func everyFile(t *testing.T, e *Env, vm string) { t.Helper() v := e.Dirs.VM(vm) for _, p := range []string{ - v.Policy(), v.Proxy(".pid"), v.ProxyConfig(), v.Proxy(".status"), v.GitPins(), v.Profile(), v.Started(), v.Secrets(), v.SecretsPolicy(), + v.Policy(), v.Proxy(".pid"), v.ProxyConfig(), v.Proxy(".status"), v.GitPins(".jsonl"), v.GitPins(".json"), v.Profile(), v.Started(), v.Secrets(), v.SecretsPolicy(), v.LinksPID(), v.LinkList(), v.EventLog(), v.EventLog() + ".1", v.ProxyLog(), v.LinksLog(), v.Forwarder(".known_hosts"), v.Forwarder(".log"), v.Forwarder(".lock"), filepath.Join(v.Run(), ".proxy.json.tmp-1"), // a write that never finished diff --git a/locales/en.toml b/locales/en.toml index 0245f082..87ba6a39 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -206,6 +206,9 @@ other = "The newest devvm release is {{.latest}}, as of {{.date}}." description = "reason is an error from the system, in English" other = "Checking what devvm needs failed: {{.reason}}." +[doctor_git_bare] +other = "Tip: run git config --global safe.bareRepository explicit, so git on this machine uses a bare repo only when you name it. Then a folder that a VM makes look like a git folder can't take over git in the folders below it." + [doctor_pins_apparmor] other = "AppArmor on this machine keeps devvm out of the user namespace it locks .git in, so devvm only watches .git here. To keep a VM out of .git, use devvm --clone." @@ -2188,6 +2191,73 @@ description = "paths is a comma-separated list of paths relative to the project one = "WARNING: Each of {{.paths}} and 1 more path is a symlink, under one, or past what devvm reads, so the VM can change what git on this machine runs from it without devvm naming the change. Check them before you run git here, or use devvm --clone." other = "WARNING: Each of {{.paths}} and {{.count}} more paths is a symlink, under one, or past what devvm reads, so the VM can change what git on this machine runs from it without devvm naming the change. Check them before you run git here, or use devvm --clone." +[git_nested_unprotected] +description = "repos is a comma-separated list of folders relative to the project folder" +other = "WARNING: .git protection doesn't cover the git repos nested in this folder at {{.repos}}, so {{.vm}} can change their hooks and config, which git on this machine runs. Check them before you run git there." + +[git_nested_unprotected_more] +description = "repos is a comma-separated list of folders relative to the project folder; count is how many more there are" +one = "WARNING: .git protection doesn't cover the git repos nested in this folder at {{.repos}} and 1 more folder, so {{.vm}} can change their hooks and config, which git on this machine runs. Check them before you run git there." +other = "WARNING: .git protection doesn't cover the git repos nested in this folder at {{.repos}} and {{.count}} more folders, so {{.vm}} can change their hooks and config, which git on this machine runs. Check them before you run git there." + +[git_nested_past_bound] +description = "count is how many repos past the bound there are; repos is a comma-separated list of the first of them, relative to the project folder" +one = "WARNING: .git protection covers the first 100 git repos nested in this folder, and not 1 more, {{.repos}}, so {{.vm}} can change its hooks and config, which git on this machine runs. Move the repos you don't use out of this folder." +other = "WARNING: .git protection covers the first 100 git repos nested in this folder, and not {{.count}} more, such as {{.repos}}, so {{.vm}} can change their hooks and config, which git on this machine runs. Move the repos you don't use out of this folder." + +[git_nested_protectable] +description = "repos is a comma-separated list of folders relative to the project folder" +other = "WARNING: {{.vm}}'s .git protection doesn't cover the git repos nested in this folder at {{.repos}}, so the VM can change their hooks and config, which git on this machine runs. Run devvm git-protect on to protect them too, as devvm does for new VMs." + +[git_nested_protectable_more] +description = "repos is a comma-separated list of folders relative to the project folder; count is how many more there are" +one = "WARNING: {{.vm}}'s .git protection doesn't cover the git repos nested in this folder at {{.repos}} and 1 more folder, so the VM can change their hooks and config, which git on this machine runs. Run devvm git-protect on to protect them too, as devvm does for new VMs." +other = "WARNING: {{.vm}}'s .git protection doesn't cover the git repos nested in this folder at {{.repos}} and {{.count}} more folders, so the VM can change their hooks and config, which git on this machine runs. Run devvm git-protect on to protect them too, as devvm does for new VMs." + +[git_nested_appeared] +description = "repo is a folder relative to the project folder" +other = "WARNING: A git repo appeared at {{.repo}} while {{.vm}} could write this folder, so the VM may have made it. devvm protects it from now on, but check its hooks and config before you run git there." + +[git_nested_gone] +description = "repo is a folder relative to the project folder" +other = "WARNING: The git repo at {{.repo}} that devvm protected is gone or moved, perhaps by {{.vm}}. If you didn't move it, check where it went before you run git there." + +[git_nested_appeared_runs] +description = "repo is a folder relative to the project folder; runs is a comma-separated list of config keys and hooks that run programs" +other = "WARNING: A git repo appeared at {{.repo}} while {{.vm}} could write this folder, and its {{.runs}} run programs on this machine. devvm protects it as it is from now on, so check them before you run git there." + +[git_nested_gitdir_outside] +description = "repo is a folder relative to the project folder; git is the git folder its .git names" +other = "The git repo at {{.repo}} keeps its git folder outside the project, at {{.git}}, so devvm can't lock it. git on this machine still reads its config there." + +[git_nested_bare] +description = "dirs is a comma-separated list of folders relative to the project folder" +other = "WARNING: {{.dirs}} in this folder look like git folders, which git run below them can take for its repo, and {{.vm}} can change them. Check them before you run git there, and see devvm doctor for git's safe.bareRepository." + +[git_nested_skipped] +description = "count is how many repos the walk saw where it doesn't protect them" +one = "WARNING: devvm doesn't protect 1 git repo in this folder, as it's deeper than four folders or in a folder such as node_modules, so {{.vm}} can change its hooks and config. Check it before you run git there." +other = "WARNING: devvm doesn't protect {{.count}} git repos in this folder, as they're deeper than four folders or in folders such as node_modules, so {{.vm}} can change their hooks and config. Check them before you run git there." + +[git_nested_devices] +description = "count is how many folders are on another file system" +one = "WARNING: devvm doesn't look for git repos in 1 folder of this folder that's on another disk, so {{.vm}} can change the hooks and config of any repo there. Check it before you run git there." +other = "WARNING: devvm doesn't look for git repos in {{.count}} folders of this folder that are on another disk, so {{.vm}} can change the hooks and config of any repo there. Check them before you run git there." + +[git_scan_bounded] +other = "WARNING: devvm stopped following the submodules of {{.git}} after 1,000 git folders, so it doesn't lock the rest. Check them before you run git there, or move the repos you don't use out of this folder." + +[git_kept_unread] +description = "state is the VM state file, or the folder of them, that can't be read" +other = "Some of .git's locks stay on, as devvm can't read {{.state}}, the state of a VM that may protect the same repos. Fix or remove that VM's state, then run this again." + +[git_locks_left] +description = "repos is a comma-separated list of folders relative to the project folder" +other = "WARNING: devvm locked the .git of the git repos at {{.repos}}, which aren't in this folder any more, so it can't take their locks off. If you moved them, run chflags -R nouchg on their .git/hooks and .git/config." + +[git_kept_locked] +other = "Some of .git's locks stay on, as {{.vm}}'s .git protection covers the same repos. Run devvm git-protect off in that VM's folder to take them off too." + [no_vm_git_protect] other = "There's no VM for {{.dir}}. Run devvm to make one, or devvm --no-git-protect to make one without .git protection." diff --git a/testdata/script/doctor.txtar b/testdata/script/doctor.txtar index 5788d12a..6f6a8316 100644 --- a/testdata/script/doctor.txtar +++ b/testdata/script/doctor.txtar @@ -26,8 +26,20 @@ stdout '^doctor_ok backend=lima version=\S+\n\z' ! stderr . stub_calls stdout '^limactl --version\n\z' + +# git that takes any folder shaped like a git folder for a bare repo gets +# a tip, which isn't a warning, and --json lists it apart; the sandbox's +# own git takes one only when it's named. +exec git config --global --unset safe.bareRepository +exec devvm doctor +stdout '^doctor_git_bare$' +! stderr . exec devvm doctor --json -stdout '^{\n "version": 1,\n "backend": "lima",\n "problems": \[\],\n "warnings": \[\],\n "docker": true,\n' +stdout '^ "tips": \[\n "doctor_git_bare"\n \],$' +exec git config --global safe.bareRepository explicit + +exec devvm doctor --json +stdout '^{\n "version": 1,\n "backend": "lima",\n "problems": \[\],\n "warnings": \[\],\n "tips": \[\],\n "docker": true,\n' stdout '^ "ports": "emulated",$' ! stderr . diff --git a/testdata/script/git_nested.txtar b/testdata/script/git_nested.txtar new file mode 100644 index 00000000..142e1729 --- /dev/null +++ b/testdata/script/git_nested.txtar @@ -0,0 +1,85 @@ +# The git repos nested in a VM's folder get .git protection as the +# folder's own repo does, in a folder of repos without one of its own +# too: on macOS they're locked, and on a host without locks they're +# watched. The walk that finds them, when the VM is made and when a check +# finds it stopped, looks no deeper than four folders, and not in a +# package manager's folder, such as node_modules. The chflags stub changes +# no flags. +env GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t + +project ws +exec git init -q a +exec git init -q b/c +exec git init -q node_modules/x +exec git init -q deep/1/2/3/4 +exec devvm --network open +vm_name WS ws +! stderr 'git_nested_(unprotected|appeared|bare|gone)' +[linux] stderr '^devvm: git_unprotected vm=devvm-ws-[0-9a-f]{14}$' +# On Linux, the walk for set-id files sees the repos it skips, and counts +# them; on macOS it doesn't enter their folders. +[linux] stderr '^devvm: git_nested_skipped count=2 vm=devvm-ws-[0-9a-f]{14}$' +[darwin] ! stderr git_nested_skipped +[darwin] stub_calls +[darwin] stdout '^chflags -R -P uchg /\S*/ws/a/\.git/config$' +[darwin] stdout '^chflags -R -P uchg /\S*/ws/b/c/\.git/hooks$' +[darwin] ! stdout 'node_modules|deep' +vm_state $WS_dir/vm.json +stdout '^git.made.nested=true$' +stdout '^git.made.repos.a.git_id=[0-9]+:[0-9]+' +stdout '^git.made.repos.b/c.git_id=[0-9]+:[0-9]+' +! stdout 'repos.node_modules|repos.deep' + +# A repo made while the VM runs: a launch into it walks nothing, and +# devvm stop names it and protects it from then on. +exec git init -q d +exec devvm +! stderr git_nested +stub_reset +exec devvm stop +stderr '^devvm: git_nested_appeared repo=d vm=devvm-ws-[0-9a-f]{14}$' +[darwin] stub_calls +[darwin] stdout '^chflags -R -P uchg /\S*/ws/d/\.git/config$' +vm_state $WS_dir/vm.json +stdout '^git.made.repos.d.git_id=' + +# On a host without locks, the watch names what changed in one. +[linux] exec git -C a config core.fsmonitor ./evil +[linux] exec devvm stop +[linux] stderr '^devvm: git_changed paths=a/\.git/config vm=devvm-ws-[0-9a-f]{14}$' + +# A VM whose protection covers its own repo alone, as an older devvm's +# does, is told once that devvm git-protect on protects them. +[linux] stop 'devvm git-protect on needs locks' +json_set $WS_dir/vm.json git.made.nested:=false git.made.repos:=null +exec devvm stop +stderr '^devvm: git_nested_protectable repos=a, b/c, d vm=devvm-ws-[0-9a-f]{14}$' +exec devvm stop +! stderr git_nested +exec devvm git-protect on +stdout '^==> git_locked vm=devvm-ws-[0-9a-f]{14}$' +vm_state $WS_dir/vm.json +stdout '^git.made.nested=true$' +stdout '^git.made.repos.d.git_id=' + +# devvm rm unlocks them. +stub_reset +exec devvm rm --force --no-export +stub_calls +stdout '^chflags -R -P nouchg /\S*/ws/a/\.git/config$' + +# A nested repo with a VM of its own: the parent folder's VM locks it +# too, and its rm leaves the locks the nested VM holds. +project parent git +exec git init -q child +cd child +exec devvm --network open +vm_name CHILD child +cd .. +exec devvm --here --network open +stub_reset +exec devvm rm --force --no-export +stderr '^devvm: git_kept_locked vm=devvm-child-[0-9a-f]{14}$' +stub_calls +stdout '^chflags -R -P nouchg /\S*/parent/\.git/config$' +! stdout 'nouchg /\S*/child/' diff --git a/testdata/script/publish.txtar b/testdata/script/publish.txtar index 0089af02..6a141402 100644 --- a/testdata/script/publish.txtar +++ b/testdata/script/publish.txtar @@ -137,7 +137,7 @@ cmp stdout assets.want cmp gh/notes notes.want cmp tap/Formula/devvm.rb repo/dist/devvm.rb cmp tap/Formula/devvm-rc.rb repo/dist/devvm-rc.rb -exec git -C tap.git log -1 --format=%s main +exec git --git-dir=tap.git log -1 --format=%s main stdout '^devvm 1\.2\.3$' # And once more: everything's done, so it asks nothing. @@ -178,9 +178,9 @@ stdout '^Check it with Homebrew, brew update && brew upgrade devvm-rc \(or brew cmp calls calls.pre exists gh/prerelease cmp gh/notes notes.pre -exec git -C tap.git log -1 --format=%s main +exec git --git-dir=tap.git log -1 --format=%s main stdout '^devvm-rc 1\.3\.0-rc\.1$' -exec git -C tap.git show --name-only --format= main +exec git --git-dir=tap.git show --name-only --format= main cmp stdout rc.changed cmp tap/Formula/devvm-rc.rb repo/dist/devvm-rc.rb grep 'download/v1\.2\.3/' tap/Formula/devvm.rb @@ -209,7 +209,7 @@ rm calls ttyin -stdin yes.txt exec repo/scripts/publish.sh stdout '^==> the tap''s Formula/devvm\.rb$' -exec git -C tap.git show --name-only --format= main +exec git --git-dir=tap.git show --name-only --format= main stdout '^Formula/devvm\.rb\n\z' grep 'download/v1\.3\.0-rc\.1/' tap/Formula/devvm-rc.rb @@ -239,9 +239,9 @@ stdout '^\+ url "https://github.com/devvmhq/devvm/releases/download/v1\.3\. rm calls ttyin -stdin yes.txt exec repo/scripts/publish.sh -exec git -C tap.git log -1 --format=%s main +exec git --git-dir=tap.git log -1 --format=%s main stdout '^devvm 1\.3\.0$' -exec git -C tap.git show --name-only --format= main +exec git --git-dir=tap.git show --name-only --format= main cmp stdout both.changed cmp tap/Formula/devvm.rb repo/dist/devvm.rb cmp tap/Formula/devvm-rc.rb repo/dist/devvm-rc.rb @@ -329,10 +329,10 @@ bash tag.sh good "v$1" -- refs.sh -- # What origin and the tap hold: main's commit message, the tag, the tap's # last commit, and whether it has the formula. -git -C origin.git log -1 --format=%s main -git -C origin.git tag -l -git -C tap.git log -1 --format=%s main -f=$(git -C tap.git ls-tree --name-only main Formula/ | paste -sd' ' -) +git --git-dir=origin.git log -1 --format=%s main +git --git-dir=origin.git tag -l +git --git-dir=tap.git log -1 --format=%s main +f=$(git --git-dir=tap.git ls-tree --name-only main Formula/ | paste -sd' ' -) echo "formulas: ${f:-none}" -- refs.before -- r diff --git a/testdata/script/qemu.txtar b/testdata/script/qemu.txtar index 2dfd0535..697cf93f 100644 --- a/testdata/script/qemu.txtar +++ b/testdata/script/qemu.txtar @@ -31,8 +31,12 @@ stdout '^user,id=net0,net=192.168.5.0/24\n' ! stdout restrict env DEVVM_QEMU_NET= -# Pins that aren't what devvm writes: QEMU doesn't run. -env DEVVM_QEMU_PINS='{"root":"/p","pins":[{"path":"../x"}]}' +# Pins that aren't what devvm writes, in their file or as the variable: +# QEMU doesn't run. +env DEVVM_QEMU_PINS=$WORK/bad-pins.json +! exec wrap/qemu-system-aarch64 -m 4G -netdev user,id=net0,net=192.168.5.0/24 +! stdout . +env DEVVM_QEMU_PINS='{"root":"/p","pins":[{"path":".git"}]}' ! exec wrap/qemu-system-aarch64 -m 4G -netdev user,id=net0,net=192.168.5.0/24 ! stdout . env DEVVM_QEMU_PINS= @@ -69,3 +73,5 @@ virtio-net-pci,netdev=net0 none -netdev help +-- bad-pins.json -- +{"root":"/p","pins":[{"path":"../x"}]} diff --git a/tests/e2e/gitpins_test.go b/tests/e2e/gitpins_test.go index a3565ca2..8d8bd043 100644 --- a/tests/e2e/gitpins_test.go +++ b/tests/e2e/gitpins_test.go @@ -3,6 +3,7 @@ package e2e import ( + "encoding/json" "errors" "fmt" "os" @@ -38,7 +39,7 @@ func pinnedProcs(p, vm string) map[int]bool { args := string(cmd) ns, _ := os.Readlink(filepath.Join("/proc", e.Name(), "ns", "mnt")) qemu := strings.Contains(args, "qemu-system") && strings.Contains(args, "/"+vm+"/") && !strings.Contains(args, "_qemu") && ns != self - keeper := strings.Contains(args, "_qemu\x00keep") && strings.Contains(string(env), `"root":"`+p+`"`) + keeper := strings.Contains(args, "_qemu\x00pinned") && pinsRoot(string(env)) == p if qemu || keeper { out[pid] = qemu } @@ -46,6 +47,26 @@ func pinnedProcs(p, vm string) map[int]bool { return out } +// pinsRoot is the project folder whose pins a process's environment env +// (/proc/PID/environ) names: the root in the file DEVVM_QEMU_PINS holds; +// "" for none. +func pinsRoot(env string) string { + for kv := range strings.SplitSeq(env, "\x00") { + if f, ok := strings.CutPrefix(kv, "DEVVM_QEMU_PINS="); ok && f != "" { + b, err := os.ReadFile(f) + if err != nil { + return "" + } + var set struct { + Root string `json:"root"` + } + _ = json.Unmarshal(b, &set) + return set.Root + } + } + return "" +} + func projectGitPins(s *S, w *webVM) { p, vm := w.p, w.vm s.Check("QEMU runs in a namespace that pins .git's hooks and config read-only, with no capability", func() error { diff --git a/tests/e2e/nestedrepos_test.go b/tests/e2e/nestedrepos_test.go new file mode 100644 index 00000000..8b4112fb --- /dev/null +++ b/tests/e2e/nestedrepos_test.go @@ -0,0 +1,164 @@ +//go:build e2e + +package e2e + +import ( + "errors" + "path/filepath" + "runtime" +) + +// projectNestedRepos: a folder of two git repos, without one of its own, +// gets a VM whose .git protection covers both: on macOS and on a Linux +// host that pins, root in the VM can't change either repo's hooks or +// config; on a Linux host that can't pin, devvm stop names the config the +// VM changed. devvm rm takes the locks off both. +func projectNestedRepos(s *S) { + s.Section("the git repos nested in a VM's folder") + ws, err := s.NewProject("nested-repos") + if err != nil { + s.Check("a folder of repos", func() error { return err }) + return + } + for _, r := range []string{"repo-a", "repo-b"} { + _, _ = s.Run(Cmd{Args: []string{"git", "init", "-q", filepath.Join(ws, r)}}) + _, _ = s.Run(Cmd{Args: []string{"git", "-C", filepath.Join(ws, r), "-c", "user.email=e@e", "-c", "user.name=e", "commit", "-q", "--allow-empty", "-m", "x"}}) + } + vm, _, _ := s.Launch(ws, "exit", "--network", "open") + pinned := s.Paths.State(vm)["git.mode"] == "on" + if runtime.GOOS == "darwin" || pinned { + nestedReposLocked(s, ws, vm) + } else { + nestedReposWatched(s, ws, vm) + } + nestedReposPlanted(s, ws, vm, runtime.GOOS == "darwin" || pinned) + s.Check("devvm rm takes the locks off both repos", func() error { + if _, err := s.Devvm(ws, "rm", "--force", "--no-export"); err != nil { + return err + } + for _, r := range []string{"repo-a", "repo-b"} { + if Locked(s, filepath.Join(ws, r, ".git", "config")) { + return errors.New(r + "'s .git is still locked") + } + } + return nil + }) +} + +// nestedReposLocked: root in the VM can't add a hook or change the config +// of either nested repo. +func nestedReposLocked(s *S, ws, vm string) { + for _, r := range []string{"repo-a", "repo-b"} { + for _, c := range []struct{ what, script string }{ + {"add a hook", "echo x > .git/hooks/pre-commit"}, + {"change the config", "echo '[core]' >> .git/config && echo ' fsmonitor = ./evil' >> .git/config"}, + } { + s.Check("root in the VM can't "+c.what+" in "+r, func() error { + dir := filepath.Join(ws, r) + if _, err := s.Limactl("shell", "--workdir", "/", vm, "sudo", "sh", "-c", "cd "+dir+" && "+c.script); err == nil { + return errors.New("root could " + c.what) + } + if g, _ := s.Run(Cmd{Args: []string{"git", "config", "--file", ".git/config", "core.fsmonitor"}, Dir: dir}); Trim(g.Stdout) != "" { + return errors.New("the config changed: " + g.Stdout) + } + if Exists(filepath.Join(dir, ".git", "hooks", "pre-commit")) { + return errors.New("a hook appeared") + } + return nil + }) + } + } +} + +// nestedReposPlanted: what the VM plants to get git on this machine to +// run its fsmonitor is named, or kept protected, at devvm stop: a repo +// whose .git file names a git folder it made inside a protected repo's +// .git; a protected repo whose objects and refs it renamed, with a +// commondir to that git folder; and on macOS, a .git it renamed .GIT. +// Where the host locks, devvm stop also names the repo as one it doesn't +// protect; elsewhere each launch does. +func nestedReposPlanted(s *S, ws, vm string, locks bool) { + running := func() error { + if _, err := DevvmIn(s, ws, "exit\n", nil); err != nil || s.Status(vm) != "Running" { + return errors.New("it didn't start") + } + return nil + } + s.Check("a repo whose .git names a git folder the VM made in a repo's .git is named at devvm stop", func() error { + if err := running(); err != nil { + return err + } + if _, err := s.InVM(vm, "cd "+ws+` && mkdir -p repo-a/.git/evil/objects repo-a/.git/evil/refs src && + printf 'ref: refs/heads/main\n' > repo-a/.git/evil/HEAD && + printf '[core]\n\tfsmonitor = ./evil\n' > repo-a/.git/evil/config && + echo 'gitdir: ../repo-a/.git/evil' > src/.git`); err != nil { + return err + } + r, err := s.Devvm(ws, "stop") + if err != nil { + return err + } + if !grepF(r.Out, FirstLine(s.Msg("git_nested_appeared_runs", "repo=src", "runs=core.fsmonitor", "vm="+vm))) || + locks && !grepF(r.Out, FirstLine(s.Msg("git_nested_unprotected", "repos=src", "vm="+vm))) { + return errors.New("devvm stop didn't name src:\n" + r.Out) + } + return nil + }) + s.Check("a protected repo whose objects and refs the VM renamed, with a commondir, stays protected", func() error { + if err := running(); err != nil { + return err + } + if _, err := s.InVM(vm, "cd "+ws+"/repo-b/.git && mv objects objects-old && mv refs refs-old && echo ../../repo-a/.git/evil > commondir"); err != nil { + return err + } + r, err := s.Devvm(ws, "stop") + if err != nil { + return err + } + if grepF(r.Out, FirstLine(s.Msg("git_nested_gone", "repo=repo-b", "vm="+vm))) || s.Paths.State(vm)["git.made.repos.repo-b.git_id"] == "" { + return errors.New("repo-b went:\n" + r.Out) + } + return nil + }) + if runtime.GOOS != "darwin" { + return + } + s.Check("on macOS, a .git the VM renamed .GIT stays protected", func() error { + if err := running(); err != nil { + return err + } + // Through another name: the guest finds .GIT already there, the + // same folder on a file system that folds case, and mv won't + // rename a file to itself. + if _, err := s.InVM(vm, "cd "+ws+"/repo-a && mv .git .git-case && mv .git-case .GIT"); err != nil { + return err + } + r, err := s.Devvm(ws, "stop") + if err != nil { + return err + } + if grepF(r.Out, FirstLine(s.Msg("git_nested_gone", "repo=repo-a", "vm="+vm))) || s.Paths.State(vm)["git.made.repos.repo-a.git_id"] == "" || + !Locked(s, filepath.Join(ws, "repo-a", ".GIT", "config")) { + return errors.New("repo-a went, or isn't locked:\n" + r.Out) + } + return nil + }) +} + +// nestedReposWatched: on a Linux host that can't pin, the VM changes a +// nested repo's config, and devvm stop names it. +func nestedReposWatched(s *S, ws, vm string) { + s.Check("on a Linux host that can't pin, devvm stop names a nested repo's config the VM changed", func() error { + if _, err := s.InVM(vm, "printf '[e2e]\\n\\twatched = vm\\n' >> "+ws+"/repo-a/.git/config"); err != nil { + return err + } + r, err := s.Devvm(ws, "stop") + if err != nil { + return err + } + if !grepF(r.Out, s.Msg("git_changed", "paths=repo-a/.git/config", "vm="+vm)) { + return errors.New("devvm stop didn't name repo-a/.git/config:\n" + r.Out) + } + return nil + }) +} diff --git a/tests/e2e/project_test.go b/tests/e2e/project_test.go index 3cf144cb..faba3212 100644 --- a/tests/e2e/project_test.go +++ b/tests/e2e/project_test.go @@ -32,6 +32,7 @@ func projectSection(s *S) { projectPorts(s, w) projectGitProtect(s, w) projectNested(s, w) + projectNestedRepos(s) projectMoved(s, w) projectDevcontainer(s) projectAgents(s)