applier: refuse to clobber a symlinked LICENSE (#33) #40

Merged
KofTwentyTwo merged 1 commits from feature/GH-33-symlink-license into develop 2026-06-09 15:17:56 +00:00
3 changed files with 145 additions and 14 deletions

No files matched your search

+26
View File
@@ -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)
+33 -12
View File
@@ -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()
}
+86 -2
View File
@@ -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.