mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 16:27:33 -10:00
feat(gitprotect): on Linux, warn at each launch and report .git hooks and config that changed (#20)
Linux hosts have no unprivileged immutable flag, so devvm can't lock .git there. It now warns at every launch of a VM that mounts a folder with a .git (git_unprotected), unless it's a --clone VM or the user chose devvm git-protect off (git.chosen), and it names, after the fact, the hooks and config that changed (git_changed). It sums what a lock would cover, .git/commondir, include.path targets and the folder core.hooksPath names, never through a symlink out of the project folder and within bounds (git_watch_blind names what it can't fully watch), at each launch that finds the VM stopped and at devvm stop. A check on such a host runs protect's reports without locking: git_replaced, git_commondir, stray worktrees, git dirs that appeared, core.hooksPath and delegations into the project folder, and a submodule's folder that isn't a git dir (git_gitdir_not_git), in which nothing is created and which the watch doesn't sum as a git dir. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
30 files changed
+1261
-97
No files matched your search
@@ -46,6 +46,20 @@ 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.
|
||||
|
||||
## On Linux hosts
|
||||
|
||||
Linux hosts have no immutable flag that a user can set, so devvm locks nothing there, 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. 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.
|
||||
|
||||
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.
|
||||
|
||||
The watch reads `.git` only when the VM is stopped, so it misses a change the VM made and undid before it stopped. It's a report, not a security boundary.
|
||||
|
||||
The hashes go in the VM's state, in the `git` section's `watched`, by each path relative to the project folder, with `scanned` set once a check has recorded them. devvm records them when it creates the VM, and checks them again on each launch that finds the VM stopped and on `devvm stop`, the same places that check the locks on macOS. Each check names every path whose hash changed, appeared or went since the last one, in one warning, at most ten of them and then how many more (`git_changed_more`), and then records the new hashes. A launch of a running VM checks nothing. A VM whose state has no `watched` yet, such as one an older devvm made, or one that `devvm adopt` gave this folder, records its first hashes without naming anything.
|
||||
|
||||
Each launch also warns that the VM can change `.git` (`git_unprotected`), unless the folder has no `.git` or the VM is a `--clone` VM. The warning stops once the user has chosen the mode, which devvm records as the `git` section's `chosen`: `devvm git-protect off` sets it, and so does `--no-git-protect` when devvm creates the VM.
|
||||
|
||||
## What a lock can't stop
|
||||
|
||||
The VM can rename `.git` and put a new one in its place, add `.git/commondir` to point git at another config, or do the same with a linked worktree's folder in `.git/worktrees`. When devvm creates the VM, and [on each launch](#on-each-launch), it reports a `commondir` that's there, linked worktrees whose `commondir` leads somewhere else, and paths it couldn't lock because they're symlinks. devvm doesn't repair anything, so check what it names before you run git in the folder. When you don't trust what runs in the VM, use [`--clone`](../using/clone.md), which mounts no `.git` at all.
|
||||
|
||||
@@ -71,4 +71,30 @@ The lock covers `.git`, and the VM can still put things elsewhere that git on th
|
||||
|
||||
## Linux hosts
|
||||
|
||||
Linux has no immutable flag that a user can set, so VMs on Linux hosts have no `.git` protection, and the VM can change `.git` hooks and config, which run on the host. devvm says so when it creates a VM for a folder with a `.git`, and it refuses `devvm git-protect on` and `strict`. [`--clone`](../using/clone.md) keeps the VM out of `.git` instead.
|
||||
Linux has no immutable flag that a user can set, so VMs on Linux hosts have no `.git` protection, and the VM can change `.git` hooks and config, which run on the host. devvm refuses `devvm git-protect on` and `strict` there, and [`--clone`](../using/clone.md) keeps the VM out of `.git` instead, so use it for any repo where you don't trust what runs in the VM.
|
||||
|
||||
### The warning at each launch
|
||||
|
||||
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`.
|
||||
|
||||
### When devvm names a change
|
||||
|
||||
devvm can't stop the VM from changing `.git` on a Linux host, but it notices the change afterwards. 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.
|
||||
|
||||
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:
|
||||
|
||||
- `git config --list --show-origin` shows each setting of the repo and the file it comes from. Look for settings that run a program, such as `core.fsmonitor`, `core.hooksPath`, `core.sshCommand`, `core.pager`, `filter.*` and `include.path`.
|
||||
- `ls -la .git/hooks` lists the hooks, and git runs a hook there by its name, such as `pre-commit`, so read every file whose name doesn't end in `.sample`.
|
||||
|
||||
If you find something that you didn't put there, remove it, and use [`--clone`](../using/clone.md) for that repo.
|
||||
|
||||
### What the watch can't see
|
||||
|
||||
The watch isn't a security boundary, and it doesn't stop anything. It compares what's in `.git` when the VM is stopped with what was there at the last check, so it misses a change that the VM made and then undid before it stopped, even though git on this machine may have run the change in between. It also can't fully watch some paths, and it names them at every check until they're gone:
|
||||
|
||||
- **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 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.
|
||||
@@ -20,7 +20,7 @@ These are the things devvm can't do, everywhere, on Linux hosts and on Intel Mac
|
||||
|
||||
## Linux hosts
|
||||
|
||||
- They have no `.git` protection, so use `--clone` there ([details](../safety/git-protection.md#linux-hosts)).
|
||||
- They have no `.git` protection. devvm warns about it at each launch, and it names the `.git` hooks and config that changed, but only after the fact, so use `--clone` there ([details](../safety/git-protection.md#linux-hosts)).
|
||||
- VMs mount the project folder with 9p instead of virtiofs, so file watchers in a VM also miss the VM's own changes in the folder's subfolders, and need polling there ([details](../backends/lima.md#file-watchers)).
|
||||
- Set-id bits that root in a VM sets on files in the project folder reach the host, and devvm names such files when it makes a VM and once a VM is stopped ([what to do](troubleshooting.md#devvm-names-set-id-files)).
|
||||
- devvm keeps your secrets in files under `~/.local/share/devvm/secrets/`, which only you can read, instead of the Keychain ([details](settings.md#devvms-state)).
|
||||
|
||||
@@ -35,12 +35,18 @@ import (
|
||||
const Section = "git"
|
||||
|
||||
// InVM is a VM's .git protection section: its mode, as asked (recorded
|
||||
// before its backend makes it, so it's never unset), the mode chosen
|
||||
// while it ran, and what protecting it found.
|
||||
// before its backend makes it, so it's never unset), whether the user
|
||||
// chose it, the mode chosen while it ran, and what protecting it found;
|
||||
// on hosts without locks, what watching it found.
|
||||
type InVM struct {
|
||||
Mode string `json:"mode"` // On, Strict, Off, or Clone for a --clone VM
|
||||
Next string `json:"next,omitempty"` // the mode chosen while the VM ran, set when it's next stopped
|
||||
Made Made `json:"made,omitzero"`
|
||||
Mode string `json:"mode"` // On, Strict, Off, or Clone for a --clone VM
|
||||
// Chosen is set once the user chose the mode (--no-git-protect,
|
||||
// devvm git-protect), rather than the host: off chosen on a host
|
||||
// without locks quiets the launches' warning (WarnUnprotected).
|
||||
Chosen bool `json:"chosen,omitempty"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// Made is what protecting a VM's .git found, and checks compare with.
|
||||
@@ -115,31 +121,35 @@ func New(dir, home string, r msg.Reporter) *Protector {
|
||||
}
|
||||
}
|
||||
|
||||
// NewMode is the protection a new VM gets, recorded before its backend
|
||||
// makes it: off when asked, or on hosts without locks (saying so when
|
||||
// there's a .git); otherwise on, which NewVM sets up once it's made.
|
||||
func (p *Protector) NewMode(off bool) string {
|
||||
// NewSection is the protection a new VM gets, recorded before its
|
||||
// backend makes it: off when asked (chosen), or on hosts without locks,
|
||||
// whose launches warn (WarnUnprotected); otherwise on, which NewVM sets
|
||||
// up once it's made.
|
||||
func (p *Protector) NewSection(off bool) InVM {
|
||||
switch {
|
||||
case off:
|
||||
return Off
|
||||
return InVM{Mode: Off, Chosen: true}
|
||||
case !p.CanLock:
|
||||
if exists(p.git()) {
|
||||
p.Warn(msg.GitProtectNeedsMacosNew())
|
||||
}
|
||||
return Off
|
||||
return InVM{Mode: Off}
|
||||
}
|
||||
return On
|
||||
return InVM{Mode: On}
|
||||
}
|
||||
|
||||
// NewVM sets up the protection of a VM just made for the folder,
|
||||
// stopped, as its mode says (NewMode): on locks .git and reports what a
|
||||
// lock can't cover.
|
||||
// stopped, as its mode says (NewSection): on locks .git and reports what
|
||||
// a lock can't cover. On a host without locks, it records the watch's
|
||||
// first sums instead, so the next check names what changed since.
|
||||
func (p *Protector) NewVM(ctx context.Context, vm *state.VM) error {
|
||||
g, err := Of(vm)
|
||||
if err != nil || g.Mode != On && g.Mode != Strict || !p.CanLock {
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case !p.CanLock && g.Mode != Clone:
|
||||
return watcher{p}.check(ctx, vm, g)
|
||||
case g.Mode != On && g.Mode != Strict || !p.CanLock:
|
||||
return nil
|
||||
}
|
||||
made, err := p.protect(ctx, g, whyNew, false)
|
||||
made, err := p.protect(ctx, g, whyNew, lockNow)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -178,7 +188,7 @@ func SetNext(ctx context.Context, vm *state.VM, mode string) error {
|
||||
// sets diff.ignoreSubmodules=all in the locked .git/config, which on and
|
||||
// off take out again; off unlocks. On and strict need macOS. Once it's
|
||||
// set, a mode saved for the VM's next stop (SetNext) is dropped: both
|
||||
// are recorded at once.
|
||||
// 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 {
|
||||
g, err := Of(vm)
|
||||
if err != nil {
|
||||
@@ -192,7 +202,7 @@ func (p *Protector) Set(ctx context.Context, vm *state.VM, mode string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return record(ctx, vm, func(g *InVM) { g.Mode, g.Next = Off, "" })
|
||||
return record(ctx, vm, func(g *InVM) { g.Mode, g.Chosen, g.Next = Off, true, "" })
|
||||
}
|
||||
if !p.CanLock {
|
||||
return msg.GitProtectOnNeedsMacos()
|
||||
@@ -207,11 +217,11 @@ func (p *Protector) Set(ctx context.Context, vm *state.VM, mode string) error {
|
||||
}
|
||||
}
|
||||
g.Mode = mode
|
||||
made, err := p.protect(ctx, g, whyOn, false)
|
||||
made, err := p.protect(ctx, g, whyOn, lockNow)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return record(ctx, vm, func(g *InVM) { g.Mode, g.Next, g.Made = mode, "", made })
|
||||
return record(ctx, vm, func(g *InVM) { g.Mode, g.Chosen, g.Next, g.Made = mode, true, "", made })
|
||||
}
|
||||
|
||||
// ignoreSubmodules sets diff.ignoreSubmodules=all in .git/config, or takes
|
||||
@@ -264,13 +274,22 @@ func (p *Protector) warnDelegations(ds []delegation) {
|
||||
// folder when they change. Locks are set only while the VM is stopped
|
||||
// (running), so nothing in it can race them; a running VM gets them at
|
||||
// its next start. A VM whose protection was never set up (its creation
|
||||
// stopped short, or devvm adopt moved it) gets it as a new VM does.
|
||||
// stopped short, or devvm adopt moved it) gets it as a new VM does. On a
|
||||
// host without locks, a stopped VM's .git is watched instead, whatever
|
||||
// its mode: what a lock can't stop is reported all the same, and what a
|
||||
// lock would cover that changed since the last check is named
|
||||
// (watcher.check).
|
||||
func (p *Protector) Check(ctx context.Context, vm *state.VM, running bool) error {
|
||||
g, err := Of(vm)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case g.Mode != On && g.Mode != Strict, !p.CanLock:
|
||||
case !p.CanLock:
|
||||
if running || g.Mode == Clone {
|
||||
return nil
|
||||
}
|
||||
return watcher{p}.check(ctx, vm, g)
|
||||
case g.Mode != On && g.Mode != Strict:
|
||||
return nil
|
||||
case !g.Made.Protected:
|
||||
if running {
|
||||
@@ -278,7 +297,11 @@ func (p *Protector) Check(ctx context.Context, vm *state.VM, running bool) error
|
||||
}
|
||||
return p.NewVM(ctx, vm)
|
||||
}
|
||||
made, err := p.protect(ctx, g, whyCheck, running)
|
||||
h := lockNow
|
||||
if running {
|
||||
h = later
|
||||
}
|
||||
made, err := p.protect(ctx, g, whyCheck, h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -294,12 +317,23 @@ const (
|
||||
whyCheck // a launch of an existing VM
|
||||
)
|
||||
|
||||
// protect locks .git, unless running, and reports what a lock can't stop;
|
||||
// it returns what it found (g's Made, as it is now), for the caller to
|
||||
// how protect treats the locks.
|
||||
type how int
|
||||
|
||||
const (
|
||||
lockNow how = iota // a stopped VM's: lock
|
||||
later // a running VM's: report, and lock at its next stop
|
||||
watching // a host without locks: report, record .git's identity, lock nothing
|
||||
)
|
||||
|
||||
// protect locks .git, as h says, and reports what a lock can't stop; it
|
||||
// returns what it found (g's Made, as it is now), for the caller to
|
||||
// record with the mode it set. A new VM's git dirs are recorded, not
|
||||
// reported; a check reports what changed since the last one, and the
|
||||
// hooks path and delegations only when they change.
|
||||
func (p *Protector) protect(ctx context.Context, rec InVM, w why, running bool) (Made, error) {
|
||||
// hooks path and delegations only when they change. Watching, nothing is
|
||||
// locked, so the hooks in folders a lock would cover aren't news: the
|
||||
// watch names their changes.
|
||||
func (p *Protector) protect(ctx context.Context, rec InVM, w why, h how) (Made, error) {
|
||||
g := p.git()
|
||||
was := rec.Made
|
||||
if !exists(g) {
|
||||
@@ -307,6 +341,10 @@ func (p *Protector) protect(ctx context.Context, rec InVM, w why, running bool)
|
||||
}
|
||||
if w == whyCheck && was.GitID != "" && was.GitID != folderID(g) {
|
||||
p.Warn(msg.GitReplaced(g))
|
||||
if h == watching {
|
||||
// Nothing to lock again: the next check compares with this one.
|
||||
was.GitID = folderID(g)
|
||||
}
|
||||
return was, nil
|
||||
}
|
||||
if isDir(g) && exists(filepath.Join(g, "commondir")) {
|
||||
@@ -333,16 +371,20 @@ func (p *Protector) protect(ctx context.Context, rec InVM, w why, running bool)
|
||||
// Hooks in a hooks folder that isn't locked appeared since the last
|
||||
// lock (there was no folder to lock, or it's a new submodule's), so the
|
||||
// VM may have made them.
|
||||
if w == whyCheck {
|
||||
if w == whyCheck && h != watching {
|
||||
for _, path := range p.paths(ctx, emb) {
|
||||
if filepath.Base(path) == "hooks" && isDir(path) && !isLink(path) && !p.Locked(path) && hasHooks(path) {
|
||||
p.Warn(msg.GitHooksUnlocked(path))
|
||||
}
|
||||
}
|
||||
}
|
||||
if !running {
|
||||
switch h {
|
||||
case lockNow:
|
||||
p.lock(ctx, emb)
|
||||
made.GitID = folderID(g)
|
||||
case watching:
|
||||
made.GitID = folderID(g)
|
||||
case later:
|
||||
}
|
||||
if w != whyCheck {
|
||||
if hp := gitConfig(ctx, filepath.Join(g, "config"), "core.hooksPath"); hp != "" && p.hooksPathInside(hp) {
|
||||
@@ -384,7 +426,7 @@ func (p *Protector) abs(rel []string) []string {
|
||||
func (p *Protector) rel(dirs []string) []string {
|
||||
var out []string
|
||||
for _, d := range dirs {
|
||||
out = append(out, strings.TrimPrefix(d, p.Dir+"/"))
|
||||
out = append(out, relTo(p.Dir, d))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -686,7 +728,7 @@ func commonOf(g string) (string, bool) {
|
||||
// working tree. A path that isn't an existing folder counts by name and
|
||||
// resolved as far as it exists.
|
||||
func (p *Protector) hooksPathInside(hp string) bool {
|
||||
hp = p.expandHome(hp)
|
||||
hp = expandHome(p.Home, hp)
|
||||
if !filepath.IsAbs(hp) {
|
||||
return true
|
||||
}
|
||||
@@ -696,10 +738,10 @@ func (p *Protector) hooksPathInside(hp string) bool {
|
||||
return paths.Within(filepath.Clean(hp), p.Dir) || paths.Within(physicalParent(hp), p.Dir)
|
||||
}
|
||||
|
||||
// expandHome expands ~ as git does.
|
||||
func (p *Protector) expandHome(path string) string {
|
||||
// expandHome expands ~ as git does, to home.
|
||||
func expandHome(home, path string) string {
|
||||
if path == "~" || strings.HasPrefix(path, "~/") {
|
||||
return p.Home + path[1:]
|
||||
return home + path[1:]
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -710,6 +752,7 @@ type delegation struct {
|
||||
kind string // include, hook, outside or notgit
|
||||
where string // the config, the hook, or the submodule's folder
|
||||
target string // the include's path or the hook's link as written, or the git dir
|
||||
path string // what an include leads to, absolute, for the watch
|
||||
}
|
||||
|
||||
// delegations finds what the locked config and hooks hand over to files
|
||||
@@ -729,12 +772,12 @@ func (p *Protector) delegations(ctx context.Context, emb embeds) []delegation {
|
||||
if !ok || len(v) == 0 {
|
||||
continue
|
||||
}
|
||||
path := p.expandHome(string(v))
|
||||
path := expandHome(p.Home, string(v))
|
||||
if !filepath.IsAbs(path) {
|
||||
path = filepath.Join(d, path)
|
||||
}
|
||||
if p.into(path) {
|
||||
out = append(out, delegation{"include", cfg, string(v)})
|
||||
out = append(out, delegation{"include", cfg, string(v), filepath.Clean(path)})
|
||||
}
|
||||
}
|
||||
_ = filepath.WalkDir(filepath.Join(d, "hooks"), func(path string, e fs.DirEntry, err error) error {
|
||||
@@ -750,16 +793,16 @@ func (p *Protector) delegations(ctx context.Context, emb embeds) []delegation {
|
||||
target = filepath.Join(filepath.Dir(path), target)
|
||||
}
|
||||
if p.into(target) {
|
||||
out = append(out, delegation{"hook", path, link})
|
||||
out = append(out, delegation{"hook", path, link, ""})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
for _, o := range emb.outside {
|
||||
out = append(out, delegation{"outside", o[0], o[1]})
|
||||
out = append(out, delegation{"outside", o[0], o[1], ""})
|
||||
}
|
||||
for _, n := range emb.notGit {
|
||||
out = append(out, delegation{"notgit", n[0], n[1]})
|
||||
out = append(out, delegation{"notgit", n[0], n[1], ""})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -59,10 +59,10 @@ func newFixture(t *testing.T, name string) *fixture {
|
||||
}
|
||||
|
||||
// newVM sets up protection as up does for a VM just made: its mode
|
||||
// (NewMode), recorded, then NewVM.
|
||||
// (NewSection), recorded, then NewVM.
|
||||
func (f *fixture) newVM(off bool) error {
|
||||
mode := f.p.NewMode(off)
|
||||
if err := record(f.t.Context(), f.vm, func(g *InVM) { g.Mode = mode }); err != nil {
|
||||
n := f.p.NewSection(off)
|
||||
if err := record(f.t.Context(), f.vm, func(g *InVM) { g.Mode, g.Chosen = n.Mode, n.Chosen }); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.p.NewVM(f.t.Context(), f.vm)
|
||||
@@ -589,31 +589,28 @@ func TestSetNext(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Off: nothing is locked. On hosts without locks it's off, saying so when
|
||||
// there's a .git.
|
||||
// Off: nothing is locked, and off is the user's choice. On hosts without
|
||||
// locks it's off, not chosen, and creating says nothing: the launches
|
||||
// warn (WarnUnprotected).
|
||||
func TestNewVMOffAndLinux(t *testing.T) {
|
||||
f := newFixture(t, "p")
|
||||
mkdirs(t, f.path(".git/hooks"))
|
||||
if err := f.newVM(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Mode(f.vm) != "off" || len(f.flags) > 0 || len(f.warns.Names()) > 0 {
|
||||
t.Errorf("off: %s, locks %q, warnings %q", Mode(f.vm), f.flags, f.warns.Names())
|
||||
if Mode(f.vm) != "off" || !f.section().Chosen || len(f.flags) > 0 || len(f.warns.Names()) > 0 {
|
||||
t.Errorf("off: %s, chosen %t, locks %q, warnings %q", Mode(f.vm), f.section().Chosen, f.flags, f.warns.Names())
|
||||
}
|
||||
f.p.CanLock = false
|
||||
if err := f.newVM(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Mode(f.vm) != "off" || len(f.flags) > 0 || !slices.Equal(f.warns.Names(), []string{"git_protect_needs_macos_new"}) {
|
||||
t.Errorf("linux: %s, locks %q, warnings %q", Mode(f.vm), f.flags, f.warns.Names())
|
||||
if Mode(f.vm) != "off" || f.section().Chosen || len(f.flags) > 0 || len(f.warns.Names()) > 0 {
|
||||
t.Errorf("linux: %s, chosen %t, locks %q, warnings %q", Mode(f.vm), f.section().Chosen, f.flags, f.warns.Names())
|
||||
}
|
||||
if err := os.RemoveAll(f.path(".git")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.warns.Reset()
|
||||
if err := f.newVM(false); err != nil || len(f.warns.Names()) > 0 {
|
||||
t.Errorf("linux without .git: %v, warnings %q", err, f.warns.Names())
|
||||
}
|
||||
f.p.CanLock = true
|
||||
if err := f.newVM(false); err != nil || Mode(f.vm) != "on" || len(f.flags) > 0 {
|
||||
t.Errorf("no .git: %v, %s, locks %q", err, Mode(f.vm), f.flags)
|
||||
@@ -952,7 +949,7 @@ func TestNewHome(t *testing.T) {
|
||||
t.Setenv("HOME", "/elsewhere")
|
||||
p := New("/p", "/h", nil)
|
||||
for in, want := range map[string]string{"~": "/h", "~/x": "/h/x", "~x/y": "~x/y", "/a": "/a"} {
|
||||
if got := p.expandHome(in); got != want {
|
||||
if got := expandHome(p.Home, in); got != want {
|
||||
t.Errorf("expandHome(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
package gitprotect
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/devvmhq/devvm/internal/hostgit"
|
||||
"github.com/devvmhq/devvm/internal/msg"
|
||||
"github.com/devvmhq/devvm/internal/paths"
|
||||
"github.com/devvmhq/devvm/internal/platform"
|
||||
"github.com/devvmhq/devvm/internal/state"
|
||||
)
|
||||
|
||||
// On hosts without locks (Linux), devvm can't stop the VM changing what a
|
||||
// lock would cover (paths), so it watches those paths instead: each check
|
||||
// reports what a lock can't stop, as protect does without locking, sums
|
||||
// them, compares with the sums the last one recorded, and names what
|
||||
// changed. That's after the fact: git on the host may have run it
|
||||
// already, and the VM may have put it back before it stopped.
|
||||
|
||||
// Watched is what the last watch found: a sum of each path a lock would
|
||||
// cover, by its path relative to the project folder, of each file in its
|
||||
// hooks folders, of .git/commondir, and of what the config hands over to
|
||||
// the project folder (includes, core.hooksPath). Scanned is set once a
|
||||
// check has recorded it, so the first check of a VM, or of one an older
|
||||
// devvm made, records without reporting.
|
||||
type Watched struct {
|
||||
Scanned bool `json:"scanned,omitempty"`
|
||||
Sums map[string]string `json:"sums,omitempty"`
|
||||
}
|
||||
|
||||
// The watch's bounds: hooks folders and configs are small, so a folder
|
||||
// with more entries, or a file larger, than these is the VM's doing, and
|
||||
// is summed by what's cheap (its entries' count, its size, its inode and
|
||||
// change time) past them, and named at each check. A warning names at most
|
||||
// maxListed paths, and the rest by their count.
|
||||
const (
|
||||
maxWatchEntries = 1000 // entries of one hooks folder
|
||||
maxWatchBytes = 16 << 20 // bytes of one file
|
||||
maxWatchTotal = 2000 // sums of one watch
|
||||
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.
|
||||
func (p *Protector) WarnUnprotected(vm *state.VM) {
|
||||
g, _ := Of(vm)
|
||||
if p.CanLock || g.Mode == Clone || g.Mode == Off && g.Chosen || !exists(p.git()) {
|
||||
return
|
||||
}
|
||||
p.Warn(msg.GitUnprotected(vm.Name()))
|
||||
}
|
||||
|
||||
// watcher is a protector's watch, on a host without locks.
|
||||
type watcher struct{ *Protector }
|
||||
|
||||
// check is a check of a stopped VM's .git on a host without locks: what a
|
||||
// lock can't stop, reported as protect reports it, without locking (a VM
|
||||
// whose protection was never set up reports as a new VM does), then the
|
||||
// watch.
|
||||
func (w watcher) check(ctx context.Context, vm *state.VM, g InVM) error {
|
||||
why := whyCheck
|
||||
if !g.Made.Protected {
|
||||
why = whyNew
|
||||
}
|
||||
made, err := w.protect(ctx, g, why, watching)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := record(ctx, vm, func(g *InVM) { g.Made = made }); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.watch(ctx, vm, g.Watched)
|
||||
}
|
||||
|
||||
// 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, was Watched) error {
|
||||
s := w.sums(ctx)
|
||||
now := Watched{Scanned: true, Sums: s.sums}
|
||||
if was.Scanned {
|
||||
if changed := changedPaths(was.Sums, now.Sums); len(changed) > 0 {
|
||||
l, more := listed(changed)
|
||||
if more == 0 {
|
||||
w.Warn(msg.GitChanged(l, vm.Name()))
|
||||
} else {
|
||||
w.Warn(msg.GitChangedMore(more, l, vm.Name()))
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(s.blind) > 0 {
|
||||
if l, more := listed(s.blind); more == 0 {
|
||||
w.Warn(msg.GitWatchBlind(l))
|
||||
} else {
|
||||
w.Warn(msg.GitWatchBlindMore(more, l))
|
||||
}
|
||||
}
|
||||
return record(ctx, vm, func(g *InVM) { g.Watched = now })
|
||||
}
|
||||
|
||||
// listed is paths as a warning names them: at most maxListed, joined, and
|
||||
// how many more there are.
|
||||
func listed(paths []string) (string, int) {
|
||||
if len(paths) <= maxListed {
|
||||
return strings.Join(paths, ", "), 0
|
||||
}
|
||||
return strings.Join(paths[:maxListed], ", "), len(paths) - maxListed
|
||||
}
|
||||
|
||||
// changedPaths returns the paths whose sums differ between was and now,
|
||||
// those added or gone included, sorted.
|
||||
func changedPaths(was, now map[string]string) []string {
|
||||
var out []string
|
||||
for path, sum := range now {
|
||||
if was[path] != sum {
|
||||
out = append(out, path)
|
||||
}
|
||||
}
|
||||
for path := range was {
|
||||
if _, ok := now[path]; !ok {
|
||||
out = append(out, path)
|
||||
}
|
||||
}
|
||||
slices.Sort(out)
|
||||
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
|
||||
// project folder.
|
||||
func (w watcher) sums(ctx context.Context) summer {
|
||||
s := summer{top: w.Dir, real: w.realInDir, sums: map[string]string{}}
|
||||
emb := w.embedded(ctx)
|
||||
todo := w.paths(ctx, emb)
|
||||
if g := w.git(); !isFile(g) {
|
||||
todo = append(todo, filepath.Join(g, "commondir"))
|
||||
}
|
||||
todo = append(todo, w.watchedDelegations(ctx, emb)...)
|
||||
done := map[string]bool{}
|
||||
for _, path := range todo {
|
||||
if !done[path] {
|
||||
done[path] = true
|
||||
s.add(path)
|
||||
}
|
||||
}
|
||||
slices.Sort(s.blind)
|
||||
s.blind = slices.Compact(s.blind)
|
||||
return s
|
||||
}
|
||||
|
||||
// watchedDelegations are the files and folders in the project folder
|
||||
// that the config hands over to git: include.path's and includeIf's
|
||||
// files (delegations), and the folder core.hooksPath names, whose hooks
|
||||
// git runs in place of .git/hooks.
|
||||
func (w watcher) watchedDelegations(ctx context.Context, emb embeds) []string {
|
||||
var out []string
|
||||
for _, d := range w.delegations(ctx, emb) {
|
||||
if d.kind == "include" && d.path != "" {
|
||||
out = append(out, d.path)
|
||||
}
|
||||
}
|
||||
if hp := gitConfig(ctx, filepath.Join(w.git(), "config"), "core.hooksPath"); hp != "" && w.hooksPathInside(hp) {
|
||||
hp = expandHome(w.Home, hp)
|
||||
if !filepath.IsAbs(hp) {
|
||||
hp = filepath.Join(w.Dir, hp)
|
||||
}
|
||||
out = append(out, filepath.Clean(hp))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 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.
|
||||
type summer struct {
|
||||
top string // the project folder
|
||||
real func(path string) bool
|
||||
sums map[string]string
|
||||
blind []string
|
||||
}
|
||||
|
||||
// add sums what's at path, if anything: a missing path is absent from the
|
||||
// sums, so one that appears is named.
|
||||
func (s *summer) add(path string) {
|
||||
rel := relTo(s.top, path)
|
||||
fi, err := os.Lstat(path)
|
||||
switch {
|
||||
case err != nil:
|
||||
case fi.Mode()&fs.ModeSymlink != 0:
|
||||
s.put(rel, sumOf(path, fi)+s.within(path))
|
||||
s.blind = append(s.blind, rel)
|
||||
case !s.real(path):
|
||||
s.put(rel, "under a symlink"+s.within(path))
|
||||
s.blind = append(s.blind, rel)
|
||||
case fi.IsDir():
|
||||
s.hooks(path)
|
||||
default:
|
||||
s.file(rel, path, fi)
|
||||
}
|
||||
}
|
||||
|
||||
// put records a sum, or past maxWatchTotal, the path as one it can't
|
||||
// watch.
|
||||
func (s *summer) put(rel, sum string) {
|
||||
if len(s.sums) >= maxWatchTotal {
|
||||
s.blind = append(s.blind, rel)
|
||||
return
|
||||
}
|
||||
s.sums[rel] = sum
|
||||
}
|
||||
|
||||
// file sums a regular file, or anything else that isn't a folder or a
|
||||
// symlink, by its type.
|
||||
func (s *summer) file(rel, path string, fi fs.FileInfo) {
|
||||
if fi.Mode().IsRegular() && fi.Size() > maxWatchBytes {
|
||||
s.blind = append(s.blind, rel)
|
||||
}
|
||||
s.put(rel, sumOf(path, fi))
|
||||
}
|
||||
|
||||
// within is what a symlink, or a path under one, holds, when it leads to
|
||||
// a file or folder in the project folder, which the VM can change: its
|
||||
// sum after ", ". A link out of the project folder isn't followed.
|
||||
func (s *summer) within(path string) string {
|
||||
r, err := filepath.EvalSymlinks(path)
|
||||
if err != nil || !paths.Below(r, s.top) {
|
||||
return ""
|
||||
}
|
||||
fi, err := os.Lstat(r)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ""
|
||||
case fi.IsDir():
|
||||
inner := summer{top: s.top, real: s.real, sums: map[string]string{}}
|
||||
inner.hooks(r)
|
||||
h := sha256.New()
|
||||
for _, k := range slices.Sorted(maps.Keys(inner.sums)) {
|
||||
h.Write([]byte(strconv.Itoa(len(k)) + ":" + k + "=" + inner.sums[k] + "\n"))
|
||||
}
|
||||
return ", folder " + hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
return ", " + sumOf(r, fi)
|
||||
}
|
||||
|
||||
// hooks sums each entry of a hooks folder below it, git's samples apart
|
||||
// (git never runs them): first the entries at its top named as git's
|
||||
// hooks (hostgit.HookEvents), which git runs, then the rest, at most
|
||||
// maxWatchEntries in all. Past those, the folder is summed by its count,
|
||||
// inode and change time, and named as one it can't watch.
|
||||
func (s *summer) hooks(dir string) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
events := hostgit.HookEvents()
|
||||
slices.SortStableFunc(entries, func(a, b fs.DirEntry) int {
|
||||
return boolOrder(!slices.Contains(events, a.Name())) - boolOrder(!slices.Contains(events, b.Name()))
|
||||
})
|
||||
n := 0
|
||||
var sub []string
|
||||
for _, e := range entries {
|
||||
path := filepath.Join(dir, e.Name())
|
||||
switch {
|
||||
case e.Type().IsRegular() && strings.HasSuffix(e.Name(), ".sample"):
|
||||
continue
|
||||
case e.IsDir():
|
||||
sub = append(sub, path)
|
||||
continue
|
||||
}
|
||||
if n++; n > maxWatchEntries {
|
||||
s.over(dir)
|
||||
return
|
||||
}
|
||||
s.entry(path)
|
||||
}
|
||||
for _, d := range sub {
|
||||
err := filepath.WalkDir(d, func(path string, e fs.DirEntry, err error) error {
|
||||
if err != nil || e.IsDir() || e.Type().IsRegular() && strings.HasSuffix(e.Name(), ".sample") {
|
||||
return nil //nolint:nilerr // unreadable: skipped, like find
|
||||
}
|
||||
if n++; n > maxWatchEntries {
|
||||
return fs.SkipAll
|
||||
}
|
||||
s.entry(path)
|
||||
return nil
|
||||
})
|
||||
if err != nil || n > maxWatchEntries {
|
||||
s.over(dir)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// entry sums one entry of a hooks folder.
|
||||
func (s *summer) entry(path string) {
|
||||
fi, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rel := relTo(s.top, path)
|
||||
if fi.Mode()&fs.ModeSymlink != 0 {
|
||||
s.put(rel, sumOf(path, fi)+s.within(path))
|
||||
s.blind = append(s.blind, rel)
|
||||
return
|
||||
}
|
||||
s.file(rel, path, fi)
|
||||
}
|
||||
|
||||
// over sums a hooks folder past maxWatchEntries by its count, inode and
|
||||
// change time, and names it as one it can't watch.
|
||||
func (s *summer) over(dir string) {
|
||||
rel := relTo(s.top, dir)
|
||||
sum := "more than " + strconv.Itoa(maxWatchEntries) + " entries"
|
||||
if fi, err := os.Lstat(dir); err == nil {
|
||||
sum += ", " + platform.ChangeID(fi)
|
||||
}
|
||||
s.put(rel, sum)
|
||||
s.blind = append(s.blind, rel)
|
||||
}
|
||||
|
||||
func boolOrder(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// relTo is a path in the project folder top relative to it.
|
||||
func relTo(top, path string) string { return strings.TrimPrefix(path, top+"/") }
|
||||
|
||||
// sumOf sums what's at path, which fi (from Lstat) describes: a regular
|
||||
// file by its contents, read without following a symlink, past
|
||||
// maxWatchBytes by its size, inode and change time (which the VM can't set
|
||||
// back), a symlink by where it points, and anything else by its type.
|
||||
func sumOf(path string, fi fs.FileInfo) string {
|
||||
switch {
|
||||
case fi.Mode()&fs.ModeSymlink != 0:
|
||||
link, _ := os.Readlink(path)
|
||||
return "symlink " + link
|
||||
case !fi.Mode().IsRegular():
|
||||
return "type " + fi.Mode().Type().String()
|
||||
case fi.Size() > maxWatchBytes:
|
||||
return "size " + strconv.FormatInt(fi.Size(), 10) + ", " + platform.ChangeID(fi)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDONLY|platform.NoBlock|platform.NoFollow, 0) //nolint:gosec // the project's own, not through a symlink
|
||||
if err != nil {
|
||||
return "unreadable"
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
if fi, err := f.Stat(); err != nil || !fi.Mode().IsRegular() {
|
||||
return "unreadable"
|
||||
}
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, io.LimitReader(f, maxWatchBytes)); err != nil {
|
||||
return "unreadable"
|
||||
}
|
||||
return "sha256 " + hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
package gitprotect
|
||||
|
||||
import (
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// linuxFixture is a fixture on a host without locks, its VM's mode off as
|
||||
// such a host gives a new VM, not chosen.
|
||||
func linuxFixture(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
f := newFixture(t, "p")
|
||||
f.p.CanLock = false
|
||||
if err := f.newVM(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// check runs a check of the stopped VM, and returns what it warned.
|
||||
func (f *fixture) check() []string {
|
||||
f.t.Helper()
|
||||
f.warns.Reset()
|
||||
if err := f.p.Check(f.t.Context(), f.vm, false); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return f.warns.Names()
|
||||
}
|
||||
|
||||
// Each launch on a host without locks warns that the VM can change .git,
|
||||
// unless there's no .git, the user chose off, or it's a --clone VM; a
|
||||
// host with locks never does.
|
||||
func TestWarnUnprotected(t *testing.T) {
|
||||
f := linuxFixture(t)
|
||||
mkdirs(t, f.path(".git/hooks"))
|
||||
want := []string{"git_unprotected vm=" + f.vm.Name()}
|
||||
f.p.WarnUnprotected(f.vm)
|
||||
if !slices.Equal(f.warns.Names(), want) {
|
||||
t.Errorf("off by the host: %q", f.warns.Names())
|
||||
}
|
||||
f.warns.Reset()
|
||||
f.p.CanLock = true
|
||||
f.p.WarnUnprotected(f.vm)
|
||||
f.p.CanLock = false
|
||||
if err := os.RemoveAll(f.path(".git")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.p.WarnUnprotected(f.vm)
|
||||
if len(f.warns.Names()) > 0 {
|
||||
t.Errorf("macOS, or no .git: %q", f.warns.Names())
|
||||
}
|
||||
mkdirs(t, f.path(".git/hooks"))
|
||||
for _, g := range []InVM{{Mode: Off, Chosen: true}, {Mode: Clone}} {
|
||||
if err := record(t.Context(), f.vm, func(s *InVM) { *s = g }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.p.WarnUnprotected(f.vm)
|
||||
if len(f.warns.Names()) > 0 {
|
||||
t.Errorf("%+v: %q", g, f.warns.Names())
|
||||
}
|
||||
}
|
||||
// devvm git-protect off, on such a host, is the user's choice.
|
||||
if err := record(t.Context(), f.vm, func(s *InVM) { *s = InVM{Mode: Off} }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.p.Set(t.Context(), f.vm, Off); err != nil || !f.section().Chosen {
|
||||
t.Errorf("devvm git-protect off: %v, chosen %t", err, f.section().Chosen)
|
||||
}
|
||||
}
|
||||
|
||||
// A new VM's first sums are recorded as it's made, without reporting;
|
||||
// each later check names what changed since, added and gone included,
|
||||
// and nothing when nothing did. A running VM's launch checks nothing.
|
||||
func TestWatch(t *testing.T) {
|
||||
needGit(t)
|
||||
f := newFixture(t, "p")
|
||||
f.git(f.dir, "init", "-q")
|
||||
write(t, f.path(".git/hooks/post-merge"), "#!/bin/sh\n")
|
||||
f.p.CanLock = false
|
||||
if err := f.newVM(false); err != nil || len(f.warns.Names()) > 0 {
|
||||
t.Errorf("new VM: %v, %q", err, f.warns.Names())
|
||||
}
|
||||
w := f.section().Watched
|
||||
if !w.Scanned || w.Sums[".git/config"] == "" || w.Sums[".git/hooks/post-merge"] == "" {
|
||||
t.Errorf("first check recorded %+v", w)
|
||||
}
|
||||
for path := range w.Sums {
|
||||
if strings.HasSuffix(path, ".sample") {
|
||||
t.Errorf("a sample is watched: %s", path)
|
||||
}
|
||||
}
|
||||
if w := f.check(); len(w) > 0 {
|
||||
t.Errorf("nothing changed: %q", w)
|
||||
}
|
||||
f.git(f.dir, "config", "core.fsmonitor", "./evil")
|
||||
write(t, f.path(".git/hooks/pre-commit"), "#!/bin/sh\n")
|
||||
if err := os.Remove(f.path(".git/hooks/post-merge")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.warns.Reset()
|
||||
if err := f.p.Check(t.Context(), f.vm, true); err != nil || len(f.warns.Names()) > 0 {
|
||||
t.Errorf("running: %v, %q", err, f.warns.Names())
|
||||
}
|
||||
want := []string{"git_changed paths=.git/config, .git/hooks/post-merge, .git/hooks/pre-commit vm=" + f.vm.Name()}
|
||||
if w := f.check(); !slices.Equal(w, want) {
|
||||
t.Errorf("changed: %q, want %q", w, want)
|
||||
}
|
||||
if w := f.check(); len(w) > 0 {
|
||||
t.Errorf("named once: %q", w)
|
||||
}
|
||||
}
|
||||
|
||||
// A VM that an older devvm made, or that a host's lock protected, has
|
||||
// nothing watched: its first check records without reporting, and so
|
||||
// does the first after its record was dropped (devvm adopt).
|
||||
func TestWatchFirstOfExisting(t *testing.T) {
|
||||
f := linuxFixture(t)
|
||||
mkdirs(t, f.path(".git/hooks"))
|
||||
write(t, f.path(".git/config"), "[core]\n")
|
||||
if err := record(t.Context(), f.vm, func(g *InVM) { g.Watched, g.Made = Watched{}, Made{} }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := f.check(); len(w) > 0 || !f.section().Watched.Scanned || !f.section().Made.Protected {
|
||||
t.Errorf("first: %q, %+v", w, f.section())
|
||||
}
|
||||
// A folder with no .git yet: one that appears is named.
|
||||
g := newFixture(t, "q")
|
||||
g.p.CanLock = false
|
||||
if err := g.newVM(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := g.check(); len(w) > 0 || !g.section().Watched.Scanned {
|
||||
t.Errorf("no .git: %q, %+v", w, g.section().Watched)
|
||||
}
|
||||
mkdirs(t, g.path(".git/hooks"))
|
||||
write(t, g.path(".git/config"), "[core]\n")
|
||||
if w := g.check(); !slices.Equal(w, []string{"git_appeared", "git_changed paths=.git/config vm=" + g.vm.Name()}) {
|
||||
t.Errorf("appeared: %q", w)
|
||||
}
|
||||
}
|
||||
|
||||
// blind is the standing warning a check gives for paths it can't fully
|
||||
// watch.
|
||||
func blind(paths string) string { return "git_watch_blind paths=" + paths }
|
||||
|
||||
// No symlink out of the project folder is followed: such a symlink is
|
||||
// summed by where it points, so changing what it points to names nothing,
|
||||
// and changing the link names it. One that leads into the project folder
|
||||
// is summed by what it holds too, so the VM changing that is named. Every
|
||||
// check names them all as paths it can't fully watch.
|
||||
func TestWatchSymlinks(t *testing.T) {
|
||||
f := linuxFixture(t)
|
||||
mkdirs(t, f.path(".git/hooks"))
|
||||
outside := f.root + "/outside"
|
||||
write(t, outside, "one")
|
||||
write(t, f.path("tracked.sh"), "one")
|
||||
symlink(t, outside, f.path(".git/config"))
|
||||
symlink(t, outside, f.path(".git/hooks/pre-commit"))
|
||||
symlink(t, "../../tracked.sh", f.path(".git/hooks/post-merge"))
|
||||
f.check()
|
||||
s := f.section().Watched.Sums
|
||||
if s[".git/config"] != "symlink "+outside || s[".git/hooks/pre-commit"] != "symlink "+outside ||
|
||||
!strings.HasPrefix(s[".git/hooks/post-merge"], "symlink ../../tracked.sh, sha256 ") {
|
||||
t.Errorf("sums %q", s)
|
||||
}
|
||||
stand := blind(".git/config, .git/hooks/post-merge, .git/hooks/pre-commit")
|
||||
write(t, outside, "two")
|
||||
if w := f.check(); !slices.Equal(w, []string{stand}) {
|
||||
t.Errorf("what a link out points to changed: %q", w)
|
||||
}
|
||||
write(t, f.path("tracked.sh"), "two")
|
||||
if w := f.check(); !slices.Equal(w, []string{"git_changed paths=.git/hooks/post-merge vm=" + f.vm.Name(), stand}) {
|
||||
t.Errorf("what a link in points to changed: %q", w)
|
||||
}
|
||||
if err := os.Remove(f.path(".git/hooks/pre-commit")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
symlink(t, f.root+"/elsewhere", f.path(".git/hooks/pre-commit"))
|
||||
if w := f.check(); !slices.Equal(w, []string{"git_changed paths=.git/hooks/pre-commit vm=" + f.vm.Name(), stand}) {
|
||||
t.Errorf("the link changed: %q", w)
|
||||
}
|
||||
|
||||
// .git itself a symlink: to a repo elsewhere, never read; to one in
|
||||
// the project folder, read.
|
||||
g := newFixture(t, "q")
|
||||
g.p.CanLock = false
|
||||
if err := g.newVM(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := g.root + "/repo"
|
||||
mkdirs(t, repo+"/hooks")
|
||||
write(t, repo+"/config", "")
|
||||
write(t, repo+"/hooks/pre-commit", "one")
|
||||
symlink(t, repo, g.path(".git"))
|
||||
g.check()
|
||||
if s := g.section().Watched.Sums; s[".git/hooks"] != "under a symlink" || s[".git/config"] != "under a symlink" {
|
||||
t.Errorf("sums %q", s)
|
||||
}
|
||||
write(t, repo+"/hooks/pre-commit", "two")
|
||||
if w := g.check(); !slices.Equal(w, []string{blind(".git/config, .git/hooks")}) {
|
||||
t.Errorf("read through .git's link out: %q", w)
|
||||
}
|
||||
if err := os.Remove(g.path(".git")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inner := g.path("inner")
|
||||
mkdirs(t, inner+"/hooks")
|
||||
write(t, inner+"/config", "")
|
||||
symlink(t, "inner", g.path(".git"))
|
||||
g.check()
|
||||
write(t, inner+"/hooks/pre-commit", "evil")
|
||||
if w := g.check(); len(w) != 2 || w[0] != "git_changed paths=.git/hooks vm="+g.vm.Name() {
|
||||
t.Errorf("through .git's link in: %q", w)
|
||||
}
|
||||
}
|
||||
|
||||
// The watch is bounded, and names what it reads only in part at each
|
||||
// check: a hooks folder past maxWatchEntries, summed by that and its
|
||||
// change time, though the hooks git runs at its top are always summed, and
|
||||
// a file past maxWatchBytes, summed by its size, inode and change time, so
|
||||
// a change that keeps its size is named.
|
||||
func TestWatchBounds(t *testing.T) {
|
||||
f := linuxFixture(t)
|
||||
mkdirs(t, f.path(".git/hooks/a"))
|
||||
for i := range maxWatchEntries + 1 {
|
||||
write(t, f.path(".git/hooks/a/h"+strconv.Itoa(i)), "")
|
||||
}
|
||||
write(t, f.path(".git/hooks/pre-commit"), "one")
|
||||
write(t, f.path(".git/config"), "")
|
||||
if err := os.Truncate(f.path(".git/config"), maxWatchBytes+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = f.check() // the repo, made since the VM, recorded
|
||||
if w := f.check(); !slices.Equal(w, []string{blind(".git/config, .git/hooks")}) {
|
||||
t.Errorf("unchanged: %q", w)
|
||||
}
|
||||
s := f.section().Watched.Sums
|
||||
if !strings.HasPrefix(s[".git/hooks"], "more than 1000 entries, ino ") || len(s) > maxWatchEntries+4 {
|
||||
t.Errorf("hooks: %q, %d sums", s[".git/hooks"], len(s))
|
||||
}
|
||||
if !strings.HasPrefix(s[".git/config"], "size "+strconv.Itoa(maxWatchBytes+1)+", ino ") {
|
||||
t.Errorf("config: %q", s[".git/config"])
|
||||
}
|
||||
if !strings.HasPrefix(s[".git/hooks/pre-commit"], "sha256 ") {
|
||||
t.Errorf("pre-commit, hidden by a/: %q", s[".git/hooks/pre-commit"])
|
||||
}
|
||||
write(t, f.path(".git/hooks/pre-commit"), "two")
|
||||
cfg, err := os.OpenFile(f.path(".git/config"), os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cfg.WriteAt([]byte("[core]"), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = cfg.Close()
|
||||
if err := os.Chtimes(f.path(".git/config"), time.Unix(1, 0), time.Unix(1, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := f.check()
|
||||
if len(w) != 2 || w[0] != "git_changed paths=.git/config, .git/hooks/pre-commit vm="+f.vm.Name() {
|
||||
t.Errorf("changed, its size and times kept: %q", w)
|
||||
}
|
||||
}
|
||||
|
||||
// A watch keeps at most maxWatchTotal sums, and a warning names at most
|
||||
// maxListed paths, then how many more.
|
||||
func TestWatchTotal(t *testing.T) {
|
||||
f := linuxFixture(t)
|
||||
mkdirs(t, f.path(".git/hooks"))
|
||||
// Submodules' git dirs, each with a hooks folder within its own bound.
|
||||
for i := range 3 {
|
||||
dir := f.path(".git/modules/m" + strconv.Itoa(i))
|
||||
mkdirs(t, dir+"/objects", dir+"/refs", dir+"/hooks")
|
||||
write(t, dir+"/HEAD", "")
|
||||
for j := range maxWatchEntries - 10 {
|
||||
write(t, dir+"/hooks/h"+strconv.Itoa(j), "")
|
||||
}
|
||||
}
|
||||
_ = f.check()
|
||||
if s := f.section().Watched.Sums; len(s) > maxWatchTotal {
|
||||
t.Errorf("%d sums", len(s))
|
||||
}
|
||||
for i := range maxListed + 3 {
|
||||
write(t, f.path(".git/hooks/n"+strconv.Itoa(i)), "")
|
||||
}
|
||||
w := f.check()
|
||||
if len(w) != 2 || !strings.HasPrefix(w[0], "git_changed_more count=") || !strings.HasPrefix(w[1], "git_watch_blind_more count=") {
|
||||
t.Errorf("changed: %q", w)
|
||||
}
|
||||
if l, more := listed([]string{"a", "b"}); l != "a, b" || more != 0 {
|
||||
t.Errorf("listed: %q, %d", l, more)
|
||||
}
|
||||
}
|
||||
|
||||
// The VM pointing git at another config through .git/commondir, as a
|
||||
// proven exploit did, is reported at the next check, as a lock's check
|
||||
// reports it, and the watch names it; so are core.hooksPath into the
|
||||
// project folder (husky's .husky) and an include into it, and changes to
|
||||
// what they lead to.
|
||||
func TestWatchReportsWhatALockCantStop(t *testing.T) {
|
||||
needGit(t)
|
||||
f := newFixture(t, "p")
|
||||
f.git(f.dir, "init", "-q")
|
||||
f.p.CanLock = false
|
||||
if err := f.newVM(false); err != nil || len(f.warns.Names()) > 0 {
|
||||
t.Fatalf("new VM: %v, %q", err, f.warns.Names())
|
||||
}
|
||||
mkdirs(t, f.path("evil"))
|
||||
symlink(t, "../.git/objects", f.path("evil/objects"))
|
||||
symlink(t, "../.git/refs", f.path("evil/refs"))
|
||||
write(t, f.path("evil/config"), "[core]\n\tfsmonitor = ./pwn\n")
|
||||
write(t, f.path(".git/commondir"), "../evil\n")
|
||||
w := f.check()
|
||||
if !slices.Contains(w, "git_commondir git="+f.path(".git")+" target=../evil") ||
|
||||
!slices.Contains(w, "git_changed paths=.git/commondir vm="+f.vm.Name()) {
|
||||
t.Errorf("commondir: %q", w)
|
||||
}
|
||||
if err := os.Remove(f.path(".git/commondir")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = f.check()
|
||||
|
||||
// A .git replaced: named once, then compared with the new one.
|
||||
if err := os.Rename(f.path(".git"), f.path(".git-old")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.git(f.dir, "init", "-q")
|
||||
if w := f.check(); !slices.Contains(w, "git_replaced git="+f.path(".git")) {
|
||||
t.Errorf("replaced: %q", w)
|
||||
}
|
||||
if w := f.check(); slices.Contains(w, "git_replaced git="+f.path(".git")) {
|
||||
t.Errorf("replaced, again: %q", w)
|
||||
}
|
||||
|
||||
// Delegations into the project folder.
|
||||
mkdirs(t, f.path(".husky"))
|
||||
write(t, f.path(".husky/pre-commit"), "one")
|
||||
write(t, f.path("more.cfg"), "")
|
||||
f.git(f.dir, "config", "core.hooksPath", ".husky")
|
||||
f.git(f.dir, "config", "include.path", "../more.cfg")
|
||||
w = f.check()
|
||||
if !slices.Contains(w, "git_include_inside config="+f.path(".git/config")+" path=../more.cfg") {
|
||||
t.Errorf("include: %q", w)
|
||||
}
|
||||
write(t, f.path(".husky/pre-commit"), "two")
|
||||
write(t, f.path("more.cfg"), "[core]\n\tpager = ./pwn\n")
|
||||
if w := f.check(); !slices.Contains(w, "git_changed paths=.husky/pre-commit, more.cfg vm="+f.vm.Name()) {
|
||||
t.Errorf("what they lead to: %q", w)
|
||||
}
|
||||
}
|
||||
|
||||
// On a host without locks, a gitlink whose .git file names a folder of the
|
||||
// project's own source, or one with no hooks folder, is reported as a
|
||||
// lock's check reports it, once; nothing is locked or made there, and the
|
||||
// watch doesn't sum that folder's files as a git dir's.
|
||||
func TestWatchGitdirNotGit(t *testing.T) {
|
||||
needGit(t)
|
||||
f := newFixture(t, "p")
|
||||
f.git(f.dir, "init", "-q")
|
||||
f.git(f.dir, "commit", "-q", "--allow-empty", "-m", "x")
|
||||
f.p.CanLock = false
|
||||
if err := f.newVM(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mkdirs(t, f.path("src/hooks"), f.path("lib"), f.path("evil"))
|
||||
write(t, f.path("src/hooks/useThing.ts"), "export {}\n")
|
||||
write(t, f.path("src/config"), "x\n")
|
||||
write(t, f.path("evil/.git"), "gitdir: ../src\n")
|
||||
write(t, f.path("lib/.git"), "gitdir: ../lib\n")
|
||||
head := f.git(f.dir, "rev-parse", "HEAD")
|
||||
for _, sub := range []string{"evil", "lib"} {
|
||||
f.git(f.dir, "update-index", "--add", "--cacheinfo", "160000,"+head+","+sub)
|
||||
}
|
||||
w := f.check()
|
||||
for _, want := range []string{
|
||||
"git_gitdir_not_git git=" + f.path("src") + " sub=" + f.path("evil"),
|
||||
"git_gitdir_not_git git=" + f.path("lib") + " sub=" + f.path("lib"),
|
||||
} {
|
||||
if !slices.Contains(w, want) {
|
||||
t.Errorf("warnings %q lack %s", w, want)
|
||||
}
|
||||
}
|
||||
if len(f.flags) > 0 {
|
||||
t.Errorf("locked: %q", f.flags)
|
||||
}
|
||||
if _, err := os.Lstat(f.path("lib/hooks")); err == nil {
|
||||
t.Error("made lib/hooks")
|
||||
}
|
||||
for path := range f.section().Watched.Sums {
|
||||
if strings.HasPrefix(path, "src/") || strings.HasPrefix(path, "lib/") {
|
||||
t.Errorf("watched as a git dir's: %s", path)
|
||||
}
|
||||
}
|
||||
if w := f.check(); slices.ContainsFunc(w, func(s string) bool { return strings.HasPrefix(s, "git_gitdir_not_git ") }) {
|
||||
t.Errorf("again: %q", w)
|
||||
}
|
||||
}
|
||||
|
||||
// What changed is sorted, gone and added included.
|
||||
func TestChangedPaths(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
was, now map[string]string
|
||||
want []string
|
||||
}{
|
||||
{nil, nil, nil},
|
||||
{map[string]string{"a": "1"}, map[string]string{"a": "1"}, nil},
|
||||
{map[string]string{"b": "1", "c": "1"}, map[string]string{"a": "1", "b": "2"}, []string{"a", "b", "c"}},
|
||||
} {
|
||||
if got := changedPaths(c.was, c.now); !slices.Equal(got, c.want) {
|
||||
t.Errorf("changedPaths(%v, %v) = %q, want %q", c.was, c.now, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,10 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// hooks are the events git runs hooks for (githooks(5)), each turned off
|
||||
// for the hooks a config names for it (hook.EVENT.enabled).
|
||||
func hooks() []string {
|
||||
// HookEvents are the events git runs hooks for (githooks(5)), each turned
|
||||
// off for the hooks a config names for it (hook.EVENT.enabled), and the
|
||||
// names git runs in a hooks folder.
|
||||
func HookEvents() []string {
|
||||
return []string{
|
||||
"applypatch-msg", "pre-applypatch", "post-applypatch", "pre-commit", "pre-merge-commit",
|
||||
"prepare-commit-msg", "commit-msg", "post-commit", "pre-rebase", "post-checkout", "post-merge",
|
||||
@@ -48,7 +49,7 @@ func hardened() [][2]string {
|
||||
{"maintenance.auto", "false"},
|
||||
{"gc.auto", "0"},
|
||||
}
|
||||
for _, h := range hooks() {
|
||||
for _, h := range HookEvents() {
|
||||
kv = append(kv, [2]string{"hook." + h + ".enabled", "false"})
|
||||
}
|
||||
return kv
|
||||
|
||||
@@ -219,7 +219,12 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede
|
||||
"devcontainer_initialize": "using/devcontainer#properties",
|
||||
"devcontainer_feature_options": "using/devcontainer#properties",
|
||||
"devcontainer_ports_ignored": "using/devcontainer#properties",
|
||||
"git_protect_needs_macos_new": "safety/git-protection#linux-hosts",
|
||||
"git_unprotected": "safety/git-protection#linux-hosts",
|
||||
"git_unprotected_quiet": "safety/git-protection#the-warning-at-each-launch",
|
||||
"git_changed": "safety/git-protection#when-devvm-names-a-change",
|
||||
"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_protect_on_needs_macos": "safety/git-protection#linux-hosts",
|
||||
"git_protect_next_stop": "safety/git-protection#turning-it-on-or-off",
|
||||
"git_unlocked": "safety/git-protection#turning-it-on-or-off",
|
||||
|
||||
@@ -1379,6 +1379,16 @@ func GitAppeared() M {
|
||||
return M{id: "git_appeared"}
|
||||
}
|
||||
|
||||
// GitChanged is [git_changed]: "WARNING: {{.paths}} changed since devvm last checked, perhaps by {{.vm}}, and git on this machine runs what they hold. devvm can tell you only after the fact, so if you didn't change them, check them before you run git here."
|
||||
func GitChanged(paths string, vm string) M {
|
||||
return M{id: "git_changed", vals: []val{{"paths", paths}, {"vm", vm}}}
|
||||
}
|
||||
|
||||
// GitChangedMore is [git_changed_more]: "WARNING: {{.paths}} and {{.count}} more paths changed since devvm last checked, perhaps by {{.vm}}, and git on this machine runs what they hold. devvm can tell you only after the fact, so if you didn't change them, check them before you run git here."
|
||||
func GitChangedMore(count int, paths string, vm string) M {
|
||||
return M{id: "git_changed_more", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"paths", paths}, {"vm", vm}}}
|
||||
}
|
||||
|
||||
// GitCommondir is [git_commondir]: "WARNING: If you didn't make {{.git}}/commondir, check it before you run git here. It makes git read config from {{.target}}."
|
||||
func GitCommondir(git string, target string) M {
|
||||
return M{id: "git_commondir", vals: []val{{"git", git}, {"target", target}}}
|
||||
@@ -1459,11 +1469,6 @@ func GitProtectFailed(reason string) M {
|
||||
return M{id: "git_protect_failed", vals: []val{{"reason", reason}}}
|
||||
}
|
||||
|
||||
// GitProtectNeedsMacosNew is [git_protect_needs_macos_new]: ".git protection needs macOS, so this VM can change the hooks and config in .git, which run on this machine. To keep a VM out of .git, use devvm --clone."
|
||||
func GitProtectNeedsMacosNew() M {
|
||||
return M{id: "git_protect_needs_macos_new"}
|
||||
}
|
||||
|
||||
// GitProtectNextStop is [git_protect_next_stop]: "{{.vm}} is running, so devvm turns its .git protection {{.mode}} when the VM next stops. Run devvm stop or devvm restart to apply it now."
|
||||
func GitProtectNextStop(mode string, vm string) M {
|
||||
return M{id: "git_protect_next_stop", vals: []val{{"mode", mode}, {"vm", vm}}}
|
||||
@@ -1484,6 +1489,26 @@ func GitUnlocked(vm string) M {
|
||||
return M{id: "git_unlocked", vals: []val{{"vm", vm}}}
|
||||
}
|
||||
|
||||
// GitUnprotected is [git_unprotected]: ".git protection needs macOS, so {{.vm}} can change the hooks and config in .git, which run on this machine. To keep a VM out of .git, use devvm --clone, or run devvm git-protect off to stop this warning."
|
||||
func GitUnprotected(vm string) M {
|
||||
return M{id: "git_unprotected", vals: []val{{"vm", vm}}}
|
||||
}
|
||||
|
||||
// GitUnprotectedQuiet is [git_unprotected_quiet]: "devvm stops warning about .git at each launch of {{.vm}}, and it still names the hooks and config in .git that change."
|
||||
func GitUnprotectedQuiet(vm string) M {
|
||||
return M{id: "git_unprotected_quiet", vals: []val{{"vm", vm}}}
|
||||
}
|
||||
|
||||
// GitWatchBlind is [git_watch_blind]: "WARNING: Each of {{.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."
|
||||
func GitWatchBlind(paths string) M {
|
||||
return M{id: "git_watch_blind", vals: []val{{"paths", paths}}}
|
||||
}
|
||||
|
||||
// GitWatchBlindMore is [git_watch_blind_more]: "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."
|
||||
func GitWatchBlindMore(count int, paths string) M {
|
||||
return M{id: "git_watch_blind_more", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"paths", paths}}}
|
||||
}
|
||||
|
||||
// GitWorktreeStray is [git_worktree_stray]: "WARNING: If you didn't change {{.wt}}/commondir, check it before you run git in that linked worktree. It doesn't lead back to this repo, so git there reads config and hooks from somewhere else."
|
||||
func GitWorktreeStray(wt string) M {
|
||||
return M{id: "git_worktree_stray", vals: []val{{"wt", wt}}}
|
||||
@@ -4276,6 +4301,8 @@ var specs = map[string]spec{
|
||||
"gc_tools_no_vm": {plural: true, fields: []string{"count", "size", "tools"}},
|
||||
"gc_unfinished": {fields: []string{"key"}},
|
||||
"git_appeared": {},
|
||||
"git_changed": {fields: []string{"paths", "vm"}},
|
||||
"git_changed_more": {plural: true, fields: []string{"count", "paths", "vm"}},
|
||||
"git_commondir": {fields: []string{"git", "target"}},
|
||||
"git_config_failed": {fields: []string{"config"}},
|
||||
"git_embedded_new": {fields: []string{"git"}},
|
||||
@@ -4292,11 +4319,14 @@ var specs = map[string]spec{
|
||||
"git_not_locked": {fields: []string{"path"}},
|
||||
"git_protect_clone": {fields: []string{"vm"}},
|
||||
"git_protect_failed": {fields: []string{"reason"}},
|
||||
"git_protect_needs_macos_new": {},
|
||||
"git_protect_next_stop": {fields: []string{"mode", "vm"}},
|
||||
"git_protect_on_needs_macos": {},
|
||||
"git_replaced": {fields: []string{"git"}},
|
||||
"git_unlocked": {fields: []string{"vm"}},
|
||||
"git_unprotected": {fields: []string{"vm"}},
|
||||
"git_unprotected_quiet": {fields: []string{"vm"}},
|
||||
"git_watch_blind": {fields: []string{"paths"}},
|
||||
"git_watch_blind_more": {plural: true, fields: []string{"count", "paths"}},
|
||||
"git_worktree_stray": {fields: []string{"wt"}},
|
||||
"github_token_howto": {},
|
||||
"group_already": {fields: []string{"group", "vm"}},
|
||||
|
||||
@@ -285,3 +285,22 @@ func TestFromArgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// .git protection's messages on Linux hosts, which only a Linux host's
|
||||
// runs show: each renders whole, its values in place, and each links to
|
||||
// its page; the plural ones take their count.
|
||||
func TestGitWatchMessages(t *testing.T) {
|
||||
for _, m := range []M{
|
||||
GitUnprotected("vm-1"), GitUnprotectedQuiet("vm-1"), GitChanged(".git/config", "vm-1"),
|
||||
GitChangedMore(1, ".git/config", "vm-1"), GitChangedMore(3, ".git/config", "vm-1"),
|
||||
GitWatchBlind(".git/hooks"), GitWatchBlindMore(1, ".git/hooks"), GitWatchBlindMore(3, ".git/hooks"),
|
||||
} {
|
||||
text := m.Text()
|
||||
if strings.Contains(text, "{{") || strings.Contains(text, "<no value>") || m.DocURL() == "" {
|
||||
t.Errorf("%s: %q, link %q", m.ID(), text, m.DocURL())
|
||||
}
|
||||
}
|
||||
if one, many := GitChangedMore(1, "a", "v").Text(), GitChangedMore(3, "a", "v").Text(); !strings.Contains(one, "1 more path ") || !strings.Contains(many, "3 more paths ") {
|
||||
t.Errorf("plurals: %q, %q", one, many)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"strconv"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// ChangeID is a file's inode and change time, "ino I ctime S.N", which
|
||||
// any change to the file moves and nobody but the kernel sets: "" when fi
|
||||
// has none.
|
||||
func ChangeID(fi fs.FileInfo) string {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return "ino " + strconv.FormatUint(st.Ino, 10) + " ctime " +
|
||||
strconv.FormatInt(st.Ctimespec.Sec, 10) + "." + strconv.FormatInt(st.Ctimespec.Nsec, 10)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"strconv"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// ChangeID is a file's inode and change time, "ino I ctime S.N", which
|
||||
// any change to the file moves and nobody but the kernel sets: "" when fi
|
||||
// has none.
|
||||
func ChangeID(fi fs.FileInfo) string {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return "ino " + strconv.FormatUint(st.Ino, 10) + " ctime " +
|
||||
strconv.FormatInt(st.Ctim.Sec, 10) + "." + strconv.FormatInt(st.Ctim.Nsec, 10)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !darwin && !linux
|
||||
|
||||
package platform
|
||||
|
||||
import "io/fs"
|
||||
|
||||
// ChangeID is a file's inode and change time: not on this system yet.
|
||||
func ChangeID(fs.FileInfo) string { return "" }
|
||||
@@ -0,0 +1,49 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package platform
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A file's change ID moves with any change, its times set back
|
||||
// included, and a FileInfo without a stat has none.
|
||||
func TestChangeID(t *testing.T) {
|
||||
f := filepath.Join(t.TempDir(), "f")
|
||||
if err := os.WriteFile(f, []byte("one"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stat := func() string {
|
||||
fi, err := os.Lstat(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ChangeID(fi)
|
||||
}
|
||||
was := stat()
|
||||
if !strings.HasPrefix(was, "ino ") || !strings.Contains(was, " ctime ") {
|
||||
t.Fatalf("ChangeID %q", was)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if err := os.WriteFile(f, []byte("two"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chtimes(f, time.Unix(1, 0), time.Unix(1, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if now := stat(); now == was {
|
||||
t.Errorf("unchanged: %q", now)
|
||||
}
|
||||
if id := ChangeID(fakeInfo{}); id != "" {
|
||||
t.Errorf("no stat: %q", id)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeInfo is a FileInfo without a stat.
|
||||
type fakeInfo struct{ os.FileInfo }
|
||||
|
||||
func (fakeInfo) Sys() any { return nil }
|
||||
@@ -8,6 +8,9 @@ import "io/fs"
|
||||
// on this system.
|
||||
const NoBlock = 0
|
||||
|
||||
// NoFollow is the open flag that fails on a symlink: none on this system.
|
||||
const NoFollow = 0
|
||||
|
||||
// SameDevice reports whether two files are on the same file system: on
|
||||
// this system, always yes.
|
||||
func SameDevice(fs.FileInfo, fs.FileInfo) bool { return true }
|
||||
|
||||
@@ -12,6 +12,10 @@ import (
|
||||
// writer: a file a VM could swap in for one devvm reads.
|
||||
const NoBlock = syscall.O_NONBLOCK
|
||||
|
||||
// NoFollow is the open flag that fails on a symlink rather than opening
|
||||
// what it points to: a file a VM could swap for a link out of its folder.
|
||||
const NoFollow = syscall.O_NOFOLLOW
|
||||
|
||||
// SameDevice reports whether two files are on the same file system.
|
||||
func SameDevice(a, b fs.FileInfo) bool {
|
||||
sa, oka := a.Sys().(*syscall.Stat_t)
|
||||
|
||||
@@ -693,16 +693,16 @@ func (e Lifecycle) canSwitch(ctx context.Context, t *target, p remakeInVM, o Rem
|
||||
|
||||
// switchedTo sets st's sections for the clone mode a remake made its new
|
||||
// machine in (clone: CloneOn, CloneOff, or "" for the VM's): its own
|
||||
// clone, made as its shell opens, or the folder mounted, with mode its
|
||||
// .git protection (gitprotect.Protector.NewMode). What the old machine's
|
||||
// mode left on the host stays recorded until the old machine is gone
|
||||
// (leftBehind): .git's locks, or the clone's remote.
|
||||
func switchedTo(st *state.VM, clone, mode string) error {
|
||||
// clone, made as its shell opens, or the folder mounted, with git its
|
||||
// .git protection (gitprotect.Protector.NewSection). What the old
|
||||
// machine's mode left on the host stays recorded until the old machine is
|
||||
// gone (leftBehind): .git's locks, or the clone's remote.
|
||||
func switchedTo(st *state.VM, clone string, git gitprotect.InVM) error {
|
||||
switch clone {
|
||||
case CloneOn:
|
||||
return state.SetSection(st, cloneSection, cloneInVM{On: true})
|
||||
case CloneOff:
|
||||
if err := gitprotect.Set(st, gitprotect.InVM{Mode: mode}); err != nil {
|
||||
if err := gitprotect.Set(st, git); err != nil {
|
||||
return err
|
||||
}
|
||||
return edit(st, cloneSection, func(c *cloneInVM) error { c.On = false; return nil })
|
||||
|
||||
@@ -92,7 +92,7 @@ func (e Lifecycle) Adopt(ctx context.Context, name string, force bool) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
g.Made = gitprotect.Made{}
|
||||
g.Made, g.Watched = gitprotect.Made{}, gitprotect.Watched{}
|
||||
return gitprotect.Set(st, g)
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -300,7 +300,7 @@ func recordMove(ctx context.Context, st *state.VM, dir, id string, fresh bool) e
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
g.Made = gitprotect.Made{}
|
||||
g.Made, g.Watched = gitprotect.Made{}, gitprotect.Watched{}
|
||||
return gitprotect.Set(st, g)
|
||||
})
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/devvmhq/devvm/internal/backend"
|
||||
"github.com/devvmhq/devvm/internal/build"
|
||||
"github.com/devvmhq/devvm/internal/gitprotect"
|
||||
"github.com/devvmhq/devvm/internal/image"
|
||||
"github.com/devvmhq/devvm/internal/msg"
|
||||
"github.com/devvmhq/devvm/internal/platform"
|
||||
@@ -585,15 +586,15 @@ func (e remaking) finish(ctx context.Context, t *target, p remakeInVM, c chainOf
|
||||
// The new machine is the one by its name now, in its clone mode, with
|
||||
// what p read again, and its devcontainer.json's commands run again
|
||||
// on its new disk.
|
||||
mode := ""
|
||||
var git gitprotect.InVM
|
||||
if p.Clone == CloneOff {
|
||||
mode = e.Protector(t.f.Dir).NewMode(false)
|
||||
git = e.Protector(t.f.Dir).NewSection(false)
|
||||
}
|
||||
err := st.Update(ctx, func(st *state.VM) error {
|
||||
if err := madeWith(st, p); err != nil {
|
||||
return err
|
||||
}
|
||||
return switchedTo(st, p.Clone, mode)
|
||||
return switchedTo(st, p.Clone, git)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -76,13 +76,15 @@ func (e Settings) SetGitProtect(ctx context.Context, mode string) error {
|
||||
}
|
||||
|
||||
// setGitProtect sets a stopped VM's .git protection, and says what it
|
||||
// did.
|
||||
// did: on a host without locks, off quiets the launches' warning.
|
||||
func setGitProtect(ctx context.Context, e *Env, p *gitprotect.Protector, t *target, mode string) error {
|
||||
vm := t.f.Name
|
||||
if err := p.Set(ctx, t.st, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
switch _, err := os.Lstat(filepath.Join(t.f.Dir, ".git")); {
|
||||
case mode == gitprotect.Off && !p.CanLock:
|
||||
e.Info(msg.GitUnprotectedQuiet(vm))
|
||||
case mode == gitprotect.Off:
|
||||
e.Info(msg.GitUnlocked(vm))
|
||||
case err != nil:
|
||||
|
||||
@@ -45,7 +45,8 @@ type upOpts struct {
|
||||
// agent folder mounts matched to the host's, and a running VM that gets
|
||||
// changes at its next start stopped once the user agrees
|
||||
// (restartForNextStart); its
|
||||
// project folder checked on the host (hostChecks); what it needs of its
|
||||
// project folder checked on the host (hostChecks), and on a host without
|
||||
// .git locks, a warning that its .git is unprotected (WarnUnprotected); what it needs of its
|
||||
// backend refused where the backend can't (requirements); the user's
|
||||
// agent checked for keys when it forwards it; then a stopped VM started
|
||||
// (start), or a running one gone on with as it runs (runningConfinement),
|
||||
@@ -77,6 +78,7 @@ func (s starter) bringUp(ctx context.Context, t *target, o upOpts) (backend.Conf
|
||||
if err := s.hostChecks(ctx, t, running, o.made); err != nil {
|
||||
return backend.Confinement{}, err
|
||||
}
|
||||
s.Protector(t.f.Dir).WarnUnprotected(st)
|
||||
need, err := startNeeds(st, in)
|
||||
if err != nil {
|
||||
return backend.Confinement{}, err
|
||||
@@ -366,7 +368,8 @@ func (s starter) refuse(b backend.Backend, vm string, fs []backend.Feature) erro
|
||||
// its .git locked as its protection says (NewVM), the SSH origin it
|
||||
// can't push to without an agent named, and its set-id files. A VM that
|
||||
// exists gets its .git checked under the protection it ran with
|
||||
// (gitprotect's Check), so what it changed meanwhile is named; then, once
|
||||
// (gitprotect's Check), so what it changed meanwhile is named (on a host
|
||||
// without locks, what changed of what a lock would cover); then, once
|
||||
// it's stopped, 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.
|
||||
|
||||
+6
-6
@@ -175,9 +175,9 @@ type newVM struct {
|
||||
size Size
|
||||
ports string
|
||||
net netpolicy.Tier
|
||||
agent string // sshagent.On or Off
|
||||
clone bool // --clone
|
||||
git string // its .git protection (gitprotect.Protector.NewMode), or gitprotect.Clone
|
||||
agent string // sshagent.On or Off
|
||||
clone bool // --clone
|
||||
git gitprotect.InVM // its .git protection (gitprotect.Protector.NewSection), or gitprotect.Clone's
|
||||
// from is the container image its base starts from: --from's, or its
|
||||
// devcontainer.json's image, pinned.
|
||||
from string
|
||||
@@ -458,9 +458,9 @@ func (e creation) plan(ctx context.Context, o Options, f project.Folder, b backe
|
||||
n.agent = sshagent.On
|
||||
}
|
||||
if o.Clone {
|
||||
n.clone, n.git = true, gitprotect.Clone
|
||||
n.clone, n.git = true, gitprotect.InVM{Mode: gitprotect.Clone}
|
||||
} else {
|
||||
n.git = e.Protector(f.Dir).NewMode(o.NoGitProtect)
|
||||
n.git = e.Protector(f.Dir).NewSection(o.NoGitProtect)
|
||||
}
|
||||
// Its ports, which devvm's forwarder forwards from the backend's ssh,
|
||||
// and a clone, copied in and fetched over ssh.
|
||||
@@ -613,7 +613,7 @@ func (n newVM) record(st *state.VM, tg tools.Target, files []string) error {
|
||||
}
|
||||
for _, err := range []error{
|
||||
netpolicy.Set(st, netpolicy.Net{Tier: n.net}),
|
||||
gitprotect.Set(st, gitprotect.InVM{Mode: n.git}),
|
||||
gitprotect.Set(st, n.git),
|
||||
sshagent.Set(st, sshagent.InVM{Mode: n.agent}),
|
||||
tools.Set(st, tools.InVM{Names: n.tools, Made: tools.Made{Files: files, Libc: tg.Libc, Glibc: tg.Glibc}}),
|
||||
ports.Set(st, ports.Ports{Forward: forward}),
|
||||
|
||||
+23
-2
@@ -2034,8 +2034,29 @@ other = "The project folder has set-user-id or set-group-id files, which run as
|
||||
description = "files is a space-separated list of paths"
|
||||
other = "The project folder has set-id files owned by root, which run as root for anyone who runs them: {{.files}}. Don't run them, and delete them with sudo rm FILE."
|
||||
|
||||
[git_protect_needs_macos_new]
|
||||
other = ".git protection needs macOS, so this VM can change the hooks and config in .git, which run on this machine. To keep a VM out of .git, use devvm --clone."
|
||||
[git_unprotected]
|
||||
other = ".git protection needs macOS, so {{.vm}} can change the hooks and config in .git, which run on this machine. To keep a VM out of .git, use devvm --clone, or run devvm git-protect off to stop this warning."
|
||||
|
||||
[git_unprotected_quiet]
|
||||
other = "devvm stops warning about .git at each launch of {{.vm}}, and it still names the hooks and config in .git that change."
|
||||
|
||||
[git_changed]
|
||||
description = "paths is a comma-separated list of paths relative to the project folder"
|
||||
other = "WARNING: {{.paths}} changed since devvm last checked, perhaps by {{.vm}}, and git on this machine runs what they hold. devvm can tell you only after the fact, so if you didn't change them, check them before you run git here."
|
||||
|
||||
[git_changed_more]
|
||||
description = "paths is a comma-separated list of paths relative to the project folder; count is how many more changed"
|
||||
one = "WARNING: {{.paths}} and 1 more path changed since devvm last checked, perhaps by {{.vm}}, and git on this machine runs what they hold. devvm can tell you only after the fact, so if you didn't change them, check them before you run git here."
|
||||
other = "WARNING: {{.paths}} and {{.count}} more paths changed since devvm last checked, perhaps by {{.vm}}, and git on this machine runs what they hold. devvm can tell you only after the fact, so if you didn't change them, check them before you run git here."
|
||||
|
||||
[git_watch_blind]
|
||||
description = "paths is a comma-separated list of paths relative to the project folder"
|
||||
other = "WARNING: Each of {{.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_watch_blind_more]
|
||||
description = "paths is a comma-separated list of paths relative to the project folder; count is how many more there are"
|
||||
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."
|
||||
|
||||
[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."
|
||||
|
||||
Vendored
+3
-1
@@ -10,7 +10,9 @@ vm_name WEB web
|
||||
stub_reset
|
||||
exec devvm
|
||||
! stdout 'starting|creating'
|
||||
! stderr .
|
||||
# Each launch on Linux says .git is unprotected (git_watch.txtar).
|
||||
[!linux] ! stderr .
|
||||
[linux] stderr '\Adevvm: git_unprotected vm=devvm-web-[0-9a-f]{14}\n\z'
|
||||
stub_calls
|
||||
! stdout 'limactl (start|stop|clone|create|edit|delete)'
|
||||
stdout '^limactl shell --workdir / devvm-web-[0-9a-f]{14} sh -c .*tar -xf - '
|
||||
|
||||
Vendored
+1
-1
@@ -22,7 +22,7 @@ exec devvm git-protect
|
||||
[darwin] stdout '\Aon\n\z'
|
||||
[linux] stdout '\Aoff\n\z'
|
||||
[linux] exec devvm git-protect off
|
||||
[linux] stdout '^==> git_unlocked vm=devvm-web-[0-9a-f]{14}$'
|
||||
[linux] stdout '^==> git_unprotected_quiet vm=devvm-web-[0-9a-f]{14}$'
|
||||
[linux] ! exec devvm git-protect strict
|
||||
[linux] stderr '^devvm: git_protect_on_needs_macos$'
|
||||
[linux] stop 'no locks off macOS'
|
||||
|
||||
Vendored
+79
@@ -0,0 +1,79 @@
|
||||
# On a host without .git locks (Linux), each launch warns that the VM can
|
||||
# change the hooks and config in .git, until devvm git-protect off says
|
||||
# the user knows. Each launch that finds the VM stopped, and devvm stop,
|
||||
# name what changed of what a lock would cover since the last check: the
|
||||
# new VM's first sums are recorded when it's made, and a VM with none
|
||||
# recorded (an older devvm's) records its first without naming anything.
|
||||
# A --clone VM mounts no .git, so neither applies.
|
||||
[!linux] skip 'macOS locks .git: git_protect.txtar'
|
||||
env GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t
|
||||
|
||||
# A new VM: warned, its first sums recorded, nothing named.
|
||||
project web git
|
||||
exec devvm --network open
|
||||
vm_name WEB web
|
||||
stderr '^devvm: git_unprotected vm=devvm-web-[0-9a-f]{14}$'
|
||||
! stderr git_changed
|
||||
vm_state $WEB_dir/vm.json
|
||||
stdout '^git.watched.scanned=true$'
|
||||
stdout '^git.watched.sums..git/config=sha256 [0-9a-f]{64}$'
|
||||
! stdout 'git.chosen'
|
||||
|
||||
# While it runs, a launch warns again and checks nothing.
|
||||
exec git config core.fsmonitor ./evil
|
||||
cp $WORK/hook .git/hooks/pre-commit
|
||||
exec devvm
|
||||
stderr '^devvm: git_unprotected vm=devvm-web-[0-9a-f]{14}$'
|
||||
! stderr git_changed
|
||||
|
||||
# devvm stop names what changed, once.
|
||||
exec devvm stop
|
||||
stderr '^devvm: git_changed paths=\.git/config, \.git/hooks/pre-commit vm=devvm-web-[0-9a-f]{14}$'
|
||||
! stderr git_unprotected
|
||||
exec devvm stop
|
||||
! stderr git_changed
|
||||
|
||||
# So does a launch that finds it stopped, before it starts.
|
||||
exec limactl stop $WEB
|
||||
rm .git/hooks/pre-commit
|
||||
exec devvm
|
||||
stderr '^devvm: git_changed paths=\.git/hooks/pre-commit vm=devvm-web-[0-9a-f]{14}$'
|
||||
|
||||
# devvm git-protect off is the user's choice: the warning stops, the watch
|
||||
# goes on.
|
||||
exec devvm git-protect off
|
||||
stdout '^==> git_unprotected_quiet vm=devvm-web-[0-9a-f]{14}$'
|
||||
vm_state $WEB_dir/vm.json
|
||||
stdout '^git.chosen=true$'
|
||||
exec devvm
|
||||
! stderr git_unprotected
|
||||
exec git config core.sshCommand ./evil
|
||||
exec devvm stop
|
||||
stderr '^devvm: git_changed paths=\.git/config vm=devvm-web-[0-9a-f]{14}$'
|
||||
|
||||
# A VM an older devvm made has no sums: its first check records them and
|
||||
# names nothing.
|
||||
json_set $WEB_dir/vm.json git.watched:=null
|
||||
exec git config core.pager ./evil
|
||||
exec devvm stop
|
||||
! stderr git_changed
|
||||
vm_state $WEB_dir/vm.json
|
||||
stdout '^git.watched.scanned=true$'
|
||||
|
||||
# --no-git-protect is the user's choice too.
|
||||
project quiet git
|
||||
exec devvm --no-git-protect --network open
|
||||
! stderr git_unprotected
|
||||
|
||||
# A --clone VM: neither.
|
||||
project cloned
|
||||
exec git init -q -b main
|
||||
exec git commit -q --allow-empty -m one
|
||||
exec devvm --clone --network open
|
||||
! stderr git_unprotected
|
||||
exec git config core.fsmonitor ./evil
|
||||
exec devvm stop
|
||||
! stderr git_changed
|
||||
|
||||
-- hook --
|
||||
#!/bin/sh
|
||||
Vendored
+3
-3
@@ -23,8 +23,8 @@ stdout '^==> starting vm=devvm-web-[0-9a-f]{14}$'
|
||||
# None of devvm's own files written out: they stay in the binary.
|
||||
! exists $XDG_DATA_HOME/devvm/assets
|
||||
# .git unprotected off macOS, and devvm says so.
|
||||
[darwin] ! stderr git_protect_needs_macos_new
|
||||
[linux] stderr '^devvm: git_protect_needs_macos_new$'
|
||||
[darwin] ! stderr git_unprotected
|
||||
[linux] stderr '^devvm: git_unprotected vm=devvm-web-[0-9a-f]{14}$'
|
||||
stub_calls
|
||||
stdout '^limactl clone --tty=false devvm-img-[0-9a-f]{12} devvm-web-[0-9a-f]{14} --mount-none --set \.mounts = \[\{"location":"[^"]*/web","writable":true\},\{"location":"[^"]*/data/devvm/tools","mountPoint":"/mnt/devvm-tools","writable":false\}\] --set \.ssh\.forwardAgent=false --set \.ssh\.localPort=[1-9][0-9]+ --set \.portForwards = \[\{"guestIP":"127\.0\.0\.1","guestPortRange":\[1,65535\],"proto":"any","ignore":true\},\{"guestIP":"0\.0\.0\.0","guestPortRange":\[1,65535\],"proto":"any","ignore":true\},\{"guestIP":"::","guestPortRange":\[1,65535\],"proto":"any","ignore":true\}\] --set \.propagateProxyEnv=true --set \.env = \{"NODE_EXTRA_CA_CERTS":.*\}$'
|
||||
# Its first start's one edit: its proxy in its environment (the
|
||||
@@ -98,7 +98,7 @@ stub_reset
|
||||
exec devvm --network open --no-git-protect
|
||||
! stdout building_image
|
||||
stderr '^devvm: ssh_remote_hint vm=devvm-api-[0-9a-f]{14}$'
|
||||
! stderr git_protect_needs_macos_new
|
||||
! stderr git_unprotected
|
||||
stub_calls
|
||||
! stdout chflags
|
||||
vm_name API api
|
||||
|
||||
@@ -495,7 +495,7 @@ func projectGit(s *S, w *webVM) {
|
||||
p, vm := w.p, w.vm
|
||||
if runtime.GOOS != "darwin" {
|
||||
s.Check("off on Linux (no chflags), and says so", func() error {
|
||||
if w.state(s)["git.mode"] != "off" || !grepF(w.launch, s.Msg("git_protect_needs_macos_new")) {
|
||||
if w.state(s)["git.mode"] != "off" || !grepF(w.launch, s.Msg("git_unprotected", "vm="+vm)) {
|
||||
return errors.New("git protection isn't off, or the launch didn't say so")
|
||||
}
|
||||
return nil
|
||||
@@ -781,6 +781,7 @@ func projectGitProtect(s *S, w *webVM) {
|
||||
}
|
||||
return nil
|
||||
})
|
||||
projectGitWatch(s, w)
|
||||
return
|
||||
}
|
||||
s.Check("a swapped .git is reported", func() error {
|
||||
@@ -886,6 +887,35 @@ func projectGitProtect(s *S, w *webVM) {
|
||||
})
|
||||
}
|
||||
|
||||
// projectGitWatch: on Linux, .git/config that the VM changes is named
|
||||
// when devvm stop finds it, after the fact; then the VM is as it was.
|
||||
func projectGitWatch(s *S, w *webVM) {
|
||||
p, vm := w.p, w.vm
|
||||
s.Check("on Linux, devvm stop names the .git/config the VM changed", func() error {
|
||||
if _, err := DevvmIn(s, p, "exit\n", nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.InVM(vm, "printf '[e2e]\\n\\twatched = vm\\n' >> "+p+"/.git/config"); err != nil {
|
||||
return err
|
||||
}
|
||||
r, err := s.Devvm(p, "stop")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !grepF(r.Out, s.Msg("git_changed", "paths=.git/config", "vm="+vm)) {
|
||||
return errors.New("devvm stop didn't name .git/config:\n" + r.Out)
|
||||
}
|
||||
if again, _ := s.Devvm(p, "stop"); grepF(again.Out, s.Msg("git_changed", "paths=.git/config", "vm="+vm)) {
|
||||
return errors.New("named twice:\n" + again.Out)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// Put back, and recorded as that by another devvm stop, then started again.
|
||||
_, _ = s.Run(Cmd{Args: []string{"git", "config", "--unset", "e2e.watched"}, Dir: p})
|
||||
_, _ = s.Devvm(p, "stop")
|
||||
_, _ = DevvmIn(s, p, "exit\n", nil)
|
||||
}
|
||||
|
||||
// claudeSlug is the name Claude Code gives a folder's sessions' folder.
|
||||
func claudeSlug(dir string) string {
|
||||
return regexp.MustCompile(`[^a-zA-Z0-9]`).ReplaceAllString(dir, "-")
|
||||
|
||||
Reference in new issue
Block a user