Skip to content

Commit 7261d8b

Browse files
committed
Use a private lock file for API storage ownership
Keep the lock on one persistent inode without requiring private read access to the whole data directory. Check its type, owner and permissions before flock, and verify that exec releases the descriptor. Document storage cutovers as offline operations: guest metadata and socket paths retain the configured directory name.
1 parent c0f044f commit 7261d8b

6 files changed

Lines changed: 78 additions & 20 deletions

File tree

‎DEVELOPMENT.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -229,13 +229,19 @@ cp config.example.yaml ~/.config/hypeman/config.yaml
229229

230230
### Data directory
231231

232-
Hypeman stores data in a configurable directory. Configure permissions for this directory.
232+
Only the daemon account and trusted administrators should be able to write to `data_dir`.
233233

234234
```bash
235235
sudo mkdir /var/lib/hypeman
236236
sudo chown $USER:$USER /var/lib/hypeman
237237
```
238238

239+
The API takes an exclusive lock on `<data_dir>/.hypeman.lock` before loading guest state.
240+
Leave this file in place across restarts; the OS releases the lock when the process exits.
241+
Stop the old API process before upgrading or downgrading, because older versions do not take this lock.
242+
243+
Guest metadata and socket paths use the configured directory name. Stop the guests and the API before moving or remounting the directory or repointing a symlink in its path.
244+
239245
### Dockerhub login
240246

241247
Requires Docker Hub authentication to avoid rate limits when running the tests:
@@ -271,8 +277,7 @@ The server will start on port 4973 (configurable via `port` in config.yaml).
271277
### Shared-Machine Local Config
272278

273279
When developing on a shared host, avoid global paths like `/etc/hypeman` and `/var/lib/hypeman`.
274-
Only one API process can use a data directory at a time. Stop the old process before upgrading or downgrading; older versions do not take the directory lock.
275-
Use a workspace-local config and data directory instead:
280+
Use a workspace-local config and [data directory](#data-directory) instead:
276281

277282
```bash
278283
mkdir -p .tmp/hypeman-data

‎cmd/api/config/config.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,7 @@ func Load(configPath string) (*Config, error) {
587587

588588
func (c *Config) expandPathFields() {
589589
if c.DataDir != "" {
590-
// Match filepath.Join's handling of ".." before locking the directory itself.
590+
// Direct lookups of data_dir must agree with filepath.Join's handling of "..".
591591
c.DataDir = filepath.Clean(expandHomePath(c.DataDir))
592592
}
593593
c.Build.SecretsDir = expandHomePath(c.Build.SecretsDir)

‎cmd/api/data_dir_lock.go‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,43 @@ import (
44
"errors"
55
"fmt"
66
"os"
7+
"path/filepath"
78

89
"golang.org/x/sys/unix"
910
)
1011

11-
// lockDataDir holds the directory lock until process exit. Background writers
12-
// can outlive run(), so leave the raw descriptor open rather than deferring Close.
12+
const dataDirLockName = ".hypeman.lock"
13+
14+
// lockDataDir holds the lock until process exit. Background writers can outlive
15+
// run(), so leave the raw descriptor open on success. Never unlink the file:
16+
// the next opener must lock the same inode.
1317
func lockDataDir(path string) error {
1418
if err := os.MkdirAll(path, 0755); err != nil {
1519
return err
1620
}
17-
fd, err := unix.Open(path, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
21+
name := filepath.Join(path, dataDirLockName)
22+
fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0600)
1823
if err != nil {
19-
return err
24+
return &os.PathError{Op: "open", Path: name, Err: err}
2025
}
21-
if err := unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB); err != nil {
26+
if err := lockPrivateFile(fd); err != nil {
2227
unix.Close(fd)
23-
if errors.Is(err, unix.EWOULDBLOCK) {
24-
return fmt.Errorf("another Hypeman process is using this directory: %w", err)
25-
}
26-
return err
28+
return fmt.Errorf("%s: %w", name, err)
2729
}
2830
return nil
2931
}
32+
33+
func lockPrivateFile(fd int) error {
34+
var st unix.Stat_t
35+
if err := unix.Fstat(fd, &st); err != nil {
36+
return err
37+
}
38+
if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0077 != 0 || st.Uid != uint32(os.Geteuid()) {
39+
return errors.New("lock file must be a private regular file owned by the daemon user")
40+
}
41+
err := unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB)
42+
if errors.Is(err, unix.EWOULDBLOCK) {
43+
return fmt.Errorf("another Hypeman process is using this directory: %w", err)
44+
}
45+
return err
46+
}

‎cmd/api/data_dir_lock_test.go‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@ func runLockTestChild(t *testing.T, dataDir string) {
2323
require.NoError(t, err, "%s", out)
2424
}
2525

26-
func lockTestDir(t *testing.T, path string) {
26+
func lockTestFile(t *testing.T, path string) {
2727
t.Helper()
28-
dir, err := os.Open(path)
28+
f, err := os.OpenFile(filepath.Join(path, dataDirLockName), os.O_RDWR, 0)
2929
require.NoError(t, err)
30-
t.Cleanup(func() { dir.Close() })
31-
require.NoError(t, unix.Flock(int(dir.Fd()), unix.LOCK_EX|unix.LOCK_NB))
30+
t.Cleanup(func() { f.Close() })
31+
require.NoError(t, unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB))
3232
}
3333

3434
func TestServerRefusesSecondWriterBeforeStartup(t *testing.T) {
@@ -38,13 +38,15 @@ func TestServerRefusesSecondWriterBeforeStartup(t *testing.T) {
3838
}
3939

4040
path := t.TempDir()
41-
lockTestDir(t, path)
41+
require.NoError(t, os.WriteFile(filepath.Join(path, dataDirLockName), nil, 0600))
42+
lockTestFile(t, path)
4243
alias := filepath.Join(t.TempDir(), "same-data")
4344
require.NoError(t, os.Symlink(path, alias))
4445
runLockTestChild(t, alias)
4546
entries, err := os.ReadDir(path)
4647
require.NoError(t, err)
47-
require.Empty(t, entries, "the second API must not initialize or recover anything")
48+
require.Len(t, entries, 1, "the second API must not initialize or recover anything")
49+
require.Equal(t, dataDirLockName, entries[0].Name())
4850
}
4951

5052
func TestServerKeepsStorageDirectoryLockedUntilExit(t *testing.T) {
@@ -61,5 +63,37 @@ func TestServerKeepsStorageDirectoryLockedUntilExit(t *testing.T) {
6163
link := filepath.Join(path, "link")
6264
require.NoError(t, os.Symlink(t.TempDir(), link))
6365
runLockTestChild(t, link+"/..") // Preserve the uncleaned path in the child's configuration.
64-
lockTestDir(t, path)
66+
info, err := os.Stat(filepath.Join(path, dataDirLockName))
67+
require.NoError(t, err)
68+
require.Equal(t, os.FileMode(0600), info.Mode())
69+
lockTestFile(t, path)
70+
}
71+
72+
func TestDataDirLockDoesNotSurviveExec(t *testing.T) {
73+
switch os.Getenv(lockTestChild) {
74+
case "1":
75+
require.NoError(t, lockDataDir(os.Getenv("DATA_DIR")))
76+
t.Setenv(lockTestChild, "after-exec")
77+
require.NoError(t, unix.Exec(os.Args[0], os.Args, os.Environ()))
78+
case "after-exec":
79+
lockTestFile(t, os.Getenv("DATA_DIR"))
80+
default:
81+
runLockTestChild(t, filepath.Join(t.TempDir(), "data"))
82+
}
83+
}
84+
85+
func TestDataDirLockRejectsPublicLockFile(t *testing.T) {
86+
dir := t.TempDir()
87+
name := filepath.Join(dir, dataDirLockName)
88+
require.NoError(t, os.WriteFile(name, nil, 0600))
89+
require.NoError(t, os.Chmod(name, 0644))
90+
require.ErrorContains(t, lockDataDir(dir), "private regular file")
91+
}
92+
93+
func TestDataDirLockRejectsSymlink(t *testing.T) {
94+
dir := t.TempDir()
95+
target := filepath.Join(t.TempDir(), "target")
96+
require.NoError(t, os.WriteFile(target, nil, 0600))
97+
require.NoError(t, os.Symlink(target, filepath.Join(dir, dataDirLockName)))
98+
require.ErrorIs(t, lockDataDir(dir), unix.ELOOP)
6599
}

‎config.example.darwin.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ jwt_secret: dev-secret-change-me
2626
# - "<previous-or-next-secret>"
2727

2828
# Data directory - use macOS conventions
29+
# Stop guests and the API before moving the directory or repointing a symlink in its path.
2930
# Note: ~ is NOT expanded; use full path or let the install script fill this in
3031
data_dir: ~/Library/Application Support/hypeman
3132

‎config.example.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ jwt_secret: ""
2626
# - 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
2727

2828
# Data directory (default: /var/lib/hypeman)
29+
# Stop guests and the API before moving the directory or repointing a symlink in its path.
2930
data_dir: /var/lib/hypeman
3031

3132
# Server configuration

0 commit comments

Comments
 (0)