| 1 | |
| 2 | |
| 3 | |
| 4 | package osutil |
| 5 | |
| 6 | import ( |
| 7 | "net" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "testing" |
| 11 | |
| 12 | "gotest.tools/v3/assert" |
| 13 | ) |
| 14 | |
| 15 | func TestWriteFileBeneathDir(t *testing.T) { |
| 16 | base := t.TempDir() |
| 17 | dir := filepath.Join(base, "mnt") |
| 18 | assert.NilError(t, os.MkdirAll(dir, 0o700)) |
| 19 | |
| 20 | |
| 21 | regular := filepath.Join(dir, "config") |
| 22 | assert.NilError(t, WriteFileBeneathDir(regular, []byte("ok\n"), 0o600)) |
| 23 | got, err := os.ReadFile(regular) |
| 24 | assert.NilError(t, err) |
| 25 | assert.Equal(t, string(got), "ok\n") |
| 26 | |
| 27 | |
| 28 | |
| 29 | secret := filepath.Join(base, "authorized_keys") |
| 30 | assert.NilError(t, os.WriteFile(secret, []byte("ORIGINAL\n"), 0o600)) |
| 31 | linked := filepath.Join(dir, "linked") |
| 32 | assert.NilError(t, os.Symlink(secret, linked)) |
| 33 | |
| 34 | err = WriteFileBeneathDir(linked, []byte("ATTACKER\n"), 0o600) |
| 35 | assert.Assert(t, err != nil, "expected the symlinked write to be refused") |
| 36 | got, err = os.ReadFile(secret) |
| 37 | assert.NilError(t, err) |
| 38 | assert.Equal(t, string(got), "ORIGINAL\n") |
| 39 | } |
| 40 | |
| 41 | func TestRemoveStaleSocket(t *testing.T) { |
| 42 | base := t.TempDir() |
| 43 | |
| 44 | |
| 45 | assert.NilError(t, RemoveStaleSocket(filepath.Join(base, "absent"))) |
| 46 | |
| 47 | |
| 48 | file := filepath.Join(base, "file") |
| 49 | assert.NilError(t, os.WriteFile(file, []byte("keep\n"), 0o600)) |
| 50 | assert.Assert(t, RemoveStaleSocket(file) != nil, "expected a regular file to be refused") |
| 51 | assert.Assert(t, FileExists(file), "regular file must not be removed") |
| 52 | |
| 53 | |
| 54 | dir := filepath.Join(base, "dir") |
| 55 | assert.NilError(t, os.MkdirAll(dir, 0o700)) |
| 56 | assert.NilError(t, os.WriteFile(filepath.Join(dir, "child"), []byte("keep\n"), 0o600)) |
| 57 | assert.Assert(t, RemoveStaleSocket(dir) != nil, "expected a directory to be refused") |
| 58 | assert.Assert(t, FileExists(filepath.Join(dir, "child")), "directory contents must not be removed") |
| 59 | |
| 60 | |
| 61 | sock := filepath.Join(base, "sock") |
| 62 | var lc net.ListenConfig |
| 63 | l, err := lc.Listen(t.Context(), "unix", sock) |
| 64 | assert.NilError(t, err) |
| 65 | defer l.Close() |
| 66 | assert.NilError(t, RemoveStaleSocket(sock)) |
| 67 | assert.Assert(t, !FileExists(sock), "stale socket must be removed") |
| 68 | } |