Repository navigation
Expand file tree
/
Copy pathsystem_files_test.go
More file actions
310 lines (251 loc) · 11.4 KB
/
Copy pathsystem_files_test.go
File metadata and controls
310 lines (251 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package fest
import (
"encoding/hex"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// TestSystemFilesDir_DuplicateDirectoriesDeduped tests that SystemFilesDir now deduplicates
func TestSystemFilesDir_DuplicateDirectoriesDeduped(t *testing.T) {
// Reset global state
original := systemFilesDirs
defer func() { systemFilesDirs = original }()
systemFilesDirs = []string{"system"}
// FIXED: SystemFilesDir now deduplicates
// for _, existing := range systemFilesDirs {
// if existing == dir {
// return
// }
// }
// Add same directory twice
SystemFilesDir("system")
SystemFilesDir("system")
SystemFilesDir("other")
SystemFilesDir("system") // Try again
// Should have unique entries only
require.Equal(t, 2, len(systemFilesDirs),
"Should deduplicate: %v", systemFilesDirs)
require.Contains(t, systemFilesDirs, "system")
require.Contains(t, systemFilesDirs, "other")
}
// TestListSystemDirFiles_OverwriteCollisionWarning tests that collisions are now warned about
func TestListSystemDirFiles_OverwriteCollisionWarning(t *testing.T) {
original := systemFilesDirs
defer func() { systemFilesDirs = original }()
// Create two directories with files targeting same destination
tmpDir := t.TempDir()
dir1 := filepath.Join(tmpDir, "dir1")
dir2 := filepath.Join(tmpDir, "dir2")
os.MkdirAll(filepath.Join(dir1, "etc"), 0755)
os.MkdirAll(filepath.Join(dir2, "etc"), 0755)
os.WriteFile(filepath.Join(dir1, "etc", "config"), []byte("version1"), 0644)
os.WriteFile(filepath.Join(dir2, "etc", "config"), []byte("version2"), 0644)
systemFilesDirs = []string{dir1, dir2}
files, err := listSystemDirFiles()
require.NoError(t, err)
// FIXED: listSystemDirFiles() now detects collisions
// targetToSources := make(map[string][]string)
// targetToSources[targetPath] = append(targetToSources[targetPath], path)
// if len(sources) > 1 {
// slog.Warn("Multiple source files target same destination (last one wins)", ...)
// }
// Count distinct target paths
targetPaths := make(map[string][]string)
for srcPath, targetPath := range files {
targetPaths[targetPath] = append(targetPaths[targetPath], srcPath)
}
// The collision is tracked, and both sources are retained
require.Contains(t, targetPaths, "/etc/config", "Target path should exist")
require.ElementsMatch(t, []string{
filepath.Join(dir1, "etc", "config"),
filepath.Join(dir2, "etc", "config"),
}, targetPaths["/etc/config"], "Should track both sources that target /etc/config")
}
// TestHashBytes_HasPrefix tests that hashBytes includes "sha256:" prefix
// for hash algorithm identification and forward compatibility
func TestHashBytes_HasPrefix(t *testing.T) {
data := []byte("test content")
hash := hashBytes(data)
// Hash should include "sha256:" prefix for algorithm identification
require.True(t, strings.HasPrefix(hash, "sha256:"),
"Hash should have 'sha256:' prefix for algorithm identification")
// Verify hex part is valid
hexPart := strings.TrimPrefix(hash, "sha256:")
_, err := hex.DecodeString(hexPart)
require.NoError(t, err, "Hex part should be valid hex string")
require.Equal(t, 64, len(hexPart), "SHA256 hex should be 64 characters")
}
// TestBackupFile_PathConstruction tests the backup path construction logic
func TestBackupFile_PathConstruction(t *testing.T) {
targetPath := "/etc/hosts"
content := []byte("127.0.0.1 localhost")
relBackupPath, err := backupFile(targetPath, content)
require.NoError(t, err)
// Verify path is constructed correctly
expected := filepath.Join("backups", "etc", "hosts.backup")
require.Equal(t, expected, relBackupPath,
"Backup path should be backups/etc/hosts.backup, got: %s", relBackupPath)
// Cleanup
os.RemoveAll(filepath.Join(stateDir(), "backups", "etc"))
}
// TestDeleteBackup_EmptyPathHandling tests edge case handling
func TestDeleteBackup_EmptyPathHandling(t *testing.T) {
// Empty paths should return nil
err := deleteBackup("")
require.NoError(t, err, "Empty path should be handled gracefully")
}
// TestListSystemDirFiles_EmptyDirHandling tests that empty directory strings
// are skipped properly
func TestListSystemDirFiles_EmptyDirHandling(t *testing.T) {
original := systemFilesDirs
defer func() { systemFilesDirs = original }()
systemFilesDirs = []string{"", "", ""}
files, err := listSystemDirFiles()
require.NoError(t, err)
require.Empty(t, files, "Empty directories should be skipped")
}
// TestListSystemDirFiles_NonexistentDir tests error handling for missing directories
func TestListSystemDirFiles_NonexistentDir(t *testing.T) {
original := systemFilesDirs
defer func() { systemFilesDirs = original }()
systemFilesDirs = []string{"/this/path/definitely/does/not/exist/12345"}
files, err := listSystemDirFiles()
// Bug: The function returns early on first error, but should it?
// Should it collect files from other valid dirs and just warn about bad ones?
require.Error(t, err, "Nonexistent directory should cause error")
require.NotNil(t, files, "Files map should not be nil even on error")
}
// TestListInstalled_IncludesOrphansInState tests that a file whose source was
// deleted from the system dirs is still reported as installed (from state), so
// apply offers to remove it instead of leaving it behind forever.
func TestListInstalled_IncludesOrphansInState(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
target := filepath.Join(home, "etc", "sddm.conf.d", "retro.conf")
require.NoError(t, os.MkdirAll(filepath.Dir(target), 0755))
require.NoError(t, os.WriteFile(target, []byte("old"), 0644))
require.NoError(t, saveState(&systemFilesState{Version: 1, Files: map[string]fileState{
target: {InstalledHash: hashBytes([]byte("old"))},
}}))
original := systemFilesDirs
defer func() { systemFilesDirs = original }()
emptySource := filepath.Join(home, "system")
require.NoError(t, os.MkdirAll(emptySource, 0755))
systemFilesDirs = []string{emptySource}
installed, err := systemFiles{}.ListInstalled()
require.NoError(t, err)
require.Contains(t, installed, target, "orphaned tracked file should be reported installed")
}
// TestListInstalled_SkipsReplacedOrphans tests that a tracked file whose source
// was deleted but whose on-disk content no longer matches what fest installed
// (e.g. a package reinstall restored the vendor default) is NOT reported as
// installed, so fest stops flagging it as unnecessary.
func TestListInstalled_SkipsReplacedOrphans(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
target := filepath.Join(home, "etc", "pam.d", "login")
require.NoError(t, os.MkdirAll(filepath.Dir(target), 0755))
require.NoError(t, os.WriteFile(target, []byte("vendor default"), 0644))
require.NoError(t, saveState(&systemFilesState{Version: 1, Files: map[string]fileState{
target: {InstalledHash: hashBytes([]byte("fest content"))},
}}))
original := systemFilesDirs
defer func() { systemFilesDirs = original }()
emptySource := filepath.Join(home, "system")
require.NoError(t, os.MkdirAll(emptySource, 0755))
systemFilesDirs = []string{emptySource}
installed, err := systemFiles{}.ListInstalled()
require.NoError(t, err)
require.NotContains(t, installed, target,
"file replaced by something else must no longer be reported installed")
}
// TestReadFileWithSudo_RegularFile tests normal file reading without sudo
func TestReadFileWithSudo_RegularFile(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "test.txt")
expectedContent := []byte("test content")
err := os.WriteFile(testFile, expectedContent, 0644)
require.NoError(t, err)
content, err := readFileWithSudo(testFile)
require.NoError(t, err)
require.Equal(t, expectedContent, content)
}
// TestReadFileWithSudo_NonexistentFile tests error handling for missing files
func TestReadFileWithSudo_NonexistentFile(t *testing.T) {
content, err := readFileWithSudo("/tmp/this-file-does-not-exist-12345.txt")
require.Error(t, err)
require.Nil(t, content)
}
// systemFilesBugFakeSudo installs a `sudo` shim at the front of PATH so the
// Install/Uninstall code paths (which shell out to sudo) can execute without
// real root. The shim no-ops sudo's auth probes and otherwise runs the command.
func systemFilesBugFakeSudo(t *testing.T) {
t.Helper()
bin := t.TempDir()
script := "#!/bin/sh\ncase \"$1\" in -n|-v) exit 0 ;; esac\nexec \"$@\"\n"
require.NoError(t, os.WriteFile(filepath.Join(bin, "sudo"), []byte(script), 0755))
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
}
// TestSystemFilesBugListInstalledWhitespaceContent documents that ListInstalled
// must compare file contents exactly. A target that differs from the source
// only by surrounding whitespace (e.g. a missing trailing newline) is NOT the
// declared file and must be reported as not-installed so apply re-deploys it.
//
// Bug: ListInstalled compared strings.TrimSpace(src) == strings.TrimSpace(dst),
// so whitespace-only differences were silently treated as up to date.
func TestSystemFilesBugListInstalledWhitespaceContent(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
const relDir = "fest_bug_sysfiles_ws"
rel := filepath.Join("tmp", relDir, "app.conf")
src := filepath.Join(home, "system")
require.NoError(t, os.MkdirAll(filepath.Join(src, filepath.Dir(rel)), 0755))
require.NoError(t, os.WriteFile(filepath.Join(src, rel), []byte("content\n"), 0644))
target := "/" + rel
require.NoError(t, os.MkdirAll(filepath.Dir(target), 0755))
// Different content: missing the trailing newline the source declares.
require.NoError(t, os.WriteFile(target, []byte("content"), 0644))
t.Cleanup(func() { os.RemoveAll("/tmp/" + relDir) })
orig := systemFilesDirs
defer func() { systemFilesDirs = orig }()
systemFilesDirs = []string{src}
installed, err := systemFiles{}.ListInstalled()
require.NoError(t, err)
require.NotContains(t, installed, target,
"target whose content differs from source must not be reported as installed")
}
// TestSystemFilesBugInstallPartialStateNotPersisted documents that when Install
// deploys several files and one of them fails, the state of the files that were
// already successfully deployed must still be persisted. Today Install only
// calls saveState at the very end, so an early return discards the tracking of
// files that were already written to disk, leaving them unrestorable/orphaned.
//
// Bug: Install returned from inside the loop on error without persisting state
// accumulated for previously deployed files.
func TestSystemFilesBugInstallPartialStateNotPersisted(t *testing.T) {
systemFilesBugFakeSudo(t)
home := t.TempDir()
t.Setenv("HOME", home)
const relDir = "fest_bug_sysfiles_partial"
rel := filepath.Join("tmp", relDir, "ok.conf")
src := filepath.Join(home, "system")
require.NoError(t, os.MkdirAll(filepath.Join(src, filepath.Dir(rel)), 0755))
require.NoError(t, os.WriteFile(filepath.Join(src, rel), []byte("hello"), 0644))
okTarget := "/" + rel
t.Cleanup(func() { os.RemoveAll("/tmp/" + relDir) })
orig := systemFilesDirs
defer func() { systemFilesDirs = orig }()
systemFilesDirs = []string{src}
// First op deploys fine; second op has no source and aborts the batch.
err := systemFiles{}.Install([]string{okTarget, "/definitely/not/a/managed/target"})
require.Error(t, err)
_, statErr := os.Stat(okTarget)
require.NoError(t, statErr, "first file should have been deployed")
state, loadErr := loadState()
require.NoError(t, loadErr)
_, tracked := state.Files[okTarget]
require.True(t, tracked,
"successfully deployed file must be tracked even when a later op fails")
}