From 05157ddf480ce56af68fa90b2c78653a149b40de Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 9 Jun 2026 08:00:58 -0500 Subject: [PATCH] fix(#33): refuse to overwrite a symlinked license file AtomicWrite used os.Stat + os.Rename with no symlink check, so writing a managed LICENSE / LICENSES/.txt that is a deliberate symlink (e.g. LICENSE -> LICENSES/MIT.txt) would replace the link with a regular file, silently breaking it. AtomicWrite now lstats the target and refuses with errSymlinkTarget when it is a symlink, leaving the link and its target untouched. The error message contains "refusing to write" so the CLI's isWriteRefusal mapping classifies it as a write refusal (exit code 3). writeManaged propagates this refusal as a returned error (other write failures stay recorded per-file as before). Closes #33 --- cmd/license-tool/commands_test.go | 26 +++++++++ internal/applier/applier.go | 45 +++++++++++----- internal/applier/applier_test.go | 88 ++++++++++++++++++++++++++++++- 3 files changed, 145 insertions(+), 14 deletions(-) diff --git a/cmd/license-tool/commands_test.go b/cmd/license-tool/commands_test.go index 5b602c2..b975e7d 100644 --- a/cmd/license-tool/commands_test.go +++ b/cmd/license-tool/commands_test.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" @@ -828,6 +829,31 @@ func TestLicenseCommand(t *testing.T) { assert.True(t, os.IsNotExist(statErr)) }) + t.Run("symlinked LICENSE is refused with the write-refused exit code", func(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation is restricted on windows") + } + dir := fixtureDir(t) + initGitRepo(t, dir) + target := filepath.Join(dir, "LICENSES", "AGPL-3.0-or-later.txt") + require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755)) + require.NoError(t, os.WriteFile(target, []byte("real license text\n"), 0o644)) + require.NoError(t, os.Symlink(target, filepath.Join(dir, "LICENSE"))) + + _, err := runRoot(t, "license", dir, "--write", "--allow-dirty") + require.Error(t, err) + assert.Contains(t, err.Error(), "refusing to write") + assert.Equal(t, exitWriteRefused, exitCode(err), "symlink refusal must map to the write-refused exit code") + + // The link survives as a link and its target is untouched. + fi, lerr := os.Lstat(filepath.Join(dir, "LICENSE")) + require.NoError(t, lerr) + assert.NotZero(t, fi.Mode()&os.ModeSymlink) + got, rerr := os.ReadFile(target) + require.NoError(t, rerr) + assert.Equal(t, "real license text\n", string(got)) + }) + t.Run("commit flags create scoped license-file commit", func(t *testing.T) { dir := fixtureDir(t) initGitRepo(t, dir) diff --git a/internal/applier/applier.go b/internal/applier/applier.go index e832480..d043c4c 100644 --- a/internal/applier/applier.go +++ b/internal/applier/applier.go @@ -229,23 +229,30 @@ func ManageLicenseFiles(path string, cfg model.Config, opts Options) ([]model.Fi return nil, err } - return []model.FileResult{ - writeManaged(path, "LICENSE", []byte(body), opts), - writeManaged(path, filepath.Join("LICENSES", cfg.License+".txt"), []byte(entry), opts), - }, nil + licenseFR, lerr := writeManaged(path, "LICENSE", []byte(body), opts) + if lerr != nil { + return nil, lerr + } + entryFR, eerr := writeManaged(path, filepath.Join("LICENSES", cfg.License+".txt"), []byte(entry), opts) + if eerr != nil { + return nil, eerr + } + return []model.FileResult{licenseFR, entryFR}, nil } // writeManaged computes the action/diff for a managed whole-file (LICENSE or a -// LICENSES entry) and, on --write, atomically writes it. It never errors the run; -// a write failure is recorded on the result so one bad path does not abort apply. -func writeManaged(root, rel string, want []byte, opts Options) model.FileResult { +// LICENSES entry) and, on --write, atomically writes it. A symlinked target is a hard +// refusal returned as an error so the CLI reports a write refusal rather than +// clobbering the link into a regular file; every other write failure is recorded on +// the result (and not returned) so one bad path does not abort the whole run. +func writeManaged(root, rel string, want []byte, opts Options) (model.FileResult, error) { abs := filepath.Join(root, rel) fr := model.FileResult{Path: rel, FileType: "license", Action: "none"} existing, rerr := os.ReadFile(abs) switch { case rerr == nil && string(existing) == string(want): - return fr + return fr, nil case rerr == nil: fr.Action = "replace" default: @@ -259,13 +266,16 @@ func writeManaged(root, rel string, want []byte, opts Options) model.FileResult if opts.Write { if mkerr := os.MkdirAll(filepath.Dir(abs), 0o755); mkerr != nil { fr.Err = mkerr.Error() - return fr + return fr, nil } if werr := AtomicWrite(abs, want); werr != nil { + if errors.Is(werr, errSymlinkTarget) { + return fr, werr + } fr.Err = werr.Error() } } - return fr + return fr, nil } // tmpWrite, tmpClose, and chmodFn are seams over the temp-file write/close and the @@ -278,12 +288,23 @@ var ( chmodFn = os.Chmod ) +// errSymlinkTarget is returned when a write target is itself a symlink. Its message +// contains "refusing to write" so the CLI's isWriteRefusal mapping classifies it as a +// write refusal (exit code 3) rather than a generic internal error. +var errSymlinkTarget = errors.New("applier: refusing to write through a symlink") + // AtomicWrite writes content to path via a temp-file-then-rename so a crash never -// leaves a half-written source file. It preserves the original file mode. +// leaves a half-written source file. It preserves the original file mode. If path is +// itself a symlink it refuses rather than clobbering the link: os.Rename would replace +// the symlink with a regular file, silently breaking a deliberate link such as +// LICENSE -> LICENSES/MIT.txt. func AtomicWrite(path string, content []byte) error { dir := filepath.Dir(path) mode := os.FileMode(0o644) - if fi, err := os.Stat(path); err == nil { + if fi, err := os.Lstat(path); err == nil { + if fi.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("%w: %s", errSymlinkTarget, path) + } mode = fi.Mode().Perm() } diff --git a/internal/applier/applier_test.go b/internal/applier/applier_test.go index deb1ca2..c2f2711 100644 --- a/internal/applier/applier_test.go +++ b/internal/applier/applier_test.go @@ -328,6 +328,41 @@ func TestAtomicWriteChmodError(t *testing.T) { require.ErrorIs(t, err, boom) } +// TestAtomicWriteRefusesSymlink confirms AtomicWrite refuses to replace a target +// that is a symlink (e.g. LICENSE -> LICENSES/MIT.txt) rather than clobbering it +// into a regular file. The link must be left intact and its target untouched. +func TestAtomicWriteRefusesSymlink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation is restricted on windows") + } + dir := t.TempDir() + target := filepath.Join(dir, "LICENSES", "MIT.txt") + require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755)) + require.NoError(t, os.WriteFile(target, []byte("original target\n"), 0o644)) + + link := filepath.Join(dir, "LICENSE") + require.NoError(t, os.Symlink(target, link)) + + err := AtomicWrite(link, []byte("clobbered\n")) + require.Error(t, err) + assert.Contains(t, err.Error(), "refusing to write", "refusal must match the write-refusal exit-code mapping") + assert.ErrorIs(t, err, errSymlinkTarget) + + // The symlink itself must survive as a symlink. + fi, lerr := os.Lstat(link) + require.NoError(t, lerr) + assert.NotZero(t, fi.Mode()&os.ModeSymlink, "LICENSE must still be a symlink") + + // The link target must be unchanged (not clobbered through the link). + got, rerr := os.ReadFile(target) + require.NoError(t, rerr) + assert.Equal(t, "original target\n", string(got)) + + dest, rlerr := os.Readlink(link) + require.NoError(t, rlerr) + assert.Equal(t, target, dest, "link destination must be unchanged") +} + // --- ApplyFile ------------------------------------------------------------ // agplHeaderFunc returns a HeaderRenderFunc that renders the canonical AGPL header @@ -588,7 +623,8 @@ func TestWriteManagedMkdirError(t *testing.T) { // "LICENSES" exists as a FILE, so MkdirAll(LICENSES) fails for the entry write. require.NoError(t, os.WriteFile(filepath.Join(root, "LICENSES"), []byte("x"), 0o644)) - fr := writeManaged(root, filepath.Join("LICENSES", "AGPL-3.0-or-later.txt"), []byte("body"), Options{Write: true}) + fr, err := writeManaged(root, filepath.Join("LICENSES", "AGPL-3.0-or-later.txt"), []byte("body"), Options{Write: true}) + require.NoError(t, err) assert.NotEmpty(t, fr.Err) } @@ -609,10 +645,58 @@ func TestWriteManagedWriteError(t *testing.T) { require.NoError(t, os.Mkdir(roDir, 0o555)) t.Cleanup(func() { _ = os.Chmod(roDir, 0o755) }) - fr := writeManaged(roDir, "LICENSE", []byte("body"), Options{Write: true}) + fr, err := writeManaged(roDir, "LICENSE", []byte("body"), Options{Write: true}) + require.NoError(t, err) assert.NotEmpty(t, fr.Err) } +// TestWriteManagedRefusesSymlink confirms the managed license-file write path +// surfaces a symlinked target as a returned refusal (so the CLI exit-code mapping +// reports a write refusal) rather than silently clobbering the link. +func TestWriteManagedRefusesSymlink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation is restricted on windows") + } + root := t.TempDir() + target := filepath.Join(root, "LICENSES", "AGPL-3.0-or-later.txt") + require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755)) + require.NoError(t, os.WriteFile(target, []byte("real license text\n"), 0o644)) + require.NoError(t, os.Symlink(target, filepath.Join(root, "LICENSE"))) + + _, err := ManageLicenseFiles(root, agplConfig(), Options{Write: true}) + require.Error(t, err) + assert.Contains(t, err.Error(), "refusing to write") + assert.ErrorIs(t, err, errSymlinkTarget) + + // The symlink and its target must be untouched. + fi, lerr := os.Lstat(filepath.Join(root, "LICENSE")) + require.NoError(t, lerr) + assert.NotZero(t, fi.Mode()&os.ModeSymlink) + got, rerr := os.ReadFile(target) + require.NoError(t, rerr) + assert.Equal(t, "real license text\n", string(got)) +} + +// TestLicenseRefusesSymlinkTarget confirms the refusal propagates through the +// public License entry point, where the CLI maps it to the write-refused exit code. +func TestLicenseRefusesSymlinkTarget(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation is restricted on windows") + } + root := t.TempDir() + gitInit(t, root) + writeFile(t, root, "main.go", "package main\n") + gitAddCommit(t, root) + target := filepath.Join(root, "LICENSES", "AGPL-3.0-or-later.txt") + require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755)) + require.NoError(t, os.WriteFile(target, []byte("real license text\n"), 0o644)) + require.NoError(t, os.Symlink(target, filepath.Join(root, "LICENSE"))) + + _, err := License(root, agplConfig(), Options{Write: true, AllowDirty: true}) + require.Error(t, err) + assert.Contains(t, err.Error(), "refusing to write") +} + // --- Apply: validation and dry-run ---------------------------------------- // TestApplyUnknownLicense rejects an unknown SPDX id up front. -- 2.54.0