diff --git a/analyzer/scan.go b/analyzer/scan.go index f40f9d8..60ee9cb 100644 --- a/analyzer/scan.go +++ b/analyzer/scan.go @@ -79,12 +79,15 @@ func RunCapslock(args []string, output string, pkgs []*packages.Package, queried // Build a map of packages to unique capabilities. capabilitiesByPackageSets := make(map[string]map[string]struct{}) for _, capabilityInfo := range cil.CapabilityInfo { + // The Capability enum field is unset when the capability is a + // caller-defined one that isn't in the enum, so use the name instead. + capability := capabilityInfo.GetCapabilityName() for _, path := range capabilityInfo.Path { if _, ok := capabilitiesByPackageSets[*path.Package]; ok { - capabilitiesByPackageSets[*path.Package][capabilityInfo.Capability.String()] = struct{}{} + capabilitiesByPackageSets[*path.Package][capability] = struct{}{} } else { capabilitiesByPackageSets[*path.Package] = map[string]struct{}{ - capabilityInfo.Capability.String(): {}, + capability: {}, } } } diff --git a/testing/analyzepackages_test.go b/testing/analyzepackages_test.go index 129cee0..d1dd0fd 100644 --- a/testing/analyzepackages_test.go +++ b/testing/analyzepackages_test.go @@ -8,11 +8,14 @@ package analyzepackages_test import ( "bytes" + "encoding/json" "fmt" "log" "os" "os/exec" + "path/filepath" "regexp" + "slices" "strings" "sync" "testing" @@ -464,6 +467,35 @@ func TestCompare(t *testing.T) { } } +// TestPackageOutput checks that -output=package works when the capability map +// defines a capability that isn't one of the Capability enum values. The +// Capability field is left unset for those capabilities, so the package output +// mode has to report the capability name instead. +func TestPackageOutput(t *testing.T) { + name := filepath.Join(t.TempDir(), "custom.cm") + if err := os.WriteFile(name, []byte("func os.Getpid TESTCAP\n"), 0o600); err != nil { + t.Fatalf("writing capability map: %v", err) + } + cmd := exec.Command(bin, "-packages=../testpkgs/callos", "-output=package", "-capability_map="+name) + var output bytes.Buffer + cmd.Stdout = &output + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + t.Fatalf("running capslock: %v", err) + } + got := make(map[string][]string) + if err := json.Unmarshal(output.Bytes(), &got); err != nil { + t.Fatalf("parsing output %q: %v", output.String(), err) + } + caps, ok := got["github.com/google/capslock/testpkgs/callos"] + if !ok { + t.Fatalf("output %q does not mention the callos package", output.String()) + } + if !slices.Contains(caps, "TESTCAP") { + t.Errorf("capabilities of the callos package are %v, want them to include TESTCAP", caps) + } +} + func TestVersionFlag(t *testing.T) { out, err := exec.Command(bin, "-version").CombinedOutput() if err != nil {