mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 14:33:17 -10:00
fix(sshconfig): change known_hosts under its own lock
Pinning or forgetting a VM's host keys takes known_hosts.lock (an OS file lock, paths.Dirs.KnownHostsLock), reads the file again inside it and writes it whole with state.WriteFile, so two devvms at once lose neither's pin. ForgetHostKeys takes its caller's ctx. TestHostKeyConcurrent holds two pins' reads until both have read; it fails on the unlocked code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
9 files changed
+155
-22
No files matched your search
@@ -131,7 +131,7 @@ The two folders use two formats. `config.toml` is TOML, which devvm reads strict
|
||||
In the data folder, each VM has a folder of its own, `vms/<hash>/` ([a VM's folder](#a-vms-folder)), and the rest is shared by every VM:
|
||||
|
||||
- `settings.json` holds the defaults devvm's commands save, below `config.toml`'s ([where a default comes from](../using/settings.md#where-a-default-comes-from)).
|
||||
- `ssh_config` is the [ssh config](security.md#ssh-into-vms) for running VMs, and `known_hosts` holds their pinned host keys.
|
||||
- `ssh_config` is the [ssh config](security.md#ssh-into-vms) for running VMs, and `known_hosts` holds their pinned host keys, changed under `known_hosts.lock` ([locks](#locks)).
|
||||
- `agent-keys.json` lists the keys added to [devvm's own SSH agent](../using/ssh.md#devvms-own-agent), with each one's file, fingerprint, `confirm` and `lifetime`, and `agent.sock` is that agent's socket.
|
||||
- `secrets/` holds each [secret](network.md#where-secrets-are-saved) in a file of its own, on hosts without a Keychain.
|
||||
- `images/<key>/record.json` is each image's record, and `images/rebuilds.json` holds the [rebuild counters](images.md#rebuilding), by backend, `--from` and image.
|
||||
@@ -200,6 +200,7 @@ Every lock devvm takes is an OS file lock on an open file, which the system lets
|
||||
| `oci-build.lock` | a Lima build of a base [from a container image](images.md#how-its-converted) |
|
||||
| `tools.lock` | a devvm [writing to the share](images.md#building-tools) or swapping the tools lock |
|
||||
| `making.lock` | each devvm making a VM or giving one new shared tools, shared, and `devvm gc --tool-images --force`, alone ([cleaning up](images.md#listing-and-cleaning-up)) |
|
||||
| `known_hosts.lock` | a devvm pinning a VM's host keys in `known_hosts` or forgetting them, which reads the file again once it holds the lock, so two devvms changing it at once lose neither's change |
|
||||
| `groups.lock` | a devvm [joining or leaving a group](design.md#groups), or working its links out again |
|
||||
| `retention.lock` | the devvm applying the [retention settings](../using/settings.md#retention) |
|
||||
|
||||
|
||||
@@ -268,3 +268,8 @@ func (d Dirs) SSHConfig() string { return filepath.Join(d.Data, "ssh_config") }
|
||||
|
||||
// KnownHosts holds the VMs' SSH host keys.
|
||||
func (d Dirs) KnownHosts() string { return filepath.Join(d.Data, "known_hosts") }
|
||||
|
||||
// KnownHostsLock is the lock file each devvm changing the known hosts
|
||||
// file holds, so that two pinning or forgetting keys at once lose neither
|
||||
// change.
|
||||
func (d Dirs) KnownHostsLock() string { return filepath.Join(d.Data, "known_hosts.lock") }
|
||||
@@ -123,6 +123,7 @@ func TestFiles(t *testing.T) {
|
||||
{d.Secrets(), "/d/secrets"},
|
||||
{d.SSHConfig(), "/d/ssh_config"},
|
||||
{d.KnownHosts(), "/d/known_hosts"},
|
||||
{d.KnownHostsLock(), "/d/known_hosts.lock"},
|
||||
{d.QEMUWrapper(), "/d/run/qemu"},
|
||||
{d.ToolImage("go-1.2.0-0123456789ab.erofs"), "/d/tools/go-1.2.0-0123456789ab.erofs"},
|
||||
{d.ShareLock(), "/d/tools.lock"},
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/w3cj/devvm/internal/backend"
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/paths"
|
||||
"github.com/w3cj/devvm/internal/platform"
|
||||
"github.com/w3cj/devvm/internal/sshagent"
|
||||
"github.com/w3cj/devvm/internal/state"
|
||||
"github.com/w3cj/devvm/internal/vmname"
|
||||
@@ -272,7 +273,36 @@ func (c *Config) recordHostKeys(ctx context.Context, b backend.Backend, vm strin
|
||||
if keys == "" {
|
||||
return false, nil
|
||||
}
|
||||
return true, state.WriteFile(path, append(data, keys...))
|
||||
return true, c.changeKnownHosts(ctx, func(data []byte) []byte {
|
||||
if hasHost(data, vm) {
|
||||
return data
|
||||
}
|
||||
return append(data, keys...)
|
||||
})
|
||||
}
|
||||
|
||||
// changeKnownHosts changes the known hosts file under its lock, reading
|
||||
// it again inside, so that two devvms changing it at once lose neither's
|
||||
// change; change gets the file as it is and returns it as it's to be.
|
||||
func (c *Config) changeKnownHosts(ctx context.Context, change func([]byte) []byte) error {
|
||||
if err := state.PrivateDir(c.Dirs.Data); err != nil {
|
||||
return err
|
||||
}
|
||||
unlock, err := platform.LockFile(ctx, c.Dirs.KnownHostsLock())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlock()
|
||||
path := c.Dirs.KnownHosts()
|
||||
data, err := os.ReadFile(path) //nolint:gosec // devvm's own file
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
out := change(data)
|
||||
if bytes.Equal(out, data) {
|
||||
return nil
|
||||
}
|
||||
return state.WriteFile(path, out)
|
||||
}
|
||||
|
||||
// HostKey returns vm's host key as the known hosts file pins it (TYPE
|
||||
@@ -332,26 +362,27 @@ func hasHost(data []byte, vm string) bool {
|
||||
|
||||
// ForgetHostKeys drops vm's host keys, to be read again once it runs: a
|
||||
// VM whose backend config changed can get new ones when it boots.
|
||||
func (c *Config) ForgetHostKeys(vm string) error {
|
||||
path := c.Dirs.KnownHosts()
|
||||
data, err := os.ReadFile(path) //nolint:gosec // devvm's own file
|
||||
func (c *Config) ForgetHostKeys(ctx context.Context, vm string) error {
|
||||
data, err := os.ReadFile(c.Dirs.KnownHosts())
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil || !hasHost(data, vm) {
|
||||
return err
|
||||
}
|
||||
var keep []string
|
||||
for l := range strings.SplitSeq(strings.TrimSuffix(string(data), "\n"), "\n") {
|
||||
if !strings.HasPrefix(l, vm+" ") {
|
||||
keep = append(keep, l)
|
||||
return c.changeKnownHosts(ctx, func(data []byte) []byte {
|
||||
var keep []string
|
||||
for l := range strings.SplitSeq(strings.TrimSuffix(string(data), "\n"), "\n") {
|
||||
if !strings.HasPrefix(l, vm+" ") {
|
||||
keep = append(keep, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
out := ""
|
||||
if len(keep) > 0 {
|
||||
out = strings.Join(keep, "\n") + "\n"
|
||||
}
|
||||
return state.WriteFile(path, []byte(out))
|
||||
out := ""
|
||||
if len(keep) > 0 {
|
||||
out = strings.Join(keep, "\n") + "\n"
|
||||
}
|
||||
return []byte(out)
|
||||
})
|
||||
}
|
||||
|
||||
// IncludeLine is the line ~/.ssh/config needs to read devvm's ssh config.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package sshconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
@@ -354,24 +355,24 @@ Host devvm-web ` + web + `
|
||||
t.Errorf("ssh config with one alias twice:\n%s", got)
|
||||
}
|
||||
delete(f.Instances, web2)
|
||||
if err := c.ForgetHostKeys(web2); err != nil {
|
||||
if err := c.ForgetHostKeys(t.Context(), web2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Forgotten keys are read again; forgetting keeps the others.
|
||||
if err := c.ForgetHostKeys(web); err != nil {
|
||||
if err := c.ForgetHostKeys(t.Context(), web); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(t, kh); got != imgish+" ssh-ed25519 AAAAkeydevvmimgfooabc123abc123ab\n" {
|
||||
t.Errorf("known hosts after forgetting %s = %q", web, got)
|
||||
}
|
||||
if err := c.ForgetHostKeys(imgish); err != nil {
|
||||
if err := c.ForgetHostKeys(t.Context(), imgish); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(t, kh); got != "" {
|
||||
t.Errorf("known hosts after forgetting both = %q", got)
|
||||
}
|
||||
if err := c.ForgetHostKeys(api); err != nil {
|
||||
if err := c.ForgetHostKeys(t.Context(), api); err != nil {
|
||||
t.Errorf("forgetting a VM with no keys: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -518,6 +519,98 @@ func TestHostKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// bothRead holds each Exec until two have started, so both callers have
|
||||
// read the known hosts file before either writes it.
|
||||
type bothRead struct {
|
||||
*backendtest.Fake
|
||||
both sync.WaitGroup
|
||||
}
|
||||
|
||||
func (b *bothRead) Exec(ctx context.Context, vm string, argv []string, o backend.ExecOpts) error {
|
||||
b.both.Done()
|
||||
b.both.Wait()
|
||||
return b.Fake.Exec(ctx, vm, argv, o)
|
||||
}
|
||||
|
||||
// Two devvms pinning different VMs' keys at once keep both: each has read
|
||||
// the file before either writes, and the write reads it again under the
|
||||
// lock.
|
||||
func TestHostKeyConcurrent(t *testing.T) {
|
||||
c, f := testConfig(t)
|
||||
b := &bothRead{Fake: f}
|
||||
b.both.Add(2)
|
||||
var wg sync.WaitGroup
|
||||
for _, vm := range []string{web, api} {
|
||||
wg.Go(func() {
|
||||
if _, err := c.HostKey(t.Context(), b, vm); err != nil {
|
||||
t.Errorf("%s: %v", vm, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
data, err := os.ReadFile(c.Dirs.KnownHosts())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !hasHost(data, web) || !hasHost(data, api) {
|
||||
t.Errorf("known hosts lost a pin:\n%s", data)
|
||||
}
|
||||
|
||||
// Two pinning one VM at once pin it once.
|
||||
b = &bothRead{Fake: f}
|
||||
b.both.Add(2)
|
||||
for range 2 {
|
||||
wg.Go(func() {
|
||||
if _, err := c.HostKey(t.Context(), b, imgish); err != nil {
|
||||
t.Errorf("%s: %v", imgish, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
if got := strings.Count(read(t, c.Dirs.KnownHosts()), imgish+" "); got != 1 {
|
||||
t.Errorf("%s pinned %d times", imgish, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A change to known hosts that changes nothing writes nothing, and one
|
||||
// whose folder or file can't be read fails.
|
||||
func TestChangeKnownHosts(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _ := testConfig(t)
|
||||
same := func(data []byte) []byte { return data }
|
||||
if err := c.changeKnownHosts(t.Context(), same); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(c.Dirs.KnownHosts()); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("no change wrote the file: %v", err)
|
||||
}
|
||||
if err := os.Mkdir(c.Dirs.KnownHosts(), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.changeKnownHosts(t.Context(), same); err == nil {
|
||||
t.Error("a folder at known_hosts was read")
|
||||
}
|
||||
if err := os.Remove(c.Dirs.KnownHosts()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(c.Dirs.KnownHostsLock()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(c.Dirs.KnownHostsLock(), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.changeKnownHosts(t.Context(), same); err == nil {
|
||||
t.Error("a folder at the lock was locked")
|
||||
}
|
||||
c.Dirs.Data = filepath.Join(c.Dirs.KnownHostsLock(), "x")
|
||||
if err := os.WriteFile(c.Dirs.Data, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.changeKnownHosts(t.Context(), same); err == nil {
|
||||
t.Error("a file at the data folder was used")
|
||||
}
|
||||
}
|
||||
|
||||
// In a terminal, the Include line is added once said yes to, at the top
|
||||
// of the user's config, before its Host blocks, and its ~/.ssh made the
|
||||
// user's alone; no leaves the file as it was. --ssh-config adds it
|
||||
|
||||
@@ -27,7 +27,7 @@ func devvm() rules {
|
||||
largeTypes: map[string]large{
|
||||
"internal/backend/lima.Lima": {71, "a backend: backend.Backend's 25 methods, KeyFiles, DiskDirs, Floors, Usage, Location, Strays, DevvmCache, DeleteCache and Lima's own"},
|
||||
"internal/backend/backendtest.Fake": {31, "backend.Backend's 25 methods and what tests ask of it"},
|
||||
"internal/paths.Dirs": {49, "one method per folder or file devvm uses: a list (a VM's own files are paths.VM's)"},
|
||||
"internal/paths.Dirs": {50, "one method per folder or file devvm uses: a list (a VM's own files are paths.VM's)"},
|
||||
"internal/ui.UI": {47, "the one terminal: messages and where they go, as text or names, errors with the caller's exit code, prompts and whether one can show, status line, tables, run log and how many are kept, cleanups, signals"},
|
||||
},
|
||||
allowedVars: devvmVars(),
|
||||
|
||||
+1
-1
@@ -530,7 +530,7 @@ func (e *Env) start(ctx context.Context, b backend.Backend, st *state.VM, conf b
|
||||
} else if a.Made.Toggle && !e.Registry.Allowed(b, backend.FeatureAgentToggle) {
|
||||
return conf, e.Registry.Require(b, vm, backend.FeatureAgentToggle)
|
||||
}
|
||||
if err := e.sshConfig().ForgetHostKeys(vm); err != nil {
|
||||
if err := e.sshConfig().ForgetHostKeys(ctx, vm); err != nil {
|
||||
return conf, err
|
||||
}
|
||||
// A link session of its last start's, which would end on its own: the
|
||||
|
||||
@@ -37,7 +37,7 @@ func (e vmFolders) teardown(ctx context.Context, t *found, leaves bool) error {
|
||||
if err := Groups(e).forget(ctx, vm); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := e.sshConfig().ForgetHostKeys(vm); err != nil {
|
||||
if err := e.sshConfig().ForgetHostKeys(ctx, vm); err != nil {
|
||||
return err
|
||||
}
|
||||
if f, ok := backend.As[backend.Forgetter](t.b); ok && leaves {
|
||||
|
||||
Vendored
+2
@@ -90,6 +90,7 @@ images/X/record.json
|
||||
images/locks
|
||||
images/locks/X
|
||||
known_hosts
|
||||
known_hosts.lock
|
||||
logs
|
||||
logs/runs
|
||||
logs/runs/X.log
|
||||
@@ -157,6 +158,7 @@ images/X/record.json
|
||||
images/locks
|
||||
images/locks/X
|
||||
known_hosts
|
||||
known_hosts.lock
|
||||
logs
|
||||
logs/runs
|
||||
logs/runs/X.log
|
||||
|
||||
Reference in new issue
Block a user