diff --git a/.plumber.yaml b/.plumber.yaml index b63ce8d1..34b9d096 100644 --- a/.plumber.yaml +++ b/.plumber.yaml @@ -1301,3 +1301,100 @@ github: - ACTIONS_STEP_DEBUG - ACTIONS_RUNNER_DEBUG +# ============================================================================ +# mise (mise-en-place) +# ============================================================================ +# Top level, like gitlab and github: mise does not depend on the provider, +# the same block applies to a GitHub or a GitLab repository. It drives the +# mise-en-place control. Remove the block, or set +# `enabled: false`, and nothing is scanned or reported. A check whose +# block (lockfile, versions, sources, tasks) is absent does not run. +# +# The files are read from the local checkout. A run without one (a remote +# --project run) reports the control as not evaluated. +# +# Best practice: commit mise.lock with a checksum for every download, and +# install with `mise install --locked` in CI. +mise: + # Set to false to disable every mise check + enabled: true + # Set to true to report a repository that commits no mise config + # (ISSUE-1010). A .tool-versions file alone does not count. + required: false + # Every mise config that declares tools has its lockfile committed + # (mise.toml -> mise.lock, mise..toml -> mise..lock), every tool + # request has a matching lock entry, and every locked download carries a + # checksum. A request Plumber cannot read statically (a template) or a + # format 0 lockfile is reported as not locked. A mise file that cannot + # be read or parsed stops the run with an error listing every such + # file. + lockfile: + enabled: true + requireChecksums: true + # Backends whose locked downloads must record a provenance + # (SLSA, cosign, minisign, GitHub attestations), globs allowed. + # requireProvenance: ["aqua:*"] + # Provenance kinds a locked download may record; any other kind is + # reported. Defaults to every kind mise records. + # trustedProvenance: [slsa, github-attestations, cosign, minisign] + # Platforms every tool that locks downloads must lock. + # requiredPlatforms: [linux-x64, linux-arm64] + # Oldest accepted lockfile_version. + # minimumLockfileVersion: 1 + # No tool request in a mise config uses a forbidden version (globs). + # The request as written is what people review: with `latest`, the + # lockfile pins a version, but `mise lock --bump` or `mise upgrade` moves + # it with no change in mise.toml (ISSUE-1011). A request Plumber cannot + # read statically (a template) is ISSUE-1012. A bare major such as "24" is + # not caught by this list. "ref:*" is left out: a ref pinned to a commit + # SHA cannot move. Add it to forbid every git ref. + versions: + enabled: true + forbiddenVersions: + - latest + - lts + - "lts/*" + - "lts-*" + - stable + - nightly + - beta + - "branch:*" + - "path:*" + - system + - "sub-*" + - "prefix:*" + # Where tools are fetched from. Off by default: write the block to turn + # it on. Globs allowed in every list. + # trustedTools: the tools that may be installed, by full mise name + # (`aqua:jqlang/jq`; a shorthand such as `terraform` takes the + # backend its mise.lock entry records, and with no entry it is + # reported). ISSUE-1013. + # trustedRegistries: the download URLs mise.lock may record, the ones + # `mise install --locked` downloads. Leave it out and they are not + # checked; [] trusts none. ISSUE-1014. + # trustedReplacement: where [settings] url_replacements may send + # downloads. Absent or [] trusts none. ISSUE-1015. + # trustedOptions: the URLs a tool option may set (api_url, url, + # platforms.

.url, pip indexes). Absent or [] trusts none. + # ISSUE-1016. + # sources: + # enabled: true + # trustedTools: ["core:*", "aqua:*", "github:my-org/*"] + # trustedRegistries: ["https://github.com/*", "https://nodejs.org/*"] + # trustedReplacement: [] + # trustedOptions: [] + # Every mise project (a directory holding a mise config) declares the + # tasks CI is expected to run, as `mise run` sees them there (its own, + # its task directories', its parents'). Off by default. `required` is a + # list; each entry matches a task name or alias, globs allowed. A project + # missing any of them is ISSUE-1017. + # tasks: + # enabled: true + # required: [lint, test] + # Tool keys exempted from every mise check, globs allowed. + exemptPackages: [] + # Repository paths whose mise files are not checked, for example + # fixtures ("examples/**", "testdata/**"). A file there that cannot be + # read does not stop the run. `*` stays within a directory, `**` + # crosses directories. + exemptPaths: [] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a551ea03..7a7e0954 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -461,6 +461,7 @@ Skip if your rule only reads fields the IR already exposes (jobs, scripts, trigg - `7xx` reserved for GitHub-specific supply-chain - `8xx` reserved for GitHub-specific triggers - `9xx` reserved for repo / dependabot artefacts + - `10xx` and up: package managers, one hundred-block per package manager (`10xx` is mise, under the `mise-en-place` control). Inside a block, codes take the next number in sequence whatever check raises them, and each one sets a `subject` (for mise: `lockfile`, `presence`, `versions`, `sources`, `tasks`) so the codes of one check can be filtered together. A new package manager takes the next free block, in the "Package Managers and Lockfiles" category. Its config is a top-level key of `.plumber.yaml` named after the package manager (`mise:`), not a block under `gitlab.controls` or `github.controls`: a package manager does not depend on the provider. Pick the next free number; existing assignments live in the constants block at the top of `codes.go`. - [ ] **Registry entry** — `errorCodeRegistry` map entry: ```go diff --git a/cmd/config_slim.go b/cmd/config_slim.go index c4b4a0b2..f1f5ce94 100644 --- a/cmd/config_slim.go +++ b/cmd/config_slim.go @@ -112,6 +112,11 @@ func slimToOverlay(src string) ([]byte, error) { overlay[p] = map[interface{}]interface{}{"controls": diff} } } + // mise is top level, not under a provider: an overlay source keeps + // its block as written, merged onto the base like any overlay key. + if m, ok := rawMap["mise"]; ok { + overlay["mise"] = m + } return yaml.Marshal(overlay) } @@ -145,9 +150,42 @@ func slimToOverlay(src string) ([]byte, error) { overlay[p] = map[interface{}]interface{}{"controls": diff} } } + // mise is top level. A legacy source is a full config, so its mise + // block is kept as written, and a source without one turned mise off: + // the overlay says so, or it would inherit the base's enabled block. + if m, ok := userMap["mise"].(map[interface{}]interface{}); ok { + overlay["mise"] = pinAbsentMiseChecks(m, baseCfg.Mise) + } else if baseCfg.Mise.IsEnabled() { + overlay["mise"] = map[interface{}]interface{}{"enabled": false} + } return yaml.Marshal(overlay) } +// pinAbsentMiseChecks returns a copy of a legacy source's mise block with +// every check block the source leaves out written as `{enabled: false}`. +// In a full config an absent check block does not run, but the overlay is +// deep-merged onto the base on resolve, so an absent key would inherit the +// base's enabled block and turn the check on. +func pinAbsentMiseChecks(m map[interface{}]interface{}, base *configuration.MiseConfig) map[interface{}]interface{} { + out := make(map[interface{}]interface{}) + for k, v := range m { + out[k] = v + } + if _, ok := out["lockfile"]; !ok && base.LockfileCheckEnabled() { + out["lockfile"] = map[interface{}]interface{}{"enabled": false} + } + if _, ok := out["versions"]; !ok && base.VersionsCheckEnabled() { + out["versions"] = map[interface{}]interface{}{"enabled": false} + } + if _, ok := out["sources"]; !ok && base.SourcesCheckEnabled() { + out["sources"] = map[interface{}]interface{}{"enabled": false} + } + if _, ok := out["tasks"]; !ok && base.TasksCheckEnabled() { + out["tasks"] = map[interface{}]interface{}{"enabled": false} + } + return out +} + // normalizeConfigToMap marshals a loaded *configuration.PlumberConfig back // to YAML and unmarshals it into a generic map, so it can be diffed with // diffControls/controlsSubmap the same way a raw source map is. Routing diff --git a/cmd/config_slim_test.go b/cmd/config_slim_test.go index 399b63a4..592894df 100644 --- a/cmd/config_slim_test.go +++ b/cmd/config_slim_test.go @@ -3,6 +3,7 @@ package cmd import ( "os" "path/filepath" + "reflect" "strings" "testing" @@ -671,6 +672,94 @@ github: } } +// TestSlimToOverlay_MiseSurvivesResolve pins the top-level mise block +// through slim -> resolve: a legacy source without mise turned it off, and +// a mise block the source writes is kept. +func TestSlimToOverlay_MiseSurvivesResolve(t *testing.T) { + cases := []struct { + name string + src string + wantEnabled bool + wantLockfile bool + wantVersions bool + // wantForbidden, when set, is the resolved forbiddenVersions list. + wantForbidden []string + wantExempt []string + }{ + { + name: "a legacy source without mise stays off", + src: "version: \"2.0\"\ngithub:\n controls: {}\n", + wantEnabled: false, + }, + { + name: "a legacy source keeps its mise block", + src: "version: \"2.0\"\ngithub:\n controls: {}\nmise:\n lockfile: {}\n exemptPackages: [node]\n", + wantEnabled: true, + wantLockfile: true, + wantExempt: []string{"node"}, + }, + { + name: "a legacy source keeps its versions block and pins the absent lockfile off", + src: "version: \"2.0\"\ngithub:\n controls: {}\nmise:\n versions:\n forbiddenVersions: [latest]\n", + wantEnabled: true, + wantVersions: true, + wantForbidden: []string{"latest"}, + wantExempt: []string{}, + }, + { + name: "a legacy source without a lockfile block keeps the check off", + src: "version: \"2.0\"\ngithub:\n controls: {}\nmise:\n enabled: true\n", + wantEnabled: true, + wantLockfile: false, + wantExempt: []string{}, + }, + { + name: "an overlay source keeps enabled: false", + src: "extends: plumber:default\nversion: \"2.0\"\nmise:\n enabled: false\n", + wantEnabled: false, + }, + { + name: "an overlay source without mise inherits the base", + src: "extends: plumber:default\nversion: \"2.0\"\n", + wantEnabled: true, + wantLockfile: true, + wantVersions: true, + wantExempt: []string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "src.yaml") + if err := os.WriteFile(path, []byte(tc.src), 0o600); err != nil { + t.Fatal(err) + } + out, err := slimToOverlay(path) + if err != nil { + t.Fatalf("slim: %v", err) + } + resolved, _, _, err := configuration.LoadPlumberConfigFromBytes(out, "slim-output-for-test") + if err != nil { + t.Fatalf("resolve slim overlay: %v\n%s", err, out) + } + if got := resolved.Mise.IsEnabled(); got != tc.wantEnabled { + t.Fatalf("mise enabled = %v, want %v\n%s", got, tc.wantEnabled, out) + } + if got := resolved.Mise.LockfileCheckEnabled(); tc.wantEnabled && got != tc.wantLockfile { + t.Errorf("lockfile check enabled = %v, want %v\n%s", got, tc.wantLockfile, out) + } + if got := resolved.Mise.VersionsCheckEnabled(); tc.wantEnabled && got != tc.wantVersions { + t.Errorf("versions check enabled = %v, want %v\n%s", got, tc.wantVersions, out) + } + if tc.wantForbidden != nil && !equalStringSlices(resolved.Mise.Versions.ForbiddenVersions, tc.wantForbidden) { + t.Errorf("forbiddenVersions = %v, want %v\n%s", resolved.Mise.Versions.ForbiddenVersions, tc.wantForbidden, out) + } + if tc.wantEnabled && !equalStringSlices(resolved.Mise.ExemptPackages, tc.wantExempt) { + t.Errorf("exemptPackages = %v, want %v", resolved.Mise.ExemptPackages, tc.wantExempt) + } + }) + } +} + func equalStringSlices(a, b []string) bool { if len(a) != len(b) { return false @@ -691,3 +780,58 @@ func containsString(list []string, s string) bool { } return false } + +func TestPinAbsentMiseChecks(t *testing.T) { + on := &configuration.MiseConfig{ + Lockfile: &configuration.MiseLockfileCheckConfig{}, + Versions: &configuration.MiseVersionsCheckConfig{}, + Sources: &configuration.MiseSourcesCheckConfig{}, + Tasks: &configuration.MiseTasksCheckConfig{Required: []string{"lint"}}, + } + off := map[interface{}]interface{}{"enabled": false} + disabled := false + cases := []struct { + name string + src map[interface{}]interface{} + base *configuration.MiseConfig + want map[interface{}]interface{} + }{ + { + name: "every check the source leaves out is pinned off when the base enables it", + src: map[interface{}]interface{}{"exemptPackages": []interface{}{"node"}}, + base: on, + want: map[interface{}]interface{}{"exemptPackages": []interface{}{"node"}, "lockfile": off, "versions": off, "sources": off, "tasks": off}, + }, + { + name: "a check the source writes is kept as written", + src: map[interface{}]interface{}{"sources": map[interface{}]interface{}{"trustedTools": []interface{}{"aqua:*"}}}, + base: on, + want: map[interface{}]interface{}{ + "sources": map[interface{}]interface{}{"trustedTools": []interface{}{"aqua:*"}}, + "lockfile": off, + "versions": off, + "tasks": off, + }, + }, + { + name: "a check the base turns off is not pinned", + src: map[interface{}]interface{}{}, + base: &configuration.MiseConfig{Tasks: &configuration.MiseTasksCheckConfig{Enabled: &disabled}}, + want: map[interface{}]interface{}{}, + }, + { + name: "nothing is pinned when the base enables no check", + src: map[interface{}]interface{}{}, + base: &configuration.MiseConfig{}, + want: map[interface{}]interface{}{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := pinAbsentMiseChecks(tc.src, tc.base) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("got %#v\nwant %#v", got, tc.want) + } + }) + } +} diff --git a/cmd/init.go b/cmd/init.go index 2176273b..27833168 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -43,6 +43,7 @@ const ( compScripts = "Detect unverified script execution (curl|bash, base64|bash, |sh, …)" compJobVars = "Detect sensitive variables overridden in pipeline YAML" compDinD = "Detect Docker-in-Docker (dind) usage" + compPackageManagers = "Require committed package manager lockfiles with checksums and pinned versions (mise)" // GitHub-applicable composition checks (new). The cross-provider ones // (security jobs, DinD) reuse compSecurity / compDinD above. @@ -903,7 +904,7 @@ func compositionOptionsForProviders(providers []string) []string { if hasGitLab { out = append(out, compHardcoded, compUpToDate, compForbidden, compRefCollision, compAuthorizedComponents, compAuthorizedFunctions) } - out = append(out, compSecurity, compDinD) + out = append(out, compSecurity, compDinD, compPackageManagers) if hasGitLab { out = append(out, compScripts, compJobVars) } @@ -1550,6 +1551,12 @@ func (st *initWizardState) toPlumberConfig() *configuration.PlumberConfig { } } + // Provider-independent: mise is a top-level block. It is the + // shipped default's, so the wizard and the default cannot drift. + if compSelected(st, compPackageManagers) { + cfg.Mise = embeddedDefault().Mise + } + // GitHub-only composition checks. if gh != nil { if compSelected(st, compActionPin) { diff --git a/cmd/init_test.go b/cmd/init_test.go index 929ef574..3662ba60 100644 --- a/cmd/init_test.go +++ b/cmd/init_test.go @@ -207,7 +207,7 @@ func starterWizardConfig() *configuration.PlumberConfig { TrustedURLsText: strings.Join(defaultTrustedURLs(), "\n"), AuthorizedActionsUsePlumberList: true, CompositionChoices: []string{ - compHardcoded, compUpToDate, compForbidden, compRefCollision, compAuthorizedComponents, compAuthorizedFunctions, compSecurity, compScripts, compJobVars, compDinD, + compHardcoded, compUpToDate, compForbidden, compRefCollision, compAuthorizedComponents, compAuthorizedFunctions, compSecurity, compScripts, compJobVars, compDinD, compPackageManagers, compActionPin, compAuthorizedActions, compDangerousTriggers, compPRTargetHead, compCheckoutPersist, compDeclarePermissions, compWorkflowValid, compReusableSecrets, compOverprovSecrets, compTemplateInjection, compEnvInjection, compWriteAllPerms, compRefConfusion, compArchivedActions, compKnownCVEs, compImpostorCommit, compMutableRemoteExec, compCachePoisoning, compDebugTraceGitHub, }, @@ -641,6 +641,41 @@ func TestStarterPlumberConfigGitHubMatchesCuratedDefaults(t *testing.T) { } } +// TestInitWizardMiseBlock locks the compPackageManagers -> top-level mise +// mapping in toPlumberConfig. The GitLab/GitHub parity tests only read +// provider controls, so without this a dropped mise block would turn +// mise-en-place off for every config init user while the +// suite stayed green. +func TestInitWizardMiseBlock(t *testing.T) { + t.Run("the starter config writes an enabled mise block with the lockfile and versions checks", func(t *testing.T) { + cfg := starterWizardConfig() + if !cfg.Mise.IsEnabled() || !cfg.Mise.LockfileCheckEnabled() || !cfg.Mise.VersionsCheckEnabled() { + t.Fatalf("mise = %+v, want enabled with the lockfile and versions checks on", cfg.Mise) + } + out, err := yaml.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + var written configuration.PlumberConfig + if err := yaml.Unmarshal(out, &written); err != nil { + t.Fatalf("reload written config: %v", err) + } + if !written.Mise.IsEnabled() || !written.Mise.LockfileCheckEnabled() || !written.Mise.VersionsCheckEnabled() { + t.Fatalf("written config lost the mise block:\n%s", out) + } + }) + t.Run("not selecting package managers leaves mise out", func(t *testing.T) { + st := &initWizardState{ + Providers: []string{"github"}, + Categories: []string{catComposition}, + CompositionChoices: []string{compArchivedActions}, + } + if cfg := st.toPlumberConfig(); cfg.Mise != nil { + t.Fatalf("mise = %+v, want nil", cfg.Mise) + } + }) +} + // TestInitWizardEnablesImpostorCommit locks the compImpostorCommit -> // ActionRefsMustExistUpstream mapping in toPlumberConfig: selecting the // composition option must enable the control, and a run that does not diff --git a/cmd/render_details.go b/cmd/render_details.go index 241c906e..122a1108 100644 --- a/cmd/render_details.go +++ b/cmd/render_details.go @@ -1081,6 +1081,8 @@ func buildGitHubControlStats(controlName string, stats *control.GitHubAnalysisSt {Label: statVariablesChecked, Value: fmt.Sprintf("%d", stats.VariableBindingsTotal)}, {Label: "Forbidden Found", Value: fmt.Sprintf("%d", stats.DebugTraceFound)}, } + case "mise-en-place": + return packageManagersStatLines(stats.MiseConfigsTotal, stats.MiseToolsTotal, len(findings)) case "branchMustBeProtected": unprotectedMatched := stats.BranchesMatched - stats.BranchesProtected if unprotectedMatched < 0 { @@ -1353,6 +1355,13 @@ func buildGitLabControlStats(controlName string, result *control.AnalysisResult, } } return requirementGroupStats(resolved, result, "template") + case "mise-en-place": + var m *ir.MiseScan + if result.Pipeline != nil { + m = result.Pipeline.Mise + } + configs, tools := control.MiseTotals(m) + return packageManagersStatLines(configs, tools, findingsCount) case "pipelineMustNotUseDockerInDocker": return []statLine{ {Label: statJobsChecked, Value: fmt.Sprintf("%d", jobTotal)}, @@ -1937,3 +1946,13 @@ func pathTierTag(t control.PathTier) string { return renderSeverityBadge(control.SeverityLow, " LOW ") } } + +// packageManagersStatLines is the stats block of +// mise-en-place, the same on both providers. +func packageManagersStatLines(configs, tools, issues int) []statLine { + return []statLine{ + {Label: "mise Configs Checked", Value: fmt.Sprintf("%d", configs)}, + {Label: "mise Tools Checked", Value: fmt.Sprintf("%d", tools)}, + {Label: "Issues Found", Value: fmt.Sprintf("%d", issues)}, + } +} diff --git a/cmd/render_details_package_managers_test.go b/cmd/render_details_package_managers_test.go new file mode 100644 index 00000000..df4fccad --- /dev/null +++ b/cmd/render_details_package_managers_test.go @@ -0,0 +1,55 @@ +package cmd + +import ( + "reflect" + "testing" + + "github.com/getplumber/plumber/control" + opaengine "github.com/getplumber/plumber/internal/engine/opa" + "github.com/getplumber/plumber/internal/ir" +) + +// TestBuildControlStats_PackageManagers pins the stat block of +// mise-en-place on both providers: the mise configs read, +// the tool requests they declare (every config's tools, summed), and the +// findings, in that order. A swapped or wrong value would mislabel the +// compliance report. +func TestBuildControlStats_PackageManagers(t *testing.T) { + scan := &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: "mise.toml", Tools: []ir.MiseTool{{Name: "node"}, {Name: "age"}}}, + {Path: "svc/mise.toml", Tools: []ir.MiseTool{{Name: "go"}}}, + }} + findings := []opaengine.Finding{{Code: "ISSUE-1001"}, {Code: "ISSUE-1004"}, {Code: "ISSUE-1009"}, {Code: "ISSUE-1008"}} + want := []statLine{ + {Label: "mise Configs Checked", Value: "2"}, + {Label: "mise Tools Checked", Value: "3"}, + {Label: "Issues Found", Value: "4"}, + } + + t.Run("github", func(t *testing.T) { + stats := &control.GitHubAnalysisStats{} + stats.MiseConfigsTotal, stats.MiseToolsTotal = control.MiseTotals(scan) + got := buildGitHubControlStats("mise-en-place", stats, findings) + if !reflect.DeepEqual(got, want) { + t.Fatalf("stats = %+v, want %+v", got, want) + } + }) + t.Run("gitlab", func(t *testing.T) { + result := &control.AnalysisResult{Pipeline: &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, Mise: scan}} + got := buildGitLabControlStats("mise-en-place", result, nil, findings) + if !reflect.DeepEqual(got, want) { + t.Fatalf("stats = %+v, want %+v", got, want) + } + }) + t.Run("gitlab without a scan counts zero", func(t *testing.T) { + got := buildGitLabControlStats("mise-en-place", &control.AnalysisResult{}, nil, nil) + wantZero := []statLine{ + {Label: "mise Configs Checked", Value: "0"}, + {Label: "mise Tools Checked", Value: "0"}, + {Label: "Issues Found", Value: "0"}, + } + if !reflect.DeepEqual(got, wantZero) { + t.Fatalf("stats = %+v, want %+v", got, wantZero) + } + }) +} diff --git a/cmd/testdata/catalog_golden.json b/cmd/testdata/catalog_golden.json index f9aa2824..cbb21bea 100644 --- a/cmd/testdata/catalog_golden.json +++ b/cmd/testdata/catalog_golden.json @@ -1201,6 +1201,61 @@ }, "issueCodeEntryKinds": {} }, + { + "id": "CTRL-1001", + "name": "mise-en-place", + "displayName": "mise-en-place", + "category": "Package Managers and Lockfiles", + "providers": [ + "gitlab", + "github" + ], + "description": "Verifies the mise files of the repository: that every config has a committed, up to date lockfile whose downloads carry checksums and trusted provenance, that no tool requests a forbidden version such as latest, that tools come from authorized sources, that every mise project declares the required tasks, and, when required, that the repository uses mise at all.", + "requiresConfig": false, + "issueCodes": [ + "ISSUE-1001", + "ISSUE-1002", + "ISSUE-1003", + "ISSUE-1004", + "ISSUE-1005", + "ISSUE-1006", + "ISSUE-1007", + "ISSUE-1008", + "ISSUE-1009", + "ISSUE-1010", + "ISSUE-1011", + "ISSUE-1012", + "ISSUE-1013", + "ISSUE-1014", + "ISSUE-1015", + "ISSUE-1016", + "ISSUE-1017", + "ISSUE-1018", + "ISSUE-1019" + ], + "issueCodeRoles": { + "ISSUE-1001": "hygiene", + "ISSUE-1002": "hygiene", + "ISSUE-1003": "hygiene", + "ISSUE-1004": "hygiene", + "ISSUE-1005": "hygiene", + "ISSUE-1006": "hygiene", + "ISSUE-1007": "hygiene", + "ISSUE-1008": "hygiene", + "ISSUE-1009": "hygiene", + "ISSUE-1010": "hygiene", + "ISSUE-1011": "hygiene", + "ISSUE-1012": "hygiene", + "ISSUE-1013": "hygiene", + "ISSUE-1014": "hygiene", + "ISSUE-1015": "hygiene", + "ISSUE-1016": "hygiene", + "ISSUE-1017": "hygiene", + "ISSUE-1018": "hygiene", + "ISSUE-1019": "hygiene" + }, + "issueCodeEntryKinds": {} + }, { "id": "CTRL-507", "name": "numberOfProjectMembersMustRespectQuota", @@ -2561,6 +2616,96 @@ } ], "issueTypes": [ + { + "code": "ISSUE-1001", + "severity": "high", + "title": "mise: tools are declared and the lockfile is not committed", + "description": "A mise config file declares tools in `[tools]`, but the lockfile mise writes them to (`mise.lock`, or `mise.\u003cenv\u003e.lock` for `mise.\u003cenv\u003e.toml`) is not committed. Without it, every `mise install` resolves versions and download URLs at install time, so CI can install a different build than the one that was reviewed, and nothing checks the downloaded bytes against a recorded checksum.", + "remediation": "Turn lockfiles on with `[settings] lockfile = true` in the config, run `mise lock`, and commit the lockfile. Install in CI with `mise install --locked` (or `jdx/mise-action`, which adds it when a lockfile exists).", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1001", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1002", + "severity": "high", + "title": "mise: lockfiles are turned off", + "description": "A mise config sets `[settings] lockfile = false`. mise then never reads or writes a lockfile for the project, so tool versions and downloads are resolved at install time on every machine and in CI.", + "remediation": "Remove `lockfile = false` (or set it to `true`), run `mise lock`, and commit the lockfile.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1002", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1003", + "severity": "high", + "title": "mise: a tool is not locked", + "description": "A tool request in a mise config has no entry in the lockfile whose `specifiers` contain that request: the lockfile is stale or incomplete, so mise resolves the tool at install time. The same finding is raised when Plumber cannot read the request statically (a template value) or when the lockfile uses format 0, which records no `specifiers`: Plumber cannot prove the tool is locked, so it does not pass it.", + "remediation": "Run `mise lock` and commit the updated lockfile. For a format 0 lockfile, run `mise lock --upgrade` to move it to the current format. Replace a templated version with a literal one, or list the tool in `exemptPackages` if the exception is intentional.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1003", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1004", + "severity": "high", + "title": "mise: a tool is locked without a checksum", + "description": "A platform entry of `mise.lock` records a download URL but no `checksum`. mise then cannot verify that the bytes it downloads are the ones that were locked, so a release asset replaced upstream (a re-published GitHub release, a compromised mirror) is installed without notice.", + "remediation": "Run `mise lock` so mise records the checksum, and prefer a backend that publishes checksums (aqua, core tools). If the source publishes none, list the tool in `exemptPackages` once you have reviewed it.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1004", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1005", + "severity": "medium", + "title": "mise: a tool is locked with an untrusted provenance", + "description": "A platform entry of `mise.lock` records a provenance of a kind that is not in `trustedProvenance`. mise verifies a download against the provenance its lockfile records, so a kind you do not trust is the only proof of who built the tool.", + "remediation": "Lock the tool from a source that publishes a trusted provenance (`mise lock` records it), add the kind to `trustedProvenance` once you have reviewed it, or list the tool in `exemptPackages`.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1005", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1006", + "severity": "medium", + "title": "mise: a tool is locked without a provenance", + "description": "A download locked in `mise.lock` comes from a backend listed in `requireProvenance`, but its platform entry records no `provenance` (SLSA, cosign, minisign or GitHub attestations). The checksum only proves the bytes did not change after locking; provenance proves who built them.", + "remediation": "Run `mise lock` with a mise version that records provenance, use a source that publishes it, or remove the backend from `requireProvenance`.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1006", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1007", + "severity": "low", + "title": "mise: a required platform is not locked", + "description": "A tool that locks per-platform downloads has no entry for a platform listed in `requiredPlatforms`. CI or developers on that platform resolve the download at install time, outside the lockfile.", + "remediation": "Run `mise lock --platform \u003cplatform\u003e` for the missing platforms (or set `lockfile_platforms`) and commit the lockfile.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1007", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1008", + "severity": "low", + "title": "mise: the lockfile format is older than the minimum", + "description": "The lockfile's `lockfile_version` is older than `minimumLockfileVersion`. Older formats record less: format 0 has no `specifiers`, so it cannot prove which request a locked version belongs to.", + "remediation": "Run `mise lock --upgrade` to move the lockfile to the current format, and commit it.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1008", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1009", + "severity": "medium", + "title": "mise: a tool is declared in asdf's .tool-versions", + "description": "A tool is declared in a `.tool-versions` file and in no mise config of the same directory. mise reads `.tool-versions` but never locks it, so the tool's version and download are resolved at install time.", + "remediation": "Move the tool to the `[tools]` table of `mise.toml`, run `mise lock`, and commit the lockfile.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1009", + "controlName": "mise-en-place", + "subject": "lockfile" + }, { "code": "ISSUE-101", "severity": "high", @@ -2570,6 +2715,106 @@ "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-101", "controlName": "containerImageMustComeFromAuthorizedSources" }, + { + "code": "ISSUE-1010", + "severity": "medium", + "title": "mise: the repository has no mise config", + "description": "`mise.required` is set, and the repository commits no mise config outside `exemptPaths` (a `.tool-versions` file alone does not count). The tools CI installs are then not declared, locked or checked with mise.", + "remediation": "Declare the tools CI uses in a `mise.toml`, run `mise lock`, and commit both files. Remove `required` if this repository does not use mise.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1010", + "controlName": "mise-en-place", + "subject": "presence" + }, + { + "code": "ISSUE-1011", + "severity": "high", + "title": "mise: a tool uses a forbidden version", + "description": "A tool request in a mise config matches a pattern of `forbiddenVersions` (`latest`, `lts`, `stable`, `nightly`, `prefix:`, `system`, ...). The lockfile may still pin a version, but the next `mise lock --bump`, `mise upgrade` or regenerated lockfile moves it with no change in the config, so the version is never reviewed where people review it.", + "remediation": "Write an exact version in the config (`terraform = \"1.9.8\"`), run `mise lock`, and commit both files, or list the tool in `exemptPackages` if the exception is intentional.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1011", + "controlName": "mise-en-place", + "subject": "versions" + }, + { + "code": "ISSUE-1012", + "severity": "high", + "title": "mise: a tool version cannot be read statically", + "description": "A tool request in a mise config is a template (`{{ env.NODE_VERSION }}`), is empty, or is not a quoted string (`node = 24`, which mise rejects). Plumber reads files and never runs mise, so it cannot tell which version is requested or check it against `forbiddenVersions`: it reports the request instead of passing it.", + "remediation": "Write the version as a quoted literal (`node = \"24.11.1\"`), run `mise lock`, and commit both files. List the tool in `exemptPackages` if the version has to come from the environment.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1012", + "controlName": "mise-en-place", + "subject": "versions" + }, + { + "code": "ISSUE-1013", + "severity": "high", + "title": "mise: a tool is not trusted", + "description": "A tool in a mise config matches no pattern of `trustedTools`. The pattern is matched against the tool's full mise name: its key when it names a backend (`aqua:jqlang/jq`, `github:org/repo`), or the backend its `mise.lock` entry records for a shorthand (`terraform`). The backend decides where mise downloads the tool from and how it verifies it. A shorthand with no lock entry can't be traced to a backend, so it is reported too.", + "remediation": "Install the tool from a trusted backend (for example `aqua:` or a core tool), add it to `trustedTools` once you have reviewed it, or list it in `exemptPackages`.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1013", + "controlName": "mise-en-place", + "subject": "sources" + }, + { + "code": "ISSUE-1014", + "severity": "high", + "title": "mise: a locked download URL is not a trusted registry", + "description": "A platform entry of `mise.lock` records a download `url` that matches no pattern of `trustedRegistries`. That is the URL `mise install --locked` downloads, so a change to `mise.lock` alone can point a trusted tool at any host. Checked only when `trustedRegistries` is set.", + "remediation": "Run `mise lock` from a trusted source so the lockfile records its URL, or add the registry to `trustedRegistries` once you operate or trust it.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1014", + "controlName": "mise-en-place", + "subject": "sources" + }, + { + "code": "ISSUE-1015", + "severity": "high", + "title": "mise: a URL replacement is not trusted", + "description": "A mise config sets `[settings] url_replacements`, and a replacement URL matches no pattern of `trustedReplacement`. mise sends the download to the replacement first, while `mise.lock` keeps the original URL, so the lockfile alone does not show where tools come from.", + "remediation": "Remove the replacement, or add its URL to `trustedReplacement` once you operate or trust the host.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1015", + "controlName": "mise-en-place", + "subject": "sources" + }, + { + "code": "ISSUE-1016", + "severity": "medium", + "title": "mise: a tool option sets an untrusted URL", + "description": "A trusted tool sets an option that changes where it is downloaded from, to a URL that matches no pattern of `trustedOptions`: `api_url` (a GitHub or GitLab server), `url` or `platforms.\u003cplatform\u003e.url` (the asset itself), or a pip index (`registry_url`, `indexes`, `pipx_args`, `uvx_args`, `install_env`).", + "remediation": "Remove the option so the backend fetches from its own source, add the URL to `trustedOptions` if you operate it (a GitHub Enterprise server, an internal mirror), or list the tool in `exemptPackages` once reviewed.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1016", + "controlName": "mise-en-place", + "subject": "sources" + }, + { + "code": "ISSUE-1017", + "severity": "medium", + "title": "mise: a project misses required tasks", + "description": "A mise project (a directory holding a mise config) does not declare the tasks `mise.tasks.required` asks for. When CI runs `mise run \u003ctask\u003e`, the tasks the organization expects (lint, test, a security scan) are the steps that actually run, so a project without them skips those steps. Tasks count from `[tasks]` tables, TOML task files, executable files of the task directories, and parent directories, as `mise run` sees them. Tasks from a remote (`git::`, `oci::`, `zip::`) or templated include are not read, so they never satisfy the requirement.", + "remediation": "Declare the missing tasks in the project's `mise.toml` (`[tasks.lint]`) or as executable files in `mise-tasks/`, or list the project's path in `exemptPaths` if it is not meant to run them.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1017", + "controlName": "mise-en-place", + "subject": "tasks" + }, + { + "code": "ISSUE-1018", + "severity": "high", + "title": "mise: a tool is locked without a download URL or checksum", + "description": "A lock entry in `mise.lock` records nothing mise can verify a download against: a tool from a backend that downloads a per-platform binary (aqua, github, gitlab, ubi, http) is locked with no platform table, or a platform table has neither `url` nor `checksum`. mise then resolves and downloads the binary at install time with no checksum to check it against.", + "remediation": "Run `mise lock --platform \u003cplatforms\u003e` so mise records the URL and checksum of each platform, and commit the lockfile. List the tool in `exemptPackages` if its source publishes no downloadable asset you can lock.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1018", + "controlName": "mise-en-place", + "subject": "lockfile" + }, + { + "code": "ISSUE-1019", + "severity": "high", + "title": "mise: a local config is committed", + "description": "A mise local config (`mise.local.toml`, `mise.\u003cenv\u003e.local.toml`, `config.local.toml` or a `conf.d/*.local.toml` fragment) is committed to the repository. mise loads it on every clone, CI included, so its tools, settings and environment apply to everyone. A local config is meant for one machine and must not be committed (https://mise.jdx.dev/glossary.html#mise-local-toml), and a reviewer reading `mise.toml` does not see what it adds.", + "remediation": "Move what CI needs into `mise.toml` and lock it with `mise lock`, delete the local config from the repository (`git rm --cached`), and add `*.local.toml` to `.gitignore`.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-1019", + "controlName": "mise-en-place", + "subject": "lockfile" + }, { "code": "ISSUE-102", "severity": "medium", diff --git a/configuration/catalog_export_test.go b/configuration/catalog_export_test.go index 27bd7cd1..c2f9688c 100644 --- a/configuration/catalog_export_test.go +++ b/configuration/catalog_export_test.go @@ -13,7 +13,7 @@ func TestControlsCatalogIsComplete(t *testing.T) { CategoryCICDSecrets: true, CategoryPipelineComposition: true, CategoryAccessAndAuthorization: true, CategorySecuritySource: true, CategoryThirdPartyActions: true, CategoryWorkflowTriggersAndPermissions: true, - CategoryRepositoryHygiene: true, + CategoryRepositoryHygiene: true, CategoryPackageManagers: true, } cat := ControlsCatalog() if len(cat) != len(controlsMeta) { diff --git a/configuration/packagemanagers.go b/configuration/packagemanagers.go new file mode 100644 index 00000000..59ad4520 --- /dev/null +++ b/configuration/packagemanagers.go @@ -0,0 +1,309 @@ +package configuration + +import ( + "fmt" + "slices" + "sort" + "strings" + + "github.com/gobwas/glob" +) + +// MiseConfig is the top-level `mise:` block of .plumber.yaml. It does not +// depend on the provider: the same block applies whether the repository +// is on GitHub or GitLab. It drives the mise-en-place control. A missing +// block, or `enabled: false`, turns it off: nothing is scanned and +// nothing is reported. +type MiseConfig struct { + // Enabled turns mise checks off when false. A present block is enabled. + Enabled *bool `yaml:"enabled,omitempty"` + + // Required reports a repository with no mise config (ISSUE-1010). + // A .tool-versions file alone does not count: it is asdf's file. + Required bool `yaml:"required,omitempty"` + + // Lockfile checks that every mise config has a committed, up to date + // lockfile with checksums. An absent block does not run. + Lockfile *MiseLockfileCheckConfig `yaml:"lockfile,omitempty"` + + // Versions checks that no tool request uses a forbidden version + // ("latest", "lts", "nightly", ...). An absent block does not run. + Versions *MiseVersionsCheckConfig `yaml:"versions,omitempty"` + + // Sources checks where tools are fetched from: their backend, the + // settings that redirect fetching, and the tool options that change + // the download location. An absent block does not run. + Sources *MiseSourcesCheckConfig `yaml:"sources,omitempty"` + + // Tasks checks that every mise project declares the required tasks. + // An absent block does not run. + Tasks *MiseTasksCheckConfig `yaml:"tasks,omitempty"` + + // ExemptPackages lists tool keys exempted from every mise check + // (globs allowed, e.g. "aqua:my-org/*"). + ExemptPackages []string `yaml:"exemptPackages,omitempty"` + + // ExemptPaths lists repository paths whose mise files are not checked + // (globs with `/` as separator, e.g. "examples/**"), for example + // fixtures that leave a lockfile out on purpose. + ExemptPaths []string `yaml:"exemptPaths,omitempty"` +} + +// UnmarshalYAML rejects unknown mise keys. +func (c *MiseConfig) UnmarshalYAML(unmarshal func(any) error) error { + if err := rejectUnknownKeys(unmarshal, "mise", "enabled", "required", "lockfile", "versions", "sources", "tasks", "exemptPackages", "exemptPaths"); err != nil { + return err + } + type plain MiseConfig + return unmarshal((*plain)(c)) +} + +// IsEnabled reports whether mise is checked: the block is present and does +// not say enabled: false. +func (c *MiseConfig) IsEnabled() bool { + return c != nil && (c.Enabled == nil || *c.Enabled) +} + +// AnyCheckEnabled reports whether at least one mise check is on: a check +// block, or `required`. An enabled mise block with none asserts nothing. +func (c *MiseConfig) AnyCheckEnabled() bool { + return c != nil && (c.Required || c.LockfileCheckEnabled() || c.VersionsCheckEnabled() || c.SourcesCheckEnabled() || c.TasksCheckEnabled()) +} + +// TasksCheckEnabled reports whether the tasks check runs: its block is +// present and does not say enabled: false. +func (c *MiseConfig) TasksCheckEnabled() bool { + return c != nil && c.Tasks != nil && (c.Tasks.Enabled == nil || *c.Tasks.Enabled) +} + +// LockfileCheckEnabled reports whether the lockfile check runs: its block +// is present and does not say enabled: false. +func (c *MiseConfig) LockfileCheckEnabled() bool { + return c != nil && c.Lockfile != nil && (c.Lockfile.Enabled == nil || *c.Lockfile.Enabled) +} + +// VersionsCheckEnabled reports whether the versions check runs: its block +// is present and does not say enabled: false. +func (c *MiseConfig) VersionsCheckEnabled() bool { + return c != nil && c.Versions != nil && (c.Versions.Enabled == nil || *c.Versions.Enabled) +} + +// SourcesCheckEnabled reports whether the sources check runs: its block +// is present and does not say enabled: false. +func (c *MiseConfig) SourcesCheckEnabled() bool { + return c != nil && c.Sources != nil && (c.Sources.Enabled == nil || *c.Sources.Enabled) +} + +// MiseLockfileCheckConfig configures the mise lockfile check. +type MiseLockfileCheckConfig struct { + // Enabled turns the check off when false. A present block is enabled. + Enabled *bool `yaml:"enabled,omitempty"` + + // RequireChecksums reports a locked download that has no checksum. + // Defaults to true: only an explicit false turns it off. + RequireChecksums *bool `yaml:"requireChecksums,omitempty"` + + // RequireProvenance lists backends (globs allowed, e.g. "aqua:*") + // whose locked downloads must record a provenance (ISSUE-1006). + RequireProvenance []string `yaml:"requireProvenance,omitempty"` + + // TrustedProvenance lists the provenance kinds a locked download may + // record (ISSUE-1005). Nil (the key is absent) means + // DefaultTrustedProvenance; an empty list trusts no kind. A pointer, so + // an empty list survives a YAML round trip (omitempty drops an empty + // slice, which would read back as absent and trust every kind). + TrustedProvenance *[]string `yaml:"trustedProvenance,omitempty"` + + // RequiredPlatforms lists the platforms (e.g. "linux-x64") every tool + // that locks downloads must lock. + RequiredPlatforms []string `yaml:"requiredPlatforms,omitempty"` + + // MinimumLockfileVersion is the oldest accepted lockfile_version. + MinimumLockfileVersion *int `yaml:"minimumLockfileVersion,omitempty"` +} + +// UnmarshalYAML rejects unknown lockfile check keys. +func (c *MiseLockfileCheckConfig) UnmarshalYAML(unmarshal func(any) error) error { + if err := rejectUnknownKeys(unmarshal, "mise.lockfile", + "enabled", "requireChecksums", "requireProvenance", "trustedProvenance", "requiredPlatforms", "minimumLockfileVersion"); err != nil { + return err + } + type plain MiseLockfileCheckConfig + return unmarshal((*plain)(c)) +} + +// DefaultTrustedProvenance is every provenance kind mise records in a +// lockfile. +var DefaultTrustedProvenance = []string{"slsa", "github-attestations", "cosign", "minisign"} + +// TrustedProvenanceOrDefault returns TrustedProvenance, or +// DefaultTrustedProvenance when it is unset. +func (c *MiseLockfileCheckConfig) TrustedProvenanceOrDefault() []string { + if c == nil || c.TrustedProvenance == nil { + return slices.Clone(DefaultTrustedProvenance) + } + if *c.TrustedProvenance == nil { + return []string{} + } + return *c.TrustedProvenance +} + +// MiseVersionsCheckConfig configures the mise versions check. +type MiseVersionsCheckConfig struct { + // Enabled turns the check off when false. A present block is enabled. + Enabled *bool `yaml:"enabled,omitempty"` + + // ForbiddenVersions lists version requests a tool must not use, globs + // allowed (e.g. "latest", "lts/*"). + ForbiddenVersions []string `yaml:"forbiddenVersions,omitempty"` +} + +// UnmarshalYAML rejects unknown versions check keys. +func (c *MiseVersionsCheckConfig) UnmarshalYAML(unmarshal func(any) error) error { + if err := rejectUnknownKeys(unmarshal, "mise.versions", "enabled", "forbiddenVersions"); err != nil { + return err + } + type plain MiseVersionsCheckConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return validateGlobs("mise.versions.forbiddenVersions", c.ForbiddenVersions) +} + +// MiseSourcesCheckConfig configures the mise sources check. +type MiseSourcesCheckConfig struct { + // Enabled turns the check off when false. A present block is enabled. + Enabled *bool `yaml:"enabled,omitempty"` + + // TrustedTools lists the tools that may be installed, matched against + // the tool's full mise name: its key when it names a backend + // ("aqua:jqlang/jq"), the backend its lock entry records for a + // shorthand ("terraform" -> "aqua:hashicorp/terraform"). Globs allowed + // ("core:*", "github:my-org/*"). ISSUE-1013. + TrustedTools []string `yaml:"trustedTools,omitempty"` + + // TrustedRegistries lists the download URLs mise.lock may record, + // globs allowed ("https://github.com/*"). Nil (the key is absent) + // leaves the URLs unchecked; an empty list trusts none. A pointer, so + // an empty list survives a YAML round trip. ISSUE-1014. + TrustedRegistries *[]string `yaml:"trustedRegistries,omitempty"` + + // TrustedReplacement lists the URLs a `url_replacements` entry may + // send downloads to, globs allowed. Absent or empty trusts none. + // ISSUE-1015. + TrustedReplacement []string `yaml:"trustedReplacement,omitempty"` + + // TrustedOptions lists the URLs a tool option (api_url, url, + // platforms.

.url, pip indexes) may point at, globs allowed. Absent + // or empty trusts none. ISSUE-1016. + TrustedOptions []string `yaml:"trustedOptions,omitempty"` +} + +// TrustedRegistriesList returns TrustedRegistries and whether it is set. +func (c *MiseSourcesCheckConfig) TrustedRegistriesList() ([]string, bool) { + if c == nil || c.TrustedRegistries == nil { + return nil, false + } + if *c.TrustedRegistries == nil { + return []string{}, true + } + return *c.TrustedRegistries, true +} + +// UnmarshalYAML rejects unknown sources check keys and invalid globs. +func (c *MiseSourcesCheckConfig) UnmarshalYAML(unmarshal func(any) error) error { + if err := rejectUnknownKeys(unmarshal, "mise.sources", "enabled", "trustedTools", "trustedRegistries", "trustedReplacement", "trustedOptions"); err != nil { + return err + } + type plain MiseSourcesCheckConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + registries, _ := c.TrustedRegistriesList() + for _, l := range []struct { + key string + patterns []string + }{ + {"mise.sources.trustedTools", c.TrustedTools}, + {"mise.sources.trustedRegistries", registries}, + {"mise.sources.trustedReplacement", c.TrustedReplacement}, + {"mise.sources.trustedOptions", c.TrustedOptions}, + } { + if err := validateGlobs(l.key, l.patterns); err != nil { + return err + } + } + return nil +} + +// MiseTasksCheckConfig configures the mise tasks check: every mise +// project must declare each task of Required (ISSUE-1017). +type MiseTasksCheckConfig struct { + // Enabled turns the check off when false. A present block is enabled. + Enabled *bool `yaml:"enabled,omitempty"` + + // Required lists the tasks every mise project must declare. Each + // entry is a task name or alias, globs allowed (`lint:*`). + Required []string `yaml:"required,omitempty"` +} + +// UnmarshalYAML rejects unknown tasks check keys, an empty requirement +// and invalid globs. +func (c *MiseTasksCheckConfig) UnmarshalYAML(unmarshal func(any) error) error { + if err := rejectUnknownKeys(unmarshal, "mise.tasks", "enabled", "required"); err != nil { + return err + } + type plain MiseTasksCheckConfig + if err := unmarshal((*plain)(c)); err != nil { + return fmt.Errorf("mise.tasks.required must be a list of task names: %w", err) + } + if c.Enabled != nil && !*c.Enabled { + return nil + } + if len(c.Required) == 0 { + return fmt.Errorf("mise.tasks: set 'required', the list of tasks every mise project must declare") + } + return validateGlobs("mise.tasks.required", c.Required) +} + +// validateGlobs rejects a pattern the Rego rules cannot match. They use +// glob.match, which fails on a bad pattern and then matches nothing, so a +// typo would silently change what the check passes. Each pattern is +// compiled the same way (no separator). +func validateGlobs(where string, patterns []string) error { + for _, p := range patterns { + if _, err := glob.Compile(p); err != nil { + return fmt.Errorf("invalid pattern %q in %s: %w", p, where, err) + } + } + return nil +} + +// rejectUnknownKeys decodes the node as a map and fails on any key not in +// allowed. A null or non-map node is left to the typed decode. +func rejectUnknownKeys(unmarshal func(any) error, where string, allowed ...string) error { + var raw map[string]any + if err := unmarshal(&raw); err != nil { + return nil //nolint:nilerr // not a map: the typed decode reports it + } + var unknown []string + for k := range raw { + if !slices.Contains(allowed, k) { + unknown = append(unknown, k) + } + } + if len(unknown) == 0 { + return nil + } + sort.Strings(unknown) + return fmt.Errorf("unknown key(s) %s in %s; valid keys: %s", + strings.Join(quoteAll(unknown), ", "), where, strings.Join(allowed, ", ")) +} + +func quoteAll(in []string) []string { + out := make([]string, len(in)) + for i, s := range in { + out[i] = fmt.Sprintf("%q", s) + } + return out +} diff --git a/configuration/packagemanagers_test.go b/configuration/packagemanagers_test.go new file mode 100644 index 00000000..948f7cb9 --- /dev/null +++ b/configuration/packagemanagers_test.go @@ -0,0 +1,417 @@ +package configuration + +import ( + "slices" + "strings" + "testing" + + "gopkg.in/yaml.v2" +) + +func TestMiseConfigDecoding(t *testing.T) { + cases := []struct { + name string + block string + wantErr string + wantEnabled bool + wantLockfile bool + wantVersions bool + wantSources bool + wantTasks bool + + wantExemptPaths []string + wantRequired bool + wantAnyCheck bool + // wantTrustedProvenance is TrustedProvenanceOrDefault, checked + // when the lockfile check is on. + wantTrustedProvenance []string + // The lockfile check keys, checked when the lockfile check is on. + wantRequireProvenance []string + wantRequiredPlatforms []string + wantMinimumLockfileVersion *int + }{ + {name: "a missing mise block is off", block: ""}, + { + name: "enabled: false turns mise off", + block: ` +mise: + enabled: false + lockfile: {}`, + wantLockfile: true, + }, + { + name: "a present block without enabled is on", + block: ` +mise: + lockfile: + requireChecksums: true`, + wantEnabled: true, + wantLockfile: true, + wantAnyCheck: true, + wantTrustedProvenance: DefaultTrustedProvenance, + }, + { + name: "the lockfile check keys decode", + block: ` +mise: + lockfile: + requireProvenance: ["aqua:*"] + requiredPlatforms: [linux-x64, linux-arm64] + minimumLockfileVersion: 2`, + wantEnabled: true, + wantLockfile: true, + wantAnyCheck: true, + wantTrustedProvenance: DefaultTrustedProvenance, + wantRequireProvenance: []string{"aqua:*"}, + wantRequiredPlatforms: []string{"linux-x64", "linux-arm64"}, + wantMinimumLockfileVersion: new(2), + }, + { + name: "trustedProvenance replaces the default list", + block: ` +mise: + lockfile: + trustedProvenance: [slsa]`, + wantEnabled: true, + wantLockfile: true, + wantAnyCheck: true, + wantTrustedProvenance: []string{"slsa"}, + }, + { + name: "an empty trustedProvenance trusts no kind", + block: ` +mise: + lockfile: + trustedProvenance: []`, + wantEnabled: true, + wantLockfile: true, + wantAnyCheck: true, + wantTrustedProvenance: []string{}, + }, + { + name: "required alone is a check", + block: ` +mise: + required: true`, + wantEnabled: true, + wantRequired: true, + wantAnyCheck: true, + }, + { + name: "enabled: false turns the lockfile check off", + block: ` +mise: + lockfile: + enabled: false`, + wantEnabled: true, + }, + { + name: "an absent lockfile block is off", + block: ` +mise: + exemptPackages: [node]`, + wantEnabled: true, + }, + { + name: "exemptPaths is read", + block: ` +mise: + lockfile: {} + exemptPaths: ["examples/**", "testdata/**"]`, + wantEnabled: true, + wantLockfile: true, + wantAnyCheck: true, + wantExemptPaths: []string{"examples/**", "testdata/**"}, + wantTrustedProvenance: DefaultTrustedProvenance, + }, + { + name: "a present versions block is on", + block: ` +mise: + versions: + forbiddenVersions: [latest]`, + wantEnabled: true, + wantVersions: true, + wantAnyCheck: true, + }, + { + name: "enabled: false turns the versions check off", + block: ` +mise: + versions: + enabled: false`, + wantEnabled: true, + }, + { + name: "a present sources block is on", + block: ` +mise: + sources: + trustedTools: ["core:*", "aqua:*"] + trustedRegistries: ["https://github.com/*"] + trustedReplacement: ["https://mirror.example.com/*"] + trustedOptions: ["https://ghe.example.com/*"]`, + wantEnabled: true, + wantSources: true, + wantAnyCheck: true, + }, + { + name: "enabled: false turns the sources check off", + block: ` +mise: + sources: + enabled: false`, + wantEnabled: true, + }, + { + name: "an invalid trustedTools glob is a config error", + block: ` +mise: + sources: + trustedTools: ["aqua:[x"]`, + wantErr: `invalid pattern "aqua:[x" in mise.sources.trustedTools`, + }, + { + name: "an invalid trustedRegistries glob is a config error", + block: ` +mise: + sources: + trustedRegistries: ["https://[x"]`, + wantErr: `invalid pattern "https://[x" in mise.sources.trustedRegistries`, + }, + { + name: "the old authorizedSources key is a config error", + block: ` +mise: + sources: + authorizedSources: ["aqua:*"]`, + wantErr: `unknown key(s) "authorizedSources" in mise.sources`, + }, + { + name: "an unknown sources key is a config error", + block: ` +mise: + sources: + trustedSources: []`, + wantErr: `unknown key(s) "trustedSources" in mise.sources`, + }, + { + name: "a tasks block with a list is on", + block: ` +mise: + tasks: + required: [lint, "test:*"]`, + wantEnabled: true, + wantTasks: true, + wantAnyCheck: true, + }, + { + name: "a disabled tasks block needs no requirement", + block: ` +mise: + tasks: + enabled: false`, + wantEnabled: true, + }, + { + name: "a tasks block with no requirement is a config error", + block: ` +mise: + tasks: {}`, + wantErr: `mise.tasks: set 'required'`, + }, + { + name: "an empty list is a config error", + block: ` +mise: + tasks: + required: []`, + wantErr: `mise.tasks: set 'required'`, + }, + { + name: "the old expression form is a config error", + block: ` +mise: + tasks: + required: lint AND test`, + wantErr: `mise.tasks.required must be a list of task names`, + }, + { + name: "the old requiredGroups key is a config error", + block: ` +mise: + tasks: + requiredGroups: [[lint]]`, + wantErr: `unknown key(s) "requiredGroups" in mise.tasks`, + }, + { + name: "an invalid task glob is a config error", + block: ` +mise: + tasks: + required: ["lint:["]`, + wantErr: `invalid pattern "lint:[" in mise.tasks.required`, + }, + { + name: "an unknown mise key is a config error", + block: ` +mise: + npm: {}`, + wantErr: `unknown key(s) "npm" in mise;`, + }, + { + name: "an invalid forbiddenVersions glob is a config error", + block: ` +mise: + versions: + forbiddenVersions: ["[latest"]`, + wantErr: `invalid pattern "[latest" in mise.versions.forbiddenVersions`, + }, + { + name: "an unknown versions key is a config error", + block: ` +mise: + versions: + allowedVersionPattern: '^1$'`, + wantErr: `unknown key(s) "allowedVersionPattern" in mise.versions`, + }, + { + name: "an unknown lockfile key is a config error", + block: ` +mise: + lockfile: + requireChecksum: true`, + wantErr: `unknown key(s) "requireChecksum" in mise.lockfile`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + data := "version: \"2.0\"\ngithub:\n controls: {}" + tc.block + "\n" + pc, _, _, err := LoadPlumberConfigFromBytes([]byte(data), "test") + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatalf("load: %v", err) + } + if got := pc.Mise.IsEnabled(); got != tc.wantEnabled { + t.Errorf("IsEnabled = %v, want %v", got, tc.wantEnabled) + } + if got := pc.Mise.LockfileCheckEnabled(); got != tc.wantLockfile { + t.Errorf("LockfileCheckEnabled = %v, want %v", got, tc.wantLockfile) + } + if got := pc.Mise.VersionsCheckEnabled(); got != tc.wantVersions { + t.Errorf("VersionsCheckEnabled = %v, want %v", got, tc.wantVersions) + } + if got := pc.Mise.TasksCheckEnabled(); got != tc.wantTasks { + t.Errorf("TasksCheckEnabled = %v, want %v", got, tc.wantTasks) + } + if got := pc.Mise.SourcesCheckEnabled(); got != tc.wantSources { + t.Errorf("SourcesCheckEnabled = %v, want %v", got, tc.wantSources) + } + var gotPaths []string + if pc.Mise != nil { + gotPaths = pc.Mise.ExemptPaths + } + if !slices.Equal(gotPaths, tc.wantExemptPaths) { + t.Errorf("ExemptPaths = %v, want %v", gotPaths, tc.wantExemptPaths) + } + if got := pc.Mise != nil && pc.Mise.Required; got != tc.wantRequired { + t.Errorf("Required = %v, want %v", got, tc.wantRequired) + } + if got := pc.Mise.IsEnabled() && pc.Mise.AnyCheckEnabled(); got != tc.wantAnyCheck { + t.Errorf("AnyCheckEnabled = %v, want %v", got, tc.wantAnyCheck) + } + if tc.wantLockfile && tc.wantEnabled { + got := pc.Mise.Lockfile.TrustedProvenanceOrDefault() + if !slices.Equal(got, tc.wantTrustedProvenance) || (got == nil) != (tc.wantTrustedProvenance == nil) { + t.Errorf("TrustedProvenanceOrDefault = %#v, want %#v", got, tc.wantTrustedProvenance) + } + lf := pc.Mise.Lockfile + if !slices.Equal(lf.RequireProvenance, tc.wantRequireProvenance) { + t.Errorf("RequireProvenance = %#v, want %#v", lf.RequireProvenance, tc.wantRequireProvenance) + } + if !slices.Equal(lf.RequiredPlatforms, tc.wantRequiredPlatforms) { + t.Errorf("RequiredPlatforms = %#v, want %#v", lf.RequiredPlatforms, tc.wantRequiredPlatforms) + } + if (lf.MinimumLockfileVersion == nil) != (tc.wantMinimumLockfileVersion == nil) || + (lf.MinimumLockfileVersion != nil && *lf.MinimumLockfileVersion != *tc.wantMinimumLockfileVersion) { + t.Errorf("MinimumLockfileVersion = %v, want %v", lf.MinimumLockfileVersion, tc.wantMinimumLockfileVersion) + } + } + }) + } +} + +// TestMiseConfigYAMLRoundTrip pins that a list whose emptiness means +// something survives marshal then unmarshal: config slim and the resolver +// write configs back to YAML, and omitempty drops an empty slice. +func TestMiseConfigYAMLRoundTrip(t *testing.T) { + cases := []struct { + name string + block string + want []string + }{ + {name: "an empty trustedProvenance stays empty", block: "trustedProvenance: []\n", want: []string{}}, + {name: "an absent trustedProvenance stays the default", block: "requireChecksums: true\n", want: DefaultTrustedProvenance}, + {name: "a set trustedProvenance is kept", block: "trustedProvenance: [slsa]\n", want: []string{"slsa"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var c MiseLockfileCheckConfig + if err := yaml.Unmarshal([]byte(tc.block), &c); err != nil { + t.Fatal(err) + } + out, err := yaml.Marshal(&c) + if err != nil { + t.Fatal(err) + } + var back MiseLockfileCheckConfig + if err := yaml.Unmarshal(out, &back); err != nil { + t.Fatal(err) + } + got := back.TrustedProvenanceOrDefault() + if !slices.Equal(got, tc.want) || (got == nil) != (tc.want == nil) { + t.Errorf("after a round trip (%q): TrustedProvenanceOrDefault = %#v, want %#v", out, got, tc.want) + } + }) + } +} + +// An empty trustedRegistries trusts no URL and an absent one checks none: +// a YAML round trip must not turn the first into the second. +func TestMiseSourcesConfigYAMLRoundTrip(t *testing.T) { + cases := []struct { + name string + block string + want []string + wantSet bool + }{ + {name: "an empty trustedRegistries stays set and empty", block: "trustedRegistries: []\n", want: []string{}, wantSet: true}, + {name: "an absent trustedRegistries stays unset", block: "trustedTools: [\"core:*\"]\n"}, + {name: "a set trustedRegistries is kept", block: "trustedRegistries: [\"https://github.com/*\"]\n", want: []string{"https://github.com/*"}, wantSet: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var c MiseSourcesCheckConfig + if err := yaml.Unmarshal([]byte(tc.block), &c); err != nil { + t.Fatal(err) + } + out, err := yaml.Marshal(&c) + if err != nil { + t.Fatal(err) + } + var back MiseSourcesCheckConfig + if err := yaml.Unmarshal(out, &back); err != nil { + t.Fatal(err) + } + got, set := back.TrustedRegistriesList() + if set != tc.wantSet || !slices.Equal(got, tc.want) || (got == nil) != (tc.want == nil) { + t.Errorf("after a round trip (%q): TrustedRegistriesList = %#v, %v, want %#v, %v", out, got, set, tc.want, tc.wantSet) + } + }) + } +} diff --git a/configuration/plumberconfig.go b/configuration/plumberconfig.go index 5e0833d5..efc74b11 100644 --- a/configuration/plumberconfig.go +++ b/configuration/plumberconfig.go @@ -179,9 +179,17 @@ func validControlNames() []string { return keys } -// ValidControlNames returns all known control names from the configuration schema. +// topLevelConfigControls are controls configured by a top-level key of +// .plumber.yaml instead of a block under gitlab.controls or github.controls +// (mise-en-place: the `mise:` block, #254). They are not +// valid keys under a provider's controls, but they are valid control names +// for --controls and --skip-controls. +var topLevelConfigControls = []string{"mise-en-place"} + +// ValidControlNames returns every known control name: the ones configured +// under a provider's controls and the ones configured by a top-level key. func ValidControlNames() []string { - names := validControlNames() + names := append(validControlNames(), topLevelConfigControls...) sort.Strings(names) return names } @@ -230,6 +238,12 @@ type PlumberConfig struct { // GitHub provider section (v2 schema). Same shape as GitLab. GitHub *ProviderConfig `yaml:"github,omitempty"` + // Mise configures the mise checks of mise-en-place + // (#254). It is top level because it does not depend on the provider: + // the same block applies to a GitHub or a GitLab repository. Missing + // or `enabled: false` turns the checks off. + Mise *MiseConfig `yaml:"mise,omitempty"` + // Controls configuration (legacy v1 schema, top-level). // After a v2 load this is the zero value; after a v1 load convertV1ToV2 // moves these into GitLab.Controls and clears this field. diff --git a/configuration/plumberconfig_test.go b/configuration/plumberconfig_test.go index fcf2bbef..4f1f00ba 100644 --- a/configuration/plumberconfig_test.go +++ b/configuration/plumberconfig_test.go @@ -456,6 +456,7 @@ func TestValidControlNames(t *testing.T) { "mergeRequestApprovalRulesMustRequireMinimumApprovals", "mergeRequestApprovalSettingsMustBeCompliant", "mergeRequestSettingsMustBeCompliant", + "mise-en-place", "numberOfProjectMembersMustRespectQuota", "pipelineMustIncludeComponent", "pipelineMustIncludeTemplate", diff --git a/configuration/registry.go b/configuration/registry.go index 15c5c522..c5fda938 100644 --- a/configuration/registry.go +++ b/configuration/registry.go @@ -100,6 +100,7 @@ const ( CategoryThirdPartyActions = "Third-party Actions" CategoryWorkflowTriggersAndPermissions = "Workflow Triggers and Permissions" CategoryRepositoryHygiene = "Repository Hygiene" + CategoryPackageManagers = "Package Managers and Lockfiles" ) // controlsMeta is the canonical registry of every control name the @@ -410,6 +411,13 @@ var controlsMeta = map[string]ControlMeta{ ID: "CTRL-305", Description: "Verifies that deploy and release jobs consuming production secrets declare an environment gate.", }, + "mise-en-place": { + Providers: []string{ProviderGitLab, ProviderGitHub}, + DisplayName: "mise-en-place", + Category: CategoryPackageManagers, + ID: "CTRL-1001", + Description: "Verifies the mise files of the repository: that every config has a committed, up to date lockfile whose downloads carry checksums and trusted provenance, that no tool requests a forbidden version such as latest, that tools come from authorized sources, that every mise project declares the required tasks, and, when required, that the repository uses mise at all.", + }, "dockerfilesMustPinBaseImageByDigest": { Providers: []string{ProviderGitHub}, DisplayName: "Dockerfiles must pin base images by digest", diff --git a/configuration/registry_id_test.go b/configuration/registry_id_test.go index 8315857a..6e3fbda1 100644 --- a/configuration/registry_id_test.go +++ b/configuration/registry_id_test.go @@ -16,7 +16,7 @@ var updateIDs = flag.Bool("update-ids", false, "rewrite testdata/control_ids_gol // can hang durable state on (#458). Format and uniqueness are pinned here; // the id-to-name pairing is frozen by the golden below. func TestControlIDsAreWellFormedAndUnique(t *testing.T) { - idPattern := regexp.MustCompile(`^CTRL-\d{3}$`) + idPattern := regexp.MustCompile(`^CTRL-\d{3,4}$`) seen := map[string]string{} for _, e := range ControlsCatalog() { if !idPattern.MatchString(e.ID) { diff --git a/configuration/testdata/control_ids_golden.txt b/configuration/testdata/control_ids_golden.txt index 07d1d812..b545e887 100644 --- a/configuration/testdata/control_ids_golden.txt +++ b/configuration/testdata/control_ids_golden.txt @@ -1,3 +1,4 @@ +CTRL-1001 mise-en-place CTRL-101 containerImageMustComeFromAuthorizedSources CTRL-102 containerImageMustNotUseForbiddenTags CTRL-201 cicdVariablesMustBeProtected diff --git a/control/catalog_document.go b/control/catalog_document.go index 52ea1ea8..3f57cbc1 100644 --- a/control/catalog_document.go +++ b/control/catalog_document.go @@ -18,6 +18,9 @@ type CatalogIssueType struct { Remediation string `json:"remediation"` DocURL string `json:"docUrl"` ControlName string `json:"controlName"` + // Subject groups the codes of one control by the check that raises + // them (mise-en-place: lockfile, presence, ...), absent otherwise. + Subject string `json:"subject,omitempty"` } // CatalogControl is one control in the exported catalog: the CTRL-XXX @@ -81,6 +84,7 @@ func Catalog(cliVersion string) CatalogDocument { Remediation: info.Remediation, DocURL: info.DocURL, ControlName: info.ControlName, + Subject: info.Subject, }) if info.ControlName != "" { codesByControl[info.ControlName] = append(codesByControl[info.ControlName], string(info.Code)) diff --git a/control/catalog_export_test.go b/control/catalog_export_test.go index 72e9bfe7..16598a60 100644 --- a/control/catalog_export_test.go +++ b/control/catalog_export_test.go @@ -12,25 +12,29 @@ import ( // the block its registered codes live in. Pinning the derivation keeps a // new control from landing in the wrong docs grouping silently (#440). func TestControlCategoriesFollowTheCodeBlocks(t *testing.T) { - blockCategory := map[byte]string{ - '1': configuration.CategoryContainerImages, - '2': configuration.CategoryCICDVariables, - '3': configuration.CategoryCICDSecrets, - '4': configuration.CategoryPipelineComposition, - '5': configuration.CategoryAccessAndAuthorization, - '6': configuration.CategorySecuritySource, - '7': configuration.CategoryThirdPartyActions, - '8': configuration.CategoryWorkflowTriggersAndPermissions, - '9': configuration.CategoryRepositoryHygiene, + // Keyed by the hundreds block: "1" for 1xx ... "10" for 10xx. Every + // package manager owns its own block from 10xx on, all in one category. + blockCategory := map[string]string{ + "1": configuration.CategoryContainerImages, + "2": configuration.CategoryCICDVariables, + "3": configuration.CategoryCICDSecrets, + "4": configuration.CategoryPipelineComposition, + "5": configuration.CategoryAccessAndAuthorization, + "6": configuration.CategorySecuritySource, + "7": configuration.CategoryThirdPartyActions, + "8": configuration.CategoryWorkflowTriggersAndPermissions, + "9": configuration.CategoryRepositoryHygiene, + "10": configuration.CategoryPackageManagers, } for _, entry := range configuration.ControlsCatalog() { codes := CodesForControl(entry.Name) if len(codes) == 0 { continue } - blocks := map[byte]bool{} + blocks := map[string]bool{} for _, c := range codes { - blocks[strings.TrimPrefix(string(c), "ISSUE-")[0]] = true + n := strings.TrimPrefix(string(c), "ISSUE-") + blocks[n[:len(n)-2]] = true } if len(blocks) != 1 { t.Errorf("%s: codes span more than one block (%v); the category derivation assumes one", entry.Name, codes) @@ -38,7 +42,7 @@ func TestControlCategoriesFollowTheCodeBlocks(t *testing.T) { } for b := range blocks { if want := blockCategory[b]; entry.Category != want { - t.Errorf("%s: category %q, want %q (its codes live in the %cxx block)", entry.Name, entry.Category, want, b) + t.Errorf("%s: category %q, want %q (its codes live in the %sxx block)", entry.Name, entry.Category, want, b) } } } diff --git a/control/codes.go b/control/codes.go index a651b6a4..e1488dd4 100644 --- a/control/codes.go +++ b/control/codes.go @@ -229,6 +229,60 @@ const ( CodeSecurityPolicyProjectNotSet ErrorCode = "ISSUE-601" ) +// Issue codes for the mise-en-place control (10xx). Codes are numbered +// in sequence, whatever check they belong to; Subject groups them +// (lockfile, presence, versions, sources, tasks). The next package +// manager takes 11xx. +const ( + // ISSUE-1001: Tools are declared in a mise config and its lockfile is not committed + CodeMiseLockfileMissing ErrorCode = "ISSUE-1001" + // ISSUE-1002: A mise config turns lockfiles off (`[settings] lockfile = false`) + CodeMiseLockfileDisabled ErrorCode = "ISSUE-1002" + // ISSUE-1003: A mise tool request has no matching entry in mise.lock + CodeMiseToolNotLocked ErrorCode = "ISSUE-1003" + // ISSUE-1004: A download locked in mise.lock has no checksum + CodeMiseChecksumMissing ErrorCode = "ISSUE-1004" + // ISSUE-1005: A download locked in mise.lock records a provenance outside trustedProvenance + CodeMiseProvenanceUntrusted ErrorCode = "ISSUE-1005" + // ISSUE-1006: A download locked in mise.lock has no provenance where requireProvenance asks for one + CodeMiseProvenanceMissing ErrorCode = "ISSUE-1006" + // ISSUE-1007: A platform listed in requiredPlatforms is not locked in mise.lock + CodeMisePlatformNotLocked ErrorCode = "ISSUE-1007" + // ISSUE-1008: mise.lock uses a format older than minimumLockfileVersion + CodeMiseLockfileOutdatedFormat ErrorCode = "ISSUE-1008" + // ISSUE-1009: A tool is declared in asdf's .tool-versions, which mise never locks + CodeMiseToolVersionsUnlocked ErrorCode = "ISSUE-1009" + // ISSUE-1010: mise is required and the repository has no mise config + CodeMiseMissing ErrorCode = "ISSUE-1010" + // ISSUE-1011: A mise tool request uses a forbidden version (latest, lts, nightly, ...) + CodeMiseVersionForbidden ErrorCode = "ISSUE-1011" + // ISSUE-1012: A mise tool request cannot be read statically (template, empty or unquoted version) + CodeMiseVersionUnreadable ErrorCode = "ISSUE-1012" + // ISSUE-1013: A mise tool is not in trustedTools + CodeMiseToolUntrusted ErrorCode = "ISSUE-1013" + // ISSUE-1014: A download URL locked in mise.lock is not in trustedRegistries + CodeMiseRegistryUntrusted ErrorCode = "ISSUE-1014" + // ISSUE-1015: A mise url_replacements entry sends downloads to a URL outside trustedReplacement + CodeMiseReplacementUntrusted ErrorCode = "ISSUE-1015" + // ISSUE-1016: A mise tool option sets a download URL outside trustedOptions + CodeMiseOptionUntrusted ErrorCode = "ISSUE-1016" + // ISSUE-1017: A mise project does not declare every task of tasks.required + CodeMiseTasksMissing ErrorCode = "ISSUE-1017" + // ISSUE-1018: A tool is locked in mise.lock without a download URL or checksum + CodeMiseDownloadNotLocked ErrorCode = "ISSUE-1018" + // ISSUE-1019: A mise local config (mise.local.toml, ...) is committed + CodeMiseLocalConfigCommitted ErrorCode = "ISSUE-1019" +) + +// Subjects of the mise-en-place codes (ErrorCodeInfo.Subject). +const ( + SubjectMiseLockfile = "lockfile" + SubjectMisePresence = "presence" + SubjectMiseVersions = "versions" + SubjectMiseSources = "sources" + SubjectMiseTasks = "tasks" +) + // ErrorCodeInfo provides metadata about an issue code. type ErrorCodeInfo struct { // Code is the unique issue code (e.g., ISSUE-102). @@ -255,6 +309,10 @@ type ErrorCodeInfo struct { DocURL string `json:"docUrl"` // ControlName is the .plumber.yaml control key this code belongs to. ControlName string `json:"controlName"` + // Subject groups the codes of one control by the check that raises + // them, so they can be filtered together (mise-en-place: lockfile, + // presence, versions, sources, tasks). Empty for other controls. + Subject string `json:"subject,omitempty"` // Role decides how a finding of this code enters the score (spec: contextual // score). EntryKind is set for RoleEntry only and names the situation fact // the finding anchors to. @@ -1145,6 +1203,219 @@ var errorCodeRegistry = map[ErrorCode]ErrorCodeInfo{ ControlName: "workflowMustNotGrantPermissionsWriteAll", Role: RolePrivilege, }, + // Package manager controls (10xx: mise). Role: hygiene. The tools + // are installed by the pipeline, but a version or a download that is + // not pinned is a supply-chain weakness, not an attack path a finding + // can anchor. + CodeMiseLockfileMissing: { + Code: CodeMiseLockfileMissing, + Severity: SeverityHigh, + Title: "mise: tools are declared and the lockfile is not committed", + Description: "A mise config file declares tools in `[tools]`, but the lockfile mise writes them to (`mise.lock`, or `mise..lock` for `mise..toml`) is not committed. Without it, every `mise install` resolves versions and download URLs at install time, so CI can install a different build than the one that was reviewed, and nothing checks the downloaded bytes against a recorded checksum.", + Remediation: "Turn lockfiles on with `[settings] lockfile = true` in the config, run `mise lock`, and commit the lockfile. Install in CI with `mise install --locked` (or `jdx/mise-action`, which adds it when a lockfile exists).", + DocURL: docsBaseURL + string(CodeMiseLockfileMissing), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseLockfileDisabled: { + Code: CodeMiseLockfileDisabled, + Severity: SeverityHigh, + Title: "mise: lockfiles are turned off", + Description: "A mise config sets `[settings] lockfile = false`. mise then never reads or writes a lockfile for the project, so tool versions and downloads are resolved at install time on every machine and in CI.", + Remediation: "Remove `lockfile = false` (or set it to `true`), run `mise lock`, and commit the lockfile.", + DocURL: docsBaseURL + string(CodeMiseLockfileDisabled), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseToolNotLocked: { + Code: CodeMiseToolNotLocked, + Severity: SeverityHigh, + Title: "mise: a tool is not locked", + Description: "A tool request in a mise config has no entry in the lockfile whose `specifiers` contain that request: the lockfile is stale or incomplete, so mise resolves the tool at install time. The same finding is raised when Plumber cannot read the request statically (a template value) or when the lockfile uses format 0, which records no `specifiers`: Plumber cannot prove the tool is locked, so it does not pass it.", + Remediation: "Run `mise lock` and commit the updated lockfile. For a format 0 lockfile, run `mise lock --upgrade` to move it to the current format. Replace a templated version with a literal one, or list the tool in `exemptPackages` if the exception is intentional.", + DocURL: docsBaseURL + string(CodeMiseToolNotLocked), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseChecksumMissing: { + Code: CodeMiseChecksumMissing, + Severity: SeverityHigh, + Title: "mise: a tool is locked without a checksum", + Description: "A platform entry of `mise.lock` records a download URL but no `checksum`. mise then cannot verify that the bytes it downloads are the ones that were locked, so a release asset replaced upstream (a re-published GitHub release, a compromised mirror) is installed without notice.", + Remediation: "Run `mise lock` so mise records the checksum, and prefer a backend that publishes checksums (aqua, core tools). If the source publishes none, list the tool in `exemptPackages` once you have reviewed it.", + DocURL: docsBaseURL + string(CodeMiseChecksumMissing), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseProvenanceUntrusted: { + Code: CodeMiseProvenanceUntrusted, + Severity: SeverityMedium, + Title: "mise: a tool is locked with an untrusted provenance", + Description: "A platform entry of `mise.lock` records a provenance of a kind that is not in `trustedProvenance`. mise verifies a download against the provenance its lockfile records, so a kind you do not trust is the only proof of who built the tool.", + Remediation: "Lock the tool from a source that publishes a trusted provenance (`mise lock` records it), add the kind to `trustedProvenance` once you have reviewed it, or list the tool in `exemptPackages`.", + DocURL: docsBaseURL + string(CodeMiseProvenanceUntrusted), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseProvenanceMissing: { + Code: CodeMiseProvenanceMissing, + Severity: SeverityMedium, + Title: "mise: a tool is locked without a provenance", + Description: "A download locked in `mise.lock` comes from a backend listed in `requireProvenance`, but its platform entry records no `provenance` (SLSA, cosign, minisign or GitHub attestations). The checksum only proves the bytes did not change after locking; provenance proves who built them.", + Remediation: "Run `mise lock` with a mise version that records provenance, use a source that publishes it, or remove the backend from `requireProvenance`.", + DocURL: docsBaseURL + string(CodeMiseProvenanceMissing), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMisePlatformNotLocked: { + Code: CodeMisePlatformNotLocked, + Severity: SeverityLow, + Title: "mise: a required platform is not locked", + Description: "A tool that locks per-platform downloads has no entry for a platform listed in `requiredPlatforms`. CI or developers on that platform resolve the download at install time, outside the lockfile.", + Remediation: "Run `mise lock --platform ` for the missing platforms (or set `lockfile_platforms`) and commit the lockfile.", + DocURL: docsBaseURL + string(CodeMisePlatformNotLocked), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseLockfileOutdatedFormat: { + Code: CodeMiseLockfileOutdatedFormat, + Severity: SeverityLow, + Title: "mise: the lockfile format is older than the minimum", + Description: "The lockfile's `lockfile_version` is older than `minimumLockfileVersion`. Older formats record less: format 0 has no `specifiers`, so it cannot prove which request a locked version belongs to.", + Remediation: "Run `mise lock --upgrade` to move the lockfile to the current format, and commit it.", + DocURL: docsBaseURL + string(CodeMiseLockfileOutdatedFormat), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseToolVersionsUnlocked: { + Code: CodeMiseToolVersionsUnlocked, + Severity: SeverityMedium, + Title: "mise: a tool is declared in asdf's .tool-versions", + Description: "A tool is declared in a `.tool-versions` file and in no mise config of the same directory. mise reads `.tool-versions` but never locks it, so the tool's version and download are resolved at install time.", + Remediation: "Move the tool to the `[tools]` table of `mise.toml`, run `mise lock`, and commit the lockfile.", + DocURL: docsBaseURL + string(CodeMiseToolVersionsUnlocked), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseDownloadNotLocked: { + Code: CodeMiseDownloadNotLocked, + Severity: SeverityHigh, + Title: "mise: a tool is locked without a download URL or checksum", + Description: "A lock entry in `mise.lock` records nothing mise can verify a download against: a tool from a backend that downloads a per-platform binary (aqua, github, gitlab, ubi, http) is locked with no platform table, or a platform table has neither `url` nor `checksum`. mise then resolves and downloads the binary at install time with no checksum to check it against.", + Remediation: "Run `mise lock --platform ` so mise records the URL and checksum of each platform, and commit the lockfile. List the tool in `exemptPackages` if its source publishes no downloadable asset you can lock.", + DocURL: docsBaseURL + string(CodeMiseDownloadNotLocked), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseLocalConfigCommitted: { + Code: CodeMiseLocalConfigCommitted, + Severity: SeverityHigh, + Title: "mise: a local config is committed", + Description: "A mise local config (`mise.local.toml`, `mise..local.toml`, `config.local.toml` or a `conf.d/*.local.toml` fragment) is committed to the repository. mise loads it on every clone, CI included, so its tools, settings and environment apply to everyone. A local config is meant for one machine and must not be committed (https://mise.jdx.dev/glossary.html#mise-local-toml), and a reviewer reading `mise.toml` does not see what it adds.", + Remediation: "Move what CI needs into `mise.toml` and lock it with `mise lock`, delete the local config from the repository (`git rm --cached`), and add `*.local.toml` to `.gitignore`.", + DocURL: docsBaseURL + string(CodeMiseLocalConfigCommitted), + ControlName: "mise-en-place", + Subject: SubjectMiseLockfile, + Role: RoleHygiene, + }, + CodeMiseMissing: { + Code: CodeMiseMissing, + Severity: SeverityMedium, + Title: "mise: the repository has no mise config", + Description: "`mise.required` is set, and the repository commits no mise config outside `exemptPaths` (a `.tool-versions` file alone does not count). The tools CI installs are then not declared, locked or checked with mise.", + Remediation: "Declare the tools CI uses in a `mise.toml`, run `mise lock`, and commit both files. Remove `required` if this repository does not use mise.", + DocURL: docsBaseURL + string(CodeMiseMissing), + ControlName: "mise-en-place", + Subject: SubjectMisePresence, + Role: RoleHygiene, + }, + CodeMiseVersionForbidden: { + Code: CodeMiseVersionForbidden, + Severity: SeverityHigh, + Title: "mise: a tool uses a forbidden version", + Description: "A tool request in a mise config matches a pattern of `forbiddenVersions` (`latest`, `lts`, `stable`, `nightly`, `prefix:`, `system`, ...). The lockfile may still pin a version, but the next `mise lock --bump`, `mise upgrade` or regenerated lockfile moves it with no change in the config, so the version is never reviewed where people review it.", + Remediation: "Write an exact version in the config (`terraform = \"1.9.8\"`), run `mise lock`, and commit both files, or list the tool in `exemptPackages` if the exception is intentional.", + DocURL: docsBaseURL + string(CodeMiseVersionForbidden), + ControlName: "mise-en-place", + Subject: SubjectMiseVersions, + Role: RoleHygiene, + }, + CodeMiseVersionUnreadable: { + Code: CodeMiseVersionUnreadable, + Severity: SeverityHigh, + Title: "mise: a tool version cannot be read statically", + Description: "A tool request in a mise config is a template (`{{ env.NODE_VERSION }}`), is empty, or is not a quoted string (`node = 24`, which mise rejects). Plumber reads files and never runs mise, so it cannot tell which version is requested or check it against `forbiddenVersions`: it reports the request instead of passing it.", + Remediation: "Write the version as a quoted literal (`node = \"24.11.1\"`), run `mise lock`, and commit both files. List the tool in `exemptPackages` if the version has to come from the environment.", + DocURL: docsBaseURL + string(CodeMiseVersionUnreadable), + ControlName: "mise-en-place", + Subject: SubjectMiseVersions, + Role: RoleHygiene, + }, + CodeMiseToolUntrusted: { + Code: CodeMiseToolUntrusted, + Severity: SeverityHigh, + Title: "mise: a tool is not trusted", + Description: "A tool in a mise config matches no pattern of `trustedTools`. The pattern is matched against the tool's full mise name: its key when it names a backend (`aqua:jqlang/jq`, `github:org/repo`), or the backend its `mise.lock` entry records for a shorthand (`terraform`). The backend decides where mise downloads the tool from and how it verifies it. A shorthand with no lock entry can't be traced to a backend, so it is reported too.", + Remediation: "Install the tool from a trusted backend (for example `aqua:` or a core tool), add it to `trustedTools` once you have reviewed it, or list it in `exemptPackages`.", + DocURL: docsBaseURL + string(CodeMiseToolUntrusted), + ControlName: "mise-en-place", + Subject: SubjectMiseSources, + Role: RoleHygiene, + }, + CodeMiseRegistryUntrusted: { + Code: CodeMiseRegistryUntrusted, + Severity: SeverityHigh, + Title: "mise: a locked download URL is not a trusted registry", + Description: "A platform entry of `mise.lock` records a download `url` that matches no pattern of `trustedRegistries`. That is the URL `mise install --locked` downloads, so a change to `mise.lock` alone can point a trusted tool at any host. Checked only when `trustedRegistries` is set.", + Remediation: "Run `mise lock` from a trusted source so the lockfile records its URL, or add the registry to `trustedRegistries` once you operate or trust it.", + DocURL: docsBaseURL + string(CodeMiseRegistryUntrusted), + ControlName: "mise-en-place", + Subject: SubjectMiseSources, + Role: RoleHygiene, + }, + CodeMiseReplacementUntrusted: { + Code: CodeMiseReplacementUntrusted, + Severity: SeverityHigh, + Title: "mise: a URL replacement is not trusted", + Description: "A mise config sets `[settings] url_replacements`, and a replacement URL matches no pattern of `trustedReplacement`. mise sends the download to the replacement first, while `mise.lock` keeps the original URL, so the lockfile alone does not show where tools come from.", + Remediation: "Remove the replacement, or add its URL to `trustedReplacement` once you operate or trust the host.", + DocURL: docsBaseURL + string(CodeMiseReplacementUntrusted), + ControlName: "mise-en-place", + Subject: SubjectMiseSources, + Role: RoleHygiene, + }, + CodeMiseOptionUntrusted: { + Code: CodeMiseOptionUntrusted, + Severity: SeverityMedium, + Title: "mise: a tool option sets an untrusted URL", + Description: "A trusted tool sets an option that changes where it is downloaded from, to a URL that matches no pattern of `trustedOptions`: `api_url` (a GitHub or GitLab server), `url` or `platforms..url` (the asset itself), or a pip index (`registry_url`, `indexes`, `pipx_args`, `uvx_args`, `install_env`).", + Remediation: "Remove the option so the backend fetches from its own source, add the URL to `trustedOptions` if you operate it (a GitHub Enterprise server, an internal mirror), or list the tool in `exemptPackages` once reviewed.", + DocURL: docsBaseURL + string(CodeMiseOptionUntrusted), + ControlName: "mise-en-place", + Subject: SubjectMiseSources, + Role: RoleHygiene, + }, + CodeMiseTasksMissing: { + Code: CodeMiseTasksMissing, + Severity: SeverityMedium, + Title: "mise: a project misses required tasks", + Description: "A mise project (a directory holding a mise config) does not declare the tasks `mise.tasks.required` asks for. When CI runs `mise run `, the tasks the organization expects (lint, test, a security scan) are the steps that actually run, so a project without them skips those steps. Tasks count from `[tasks]` tables, TOML task files, executable files of the task directories, and parent directories, as `mise run` sees them. Tasks from a remote (`git::`, `oci::`, `zip::`) or templated include are not read, so they never satisfy the requirement.", + Remediation: "Declare the missing tasks in the project's `mise.toml` (`[tasks.lint]`) or as executable files in `mise-tasks/`, or list the project's path in `exemptPaths` if it is not meant to run them.", + DocURL: docsBaseURL + string(CodeMiseTasksMissing), + ControlName: "mise-en-place", + Subject: SubjectMiseTasks, + Role: RoleHygiene, + }, } // NestedRemediationApplies says whether a finding reached through via diff --git a/control/github_stats.go b/control/github_stats.go index fd0b6051..58c11d85 100644 --- a/control/github_stats.go +++ b/control/github_stats.go @@ -25,6 +25,7 @@ func AggregateGitHubStats(pipeline *ir.NormalizedPipeline, pc *configuration.Plu return &GitHubAnalysisStats{} } stats := &GitHubAnalysisStats{WorkflowLockfilePath: pipeline.WorkflowLockfilePath} + stats.MiseConfigsTotal, stats.MiseToolsTotal = MiseTotals(pipeline.Mise) gh := pc.ControlsFor("github") trustedOwners := defaultTrustedActionOwners diff --git a/control/gitlab_shaped_providers_test.go b/control/gitlab_shaped_providers_test.go index 6758bbae..0e2752d9 100644 --- a/control/gitlab_shaped_providers_test.go +++ b/control/gitlab_shaped_providers_test.go @@ -73,6 +73,7 @@ var wantLiveGitLab = []string{ "mergeRequestApprovalRulesMustRequireMinimumApprovals", "mergeRequestApprovalSettingsMustBeCompliant", "mergeRequestSettingsMustBeCompliant", + "mise-en-place", "numberOfProjectMembersMustRespectQuota", "pipelineMustIncludeComponent", "pipelineMustIncludeTemplate", @@ -125,7 +126,10 @@ func TestGitLabShapedControls_ControlSetsUnchanged(t *testing.T) { t.Errorf("GitHubControls changed:\n got %v\nwant %v", gotOrder, wantGitHubControlsOrder) } + // Live on GitHub: GitHubControls plus the provider-independent controls + // (PackageManagerControls), which RunControls adds to every run. wantLiveGitHub := append([]string(nil), wantGitHubControlsOrder...) + wantLiveGitHub = append(wantLiveGitHub, "mise-en-place") sort.Strings(wantLiveGitHub) if got := liveControls(configuration.ProviderGitHub); !reflect.DeepEqual(got, wantLiveGitHub) { t.Errorf("controls reaching GitHub users changed:\n got %v\nwant %v", got, wantLiveGitHub) diff --git a/control/lanes.go b/control/lanes.go index dbc8cf3a..4efee1a8 100644 --- a/control/lanes.go +++ b/control/lanes.go @@ -998,6 +998,11 @@ func ReEvaluateForConfig( // was missing entirely - markPlatformLaneGapsFor above is GitLab-only // by design, and GitHub's branch control passed vacuously without it. MarkUncollectedLanes(&scopedResult, entries, provider) + // mise-en-place is not in entries (it is not a provider control), so + // its gap is marked against this policy's own mise block: a policy + // that turns mise on over a scan nobody read gets not_evaluated, not a + // pass. + markPackageManagersGap(&scopedResult, pc) scopedResult.DropNotEvaluableFindings() // The counters must describe the findings that survive the drop above, // so this runs after it: the per-control counts on GitHubStats have to diff --git a/control/mrcomment.go b/control/mrcomment.go index 7223bff0..49bd0357 100644 --- a/control/mrcomment.go +++ b/control/mrcomment.go @@ -200,7 +200,7 @@ func generateMRComment(result *AnalysisResult, pc *configuration.PlumberConfig, // always zero, under v3. var otherIssues int - mrEntries := GitLabControls(pc) + mrEntries := RunControls(pc, configuration.ProviderGitLab) MarkSkippedByFilter(mrEntries, controlsFilterList, skipControlsList) for _, e := range mrEntries { findings := findingsByControl[e.ControlName] @@ -684,4 +684,5 @@ var mrCommentControlOrder = []struct { {"pullRequestTargetMustNotCheckoutHead", "pull_request_target workflows must not check out the PR head"}, {"workflowMustNotGrantPermissionsWriteAll", "Workflow must not grant write-all permissions"}, {"githubActionMustComeFromAuthorizedSources", "Actions must come from authorized sources"}, + {"mise-en-place", "mise-en-place"}, } diff --git a/control/packagemanagers.go b/control/packagemanagers.go new file mode 100644 index 00000000..36092d46 --- /dev/null +++ b/control/packagemanagers.go @@ -0,0 +1,346 @@ +package control + +import ( + "context" + "errors" + "fmt" + "slices" + "strings" + "time" + + "github.com/sirupsen/logrus" + + "github.com/getplumber/plumber/configuration" + githubpkg "github.com/getplumber/plumber/github" + "github.com/getplumber/plumber/gitlab" + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/internal/repofs" + "github.com/getplumber/plumber/packagemanager/mise" + "github.com/getplumber/plumber/utils" +) + +// controlMiseEnPlace checks the mise files of the repository (#254): +// configs, lockfiles and .tool-versions. +const controlMiseEnPlace = "mise-en-place" + +// PackageManagerControls lists the controls that do not depend on the +// provider: they are configured by a top-level key of .plumber.yaml +// (`mise:`), not under gitlab.controls or github.controls. A missing or +// disabled mise block skips the control. +func PackageManagerControls(pc *configuration.PlumberConfig) []ControlEntry { + if pc == nil { + return nil + } + return []ControlEntry{{ + DisplayName: "mise-en-place", + ControlName: controlMiseEnPlace, + Skipped: !pc.Mise.IsEnabled(), + }} +} + +// RunControls lists every control a run on provider evaluates: the +// provider's own controls (GitLabControls, GitHubControls), then the +// provider-independent ones (PackageManagerControls). The report, the +// score and the MR comment read this list. +func RunControls(pc *configuration.PlumberConfig, provider string) []ControlEntry { + var entries []ControlEntry + switch provider { + case configuration.ProviderGitLab: + entries = GitLabControls(pc) + case configuration.ProviderGitHub: + entries = GitHubControls(pc) + default: + return nil + } + return append(entries, PackageManagerControls(pc)...) +} + +// miseChecksRun reports whether at least one mise check runs: the +// top-level mise block is present, not disabled, and turns a check on. +func miseChecksRun(pc *configuration.PlumberConfig) bool { + return pc != nil && pc.Mise.IsEnabled() && pc.Mise.AnyCheckEnabled() +} + +// packageSource is where scanPackageManagers reads the repository: the +// local checkout at root, or, without one, the remote repository remote +// opens. The run's provider and mode choose it, so the mise block names +// no provider. Both empty means nothing can be read. +type packageSource struct { + root string + remote func() (repofs.Source, error) +} + +// newGitHubRemoteFiles and newGitLabRemoteFiles open a remote +// repository's files; tests swap them. +var ( + newGitHubRemoteFiles = func(host, owner, repo, rev string) (repofs.Source, error) { + return githubpkg.NewRemoteFiles(host, owner, repo, rev) + } + newGitLabRemoteFiles = func(conf *configuration.Configuration, ref string) (repofs.Source, error) { + return gitlab.NewRemoteFiles(conf.ProjectPath, ref, conf.GitlabToken, conf.GitlabURL, conf) + } +) + +// scanPackageManagers reads the package manager files of the repository +// into pipeline, from the checkout or the remote repository (src). It +// reads them when any configuration the run collects for turns a mise +// check on: the run's own configuration, or in platform mode every +// resolved policy (collectionConfigs), since each policy is then +// evaluated over this one scan. Nothing is read when --controls / +// --skip-controls leave mise-en-place out: a control the run does not +// report must not stop it. With no source pipeline.Mise stays nil and +// markPackageManagersGap reports the control not evaluated. +// +// A remote read lists the tree once and fetches the mise files in +// batches (repofs.Rounds), never one request per file. +// +// A mise file that cannot be read stops the run: the error +// (*mise.ReadError) lists every such file, and no report is produced. A +// file under exemptPaths only spares the run when every configuration +// that checks mise exempts it. +func scanPackageManagers(pipeline *ir.NormalizedPipeline, conf *configuration.Configuration, src packageSource) error { + if pipeline == nil || conf == nil || (src.root == "" && src.remote == nil) { + return nil + } + if !shouldRunControl(controlMiseEnPlace, conf) { + return nil + } + var opts mise.Options + for _, pc := range collectionConfigs(conf) { + if !miseChecksRun(pc) { + continue + } + opts.ExemptPaths = append(opts.ExemptPaths, stringsOrEmpty(pc.Mise.ExemptPaths)) + // .tool-versions is read for the lockfile check only (ISSUE-1009). + // The sources check reads lock entries: a shorthand's backend and + // the locked download URLs. + opts.ToolVersions = opts.ToolVersions || pc.Mise.LockfileCheckEnabled() + opts.Lockfiles = opts.Lockfiles || pc.Mise.LockfileCheckEnabled() || pc.Mise.SourcesCheckEnabled() + opts.Tasks = opts.Tasks || pc.Mise.TasksCheckEnabled() + } + if len(opts.ExemptPaths) == 0 { + return nil + } + var scan *ir.MiseScan + var err error + start := time.Now() + mode := "local" + if src.root != "" { + root := src.root + opts.Tracked = func(paths []string) []string { return trackedFiles(root, paths) } + scan, err = mise.Scan(mise.DirFS(root), opts) + } else { + // Every file of a remote repository is committed: opts.Tracked + // stays nil, so a local config there is read. + mode = "remote" + scan, err = scanRemoteMise(context.Background(), src.remote, opts) + } + logrus.WithFields(logrus.Fields{"mode": mode, "duration": time.Since(start).Round(time.Millisecond)}). + Info("mise files read") + if errors.Is(err, repofs.ErrTooLarge) { + // Too large to read remotely: mise-en-place is not evaluated, + // every other control still reports (markPackageManagersGap). + logrus.WithError(err).Warn("mise files not read") + pipeline.MiseNotRead = err.Error() + return nil + } + if err != nil { + return err + } + pipeline.Mise = scan + return nil +} + +// gitlabMiseRef is the ref a remote GitLab read of the mise files uses: +// the analyzed commit, so the files match the CI configuration read. When +// --branch names another branch and its head could not be fetched, +// HeadCommitSha is still the default branch's head: the branch itself is +// read then, never the default branch under the analyzed branch's name. +func gitlabMiseRef(project *gitlab.Project, result *AnalysisResult) string { + if result == nil { + return project.DefaultBranch + } + sha, branch := result.HeadCommitSha, result.AnalyzeBranch + switch { + case branch != "" && branch != project.DefaultBranch && sha == project.LatestHeadCommitSha: + return branch + case sha != "" && sha != "HEAD": + return sha + case branch != "": + return branch + } + return project.DefaultBranch +} + +// scanRemoteMise lists the remote repository, fetches every file the +// scan reads by name in one batch, and scans; a file only the scan finds +// (a task include, a symlink target) is fetched in a later round. +func scanRemoteMise(ctx context.Context, open func() (repofs.Source, error), opts mise.Options) (*ir.MiseScan, error) { + src, err := open() + if err != nil { + return nil, fmt.Errorf("read the mise files: %w", err) + } + entries, err := src.List(ctx) + if err != nil { + return nil, fmt.Errorf("read the mise files: %w", err) + } + f := repofs.New(entries) + if err := f.Fetch(ctx, src, f.Paths(opts.Wanted)); err != nil { + return nil, fmt.Errorf("read the mise files: %w", err) + } + return repofs.Rounds(ctx, f, src, repofs.MaxRounds, func(f *repofs.FS) (*ir.MiseScan, error) { + return mise.Scan(f, opts) + }) +} + +// trackedFiles keeps the paths git tracks in the repository at root: a +// mise local config on disk is personal unless it was committed. When git +// cannot answer, every path is kept, so a committed file is never missed. +func trackedFiles(root string, paths []string) []string { + if len(paths) == 0 { + return paths + } + out, err := utils.GitOutput(root, append([]string{"ls-files", "-z", "--"}, paths...)...) + if err != nil { + return paths + } + tracked := map[string]bool{} + for _, p := range strings.Split(out, "\x00") { + tracked[p] = true + } + var kept []string + for _, p := range paths { + if tracked[p] { + kept = append(kept, p) + } + } + return kept +} + +// markPackageManagersGap reports mise-en-place not +// evaluated, never passed, when it could not check anything: +// - the mise block is on but turns no check on (config_required), +// - the repository was too large to read remotely (collection_failed, +// the run degraded), +// - the mise files were not read for this run (a policy that turns +// mise on over a run that did not read them). +// +// A mise file that cannot be read is not a gap: it stops the run before +// this point (scanPackageManagers). A missing or disabled mise block +// leaves the result alone: the control is skipped. +func markPackageManagersGap(r *AnalysisResult, pc *configuration.PlumberConfig) { + if pc == nil || !pc.Mise.IsEnabled() { + return + } + p := r.evaluatedPipeline() + m := p.MiseOrNil() + switch { + case !pc.Mise.AnyCheckEnabled(): + r.MarkNotEvaluable(controlMiseEnPlace, ReasonConfigRequired) + case m == nil && p != nil && p.MiseNotRead != "": + r.MarkNotEvaluable(controlMiseEnPlace, ReasonCollectionFailed) + markDegraded(r, "the mise files were not read: "+p.MiseNotRead+"; mise-en-place was not evaluated") + case m == nil: + r.MarkNotEvaluable(controlMiseEnPlace, ReasonLaneNotCollected) + default: + return + } + r.DropNotEvaluableFindings() +} + +// skipFilterWithMise returns skip plus mise-en-place when +// the top-level mise block is missing or disabled. DisabledControlNames +// only reads the provider controls, which do not carry the mise switch, so +// this is how the finding filter and the failed-policy count learn that +// the control is off. +func skipFilterWithMise(skip []string, pc *configuration.PlumberConfig) []string { + if pc != nil && pc.Mise.IsEnabled() { + return skip + } + return append(slices.Clone(skip), controlMiseEnPlace) +} + +// engineConfigFor is the Rego config of one provider's run: the provider's +// controls (buildEngineConfig) plus the top-level mise block, which does +// not depend on the provider. +func engineConfigFor(pc *configuration.PlumberConfig, controls *configuration.ControlsConfig, gitlabURL string) map[string]any { + cfg := buildEngineConfig(controls, gitlabURL) + if pc == nil { + return cfg + } + if pm := packageManagersEngineConfig(pc.Mise); pm != nil { + if cfg == nil { + cfg = map[string]any{} + } + cfg[controlMiseEnPlace] = pm + } + return cfg +} + +// packageManagersEngineConfig projects the top-level mise block onto the +// Rego input (input.config["mise-en-place"].mise). A check +// whose block is absent or disabled is left out, so its rules abstain. +func packageManagersEngineConfig(m *configuration.MiseConfig) map[string]any { + if !m.IsEnabled() { + return nil + } + miseCfg := map[string]any{ + "required": m.Required, + "exemptPackages": stringsOrEmpty(m.ExemptPackages), + "exemptPaths": stringsOrEmpty(m.ExemptPaths), + } + if m.LockfileCheckEnabled() { + lf := m.Lockfile + lockfile := map[string]any{ + "requireChecksums": lf.RequireChecksums == nil || *lf.RequireChecksums, + "requireProvenance": stringsOrEmpty(lf.RequireProvenance), + "trustedProvenance": lf.TrustedProvenanceOrDefault(), + "requiredPlatforms": stringsOrEmpty(lf.RequiredPlatforms), + } + if lf.MinimumLockfileVersion != nil { + lockfile["minimumLockfileVersion"] = *lf.MinimumLockfileVersion + } + miseCfg["lockfile"] = lockfile + } + if m.VersionsCheckEnabled() { + miseCfg["versions"] = map[string]any{ + "forbiddenVersions": stringsOrEmpty(m.Versions.ForbiddenVersions), + } + } + if m.TasksCheckEnabled() { + miseCfg["tasks"] = map[string]any{"required": stringsOrEmpty(m.Tasks.Required)} + } + if m.SourcesCheckEnabled() { + sources := map[string]any{ + "trustedTools": stringsOrEmpty(m.Sources.TrustedTools), + "trustedReplacement": stringsOrEmpty(m.Sources.TrustedReplacement), + "trustedOptions": stringsOrEmpty(m.Sources.TrustedOptions), + } + // Absent trustedRegistries: the locked URLs are not checked, so + // the key is left out and ISSUE-1014 abstains. + if registries, ok := m.Sources.TrustedRegistriesList(); ok { + sources["trustedRegistries"] = registries + } + miseCfg["sources"] = sources + } + return map[string]any{"mise": miseCfg} +} + +func stringsOrEmpty(in []string) []string { + if in == nil { + return []string{} + } + return in +} + +// MiseTotals returns how many mise configs the scan read and how many tool +// requests they declare, for the stats blocks. +func MiseTotals(m *ir.MiseScan) (configs, tools int) { + if m == nil { + return 0, 0 + } + for _, c := range m.Configs { + tools += len(c.Tools) + } + return len(m.Configs), tools +} diff --git a/control/packagemanagers_run_test.go b/control/packagemanagers_run_test.go new file mode 100644 index 00000000..f6071345 --- /dev/null +++ b/control/packagemanagers_run_test.go @@ -0,0 +1,532 @@ +package control + +import ( + "context" + "errors" + "fmt" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/sirupsen/logrus" + + "github.com/getplumber/plumber/configuration" + githubpkg "github.com/getplumber/plumber/github" + "github.com/getplumber/plumber/gitlab" + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/internal/repofs" + "github.com/getplumber/plumber/packagemanager/mise" +) + +// writeMiseFiles writes files (repository path -> content) under root. +func writeMiseFiles(t *testing.T, root string, files map[string]string) { + t.Helper() + for rel, content := range files { + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } +} + +// readErrorPaths returns the files a *mise.ReadError names, nil for any +// other error. +func readErrorPaths(err error) []string { + readErr, ok := errors.AsType[*mise.ReadError](err) + if !ok { + return nil + } + var out []string + for _, f := range readErr.Files { + out = append(out, f.Path) + } + return out +} + +func miseLockfileOn() *configuration.MiseConfig { + return &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}} +} + +// memRepo is a remote repository held in memory (path -> content). It +// records the listings and reads it serves. +type memRepo struct { + files map[string]string + lists, reads int +} + +func (m *memRepo) List(context.Context) ([]repofs.Entry, error) { + m.lists++ + var out []repofs.Entry + for p := range m.files { + out = append(out, repofs.Entry{Path: p, Mode: 0o644}) + } + return out, nil +} + +func (m *memRepo) Read(_ context.Context, paths []string) (map[string]repofs.Blob, error) { + m.reads++ + out := map[string]repofs.Blob{} + for _, p := range paths { + if c, ok := m.files[p]; ok { + out[p] = repofs.Blob{Data: []byte(c)} + } + } + return out, nil +} + +// swapGitLabRemote serves repo as the remote GitLab project and returns +// the refs it was opened at. +func swapGitLabRemote(t *testing.T, repo *memRepo) *[]string { + t.Helper() + var refs []string + orig := newGitLabRemoteFiles + newGitLabRemoteFiles = func(_ *configuration.Configuration, ref string) (repofs.Source, error) { + refs = append(refs, ref) + return repo, nil + } + t.Cleanup(func() { newGitLabRemoteFiles = orig }) + return &refs +} + +// TestRunRegoEngine_Mise drives the GitLab engine entry point: a checkout +// at the analyzed ref is read from disk, where an unreadable mise file +// stops the run; a checkout at another ref is not read, the project is +// read through the API at the analyzed ref instead. +func TestRunRegoEngine_Mise(t *testing.T) { + cases := []struct { + name string + files map[string]string + remote map[string]string + branch string + wantErr []string + wantScanned bool + wantRefs []string + }{ + { + name: "an unreadable mise file stops the run", + files: map[string]string{"mise.toml": "[tools"}, + wantErr: []string{"mise.toml"}, + }, + { + name: "a readable checkout is scanned", + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n"}, + wantScanned: true, + }, + { + name: "a checkout at another ref than --branch is not read: the remote project is, at that ref", + files: map[string]string{"mise.toml": "[tools"}, + remote: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n"}, + branch: "feature", + wantScanned: true, + wantRefs: []string{"feature"}, + }, + { + name: "an unreadable remote mise file stops the run too", + remote: map[string]string{"svc/mise.toml": "[tools"}, + branch: "feature", + wantErr: []string{"svc/mise.toml"}, + wantRefs: []string{"feature"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + writeMiseFiles(t, root, tc.files) + refs := swapGitLabRemote(t, &memRepo{files: tc.remote}) + conf := &configuration.Configuration{ + ProjectPath: "grp/app", + Branch: tc.branch, + IsLocalProject: true, + GitRepoRoot: root, + PlumberConfig: &configuration.PlumberConfig{Version: "2.0", GitLab: &configuration.ProviderConfig{}, Mise: miseLockfileOn()}, + } + result := &AnalysisResult{CiValid: true, AnalyzeBranch: tc.branch} + findings, err := runRegoEngine(logrus.NewEntry(logrus.New()), conf, &gitlab.Project{DefaultBranch: "main"}, nil, nil, nil, nil, nil, nil, nil, result) + if !reflect.DeepEqual(*refs, tc.wantRefs) { + t.Errorf("remote read at %v, want %v", *refs, tc.wantRefs) + } + if got := readErrorPaths(err); !reflect.DeepEqual(got, tc.wantErr) { + t.Fatalf("unreadable files = %v (err %v), want %v", got, err, tc.wantErr) + } + if tc.wantErr != nil { + if findings != nil { + t.Errorf("findings = %v, want none when the run stops", findings) + } + return + } + if got := result.Pipeline.MiseOrNil() != nil; got != tc.wantScanned { + t.Errorf("scanned = %v, want %v", got, tc.wantScanned) + } + }) + } +} + +// TestRunGitHubAnalysis_Mise drives a local GitHub run: an unreadable mise +// file stops it with no result, and a readable config reaches the +// policies. +func TestRunGitHubAnalysis_Mise(t *testing.T) { + cases := []struct { + name string + files map[string]string + wantErr []string + wantCode string + }{ + { + name: "an unreadable mise file stops the run", + files: map[string]string{"mise.toml": "[tools", "svc/mise.lock": "[tools", "svc/mise.toml": "[tools]\nnode = \"24\"\n"}, + wantErr: []string{"mise.toml", "svc/mise.lock"}, + }, + { + name: "a config without its lockfile reaches the policies", + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n"}, + wantCode: "ISSUE-1001", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := writeMinimalGitHubWorkflowRow62(t) + writeMiseFiles(t, root, tc.files) + conf := &configuration.Configuration{ + ProjectPath: "owner/repo", + Branch: "main", + GitRepoRoot: root, + PlumberConfig: &configuration.PlumberConfig{Version: "2.0", GitHub: &configuration.ProviderConfig{}, Mise: miseLockfileOn()}, + } + result, err := RunGitHubAnalysis(conf) + if got := readErrorPaths(err); !reflect.DeepEqual(got, tc.wantErr) { + t.Fatalf("unreadable files = %v (err %v), want %v", got, err, tc.wantErr) + } + if tc.wantErr != nil { + if result != nil { + t.Errorf("result = %+v, want nil when the run stops", result) + } + return + } + found := false + for _, f := range result.Findings { + if f.Code == tc.wantCode && f.File == "mise.toml" { + found = true + } + } + if !found { + t.Errorf("findings = %v, want %s on mise.toml", result.Findings, tc.wantCode) + } + }) + } +} + +// TestRunGitHubAnalysisRemote_Mise drives a remote GitHub run: the mise +// files are read through the API at the commit the workflows were read +// at, with one listing and one batched read, and reach the policies; an +// unreadable one stops the run. +func TestRunGitHubAnalysisRemote_Mise(t *testing.T) { + cases := []struct { + name string + remote map[string]string + remoteRev string + wantErr []string + wantCode string + wantRev string + }{ + { + name: "a config without its lockfile reaches the policies", + remote: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n", "README.md": "x"}, + remoteRev: "0123abcd", + wantCode: "ISSUE-1001", + wantRev: "0123abcd", + }, + { + name: "an unreadable mise file stops the run", + remote: map[string]string{"mise.toml": "[tools"}, + wantErr: []string{"mise.toml"}, + wantRev: "feature-x", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + swapRemoteScan(t, func(host, owner, repo, ref string, enrich, scanMutableExec bool, progressFn githubpkg.ProgressFunc) (*ir.NormalizedPipeline, []error, error) { + p, errs, err := remoteScanStub(host, owner, repo, ref, enrich, scanMutableExec, progressFn) + p.RemoteRev = tc.remoteRev + return p, errs, err + }) + repo := &memRepo{files: tc.remote} + var revs []string + orig := newGitHubRemoteFiles + newGitHubRemoteFiles = func(_, _, _, rev string) (repofs.Source, error) { + revs = append(revs, rev) + return repo, nil + } + t.Cleanup(func() { newGitHubRemoteFiles = orig }) + conf := &configuration.Configuration{ + ProjectPath: "owner/repo", + PlumberConfig: &configuration.PlumberConfig{Version: "2.0", GitHub: &configuration.ProviderConfig{}, Mise: miseLockfileOn()}, + } + result, err := RunGitHubAnalysisRemote(conf, "owner", "repo", "feature-x") + if got := readErrorPaths(err); !reflect.DeepEqual(got, tc.wantErr) { + t.Fatalf("unreadable files = %v (err %v), want %v", got, err, tc.wantErr) + } + if !reflect.DeepEqual(revs, []string{tc.wantRev}) { + t.Errorf("remote read at %v, want [%s]", revs, tc.wantRev) + } + if repo.lists != 1 || repo.reads != 1 { + t.Errorf("%d listings and %d reads, want 1 and 1", repo.lists, repo.reads) + } + if tc.wantErr != nil { + return + } + found := false + for _, f := range result.Findings { + if f.Code == tc.wantCode && f.File == "mise.toml" { + found = true + } + } + if !found { + t.Errorf("findings = %v, want %s on mise.toml", result.Findings, tc.wantCode) + } + }) + } +} + +// TestReEvaluateForConfig_Mise is the per-policy side of platform mode: a +// policy is evaluated over the scan the run already made. A policy that +// turns mise on over a run whose mise files were never read must report +// mise-en-place not evaluated, never a pass; one whose data was read is +// judged on it. +func TestReEvaluateForConfig_Mise(t *testing.T) { + scanned := &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}} + cases := []struct { + name string + provider string + scan *ir.MiseScan + policy *configuration.MiseConfig + wantReason string + wantCode string + }{ + { + name: "GitLab: mise files never read, the policy turns mise on", + provider: configuration.ProviderGitLab, + policy: miseLockfileOn(), + wantReason: ReasonLaneNotCollected, + }, + { + name: "GitHub: mise files never read, the policy turns mise on", + provider: configuration.ProviderGitHub, + policy: miseLockfileOn(), + wantReason: ReasonLaneNotCollected, + }, + { + name: "GitLab: the scan was read, the policy is judged on it", + provider: configuration.ProviderGitLab, + scan: scanned, + policy: miseLockfileOn(), + wantCode: "ISSUE-1001", + }, + { + name: "the policy's mise block turns no check on", + provider: configuration.ProviderGitHub, + scan: scanned, + policy: &configuration.MiseConfig{}, + wantReason: ReasonConfigRequired, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + pipeline := &ir.NormalizedPipeline{Provider: ir.Provider(tc.provider), ProjectPath: "grp/app", Mise: tc.scan} + result := &AnalysisResult{CiValid: true} + policy := &configuration.PlumberConfig{Version: "2.0", Mise: tc.policy} + if tc.provider == configuration.ProviderGitLab { + result.Pipeline = pipeline + policy.GitLab = &configuration.ProviderConfig{} + } else { + result.GitHubPipeline = pipeline + policy.GitHub = &configuration.ProviderConfig{} + } + conf := &configuration.Configuration{PlumberConfig: &configuration.PlumberConfig{Version: "2.0"}} + scoped, _, ok := ReEvaluateForConfig(result, conf, tc.provider, policy) + if !ok { + t.Fatal("a result carrying a pipeline must be re-evaluable") + } + if got := scoped.NotEvaluable[controlMiseEnPlace]; got != tc.wantReason { + t.Errorf("mise-en-place not evaluable = %q, want %q", got, tc.wantReason) + } + var codes []string + for _, f := range scoped.Findings { + if strings.HasPrefix(f.Code, "ISSUE-10") { + codes = append(codes, f.Code) + } + } + var want []string + if tc.wantCode != "" { + want = []string{tc.wantCode} + } + if !reflect.DeepEqual(codes, want) { + t.Errorf("mise findings = %v, want %v", codes, want) + } + }) + } +} + +// errRepo is a remote repository whose listing or reads fail with err. +type errRepo struct { + listErr, readErr error + files []repofs.Entry +} + +func (e errRepo) List(context.Context) ([]repofs.Entry, error) { return e.files, e.listErr } +func (e errRepo) Read(context.Context, []string) (map[string]repofs.Blob, error) { + return nil, e.readErr +} + +// TestScanPackageManagers_RemoteFailures: a remote that cannot be opened, +// listed or read stops the run; one too large to read leaves mise-en-place +// not evaluated (collection_failed) and the run degraded, and every other +// control still reports. +func TestScanPackageManagers_RemoteFailures(t *testing.T) { + tooLarge := fmt.Errorf("%w: GitHub cannot list the tree", repofs.ErrTooLarge) + cases := []struct { + name string + open func() (repofs.Source, error) + wantErr string + wantNotRead bool + }{ + {name: "the remote cannot be opened", open: func() (repofs.Source, error) { return nil, errors.New("no token") }, wantErr: "read the mise files: no token"}, + {name: "the listing fails", open: func() (repofs.Source, error) { return errRepo{listErr: errors.New("502")}, nil }, wantErr: "read the mise files: 502"}, + {name: "the reads fail", open: func() (repofs.Source, error) { + return errRepo{readErr: errors.New("rate limited"), files: []repofs.Entry{{Path: "mise.toml", Mode: 0o644}}}, nil + }, wantErr: "read the mise files: rate limited"}, + {name: "too large to read", open: func() (repofs.Source, error) { return errRepo{listErr: tooLarge}, nil }, wantNotRead: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := &ir.NormalizedPipeline{} + conf := &configuration.Configuration{PlumberConfig: &configuration.PlumberConfig{Mise: miseLockfileOn()}} + err := scanPackageManagers(p, conf, packageSource{remote: tc.open}) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Errorf("error = %v, want %q", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatalf("error = %v, want none", err) + } + if p.Mise != nil || (p.MiseNotRead != "") != tc.wantNotRead { + t.Errorf("Mise = %v, MiseNotRead = %q; want no scan and a reason", p.Mise, p.MiseNotRead) + } + }) + } +} + +// TestRunGitHubAnalysisRemote_MiseTooLarge: a repository too large to +// read remotely is reported, mise-en-place not evaluated, the run +// degraded. +func TestRunGitHubAnalysisRemote_MiseTooLarge(t *testing.T) { + swapRemoteScan(t, remoteScanStub) + orig := newGitHubRemoteFiles + newGitHubRemoteFiles = func(string, string, string, string) (repofs.Source, error) { + return errRepo{listErr: fmt.Errorf("%w: GitHub cannot list the tree", repofs.ErrTooLarge)}, nil + } + t.Cleanup(func() { newGitHubRemoteFiles = orig }) + conf := &configuration.Configuration{ + ProjectPath: "owner/repo", + PlumberConfig: &configuration.PlumberConfig{Version: "2.0", GitHub: &configuration.ProviderConfig{}, Mise: miseLockfileOn()}, + } + result, err := RunGitHubAnalysisRemote(conf, "owner", "repo", "main") + if err != nil { + t.Fatalf("RunGitHubAnalysisRemote: %v", err) + } + if got := result.NotEvaluable[controlMiseEnPlace]; got != ReasonCollectionFailed { + t.Errorf("mise-en-place not evaluable = %q, want %q", got, ReasonCollectionFailed) + } + if !result.DataCollectionDegraded || !strings.Contains(strings.Join(result.DegradedReasons, "\n"), "mise files were not read") { + t.Errorf("degraded = %v %v, want the mise reason", result.DataCollectionDegraded, result.DegradedReasons) + } +} + +func TestGitlabMiseRef(t *testing.T) { + project := &gitlab.Project{DefaultBranch: "main", LatestHeadCommitSha: "aaa"} + cases := []struct { + name string + result *AnalysisResult + want string + }{ + {name: "the analyzed commit", result: &AnalysisResult{HeadCommitSha: "bbb", AnalyzeBranch: "feature"}, want: "bbb"}, + {name: "the default branch at its commit", result: &AnalysisResult{HeadCommitSha: "aaa", AnalyzeBranch: "main"}, want: "aaa"}, + {name: "a branch whose head could not be fetched is read by name", result: &AnalysisResult{HeadCommitSha: "aaa", AnalyzeBranch: "feature"}, want: "feature"}, + {name: "no commit known: the analyzed branch", result: &AnalysisResult{HeadCommitSha: "HEAD", AnalyzeBranch: "feature"}, want: "feature"}, + {name: "nothing known: the default branch", result: &AnalysisResult{}, want: "main"}, + {name: "no result: the default branch", want: "main"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := gitlabMiseRef(project, tc.result); got != tc.want { + t.Errorf("gitlabMiseRef = %q, want %q", got, tc.want) + } + }) + } +} + +// TestRunAnalysis_MiseWithoutCI: a GitLab run that stops early, before the +// mise files are read, reports mise-en-place not evaluated, never passed: +// a project without a CI file (limited analysis), and a network failure +// while fetching the project, its pipeline configuration or its pipeline +// variables (degraded run). +func TestRunAnalysis_MiseWithoutCI(t *testing.T) { + cases := []struct { + name string + recorder *gitlabRecorder + wantMissing bool + wantDegraded bool + // wantReason pins which early return the run took. + wantReason string + }{ + {name: "no CI file", recorder: &gitlabRecorder{noCI: true}, wantMissing: true}, + {name: "project fetch fails", recorder: &gitlabRecorder{resetOn: "GET /api/v4/projects/:id"}, wantDegraded: true, wantReason: "project information could not be fetched"}, + // Origin collection turns a failed CI read into a limited analysis + // and never returns a network error, so the run's own "pipeline + // configuration could not be fetched" return is not reached. + {name: "CI file read fails", recorder: &gitlabRecorder{resetOn: "GET /api/v4/projects/:id/repository/files/:file/raw"}, wantDegraded: true, wantReason: "connection reset by peer"}, + {name: "pipeline image collection fails", recorder: &gitlabRecorder{resetOn: "POST /api/graphql getProjectGroupsVariables"}, wantDegraded: true, wantReason: "pipeline image/variable data could not be fetched"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + tc.recorder.sha = "0123456789abcdef0123456789abcdef01234567" + srv := httptest.NewServer(tc.recorder) + defer srv.Close() + conf := configuration.NewDefaultConfiguration() + conf.GitlabURL = srv.URL + conf.GitlabToken = "glpat-mise" + conf.ProjectPath = testProjectPath + conf.HTTPClientTimeout = 10 * time.Second + conf.GitlabRetryMaxRetries = 0 + conf.PlumberConfig = &configuration.PlumberConfig{Version: "2.0", GitLab: &configuration.ProviderConfig{}, Mise: miseLockfileOn()} + + result, err := RunAnalysis(conf) + if err != nil { + t.Fatalf("RunAnalysis: %v", err) + } + if result.CiMissing != tc.wantMissing || result.DataCollectionDegraded != tc.wantDegraded { + t.Fatalf("CiMissing = %v, DataCollectionDegraded = %v (%v); want %v, %v", + result.CiMissing, result.DataCollectionDegraded, result.DegradedReasons, tc.wantMissing, tc.wantDegraded) + } + if tc.wantReason != "" && !slices.ContainsFunc(result.DegradedReasons, func(r string) bool { return strings.Contains(r, tc.wantReason) }) { + t.Errorf("DegradedReasons = %q, want one containing %q", result.DegradedReasons, tc.wantReason) + } + if got := result.NotEvaluable[controlMiseEnPlace]; got != ReasonLaneNotCollected { + t.Errorf("mise-en-place not evaluable = %q, want %q", got, ReasonLaneNotCollected) + } + }) + } +} diff --git a/control/packagemanagers_test.go b/control/packagemanagers_test.go new file mode 100644 index 00000000..9e26d612 --- /dev/null +++ b/control/packagemanagers_test.go @@ -0,0 +1,537 @@ +package control + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "reflect" + "testing" + + "github.com/getplumber/plumber/configuration" + opaengine "github.com/getplumber/plumber/internal/engine/opa" + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/packagemanager/mise" +) + +func TestMarkPackageManagersGap(t *testing.T) { + on, off := true, false + withLockfile := &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}} + finding := opaengine.Finding{Code: "ISSUE-1001", File: "mise.toml"} + cases := []struct { + name string + mise *configuration.MiseConfig + scan *ir.MiseScan + wantReason string + wantKept int + }{ + {name: "no checkout: not evaluated", mise: withLockfile, scan: nil, wantReason: ReasonLaneNotCollected}, + {name: "a complete scan keeps its findings", mise: withLockfile, scan: &ir.MiseScan{}, wantKept: 1}, + {name: "no check block: config required", mise: &configuration.MiseConfig{Enabled: &on}, wantReason: ReasonConfigRequired}, + {name: "required alone is a check", mise: &configuration.MiseConfig{Required: true}, scan: &ir.MiseScan{}, wantKept: 1}, + {name: "a missing mise block is left alone", mise: nil, wantKept: 1}, + {name: "a disabled mise block is left alone", mise: &configuration.MiseConfig{Enabled: &off, Lockfile: &configuration.MiseLockfileCheckConfig{}}, wantKept: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := &AnalysisResult{ + Pipeline: &ir.NormalizedPipeline{Mise: tc.scan}, + Findings: []opaengine.Finding{finding}, + } + markPackageManagersGap(r, &configuration.PlumberConfig{Mise: tc.mise}) + reason, _ := r.NotEvaluableReason(controlMiseEnPlace) + if reason != tc.wantReason { + t.Errorf("reason = %q, want %q", reason, tc.wantReason) + } + if len(r.Findings) != tc.wantKept { + t.Errorf("findings kept = %d, want %d", len(r.Findings), tc.wantKept) + } + }) + } +} + +func TestScanPackageManagers(t *testing.T) { + off := false + cases := []struct { + name string + mise *configuration.MiseConfig + root string + wantScan bool + // files are written under root before the scan. + files map[string]string + // wantErr lists the files the *mise.ReadError names. + wantErr []string + // controls and skip are --controls and --skip-controls. + controls []string + skip []string + // policies are the platform policies the run collects for. + policies []*configuration.PlumberConfig + // tracked, when set, makes root a git repository that tracks + // these files. + tracked []string + // wantLocal is the scan's LocalConfigs. + wantLocal []string + }{ + {name: "a lockfile check scans the checkout", mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, root: t.TempDir(), wantScan: true}, + {name: "a versions check alone scans the checkout", mise: &configuration.MiseConfig{Versions: &configuration.MiseVersionsCheckConfig{}}, root: t.TempDir(), wantScan: true}, + {name: "a sources check alone scans the checkout", mise: &configuration.MiseConfig{Sources: &configuration.MiseSourcesCheckConfig{}}, root: t.TempDir(), wantScan: true}, + {name: "a tasks check alone scans the checkout", mise: &configuration.MiseConfig{Tasks: &configuration.MiseTasksCheckConfig{Required: []string{"lint"}}}, root: t.TempDir(), wantScan: true}, + {name: "no checkout: no scan", mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, root: ""}, + {name: "a missing mise block: no scan", mise: nil, root: t.TempDir()}, + {name: "a disabled mise block: no scan", mise: &configuration.MiseConfig{Enabled: &off, Lockfile: &configuration.MiseLockfileCheckConfig{}}, root: t.TempDir()}, + {name: "no check block: no scan", mise: &configuration.MiseConfig{}, root: t.TempDir()}, + {name: "required alone scans the checkout", mise: &configuration.MiseConfig{Required: true}, root: t.TempDir(), wantScan: true}, + { + name: "an unreadable mise file stops the run", + mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, + root: t.TempDir(), + files: map[string]string{"mise.toml": "[tools", "svc/mise.toml": "[tools"}, + wantErr: []string{"mise.toml", "svc/mise.toml"}, + }, + { + name: "a platform policy that turns mise on scans the checkout when the run's own config does not", + mise: nil, + root: t.TempDir(), + policies: []*configuration.PlumberConfig{{}, {Mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}}}, + files: map[string]string{"mise.toml": "[tools]\n", ".tool-versions": "node 24\n"}, + wantScan: true, + }, + { + name: "no platform policy turns mise on: no scan", + mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, + root: t.TempDir(), + policies: []*configuration.PlumberConfig{{}, {}}, + }, + { + name: "a broken file only one policy exempts stops the run", + root: t.TempDir(), + policies: []*configuration.PlumberConfig{ + {Mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}, ExemptPaths: []string{"examples/**"}}}, + {Mise: &configuration.MiseConfig{Required: true}}, + }, + files: map[string]string{"examples/mise.toml": "[tools"}, + wantErr: []string{"examples/mise.toml"}, + }, + { + name: "the versions check alone reads no lockfile, so a broken one does not stop the run", + mise: &configuration.MiseConfig{Versions: &configuration.MiseVersionsCheckConfig{}}, + root: t.TempDir(), + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n", "mise.lock": "[tools"}, + wantScan: true, + }, + { + name: "the sources check alone reads lockfiles, so a broken one stops the run", + mise: &configuration.MiseConfig{Sources: &configuration.MiseSourcesCheckConfig{}}, + root: t.TempDir(), + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n", "mise.lock": "[tools"}, + wantErr: []string{"mise.lock"}, + }, + { + name: "--skip-controls mise-en-place reads nothing, so a broken file does not stop the run", + mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, + root: t.TempDir(), + files: map[string]string{"mise.toml": "[tools"}, + skip: []string{controlMiseEnPlace}, + }, + { + name: "--controls without mise-en-place reads nothing", + mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, + root: t.TempDir(), + files: map[string]string{"mise.toml": "[tools"}, + controls: []string{"branchMustBeProtected"}, + }, + { + name: "--controls with mise-en-place scans the checkout", + mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, + root: t.TempDir(), + controls: []string{controlMiseEnPlace}, + wantScan: true, + }, + { + name: "an unreadable mise file under exemptPaths does not stop the run", + mise: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}, ExemptPaths: []string{"examples/**"}}, + root: t.TempDir(), + files: map[string]string{"examples/mise.toml": "[tools"}, + wantScan: true, + }, + { + name: ".tool-versions is not read without the lockfile check", + mise: &configuration.MiseConfig{Required: true}, + root: t.TempDir(), + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n", ".tool-versions": "node 24\n"}, + wantScan: true, + }, + { + name: "a local config git does not track is left out of the scan", + mise: &configuration.MiseConfig{Required: true}, + root: t.TempDir(), + files: map[string]string{"mise.local.toml": "[tools]\n", "svc/mise.local.toml": "[tools]\n"}, + tracked: []string{"mise.local.toml"}, + wantScan: true, + wantLocal: []string{"mise.local.toml"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + for rel, content := range tc.files { + path := filepath.Join(tc.root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + if tc.tracked != nil { + for _, args := range [][]string{{"init", "-q"}, append([]string{"add", "--"}, tc.tracked...)} { + cmd := exec.Command("git", args...) + cmd.Dir = tc.root + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v %s", args, err, out) + } + } + } + p := &ir.NormalizedPipeline{} + err := scanPackageManagers(p, &configuration.Configuration{ + GitRepoRoot: tc.root, + PlumberConfig: &configuration.PlumberConfig{Mise: tc.mise}, + CollectionConfigs: tc.policies, + ControlsFilter: tc.controls, + SkipControlsFilter: tc.skip, + }, packageSource{root: tc.root}) + var gotErr []string + if readErr, ok := errors.AsType[*mise.ReadError](err); ok { + for _, f := range readErr.Files { + gotErr = append(gotErr, f.Path) + } + } else if err != nil { + t.Fatalf("error = %v, want a *mise.ReadError or nil", err) + } + if !reflect.DeepEqual(gotErr, tc.wantErr) { + t.Errorf("unreadable files = %v, want %v", gotErr, tc.wantErr) + } + if got := p.Mise != nil; got != tc.wantScan { + t.Errorf("scanned = %v, want %v", got, tc.wantScan) + } + if p.Mise != nil && (len(p.Mise.LocalConfigs) > 0 || len(tc.wantLocal) > 0) && !reflect.DeepEqual(p.Mise.LocalConfigs, tc.wantLocal) { + t.Errorf("LocalConfigs = %v, want %v", p.Mise.LocalConfigs, tc.wantLocal) + } + if p.Mise != nil && len(p.Mise.ToolVersions) > 0 && tc.policies == nil && !tc.mise.LockfileCheckEnabled() { + t.Errorf("ToolVersions = %v, want none without the lockfile check", p.Mise.ToolVersions) + } + }) + } +} + +// miseFromYAML loads a .plumber.yaml mise block, so a case goes through +// the same decoding as a user's file. +func miseFromYAML(block string) *configuration.MiseConfig { + pc, _, _, err := configuration.LoadPlumberConfigFromBytes([]byte("version: \"2.0\"\ngithub:\n controls: {}"+block+"\n"), "test") + if err != nil { + panic(err) + } + return pc.Mise +} + +func TestPackageManagersEngineConfig(t *testing.T) { + on, off := true, false + minimum := 3 + cases := []struct { + name string + cfg *configuration.MiseConfig + want map[string]any + }{ + {name: "missing mise block", cfg: nil, want: nil}, + {name: "disabled mise block", cfg: &configuration.MiseConfig{Enabled: &off}, want: nil}, + { + name: "no lockfile block leaves the check out", + cfg: &configuration.MiseConfig{ExemptPackages: []string{"node"}, ExemptPaths: []string{"examples/**"}}, + want: map[string]any{"mise": map[string]any{"required": false, "exemptPackages": []string{"node"}, "exemptPaths": []string{"examples/**"}}}, + }, + { + name: "required is passed on", + cfg: &configuration.MiseConfig{Required: true}, + want: map[string]any{"mise": map[string]any{"required": true, "exemptPackages": []string{}, "exemptPaths": []string{}}}, + }, + { + name: "lockfile block", + cfg: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{ + RequireChecksums: &on, RequiredPlatforms: []string{"linux-x64"}, MinimumLockfileVersion: &minimum, + }}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "lockfile": map[string]any{ + "requireChecksums": true, + "requireProvenance": []string{}, + "trustedProvenance": []string{"slsa", "github-attestations", "cosign", "minisign"}, + "requiredPlatforms": []string{"linux-x64"}, + "minimumLockfileVersion": 3, + }, + }}, + }, + { + name: "lockfile keys loaded from YAML reach the engine", + cfg: miseFromYAML(` +mise: + lockfile: + requireProvenance: ["aqua:*"] + requiredPlatforms: [linux-x64] + minimumLockfileVersion: 2`), + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "lockfile": map[string]any{ + "requireChecksums": true, + "requireProvenance": []string{"aqua:*"}, + "trustedProvenance": []string{"slsa", "github-attestations", "cosign", "minisign"}, + "requiredPlatforms": []string{"linux-x64"}, + "minimumLockfileVersion": 2, + }, + }}, + }, + { + name: "an empty lockfile block requires checksums", + cfg: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "lockfile": map[string]any{ + "requireChecksums": true, + "requireProvenance": []string{}, + "trustedProvenance": []string{"slsa", "github-attestations", "cosign", "minisign"}, + "requiredPlatforms": []string{}, + }, + }}, + }, + { + name: "versions block", + cfg: &configuration.MiseConfig{Versions: &configuration.MiseVersionsCheckConfig{ForbiddenVersions: []string{"latest", "ref:*"}}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "versions": map[string]any{"forbiddenVersions": []string{"latest", "ref:*"}}, + }}, + }, + { + name: "an empty versions block sends an empty list", + cfg: &configuration.MiseConfig{Versions: &configuration.MiseVersionsCheckConfig{}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "versions": map[string]any{"forbiddenVersions": []string{}}, + }}, + }, + { + name: "sources block without trustedRegistries leaves the locked URLs unchecked", + cfg: &configuration.MiseConfig{Sources: &configuration.MiseSourcesCheckConfig{ + TrustedTools: []string{"core:*", "aqua:*"}, + }}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "sources": map[string]any{ + "trustedTools": []string{"core:*", "aqua:*"}, + "trustedReplacement": []string{}, + "trustedOptions": []string{}, + }, + }}, + }, + { + name: "an empty trustedRegistries is passed on", + cfg: &configuration.MiseConfig{Sources: &configuration.MiseSourcesCheckConfig{ + TrustedRegistries: &[]string{}, + TrustedReplacement: []string{"https://mirror.example/*"}, + TrustedOptions: []string{"https://ghe.example/*"}, + }}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "sources": map[string]any{ + "trustedTools": []string{}, + "trustedRegistries": []string{}, + "trustedReplacement": []string{"https://mirror.example/*"}, + "trustedOptions": []string{"https://ghe.example/*"}, + }, + }}, + }, + { + name: "tasks block", + cfg: &configuration.MiseConfig{Tasks: &configuration.MiseTasksCheckConfig{Required: []string{"lint", "test:*"}}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "tasks": map[string]any{"required": []string{"lint", "test:*"}}, + }}, + }, + { + name: "a disabled tasks block leaves the check out", + cfg: &configuration.MiseConfig{Tasks: &configuration.MiseTasksCheckConfig{Enabled: &off}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + }}, + }, + { + name: "a disabled sources block leaves the check out", + cfg: &configuration.MiseConfig{Sources: &configuration.MiseSourcesCheckConfig{Enabled: &off}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + }}, + }, + { + name: "a disabled versions block leaves the check out", + cfg: &configuration.MiseConfig{Versions: &configuration.MiseVersionsCheckConfig{Enabled: &off, ForbiddenVersions: []string{"latest"}}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + }}, + }, + { + name: "requireChecksums false turns it off", + cfg: &configuration.MiseConfig{Lockfile: &configuration.MiseLockfileCheckConfig{RequireChecksums: &off}}, + want: map[string]any{"mise": map[string]any{ + "required": false, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + "lockfile": map[string]any{ + "requireChecksums": false, + "requireProvenance": []string{}, + "trustedProvenance": []string{"slsa", "github-attestations", "cosign", "minisign"}, + "requiredPlatforms": []string{}, + }, + }}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := packageManagersEngineConfig(tc.cfg) + if tc.want == nil { + if got != nil { + t.Errorf("got %v, want nil", got) + } + return + } + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("got %#v\nwant %#v", got, tc.want) + } + }) + } +} + +func TestSkipFilterWithMise(t *testing.T) { + off := false + cases := []struct { + name string + mise *configuration.MiseConfig + want []string + }{ + {name: "a missing mise block skips the control", mise: nil, want: []string{"x", controlMiseEnPlace}}, + {name: "a disabled mise block skips the control", mise: &configuration.MiseConfig{Enabled: &off}, want: []string{"x", controlMiseEnPlace}}, + {name: "an enabled mise block keeps the filter", mise: &configuration.MiseConfig{}, want: []string{"x"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := skipFilterWithMise([]string{"x"}, &configuration.PlumberConfig{Mise: tc.mise}) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("got %v, want %v", got, tc.want) + } + }) + } +} + +func TestRunControls(t *testing.T) { + off := false + cases := []struct { + name string + provider string + mise *configuration.MiseConfig + wantSkipped bool + }{ + {name: "gitlab, missing mise block", provider: configuration.ProviderGitLab, mise: nil, wantSkipped: true}, + {name: "gitlab, disabled mise block", provider: configuration.ProviderGitLab, mise: &configuration.MiseConfig{Enabled: &off}, wantSkipped: true}, + {name: "gitlab, mise on", provider: configuration.ProviderGitLab, mise: &configuration.MiseConfig{}}, + {name: "github, missing mise block", provider: configuration.ProviderGitHub, mise: nil, wantSkipped: true}, + {name: "github, mise on", provider: configuration.ProviderGitHub, mise: &configuration.MiseConfig{}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + pc := &configuration.PlumberConfig{Mise: tc.mise} + providerList := GitLabControls(pc) + if tc.provider == configuration.ProviderGitHub { + providerList = GitHubControls(pc) + } + got := RunControls(pc, tc.provider) + if len(got) != len(providerList)+1 { + t.Fatalf("len = %d, want the %d provider controls plus mise", len(got), len(providerList)) + } + if !reflect.DeepEqual(got[:len(providerList)], providerList) { + t.Errorf("the provider controls must come first, unchanged") + } + last := got[len(got)-1] + if last.ControlName != controlMiseEnPlace || last.Skipped != tc.wantSkipped { + t.Errorf("last entry = %+v, want %s with Skipped=%v", last, controlMiseEnPlace, tc.wantSkipped) + } + }) + } +} + +func TestTrackedFiles(t *testing.T) { + cases := []struct { + name string + git bool + paths []string + want []string + }{ + { + name: "only the files git tracks are kept", + git: true, + paths: []string{"mise.local.toml", "svc/mise.local.toml"}, + want: []string{"mise.local.toml"}, + }, + { + name: "outside a git repository every file is kept", + paths: []string{"mise.local.toml", "svc/mise.local.toml"}, + want: []string{"mise.local.toml", "svc/mise.local.toml"}, + }, + {name: "no file, no git call", git: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + for _, rel := range []string{"mise.local.toml", "svc/mise.local.toml"} { + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("[tools]\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if tc.git { + for _, args := range [][]string{{"init", "-q"}, {"add", "mise.local.toml"}} { + cmd := exec.Command("git", args...) + cmd.Dir = root + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v %s", args, err, out) + } + } + } + if got := trackedFiles(root, tc.paths); !reflect.DeepEqual(got, tc.want) { + t.Errorf("trackedFiles = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/control/phrases.go b/control/phrases.go index 6a4d2a91..37b8d05d 100644 --- a/control/phrases.go +++ b/control/phrases.go @@ -1211,60 +1211,79 @@ var findingFixes = map[ErrorCode]string{ CodeImageNotPinnedByDigest: "pin the image by digest", CodeActionUnauthorizedSource: untrustedActionFix("action"), // Every other code that never anchors a path, as something to do. - "ISSUE-201": "protect the variable", - "ISSUE-202": "mask the variable", - "ISSUE-203": "turn off the CI debug trace", - "ISSUE-205": "stop overriding the controlled variable in the job", - "ISSUE-208": "stop re-enabling the deprecated workflow commands", - "ISSUE-210": "gate on a check the actor cannot spoof", - "ISSUE-211": "fix the if: condition", - "ISSUE-212": "fix the contains() call", - "ISSUE-214": "pin the package version or install from a lockfile", - "ISSUE-215": "pass the value through an environment variable", - "ISSUE-302": "forward only the secrets the called workflow needs", - "ISSUE-303": "read the secret by name, not through fromJSON", - "ISSUE-305": "gate the job with a protected environment", - "ISSUE-306": "let the app token be revoked when the job ends", - "ISSUE-307": "set persist-credentials: false on the checkout", - "ISSUE-308": "read the secret by its name, not by a computed index", - "ISSUE-309": "pass only the secrets the step needs, by name", - "ISSUE-310": "set persist-credentials: false before uploading the workspace", - "ISSUE-401": "replace the hard-coded job with the shared template", - "ISSUE-403": "update the template to its current version", - "ISSUE-405": "include the required template", - "ISSUE-406": "stop overriding the required template", - "ISSUE-408": "include the required component", - "ISSUE-409": "stop overriding the required component", - "ISSUE-410": "restore the security job's settings", - "ISSUE-412": "drop the Docker-in-Docker service, or isolate it", - "ISSUE-413": "turn on TLS for the Docker-in-Docker daemon", - "ISSUE-417": "add the required action or reusable workflow", - "ISSUE-418": "add a concurrency block", - "ISSUE-419": "replace the misfeature pattern", - "ISSUE-420": "remove the hidden characters from the script", - "ISSUE-421": "publish through OIDC trusted publishing", - "ISSUE-422": "give the workflow a name", - "ISSUE-423": "fix the workflow file so GitHub can read it", - "ISSUE-502": "require more approvals on merge requests", - "ISSUE-503": "fix the merge request approval settings", - "ISSUE-504": "cover every protected branch with an approval rule", - "ISSUE-506": "fix the merge request settings", - "ISSUE-510": "protect the tag pattern", - "ISSUE-601": "link the security policy project", - "ISSUE-702": "replace the archived action", - "ISSUE-704": "move the registry password into a secret", - "ISSUE-706": "pin the Dockerfile base image by digest", - "ISSUE-708": "make the version comment match the SHA", - "ISSUE-709": "move the pin to the latest release", - "ISSUE-711": "replace the action with the runner's built-in tool", - "ISSUE-712": "sign what the workflow publishes", - "ISSUE-801": "declare a permissions block with only what the job needs", - "ISSUE-803": "narrow the permissions to what the job needs", - "ISSUE-901": "turn off insecure external code execution in Dependabot", - "ISSUE-902": "add a cooldown to the Dependabot ecosystem", - "ISSUE-903": "add a dependency update tool (Dependabot or Renovate)", - "ISSUE-904": "run a static analysis scanner in CI", - "ISSUE-905": "add a SECURITY.md policy file", + "ISSUE-201": "protect the variable", + "ISSUE-202": "mask the variable", + "ISSUE-203": "turn off the CI debug trace", + "ISSUE-205": "stop overriding the controlled variable in the job", + "ISSUE-208": "stop re-enabling the deprecated workflow commands", + "ISSUE-210": "gate on a check the actor cannot spoof", + "ISSUE-211": "fix the if: condition", + "ISSUE-212": "fix the contains() call", + "ISSUE-214": "pin the package version or install from a lockfile", + "ISSUE-215": "pass the value through an environment variable", + "ISSUE-302": "forward only the secrets the called workflow needs", + "ISSUE-303": "read the secret by name, not through fromJSON", + "ISSUE-305": "gate the job with a protected environment", + "ISSUE-306": "let the app token be revoked when the job ends", + "ISSUE-307": "set persist-credentials: false on the checkout", + "ISSUE-308": "read the secret by its name, not by a computed index", + "ISSUE-309": "pass only the secrets the step needs, by name", + "ISSUE-310": "set persist-credentials: false before uploading the workspace", + "ISSUE-401": "replace the hard-coded job with the shared template", + "ISSUE-403": "update the template to its current version", + "ISSUE-405": "include the required template", + "ISSUE-406": "stop overriding the required template", + "ISSUE-408": "include the required component", + "ISSUE-409": "stop overriding the required component", + "ISSUE-410": "restore the security job's settings", + "ISSUE-412": "drop the Docker-in-Docker service, or isolate it", + "ISSUE-413": "turn on TLS for the Docker-in-Docker daemon", + "ISSUE-417": "add the required action or reusable workflow", + "ISSUE-418": "add a concurrency block", + "ISSUE-419": "replace the misfeature pattern", + "ISSUE-420": "remove the hidden characters from the script", + "ISSUE-421": "publish through OIDC trusted publishing", + "ISSUE-422": "give the workflow a name", + "ISSUE-423": "fix the workflow file so GitHub can read it", + "ISSUE-502": "require more approvals on merge requests", + "ISSUE-503": "fix the merge request approval settings", + "ISSUE-504": "cover every protected branch with an approval rule", + "ISSUE-506": "fix the merge request settings", + "ISSUE-510": "protect the tag pattern", + "ISSUE-601": "link the security policy project", + "ISSUE-702": "replace the archived action", + "ISSUE-704": "move the registry password into a secret", + "ISSUE-706": "pin the Dockerfile base image by digest", + "ISSUE-708": "make the version comment match the SHA", + "ISSUE-709": "move the pin to the latest release", + "ISSUE-711": "replace the action with the runner's built-in tool", + "ISSUE-712": "sign what the workflow publishes", + "ISSUE-801": "declare a permissions block with only what the job needs", + "ISSUE-803": "narrow the permissions to what the job needs", + "ISSUE-901": "turn off insecure external code execution in Dependabot", + "ISSUE-902": "add a cooldown to the Dependabot ecosystem", + "ISSUE-903": "add a dependency update tool (Dependabot or Renovate)", + "ISSUE-904": "run a static analysis scanner in CI", + "ISSUE-905": "add a SECURITY.md policy file", + "ISSUE-1001": "commit the mise lockfile", + "ISSUE-1002": "turn mise lockfiles back on", + "ISSUE-1003": "run mise lock and commit the lockfile", + "ISSUE-1004": "lock the tool with a checksum", + "ISSUE-1005": "lock the tool with a trusted provenance", + "ISSUE-1006": "lock the tool with its provenance", + "ISSUE-1007": "lock the tool for every required platform", + "ISSUE-1008": "upgrade the mise lockfile format", + "ISSUE-1009": "move the tool from .tool-versions to mise.toml", + "ISSUE-1010": "declare the tools in a mise.toml", + "ISSUE-1011": "pin the tool to an exact version", + "ISSUE-1012": "write the version as a quoted literal", + "ISSUE-1013": "install the tool from a trusted backend", + "ISSUE-1014": "lock the tool from a trusted registry", + "ISSUE-1015": "remove the URL replacement, or trust its target", + "ISSUE-1016": "let the backend fetch from its own source", + "ISSUE-1017": "declare the required tasks", + "ISSUE-1018": "lock the tool with its download URL and checksum", + "ISSUE-1019": "move the local config into mise.toml and stop committing it", } // FindingFixFor is the fix of a finding of code read on its own, from diff --git a/control/platform_call_inventory_test.go b/control/platform_call_inventory_test.go index c304ac0c..921e262e 100644 --- a/control/platform_call_inventory_test.go +++ b/control/platform_call_inventory_test.go @@ -70,6 +70,29 @@ type gitlabRecorder struct { // invalidCI makes GitLab's CI lint answer INVALID with an error for the // project's own configuration (the file exists but does not validate). invalidCI bool + // noCI answers 404 for the project's CI file: a project without one. + noCI bool + // resetOn is a ledger label ("GET /api/v4/projects/:id") whose request + // gets its connection reset: a network failure, which the run reports + // as degraded data rather than an error. + resetOn string +} + +// reset resets the connection of a request recorded as label when it is +// resetOn, and reports whether it did. +func (g *gitlabRecorder) reset(w http.ResponseWriter, label string) bool { + if g.resetOn == "" || label != g.resetOn { + return false + } + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + panic(err) + } + if tcp, ok := conn.(*net.TCPConn); ok { + _ = tcp.SetLinger(0) // close with RST: "connection reset by peer" + } + _ = conn.Close() + return true } // jsonOrEmptyList returns body, or `[]` when it is empty. @@ -149,6 +172,9 @@ func (g *gitlabRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } g.record("POST /api/graphql " + op) + if g.reset(w, "POST /api/graphql "+op) { + return + } g.graphql(w, op, body.Variables) return } @@ -158,13 +184,16 @@ func (g *gitlabRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { normalized = encodedPath.ReplaceAllString(normalized, "/:id") normalized = numericID.ReplaceAllString(normalized, "/:id$1") g.record(r.Method + " " + normalized) + if g.reset(w, r.Method+" "+normalized) { + return + } w.Header().Set("Content-Type", "application/json") switch { case strings.HasSuffix(path, "/repository/commits"): _, _ = fmt.Fprintf(w, `[{"id":%q}]`, g.sha) case strings.Contains(path, "/repository/files/"): - if g.noCIFile { + if g.noCI || g.noCIFile { w.WriteHeader(http.StatusNotFound) _, _ = w.Write([]byte(`{"message":"404 File Not Found"}`)) return @@ -192,6 +221,11 @@ func (g *gitlabRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"message":"403 Forbidden"}`)) return } + if g.noCI && strings.HasSuffix(path, "/repository/branches/main") { + // A missing CI file sends the run to check the branch exists. + _, _ = w.Write([]byte(`{"name":"main"}`)) + return + } // Single-ref probes (ref-confusion): "not that kind of ref". w.WriteHeader(http.StatusNotFound) _, _ = w.Write([]byte(`{"message":"404 Not Found"}`)) diff --git a/control/policy_failure_gitlab_test.go b/control/policy_failure_gitlab_test.go index f53e4b66..d668e907 100644 --- a/control/policy_failure_gitlab_test.go +++ b/control/policy_failure_gitlab_test.go @@ -34,7 +34,7 @@ func TestRunRegoEngine_FailingPolicyDegradesTheRun(t *testing.T) { }}}} project := &gitlab.Project{DefaultBranch: "main"} result := &AnalysisResult{CiValid: true} - runRegoEngine(logrus.NewEntry(logrus.New()), conf, project, nil, nil, nil, nil, nil, nil, nil, result) + _, _ = runRegoEngine(logrus.NewEntry(logrus.New()), conf, project, nil, nil, nil, nil, nil, nil, nil, result) if !result.DataCollectionDegraded || !strings.Contains(strings.Join(result.DegradedReasons, "|"), "brokengl") { t.Fatalf("a failing policy must degrade the GitLab run naming the module, got degraded=%v reasons=%v", result.DataCollectionDegraded, result.DegradedReasons) diff --git a/control/task.go b/control/task.go index 0216d7f4..3a225d21 100644 --- a/control/task.go +++ b/control/task.go @@ -12,6 +12,7 @@ import ( "github.com/getplumber/plumber/gitlab" opaengine "github.com/getplumber/plumber/internal/engine/opa" "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/internal/repofs" "github.com/getplumber/plumber/policies" "github.com/getplumber/plumber/utils" "github.com/sirupsen/logrus" @@ -432,6 +433,18 @@ func collectGitLabTagProtection(l *logrus.Entry, conf *configuration.Configurati return tagData } +// gitlabCheckoutIsAnalyzed reports whether the local checkout holds the +// analyzed project at the analyzed ref, so files can be read from disk: +// a plain local run (no --branch), or a platform run whose checkout is at +// the analyzed ref. --branch in a local run names another ref, which the +// working tree does not hold. +func gitlabCheckoutIsAnalyzed(conf *configuration.Configuration) bool { + useCheckoutInPlatformMode := conf.PlatformRun.Engaged() && + conf.CheckoutIsAnalyzedProject && + gitlab.CheckoutIsAtRef(conf.Branch) + return useCheckoutInPlatformMode || (conf.Branch == "" && conf.IsLocalProject) +} + // attachMemberQuotaOnly is what an early return (a limited analysis, a failed // image collection) leaves of the member quota control: its collected data on // the result and its own finding, nothing else. The control reads the member @@ -531,7 +544,8 @@ func (r *AnalysisResult) DecidedOffPipeline(controlName string) bool { // legacy Go controls always run and remain authoritative until parity // is reached (see phases 2+). On any failure the returned slice is nil // and the error is logged at Warn level so the overall analysis still -// completes. +// completes. The one error returned is a mise file that cannot be read +// (scanPackageManagers), which stops the run. func runRegoEngine( l *logrus.Entry, conf *configuration.Configuration, @@ -544,7 +558,7 @@ func runRegoEngine( tagData *gitlab.GitlabTagProtectionData, membersData *gitlab.GitlabMembersAnalysisData, result *AnalysisResult, -) []opaengine.Finding { +) ([]opaengine.Finding, error) { pipeline := gitlab.ToNormalizedPipeline( conf.ProjectPath, project.DefaultBranch, @@ -559,6 +573,16 @@ func runRegoEngine( applyGitLabVisibility(pipeline, project) applyGitLabRegistryHost(pipeline, project, conf.GitlabURL) pipeline.TagProtection = gitlab.BuildTagProtection(tagData) + // The checkout holds the analyzed ref: read it from disk. Otherwise + // read the project at the analyzed commit through the API. + src := packageSource{root: conf.GitRepoRoot} + if !gitlabCheckoutIsAnalyzed(conf) { + ref := gitlabMiseRef(project, result) + src = packageSource{remote: func() (repofs.Source, error) { return newGitLabRemoteFiles(conf, ref) }} + } + if err := scanPackageManagers(pipeline, conf, src); err != nil { + return nil, err + } // Retained so a later per-policy evaluation can re-run the rules over the // SAME collected data under a different policy's parameters, without // re-collecting anything from the git host. @@ -568,7 +592,7 @@ func runRegoEngine( findings, failures := evaluatePolicies(l, conf, "gitlab", pipeline) applyPolicyFailures(result, failures) attachSituation(l, conf, "gitlab", pipeline, result) - return findings + return findings, nil } // attachSituation runs the situation facts module on pipeline with the same @@ -584,7 +608,7 @@ func attachSituation(l *logrus.Entry, conf *configuration.Configuration, provide controls := conf.PlumberConfig.ControlsFor(provider) ctx, cancel := context.WithTimeout(context.Background(), opaEvaluateTimeout) defer cancel() - sit, err := EvaluateSituation(ctx, pipeline, buildEngineConfig(controls, conf.GitlabURL)) + sit, err := EvaluateSituation(ctx, pipeline, engineConfigFor(conf.PlumberConfig, controls, conf.GitlabURL)) result.Situation = sit // A finding on a job no outsider can make run anchors no path: it is // priced as an individual finding, downgraded, with the note. @@ -635,7 +659,7 @@ func evaluatePolicies(l *logrus.Entry, conf *configuration.Configuration, provid controls := conf.PlumberConfig.ControlsFor(provider) ctx, cancel := context.WithTimeout(context.Background(), opaEvaluateTimeout) defer cancel() - engineCfg := buildEngineConfig(controls, conf.GitlabURL) + engineCfg := engineConfigFor(conf.PlumberConfig, controls, conf.GitlabURL) omitUnreadMergeGates(engineCfg, pipeline) findings, failed, err := engine.EvaluateModules(ctx, pipeline, engineCfg) if err != nil { @@ -645,10 +669,11 @@ func evaluatePolicies(l *logrus.Entry, conf *configuration.Configuration, provid l.WithError(err).Error("Rego/OPA engine evaluation failed") return empty, []policyFailure{{Module: "engine", Err: err}} } + skipControls := skipFilterWithMise(conf.SkipControlsFilter, conf.PlumberConfig) var failures []policyFailure for _, f := range failed { source, _ := engine.ModuleSource(f.Module) - affected := activeControls(controlsDeclaredBy([]byte(source)), provider, controls, conf.ControlsFilter, conf.SkipControlsFilter) + affected := activeControls(controlsDeclaredBy([]byte(source)), provider, controls, conf.ControlsFilter, skipControls) if len(affected) == 0 { // The failure touches no control this run evaluates (disabled, // filtered out, benched, or not this provider's): the same rule @@ -660,7 +685,7 @@ func evaluatePolicies(l *logrus.Entry, conf *configuration.Configuration, provid l.WithError(f.Err).WithField("policy", f.Module).Error("Policy failed to evaluate; its controls are not evaluable this run") failures = append(failures, policyFailure{Module: f.Module, Err: f.Err, Controls: affected}) } - findings = FilterFindingsByEnabledControls(findings, provider, controls, conf.ControlsFilter, conf.SkipControlsFilter) + findings = FilterFindingsByEnabledControls(findings, provider, controls, conf.ControlsFilter, skipControls) // A nested finding closes on the nested fix, not on the direct // remediation of a reference the user cannot edit (spec section 6, // maintainer review of PR 549): rewritten once here, every output @@ -1107,6 +1132,7 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { l.WithError(err).Warn("Project information fetch failed (network); reporting incomplete data") markDegraded(result, "project information could not be fetched (network or timeout)") result.CiValid = false + markPackageManagersGap(result, conf.PlumberConfig) return result, nil } l.WithError(err).Error("Failed to fetch project from GitLab") @@ -1210,10 +1236,7 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { // taken when the checkout genuinely holds the analyzed ref // (CheckoutIsAtRef): a working tree at a different branch parses just as // cleanly and would be silently wrong. - useCheckoutInPlatformMode := conf.PlatformRun.Engaged() && - conf.CheckoutIsAnalyzedProject && - gitlab.CheckoutIsAtRef(conf.Branch) - if useCheckoutInPlatformMode || (conf.Branch == "" && conf.IsLocalProject) { + if gitlabCheckoutIsAnalyzed(conf) { localCIPath, cErr := gitlab.ResolveWithinRepo(conf.GitRepoRoot, project.CiConfPath) if cErr != nil { l.WithFields(logrus.Fields{ @@ -1265,6 +1288,7 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { l.WithError(err).Warn("Pipeline Origin data collection failed (network); reporting incomplete data") markDegraded(result, "pipeline configuration could not be fetched (network or timeout)") result.CiValid = false + markPackageManagersGap(result, conf.PlumberConfig) return result, nil } l.WithError(err).Error("Pipeline Origin data collection failed") @@ -1368,10 +1392,12 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { // If limited analysis (CI invalid or missing), return early // Note: when using local CI config, errors are returned directly by the - // collector (hard fail) and won't reach this point. + // collector (hard fail) and won't reach this point. The mise files were + // not read either: mise-en-place reports not evaluated, never passed. if pipelineOriginData.LimitedAnalysis { l.Info("Limited analysis due to CI configuration errors") attachMemberQuotaOnly(l, conf, project, membersData, result) + markPackageManagersGap(result, conf.PlumberConfig) return result, nil } @@ -1389,6 +1415,7 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { markDegraded(result, "pipeline image/variable data could not be fetched (network or timeout)") result.CiValid = false attachMemberQuotaOnly(l, conf, project, membersData, result) + markPackageManagersGap(result, conf.PlumberConfig) return result, nil } l.WithError(err).Error("Pipeline Image data collection failed") @@ -1518,7 +1545,11 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { // Rego/OPA rule engine evaluation — the single authoritative // compliance path (the legacy Go controls were retired in // docs/REFACTOR_MULTI_PROVIDER.md §8 Phase A). - result.Findings = runRegoEngine(l, conf, project, pipelineOriginData, pipelineImageData, protectionData, variablesData, securityPolicyData, tagData, membersData, result) + findings, err := runRegoEngine(l, conf, project, pipelineOriginData, pipelineImageData, protectionData, variablesData, securityPolicyData, tagData, membersData, result) + if err != nil { + return nil, err + } + result.Findings = findings result.ProtectionData = protectionData // An approval-rule control that ran but saw zero rules is the ambiguous // GitLab-Free-vs-premium-with-no-rules case (the approvals API 200-empties @@ -1561,6 +1592,7 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { // Runs after the findings above exist: the mark depends on whether the // control reports a deviation. markMergeGatesGap(result, conf) + markPackageManagersGap(result, conf.PlumberConfig) markPlatformLaneGaps(result, conf) diff --git a/control/task_github.go b/control/task_github.go index 8d9d8196..9bb30bc5 100644 --- a/control/task_github.go +++ b/control/task_github.go @@ -8,6 +8,7 @@ import ( "github.com/getplumber/plumber/configuration" githubpkg "github.com/getplumber/plumber/github" "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/internal/repofs" "github.com/getplumber/plumber/utils" "github.com/sirupsen/logrus" ) @@ -622,6 +623,9 @@ func RunGitHubAnalysis(conf *configuration.Configuration) (*AnalysisResult, erro if defaultBranch == "" { defaultBranch = conf.Branch } + if err := scanPackageManagers(pipeline, conf, packageSource{root: conf.GitRepoRoot}); err != nil { + return nil, err + } findings, policyFailures := evaluatePolicies(l, conf, "github", pipeline) result := &AnalysisResult{ ProjectPath: conf.ProjectPath, @@ -653,6 +657,7 @@ func RunGitHubAnalysis(conf *configuration.Configuration) (*AnalysisResult, erro markDegraded(result, degradedReasonTagProtectionPrefix+"; tag controls were not evaluated") } markTagProtectionGap(result, GitHubControls(conf.PlumberConfig)) + markPackageManagersGap(result, conf.PlumberConfig) applyNestedActions(result, pipeline) // Resolve the local clone's HEAD SHA so source links in the report // point at the exact commit being analysed instead of a mutable @@ -777,6 +782,17 @@ func RunGitHubAnalysisRemote(conf *configuration.Configuration, owner, repo, ref if defaultBranch == "" { defaultBranch = ref } + // The mise files are read at the commit the workflows were read at. + rev := pipeline.RemoteRev + if rev == "" { + rev = ref + } + remoteFiles := packageSource{remote: func() (repofs.Source, error) { + return newGitHubRemoteFiles(conf.GithubAPIHost, owner, repo, rev) + }} + if err := scanPackageManagers(pipeline, conf, remoteFiles); err != nil { + return nil, err + } findings, policyFailures := evaluatePolicies(l, conf, "github", pipeline) result := &AnalysisResult{ ProjectPath: owner + "/" + repo, @@ -804,6 +820,7 @@ func RunGitHubAnalysisRemote(conf *configuration.Configuration, owner, repo, ref markDegraded(result, degradedReasonTagProtectionPrefix+"; tag controls were not evaluated") } markTagProtectionGap(result, GitHubControls(conf.PlumberConfig)) + markPackageManagersGap(result, conf.PlumberConfig) applyNestedActions(result, pipeline) // An enabled control asserting nothing until its substantive fields are set is not a clean // pass either (#459): it is not_evaluable, config_required, same as any other lane gap. Runs diff --git a/control/task_test.go b/control/task_test.go index f651deb3..6cd0bf4c 100644 --- a/control/task_test.go +++ b/control/task_test.go @@ -1,6 +1,69 @@ package control -import "testing" +import ( + "testing" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/platform" +) + +// TestGitlabCheckoutIsAnalyzed guards the gate on reading GitLab files +// (mise files, the local CI file) from the working tree: only when the +// checkout holds the analyzed ref. A local --branch run names another ref, +// so reading the working tree would judge the wrong files. +func TestGitlabCheckoutIsAnalyzed(t *testing.T) { + engaged := &platform.RunContext{Context: &platform.ProjectContext{}} + cases := []struct { + name string + conf configuration.Configuration + ci bool + ciRef string + want bool + }{ + {name: "local run, no branch", conf: configuration.Configuration{IsLocalProject: true}, want: true}, + {name: "local run with --branch", conf: configuration.Configuration{IsLocalProject: true, Branch: "feature"}, want: false}, + {name: "remote run, no platform run", conf: configuration.Configuration{}, want: false}, + { + name: "platform run, checkout at the analyzed ref", + conf: configuration.Configuration{PlatformRun: engaged, CheckoutIsAnalyzedProject: true, Branch: "main"}, + ci: true, + ciRef: "main", + want: true, + }, + { + name: "platform run, checkout at another ref", + conf: configuration.Configuration{PlatformRun: engaged, CheckoutIsAnalyzedProject: true, Branch: "other"}, + ci: true, + ciRef: "main", + want: false, + }, + { + name: "platform run outside CI", + conf: configuration.Configuration{PlatformRun: engaged, CheckoutIsAnalyzedProject: true, Branch: "main"}, + want: false, + }, + { + name: "platform run, checkout of another project", + conf: configuration.Configuration{PlatformRun: engaged, Branch: "main"}, + ci: true, + ciRef: "main", + want: false, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ci := "false" + if tc.ci { + ci = "true" + } + t.Setenv("CI", ci) + t.Setenv("CI_COMMIT_REF_NAME", tc.ciRef) + if got := gitlabCheckoutIsAnalyzed(&tc.conf); got != tc.want { + t.Errorf("gitlabCheckoutIsAnalyzed = %v, want %v", got, tc.want) + } + }) + } +} func TestGitlabInstanceHost(t *testing.T) { cases := []struct { diff --git a/control/testmain_test.go b/control/testmain_test.go index 1ce8a522..332d7390 100644 --- a/control/testmain_test.go +++ b/control/testmain_test.go @@ -1,16 +1,35 @@ package control import ( + "context" "os" "testing" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/repofs" ) // TestMain disables the collector's GitHub API metadata enrichment // globally for the control package's tests. See the matching file -// under policies/ for the rationale. +// under policies/ for the rationale. A remote run reads the mise files +// of an empty repository unless a test swaps in its own (the default +// configuration turns mise on, and the test servers serve no tree). func TestMain(m *testing.M) { if err := os.Setenv("PLUMBER_DISABLE_GITHUB_API", "1"); err != nil { panic(err) } + newGitHubRemoteFiles = func(string, string, string, string) (repofs.Source, error) { return emptyRepo{}, nil } + newGitLabRemoteFiles = func(*configuration.Configuration, string) (repofs.Source, error) { return emptyRepo{}, nil } os.Exit(m.Run()) } + +// emptyRepo is a remote repository with no file. +type emptyRepo struct{} + +func (emptyRepo) List(context.Context) ([]repofs.Entry, error) { + return nil, nil +} + +func (emptyRepo) Read(context.Context, []string) (map[string]repofs.Blob, error) { + return map[string]repofs.Blob{}, nil +} diff --git a/control/types.go b/control/types.go index 67803108..eafd8ade 100644 --- a/control/types.go +++ b/control/types.go @@ -328,6 +328,11 @@ type GitHubAnalysisStats struct { VariableBindingsTotal int DebugTraceFound int + // Package managers (10xx, mise): the mise configs and the tool + // requests they declare, the denominators of the stats block. + MiseConfigsTotal int + MiseToolsTotal int + // Reusable workflow secrets (ISSUE-302). ReusableCalls int ReusableCallsSecretsInherit int diff --git a/defaultConfig/.plumber.yaml b/defaultConfig/.plumber.yaml index cab552ee..5a5e6e1e 100644 --- a/defaultConfig/.plumber.yaml +++ b/defaultConfig/.plumber.yaml @@ -1409,6 +1409,104 @@ github: - ACTIONS_STEP_DEBUG - ACTIONS_RUNNER_DEBUG +# ============================================================================ +# mise (mise-en-place) +# ============================================================================ +# Top level, like gitlab and github: mise does not depend on the provider, +# the same block applies to a GitHub or a GitLab repository. It drives the +# mise-en-place control. Remove the block, or set +# `enabled: false`, and nothing is scanned or reported. A check whose +# block (lockfile, versions, sources, tasks) is absent does not run. +# +# The files are read from the local checkout. A run without one (a remote +# --project run) reports the control as not evaluated. +# +# Best practice: commit mise.lock with a checksum for every download, and +# install with `mise install --locked` in CI. +mise: + # Set to false to disable every mise check + enabled: true + # Set to true to report a repository that commits no mise config + # (ISSUE-1010). A .tool-versions file alone does not count. + required: false + # Every mise config that declares tools has its lockfile committed + # (mise.toml -> mise.lock, mise..toml -> mise..lock), every tool + # request has a matching lock entry, and every locked download carries a + # checksum. A request Plumber cannot read statically (a template) or a + # format 0 lockfile is reported as not locked. A mise file that cannot + # be read or parsed stops the run with an error listing every such + # file. + lockfile: + enabled: true + requireChecksums: true + # Backends whose locked downloads must record a provenance + # (SLSA, cosign, minisign, GitHub attestations), globs allowed. + # requireProvenance: ["aqua:*"] + # Provenance kinds a locked download may record; any other kind is + # reported. Defaults to every kind mise records. + # trustedProvenance: [slsa, github-attestations, cosign, minisign] + # Platforms every tool that locks downloads must lock. + # requiredPlatforms: [linux-x64, linux-arm64] + # Oldest accepted lockfile_version. + # minimumLockfileVersion: 1 + # No tool request in a mise config uses a forbidden version (globs). + # The request as written is what people review: with `latest`, the + # lockfile pins a version, but `mise lock --bump` or `mise upgrade` moves + # it with no change in mise.toml (ISSUE-1011). A request Plumber cannot + # read statically (a template) is ISSUE-1012. A bare major such as "24" is + # not caught by this list. "ref:*" is left out: a ref pinned to a commit + # SHA cannot move. Add it to forbid every git ref. + versions: + enabled: true + forbiddenVersions: + - latest + - lts + - "lts/*" + - "lts-*" + - stable + - nightly + - beta + - "branch:*" + - "path:*" + - system + - "sub-*" + - "prefix:*" + # Where tools are fetched from. Off by default: write the block to turn + # it on. Globs allowed in every list. + # trustedTools: the tools that may be installed, by full mise name + # (`aqua:jqlang/jq`; a shorthand such as `terraform` takes the + # backend its mise.lock entry records, and with no entry it is + # reported). ISSUE-1013. + # trustedRegistries: the download URLs mise.lock may record, the ones + # `mise install --locked` downloads. Leave it out and they are not + # checked; [] trusts none. ISSUE-1014. + # trustedReplacement: where [settings] url_replacements may send + # downloads. Absent or [] trusts none. ISSUE-1015. + # trustedOptions: the URLs a tool option may set (api_url, url, + # platforms.

.url, pip indexes). Absent or [] trusts none. + # ISSUE-1016. + # sources: + # enabled: true + # trustedTools: ["core:*", "aqua:*", "github:my-org/*"] + # trustedRegistries: ["https://github.com/*", "https://nodejs.org/*"] + # trustedReplacement: [] + # trustedOptions: [] + # Every mise project (a directory holding a mise config) declares the + # tasks CI is expected to run, as `mise run` sees them there (its own, + # its task directories', its parents'). Off by default. `required` is a + # list; each entry matches a task name or alias, globs allowed. A project + # missing any of them is ISSUE-1017. + # tasks: + # enabled: true + # required: [lint, test] + # Tool keys exempted from every mise check, globs allowed. + exemptPackages: [] + # Repository paths whose mise files are not checked, for example + # fixtures ("examples/**", "testdata/**"). A file there that cannot be + # read does not stop the run. `*` stays within a directory, `**` + # crosses directories. + exemptPaths: [] + # =========================================== # Pipeline capabilities # =========================================== diff --git a/docs/FINGERPRINT.md b/docs/FINGERPRINT.md index f04839b9..ce992098 100644 --- a/docs/FINGERPRINT.md +++ b/docs/FINGERPRINT.md @@ -263,7 +263,7 @@ where the finding has no sub-finding subject: | `ecosystem` (the dependabot ecosystem) | ISSUE-901, ISSUE-902 | | `{file, job}` (one finding per job) | ISSUE-207, ISSUE-208, ISSUE-213, ISSUE-214, ISSUE-215, ISSUE-303, ISSUE-305, ISSUE-308, ISSUE-309, ISSUE-419, ISSUE-420, ISSUE-704, ISSUE-712, ISSUE-801, ISSUE-802, ISSUE-803 | | `{file}` (one finding per workflow file) | ISSUE-418, ISSUE-422, ISSUE-423 | -| `{}` (one finding per repository) | ISSUE-601, ISSUE-903, ISSUE-904, ISSUE-905 | +| `{}` (one finding per repository) | ISSUE-601, ISSUE-903, ISSUE-904, ISSUE-905, ISSUE-1010 | Rewording any rule's prose no longer re-keys a registered finding. @@ -318,7 +318,7 @@ complete identity; two `write-all` jobs in different workflows differ on `file`. `identity.Of` reports `SubjectFromMessage == false`, and rewording the rule's message does not move the fingerprint. Coarser variants exist for findings that are one per file (`{file}`: ISSUE-418, ISSUE-422, ISSUE-423) or one per -repository (the `{}` singleton: ISSUE-601, ISSUE-903, ISSUE-904, ISSUE-905). +repository (the `{}` singleton: ISSUE-601, ISSUE-903, ISSUE-904, ISSUE-905, ISSUE-1010). Moving a rule from prose onto a structured payload changes its declaration and re-keys its findings once. Recipe version 2 did this for eleven finding blocks diff --git a/docs/GITHUB_ISSUES.md b/docs/GITHUB_ISSUES.md index 37041ef7..84275efa 100644 --- a/docs/GITHUB_ISSUES.md +++ b/docs/GITHUB_ISSUES.md @@ -90,6 +90,30 @@ reading the upstream docs. | [ISSUE-904](#issue-904--sast-workflow-missing) | `sast-workflow-missing` | low | | [ISSUE-905](#issue-905--security-policy-missing) | `security-policy-missing` | low | +### Package managers and lockfiles — `10xx` (mise) + +| Code | Name | Severity | +| :--- | :--- | :--- | +| [ISSUE-1001](#issue-10xx--mise-en-place) | `mise-lockfile-missing` | high | +| [ISSUE-1002](#issue-10xx--mise-en-place) | `mise-lockfile-disabled` | high | +| [ISSUE-1003](#issue-10xx--mise-en-place) | `mise-tool-not-locked` | high | +| [ISSUE-1004](#issue-10xx--mise-en-place) | `mise-checksum-missing` | high | +| [ISSUE-1005](#issue-10xx--mise-en-place) | `mise-provenance-untrusted` | medium | +| [ISSUE-1006](#issue-10xx--mise-en-place) | `mise-provenance-missing` | medium | +| [ISSUE-1007](#issue-10xx--mise-en-place) | `mise-platform-not-locked` | low | +| [ISSUE-1008](#issue-10xx--mise-en-place) | `mise-lockfile-outdated-format` | low | +| [ISSUE-1009](#issue-10xx--mise-en-place) | `mise-tool-versions-unlocked` | medium | +| [ISSUE-1010](#issue-10xx--mise-en-place) | `mise-missing` | medium | +| [ISSUE-1011](#issue-1011-and-issue-1012--mise-versions) | `mise-version-forbidden` | high | +| [ISSUE-1012](#issue-1011-and-issue-1012--mise-versions) | `mise-version-unreadable` | high | +| [ISSUE-1013](#issue-1013-to-issue-1016--mise-sources) | `mise-tool-untrusted` | high | +| [ISSUE-1014](#issue-1013-to-issue-1016--mise-sources) | `mise-registry-untrusted` | high | +| [ISSUE-1015](#issue-1013-to-issue-1016--mise-sources) | `mise-replacement-untrusted` | high | +| [ISSUE-1016](#issue-1013-to-issue-1016--mise-sources) | `mise-option-untrusted` | medium | +| [ISSUE-1018](#issue-10xx--mise-en-place) | `mise-download-not-locked` | high | +| [ISSUE-1019](#issue-10xx--mise-en-place) | `mise-local-config-committed` | high | +| [ISSUE-1017](#issue-1017--mise-tasks-missing) | `mise-tasks-missing` | medium | + ### Run / output conventions - Every finding prints a clickable `↳ at :` — `Ctrl+click` @@ -105,6 +129,330 @@ reading the upstream docs. --- +## ISSUE-10xx — `mise-en-place` + +**Control:** `mise-en-place`, configured by the top-level `mise` block + +Many teams use [mise](https://mise.jdx.dev) to pin the tools their CI +runs (terraform, linters, scanners, runtimes). The workflow then shrinks to +`mise install`, and what CI installs is decided by `mise.toml` and +`mise.lock`. This check reads both files from the local checkout, or, +without one (a remote `--project` run), from the repository at the analyzed +commit through the GitHub or GitLab API. It never runs mise. + +Every committed mise config is checked, in any directory. The walk skips +`.git`, `node_modules`, `vendor`, hidden directories other than `.config` +and `.mise`. A mise local config (`*.local.toml`) that git tracks is +ISSUE-1019; this check does not judge it as a config, but the versions +and sources checks do, since mise loads it. An untracked one, a +developer's own, is not read at all. Each config pairs with the +lockfile next to it (`mise.toml` and `mise.lock`, `mise..toml` and +`mise..lock`, a `conf.d/` fragment and the `mise.lock` of the +directory holding `conf.d/`). When the root config sets +`[monorepo] lockfile = true`, subproject configs pair with the root +lockfiles. + +Codes are numbered in sequence across the control. Each one has a +`subject` in the catalog, so the codes of one check can be filtered +together. + +| Code | Subject | Finding | Severity | +| :--- | :--- | :--- | :--- | +| ISSUE-1001 | lockfile | A config declares `[tools]` but its lockfile is not committed | high | +| ISSUE-1002 | lockfile | A config sets `[settings] lockfile = false` | high | +| ISSUE-1003 | lockfile | A tool request has no lock entry whose `specifiers` contain it | high | +| ISSUE-1004 | lockfile | A locked download has a `url` but no `checksum` (`requireChecksums`) | high | +| ISSUE-1005 | lockfile | A locked download records a `provenance` kind outside `trustedProvenance` | medium | +| ISSUE-1006 | lockfile | A locked download of a backend in `requireProvenance` has no `provenance` | medium | +| ISSUE-1007 | lockfile | A tool that locks downloads misses a platform in `requiredPlatforms` | low | +| ISSUE-1008 | lockfile | `lockfile_version` is below `minimumLockfileVersion` | low | +| ISSUE-1009 | lockfile | A tool is declared in asdf's `.tool-versions` and in no mise config of the same directory | medium | +| ISSUE-1010 | presence | `required: true` and the repository has no mise config | medium | +| ISSUE-1018 | lockfile | A tool is locked with no download data (`requireChecksums`): a binary backend (aqua, github, gitlab, ubi, http) with no platform table, or a platform with neither `url` nor `checksum` | high | +| ISSUE-1019 | lockfile | A mise local config (`mise.local.toml`, `mise..local.toml`, `config.local.toml`, `conf.d/*.local.toml`) is committed; [mise says it must not be](https://mise.jdx.dev/glossary.html#mise-local-toml) | high | + +ISSUE-1003 fails closed. A request Plumber cannot read statically (a +`{{ ... }}` template), an unquoted version (`node = 24`, which mise +itself rejects) and a format 0 lockfile (it records no `specifiers`) +are reported as not locked, never passed. + +A mise file that cannot be read stops the run with an error and no +report: a config or lockfile that is not valid TOML, a file over 2 MiB, +or a symlink that points outside the repository, at a device, or +nowhere. Plumber reads every mise file first, then lists every file that +failed in one error. A symlink that resolves to a file inside the +repository is followed, as mise follows it. Files under `exemptPaths` do +not stop the run, unless a checked config pairs with that lockfile. + +`.tool-versions` is read for ISSUE-1009 only, so only when the lockfile +check runs. An asdf plugin name that mise reads as one of its tools +(`nodejs` for `node`, `golang` for `go`) counts as that tool. +Idiomatic version files (`.nvmrc`, `.node-version`, `.python-version` +and the like), which mise reads only for the tools listed in its +`idiomatic_version_file_enable_tools` setting, are not read. + +`[settings] lockfile = false` applies to every config below it that +does not set `lockfile` itself, as mise applies it. ISSUE-1002 is raised +on the config that sets it. A subproject that inherits it is only +reported itself when that config is under `exemptPaths`. ISSUE-1010 needs `required: true`; a `.tool-versions` file +alone does not count as a mise config. +List the tool in `exemptPackages`, or the path in `exemptPaths` (for +example `examples/**` for fixtures), when the exception is intentional. + +```toml +# ❌ before: mise.toml with no mise.lock committed (ISSUE-1001) +[tools] +terraform = "1.9.8" +``` + +**Fix.** Set `[settings] lockfile = true`, run `mise lock`, commit +`mise.lock`, and install with `mise install --locked` in CI. + +**Remote runs.** Plumber lists the repository tree once (GitHub: one +`git/trees?recursive=1` request; GitLab: the recursive tree, 100 entries a +page), then reads the mise files in batched GraphQL queries of 50 files +(GitLab asks the sizes first, so a file over 2 MiB is never downloaded). +A file only a task include or a symlink reaches is read in a later batch, +up to 4 more. Two cases fall back to one request per file: a GitHub file +whose GraphQL text is truncated or not byte-exact (read over the contents +API), and a GitLab instance that does not answer the `blobs` query (older +than 13.11). An empty repository has no mise file. + +**Not evaluated** when the mise files were not read for the run: a +repository too large to read remotely (a tree GitHub cannot list in full, +over 100,000 entries or 7 MB, or more than 5,000 files to fetch) leaves +the control not evaluated and the run degraded, and a checkout reads it +in full; in platform mode, a policy that turns mise on over a run that did +not read them. The control never passes on data it did not read. An enabled `mise` block with no check block and no +`required: true` reports the control as needing configuration. + +**Config.** `mise` is a top-level key of `.plumber.yaml`, next to `gitlab` +and `github`, because it does not depend on the provider. When the block +is missing or sets `enabled: false`, Plumber reads no mise file and +reports nothing. `requireChecksums` is on unless set to `false`. +`trustedProvenance` defaults to every kind mise records (`slsa`, +`github-attestations`, `cosign`, `minisign`). + +```yaml +version: "2.0" +gitlab: + controls: ... +github: + controls: ... +mise: + enabled: true + required: false # true: a repository with no mise config is ISSUE-1010 + lockfile: + enabled: true + requireChecksums: true + # requireProvenance: ["aqua:*"] + # trustedProvenance: [slsa, github-attestations, cosign, minisign] + # requiredPlatforms: [linux-x64, linux-arm64] + # minimumLockfileVersion: 1 + exemptPackages: [] + exemptPaths: [] # globs: `*` within a directory, `**` across +``` + +--- + +## ISSUE-1011 and ISSUE-1012 — `mise-versions` + +**Severity:** `high` • **Control:** `mise-en-place`, configured by the top-level `mise.versions` block + +A tool request in a mise config matches a pattern of `forbiddenVersions` +(globs). The check reads the request as written in the config, where +people review it. With `latest`, the lockfile still pins a version, but +the next `mise lock --bump`, `mise upgrade` or regenerated lockfile moves +it with no change in `mise.toml`, so nobody reviews the new version. + +| Code | Finding | Severity | +| :--- | :--- | :--- | +| ISSUE-1011 | A tool request matches a pattern of `forbiddenVersions` | high | +| ISSUE-1012 | A tool request cannot be read statically: a `{{ ... }}` template, an empty or unquoted version | high | + +The check covers the same configs as the lockfile check, with or without +a lockfile. It fails closed: a request Plumber cannot read statically +can't be checked against `forbiddenVersions`, so it is ISSUE-1012, never +passed. A mise +config that cannot be parsed stops the run, as for the lockfile check. The +versions check alone reads no lockfile and no `.tool-versions`, so an +unreadable one does not stop it. +`exemptPackages` and `exemptPaths` apply as for the lockfile check. + +```toml +# ❌ before: mise.toml +[tools] +terraform = "latest" +node = "lts" + +# ✅ after +[tools] +terraform = "1.9.8" +node = "24.11.1" +``` + +**Fix.** Write an exact version, run `mise lock`, and commit both files. + +**Config.** The list below is the `plumber:default` one. It does not catch +a bare major such as `node = "24"`, which mise resolves to the newest +`24.x` when it locks. It leaves out `ref:*` on purpose: a ref pinned to a +commit SHA cannot move. Add `"ref:*"` to forbid every git ref, branches +and tags included. + +```yaml +mise: + versions: + enabled: true + forbiddenVersions: [latest, lts, "lts/*", "lts-*", stable, nightly, beta, "branch:*", "path:*", system, "sub-*", "prefix:*"] +``` + +--- + +## ISSUE-1013 to ISSUE-1016 — `mise-sources` + +**Control:** `mise-en-place`, configured by the top-level `mise.sources` block (off unless written) + +Where mise fetches a tool from depends on the tool, the URL its lockfile +records, and any redirect the config sets. This check holds each of them +to a list kept outside the repository. + +| Code | Finding | Severity | +| :--- | :--- | :--- | +| ISSUE-1013 | A tool matches no `trustedTools` pattern | high | +| ISSUE-1014 | A download URL locked in `mise.lock` matches no `trustedRegistries` pattern | high | +| ISSUE-1015 | A `[settings] url_replacements` target matches no `trustedReplacement` pattern | high | +| ISSUE-1016 | A trusted tool sets a URL option that matches no `trustedOptions` pattern | medium | + +**ISSUE-1013.** `trustedTools` is matched against the tool's full mise +name. A tool key with a backend (`aqua:jqlang/jq`, `github:org/repo`) is +its own name. A shorthand (`terraform = "1.9.8"`) is resolved by mise's +registry, so Plumber takes the `backend` its `mise.lock` entry records. +A shorthand with no matching lock entry can't be traced to a backend, and +is never passed. When the lockfile check runs, it reports the missing +entry (ISSUE-1001 or ISSUE-1003), so ISSUE-1013 stays quiet and the gap +is reported once. With the lockfile check off, for a config that sets +`lockfile = false`, or for one whose lockfile is unknown (its root +config is exempt and unreadable), the tool is ISSUE-1013. A committed +`*.local.toml` is judged like any other config. `.tool-versions` is not +judged here: ISSUE-1009 covers it. + +**ISSUE-1014.** Each platform entry of `mise.lock` records the `url` +`mise install --locked` downloads, so a change to `mise.lock` alone can +point a trusted tool at any host. Every recorded URL of a trusted tool +must match `trustedRegistries`. Leave the key out and the URLs are not +checked; `[]` trusts none. + +**ISSUE-1015.** mise sends a download to its `url_replacements` target +first, while `mise.lock` keeps the original URL, so the lockfile alone +does not show it. A replacement set from the pipeline +(`MISE_URL_REPLACEMENTS`) is not read yet. + +**ISSUE-1016** covers `api_url`, which points the github backend at +another host and turns off its attestation checks, `url` and +`platforms..url`, which download that address instead of a +release asset, and the pypi/pipx options `registry_url`, `indexes`, +`pipx_args`, `uvx_args` and the index variables of `install_env`. +For `pipx_args` and `uvx_args`, every URL in the arguments is judged on +its own, whatever flag carries it (`--index-url`, `-i`, `--pip-args`, +...): an argument with no URL, such as `--include-deps`, is not +reported. The `install_env` +variables are pip's, uv's (`UV_INDEX`, `UV_DEFAULT_INDEX`, +`UV_EXTRA_INDEX_URL`, `UV_INDEX_URL`), Go's proxy and checksum database +ones, and npm's registry, scoped ones included. +`asset_pattern` is not reported: it picks an asset of the same release. +Mirror settings such as `go.download_mirror` or `node.mirror_url` are not +read. The locked URL (ISSUE-1014) covers binary backends only: a go, +npm, cargo or pip tool locks no URL. + +A tool that is not trusted gets ISSUE-1013 alone: its URLs and options +are not judged. + +```toml +# ❌ before: mise.toml +[settings.url_replacements] +"https://releases.hashicorp.com/" = "https://mirror.example.com/" # ISSUE-1015 + +[tools] +"github:someone/tool" = "1.2.3" # ISSUE-1013 +"github:my-org/cli" = { version = "2.0.0", api_url = "https://ghe.example.com/api/v3" } # ISSUE-1016 +``` + +**Fix.** Install a trusted tool, drop the replacement or the option, or +add it to the matching list once you have reviewed it. `exemptPackages` +and `exemptPaths` apply as for the other mise checks. A mise file that +cannot be read stops the run. + +**Config.** Off in `plumber:default`: write the block to turn it on. +Patterns are globs, matched case-insensitively. + +```yaml +mise: + sources: + enabled: true + trustedTools: ["core:*", "aqua:*", "github:my-org/*"] + trustedRegistries: ["https://github.com/*", "https://nodejs.org/*"] + trustedReplacement: [] + trustedOptions: ["https://ghe.example.com/*"] +``` + +--- + +## ISSUE-1017 — `mise-tasks-missing` + +**Severity:** `medium` • **Control:** `mise-en-place`, configured by the top-level `mise.tasks` block (off unless written) + +When CI runs `mise run `, the tasks a project declares are the steps +that actually run. This check makes every mise project declare the tasks +the organization expects. + +A mise project is a directory holding a mise config. Its tasks are the +ones `mise run` sees there: +- `[tasks.]` tables of its configs +- TOML task files and executable files of its task directories + (`mise-tasks/`, `.mise-tasks/`, `.mise/tasks/`, `.config/mise/tasks/`, + `mise/tasks/`, or the paths in `task_config.includes`) +- the tasks of every parent directory's configs, which mise makes + available in subdirectories + +A file in a task directory counts only when it is executable, since mise +loads nothing else. File task names follow mise: `mise-tasks/db/migrate.sh` +is `db:migrate`, `mise-tasks/test/_default` is `test`. Include paths can use +`{{ config_root }}` and globs (`*` within a directory, `**` across). +Symlinks are followed only when they resolve inside the repository. + +What `mise run` sees without `MISE_ENV` is what counts: the tasks and +includes of a `mise..toml` are left out, and `[settings]` +`task.disable_paths` and `task.skip` drop the tasks they name. Task files +are only read when this check is on; a TOML task file that cannot be +parsed then stops the run, like any other mise file. + +`required` is a list of tasks. Each entry matches a task name or alias, +globs allowed (`lint:*`). One finding per project that misses any of +them, listing what it misses. + +It fails closed: tasks from a remote include (`git::`, `oci::`, `zip::`), a +templated include, a path outside the repository, or an include too large +to read (over 20,000 files) never satisfy the requirement, and the finding +names those includes. + +```text + MED ISSUE-1017 `svc/api/mise.toml` does not declare the required tasks: missing `test` and `scan` +``` + +**Fix.** Declare the missing tasks (`[tasks.test]` in `mise.toml`, or an +executable `mise-tasks/test`), or list the project's path in +`exemptPaths`. + +**Config.** Off in `plumber:default`: write the block to turn it on. + +```yaml +mise: + tasks: + required: [lint, test, scan] +``` + +--- + ## ISSUE-102 — `image-mutable-tag` **Severity:** `high` • **Control:** `containerImageMustNotUseForbiddenTags` diff --git a/docs/GITLAB_ISSUES.md b/docs/GITLAB_ISSUES.md index 5e251f61..aa0e0d17 100644 --- a/docs/GITLAB_ISSUES.md +++ b/docs/GITLAB_ISSUES.md @@ -22,6 +22,30 @@ absence from this file does not mean a rule doesn't exist — see | :--- | :--- | :--- | | [ISSUE-510](#issue-510--tag-unprotected) | `tag-unprotected` | **critical** | +### Package managers and lockfiles — `10xx` (mise) + +| Code | Name | Severity | +| :--- | :--- | :--- | +| [ISSUE-1001](#issue-10xx--mise-en-place) | `mise-lockfile-missing` | high | +| [ISSUE-1002](#issue-10xx--mise-en-place) | `mise-lockfile-disabled` | high | +| [ISSUE-1003](#issue-10xx--mise-en-place) | `mise-tool-not-locked` | high | +| [ISSUE-1004](#issue-10xx--mise-en-place) | `mise-checksum-missing` | high | +| [ISSUE-1005](#issue-10xx--mise-en-place) | `mise-provenance-untrusted` | medium | +| [ISSUE-1006](#issue-10xx--mise-en-place) | `mise-provenance-missing` | medium | +| [ISSUE-1007](#issue-10xx--mise-en-place) | `mise-platform-not-locked` | low | +| [ISSUE-1008](#issue-10xx--mise-en-place) | `mise-lockfile-outdated-format` | low | +| [ISSUE-1009](#issue-10xx--mise-en-place) | `mise-tool-versions-unlocked` | medium | +| [ISSUE-1010](#issue-10xx--mise-en-place) | `mise-missing` | medium | +| [ISSUE-1011](#issue-1011-and-issue-1012--mise-versions) | `mise-version-forbidden` | high | +| [ISSUE-1012](#issue-1011-and-issue-1012--mise-versions) | `mise-version-unreadable` | high | +| [ISSUE-1013](#issue-1013-to-issue-1016--mise-sources) | `mise-tool-untrusted` | high | +| [ISSUE-1014](#issue-1013-to-issue-1016--mise-sources) | `mise-registry-untrusted` | high | +| [ISSUE-1015](#issue-1013-to-issue-1016--mise-sources) | `mise-replacement-untrusted` | high | +| [ISSUE-1016](#issue-1013-to-issue-1016--mise-sources) | `mise-option-untrusted` | medium | +| [ISSUE-1018](#issue-10xx--mise-en-place) | `mise-download-not-locked` | high | +| [ISSUE-1019](#issue-10xx--mise-en-place) | `mise-local-config-committed` | high | +| [ISSUE-1017](#issue-1017--mise-tasks-missing) | `mise-tasks-missing` | medium | + ### Run / output conventions - Every finding prints a clickable `↳ at :` — `Ctrl+click` @@ -33,6 +57,330 @@ absence from this file does not mean a rule doesn't exist — see --- +## ISSUE-10xx — `mise-en-place` + +**Control:** `mise-en-place`, configured by the top-level `mise` block + +Many teams use [mise](https://mise.jdx.dev) to pin the tools their CI +runs (terraform, linters, scanners, runtimes). The workflow then shrinks to +`mise install`, and what CI installs is decided by `mise.toml` and +`mise.lock`. This check reads both files from the local checkout, or, +without one (a remote `--project` run), from the repository at the analyzed +commit through the GitHub or GitLab API. It never runs mise. + +Every committed mise config is checked, in any directory. The walk skips +`.git`, `node_modules`, `vendor`, hidden directories other than `.config` +and `.mise`. A mise local config (`*.local.toml`) that git tracks is +ISSUE-1019; this check does not judge it as a config, but the versions +and sources checks do, since mise loads it. An untracked one, a +developer's own, is not read at all. Each config pairs with the +lockfile next to it (`mise.toml` and `mise.lock`, `mise..toml` and +`mise..lock`, a `conf.d/` fragment and the `mise.lock` of the +directory holding `conf.d/`). When the root config sets +`[monorepo] lockfile = true`, subproject configs pair with the root +lockfiles. + +Codes are numbered in sequence across the control. Each one has a +`subject` in the catalog, so the codes of one check can be filtered +together. + +| Code | Subject | Finding | Severity | +| :--- | :--- | :--- | :--- | +| ISSUE-1001 | lockfile | A config declares `[tools]` but its lockfile is not committed | high | +| ISSUE-1002 | lockfile | A config sets `[settings] lockfile = false` | high | +| ISSUE-1003 | lockfile | A tool request has no lock entry whose `specifiers` contain it | high | +| ISSUE-1004 | lockfile | A locked download has a `url` but no `checksum` (`requireChecksums`) | high | +| ISSUE-1005 | lockfile | A locked download records a `provenance` kind outside `trustedProvenance` | medium | +| ISSUE-1006 | lockfile | A locked download of a backend in `requireProvenance` has no `provenance` | medium | +| ISSUE-1007 | lockfile | A tool that locks downloads misses a platform in `requiredPlatforms` | low | +| ISSUE-1008 | lockfile | `lockfile_version` is below `minimumLockfileVersion` | low | +| ISSUE-1009 | lockfile | A tool is declared in asdf's `.tool-versions` and in no mise config of the same directory | medium | +| ISSUE-1010 | presence | `required: true` and the repository has no mise config | medium | +| ISSUE-1018 | lockfile | A tool is locked with no download data (`requireChecksums`): a binary backend (aqua, github, gitlab, ubi, http) with no platform table, or a platform with neither `url` nor `checksum` | high | +| ISSUE-1019 | lockfile | A mise local config (`mise.local.toml`, `mise..local.toml`, `config.local.toml`, `conf.d/*.local.toml`) is committed; [mise says it must not be](https://mise.jdx.dev/glossary.html#mise-local-toml) | high | + +ISSUE-1003 fails closed. A request Plumber cannot read statically (a +`{{ ... }}` template), an unquoted version (`node = 24`, which mise +itself rejects) and a format 0 lockfile (it records no `specifiers`) +are reported as not locked, never passed. + +A mise file that cannot be read stops the run with an error and no +report: a config or lockfile that is not valid TOML, a file over 2 MiB, +or a symlink that points outside the repository, at a device, or +nowhere. Plumber reads every mise file first, then lists every file that +failed in one error. A symlink that resolves to a file inside the +repository is followed, as mise follows it. Files under `exemptPaths` do +not stop the run, unless a checked config pairs with that lockfile. + +`.tool-versions` is read for ISSUE-1009 only, so only when the lockfile +check runs. An asdf plugin name that mise reads as one of its tools +(`nodejs` for `node`, `golang` for `go`) counts as that tool. +Idiomatic version files (`.nvmrc`, `.node-version`, `.python-version` +and the like), which mise reads only for the tools listed in its +`idiomatic_version_file_enable_tools` setting, are not read. + +`[settings] lockfile = false` applies to every config below it that +does not set `lockfile` itself, as mise applies it. ISSUE-1002 is raised +on the config that sets it. A subproject that inherits it is only +reported itself when that config is under `exemptPaths`. ISSUE-1010 needs `required: true`; a `.tool-versions` file +alone does not count as a mise config. +List the tool in `exemptPackages`, or the path in `exemptPaths` (for +example `examples/**` for fixtures), when the exception is intentional. + +```toml +# ❌ before: mise.toml with no mise.lock committed (ISSUE-1001) +[tools] +terraform = "1.9.8" +``` + +**Fix.** Set `[settings] lockfile = true`, run `mise lock`, commit +`mise.lock`, and install with `mise install --locked` in CI. + +**Remote runs.** Plumber lists the repository tree once (GitHub: one +`git/trees?recursive=1` request; GitLab: the recursive tree, 100 entries a +page), then reads the mise files in batched GraphQL queries of 50 files +(GitLab asks the sizes first, so a file over 2 MiB is never downloaded). +A file only a task include or a symlink reaches is read in a later batch, +up to 4 more. Two cases fall back to one request per file: a GitHub file +whose GraphQL text is truncated or not byte-exact (read over the contents +API), and a GitLab instance that does not answer the `blobs` query (older +than 13.11). An empty repository has no mise file. + +**Not evaluated** when the mise files were not read for the run: a +repository too large to read remotely (a tree GitHub cannot list in full, +over 100,000 entries or 7 MB, or more than 5,000 files to fetch) leaves +the control not evaluated and the run degraded, and a checkout reads it +in full; in platform mode, a policy that turns mise on over a run that did +not read them. The control never passes on data it did not read. An enabled `mise` block with no check block and no +`required: true` reports the control as needing configuration. + +**Config.** `mise` is a top-level key of `.plumber.yaml`, next to `gitlab` +and `github`, because it does not depend on the provider. When the block +is missing or sets `enabled: false`, Plumber reads no mise file and +reports nothing. `requireChecksums` is on unless set to `false`. +`trustedProvenance` defaults to every kind mise records (`slsa`, +`github-attestations`, `cosign`, `minisign`). + +```yaml +version: "2.0" +gitlab: + controls: ... +github: + controls: ... +mise: + enabled: true + required: false # true: a repository with no mise config is ISSUE-1010 + lockfile: + enabled: true + requireChecksums: true + # requireProvenance: ["aqua:*"] + # trustedProvenance: [slsa, github-attestations, cosign, minisign] + # requiredPlatforms: [linux-x64, linux-arm64] + # minimumLockfileVersion: 1 + exemptPackages: [] + exemptPaths: [] # globs: `*` within a directory, `**` across +``` + +--- + +## ISSUE-1011 and ISSUE-1012 — `mise-versions` + +**Severity:** `high` • **Control:** `mise-en-place`, configured by the top-level `mise.versions` block + +A tool request in a mise config matches a pattern of `forbiddenVersions` +(globs). The check reads the request as written in the config, where +people review it. With `latest`, the lockfile still pins a version, but +the next `mise lock --bump`, `mise upgrade` or regenerated lockfile moves +it with no change in `mise.toml`, so nobody reviews the new version. + +| Code | Finding | Severity | +| :--- | :--- | :--- | +| ISSUE-1011 | A tool request matches a pattern of `forbiddenVersions` | high | +| ISSUE-1012 | A tool request cannot be read statically: a `{{ ... }}` template, an empty or unquoted version | high | + +The check covers the same configs as the lockfile check, with or without +a lockfile. It fails closed: a request Plumber cannot read statically +can't be checked against `forbiddenVersions`, so it is ISSUE-1012, never +passed. A mise +config that cannot be parsed stops the run, as for the lockfile check. The +versions check alone reads no lockfile and no `.tool-versions`, so an +unreadable one does not stop it. +`exemptPackages` and `exemptPaths` apply as for the lockfile check. + +```toml +# ❌ before: mise.toml +[tools] +terraform = "latest" +node = "lts" + +# ✅ after +[tools] +terraform = "1.9.8" +node = "24.11.1" +``` + +**Fix.** Write an exact version, run `mise lock`, and commit both files. + +**Config.** The list below is the `plumber:default` one. It does not catch +a bare major such as `node = "24"`, which mise resolves to the newest +`24.x` when it locks. It leaves out `ref:*` on purpose: a ref pinned to a +commit SHA cannot move. Add `"ref:*"` to forbid every git ref, branches +and tags included. + +```yaml +mise: + versions: + enabled: true + forbiddenVersions: [latest, lts, "lts/*", "lts-*", stable, nightly, beta, "branch:*", "path:*", system, "sub-*", "prefix:*"] +``` + +--- + +## ISSUE-1013 to ISSUE-1016 — `mise-sources` + +**Control:** `mise-en-place`, configured by the top-level `mise.sources` block (off unless written) + +Where mise fetches a tool from depends on the tool, the URL its lockfile +records, and any redirect the config sets. This check holds each of them +to a list kept outside the repository. + +| Code | Finding | Severity | +| :--- | :--- | :--- | +| ISSUE-1013 | A tool matches no `trustedTools` pattern | high | +| ISSUE-1014 | A download URL locked in `mise.lock` matches no `trustedRegistries` pattern | high | +| ISSUE-1015 | A `[settings] url_replacements` target matches no `trustedReplacement` pattern | high | +| ISSUE-1016 | A trusted tool sets a URL option that matches no `trustedOptions` pattern | medium | + +**ISSUE-1013.** `trustedTools` is matched against the tool's full mise +name. A tool key with a backend (`aqua:jqlang/jq`, `github:org/repo`) is +its own name. A shorthand (`terraform = "1.9.8"`) is resolved by mise's +registry, so Plumber takes the `backend` its `mise.lock` entry records. +A shorthand with no matching lock entry can't be traced to a backend, and +is never passed. When the lockfile check runs, it reports the missing +entry (ISSUE-1001 or ISSUE-1003), so ISSUE-1013 stays quiet and the gap +is reported once. With the lockfile check off, for a config that sets +`lockfile = false`, or for one whose lockfile is unknown (its root +config is exempt and unreadable), the tool is ISSUE-1013. A committed +`*.local.toml` is judged like any other config. `.tool-versions` is not +judged here: ISSUE-1009 covers it. + +**ISSUE-1014.** Each platform entry of `mise.lock` records the `url` +`mise install --locked` downloads, so a change to `mise.lock` alone can +point a trusted tool at any host. Every recorded URL of a trusted tool +must match `trustedRegistries`. Leave the key out and the URLs are not +checked; `[]` trusts none. + +**ISSUE-1015.** mise sends a download to its `url_replacements` target +first, while `mise.lock` keeps the original URL, so the lockfile alone +does not show it. A replacement set from the pipeline +(`MISE_URL_REPLACEMENTS`) is not read yet. + +**ISSUE-1016** covers `api_url`, which points the github backend at +another host and turns off its attestation checks, `url` and +`platforms..url`, which download that address instead of a +release asset, and the pypi/pipx options `registry_url`, `indexes`, +`pipx_args`, `uvx_args` and the index variables of `install_env`. +For `pipx_args` and `uvx_args`, every URL in the arguments is judged on +its own, whatever flag carries it (`--index-url`, `-i`, `--pip-args`, +...): an argument with no URL, such as `--include-deps`, is not +reported. The `install_env` +variables are pip's, uv's (`UV_INDEX`, `UV_DEFAULT_INDEX`, +`UV_EXTRA_INDEX_URL`, `UV_INDEX_URL`), Go's proxy and checksum database +ones, and npm's registry, scoped ones included. +`asset_pattern` is not reported: it picks an asset of the same release. +Mirror settings such as `go.download_mirror` or `node.mirror_url` are not +read. The locked URL (ISSUE-1014) covers binary backends only: a go, +npm, cargo or pip tool locks no URL. + +A tool that is not trusted gets ISSUE-1013 alone: its URLs and options +are not judged. + +```toml +# ❌ before: mise.toml +[settings.url_replacements] +"https://releases.hashicorp.com/" = "https://mirror.example.com/" # ISSUE-1015 + +[tools] +"github:someone/tool" = "1.2.3" # ISSUE-1013 +"github:my-org/cli" = { version = "2.0.0", api_url = "https://ghe.example.com/api/v3" } # ISSUE-1016 +``` + +**Fix.** Install a trusted tool, drop the replacement or the option, or +add it to the matching list once you have reviewed it. `exemptPackages` +and `exemptPaths` apply as for the other mise checks. A mise file that +cannot be read stops the run. + +**Config.** Off in `plumber:default`: write the block to turn it on. +Patterns are globs, matched case-insensitively. + +```yaml +mise: + sources: + enabled: true + trustedTools: ["core:*", "aqua:*", "github:my-org/*"] + trustedRegistries: ["https://github.com/*", "https://nodejs.org/*"] + trustedReplacement: [] + trustedOptions: ["https://ghe.example.com/*"] +``` + +--- + +## ISSUE-1017 — `mise-tasks-missing` + +**Severity:** `medium` • **Control:** `mise-en-place`, configured by the top-level `mise.tasks` block (off unless written) + +When CI runs `mise run `, the tasks a project declares are the steps +that actually run. This check makes every mise project declare the tasks +the organization expects. + +A mise project is a directory holding a mise config. Its tasks are the +ones `mise run` sees there: +- `[tasks.]` tables of its configs +- TOML task files and executable files of its task directories + (`mise-tasks/`, `.mise-tasks/`, `.mise/tasks/`, `.config/mise/tasks/`, + `mise/tasks/`, or the paths in `task_config.includes`) +- the tasks of every parent directory's configs, which mise makes + available in subdirectories + +A file in a task directory counts only when it is executable, since mise +loads nothing else. File task names follow mise: `mise-tasks/db/migrate.sh` +is `db:migrate`, `mise-tasks/test/_default` is `test`. Include paths can use +`{{ config_root }}` and globs (`*` within a directory, `**` across). +Symlinks are followed only when they resolve inside the repository. + +What `mise run` sees without `MISE_ENV` is what counts: the tasks and +includes of a `mise..toml` are left out, and `[settings]` +`task.disable_paths` and `task.skip` drop the tasks they name. Task files +are only read when this check is on; a TOML task file that cannot be +parsed then stops the run, like any other mise file. + +`required` is a list of tasks. Each entry matches a task name or alias, +globs allowed (`lint:*`). One finding per project that misses any of +them, listing what it misses. + +It fails closed: tasks from a remote include (`git::`, `oci::`, `zip::`), a +templated include, a path outside the repository, or an include too large +to read (over 20,000 files) never satisfy the requirement, and the finding +names those includes. + +```text + MED ISSUE-1017 `svc/api/mise.toml` does not declare the required tasks: missing `test` and `scan` +``` + +**Fix.** Declare the missing tasks (`[tasks.test]` in `mise.toml`, or an +executable `mise-tasks/test`), or list the project's path in +`exemptPaths`. + +**Config.** Off in `plumber:default`: write the block to turn it on. + +```yaml +mise: + tasks: + required: [lint, test, scan] +``` + +--- + ## ISSUE-414 — `component-authorized-sources` **Severity:** `high` • **Control:** `componentMustComeFromAuthorizedSources` diff --git a/finding/identity/declarations.go b/finding/identity/declarations.go index 39b89a7d..e737173c 100644 --- a/finding/identity/declarations.go +++ b/finding/identity/declarations.go @@ -251,6 +251,53 @@ var declarations = map[string][]string{ "ISSUE-904": {}, // Repository has no SECURITY.md: one finding per repository, keyed on the code alone (singleton) (benched, not yet live: declaration provisional, revisit on unbench). "ISSUE-905": {}, + // mise (10xx). file is the mise config, or the lockfile for findings on + // a lock entry; package is the tool key and platform the os-arch key. + // No version: a bump must not re-key an unchanged finding. + // mise config without its lockfile: one per config file. + "ISSUE-1001": {"file"}, + // mise lockfiles turned off: one per config file. + "ISSUE-1002": {"file"}, + // Tool request with no lock entry: keyed on the tool. + "ISSUE-1003": {"file", "package"}, + // Locked download without checksum: keyed on the tool and platform. + "ISSUE-1004": {"file", "package", "platform"}, + // Locked download with an untrusted provenance: keyed on the tool, + // platform and provenance kind. + "ISSUE-1005": {"file", "package", "platform", "provenance"}, + // Locked download without provenance: keyed on the tool and platform. + "ISSUE-1006": {"file", "package", "platform"}, + // Required platform not locked: keyed on the tool and platform. + "ISSUE-1007": {"file", "package", "platform"}, + // Lockfile format too old: one per lockfile. + "ISSUE-1008": {"file"}, + // Tool only in .tool-versions: keyed on the tool. + "ISSUE-1009": {"file", "package"}, + // No mise config while mise is required: one per repository. + "ISSUE-1010": {}, + // Forbidden version request: keyed on the tool and the request, the + // defect itself (a tool can list several versions). + "ISSUE-1011": {"file", "package", "request"}, + // Version not readable statically: keyed on the tool and the request. + "ISSUE-1012": {"file", "package", "request"}, + // Untrusted tool: keyed on the tool. No source: a shorthand whose lock + // entry changes backend is the same finding. + "ISSUE-1013": {"file", "package"}, + // Untrusted locked URL: keyed on the lockfile, the tool, the platform + // and the URL. + "ISSUE-1014": {"file", "package", "platform", "value"}, + // Untrusted URL replacement: keyed on the setting and its target. + "ISSUE-1015": {"file", "setting", "value"}, + // Untrusted option: keyed on the tool, the option and its URL (two + // requests of one tool can set the same option to different URLs). + "ISSUE-1016": {"file", "package", "option", "value"}, + // Locked without download data: keyed on the tool, and the platform + // when the entry has platform tables. + "ISSUE-1018": {"file", "package", "platform"}, + // Committed local config: one per file. + "ISSUE-1019": {"file"}, + // Required tasks missing: one finding per project, keyed on its config. + "ISSUE-1017": {"file"}, } // Declared returns the identity field names declared for code, and whether diff --git a/finding/identity/identity_test.go b/finding/identity/identity_test.go index 7f24f255..ed7c7bc1 100644 --- a/finding/identity/identity_test.go +++ b/finding/identity/identity_test.go @@ -323,85 +323,104 @@ func TestFingerprint_MatchesTheShippedValues(t *testing.T) { // RecipeVersion is bumped on purpose, regenerate this map. func TestDeclarations_EveryCodeFingerprintIsPinned(t *testing.T) { golden := map[string]string{ - "ISSUE-101": "042bff0ebb1d89ee", - "ISSUE-201": "ded1b4bbe17f4b90", - "ISSUE-202": "df6d1d45432e1cb5", - "ISSUE-102": "32b497995ae3be65", - "ISSUE-103": "ae7c300b437b0bb0", - "ISSUE-203": "0ebe5475110580fc", - "ISSUE-204": "7c14264872de8ef4", - "ISSUE-205": "f2974b453aec4776", - "ISSUE-207": "a057345f5450abb9", - "ISSUE-208": "2b98f71f015b242e", - "ISSUE-209": "8db95f316a53dbd4", - "ISSUE-210": "08e465d22142ff2c", - "ISSUE-211": "ceb796eb817f8add", - "ISSUE-212": "920b5adbc8ebefe0", - "ISSUE-213": "b35b60424da3106c", - "ISSUE-214": "459777fe828201c3", - "ISSUE-215": "fcb8941c2d1f950e", - "ISSUE-302": "c131f6dbb114f9af", - "ISSUE-303": "ecf73e88d37310ae", - "ISSUE-305": "4b3d732f9681dc92", - "ISSUE-306": "aabc6270ca4e4304", - "ISSUE-307": "05ed16253de98346", - "ISSUE-308": "de132d1493cadafe", - "ISSUE-309": "2e2c85d21a6492a6", - "ISSUE-310": "5ba5827fd01d3e4c", - "ISSUE-401": "468870372f32863b", - "ISSUE-402": "574564223df032be", - "ISSUE-403": "9c0211f37dbdd777", - "ISSUE-404": "6d22a43975ac3476", - "ISSUE-405": "14e1d331e2698a24", - "ISSUE-406": "501661c23ef116a0", - "ISSUE-408": "5d6adc6fe8df41e0", - "ISSUE-409": "f7bd5ed732e20b1b", - "ISSUE-410": "7ec575989260503a", - "ISSUE-411": "00a582d1c7ce3b61", - "ISSUE-412": "a7e4aba60a34a04a", - "ISSUE-413": "1388ae7203cc3eb8", - "ISSUE-414": "c1cbb69708f90ad4", - "ISSUE-415": "014ae9977401ed15", - "ISSUE-417": "84dd72a018932a2e", - "ISSUE-418": "b7d95784db1eafc2", - "ISSUE-419": "6147e752a7f298fb", - "ISSUE-420": "ac3048041dde8446", - "ISSUE-421": "7573d13ae392133e", - "ISSUE-501": "e36cebae06c15f85", - "ISSUE-502": "b51fcaa43b9409cf", - "ISSUE-503": "86ae932a6e3d76ca", - "ISSUE-504": "b698c0c9440ef0f5", - "ISSUE-505": "4e929715c61fcba6", - "ISSUE-506": "aa6378b9df051002", - "ISSUE-510": "624e0e1cc44935c6", - "ISSUE-507": "7874a7f9aa3f2b6f", - "ISSUE-601": "3a68700e66069498", - "ISSUE-422": "ade0bea017f69d56", - "ISSUE-423": "b30503f030b41d3a", - "ISSUE-701": "87a2f87a752971bd", - "ISSUE-702": "875ec32b1513e8a8", - "ISSUE-703": "cf522b35974397b7", - "ISSUE-704": "5d5da28eff4463bc", - "ISSUE-705": "443550083abbf9a4", - "ISSUE-706": "96136288dee3d9d0", - "ISSUE-707": "9fa2d7e4325d1945", - "ISSUE-708": "02b9293b41fd49ea", - "ISSUE-709": "5b1c47498bc5b3c9", - "ISSUE-711": "2a680e66277a78e7", - "ISSUE-712": "626d1c97a59651bb", - "ISSUE-713": "b8e68adcadca6cb2", - "ISSUE-714": "4962cbb919d4ba0a", - "ISSUE-715": "2eb0f41ca9a31bd8", - "ISSUE-716": "c0112771c48f6ab5", - "ISSUE-801": "1cf1a105d1a87734", - "ISSUE-802": "d3d7331043f5614c", - "ISSUE-803": "46e3e735b1ceec41", - "ISSUE-804": "eceec2db4ce22c05", - "ISSUE-901": "ca625b1497c56403", - "ISSUE-902": "43f4f0601229026f", - "ISSUE-903": "7fd2361c5d78fbb6", - "ISSUE-904": "83315ec9a14da003", - "ISSUE-905": "56786a18e9ce7f7c", + "ISSUE-101": "042bff0ebb1d89ee", + "ISSUE-201": "ded1b4bbe17f4b90", + "ISSUE-202": "df6d1d45432e1cb5", + "ISSUE-102": "32b497995ae3be65", + "ISSUE-103": "ae7c300b437b0bb0", + "ISSUE-203": "0ebe5475110580fc", + "ISSUE-204": "7c14264872de8ef4", + "ISSUE-205": "f2974b453aec4776", + "ISSUE-207": "a057345f5450abb9", + "ISSUE-208": "2b98f71f015b242e", + "ISSUE-209": "8db95f316a53dbd4", + "ISSUE-210": "08e465d22142ff2c", + "ISSUE-211": "ceb796eb817f8add", + "ISSUE-212": "920b5adbc8ebefe0", + "ISSUE-213": "b35b60424da3106c", + "ISSUE-214": "459777fe828201c3", + "ISSUE-215": "fcb8941c2d1f950e", + "ISSUE-302": "c131f6dbb114f9af", + "ISSUE-303": "ecf73e88d37310ae", + "ISSUE-305": "4b3d732f9681dc92", + "ISSUE-306": "aabc6270ca4e4304", + "ISSUE-307": "05ed16253de98346", + "ISSUE-308": "de132d1493cadafe", + "ISSUE-309": "2e2c85d21a6492a6", + "ISSUE-310": "5ba5827fd01d3e4c", + "ISSUE-401": "468870372f32863b", + "ISSUE-402": "574564223df032be", + "ISSUE-403": "9c0211f37dbdd777", + "ISSUE-404": "6d22a43975ac3476", + "ISSUE-405": "14e1d331e2698a24", + "ISSUE-406": "501661c23ef116a0", + "ISSUE-408": "5d6adc6fe8df41e0", + "ISSUE-409": "f7bd5ed732e20b1b", + "ISSUE-410": "7ec575989260503a", + "ISSUE-411": "00a582d1c7ce3b61", + "ISSUE-412": "a7e4aba60a34a04a", + "ISSUE-413": "1388ae7203cc3eb8", + "ISSUE-414": "c1cbb69708f90ad4", + "ISSUE-415": "014ae9977401ed15", + "ISSUE-417": "84dd72a018932a2e", + "ISSUE-418": "b7d95784db1eafc2", + "ISSUE-419": "6147e752a7f298fb", + "ISSUE-420": "ac3048041dde8446", + "ISSUE-421": "7573d13ae392133e", + "ISSUE-501": "e36cebae06c15f85", + "ISSUE-502": "b51fcaa43b9409cf", + "ISSUE-503": "86ae932a6e3d76ca", + "ISSUE-504": "b698c0c9440ef0f5", + "ISSUE-505": "4e929715c61fcba6", + "ISSUE-506": "aa6378b9df051002", + "ISSUE-507": "7874a7f9aa3f2b6f", + "ISSUE-510": "624e0e1cc44935c6", + "ISSUE-601": "3a68700e66069498", + "ISSUE-422": "ade0bea017f69d56", + "ISSUE-423": "b30503f030b41d3a", + "ISSUE-701": "87a2f87a752971bd", + "ISSUE-702": "875ec32b1513e8a8", + "ISSUE-703": "cf522b35974397b7", + "ISSUE-704": "5d5da28eff4463bc", + "ISSUE-705": "443550083abbf9a4", + "ISSUE-706": "96136288dee3d9d0", + "ISSUE-707": "9fa2d7e4325d1945", + "ISSUE-708": "02b9293b41fd49ea", + "ISSUE-709": "5b1c47498bc5b3c9", + "ISSUE-711": "2a680e66277a78e7", + "ISSUE-712": "626d1c97a59651bb", + "ISSUE-713": "b8e68adcadca6cb2", + "ISSUE-714": "4962cbb919d4ba0a", + "ISSUE-715": "2eb0f41ca9a31bd8", + "ISSUE-716": "c0112771c48f6ab5", + "ISSUE-801": "1cf1a105d1a87734", + "ISSUE-802": "d3d7331043f5614c", + "ISSUE-803": "46e3e735b1ceec41", + "ISSUE-804": "eceec2db4ce22c05", + "ISSUE-901": "ca625b1497c56403", + "ISSUE-902": "43f4f0601229026f", + "ISSUE-903": "7fd2361c5d78fbb6", + "ISSUE-904": "83315ec9a14da003", + "ISSUE-905": "56786a18e9ce7f7c", + "ISSUE-1001": "0005f3a503447fde", + "ISSUE-1002": "d8d88405b8396031", + "ISSUE-1003": "11f8c6d53c656c05", + "ISSUE-1004": "04a0ecf5190d5ae4", + "ISSUE-1005": "d4f0f4fbb37eeeae", + "ISSUE-1006": "ba0f3fac29bb7a14", + "ISSUE-1007": "89e6349db72112d4", + "ISSUE-1008": "ae2a3865a978f551", + "ISSUE-1009": "b4e7e0f4885697f0", + "ISSUE-1010": "1e1078b769a288a4", + "ISSUE-1011": "3ac87b23f2c03bd1", + "ISSUE-1012": "0e7d84cac649f0c8", + "ISSUE-1013": "18509a9089eb9a5d", + "ISSUE-1014": "b847222a4ec4de78", + "ISSUE-1015": "e9064c28640ae099", + "ISSUE-1016": "281ba79ddfd9a110", + "ISSUE-1017": "80ecf2528a40d266", + "ISSUE-1018": "bcfae9d8b7bc7841", + "ISSUE-1019": "af0b2c894ae8e62c", } codes := identity.DeclaredCodes() if len(golden) != len(codes) { diff --git a/github/github_workflows_remote.go b/github/github_workflows_remote.go index b9675691..1e687a10 100644 --- a/github/github_workflows_remote.go +++ b/github/github_workflows_remote.go @@ -74,6 +74,10 @@ func ScanGitHubWorkflowsRemote(host, owner, repo, ref string, enrichActionMetada return nil, nil, fmt.Errorf("list workflows: %w", err) } listing := tree.files + pipeline.RemoteRev = tree.rev + if tree.commit != "" { + pipeline.RemoteRev = tree.commit + } if tree.hasLockfile { pipeline.WorkflowLockfilePath = githubWorkflowLockfile } diff --git a/github/remote_files.go b/github/remote_files.go new file mode 100644 index 00000000..e23dc7dd --- /dev/null +++ b/github/remote_files.go @@ -0,0 +1,206 @@ +package github + +// Remote repository files (#254): reading the mise files of a repository +// that is not checked out lists the tree in one request and reads the +// files in aliased GraphQL batches, so it costs a few requests whatever +// the number of files. +// +// The listing is REST: GET /repos/:o/:r/git/trees/:rev?recursive=1 +// answers every entry in one request. GraphQL has no recursive tree, and +// nesting Tree.entries a few levels a query was measured far slower: on +// jdx/mise (6,664 entries, 533 directories) it took 135 queries and about +// 234 s, some of them timing out, where the REST tree took one request +// and 0.67 s (checked 2026-12-02). GitHub truncates that answer past +// 100,000 entries or 7 MB; a truncated tree is repofs.ErrTooLarge, since a +// mise file left out of it would go unchecked: the caller reports the +// control not evaluated. + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/cli/go-gh/v2/pkg/api" + + "github.com/getplumber/plumber/internal/repofs" +) + +const ( + // readAliases bounds the files one content query reads. + readAliases = 50 + // maxBlobBytes is the largest file whose text is used; a larger file + // is reported with its size and no content (the mise scan reads 2 MiB + // at most). + maxBlobBytes = 2 << 20 +) + +// RemoteFiles reads a GitHub repository at one commit as a +// repofs.Source. +type RemoteFiles struct { + gql *api.GraphQLClient + rest *api.RESTClient + owner, repo string + rev string +} + +// NewRemoteFiles reads owner/repo on host at rev (a commit oid or a ref +// expression, ir.NormalizedPipeline.RemoteRev). +func NewRemoteFiles(host, owner, repo, rev string) (*RemoteFiles, error) { + if rev == "" { + rev = "HEAD" + } + gql, err := newScannedRepoGraphQL(host) + if err != nil { + return nil, err + } + rest, err := newGitHubRESTClient(host) + if err != nil { + return nil, err + } + return &RemoteFiles{gql: gql, rest: rest, owner: owner, repo: repo, rev: rev}, nil +} + +// treeRef is rev as the trees endpoint takes it: a commit oid or HEAD as +// is, a refs/heads/ or refs/tags/ expression as its short name. +func treeRef(rev string) string { + for _, p := range []string{"refs/heads/", "refs/tags/"} { + if short, ok := strings.CutPrefix(rev, p); ok { + return short + } + } + return rev +} + +// gitTree is the answer of the trees endpoint. +type gitTree struct { + Tree []struct { + Path string `json:"path"` + Mode string `json:"mode"` + } `json:"tree"` + Truncated bool `json:"truncated"` +} + +// List implements repofs.Source: the whole repository in one request. +func (r *RemoteFiles) List(ctx context.Context) ([]repofs.Entry, error) { + endpoint := fmt.Sprintf("repos/%s/%s/git/trees/%s?recursive=1", + url.PathEscape(r.owner), url.PathEscape(r.repo), url.PathEscape(treeRef(r.rev))) + var t gitTree + if err := r.rest.DoWithContext(ctx, http.MethodGet, endpoint, nil, &t); err != nil { + // An empty repository has no tree: GitHub answers 409 "Git + // Repository is empty". It holds no mise file. + if httpErr, ok := errors.AsType[*api.HTTPError](err); ok && httpErr.StatusCode == http.StatusConflict { + return nil, nil + } + return nil, fmt.Errorf("list the tree of %s/%s at %s: %w", r.owner, r.repo, r.rev, err) + } + if t.Truncated { + return nil, fmt.Errorf("%w: GitHub cannot list the tree of %s/%s in full (over 100,000 entries or 7 MB); run plumber on a checkout of the repository", repofs.ErrTooLarge, r.owner, r.repo) + } + var entries []repofs.Entry + for _, e := range t.Tree { + mode, err := strconv.ParseUint(e.Mode, 8, 32) + if err != nil { + continue + } + if m, ok := repofs.GitMode(uint32(mode)); ok { + entries = append(entries, repofs.Entry{Path: e.Path, Mode: m}) + } + } + return entries, nil +} + +// readFields read a file's text, its oid to check the text against, and +// its size. +const readFields = "... on Blob { oid text isTruncated isBinary byteSize }" + +type readAnswer struct { + blobAnswer + ByteSize int64 `json:"byteSize"` +} + +// Read implements repofs.Source. A file GitHub does not give exactly +// (truncated, or text that does not hash to its oid) is read over the +// git blobs API; a binary file, or one over 2 MiB, comes back with its +// size and an error or no content, and the caller reports it unreadable. +func (r *RemoteFiles) Read(ctx context.Context, paths []string) (map[string]repofs.Blob, error) { + out := map[string]repofs.Blob{} + for start := 0; start < len(paths); start += readAliases { + chunk := paths[start:min(start+readAliases, len(paths))] + items := make([]treeQueryItem, len(chunk)) + for i, p := range chunk { + items[i] = treeQueryItem{"f" + strconv.Itoa(i), r.rev + ":" + p, readFields} + } + fields, failed, err := queryObjects(r.gql, "remote files: contents", r.owner, r.repo, items) + if err != nil { + return nil, fmt.Errorf("read files: %w", err) + } + for i, p := range chunk { + alias := "f" + strconv.Itoa(i) + if ferr := failed[alias]; ferr != nil { + out[p] = repofs.Blob{Err: ferr} + continue + } + var b readAnswer + if isNull(fields[alias]) || json.Unmarshal(fields[alias], &b) != nil { + continue // nothing there: the caller reports it + } + out[p] = r.blob(ctx, p, &b) + } + } + return out, nil +} + +func (r *RemoteFiles) blob(ctx context.Context, p string, b *readAnswer) repofs.Blob { + switch { + case b.IsBinary: + return repofs.Blob{Size: b.ByteSize, Err: errors.New("binary file")} + case b.ByteSize > maxBlobBytes: + return repofs.Blob{Size: b.ByteSize} + } + if text, ok := b.usable(); ok { + return repofs.Blob{Data: []byte(text), Size: b.ByteSize} + } + data, err := r.gitBlob(ctx, p, b.Oid) + if err != nil { + return repofs.Blob{Err: err} + } + return repofs.Blob{Data: data, Size: int64(len(data))} +} + +// gitBlobAnswer is the answer of the git blobs endpoint. +type gitBlobAnswer struct { + Content string `json:"content"` + Encoding string `json:"encoding"` +} + +// gitBlob reads the blob oid of file p over GET +// /repos/:o/:r/git/blobs/:oid, which serves up to 100 MB in Base64. The +// contents API is not used: it gives no content past 1 MiB, and the mise +// scan reads files up to 2 MiB. The bytes must hash to oid. +func (r *RemoteFiles) gitBlob(ctx context.Context, p, oid string) ([]byte, error) { + if oid == "" { + return nil, fmt.Errorf("read %s: GitHub gave no blob oid", p) + } + endpoint := fmt.Sprintf("repos/%s/%s/git/blobs/%s", url.PathEscape(r.owner), url.PathEscape(r.repo), url.PathEscape(oid)) + var a gitBlobAnswer + if err := r.rest.DoWithContext(ctx, http.MethodGet, endpoint, nil, &a); err != nil { + return nil, fmt.Errorf("read %s: %w", p, err) + } + if a.Encoding != "base64" { + return nil, fmt.Errorf("read %s: unexpected blob encoding %q", p, a.Encoding) + } + data, err := base64.StdEncoding.DecodeString(strings.NewReplacer("\n", "", " ", "").Replace(a.Content)) + if err != nil { + return nil, fmt.Errorf("read %s: decode base64: %w", p, err) + } + if gitBlobOID(string(data)) != oid { + return nil, fmt.Errorf("read %s: content does not match blob %s", p, oid) + } + return data, nil +} diff --git a/github/remote_files_test.go b/github/remote_files_test.go new file mode 100644 index 00000000..3e092209 --- /dev/null +++ b/github/remote_files_test.go @@ -0,0 +1,381 @@ +package github + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "io/fs" + "net/http" + "net/http/httptest" + "reflect" + "regexp" + "sort" + "strings" + "testing" + + "github.com/getplumber/plumber/internal/repofs" +) + +// blobRepo answers the content queries of RemoteFiles from files. +type blobRepo struct { + files map[string]fakeFile +} + +var aliasRe = regexp.MustCompile(`(\w+): object\(expression: \$\w+\)`) + +func (n blobRepo) respond(q graphQLRequest) (string, int) { + repo := map[string]any{} + for _, m := range aliasRe.FindAllStringSubmatch(q.Query, -1) { + alias := m[1] + _, p, _ := strings.Cut(q.Variables[alias].(string), ":") + if f, ok := n.files[p]; ok { + b := f.blob() + b["byteSize"] = len(f.text) + repo[alias] = b + continue + } + repo[alias] = nil + } + body, _ := json.Marshal(map[string]any{"data": map[string]any{"repository": repo, "rateLimit": map[string]any{"cost": 1, "remaining": 4999}}}) + return string(body), 200 +} + +// treeBody is a trees endpoint answer listing entries ("path mode"). +func treeBody(truncated bool, entries ...string) string { + var tree []map[string]string + for _, e := range entries { + p, mode, _ := strings.Cut(e, " ") + typ := "blob" + switch mode { + case "040000": + typ = "tree" + case "160000": + typ = "commit" + } + tree = append(tree, map[string]string{"path": p, "mode": mode, "type": typ}) + } + body, _ := json.Marshal(map[string]any{"sha": "t", "tree": tree, "truncated": truncated}) + return string(body) +} + +func TestRemoteFilesList(t *testing.T) { + cases := []struct { + name string + rev string + routes map[string]string + wantEntries []string + wantErr string + wantPaths []string + }{ + { + name: "one request lists the repository, modes mapped, submodules left out", + rev: "abc123", + routes: map[string]string{"/repos/o/r/git/trees/abc123": treeBody(false, + "mise.toml 100644", "svc 040000", "svc/mise-tasks 040000", "svc/mise-tasks/build 100755", + "link 120000", "sub 160000", "node_modules 040000", "node_modules/x.toml 100644")}, + wantEntries: []string{ + "link Lrwxrwxrwx", "mise.toml -rw-r--r--", "node_modules drwxr-xr-x", "node_modules/x.toml -rw-r--r--", + "svc drwxr-xr-x", "svc/mise-tasks drwxr-xr-x", "svc/mise-tasks/build -rwxr-xr-x", + }, + wantPaths: []string{"/repos/o/r/git/trees/abc123"}, + }, + { + name: "a refs/heads expression is read by its branch name", + rev: "refs/heads/feature/x", + routes: map[string]string{"/repos/o/r/git/trees/feature/x": treeBody(false, "mise.toml 100644")}, + wantEntries: []string{"mise.toml -rw-r--r--"}, + wantPaths: []string{"/repos/o/r/git/trees/feature/x"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + paths := restRecorder(t, tc.routes) + gql, queries := stubbedGraphQL(t, blobRepo{}.respond) + swapScannedRepoGraphQL(t, gql, nil) + r, err := NewRemoteFiles("", "o", "r", tc.rev) + if err != nil { + t.Fatal(err) + } + entries, err := r.List(context.Background()) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Errorf("List error = %v, want %q", err, tc.wantErr) + } + } else if err != nil { + t.Fatalf("List: %v", err) + } + var got []string + for _, e := range entries { + got = append(got, e.Path+" "+e.Mode.String()) + } + sort.Strings(got) + if !reflect.DeepEqual(got, tc.wantEntries) { + t.Errorf("entries =\n%v\nwant\n%v", got, tc.wantEntries) + } + if !reflect.DeepEqual(*paths, tc.wantPaths) { + t.Errorf("REST paths = %v, want %v", *paths, tc.wantPaths) + } + if len(*queries) != 0 { + t.Errorf("%d GraphQL queries, want none for the listing", len(*queries)) + } + }) + } +} + +func TestRemoteFilesRead(t *testing.T) { + restRecorder(t, nil) + repo := blobRepo{files: map[string]fakeFile{ + "mise.toml": {text: "[tools]\n"}, + "link": {text: "svc/mise.toml", mode: 0o120000}, + "bin.toml": {text: "x", binary: true}, + "huge.toml": {text: strings.Repeat("a", maxBlobBytes+1)}, + }} + files := []string{"mise.toml", "link", "bin.toml", "huge.toml", "gone.toml"} + for i := range readAliases { + p := "many/" + strings.Repeat("x", i+1) + repo.files[p] = fakeFile{text: p} + files = append(files, p) + } + gql, queries := stubbedGraphQL(t, repo.respond) + swapScannedRepoGraphQL(t, gql, nil) + r, err := NewRemoteFiles("", "o", "r", "abc123") + if err != nil { + t.Fatal(err) + } + got, err := r.Read(context.Background(), files) + if err != nil { + t.Fatalf("Read: %v", err) + } + if len(*queries) != 2 { + t.Errorf("%d queries for %d files, want 2", len(*queries), len(files)) + } + check := []struct { + path string + want repofs.Blob + wantErr string + }{ + {path: "mise.toml", want: repofs.Blob{Data: []byte("[tools]\n"), Size: 8}}, + {path: "link", want: repofs.Blob{Data: []byte("svc/mise.toml"), Size: 13}}, + {path: "bin.toml", wantErr: "binary file"}, + {path: "huge.toml", want: repofs.Blob{Size: maxBlobBytes + 1}}, + } + for _, c := range check { + b, ok := got[c.path] + switch { + case !ok: + t.Errorf("%s: not returned", c.path) + case c.wantErr != "": + if b.Err == nil || !strings.Contains(b.Err.Error(), c.wantErr) { + t.Errorf("%s: err = %v, want %q", c.path, b.Err, c.wantErr) + } + case !reflect.DeepEqual(b, c.want): + t.Errorf("%s = %+v, want %+v", c.path, b, c.want) + } + } + if _, ok := got["gone.toml"]; ok { + t.Errorf("gone.toml returned, want it left out") + } +} + +// TestRemoteFilesFS: the listing serves repofs, whose symlink resolution +// reads the link targets Read returned. +func TestRemoteFilesFS(t *testing.T) { + restRecorder(t, map[string]string{"/repos/o/r/git/trees/HEAD": treeBody(false, + "svc 040000", "svc/mise.toml 100644", "link 120000")}) + repo := blobRepo{files: map[string]fakeFile{ + "svc/mise.toml": {text: "x"}, + "link": {text: "svc", mode: 0o120000}, + }} + gql, _ := stubbedGraphQL(t, repo.respond) + swapScannedRepoGraphQL(t, gql, nil) + r, err := NewRemoteFiles("", "o", "r", "") + if err != nil { + t.Fatal(err) + } + entries, err := r.List(context.Background()) + if err != nil { + t.Fatal(err) + } + f := repofs.New(entries) + if err := f.Fetch(context.Background(), r, f.Paths(func(string, fs.FileMode) bool { return true })); err != nil { + t.Fatal(err) + } + got, err := f.Resolve("link/mise.toml") + if err != nil || got != "svc/mise.toml" { + t.Errorf("Resolve = %q, %v; want svc/mise.toml", got, err) + } +} + +// TestScanGitHubWorkflowsRemote_RemoteRev: the workflows are read at a +// commit, and the pipeline carries its oid (an annotated tag's target), +// so the mise files are read at the same commit. +func TestScanGitHubWorkflowsRemote_RemoteRev(t *testing.T) { + cases := []struct { + name string + repo gitRepo + ref string + want string + }{ + { + name: "a branch is read at its commit", + repo: gitRepo{refs: []string{"refs/heads/main"}, commits: map[string]string{"refs/heads/main": "c0ffee"}}, + ref: "main", + want: "c0ffee", + }, + { + name: "an annotated tag is read at the commit it points at", + repo: gitRepo{refs: []string{"refs/tags/v1"}, tags: map[string]string{"refs/tags/v1": "beef01"}}, + ref: "v1", + want: "beef01", + }, + { + name: "no oid known: the expression the workflows were read at", + repo: gitRepo{refs: []string{"refs/heads/main"}}, + ref: "main", + want: "refs/heads/main", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + tc.repo.files = map[string]fakeFile{".github/workflows/ci.yml": {text: probeWorkflow}} + swapGitRepo(t, tc.repo) + restRecorder(t, nil) + pipeline, _, err := ScanGitHubWorkflowsRemote("", "owner", "repo", tc.ref, false, false, nil) + if err != nil { + t.Fatalf("ScanGitHubWorkflowsRemote: %v", err) + } + if pipeline.RemoteRev != tc.want { + t.Errorf("RemoteRev = %q, want %q", pipeline.RemoteRev, tc.want) + } + }) + } +} + +// TestRemoteFilesListErrors: an empty repository lists nothing, a +// truncated tree is repofs.ErrTooLarge, any other failure stops the read. +func TestRemoteFilesListErrors(t *testing.T) { + cases := []struct { + name string + status int + body string + wantErr string + wantTooBig bool + wantEntries int + }{ + {name: "an empty repository (409) has no entry", status: 409, body: `{"message":"Git Repository is empty."}`}, + {name: "a truncated tree is too large", status: 200, body: treeBody(true, "mise.toml 100644"), wantErr: "cannot list the tree", wantTooBig: true}, + {name: "a server error stops the read", status: 500, body: `{"message":"boom"}`, wantErr: "list the tree of o/r"}, + {name: "an unreadable mode is left out", status: 200, body: `{"tree":[{"path":"a","mode":"zz"},{"path":"b","mode":"100644"}]}`, wantEntries: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + })) + t.Cleanup(srv.Close) + swapRESTClient(t, srv) + gql, _ := stubbedGraphQL(t, blobRepo{}.respond) + swapScannedRepoGraphQL(t, gql, nil) + r, err := NewRemoteFiles("", "o", "r", "abc") + if err != nil { + t.Fatal(err) + } + entries, err := r.List(context.Background()) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("List error = %v, want %q", err, tc.wantErr) + } + if errors.Is(err, repofs.ErrTooLarge) != tc.wantTooBig { + t.Errorf("errors.Is(err, ErrTooLarge) = %v, want %v", !tc.wantTooBig, tc.wantTooBig) + } + return + } + if err != nil || len(entries) != tc.wantEntries { + t.Errorf("List = %v, %v; want %d entries", entries, err, tc.wantEntries) + } + }) + } +} + +// TestRemoteFilesReadFallbacks: a file GraphQL does not give exactly is +// read over the git blobs API, files between 1 and 2 MiB included (the +// contents API gives no content past 1 MiB); an alias error, a failed REST +// read or bytes that do not hash to the oid are the file's error; a failed +// query fails the read. +func TestRemoteFilesReadFallbacks(t *testing.T) { + t.Run("per file", func(t *testing.T) { + big := strings.Repeat("a = 1\n", (3<<20)/(2*6)) + repo := blobRepo{files: map[string]fakeFile{ + "served.toml": {text: "real\n", served: "mangled\n"}, + "trunc.toml": {text: "whole\n", truncated: true}, + "big.lock": {text: big, truncated: true}, + "wrong.toml": {text: "right\n", served: "mangled\n"}, + }} + gql, _ := stubbedGraphQL(t, func(q graphQLRequest) (string, int) { + body, status := repo.respond(q) + if strings.Contains(q.Query, "f2:") { + // f2 (failed.toml) gets an error of its own. + body = strings.TrimSuffix(body, "}") + `,"errors":[{"path":["repository","f2"],"message":"boom"}]}` + } + return body, status + }) + swapScannedRepoGraphQL(t, gql, nil) + gitBlob := func(text string) string { + return `{"content":"` + base64.StdEncoding.EncodeToString([]byte(text)) + `","encoding":"base64"}` + } + paths := restRecorder(t, map[string]string{ + "/repos/o/r/git/blobs/" + gitBlobOID("real\n"): gitBlob("real\n"), + "/repos/o/r/git/blobs/" + gitBlobOID(big): gitBlob(big), + "/repos/o/r/git/blobs/" + gitBlobOID("right\n"): gitBlob("not right\n"), + }) + r, err := NewRemoteFiles("", "o", "r", "abc") + if err != nil { + t.Fatal(err) + } + got, err := r.Read(context.Background(), []string{"served.toml", "trunc.toml", "failed.toml", "big.lock", "wrong.toml"}) + if err != nil { + t.Fatalf("Read: %v", err) + } + if b := got["served.toml"]; string(b.Data) != "real\n" || b.Err != nil { + t.Errorf("served.toml = %+v, want the REST content", b) + } + if b := got["trunc.toml"]; b.Err == nil { + t.Errorf("trunc.toml = %+v, want the failed REST read as its error", b) + } + if b := got["failed.toml"]; b.Err == nil || !strings.Contains(b.Err.Error(), "boom") { + t.Errorf("failed.toml = %+v, want the alias error", b) + } + if b := got["big.lock"]; b.Err != nil || len(b.Data) != len(big) || b.Size != int64(len(big)) { + t.Errorf("big.lock: %d bytes, size %d, err %v; want the %d bytes of the git blob", len(b.Data), b.Size, b.Err, len(big)) + } + if b := got["wrong.toml"]; b.Err == nil || !strings.Contains(b.Err.Error(), "does not match blob") { + t.Errorf("wrong.toml = %+v, want a content mismatch error", b) + } + want := []string{ + "/repos/o/r/git/blobs/" + gitBlobOID("real\n"), + "/repos/o/r/git/blobs/" + gitBlobOID("whole\n"), + "/repos/o/r/git/blobs/" + gitBlobOID(big), + "/repos/o/r/git/blobs/" + gitBlobOID("right\n"), + } + if !reflect.DeepEqual(*paths, want) { + t.Errorf("REST paths = %v, want %v", *paths, want) + } + }) + t.Run("a failed query fails the read", func(t *testing.T) { + gql, _ := stubbedGraphQL(t, func(graphQLRequest) (string, int) { + return `{"errors":[{"message":"rate limited"}]}`, 200 + }) + swapScannedRepoGraphQL(t, gql, nil) + restRecorder(t, nil) + r, err := NewRemoteFiles("", "o", "r", "abc") + if err != nil { + t.Fatal(err) + } + if _, err := r.Read(context.Background(), []string{"mise.toml"}); err == nil { + t.Errorf("Read error = nil, want the query error") + } + }) +} diff --git a/github/remote_tree.go b/github/remote_tree.go index a3422abd..5087fbf4 100644 --- a/github/remote_tree.go +++ b/github/remote_tree.go @@ -83,6 +83,9 @@ type workflowTree struct { // (refs/heads/x, refs/tags/x, the ref as written, or HEAD); the // composite query reads at the same one. rev string + // commit is the oid of the commit rev named when the query read it + // (an annotated tag's target), "" when unknown. + commit string // files are the .yml/.yaml regular files, sorted by name. files []treeEntry hasLockfile bool @@ -161,7 +164,7 @@ func loadWorkflowTree(gql *api.GraphQLClient, owner, repo, ref string) (workflow asked := map[int]bool{} for i, c := range cands { n := strconv.Itoa(i) - items = append(items, treeQueryItem{"c" + n, c, "__typename"}) + items = append(items, treeQueryItem{"c" + n, c, "__typename ... on Commit { oid } ... on Tag { target { oid } }"}) if len(cands) == 1 || i < 2 || hexRef.MatchString(ref) { items = append(items, treeQueryItem{"t" + n, c + ":" + githubWorkflowsSubdir, treeFields}) asked[i] = true @@ -194,7 +197,22 @@ func loadWorkflowTree(gql *api.GraphQLClient, owner, repo, ref string) (workflow if ferr := failed["t"+n]; ferr != nil { return workflowTree{}, ferr } - return workflowFiles(c, raw), nil + tree := workflowFiles(c, raw) + // The commit, or the one an annotated tag points at: reading by + // oid keeps every later read on the same commit. + var commit struct { + Oid string `json:"oid"` + Target *struct { + Oid string `json:"oid"` + } `json:"target"` + } + if json.Unmarshal(fields["c"+n], &commit) == nil { + tree.commit = commit.Oid + if tree.commit == "" && commit.Target != nil { + tree.commit = commit.Target.Oid + } + } + return tree, nil } if ref == "" { // An empty repository has no default branch commit: no workflows. diff --git a/github/remote_tree_test.go b/github/remote_tree_test.go index cc540425..5d4b91ca 100644 --- a/github/remote_tree_test.go +++ b/github/remote_tree_test.go @@ -46,6 +46,10 @@ type gitRepo struct { refs []string files map[string]fakeFile byRef map[string]map[string]fakeFile + // commits gives a ref the oid its commit answers; tags makes a ref an + // annotated tag whose target is that commit oid. + commits map[string]string + tags map[string]string } func (f gitRepo) tree(ref string) (map[string]fakeFile, bool) { @@ -69,6 +73,12 @@ func (f gitRepo) answer(expr string) any { return nil } if !hasPath { + if oid, ok := f.tags[ref]; ok { + return map[string]any{"__typename": "Tag", "target": map[string]any{"oid": oid}} + } + if oid, ok := f.commits[ref]; ok { + return map[string]any{"__typename": "Commit", "oid": oid} + } return map[string]any{"__typename": "Commit"} } if file, ok := files[p]; ok { diff --git a/gitlab/remote_files.go b/gitlab/remote_files.go new file mode 100644 index 00000000..142e3d75 --- /dev/null +++ b/gitlab/remote_files.go @@ -0,0 +1,247 @@ +package gitlab + +// Remote repository files (#254): reading the mise files of a project +// that is not checked out lists the tree once and reads the files in +// batches. +// +// The listing is REST: GET /projects/:id/repository/tree?recursive=true +// with keyset pagination (100 entries a page). GraphQL's Repository.tree +// also pages at 100, but it loads the whole tree and pages through it in +// memory on every request, and a query is bounded by complexity 250 and +// 10,000 characters. The contents are GraphQL: Repository.blobs(paths:) +// reads many files in one query (GitLab 13.11 and later), where REST +// reads one file a request. The sizes are asked first, so a file over the +// cap is never downloaded. When the blobs query fails (an older instance), +// each file is read over REST, its size checked first. + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/machinebox/graphql" + gitlab "gitlab.com/gitlab-org/api/client-go" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/repofs" +) + +const ( + // treePageSize is the most entries GitLab returns per tree page. + treePageSize = 100 + // blobsPerQuery bounds the files one blobs query reads: each path + // costs 1 of the 250 complexity points. + blobsPerQuery = 50 + // maxBlobBytes is the largest file whose content is used (the mise + // scan reads 2 MiB at most). + maxBlobBytes = 2 << 20 +) + +// RemoteFiles reads a GitLab project at one ref as a repofs.Source. +type RemoteFiles struct { + rest *gitlab.Client + gql *graphql.Client + token string + project string + ref string +} + +// NewRemoteFiles reads project (its full path) at ref (a commit SHA or a +// branch) on the instance at instanceURL. +func NewRemoteFiles(project, ref, token, instanceURL string, conf *configuration.Configuration) (*RemoteFiles, error) { + rest, err := GetNewGitlabClient(token, instanceURL, conf) + if err != nil { + return nil, err + } + return &RemoteFiles{rest: rest, gql: GetGraphQLClient(instanceURL, conf), token: token, project: project, ref: ref}, nil +} + +// List implements repofs.Source: the whole repository, a page of 100 +// entries a request. +func (r *RemoteFiles) List(ctx context.Context) ([]repofs.Entry, error) { + opt := &gitlab.ListTreeOptions{ + ListOptions: gitlab.ListOptions{Pagination: "keyset", PerPage: treePageSize}, + Ref: new(r.ref), + Recursive: new(true), + } + var entries []repofs.Entry + reqOpts := []gitlab.RequestOptionFunc{gitlab.WithContext(ctx)} + for { + nodes, resp, err := r.rest.Repositories.ListTree(r.project, opt, reqOpts...) + if err != nil && entries == nil && resp != nil && resp.StatusCode == http.StatusNotFound { + // An empty repository has no tree (404 "Tree Not Found"): it + // holds no mise file. The ref comes from the API itself, so a + // 404 is not a ref that does not exist. + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list the repository tree of %s at %s: %w", r.project, r.ref, err) + } + for _, n := range nodes { + mode, err := strconv.ParseUint(n.Mode, 8, 32) + if err != nil { + continue + } + if m, ok := repofs.GitMode(uint32(mode)); ok { + entries = append(entries, repofs.Entry{Path: n.Path, Mode: m}) + } + } + next, more := gitlab.WithNext(resp) + if !more { + return entries, nil + } + reqOpts = []gitlab.RequestOptionFunc{gitlab.WithContext(ctx), next} + } +} + +// sizesQuery asks each file's size, contentQuery its text: the text is +// only asked for files under the cap. +const ( + sizesQuery = `query remoteFileSizes($fullPath: ID!, $ref: String!, $paths: [String!]!, $first: Int!) { + project(fullPath: $fullPath) { + repository { + blobs(ref: $ref, paths: $paths, first: $first) { + nodes { path rawSize } + } + } + } +}` + contentQuery = `query remoteFiles($fullPath: ID!, $ref: String!, $paths: [String!]!, $first: Int!) { + project(fullPath: $fullPath) { + repository { + blobs(ref: $ref, paths: $paths, first: $first) { + nodes { path rawSize rawTextBlob } + } + } + } +}` +) + +type blobsResponse struct { + Project *struct { + Repository *struct { + Blobs struct { + Nodes []blobNode `json:"nodes"` + } `json:"blobs"` + } `json:"repository"` + } `json:"project"` +} + +// Read implements repofs.Source. A path GitLab does not return is left +// out; a file over 2 MiB comes back with its size and no content, and a +// file without text (binary) with an error. +func (r *RemoteFiles) Read(ctx context.Context, paths []string) (map[string]repofs.Blob, error) { + out := map[string]repofs.Blob{} + for start := 0; start < len(paths); start += blobsPerQuery { + chunk := paths[start:min(start+blobsPerQuery, len(paths))] + if err := r.readGraphQL(ctx, chunk, out); err != nil { + logger.WithError(err).Debug("blobs query failed, reading the files over REST") + r.readREST(ctx, chunk, out) + } + } + return out, nil +} + +// readGraphQL reads chunk in two queries: every size, then the text of +// the files under the cap. A file over it comes back with its size only. +func (r *RemoteFiles) readGraphQL(ctx context.Context, chunk []string, out map[string]repofs.Blob) error { + sizes, err := r.blobs(ctx, sizesQuery, chunk) + if err != nil { + return err + } + var small []string + for _, n := range sizes { + if size := int64(n.RawSize); size > maxBlobBytes { + out[n.Path] = repofs.Blob{Size: size} + } else { + small = append(small, n.Path) + } + } + if len(small) == 0 { + return nil + } + nodes, err := r.blobs(ctx, contentQuery, small) + if err != nil { + return err + } + for _, n := range nodes { + size := int64(n.RawSize) + switch { + case size > maxBlobBytes: + out[n.Path] = repofs.Blob{Size: size} + case n.RawTextBlob == nil: + out[n.Path] = repofs.Blob{Size: size, Err: errors.New("binary file")} + default: + out[n.Path] = repofs.Blob{Data: []byte(*n.RawTextBlob), Size: size} + } + } + return nil +} + +type blobNode = struct { + Path string `json:"path"` + RawSize bigInt `json:"rawSize"` + RawTextBlob *string `json:"rawTextBlob"` +} + +// blobs runs one blobs query over paths. +func (r *RemoteFiles) blobs(ctx context.Context, query string, paths []string) ([]blobNode, error) { + req := graphql.NewRequest(query) + req.Var("fullPath", r.project) + req.Var("ref", r.ref) + req.Var("paths", paths) + req.Var("first", len(paths)) + req.Header.Add("Authorization", "Bearer "+r.token) + var resp blobsResponse + if err := r.gql.Run(ctx, req, &resp); err != nil { + return nil, err + } + if resp.Project == nil || resp.Project.Repository == nil { + return nil, fmt.Errorf("project %s not found", r.project) + } + return resp.Project.Repository.Blobs.Nodes, nil +} + +// readREST reads each file over REST, its size first (a HEAD request) so +// a file over the cap is never downloaded: the fallback when the blobs +// query is not available, two requests a file. +func (r *RemoteFiles) readREST(ctx context.Context, chunk []string, out map[string]repofs.Blob) { + for _, p := range chunk { + meta, resp, err := r.rest.RepositoryFiles.GetFileMetaData(r.project, p, &gitlab.GetFileMetaDataOptions{Ref: new(r.ref)}, gitlab.WithContext(ctx)) + switch { + case err != nil && resp != nil && resp.StatusCode == http.StatusNotFound: + continue // nothing there: the caller reports it + case err != nil: + out[p] = repofs.Blob{Err: err} + continue + case meta.Size > maxBlobBytes: + out[p] = repofs.Blob{Size: meta.Size} + continue + } + data, _, err := r.rest.RepositoryFiles.GetRawFile(r.project, p, &gitlab.GetRawFileOptions{Ref: new(r.ref)}, gitlab.WithContext(ctx)) + switch { + case err != nil: + out[p] = repofs.Blob{Err: err} + case len(data) > maxBlobBytes: + out[p] = repofs.Blob{Size: int64(len(data))} + default: + out[p] = repofs.Blob{Data: data, Size: int64(len(data))} + } + } +} + +// bigInt reads a GraphQL BigInt, which GitLab sends as a string (a number +// is read too). +type bigInt int64 + +func (b *bigInt) UnmarshalJSON(data []byte) error { + n, err := strconv.ParseInt(strings.Trim(string(data), `"`), 10, 64) + if err != nil { + return err + } + *b = bigInt(n) + return nil +} diff --git a/gitlab/remote_files_test.go b/gitlab/remote_files_test.go new file mode 100644 index 00000000..8b4d3dcd --- /dev/null +++ b/gitlab/remote_files_test.go @@ -0,0 +1,330 @@ +package gitlab + +import ( + "context" + "encoding/json" + "fmt" + "io/fs" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "sort" + "strconv" + "strings" + "testing" + "time" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/repofs" +) + +// remoteProject serves the tree listing (keyset pages of pageSize), the +// blobs GraphQL query and the raw file endpoint of project g/p from +// files; blobsDown makes the GraphQL query fail. +type remoteProject struct { + files map[string]string // path -> content + modes map[string]string // path -> git mode, default 100644 + pageSize int + blobsDown bool + empty bool // the repository has no commit: the tree is a 404 + treeDown bool // the tree endpoint answers 500 + rawDown bool // the raw and metadata endpoints answer 500 + + treeCalls, gqlCalls, metaCalls, rawCalls int + // textAsked lists the paths whose text a blobs query asked for. + textAsked []string +} + +func (p *remoteProject) server(t *testing.T) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + esc := r.URL.EscapedPath() + switch { + case esc == "/api/v4/projects/g%2Fp/repository/tree": + p.treeCalls++ + switch { + case p.empty: + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"404 Tree Not Found"}`)) + return + case p.treeDown: + w.WriteHeader(http.StatusInternalServerError) + return + } + p.tree(t, w, r) + case r.URL.Path == "/api/graphql": + p.gqlCalls++ + p.blobs(t, w, r) + case strings.HasPrefix(esc, "/api/v4/projects/g%2Fp/repository/files/"): + raw := strings.HasSuffix(esc, "/raw") + if raw { + p.rawCalls++ + } else { + p.metaCalls++ + } + if p.rawDown { + w.WriteHeader(http.StatusInternalServerError) + return + } + name, _ := url.PathUnescape(strings.TrimSuffix(strings.TrimPrefix(esc, "/api/v4/projects/g%2Fp/repository/files/"), "/raw")) + c, ok := p.files[name] + if !ok { + http.NotFound(w, r) + return + } + if !raw { + w.Header().Set("X-Gitlab-Size", strconv.Itoa(len(c))) + return + } + _, _ = w.Write([]byte(c)) + default: + t.Errorf("unexpected request %s", esc) + http.NotFound(w, r) + } + })) +} + +// entries lists every file and directory, sorted, as GitLab's recursive +// tree does. +func (p *remoteProject) entries() []map[string]string { + seen := map[string]bool{} + var out []map[string]string + for f := range p.files { + parts := strings.Split(f, "/") + for i := 1; i < len(parts); i++ { + d := strings.Join(parts[:i], "/") + if !seen[d] { + seen[d] = true + out = append(out, map[string]string{"path": d, "type": "tree", "mode": "040000"}) + } + } + mode := p.modes[f] + if mode == "" { + mode = "100644" + } + out = append(out, map[string]string{"path": f, "type": "blob", "mode": mode}) + } + sort.Slice(out, func(i, j int) bool { return out[i]["path"] < out[j]["path"] }) + return out +} + +func (p *remoteProject) tree(t *testing.T, w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("recursive") != "true" || q.Get("pagination") != "keyset" || q.Get("ref") != "abc" { + t.Errorf("tree query = %v, want recursive keyset at ref abc", q) + } + all := p.entries() + start, _ := strconv.Atoi(q.Get("page_token")) + end := min(start+p.pageSize, len(all)) + if end < len(all) { + next := fmt.Sprintf("http://%s%s?pagination=keyset&per_page=100&recursive=true&ref=abc&page_token=%d", r.Host, r.URL.Path, end) + w.Header().Set("Link", fmt.Sprintf("<%s>; rel=\"next\"", next)) + } + _ = json.NewEncoder(w).Encode(all[start:end]) +} + +func (p *remoteProject) blobs(t *testing.T, w http.ResponseWriter, r *http.Request) { + var req struct { + Query string `json:"query"` + Variables struct { + FullPath string `json:"fullPath"` + Ref string `json:"ref"` + Paths []string `json:"paths"` + } `json:"variables"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatal(err) + } + if p.blobsDown { + _ = json.NewEncoder(w).Encode(map[string]any{"errors": []map[string]any{{"message": "Field 'blobs' doesn't exist"}}}) + return + } + if req.Variables.FullPath != "g/p" || req.Variables.Ref != "abc" { + t.Errorf("blobs query for %s at %s, want g/p at abc", req.Variables.FullPath, req.Variables.Ref) + } + withText := strings.Contains(req.Query, "rawTextBlob") + var nodes []map[string]any + for _, path := range req.Variables.Paths { + c, ok := p.files[path] + if !ok { + continue + } + n := map[string]any{"path": path, "rawSize": strconv.Itoa(len(c))} + if withText { + p.textAsked = append(p.textAsked, path) + n["rawTextBlob"] = c + if strings.HasPrefix(c, "\x00") { + n["rawTextBlob"] = nil + } + } + nodes = append(nodes, n) + } + _ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"project": map[string]any{ + "repository": map[string]any{"blobs": map[string]any{"nodes": nodes}}, + }}}) +} + +func newRemote(t *testing.T, p *remoteProject) *RemoteFiles { + t.Helper() + srv := p.server(t) + t.Cleanup(srv.Close) + r, err := NewRemoteFiles("g/p", "abc", "glpat-test", srv.URL, &configuration.Configuration{HTTPClientTimeout: 30 * time.Second}) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestRemoteFilesList(t *testing.T) { + p := &remoteProject{pageSize: 2, files: map[string]string{ + "mise.toml": "a", + "svc/mise.toml": "b", + "svc/mise-tasks/build": "c", + "link": "svc", + "node_modules/x/mise.toml": "d", + "sub": "", + }, modes: map[string]string{"svc/mise-tasks/build": "100755", "link": "120000", "sub": "160000"}} + r := newRemote(t, p) + entries, err := r.List(context.Background()) + if err != nil { + t.Fatalf("List: %v", err) + } + var got []string + for _, e := range entries { + got = append(got, e.Path+" "+e.Mode.String()) + } + want := []string{ + "link Lrwxrwxrwx", "mise.toml -rw-r--r--", "node_modules drwxr-xr-x", "node_modules/x drwxr-xr-x", + "node_modules/x/mise.toml -rw-r--r--", "svc drwxr-xr-x", "svc/mise-tasks drwxr-xr-x", + "svc/mise-tasks/build -rwxr-xr-x", "svc/mise.toml -rw-r--r--", + } + if !reflect.DeepEqual(got, want) { + t.Errorf("entries =\n%v\nwant\n%v", got, want) + } + // 10 entries (sub included), 2 a page. + if p.treeCalls != 5 { + t.Errorf("%d tree requests, want 5", p.treeCalls) + } +} + +func TestRemoteFilesRead(t *testing.T) { + cases := []struct { + name string + blobsDown bool + wantGQL int + wantMeta int + wantRaw int + }{ + // 54 files: two chunks, each a sizes query then a text query. + {name: "sizes then text, one query each per 50 files", wantGQL: 4}, + // Each chunk's sizes query fails; every file is sized over REST, + // and only those that exist under the cap are downloaded (52: + // not gone.toml, not huge.toml). + {name: "REST, size first, when the blobs query fails", blobsDown: true, wantGQL: 2, wantMeta: 54, wantRaw: 52}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + files := map[string]string{ + "mise.toml": "[tools]\n", + "bin.toml": "\x00\x01", + "huge.toml": strings.Repeat("a", maxBlobBytes+1), + } + paths := []string{"mise.toml", "bin.toml", "huge.toml", "gone.toml"} + for i := range blobsPerQuery { + name := "many/f" + strconv.Itoa(i) + files[name] = name + paths = append(paths, name) + } + p := &remoteProject{files: files, blobsDown: tc.blobsDown} + r := newRemote(t, p) + got, err := r.Read(context.Background(), paths) + if err != nil { + t.Fatalf("Read: %v", err) + } + if p.gqlCalls != tc.wantGQL || p.metaCalls != tc.wantMeta || p.rawCalls != tc.wantRaw { + t.Errorf("%d GraphQL, %d metadata and %d raw requests, want %d, %d and %d", + p.gqlCalls, p.metaCalls, p.rawCalls, tc.wantGQL, tc.wantMeta, tc.wantRaw) + } + for _, asked := range p.textAsked { + if asked == "huge.toml" { + t.Errorf("the text of huge.toml was asked, want only its size") + } + } + if b := got["mise.toml"]; string(b.Data) != "[tools]\n" || b.Err != nil { + t.Errorf("mise.toml = %+v", b) + } + if b := got["huge.toml"]; b.Size != maxBlobBytes+1 || b.Data != nil { + t.Errorf("huge.toml = size %d, %d bytes; want its size and no content", b.Size, len(b.Data)) + } + if _, ok := got["gone.toml"]; ok { + t.Errorf("gone.toml returned, want it left out") + } + if b := got["many/f49"]; string(b.Data) != "many/f49" { + t.Errorf("many/f49 = %q", b.Data) + } + // GraphQL gives no text for a binary file; REST gives its bytes, + // which the scan then fails to parse. Either way it is unreadable. + if b := got["bin.toml"]; (b.Err == nil) != tc.blobsDown { + t.Errorf("bin.toml = %+v; want an error over GraphQL only", b) + } + }) + } +} + +// TestRemoteFilesFS: a listing and reads serve repofs end to end. +func TestRemoteFilesFS(t *testing.T) { + p := &remoteProject{pageSize: 100, files: map[string]string{"svc/mise.toml": "x", "link": "svc"}, modes: map[string]string{"link": "120000"}} + r := newRemote(t, p) + entries, err := r.List(context.Background()) + if err != nil { + t.Fatal(err) + } + f := repofs.New(entries) + if err := f.Fetch(context.Background(), r, f.Paths(func(string, fs.FileMode) bool { return true })); err != nil { + t.Fatal(err) + } + if got, err := fs.ReadFile(f, "link/mise.toml"); err != nil || string(got) != "x" { + t.Errorf("ReadFile through the link = %q, %v; want x", got, err) + } +} + +// TestRemoteFilesListErrors: an empty repository lists nothing, any other +// failure stops the read. +func TestRemoteFilesListErrors(t *testing.T) { + cases := []struct { + name string + p *remoteProject + wantErr string + }{ + {name: "an empty repository has no entry", p: &remoteProject{pageSize: 100, empty: true}}, + {name: "a server error stops the read", p: &remoteProject{pageSize: 100, treeDown: true}, wantErr: "list the repository tree of g/p at abc"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + entries, err := newRemote(t, tc.p).List(context.Background()) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Errorf("List error = %v, want %q", err, tc.wantErr) + } + return + } + if err != nil || entries != nil { + t.Errorf("List = %v, %v; want no entry and no error", entries, err) + } + }) + } +} + +// TestRemoteFilesReadRESTErrors: over REST, a server error is the file's +// error, a binary file is returned as is (the scan then fails to parse it). +func TestRemoteFilesReadRESTErrors(t *testing.T) { + p := &remoteProject{files: map[string]string{"mise.toml": "x"}, blobsDown: true, rawDown: true} + got, err := newRemote(t, p).Read(context.Background(), []string{"mise.toml"}) + if err != nil { + t.Fatalf("Read: %v", err) + } + if b, ok := got["mise.toml"]; !ok || b.Err == nil { + t.Errorf("mise.toml = %+v, %v; want its error", b, ok) + } +} diff --git a/go.mod b/go.mod index 5085114f..c673edee 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,7 @@ require ( github.com/machinebox/graphql v0.2.2 github.com/muesli/termenv v0.16.0 github.com/open-policy-agent/opa v1.21.2 + github.com/pelletier/go-toml/v2 v2.2.4 github.com/schollz/progressbar/v3 v3.19.1 github.com/sigstore/protobuf-specs v0.5.1 github.com/sigstore/sigstore-go v1.3.0 diff --git a/go.sum b/go.sum index 54fd837b..2afb21fe 100644 --- a/go.sum +++ b/go.sum @@ -354,6 +354,8 @@ github.com/open-policy-agent/opa v1.21.2/go.mod h1:mHDS61rXyiZ+9bLINSK634BcbPZcs github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= diff --git a/internal/ir/mise.go b/internal/ir/mise.go new file mode 100644 index 00000000..3b2ac38d --- /dev/null +++ b/internal/ir/mise.go @@ -0,0 +1,170 @@ +package ir + +// MiseScan is the mise view of a repository, read from the local +// checkout by packagemanager/mise. The policies of mise-en-place read it +// as input.pipeline.mise. A mise file that cannot be read stops the run +// before the policies (mise.ReadError), so the scan holds readable files +// only. +type MiseScan struct { + // Configs lists every committed mise config file, in path order. + Configs []MiseConfig `json:"configs,omitempty"` + // ToolVersions lists the tools declared in a .tool-versions file that + // no mise config of the same directory declares. mise never locks + // .tool-versions, so these tools are never pinned by a lockfile. + // Read only when the lockfile check runs. + ToolVersions []MiseToolVersionsEntry `json:"toolVersions,omitempty"` + // LocalConfigs lists the mise local configs (mise.local.toml, ...) + // committed to the repository (git tracks them), outside exemptPaths. + LocalConfigs []string `json:"localConfigs,omitempty"` + // Projects lists every mise project directory (one holding a config + // mise loads by default) with the tasks mise offers there, in + // directory order. + Projects []MiseProject `json:"projects,omitempty"` +} + +// MiseProject is a directory holding at least one mise config. +type MiseProject struct { + // Dir is the project directory, relative to the repository root + // ("" for the root). + Dir string `json:"dir"` + // Path is the project's config the findings point at. + Path string `json:"path"` + // Tasks lists the tasks mise offers in the project: its own and those + // of every parent directory's configs, sorted by name. + Tasks []MiseTask `json:"tasks,omitempty"` + // UnreadIncludes lists the task_config.includes entries, of the + // project or a parent, that Plumber cannot read from the checkout: + // remote includes (git::, oci::, zip::), templates and paths outside + // the repository. Their tasks are not in Tasks. + UnreadIncludes []string `json:"unreadIncludes,omitempty"` +} + +// MiseTask is one task: a [tasks.] table, an entry of a TOML task +// file, or an executable file of a task directory. +type MiseTask struct { + Name string `json:"name"` + Aliases []string `json:"aliases,omitempty"` + // Source is the file that declares the task. + Source string `json:"source"` +} + +// MiseConfig is one mise config file (mise.toml, .config/mise/config.toml, +// a conf.d fragment, mise..toml, ...). +type MiseConfig struct { + // Path is the config file, relative to the repository root. + Path string `json:"path"` + // Lockfile is the lockfile mise writes this config's tools to. + Lockfile MiseLockfile `json:"lockfile"` + // LockfileDisabled is true when lockfiles are off for this config: + // it sets `[settings] lockfile = false`, or inherits it from a config + // of a parent directory (LockfileDisabledBy). + LockfileDisabled bool `json:"lockfileDisabled,omitempty"` + // LockfileDisabledBy is the config that turns lockfiles off when this + // config inherits the setting; empty when it sets it itself. + LockfileDisabledBy string `json:"lockfileDisabledBy,omitempty"` + // LockfileUnknown is true for a subproject config when a root config + // cannot be read: its `[monorepo] lockfile` setting decides whether + // the subproject locks into its own lockfile or the root one, so the + // pairing is unknown and the lockfile is not judged. This only + // happens when the root config is under exemptPaths: otherwise the + // unreadable root stops the run. + LockfileUnknown bool `json:"lockfileUnknown,omitempty"` + // Tools lists the tool requests of the config's [tools] table. + Tools []MiseTool `json:"tools,omitempty"` + // SourceSettings lists the [settings] that redirect where mise fetches + // from (url_replacements targets, aqua registries, mirrors), one entry + // per URL, sorted. + SourceSettings []MiseSetting `json:"sourceSettings,omitempty"` + // Local is true for a *.local.toml file. mise loads it when it is + // committed, so the sources and versions checks judge it; the + // lockfile check does not, since it is meant to be personal. + Local bool `json:"local,omitempty"` +} + +// MiseSetting is one value of a mise setting. +type MiseSetting struct { + // Name is the setting's dotted name ("aqua.registries"), + // "plugins." for a [plugins] entry, "env." for an [env] + // index variable. + Name string `json:"name"` + // Value is one URL or path the setting points at. + Value string `json:"value"` +} + +// MiseToolOption is one tool option that changes where mise downloads the +// tool from (api_url, url, platforms..url). +type MiseToolOption struct { + Name string `json:"name"` + Value string `json:"value"` +} + +// MiseLockfile is the lockfile a config pairs with. +type MiseLockfile struct { + // Path is where the lockfile is expected, relative to the repository + // root, whether or not it exists. + Path string `json:"path"` + // Present is true when the lockfile exists and was parsed. + Present bool `json:"present"` + // Version is the file's lockfile_version, 0 when absent (format 0 + // has no field). + Version int `json:"version"` +} + +// MiseTool is one tool request from a config's [tools] table. A tool +// declared with several versions (an array) yields one MiseTool per +// version. +type MiseTool struct { + // Name is the tool key without its bracketed options + // ("node", "aqua:jqlang/jq"). + Name string `json:"name"` + // Request is the version request as written ("24", "latest"). + Request string `json:"request"` + // Unreadable is set when the request cannot be read statically (a + // template, no version); it says why. The tool is then never matched + // to a lock entry. + Unreadable string `json:"unreadable,omitempty"` + // Locked is the lock entry whose specifiers contain Request; nil when + // none does, the lockfile is missing, or its format (0) has no + // specifiers. + Locked *MiseLockEntry `json:"locked,omitempty"` + // SourceOptions lists the options of the tool's key or table that + // change where it is downloaded from, sorted by name. + SourceOptions []MiseToolOption `json:"sourceOptions,omitempty"` +} + +// MiseLockEntry is one [[tools.]] entry of a mise.lock. +type MiseLockEntry struct { + Version string `json:"version"` + Backend string `json:"backend,omitempty"` + Platforms []MiseLockPlatform `json:"platforms,omitempty"` +} + +// MiseLockPlatform is one "platforms." table of a lock entry. +type MiseLockPlatform struct { + // Platform is the os-arch key ("linux-x64", "macos-arm64"). + Platform string `json:"platform"` + // URL is the download URL (url, or url_api when only that is set). + URL string `json:"url,omitempty"` + // Checksum is ":", empty when not recorded. + Checksum string `json:"checksum,omitempty"` + // Provenance names the recorded provenance (slsa, cosign, minisign, + // github-attestations), empty when not recorded. + Provenance string `json:"provenance,omitempty"` +} + +// MiseToolVersionsEntry is a tool declared in a .tool-versions file and +// in no mise config of the same directory. +type MiseToolVersionsEntry struct { + // Path is the .tool-versions file, relative to the repository root. + Path string `json:"path"` + Name string `json:"name"` +} + +// MiseOrNil returns the mise scan, nil on a nil pipeline or when the +// collector did not run. +func (p *NormalizedPipeline) MiseOrNil() *MiseScan { + if p == nil { + return nil + } + return p.Mise +} diff --git a/internal/ir/pipeline.go b/internal/ir/pipeline.go index 7b8f4d92..1c649493 100644 --- a/internal/ir/pipeline.go +++ b/internal/ir/pipeline.go @@ -92,6 +92,19 @@ type NormalizedPipeline struct { // single "Scanning" tick rather than per-file). WorkflowFileCount int `json:"-"` + // RemoteRev is the git expression (a commit oid, or the ref as the + // remote GitHub collector resolved it) the workflows were read at, so + // every other remote read (the mise files) reads the same commit. + // Empty in local-clone mode. A collector-side record, never part of + // the OPA evaluation input. + RemoteRev string `json:"-"` + + // MiseNotRead says why the mise files of a remote repository were not + // read (too large to read remotely). Mise stays nil and mise-en-place + // is reported not evaluated, the run degraded. A collector-side + // record, never part of the OPA evaluation input. + MiseNotRead string `json:"-"` + // AnalyzedWorkflows are the GitHub workflow files this scan read, each // with its repo-relative path and content (#443). Carried json:"-" like // WorkflowFileCount above: a collector-side record for the JSON report, @@ -239,6 +252,13 @@ type NormalizedPipeline struct { // base-image extracted so policies can check pinning state. Dockerfiles []Dockerfile `json:"dockerfiles,omitempty"` + // Mise is what the mise collector (packagemanager/mise) read from the + // local checkout: every committed mise config, its lockfile and the + // tools declared only in .tool-versions. nil when the collector did not + // run (no local checkout), so mise-en-place reports + // not evaluated instead of passing. + Mise *MiseScan `json:"mise,omitempty"` + // AdvisoryWarnings collects one human-readable line per action whose // known-CVE check could not be completed because the pinned commit // could not be resolved to a version (the action repo's tag list was diff --git a/internal/repofs/repofs.go b/internal/repofs/repofs.go new file mode 100644 index 00000000..e372f148 --- /dev/null +++ b/internal/repofs/repofs.go @@ -0,0 +1,498 @@ +// Package repofs serves a remote repository as a read-only file system +// built from its tree listing, so code written for a checkout (the mise +// scan) reads a repository that is not checked out. +// +// The listing is read first, then file contents on demand in batches: a +// read of a file whose content was not fetched fails with ErrNotFetched +// and is recorded. Rounds fetches every recorded path in one call and +// runs the reader again, so a scan costs one listing and one content +// fetch per round, never one request per file. +package repofs + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "io/fs" + "path" + "slices" + "sort" + "strings" + "time" +) + +// ErrNotFetched is the error of a read the listing or the fetched +// contents cannot answer yet. Rounds fetches what it names. +var ErrNotFetched = errors.New("not fetched from the remote repository") + +// ErrTooLarge is the error of a repository too large to read remotely: +// a listing the remote truncated, or more files to fetch than MaxFetch. +// The caller reports what reads it as not evaluated, not the run as +// failed. +var ErrTooLarge = errors.New("repository too large to read remotely") + +const ( + // MaxRounds bounds the fetch rounds of Rounds: the first fetch reads + // every file a reader wants by name, a later round only what it + // reaches (a task include, a symlink target). + MaxRounds = 4 + // MaxFetch bounds the files one FS fetches over all rounds. The + // repository is not trusted: past it, a crafted repository (many + // symlinks, huge task directories) would spend the user's API quota. + MaxFetch = 5000 + // maxLinks bounds the symlinks one path resolution follows, as the OS + // does (ELOOP). + maxLinks = 255 + // maxLinkTarget bounds a symlink target, as the OS does (PATH_MAX). A + // longer one is refused: each follow requeues the whole target. + maxLinkTarget = 4096 +) + +// Entry is one file of the tree listing: a path relative to the +// repository root (slash separated) and its mode (a regular file with +// its permission bits, fs.ModeSymlink, or fs.ModeDir). +type Entry struct { + Path string + Mode fs.FileMode +} + +// GitMode converts a git tree entry mode (100644, 100755, 120000, 40000) +// to an fs.FileMode. A submodule (160000) or an unknown mode is not a +// file of the repository: ok is false. +func GitMode(mode uint32) (m fs.FileMode, ok bool) { + switch mode { + case 0o100644, 0o100664: + return 0o644, true + case 0o100755: + return 0o755, true + case 0o120000: + return fs.ModeSymlink | 0o777, true + case 0o40000: + return fs.ModeDir | 0o755, true + } + return 0, false +} + +// Blob is the fetched content of one file. Err is set when the remote +// could not give it (binary, truncated, too large); Size is the file +// size the remote reports, which may exceed len(Data). +type Blob struct { + Data []byte + Size int64 + Err error +} + +// Source reads a remote repository. +type Source interface { + // List returns every entry of the repository. + List(ctx context.Context) ([]Entry, error) + // Read returns the content of each path. A path left out of the + // result counts as unreadable. + Read(ctx context.Context, paths []string) (map[string]Blob, error) +} + +type node struct { + mode fs.FileMode + children map[string]bool // directories only +} + +// FS is the repository tree. It implements fs.FS, fs.StatFS, +// fs.ReadDirFS and fs.ReadLinkFS, plus Resolve (mise.FS). It is not safe +// for concurrent use. +type FS struct { + nodes map[string]*node + blobs map[string]Blob + misses map[string]bool + fetched int +} + +// New returns the FS of a tree listing. +func New(entries []Entry) *FS { + f := &FS{ + nodes: map[string]*node{".": {mode: fs.ModeDir | 0o755, children: map[string]bool{}}}, + blobs: map[string]Blob{}, + misses: map[string]bool{}, + } + for _, e := range entries { + f.put(e.Path, e.Mode) + } + return f +} + +// put adds p and the directories above it. +func (f *FS) put(p string, mode fs.FileMode) { + p = clean(p) + if p == "." { + return + } + if _, ok := f.nodes[p]; ok { + return + } + n := &node{mode: mode} + if mode.IsDir() { + n.children = map[string]bool{} + } + f.nodes[p] = n + parent := path.Dir(p) + f.put(parent, fs.ModeDir|0o755) + f.nodes[parent].children[path.Base(p)] = true +} + +func clean(p string) string { + p = strings.Trim(p, "/") + if p == "" { + return "." + } + return path.Clean(p) +} + +// Paths returns the files of the listing (not directories) that keep +// returns true for, in path order. +func (f *FS) Paths(keep func(p string, mode fs.FileMode) bool) []string { + var out []string + for p, n := range f.nodes { + if n.mode.IsDir() { + continue + } + if _, fetched := f.blobs[p]; fetched { + continue + } + if keep(p, n.mode) { + out = append(out, p) + } + } + sort.Strings(out) + return out +} + +// Fetch reads the content of paths through src. A path src leaves out is +// unreadable rather than fetched again. +func (f *FS) Fetch(ctx context.Context, src Source, paths []string) error { + var todo []string + for _, p := range paths { + if _, done := f.blobs[p]; !done { + todo = append(todo, p) + } + } + if len(todo) == 0 { + return nil + } + if f.fetched+len(todo) > MaxFetch { + return fmt.Errorf("%w: more than %d files to read", ErrTooLarge, MaxFetch) + } + f.fetched += len(todo) + got, err := src.Read(ctx, todo) + if err != nil { + return err + } + for _, p := range todo { + b, ok := got[p] + if !ok { + b = Blob{Err: errors.New("the remote repository did not return it")} + } + f.blobs[p] = b + } + return nil +} + +// Rounds runs read, then fetches every file read reached but the FS had +// no content for, and runs read again, until a run reaches nothing new. +// It stops with an error after maxRounds fetches. +func Rounds[T any](ctx context.Context, f *FS, src Source, maxRounds int, read func(*FS) (T, error)) (T, error) { + for round := 0; ; round++ { + v, err := read(f) + missed := f.takeMisses() + if len(missed) == 0 { + return v, err + } + if round == maxRounds { + var zero T + return zero, fmt.Errorf("remote repository: still reaching unfetched files after %d rounds: %s", maxRounds, strings.Join(missed, ", ")) + } + if err := f.Fetch(ctx, src, missed); err != nil { + var zero T + return zero, err + } + } +} + +func (f *FS) takeMisses() []string { + out := make([]string, 0, len(f.misses)) + for p := range f.misses { + out = append(out, p) + } + sort.Strings(out) + f.misses = map[string]bool{} + return out +} + +// lookup returns the node at the exact tree path p (no symlink followed). +func (f *FS) lookup(p string) (*node, error) { + if n, ok := f.nodes[p]; ok { + return n, nil + } + return nil, fs.ErrNotExist +} + +// content returns the fetched content of the file at tree path p. +func (f *FS) content(p string) (Blob, error) { + b, ok := f.blobs[p] + if !ok { + f.misses[p] = true + return Blob{}, ErrNotFetched + } + return b, b.Err +} + +var errOutside = errors.New("resolves outside the repository") + +// walk resolves name to a tree path, following every symlink on the way, +// and the last one too when followLast is set. A link's target is read +// relative to the link's directory; an absolute target or one climbing +// above the root leaves the repository. +func (f *FS) walk(name string, followLast bool) (string, error) { + queue := strings.Split(name, "/") + resolved := "." + links := 0 + for len(queue) > 0 { + c := queue[0] + queue = queue[1:] + switch c { + case "", ".": + continue + case "..": + if resolved == "." { + return "", errOutside + } + resolved = path.Dir(resolved) + continue + } + next := path.Join(resolved, c) + n, err := f.lookup(next) + if err != nil { + return "", err + } + if n.mode&fs.ModeSymlink != 0 && (len(queue) > 0 || followLast) { + links++ + if links > maxLinks { + return "", errors.New("too many levels of symbolic links") + } + b, err := f.content(next) + if err != nil { + return "", err + } + // A target over the cap, or one the remote gave no text for (a + // link over 2 MiB), cannot be resolved: refuse it rather than + // read it as "" (the link's own directory). + if b.Size > maxLinkTarget || len(b.Data) > maxLinkTarget { + return "", errors.New("symbolic link target too long") + } + target := string(b.Data) + if target == "" { + return "", errors.New("empty symbolic link target") + } + if path.IsAbs(target) { + return "", errOutside + } + queue = append(strings.Split(target, "/"), queue...) + continue + } + if len(queue) > 0 && !n.mode.IsDir() { + return "", fs.ErrNotExist + } + resolved = next + } + return resolved, nil +} + +func pathErr(op, name string, err error) error { + return &fs.PathError{Op: op, Path: name, Err: err} +} + +// Lstat describes name without following a final symlink. +func (f *FS) Lstat(name string) (fs.FileInfo, error) { + if !fs.ValidPath(name) { + return nil, pathErr("lstat", name, fs.ErrInvalid) + } + if name == "." { + return f.info(".", f.nodes["."]), nil + } + parent, err := f.walk(path.Dir(name), true) + if err != nil { + return nil, pathErr("lstat", name, err) + } + p := path.Join(parent, path.Base(name)) + n, err := f.lookup(p) + if err != nil { + return nil, pathErr("lstat", name, err) + } + return f.info(p, n), nil +} + +// Resolve returns name with every symlink resolved, with the semantics +// of mise.FS.Resolve. +func (f *FS) Resolve(name string) (string, error) { + if _, err := f.Lstat(name); err != nil { + return "", err + } + p, err := f.walk(name, true) + switch { + case err == nil: + return p, nil + case errors.Is(err, ErrNotFetched): + return "", pathErr("resolve", name, err) + case errors.Is(err, errOutside): + return "", errOutside + case errors.Is(err, fs.ErrNotExist): + // Not %w: the link exists, so its not-exist must not read as a + // missing file. + return "", errors.New("broken symlink: no such file or directory") + } + return "", err +} + +// ReadLink returns the target of the symlink name. +func (f *FS) ReadLink(name string) (string, error) { + info, err := f.Lstat(name) + if err != nil { + return "", err + } + if info.Mode()&fs.ModeSymlink == 0 { + return "", pathErr("readlink", name, fs.ErrInvalid) + } + parent, _ := f.walk(path.Dir(name), true) + b, err := f.content(path.Join(parent, path.Base(name))) + if err != nil { + return "", pathErr("readlink", name, err) + } + return string(b.Data), nil +} + +// Stat describes name, following symlinks. +func (f *FS) Stat(name string) (fs.FileInfo, error) { + if !fs.ValidPath(name) { + return nil, pathErr("stat", name, fs.ErrInvalid) + } + p, err := f.walk(name, true) + if err != nil { + return nil, pathErr("stat", name, err) + } + return f.info(p, f.nodes[p]), nil +} + +// ReadDir lists the directory name, following symlinks, in name order. +func (f *FS) ReadDir(name string) ([]fs.DirEntry, error) { + if !fs.ValidPath(name) { + return nil, pathErr("readdir", name, fs.ErrInvalid) + } + p, err := f.walk(name, true) + if err != nil { + return nil, pathErr("readdir", name, err) + } + n := f.nodes[p] + if !n.mode.IsDir() { + return nil, pathErr("readdir", name, errors.New("not a directory")) + } + names := make([]string, 0, len(n.children)) + for c := range n.children { + names = append(names, c) + } + slices.Sort(names) + out := make([]fs.DirEntry, 0, len(names)) + for _, c := range names { + cp := path.Join(p, c) + out = append(out, fs.FileInfoToDirEntry(f.info(cp, f.nodes[cp]))) + } + return out, nil +} + +// Open opens name, following symlinks. A file whose content was not +// fetched fails with ErrNotFetched. +func (f *FS) Open(name string) (fs.File, error) { + if !fs.ValidPath(name) { + return nil, pathErr("open", name, fs.ErrInvalid) + } + p, err := f.walk(name, true) + if err != nil { + return nil, pathErr("open", name, err) + } + n := f.nodes[p] + if n.mode.IsDir() { + entries, err := f.ReadDir(p) + if err != nil { + return nil, err + } + return &dirFile{info: f.info(p, n), entries: entries}, nil + } + b, err := f.content(p) + if err != nil { + return nil, pathErr("open", name, err) + } + return &file{info: f.info(p, n), r: bytes.NewReader(b.Data)}, nil +} + +// info describes the node at tree path p. A file's size is the fetched +// size, 0 until its content is fetched. +func (f *FS) info(p string, n *node) fs.FileInfo { + var size int64 + if b, ok := f.blobs[p]; ok { + size = b.Size + if size == 0 { + size = int64(len(b.Data)) + } + } + return fileInfo{name: path.Base(p), mode: n.mode, size: size} +} + +type fileInfo struct { + name string + mode fs.FileMode + size int64 +} + +func (i fileInfo) Name() string { return i.name } +func (i fileInfo) Size() int64 { return i.size } +func (i fileInfo) Mode() fs.FileMode { return i.mode } +func (i fileInfo) ModTime() time.Time { return time.Time{} } +func (i fileInfo) IsDir() bool { return i.mode.IsDir() } +func (i fileInfo) Sys() any { return nil } + +type file struct { + info fs.FileInfo + r *bytes.Reader +} + +func (f *file) Stat() (fs.FileInfo, error) { return f.info, nil } +func (f *file) Read(b []byte) (int, error) { return f.r.Read(b) } +func (f *file) Close() error { return nil } + +type dirFile struct { + info fs.FileInfo + entries []fs.DirEntry + off int +} + +func (d *dirFile) Stat() (fs.FileInfo, error) { return d.info, nil } +func (d *dirFile) Read([]byte) (int, error) { + return 0, &fs.PathError{Op: "read", Path: d.info.Name(), Err: errors.New("is a directory")} +} +func (d *dirFile) Close() error { return nil } + +// ReadDir implements fs.ReadDirFile. +func (d *dirFile) ReadDir(n int) ([]fs.DirEntry, error) { + rest := d.entries[d.off:] + if n <= 0 { + d.off = len(d.entries) + return rest, nil + } + if len(rest) == 0 { + return nil, io.EOF + } + if n > len(rest) { + n = len(rest) + } + d.off += n + return rest[:n], nil +} diff --git a/internal/repofs/repofs_test.go b/internal/repofs/repofs_test.go new file mode 100644 index 00000000..e74c4759 --- /dev/null +++ b/internal/repofs/repofs_test.go @@ -0,0 +1,355 @@ +package repofs + +import ( + "context" + "errors" + "io/fs" + "reflect" + "strconv" + "strings" + "testing" + "testing/fstest" +) + +// mapSource is a remote repository held in memory: files maps a path to +// its content; a mode of fs.ModeSymlink makes it a link to that content. +type mapSource struct { + files map[string]string + modes map[string]fs.FileMode + reads [][]string + withhold map[string]bool // paths Read leaves out +} + +func (m *mapSource) List(context.Context) ([]Entry, error) { + var entries []Entry + for p := range m.files { + mode := m.modes[p] + if mode == 0 { + mode = 0o644 + } + entries = append(entries, Entry{Path: p, Mode: mode}) + } + return entries, nil +} + +func (m *mapSource) Read(_ context.Context, paths []string) (map[string]Blob, error) { + m.reads = append(m.reads, paths) + out := map[string]Blob{} + for _, p := range paths { + if m.withhold[p] { + continue + } + if c, ok := m.files[p]; ok { + out[p] = Blob{Data: []byte(c)} + } + } + return out, nil +} + +func load(t *testing.T, src *mapSource, prefetch ...string) *FS { + t.Helper() + entries, err := src.List(context.Background()) + if err != nil { + t.Fatal(err) + } + f := New(entries) + if err := f.Fetch(context.Background(), src, prefetch); err != nil { + t.Fatal(err) + } + return f +} + +func TestGitMode(t *testing.T) { + cases := []struct { + mode uint32 + want fs.FileMode + wantOK bool + }{ + {0o100644, 0o644, true}, + {0o100755, 0o755, true}, + {0o120000, fs.ModeSymlink | 0o777, true}, + {0o40000, fs.ModeDir | 0o755, true}, + {0o160000, 0, false}, + } + for _, tc := range cases { + got, ok := GitMode(tc.mode) + if got != tc.want || ok != tc.wantOK { + t.Errorf("GitMode(%o) = %v, %v; want %v, %v", tc.mode, got, ok, tc.want, tc.wantOK) + } + } +} + +// TestFS checks the FS against testing/fstest once every file is fetched. +func TestFS(t *testing.T) { + src := &mapSource{files: map[string]string{ + "mise.toml": "[tools]\n", + "svc/mise.toml": "x", + "svc/tasks/build.sh": "#!/bin/sh\n", + "link": "svc", + "svc/deep/a/b/c.toml": "c", + }, modes: map[string]fs.FileMode{"svc/tasks/build.sh": 0o755, "link": fs.ModeSymlink | 0o777}} + f := load(t, src, "mise.toml", "svc/mise.toml", "svc/tasks/build.sh", "link", "svc/deep/a/b/c.toml") + if err := fstest.TestFS(f, "mise.toml", "svc/mise.toml", "svc/tasks/build.sh", "svc/deep/a/b/c.toml"); err != nil { + t.Fatal(err) + } + info, err := f.Stat("link/tasks/build.sh") + if err != nil || info.Mode().Perm()&0o111 == 0 { + t.Errorf("Stat through a link = %v, %v; want an executable file", info, err) + } +} + +func TestResolve(t *testing.T) { + src := &mapSource{ + files: map[string]string{ + "real/mise.toml": "x", + "in": "real", + "up": "../real", + "abs": "/etc", + "climb": "../..", + "broken": "nowhere", + "loop": "loop", + "dirlink": "real/", + }, + modes: map[string]fs.FileMode{}, + } + for _, l := range []string{"in", "up", "abs", "climb", "broken", "loop", "dirlink"} { + src.modes[l] = fs.ModeSymlink | 0o777 + } + cases := []struct { + name string + want string + wantErr string // substring; "not-exist" means fs.ErrNotExist + }{ + {name: "real/mise.toml", want: "real/mise.toml"}, + {name: "in/mise.toml", want: "real/mise.toml"}, + {name: "dirlink/mise.toml", want: "real/mise.toml"}, + {name: "real/../real/mise.toml", wantErr: "invalid"}, + {name: "missing.toml", wantErr: "not-exist"}, + {name: "in/missing.toml", wantErr: "not-exist"}, + {name: "up", wantErr: "outside the repository"}, + {name: "abs", wantErr: "outside the repository"}, + {name: "climb", wantErr: "outside the repository"}, + {name: "broken", wantErr: "broken symlink"}, + {name: "loop", wantErr: "too many levels"}, + } + f := load(t, src, "real/mise.toml", "in", "up", "abs", "climb", "broken", "loop", "dirlink") + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := f.Resolve(tc.name) + switch { + case tc.wantErr == "not-exist": + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("Resolve = %q, %v; want not-exist", got, err) + } + case tc.wantErr != "": + if err == nil || errors.Is(err, fs.ErrNotExist) || !strings.Contains(err.Error(), tc.wantErr) { + t.Errorf("Resolve = %q, %v; want an error with %q that is not not-exist", got, err, tc.wantErr) + } + case err != nil || got != tc.want: + t.Errorf("Resolve = %q, %v; want %q", got, err, tc.want) + } + }) + } +} + +func TestRounds(t *testing.T) { + cases := []struct { + name string + src *mapSource + prefetch []string + read []string // files the reader opens, each round + maxRounds int + want string + wantErr string + wantReads [][]string + }{ + { + name: "everything prefetched: no round", + src: &mapSource{files: map[string]string{"a": "A", "b": "B"}}, + prefetch: []string{"a", "b"}, + read: []string{"a", "b"}, + maxRounds: 3, + want: "AB", + wantReads: [][]string{{"a", "b"}}, + }, + { + name: "the files a run reaches are fetched in one batch", + src: &mapSource{files: map[string]string{"a": "A", "x/b": "B", "x/c": "C"}}, + prefetch: []string{"a"}, + read: []string{"a", "x/b", "x/c"}, + maxRounds: 3, + want: "ABC", + wantReads: [][]string{{"a"}, {"x/b", "x/c"}}, + }, + { + name: "a file the remote leaves out is unreadable, not fetched again", + src: &mapSource{files: map[string]string{"a": "A"}, withhold: map[string]bool{"a": true}}, + read: []string{"a"}, + maxRounds: 3, + wantErr: "did not return it", + wantReads: [][]string{{"a"}}, + }, + { + name: "past maxRounds the run stops", + src: &mapSource{files: map[string]string{"a": "A"}}, + read: []string{"a"}, + maxRounds: 0, + wantErr: "after 0 rounds: a", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := load(t, tc.src, tc.prefetch...) + got, err := Rounds(context.Background(), f, tc.src, tc.maxRounds, func(f *FS) (string, error) { + // Like the mise scan, a failed read does not stop the run. + var b strings.Builder + var first error + for _, p := range tc.read { + data, err := fs.ReadFile(f, p) + if err != nil && first == nil { + first = err + } + b.Write(data) + } + return b.String(), first + }) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Errorf("Rounds error = %v, want %q", err, tc.wantErr) + } + } else if err != nil || got != tc.want { + t.Errorf("Rounds = %q, %v; want %q", got, err, tc.want) + } + if !reflect.DeepEqual(nonEmpty(tc.src.reads), tc.wantReads) { + t.Errorf("reads = %v, want %v", tc.src.reads, tc.wantReads) + } + }) + } +} + +func nonEmpty(in [][]string) [][]string { + var out [][]string + for _, r := range in { + if len(r) > 0 { + out = append(out, r) + } + } + return out +} + +func TestOpenUnfetched(t *testing.T) { + src := &mapSource{files: map[string]string{"a": "A"}} + f := load(t, src) + if _, err := f.Open("a"); !errors.Is(err, ErrNotFetched) { + t.Errorf("Open of an unfetched file = %v, want ErrNotFetched", err) + } + if blobs := f.takeMisses(); !reflect.DeepEqual(blobs, []string{"a"}) { + t.Errorf("misses = %v, want [a]", blobs) + } +} + +func TestBlobError(t *testing.T) { + f := New([]Entry{{Path: "big.toml", Mode: 0o644}}) + f.blobs["big.toml"] = Blob{Size: 3 << 20, Err: errors.New("binary")} + info, err := f.Stat("big.toml") + if err != nil || info.Size() != 3<<20 { + t.Errorf("Stat = %v, %v; want the remote size", info, err) + } + if _, err := f.Open("big.toml"); err == nil || !strings.Contains(err.Error(), "binary") { + t.Errorf("Open = %v, want the blob error", err) + } +} + +func TestLinks(t *testing.T) { + long := strings.Repeat("L/", maxLinkTarget/2+1) + cases := []struct { + name string + blob Blob + fetched bool // the link's target was fetched + want string + wantErr string // substring; ErrNotFetched is "not fetched" + }{ + {name: "a fetched link resolves", blob: Blob{Data: []byte("real")}, fetched: true, want: "real/mise.toml"}, + {name: "a link not fetched yet is a miss", wantErr: "not fetched"}, + {name: "a target over PATH_MAX is refused", blob: Blob{Data: []byte(long)}, fetched: true, wantErr: "target too long"}, + {name: "a target the remote gave no text for is refused", blob: Blob{Size: 3 << 20}, fetched: true, wantErr: "target too long"}, + {name: "an empty target is refused", blob: Blob{}, fetched: true, wantErr: "empty symbolic link target"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := New([]Entry{{Path: "real/mise.toml", Mode: 0o644}, {Path: "L", Mode: fs.ModeSymlink | 0o777}}) + if tc.fetched { + f.blobs["L"] = tc.blob + } + got, err := f.Resolve("L/mise.toml") + switch { + case tc.wantErr != "": + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Errorf("Resolve = %q, %v; want %q", got, err, tc.wantErr) + } + case err != nil || got != tc.want: + t.Errorf("Resolve = %q, %v; want %q", got, err, tc.want) + } + if !tc.fetched { + if m := f.takeMisses(); !reflect.DeepEqual(m, []string{"L"}) { + t.Errorf("misses = %v, want [L]", m) + } + } + }) + } +} + +func TestReadLink(t *testing.T) { + f := New([]Entry{{Path: "a", Mode: 0o644}, {Path: "l", Mode: fs.ModeSymlink | 0o777}}) + f.blobs["l"] = Blob{Data: []byte("a")} + if got, err := f.ReadLink("l"); err != nil || got != "a" { + t.Errorf("ReadLink(l) = %q, %v; want a", got, err) + } + if _, err := f.ReadLink("a"); err == nil { + t.Errorf("ReadLink of a file = nil error, want one") + } +} + +func TestFetchLimits(t *testing.T) { + t.Run("past MaxFetch files the repository is too large", func(t *testing.T) { + files := map[string]string{} + var paths []string + for i := range MaxFetch + 1 { + p := "f" + strconv.Itoa(i) + files[p] = "x" + paths = append(paths, p) + } + src := &mapSource{files: files} + f := load(t, src) + if err := f.Fetch(context.Background(), src, paths); !errors.Is(err, ErrTooLarge) { + t.Errorf("Fetch error = %v, want ErrTooLarge", err) + } + if len(src.reads) != 0 { + t.Errorf("%d reads, want none past the cap", len(src.reads)) + } + }) + t.Run("Paths leaves out the files already fetched", func(t *testing.T) { + src := &mapSource{files: map[string]string{"a": "A", "b": "B"}} + f := load(t, src, "a") + if got := f.Paths(func(string, fs.FileMode) bool { return true }); !reflect.DeepEqual(got, []string{"b"}) { + t.Errorf("Paths = %v, want [b]", got) + } + }) + t.Run("a failed read fails the round", func(t *testing.T) { + f := load(t, &mapSource{files: map[string]string{"a": "A"}}) + _, err := Rounds(context.Background(), f, failingSource{}, MaxRounds, func(f *FS) (string, error) { + _, err := fs.ReadFile(f, "a") + return "", err + }) + if err == nil || !strings.Contains(err.Error(), "remote down") { + t.Errorf("Rounds error = %v, want the read error", err) + } + }) +} + +type failingSource struct{} + +func (failingSource) List(context.Context) ([]Entry, error) { return nil, errors.New("remote down") } +func (failingSource) Read(context.Context, []string) (map[string]Blob, error) { + return nil, errors.New("remote down") +} diff --git a/packagemanager/mise/mise.go b/packagemanager/mise/mise.go new file mode 100644 index 00000000..d75a1d57 --- /dev/null +++ b/packagemanager/mise/mise.go @@ -0,0 +1,1332 @@ +// Package mise reads the mise files of a repository (mise configs, +// mise.lock files and .tool-versions) into the ir.MiseScan the +// mise-en-place policies read. It parses files only and +// never runs mise: a config can run code through templates, hooks and +// plugins, and Plumber holds the policy outside the repository. +package mise + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "slices" + "sort" + "strconv" + "strings" + "unicode" + + "github.com/gobwas/glob" + "github.com/pelletier/go-toml/v2" + + "github.com/getplumber/plumber/internal/ir" +) + +// maxFileBytes bounds one mise file read. The files come from the +// analyzed repository, so their size is not trusted. +const maxFileBytes = 2 << 20 + +// skippedDirs are never walked: VCS metadata and vendored dependencies, +// whose mise files belong to someone else. +var skippedDirs = map[string]bool{ + ".git": true, + "node_modules": true, + "vendor": true, +} + +// keptHiddenDirs are the hidden directories mise reads config from. Every +// other hidden directory is skipped. +var keptHiddenDirs = map[string]bool{ + ".config": true, + ".mise": true, +} + +var ( + // miseFileRe matches mise.toml, .mise.toml and mise..toml. + miseFileRe = regexp.MustCompile(`^\.?mise(?:\.([^.]+))?\.toml$`) + // configFileRe matches config.toml and config..toml inside a mise + // directory (mise/, .mise/, .config/mise/). + configFileRe = regexp.MustCompile(`^config(?:\.([^.]+))?\.toml$`) + // toolKeyOptionsRe strips the bracketed options of a tool key + // ("tool[opt=value]"). + toolKeyOptionsRe = regexp.MustCompile(`\[[^\]]*\]$`) +) + +// configFile is a mise config found by the walk. +type configFile struct { + rel string // path relative to the root, slash separated + lockDir string // directory of its lockfile, relative to the root + env string // "" or the of mise..toml + projDir string // the project directory the config belongs to + isRootFS bool // the config belongs to the repository root project + local bool // a *.local.toml file +} + +// Options says what Scan reads and which failures it reports. +type Options struct { + // ExemptPaths holds one list of repository path globs (`/` + // separator) per configuration the scan is read for: one for a plain + // run, one per policy in platform mode. A path is exempt only when + // every list matches it, since each configuration is evaluated over + // this one scan. A file under an exempt path that cannot be read does + // not fail the scan, unless a checked config pairs with it, and a local + // config there is not listed. + ExemptPaths [][]string + // ToolVersions reads .tool-versions files. Only the lockfile check + // uses them; with it off they are never opened. + ToolVersions bool + // Lockfiles reads the lockfile each config pairs with. The versions + // check reads configs only, so with it alone no lockfile is opened and + // an unreadable one does not stop the run. + Lockfiles bool + // Tracked returns the paths, among those given, that git tracks. A + // mise local config (*.local.toml) is personal unless committed, so + // one that is not tracked is neither read nor listed. Nil treats every + // path as tracked. + Tracked func(paths []string) []string + // Tasks reads the tasks of every mise project: task directories, + // TOML task files and includes. Only the tasks check uses them; with + // it off they are never opened, so an unreadable task file does not + // stop the run. + Tasks bool +} + +// UnreadableFile is a mise file that exists but could not be read or +// parsed. +type UnreadableFile struct { + // Path is the file, relative to the repository root. + Path string + // Reason says why it could not be read. + Reason string +} + +// ReadError lists every mise file Scan could not read. Plumber cannot +// tell what such a file pins, so the run stops instead of passing it. +type ReadError struct { + Files []UnreadableFile +} + +// Error lists one file per line. Paths and reasons come from the analyzed +// repository (a file name may hold a newline or an escape sequence), so +// control characters are escaped: a crafted name cannot add a line to the +// message or drive the terminal. +func (e *ReadError) Error() string { + var b strings.Builder + b.WriteString("cannot read the mise files below; fix them or list their paths in mise.exemptPaths:") + for _, f := range e.Files { + fmt.Fprintf(&b, "\n - %s: %s", escapeControl(f.Path), escapeControl(f.Reason)) + } + return b.String() +} + +// escapeControl writes each control character of s as a Go escape +// (\n, \x1b, ...) and keeps every other character as is. +func escapeControl(s string) string { + var b strings.Builder + for _, r := range s { + if unicode.IsControl(r) { + q := strconv.QuoteRune(r) + b.WriteString(q[1 : len(q)-1]) + continue + } + b.WriteRune(r) + } + return b.String() +} + +// unreadableSet records the files that failed, keyed by path. +type unreadableSet map[string]string + +func (u unreadableSet) add(rel string, err error) { + if _, seen := u[rel]; seen { + return + } + u[rel] = reason(err) +} + +// reason is err without the absolute path an *fs.PathError carries: the +// report names the file by its repository path. +func reason(err error) string { + if pe, ok := errors.AsType[*fs.PathError](err); ok { + return pe.Err.Error() + } + return err.Error() +} + +// FS is the repository tree Scan reads: names are slash paths relative to +// the repository root, "." being the root. DirFS reads a checkout; a +// remote repository is read through a tree listing (internal/repofs). +type FS interface { + fs.FS + // Lstat describes name without following a final symlink. + Lstat(name string) (fs.FileInfo, error) + // Resolve returns name with every symlink of its path resolved (the + // file itself or any directory above it), when that stays inside the + // repository. A name with nothing at it keeps its not-exist error; a + // broken link or a path that resolves out of the repository is an + // error that is not not-exist, so the file counts as unreadable. + Resolve(name string) (string, error) +} + +// DirFS returns the FS of the checkout at root. +func DirFS(root string) FS { + return dirFS{root: root, fsys: os.DirFS(root)} +} + +type dirFS struct { + root string + fsys fs.FS +} + +func (d dirFS) Open(name string) (fs.File, error) { return d.fsys.Open(name) } + +func (d dirFS) Lstat(name string) (fs.FileInfo, error) { + if !fs.ValidPath(name) { + return nil, &fs.PathError{Op: "lstat", Path: name, Err: fs.ErrInvalid} + } + return os.Lstat(filepath.Join(d.root, filepath.FromSlash(name))) +} + +func (d dirFS) Resolve(name string) (string, error) { + if !fs.ValidPath(name) { + return "", &fs.PathError{Op: "resolve", Path: name, Err: fs.ErrInvalid} + } + return resolveInRepo(d.root, filepath.Join(d.root, filepath.FromSlash(name))) +} + +// lockFileRe matches mise.lock and mise..lock. +var lockFileRe = regexp.MustCompile(`^mise(?:\.[^.]+)?\.lock$`) + +// skipDir reports whether Scan leaves the directory named name out of +// its walk: VCS metadata, vendored dependencies and every hidden +// directory mise does not read config from. +func skipDir(name string) bool { + return skippedDirs[name] || (strings.HasPrefix(name, ".") && !keptHiddenDirs[name]) +} + +// Wanted reports whether Scan with these options is likely to read the +// file at the repository path p (slash separated) with the given mode: a +// mise config or local config, a lockfile or .tool-versions when they are +// read, a file of a default task directory when tasks are, or a symlink +// (resolving a path reads it), outside the directories the walk skips. A +// remote read fetches these up front; any other file Scan reaches (a task +// include, a link the walk follows into a skipped directory) is fetched +// in a later round. +func (o Options) Wanted(p string, mode fs.FileMode) bool { + dirs := strings.Split(p, "/") + for _, d := range dirs[:len(dirs)-1] { + if skipDir(d) { + return false + } + } + if mode&fs.ModeSymlink != 0 { + return true + } + if !mode.IsRegular() { + return false + } + base := path.Base(p) + switch { + case base == ".tool-versions": + return o.ToolVersions + case lockFileRe.MatchString(base): + return o.Lockfiles + case isLocalConfig(p): + return true + } + if _, ok := classify(p); ok { + return true + } + if !o.Tasks { + return false + } + for _, d := range defaultTaskDirs { + if strings.HasPrefix(p, d+"/") || strings.Contains(p, "/"+d+"/") { + return true + } + } + return false +} + +// Scan walks the repository and reads every mise file it finds. Every file that +// cannot be read or parsed (including a symlink out of the repository or +// to a device, and a file over 2 MiB) is collected first; Scan then +// returns a *ReadError listing them all. Files under opts.ExemptPaths are +// left out of that list, except a lockfile a checked config pairs with. +func Scan(fsys FS, opts Options) (*ir.MiseScan, error) { + exempt, err := compileExempt(opts.ExemptPaths) + if err != nil { + return nil, err + } + scan := &ir.MiseScan{} + unreadable := unreadableSet{} + var configs []configFile + var toolVersions []string + var localConfigs []string + + // visited holds the real path of every directory walked, so a + // directory symlink is followed once and a link loop stops. + visited := map[string]bool{} + var walk func(dir, relBase string) + walk = func(dir, relBase string) { + _ = fs.WalkDir(fsys, dir, func(p string, d fs.DirEntry, err error) error { + rel := path.Join(relBase, relUnder(dir, p)) + if rel == "." { + rel = "" + } + if err != nil { + // Only a mise file that cannot be read makes the scan + // incomplete. An unreadable directory (a root-owned + // volume, a broken permission) is skipped like any other + // directory. + if p == dir { + return nil + } + if _, ok := classify(rel); ok || (opts.ToolVersions && path.Base(rel) == ".tool-versions") { + unreadable.add(rel, err) + } + return nil + } + name := d.Name() + if d.IsDir() { + if p != dir && skipDir(name) { + return fs.SkipDir + } + if real, err := fsys.Resolve(p); err == nil { + if p != dir && visited[real] { + return fs.SkipDir + } + visited[real] = true + } + return nil + } + _, isConfig := classify(rel) + isToolVersions := name == ".tool-versions" + if d.Type()&fs.ModeSymlink != 0 && !isConfig && !isToolVersions { + followDirLink(fsys, p, rel, name, visited, unreadable, walk) + return nil + } + if !d.Type().IsRegular() && d.Type()&fs.ModeSymlink == 0 { + // A device or pipe named like a mise file is never read. A + // symlink goes on to readFile, which follows it only to a + // regular file inside the repository. + if isConfig || (opts.ToolVersions && isToolVersions) { + unreadable.add(rel, errors.New("not a regular file")) + } + return nil + } + if isToolVersions { + if opts.ToolVersions { + toolVersions = append(toolVersions, rel) + } + return nil + } + if cf, ok := classify(rel); ok { + configs = append(configs, cf) + } else if isLocalConfig(rel) { + localConfigs = append(localConfigs, rel) + } + return nil + }) + } + walk(".", "") + configs, scan.LocalConfigs = keepTrackedLocal(configs, localConfigs, opts.Tracked, exempt) + + monorepoRootLock, layoutKnown := rootLockfileForMonorepo(fsys, configs) + locks := map[string]*lockFile{} + declared := map[string]map[string]bool{} // project dir -> tool names + // Project dirs holding an unreadable config: what they declare is + // unknown, so their .tool-versions is not judged. + unreadableDirs := map[string]bool{} + neededLocks := map[string]bool{} + // lockSettings records each readable config's own + // `[settings] lockfile`, for inheritLockfileSetting. + var lockSettings []lockSetting + own := map[string]*projectTasks{} // project dir -> what its configs declare + + for _, cf := range configs { + doc, err := readTOML(fsys, cf.rel) + if err != nil { + unreadable.add(cf.rel, err) + unreadableDirs[cf.projDir] = true + continue + } + lockDir := cf.lockDir + if monorepoRootLock && !cf.isRootFS { + lockDir = "" + } + lockName := "mise.lock" + if cf.env != "" { + lockName = "mise." + cf.env + ".lock" + } + lockRel := path.Join(lockDir, lockName) + lock, ok := locks[lockRel] + if !ok { + lock = &lockFile{} + if opts.Lockfiles { + lock = readLock(fsys, lockRel, unreadable) + } + locks[lockRel] = lock + } + if !exempt.matches(cf.rel) { + // A checked config needs its lockfile, exempt or not. + neededLocks[lockRel] = true + } + + setting, set := lockfileSetting(doc) + lockSettings = append(lockSettings, lockSetting{cf: cf, value: setting, set: set}) + mc := ir.MiseConfig{ + Path: cf.rel, + Lockfile: ir.MiseLockfile{Path: lockRel, Present: lock.present, Version: lock.version}, + LockfileDisabled: set && !setting, + // A subproject's lockfile depends on the root config's + // [monorepo] setting; an unreadable root leaves it unknown. + LockfileUnknown: !layoutKnown && !cf.isRootFS, + SourceSettings: sourceSettings(doc), + Local: cf.local, + } + for _, t := range tools(doc) { + if t.Unreadable == "" { + t.Locked = lock.match(t.Name, t.Request) + } + mc.Tools = append(mc.Tools, t) + if declared[cf.projDir] == nil { + declared[cf.projDir] = map[string]bool{} + } + declared[cf.projDir][toolName(t.Name)] = true + } + scan.Configs = append(scan.Configs, mc) + // mise loads a mise..toml only when MISE_ENV names it, so its + // tasks are not what `mise run` sees by default. + if cf.env == "" || cf.local { + if own[cf.projDir] == nil { + own[cf.projDir] = &projectTasks{} + } + own[cf.projDir].addConfig(cf.rel, cf.projDir, cf.local, doc) + } + } + inheritLockfileSetting(scan.Configs, lockSettings) + if opts.Tasks { + scan.Projects = collectProjects(fsys, own, unreadableDirs, unreadable) + } + + // .tool-versions is also asdf's file: it only says something about + // mise when the repository uses mise at all. + if len(configs) == 0 { + toolVersions = nil + } + for _, rel := range toolVersions { + names, err := readToolVersions(fsys, rel) + if err != nil { + unreadable.add(rel, err) + continue + } + dir := path.Dir(rel) + if dir == "." { + dir = "" + } + if unreadableDirs[dir] { + continue + } + for _, n := range names { + if declared[dir][toolName(n)] { + continue + } + scan.ToolVersions = append(scan.ToolVersions, ir.MiseToolVersionsEntry{Path: rel, Name: n}) + } + } + + sort.Slice(scan.Configs, func(i, j int) bool { return scan.Configs[i].Path < scan.Configs[j].Path }) + if failed := unreadable.report(exempt, neededLocks); len(failed) > 0 { + return nil, &ReadError{Files: failed} + } + return scan, nil +} + +// asdfNames maps the asdf plugin names mise reads as one of its own tools +// (checked with mise 2026.11.16: `nodejs 22` in .tool-versions is node). +var asdfNames = map[string]string{"nodejs": "node", "golang": "go"} + +// toolName is the name mise knows a tool key by: an asdf plugin name is +// read as the mise tool it stands for, so `nodejs` in .tool-versions and +// `node` in mise.toml are the same tool. +func toolName(key string) string { + if n, ok := asdfNames[key]; ok { + return n + } + return key +} + +// miseDirNames are the directory names mise reads config from. A symlink +// with one of these names that leaves the repository hides config mise +// would load, so it fails the scan instead of being skipped. +var miseDirNames = map[string]bool{".config": true, ".mise": true, "mise": true, "conf.d": true} + +// followDirLink walks the directory a symlink at p points to, under the +// link's own path (rel), as mise sees it. Only a target inside the +// repository is walked, and only once (visited). A link that is skipped +// by name (vendor, a hidden directory mise ignores) is not followed. A +// link named like a mise config directory that points outside the +// repository, or nowhere, is unreadable: mise would follow it. +func followDirLink(fsys FS, p, rel, name string, visited map[string]bool, unreadable unreadableSet, walk func(dir, relBase string)) { + if skipDir(name) { + return + } + target, err := fsys.Resolve(p) + if err != nil { + if miseDirNames[name] { + unreadable.add(rel, err) + } + return + } + info, err := fs.Stat(fsys, target) + if err != nil || !info.IsDir() || visited[target] { + return + } + walk(target, rel) +} + +// report lists the failed files in path order, leaving out those under +// exempt paths unless a checked config needs them. +func (u unreadableSet) report(exempt exemptSets, needed map[string]bool) []UnreadableFile { + var out []UnreadableFile + for rel, why := range u { + if exempt.matches(rel) && !needed[rel] { + continue + } + out = append(out, UnreadableFile{Path: rel, Reason: why}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path }) + return out +} + +// exemptSets is one compiled glob list per configuration; a path is +// exempt when every list matches it. +type exemptSets [][]*glob.Pattern + +func compileExempt(lists [][]string) (exemptSets, error) { + out := make(exemptSets, 0, len(lists)) + for _, l := range lists { + g, err := compileGlobs(l) + if err != nil { + return nil, err + } + out = append(out, g) + } + return out, nil +} + +// matches reports whether every configuration exempts rel. +func (e exemptSets) matches(rel string) bool { + if len(e) == 0 { + return false + } + for _, set := range e { + if !matchAny(set, rel) { + return false + } + } + return true +} + +// compileGlobs compiles path globs with `/` as the separator, the way +// the policies' glob.match(pattern, ["/"], path) reads them. +func compileGlobs(patterns []string) ([]*glob.Pattern, error) { + out := make([]*glob.Pattern, 0, len(patterns)) + for _, p := range patterns { + g, err := glob.Compile(p, '/') + if err != nil { + return nil, fmt.Errorf("mise.exemptPaths: invalid glob %q: %w", p, err) + } + out = append(out, g) + } + return out, nil +} + +func matchAny(globs []*glob.Pattern, s string) bool { + for _, g := range globs { + if g.Match(s) { + return true + } + } + return false +} + +// keepTrackedLocal drops the local configs git does not track: a +// personal mise.local.toml on a developer's machine is neither read nor +// reported. It returns the configs to read and the tracked local configs +// outside exempt paths, in path order, for ISSUE-1019. localOnly are the +// local configs classify does not read as configs (mise..local.toml, +// config..local.toml). +func keepTrackedLocal(configs []configFile, localOnly []string, tracked func([]string) []string, exempt exemptSets) ([]configFile, []string) { + candidates := slices.Clone(localOnly) + for _, cf := range configs { + if cf.local { + candidates = append(candidates, cf.rel) + } + } + if len(candidates) == 0 { + return configs, nil + } + keep := map[string]bool{} + kept := candidates + if tracked != nil { + kept = tracked(candidates) + } + for _, p := range kept { + keep[p] = true + } + out := configs[:0] + for _, cf := range configs { + if !cf.local || keep[cf.rel] { + out = append(out, cf) + } + } + var local []string + for _, p := range candidates { + if keep[p] && !exempt.matches(p) { + local = append(local, p) + } + } + sort.Strings(local) + return out, local +} + +// isLocalConfig reports whether rel is a mise local config: a config name +// with `.local` before `.toml` (mise.local.toml, mise..local.toml, +// config.local.toml in a mise directory, conf.d/*.local.toml). mise loads +// it next to the config it extends; it is personal and not meant to be +// committed (https://mise.jdx.dev/glossary.html#mise-local-toml). +func isLocalConfig(rel string) bool { + base, found := strings.CutSuffix(rel, ".local.toml") + if !found { + return false + } + _, ok := classify(base + ".toml") + return ok +} + +// classify reports whether rel is a mise config, and where its lockfile +// and project directory are. A local file (*.local.toml) is meant to be +// personal, but mise loads it when it is committed: Scan keeps it only +// when git tracks it (Options.Tracked), lists it in LocalConfigs +// (ISSUE-1019), and the sources and versions checks judge it; the +// lockfile check does not. +func classify(rel string) (configFile, bool) { + dir, name := path.Split(rel) + dir = strings.TrimSuffix(dir, "/") + parts := []string{} + if dir != "" { + parts = strings.Split(dir, "/") + } + + // conf.d fragments share the lockfile of the conf.d's parent + // directory (mise/conf.d/*.toml, mise/conf.d/*/mise.toml, ...). + for i, seg := range parts { + if seg != "conf.d" || i == 0 || !isMiseDir(parts[:i]) { + continue + } + if !strings.HasSuffix(name, ".toml") { + return configFile{}, false + } + lockDir := strings.Join(parts[:i], "/") + proj := projectDirOf(parts[:i]) + return configFile{rel: rel, lockDir: lockDir, projDir: proj, isRootFS: proj == "", local: strings.HasSuffix(name, ".local.toml")}, true + } + + if m := miseFileRe.FindStringSubmatch(name); m != nil { + proj := dir + if isMiseDir(parts) { + proj = projectDirOf(parts) + } else if len(parts) > 0 && parts[len(parts)-1] == ".config" { + proj = strings.Join(parts[:len(parts)-1], "/") + } + return configFile{rel: rel, lockDir: dir, env: m[1], projDir: proj, isRootFS: proj == "", local: m[1] == "local"}, true + } + if m := configFileRe.FindStringSubmatch(name); m != nil && isMiseDir(parts) { + proj := projectDirOf(parts) + return configFile{rel: rel, lockDir: dir, env: m[1], projDir: proj, isRootFS: proj == "", local: m[1] == "local"}, true + } + return configFile{}, false +} + +// isMiseDir reports whether the directory parts end in a mise config +// directory: mise, .mise or .config/mise. +func isMiseDir(parts []string) bool { + n := len(parts) + if n == 0 { + return false + } + last := parts[n-1] + if last == ".mise" { + return true + } + if last == "mise" { + return true + } + return false +} + +// projectDirOf returns the project directory a mise directory belongs to +// (the directory holding mise/, .mise/ or .config/). +func projectDirOf(parts []string) string { + n := len(parts) + if n >= 2 && parts[n-1] == "mise" && parts[n-2] == ".config" { + return strings.Join(parts[:n-2], "/") + } + return strings.Join(parts[:n-1], "/") +} + +// rootLockfileForMonorepo reports whether a config of the root project +// sets `[monorepo] lockfile = true`: subproject tools then go to the +// root lockfiles. known is false when a root config cannot be read: the +// setting may hide in it, so where subproject tools are locked is unknown. +func rootLockfileForMonorepo(fsys FS, configs []configFile) (mono, known bool) { + known = true + for _, cf := range configs { + if !cf.isRootFS || cf.local { + continue + } + doc, err := readTOML(fsys, cf.rel) + if err != nil { + known = false // the config itself is reported as unreadable + continue + } + m, ok := doc["monorepo"].(map[string]any) + if !ok { + continue + } + if b, ok := m["lockfile"].(bool); ok && b { + mono = true + } + } + if mono { + known = true // a readable root config settles it + } + return mono, known +} + +// lockfileSetting returns the config's own `[settings] lockfile` value, +// and whether it sets one. +func lockfileSetting(doc map[string]any) (value, set bool) { + settings, ok := doc["settings"].(map[string]any) + if !ok { + return false, false + } + value, set = settings["lockfile"].(bool) + return value, set +} + +// lockSetting is one config's own `[settings] lockfile`. +type lockSetting struct { + cf configFile + value bool + set bool +} + +// inheritLockfileSetting applies `[settings] lockfile` the way mise does +// to a config that does not set it: mise merges the settings of every +// config from the project directory up to the root, the closest one +// winning. So `lockfile = false` in the root mise.toml turns lockfiles +// off for every subproject that does not set it back to true. The +// config then has LockfileDisabled and LockfileDisabledBy naming the +// config that set it. Env configs (mise..toml) only apply with their +// env, so they are not inherited from. configs and settings are in the +// same order. +func inheritLockfileSetting(configs []ir.MiseConfig, settings []lockSetting) { + // The setting of each project directory, from its non-env configs: + // false wins over true when two files of one directory disagree. + type dirSetting struct { + value bool + by string + } + byDir := map[string]dirSetting{} + for _, ls := range settings { + if !ls.set || ls.cf.env != "" { + continue + } + cur, seen := byDir[ls.cf.projDir] + if !seen || (cur.value && !ls.value) { + byDir[ls.cf.projDir] = dirSetting{value: ls.value, by: ls.cf.rel} + } + } + for i, ls := range settings { + if ls.set { + continue + } + for dir := ls.cf.projDir; ; dir = parentDir(dir) { + if ds, ok := byDir[dir]; ok { + if !ds.value { + configs[i].LockfileDisabled = true + configs[i].LockfileDisabledBy = ds.by + } + break + } + if dir == "" { + break + } + } + } +} + +// parentDir is the parent of a slash-separated repository directory, "" +// for the root. +func parentDir(dir string) string { + parent := path.Dir(dir) + if parent == "." || parent == "/" { + return "" + } + return parent +} + +// tools reads the [tools] table. A value is a string, an array of +// strings, or a table with a version. +func tools(doc map[string]any) []ir.MiseTool { + table, ok := doc["tools"].(map[string]any) + if !ok { + return nil + } + keys := make([]string, 0, len(table)) + for k := range table { + keys = append(keys, k) + } + sort.Strings(keys) + + var out []ir.MiseTool + for _, key := range keys { + name := toolKeyOptionsRe.ReplaceAllString(key, "") + // Each element of an array carries its own options, so a request + // gets the options of the table it was written in. + items, ok := table[key].([]any) + if !ok { + items = []any{table[key]} + } + for _, item := range items { + opts := sourceOptions(key, item) + for _, req := range requests(item) { + t := ir.MiseTool{Name: name, Request: req.value, Unreadable: req.unreadable, SourceOptions: opts} + out = append(out, t) + } + } + } + return out +} + +// sourceOptionNames are the string tool options that change where mise +// downloads a tool from: api_url (another GitHub host), url (a URL instead +// of a release asset), and the pypi/pipx backend's registry_url, +// pipx_args and uvx_args (which can carry --index-url). asset_pattern is +// not one: it picks an asset of the same release. +var sourceOptionNames = []string{"api_url", "pipx_args", "registry_url", "url", "uvx_args"} + +// argOptionNames are the source options that hold a command line rather +// than a URL. Only the URLs in them count (see argURLs). +var argOptionNames = []string{"pipx_args", "uvx_args"} + +// argURLRe is a URL with a scheme pip, pipx or uv downloads from. +var argURLRe = regexp.MustCompile(`(?i)(?:git\+)?(?:https?|ssh|file|ftp)://\S+`) + +// argURLs returns every URL in a pip, pipx or uv argument string, in +// order, whatever flag carries it: pip accepts a value attached to a short +// flag (`-ihttps://...`) and any unambiguous prefix of a long one +// (`--extra-index`), so flags are not parsed. Tokens are split on spaces, +// quotes and `=`, which also gives the URL of uv's `--index name=URL`. A +// token holding `://` with no known scheme is kept whole, so it is judged +// too (fail closed). An argument with no URL, such as `--include-deps`, +// gives nothing. +func argURLs(args string) []string { + var out []string + split := func(r rune) bool { return unicode.IsSpace(r) || r == '\'' || r == '"' || r == '=' } + for _, tok := range strings.FieldsFunc(args, split) { + if !strings.Contains(tok, "://") { + continue + } + if u := argURLRe.FindString(tok); u != "" { + tok = u + } + out = append(out, tok) + } + return out +} + +// sourceOption returns the options a source option name and value give: +// the value itself, or for pipx_args/uvx_args one option per URL they +// hold (none when they hold none, as with `--include-deps`). +func sourceOption(name, value string) []ir.MiseToolOption { + if !slices.Contains(argOptionNames, name) { + return []ir.MiseToolOption{{Name: name, Value: value}} + } + var out []ir.MiseToolOption + for _, u := range argURLs(value) { + out = append(out, ir.MiseToolOption{Name: name, Value: u}) + } + return out +} + +// indexEnvVars are the environment variables that point a package +// manager mise runs (go, pip, uv, npm) at another index, or turn off Go's +// checksum database. They count in a tool's install_env (ISSUE-1016), +// along with npm's scoped registries (isIndexEnvVar). +var indexEnvVars = []string{ + "GONOSUMDB", "GOPROXY", "GOSUMDB", + "NPM_CONFIG_REGISTRY", + "PIP_EXTRA_INDEX_URL", "PIP_INDEX_URL", + "UV_DEFAULT_INDEX", "UV_EXTRA_INDEX_URL", "UV_INDEX", "UV_INDEX_URL", +} + +// isIndexEnvVar reports whether an install_env key is one of +// indexEnvVars, or an npm scoped registry (`NPM_CONFIG_@scope:registry`, +// any case, as npm reads it). +func isIndexEnvVar(k string) bool { + if slices.Contains(indexEnvVars, k) { + return true + } + u := strings.ToUpper(k) + return strings.HasPrefix(u, "NPM_CONFIG_@") && strings.HasSuffix(u, ":REGISTRY") +} + +// sourceOptions returns the source options of a tool, from its key +// ("tool[api_url=...]") and its value (a table, or the tables of an +// array), sorted by name then value. +func sourceOptions(key string, v any) []ir.MiseToolOption { + var out []ir.MiseToolOption + if m := toolKeyOptionsRe.FindString(key); m != "" { + for kv := range strings.SplitSeq(strings.Trim(m, "[]"), ",") { + k, val, ok := strings.Cut(kv, "=") + if k = strings.TrimSpace(k); ok && slices.Contains(sourceOptionNames, k) { + out = append(out, sourceOption(k, strings.TrimSpace(val))...) + } + } + } + out = append(out, tableSourceOptions(v)...) + sort.Slice(out, func(i, j int) bool { + if out[i].Name != out[j].Name { + return out[i].Name < out[j].Name + } + return out[i].Value < out[j].Value + }) + return out +} + +// tableSourceOptions reads api_url, url and platforms..url from +// a tool table. The platform tables come nested +// (`platforms = { linux-x64 = { url = ... } }`, or the dotted key +// `platforms.linux-x64.url`) or as a quoted key ("platforms.linux-x64"). +func tableSourceOptions(v any) []ir.MiseToolOption { + var out []ir.MiseToolOption + switch val := v.(type) { + case []any: + for _, e := range val { + out = append(out, tableSourceOptions(e)...) + } + case map[string]any: + for _, name := range sourceOptionNames { + if s, ok := val[name].(string); ok { + out = append(out, sourceOption(name, s)...) + } + } + // indexes = [{ name = "x", url = "..." }]: one option per index. + if idx, ok := val["indexes"].([]any); ok { + for _, e := range idx { + if m, ok := e.(map[string]any); ok { + if s, ok := m["url"].(string); ok { + out = append(out, ir.MiseToolOption{Name: "indexes", Value: s}) + } + } + } + } + if env, ok := val["install_env"].(map[string]any); ok { + for k, v := range env { + if s, ok := v.(string); ok && isIndexEnvVar(k) { + out = append(out, ir.MiseToolOption{Name: "install_env." + k, Value: s}) + } + } + } + for k, pv := range val { + pm, ok := pv.(map[string]any) + if !ok { + continue + } + if k == "platforms" { + for p, ppv := range pm { + out = append(out, platformURL(p, ppv)...) + } + } + if p, found := strings.CutPrefix(k, "platforms."); found { + out = append(out, platformURL(p, pm)...) + } + } + } + return out +} + +// platformURL returns the url option of one platform table. +func platformURL(platform string, v any) []ir.MiseToolOption { + m, ok := v.(map[string]any) + if !ok { + return nil + } + s, ok := m["url"].(string) + if !ok { + return nil + } + return []ir.MiseToolOption{{Name: "platforms." + platform + ".url", Value: s}} +} + +// sourceSettings returns one entry per target of the config's +// `[settings] url_replacements` (ISSUE-1015), sorted by value. mise sends +// a download to the replacement first, and the lockfile keeps the original +// URL, so only the config shows it. Other settings that point mise at a +// mirror or a registry (go.download_mirror, node.mirror_url, +// pypi.registry_url, ...) are not read (#678). The download URL locked in +// mise.lock is checked instead (ISSUE-1014), but only binary backends +// (aqua, github, gitlab, ubi, http) lock one: a mirror for go, npm, cargo +// or pip tools is not checked. +func sourceSettings(doc map[string]any) []ir.MiseSetting { + var out []ir.MiseSetting + if settings, ok := doc["settings"].(map[string]any); ok { + for _, v := range settingValues(settings, "url_replacements") { + for _, s := range settingStrings(v) { + out = append(out, ir.MiseSetting{Name: "url_replacements", Value: s}) + } + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Value < out[j].Value }) + return out +} + +// settingValues returns every value a dotted setting has: nested +// (`aqua.registries = ...` under [settings] decodes as +// settings.aqua.registries) and as a quoted key ("aqua.registries"). Both +// can be written in one file, so both are kept. +func settingValues(settings map[string]any, name string) []any { + var out []any + if v, ok := settings[name]; ok { + out = append(out, v) + } + var cur any = settings + for part := range strings.SplitSeq(name, ".") { + m, ok := cur.(map[string]any) + if !ok { + return out + } + if cur, ok = m[part]; !ok { + return out + } + } + if !strings.Contains(name, ".") { + return out // the nested walk found the same top-level key + } + return append(out, cur) +} + +// settingStrings returns the URLs of a setting value: a string, an array +// of strings, or a table (url_replacements) whose values are the targets. +func settingStrings(v any) []string { + switch val := v.(type) { + case string: + return []string{val} + case []any: + var out []string + for _, e := range val { + out = append(out, settingStrings(e)...) + } + return out + case map[string]any: + var out []string + for _, e := range val { + out = append(out, settingStrings(e)...) + } + return out + } + return nil +} + +type request struct { + value string + unreadable string +} + +func requests(v any) []request { + switch val := v.(type) { + case string: + return []request{readRequest(val)} + case []any: + var out []request + for _, e := range val { + out = append(out, requests(e)...) + } + return out + case map[string]any: + if ver, ok := val["version"]; ok { + return requests(ver) + } + return []request{{unreadable: "the tool has no version"}} + default: + // An unquoted version (node = 24, python = 3.12) is a TOML number, + // which mise rejects ("expected tool list"): no mise lock can match it. + return []request{{value: fmt.Sprint(val), unreadable: "the version is not a quoted string, which mise rejects"}} + } +} + +func readRequest(s string) request { + if strings.Contains(s, "{{") { + return request{value: s, unreadable: "the version is a template, which Plumber cannot resolve without running mise"} + } + if strings.TrimSpace(s) == "" { + return request{value: s, unreadable: "the version is empty"} + } + return request{value: s} +} + +// lockFile is a parsed mise.lock. +type lockFile struct { + present bool + version int + entries map[string][]lockEntry +} + +type lockEntry struct { + specifiers []string + entry ir.MiseLockEntry +} + +// match returns the entry of tool name whose specifiers contain req. +// mise writes one entry per platform when a tool's options differ by +// platform (a `platforms..url`), each with the same specifiers, +// so the platforms of every matching entry are merged into the first. +// Format 0 has no specifiers, so nothing matches. +func (l *lockFile) match(name, req string) *ir.MiseLockEntry { + if l == nil || !l.present { + return nil + } + var out *ir.MiseLockEntry + for _, e := range l.entries[name] { + if !slices.Contains(e.specifiers, req) { + continue + } + if out == nil { + entry := e.entry + entry.Platforms = slices.Clone(e.entry.Platforms) + out = &entry + continue + } + out.Platforms = append(out.Platforms, e.entry.Platforms...) + } + if out != nil { + sort.SliceStable(out.Platforms, func(i, j int) bool { return out.Platforms[i].Platform < out.Platforms[j].Platform }) + } + return out +} + +func readLock(fsys FS, rel string, unreadable unreadableSet) *lockFile { + doc, err := readTOML(fsys, rel) + if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + unreadable.add(rel, err) + } + return &lockFile{} + } + lf := &lockFile{present: true, entries: map[string][]lockEntry{}} + if v, ok := doc["lockfile_version"].(int64); ok { + lf.version = int(v) + } + toolsTable, _ := doc["tools"].(map[string]any) + for name, raw := range toolsTable { + var items []map[string]any + switch val := raw.(type) { + case []any: // [[tools.]] + for _, it := range val { + if m, ok := it.(map[string]any); ok { + items = append(items, m) + } + } + case map[string]any: // [tools.], older files + items = append(items, val) + } + for _, it := range items { + lf.entries[name] = append(lf.entries[name], parseLockEntry(it)) + } + } + return lf +} + +func parseLockEntry(m map[string]any) lockEntry { + e := lockEntry{} + e.entry.Version, _ = m["version"].(string) + e.entry.Backend, _ = m["backend"].(string) + if specs, ok := m["specifiers"].([]any); ok { + for _, s := range specs { + if str, ok := s.(string); ok { + e.specifiers = append(e.specifiers, str) + } + } + } + platforms := map[string]map[string]any{} + for k, v := range m { + pm, ok := v.(map[string]any) + if !ok { + continue + } + if p, found := strings.CutPrefix(k, "platforms."); found { + platforms[p] = pm + } + if k == "platforms" { + for p, pv := range pm { + if ppm, ok := pv.(map[string]any); ok { + platforms[p] = ppm + } + } + } + } + names := make([]string, 0, len(platforms)) + for p := range platforms { + names = append(names, p) + } + sort.Strings(names) + for _, p := range names { + pm := platforms[p] + lp := ir.MiseLockPlatform{Platform: p} + lp.URL, _ = pm["url"].(string) + if lp.URL == "" { + lp.URL, _ = pm["url_api"].(string) + } + lp.Checksum, _ = pm["checksum"].(string) + lp.Provenance = provenanceName(pm["provenance"]) + e.entry.Platforms = append(e.entry.Platforms, lp) + } + return e +} + +// provenanceName reads a platform's provenance: a string ("slsa") or a +// table keyed by the kind ({ slsa = { url = "..." } }). +func provenanceName(v any) string { + switch val := v.(type) { + case string: + return val + case map[string]any: + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + return strings.Join(keys, ",") + } + return "" +} + +// readToolVersions returns the tool names of a .tool-versions file. +func readToolVersions(fsys FS, name string) ([]string, error) { + data, err := readFile(fsys, name) + if err != nil { + return nil, err + } + var names []string + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + line := sc.Text() + if i := strings.Index(line, "#"); i >= 0 { + line = line[:i] + } + fields := strings.Fields(line) + if len(fields) == 0 { + continue + } + names = append(names, fields[0]) + } + return names, sc.Err() +} + +func readTOML(fsys FS, name string) (map[string]any, error) { + data, err := readFile(fsys, name) + if err != nil { + return nil, err + } + doc := map[string]any{} + if err := toml.Unmarshal(data, &doc); err != nil { + return nil, err + } + return doc, nil +} + +// readFile reads the mise file name of the repository. A symlink +// is followed, as mise follows it, but only to a regular file inside the +// repository: a link out of it would read host files, and a link to a +// device such as /dev/zero (Stat size 0) would never end. The read itself +// is capped, whatever Stat reports. A refused file, including a broken +// link, is unreadable, which stops the run; only a path with nothing at +// it reports not-exist. +func readFile(fsys FS, name string) ([]byte, error) { + target, err := fsys.Resolve(name) + if err != nil { + return nil, err + } + info, err := fs.Stat(fsys, target) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, errors.New("not a regular file") + } + if info.Size() > maxFileBytes { + return nil, fmt.Errorf("larger than %d bytes", maxFileBytes) + } + f, err := fsys.Open(target) + if err != nil { + return nil, err + } + defer func() { _ = f.Close() }() // read-only: a close error changes nothing + data, err := io.ReadAll(io.LimitReader(f, maxFileBytes+1)) + if err != nil { + return nil, err + } + if len(data) > maxFileBytes { + return nil, fmt.Errorf("larger than %d bytes", maxFileBytes) + } + return data, nil +} + +// resolveInRepo returns where p (an absolute path under root) really is, +// relative to the repository root and slash separated, with every symlink +// of the path resolved (the file itself or any directory above it), when +// that is inside root. A path with nothing at it keeps its not-exist error; a +// broken link or a path that resolves out of root is an error that is not +// not-exist, so the file counts as unreadable. +func resolveInRepo(root, p string) (string, error) { + if _, err := os.Lstat(p); err != nil { + return "", err + } + target, err := filepath.EvalSymlinks(p) + if err != nil { + // %v, not %w: a broken link exists in the repository, so its + // not-exist must not read as a missing file. + return "", fmt.Errorf("broken symlink: %s", reason(err)) + } + realRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return "", err + } + rel, err := filepath.Rel(realRoot, target) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", errors.New("resolves outside the repository") + } + return filepath.ToSlash(rel), nil +} + +// relUnder returns the FS name p relative to the FS directory dir, which +// holds it. +func relUnder(dir, p string) string { + switch { + case p == dir: + return "." + case dir == ".": + return p + } + return strings.TrimPrefix(p, dir+"/") +} diff --git a/packagemanager/mise/mise_test.go b/packagemanager/mise/mise_test.go new file mode 100644 index 00000000..99ef7a9e --- /dev/null +++ b/packagemanager/mise/mise_test.go @@ -0,0 +1,1178 @@ +package mise + +import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/internal/repofs" +) + +// lockV5 is a format 5 mise.lock locking node "24" for two platforms, one +// of them without checksum. +const lockV5 = `lockfile_version = 5 + +[[tools.node]] +version = "24.21.0" +backend = "core:node" +specifiers = ["24"] + +[tools.node."platforms.linux-x64"] +checksum = "sha256:aa" +url = "https://nodejs.org/dist/v24.21.0/node-v24.21.0-linux-x64.tar.gz" + +[tools.node."platforms.macos-arm64"] +url = "https://nodejs.org/dist/v24.21.0/node-v24.21.0-darwin-arm64.tar.gz" +provenance = { slsa = { url = "https://example.com/att" } } +` + +var nodeLocked = &ir.MiseLockEntry{ + Version: "24.21.0", + Backend: "core:node", + Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://nodejs.org/dist/v24.21.0/node-v24.21.0-linux-x64.tar.gz", Checksum: "sha256:aa"}, + {Platform: "macos-arm64", URL: "https://nodejs.org/dist/v24.21.0/node-v24.21.0-darwin-arm64.tar.gz", Provenance: "slsa"}, + }, +} + +// diskSource serves a checkout as a remote repository: List lists every +// entry, Read reads files and link targets. +type diskSource struct { + root string +} + +func (d *diskSource) List(context.Context) ([]repofs.Entry, error) { + var entries []repofs.Entry + err := filepath.WalkDir(d.root, func(p string, e fs.DirEntry, err error) error { + if err != nil || p == d.root { + return nil //nolint:nilerr // an unreadable directory lists nothing + } + rel := filepath.ToSlash(strings.TrimPrefix(p, d.root+string(filepath.Separator))) + info, err := os.Lstat(p) + if err != nil { + return nil //nolint:nilerr // gone + } + switch { + case e.IsDir(): + entries = append(entries, repofs.Entry{Path: rel, Mode: fs.ModeDir | 0o755}) + case info.Mode()&fs.ModeSymlink != 0: + entries = append(entries, repofs.Entry{Path: rel, Mode: fs.ModeSymlink | 0o777}) + case info.Mode().IsRegular() && info.Mode().Perm()&0o111 != 0: + entries = append(entries, repofs.Entry{Path: rel, Mode: 0o755}) + case info.Mode().IsRegular(): + entries = append(entries, repofs.Entry{Path: rel, Mode: 0o644}) + } + return nil + }) + return entries, err +} + +func (d *diskSource) Read(_ context.Context, paths []string) (map[string]repofs.Blob, error) { + out := map[string]repofs.Blob{} + for _, rel := range paths { + p := filepath.Join(d.root, filepath.FromSlash(rel)) + if target, err := os.Readlink(p); err == nil { + out[rel] = repofs.Blob{Data: []byte(filepath.ToSlash(target))} + continue + } + data, err := os.ReadFile(p) + if err != nil { + out[rel] = repofs.Blob{Err: err} + continue + } + out[rel] = repofs.Blob{Data: data} + } + return out, nil +} + +// scanRemote scans the checkout at root the way a remote run does: one +// listing, the Wanted files fetched up front, the rest in rounds. +func scanRemote(t *testing.T, root string, opts Options) (*ir.MiseScan, error) { + t.Helper() + ctx := context.Background() + src := &diskSource{root: root} + entries, err := src.List(ctx) + if err != nil { + t.Fatal(err) + } + f := repofs.New(entries) + if err := f.Fetch(ctx, src, f.Paths(opts.Wanted)); err != nil { + t.Fatal(err) + } + return repofs.Rounds(ctx, f, src, repofs.MaxRounds, func(f *repofs.FS) (*ir.MiseScan, error) { return Scan(f, opts) }) +} + +// scanBoth runs Scan on the checkout, and again as a remote read unless +// remote is false (a case only a checkout has: an unreadable directory, +// a device), and fails when the two differ. +func scanBoth(t *testing.T, root string, opts Options, remote bool) (*ir.MiseScan, error) { + t.Helper() + got, err := Scan(DirFS(root), opts) + if !remote { + return got, err + } + rgot, rerr := scanRemote(t, root, opts) + if !reflect.DeepEqual(readErrPaths(err), readErrPaths(rerr)) || (err == nil) != (rerr == nil) { + t.Errorf("remote scan error = %v, local = %v", rerr, err) + } else if !reflect.DeepEqual(got, rgot) { + t.Errorf("remote scan =\n%#v\nlocal\n%#v", rgot, got) + } + return got, err +} + +func readErrPaths(err error) []string { + re, ok := errors.AsType[*ReadError](err) + if !ok { + return nil + } + var out []string + for _, f := range re.Files { + out = append(out, f.Path) + } + return out +} + +func writeRepo(t *testing.T, files map[string]string) string { + t.Helper() + root := t.TempDir() + for rel, content := range files { + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + return root +} + +// mergedT is github:o/t 1.0.0 locked for two platforms by two entries. +var mergedT = &ir.MiseLockEntry{Version: "1.0.0", Backend: "github:o/t", Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://example.com/t", Checksum: "sha256:aa"}, + {Platform: "macos-arm64", URL: "https://example.com/t-mac", Checksum: "sha256:bb"}, +}} + +func TestScan(t *testing.T) { + cases := []struct { + name string + files map[string]string + // lockedDirs are made unreadable after the files are written. + lockedDirs []string + // symlinks maps a repository path to the target of a symlink + // created there after the files are written. + symlinks map[string]string + opts Options + want *ir.MiseScan + // wantErr lists the paths the *ReadError names, in order. + wantErr []string + // noLockfiles scans without Options.Lockfiles (the versions + // check alone); every other case reads lockfiles. + noLockfiles bool + }{ + { + name: "no mise files", + files: map[string]string{"README.md": "hi", ".tool-versions": "node 24\n"}, + want: &ir.MiseScan{}, + }, + { + name: "a locked tool is matched through its specifiers", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": lockV5, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }}}, + }, + { + name: "a request no specifier names is not locked", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"22\"\n", + "mise.lock": lockV5, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "22"}}, + }}}, + }, + { + name: "a missing lockfile, lockfile = false, arrays, tables, options and templates", + files: map[string]string{ + "mise.toml": `[settings] +lockfile = false + +[tools] +python = ["3.13", "3.12"] +"aqua:jqlang/jq" = { version = "1.7.1" } +"ubi:org/tool[exe=tool]" = "2" +go = "{{ env.GO_VERSION }}" +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + LockfileDisabled: true, + Tools: []ir.MiseTool{ + {Name: "aqua:jqlang/jq", Request: "1.7.1"}, + {Name: "go", Request: "{{ env.GO_VERSION }}", Unreadable: "the version is a template, which Plumber cannot resolve without running mise"}, + {Name: "python", Request: "3.13"}, + {Name: "python", Request: "3.12"}, + {Name: "ubi:org/tool", Request: "2"}, + }, + }}}, + }, + { + name: "a format 0 lockfile has no specifiers to match", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": "[tools.node]\nversion = \"24.21.0\"\nbackend = \"core:node\"\n", + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + }, + { + name: "a committed lockfile that does not parse is unreadable, not absent", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": "[tools\nnode = ", + }, + wantErr: []string{"mise.lock"}, + }, + { + // One root config is unreadable, but another readable root + // config sets [monorepo] lockfile = true: that settles where + // svc/ locks, so it pairs with the root lockfile as usual. + name: "a readable root config with [monorepo] lockfile keeps the layout known next to an exempt unreadable one", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \n", + ".config/mise.toml": "[monorepo]\nlockfile = true\n", + "mise.lock": lockV5, + "svc/mise.toml": "[tools]\nnode = \"24\"\n", + }, + opts: Options{ExemptPaths: [][]string{{"mise.toml"}}}, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{ + {Path: ".config/mise.toml", Lockfile: ir.MiseLockfile{Path: ".config/mise.lock"}}, + { + Path: "svc/mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }, + }, + }, + }, + { + name: "config.toml in .config/mise, mise and .mise directories are configs", + files: map[string]string{ + ".config/mise/config.toml": "[tools]\nnode = \"24\"\n", + "mise/config.toml": "[tools]\nnode = \"24\"\n", + ".mise/config.toml": "[tools]\nnode = \"24\"\n", + "other/config.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: ".config/mise/config.toml", Lockfile: ir.MiseLockfile{Path: ".config/mise/mise.lock"}, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + {Path: ".mise/config.toml", Lockfile: ir.MiseLockfile{Path: ".mise/mise.lock"}, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + {Path: "mise/config.toml", Lockfile: ir.MiseLockfile{Path: "mise/mise.lock"}, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + }}, + }, + { + name: "a tool table without a version is unreadable", + files: map[string]string{ + "mise.toml": "[tools]\nnode = { os = [\"linux\"] }\n", + "mise.lock": lockV5, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Unreadable: "the tool has no version"}}, + }}}, + }, + { + // A valid TOML comment one byte over the cap: only the size + // makes it unreadable. + name: "a mise file over the size cap is unreadable", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": "#" + strings.Repeat("x", maxFileBytes), + }, + wantErr: []string{"mise.lock"}, + }, + { + // The root config may set [monorepo] lockfile = true, so where + // svc/ locks is unknown; the root's own tools are unknown too, + // so the root .tool-versions is not judged. + name: "an exempt unreadable root config leaves subproject lockfiles unknown and its .tool-versions unjudged", + files: map[string]string{ + "mise.toml": "[monorepo]\nlockfile = true\n[tools]\nnode = \n", + "mise.lock": lockV5, + ".tool-versions": "node 24\n", + "svc/mise.toml": "[tools]\ngo = \"1.25\"\n", + }, + opts: Options{ExemptPaths: [][]string{{"mise.toml"}}, ToolVersions: true}, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{{ + Path: "svc/mise.toml", + Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, + LockfileUnknown: true, + Tools: []ir.MiseTool{{Name: "go", Request: "1.25"}}, + }}, + }, + }, + { + // /dev/zero reports a Stat size of 0 and never ends: following + // the link would read until the process runs out of memory. + name: "a lockfile symlinked to a device is unreadable, never followed", + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n"}, + symlinks: map[string]string{"mise.lock": "/dev/zero"}, + wantErr: []string{"mise.lock"}, + }, + { + name: "a config and a lockfile symlinked inside the repository are followed", + files: map[string]string{"shared/tools.toml": "[tools]\nnode = \"24\"\n", "shared/tools.lock": lockV5}, + symlinks: map[string]string{"mise.toml": "shared/tools.toml", "mise.lock": "shared/tools.lock"}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }}}, + }, + { + name: "a config symlinked outside the repository is unreadable", + files: map[string]string{"mise.lock": lockV5}, + symlinks: map[string]string{"mise.toml": "/etc/hosts"}, + wantErr: []string{"mise.toml"}, + }, + { + name: "a .tool-versions symlinked outside the repository is unreadable", + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n", "mise.lock": lockV5}, + symlinks: map[string]string{".tool-versions": "/etc/hosts"}, + opts: Options{ToolVersions: true}, + wantErr: []string{".tool-versions"}, + }, + { + name: "a broken lockfile symlink is unreadable, not a missing lockfile", + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n"}, + symlinks: map[string]string{"mise.lock": "does-not-exist.lock"}, + wantErr: []string{"mise.lock"}, + }, + { + name: "a lockfile symlinked to a regular file outside the repository is not read", + files: map[string]string{"mise.toml": "[tools]\nnode = \"24\"\n"}, + symlinks: map[string]string{"mise.lock": "/etc/hosts"}, + wantErr: []string{"mise.lock"}, + }, + { + name: "an unquoted numeric version is unreadable, as mise rejects it", + files: map[string]string{ + "mise.toml": "[tools]\nnode = 24\npython = 3.12\n", + "mise.lock": lockV5, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{ + {Name: "node", Request: "24", Unreadable: "the version is not a quoted string, which mise rejects"}, + {Name: "python", Request: "3.12", Unreadable: "the version is not a quoted string, which mise rejects"}, + }, + }}}, + }, + { + name: "a platform locked with url_api only uses it as the download URL", + files: map[string]string{ + "mise.toml": "[tools]\nage = \"1.3.2\"\n", + "mise.lock": `lockfile_version = 5 + +[[tools.age]] +version = "1.3.2" +backend = "aqua:FiloSottile/age" +specifiers = ["1.3.2"] + +[tools.age."platforms.linux-x64"] +url_api = "https://api.github.com/repos/FiloSottile/age/releases/assets/535541903" +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", + Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://api.github.com/repos/FiloSottile/age/releases/assets/535541903"}, + }, + }}}, + }}}, + }, + { + name: "provenance written as a string is read as its kind", + files: map[string]string{ + "mise.toml": "[tools]\nage = \"1.3.2\"\n", + "mise.lock": `lockfile_version = 5 + +[[tools.age]] +version = "1.3.2" +backend = "aqua:FiloSottile/age" +specifiers = ["1.3.2"] + +[tools.age."platforms.linux-x64"] +checksum = "sha256:cbe24006683f8eb669266162894b9a522a1af52f2665fbc63a4bb032ed26ac10" +url = "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-linux-amd64.tar.gz" +provenance = "github-attestations" +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", + Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{{ + Platform: "linux-x64", + URL: "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-linux-amd64.tar.gz", + Checksum: "sha256:cbe24006683f8eb669266162894b9a522a1af52f2665fbc63a4bb032ed26ac10", + Provenance: "github-attestations", + }}, + }}}, + }}}, + }, + { + name: "a provenance table with several kinds is read as its kinds, sorted and comma-joined", + files: map[string]string{ + "mise.toml": "[tools]\nage = \"1.3.2\"\n", + "mise.lock": `lockfile_version = 5 + +[[tools.age]] +version = "1.3.2" +backend = "aqua:FiloSottile/age" +specifiers = ["1.3.2"] + +[tools.age."platforms.linux-x64"] +checksum = "sha256:cbe24006683f8eb669266162894b9a522a1af52f2665fbc63a4bb032ed26ac10" +url = "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-linux-amd64.tar.gz" +provenance = { slsa = { url = "https://example.com/att" }, github-attestations = { url = "https://example.com/gh" } } +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", + Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{{ + Platform: "linux-x64", + URL: "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-linux-amd64.tar.gz", + Checksum: "sha256:cbe24006683f8eb669266162894b9a522a1af52f2665fbc63a4bb032ed26ac10", + Provenance: "github-attestations,slsa", + }}, + }}}, + }}}, + }, + { + name: "platforms written as nested tables are read like the quoted form", + files: map[string]string{ + "mise.toml": "[tools]\nage = \"1.3.2\"\n", + "mise.lock": `lockfile_version = 5 + +[[tools.age]] +version = "1.3.2" +backend = "aqua:FiloSottile/age" +specifiers = ["1.3.2"] + +[tools.age.platforms.macos-arm64] +checksum = "sha256:aa" +url = "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-darwin-arm64.tar.gz" + +[tools.age.platforms.linux-x64] +checksum = "sha256:bb" +url = "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-linux-amd64.tar.gz" +provenance = "github-attestations" +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", + Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-linux-amd64.tar.gz", Checksum: "sha256:bb", Provenance: "github-attestations"}, + {Platform: "macos-arm64", URL: "https://github.com/FiloSottile/age/releases/download/v1.3.2/age-v1.3.2-darwin-arm64.tar.gz", Checksum: "sha256:aa"}, + }, + }}}, + }}}, + }, + { + name: "env, .config and conf.d configs pair with their lockfiles, tracked local files are kept and listed", + files: map[string]string{ + "mise.ci.toml": "[tools]\nnode = \"24\"\n", + "mise.local.toml": "[tools]\nnode = \"24\"\n", + ".config/mise.toml": "[tools]\nnode = \"24\"\n", + ".config/mise/conf.d/extra.toml": "[tools]\nnode = \"24\"\n", + ".config/mise/conf.d/x.local.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{ + { + Path: ".config/mise.toml", + Lockfile: ir.MiseLockfile{Path: ".config/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + { + Path: ".config/mise/conf.d/extra.toml", + Lockfile: ir.MiseLockfile{Path: ".config/mise/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + { + Path: ".config/mise/conf.d/x.local.toml", + Lockfile: ir.MiseLockfile{Path: ".config/mise/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + Local: true, + }, + { + Path: "mise.ci.toml", + Lockfile: ir.MiseLockfile{Path: "mise.ci.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + { + Path: "mise.local.toml", + Lockfile: ir.MiseLockfile{Path: "mise.local.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + Local: true, + }, + }, + LocalConfigs: []string{".config/mise/conf.d/x.local.toml", "mise.local.toml"}, + }, + }, + { + name: "every mise local config name is listed, other .local.toml files and exempt paths are not", + files: map[string]string{ + "mise.dev.local.toml": "", + ".mise.local.toml": "", + "svc/.config/mise/config.local.toml": "", + "svc/mise/config.ci.local.toml": "", + "tools/settings.local.toml": "", + "examples/mise.local.toml": "", + "svc/mise/conf.d/extra.local.toml": "", + }, + opts: Options{ExemptPaths: [][]string{{"examples/**"}}}, + want: &ir.MiseScan{ + // The policies apply exemptPaths to Configs; LocalConfigs + // is filtered here. + Configs: []ir.MiseConfig{ + {Path: ".mise.local.toml", Lockfile: ir.MiseLockfile{Path: "mise.local.lock"}, Local: true}, + {Path: "examples/mise.local.toml", Lockfile: ir.MiseLockfile{Path: "examples/mise.local.lock"}, Local: true}, + {Path: "svc/.config/mise/config.local.toml", Lockfile: ir.MiseLockfile{Path: "svc/.config/mise/mise.local.lock"}, Local: true}, + {Path: "svc/mise/conf.d/extra.local.toml", Lockfile: ir.MiseLockfile{Path: "svc/mise/mise.lock"}, Local: true}, + }, + LocalConfigs: []string{ + ".mise.local.toml", + "mise.dev.local.toml", + "svc/.config/mise/config.local.toml", + "svc/mise/conf.d/extra.local.toml", + "svc/mise/config.ci.local.toml", + }}, + }, + { + // A personal mise.local.toml on a developer's machine: git does + // not track it, so it is neither read (a broken one does not + // stop the run) nor listed. + name: "a local config git does not track is neither read nor listed", + files: map[string]string{ + "mise.toml": "[tools]\n", + "mise.local.toml": "[tools", + "mise.dev.local.toml": "", + "svc/mise.local.toml": "[tools]\nnode = \"24\"\n", + }, + opts: Options{Tracked: func(paths []string) []string { + var out []string + for _, p := range paths { + if strings.HasPrefix(p, "svc/") { + out = append(out, p) + } + } + return out + }}, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{ + {Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock"}}, + {Path: "svc/mise.local.toml", Lockfile: ir.MiseLockfile{Path: "svc/mise.local.lock"}, Local: true, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + }, + LocalConfigs: []string{"svc/mise.local.toml"}, + }, + }, + { + name: "subproject configs pair with the root lockfile in monorepo lockfile mode", + files: map[string]string{ + "mise.toml": "monorepo_root = true\n\n[monorepo]\nlockfile = true\n", + "mise.lock": lockV5, + "packages/api/mise.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}}, + { + Path: "packages/api/mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }, + }}, + }, + { + // A local file is personal: it does not pick the layout for + // the whole repository. + name: "[monorepo] lockfile in a root local config does not pair subprojects with the root lockfile", + files: map[string]string{ + "mise.local.toml": "[monorepo]\nlockfile = true\n", + "mise.lock": lockV5, + "svc/mise.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{ + {Path: "mise.local.toml", Lockfile: ir.MiseLockfile{Path: "mise.local.lock"}, Local: true}, + {Path: "svc/mise.toml", Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + }, + LocalConfigs: []string{"mise.local.toml"}, + }, + }, + { + name: "vendored, hidden and node_modules directories are skipped", + files: map[string]string{ + "node_modules/x/mise.toml": "[tools]\nnode = \"24\"\n", + "vendor/y/mise.toml": "[tools]\nnode = \"24\"\n", + ".github/mise.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{}, + }, + { + name: "tools only in .tool-versions are listed when the repository uses mise", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": lockV5, + ".tool-versions": "# pinned\nnode 24\npython 3.13 3.12\n", + }, + opts: Options{ToolVersions: true}, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }}, + ToolVersions: []ir.MiseToolVersionsEntry{{Path: ".tool-versions", Name: "python"}}, + }, + }, + { + name: "a file that does not parse is listed as unreadable", + files: map[string]string{ + "mise.toml": "[tools\nnode = ", + }, + wantErr: []string{"mise.toml"}, + }, + { + name: "an unreadable directory does not make the scan incomplete", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": lockV5, + "pgdata/PG_VERSION": "16\n", + }, + lockedDirs: []string{"pgdata"}, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }}, + }, + }, + { + name: ".tool-versions is not read when the lockfile check is off", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": lockV5, + "svc/.tool-versions": "python 3.13\n", + }, + symlinks: map[string]string{".tool-versions": "/etc/hosts"}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }}}, + }, + { + // mise opens .mise/config.toml through the link; the hidden + // target is skipped by the walk, so only the link shows it. + name: "a mise directory symlinked to a hidden directory is read under the link", + files: map[string]string{".hidden/config.toml": "[tools]\nnode = \"24\"\n"}, + symlinks: map[string]string{".mise": ".hidden"}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: ".mise/config.toml", + Lockfile: ir.MiseLockfile{Path: ".mise/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + }, + { + name: "a directory symlink loop is walked once", + files: map[string]string{"svc/mise.toml": "[tools]\nnode = \"24\"\n"}, + symlinks: map[string]string{"svc/up": "..", "loop": "."}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "svc/mise.toml", + Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + }, + { + name: "a mise directory symlinked outside the repository fails the scan", + files: map[string]string{"mise.toml": "[tools]\n", "mise.lock": lockV5}, + symlinks: map[string]string{".mise": "/etc"}, + wantErr: []string{".mise"}, + }, + { + name: "another directory symlinked outside the repository is ignored", + files: map[string]string{"mise.toml": "[tools]\n", "mise.lock": lockV5}, + symlinks: map[string]string{"data": "/etc"}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + }}}, + }, + { + name: "a symlink named like a skipped directory is not followed", + files: map[string]string{"deps/x/mise.toml": "[tools\n"}, + symlinks: map[string]string{"vendor": "deps", "node_modules": "deps"}, + wantErr: []string{"deps/x/mise.toml"}, + }, + { + name: "asdf names in .tool-versions match the mise tool they stand for", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\ngo = \"1.25\"\n", + ".tool-versions": "nodejs 24\ngolang 1.25\nshellcheck 0.10.0\n", + }, + opts: Options{ToolVersions: true}, + want: &ir.MiseScan{ + Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{{Name: "go", Request: "1.25"}, {Name: "node", Request: "24"}}, + }}, + ToolVersions: []ir.MiseToolVersionsEntry{{Path: ".tool-versions", Name: "shellcheck"}}, + }, + }, + { + // Checked with mise 2026.11.16: `mise settings get lockfile` + // in a subdirectory gives the closest config's value. + name: "a subproject inherits lockfile = false from a parent config unless it sets it back", + files: map[string]string{ + "mise.toml": "[settings]\nlockfile = false\n", + "svc/mise.toml": "[tools]\nnode = \"24\"\n", + "api/mise.toml": "[settings]\nlockfile = true\n[tools]\nnode = \"24\"\n", + "api/x/mise.toml": "[tools]\nnode = \"24\"\n", + "mise.ci.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: "api/mise.toml", Lockfile: ir.MiseLockfile{Path: "api/mise.lock"}, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + {Path: "api/x/mise.toml", Lockfile: ir.MiseLockfile{Path: "api/x/mise.lock"}, Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + {Path: "mise.ci.toml", Lockfile: ir.MiseLockfile{Path: "mise.ci.lock"}, LockfileDisabled: true, LockfileDisabledBy: "mise.toml", Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + {Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock"}, LockfileDisabled: true}, + {Path: "svc/mise.toml", Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, LockfileDisabled: true, LockfileDisabledBy: "mise.toml", Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + }}, + }, + { + // a/ reads true then false, b/ reads false then true: false + // wins either way, so a subproject of each inherits it. + name: "lockfile = false wins when two configs of one directory disagree", + files: map[string]string{ + "a/.config/mise/config.toml": "[settings]\nlockfile = true\n", + "a/mise.toml": "[settings]\nlockfile = false\n", + "a/x/mise.toml": "[tools]\nnode = \"24\"\n", + "b/.config/mise/config.toml": "[settings]\nlockfile = false\n", + "b/mise.toml": "[settings]\nlockfile = true\n", + "b/x/mise.toml": "[tools]\nnode = \"24\"\n", + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: "a/.config/mise/config.toml", Lockfile: ir.MiseLockfile{Path: "a/.config/mise/mise.lock"}}, + {Path: "a/mise.toml", Lockfile: ir.MiseLockfile{Path: "a/mise.lock"}, LockfileDisabled: true}, + {Path: "a/x/mise.toml", Lockfile: ir.MiseLockfile{Path: "a/x/mise.lock"}, LockfileDisabled: true, LockfileDisabledBy: "a/mise.toml", Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + {Path: "b/.config/mise/config.toml", Lockfile: ir.MiseLockfile{Path: "b/.config/mise/mise.lock"}, LockfileDisabled: true}, + {Path: "b/mise.toml", Lockfile: ir.MiseLockfile{Path: "b/mise.lock"}}, + {Path: "b/x/mise.toml", Lockfile: ir.MiseLockfile{Path: "b/x/mise.lock"}, LockfileDisabled: true, LockfileDisabledBy: "b/.config/mise/config.toml", Tools: []ir.MiseTool{{Name: "node", Request: "24"}}}, + }}, + }, + { + name: "a file exempt for one configuration only still fails the scan", + files: map[string]string{ + "mise.toml": "[tools]\n", + "examples/bad/mise.toml": "[tools", + }, + opts: Options{ExemptPaths: [][]string{{"examples/**"}, {}}}, + wantErr: []string{"examples/bad/mise.toml"}, + }, + { + name: "a file every configuration exempts does not fail the scan", + files: map[string]string{ + "mise.toml": "[tools]\n", + "examples/bad/mise.toml": "[tools", + }, + opts: Options{ExemptPaths: [][]string{{"examples/**"}, {"examples/bad/*"}}}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock"}}}}, + }, + { + name: "without Lockfiles no lockfile is read, so an unreadable one does not fail the scan", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": "[tools", + }, + noLockfiles: true, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + }, + { + name: "every unreadable file is listed in one error", + files: map[string]string{ + "mise.toml": "[tools\nnode = ", + "svc/mise.toml": "[tools]\nnode = \"24\"\n", + "svc/mise.lock": "[tools", + }, + wantErr: []string{"mise.toml", "svc/mise.lock"}, + }, + { + name: "an unreadable file under exemptPaths does not fail the scan", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise.lock": lockV5, + "examples/bad/mise.toml": "[tools", + }, + opts: Options{ExemptPaths: [][]string{{"examples/**"}}}, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "node", Request: "24", Locked: nodeLocked}}, + }}}, + }, + { + // svc/ locks into the root lockfile, which is exempt: the + // checked subproject still needs it, so it is reported. + name: "an exempt lockfile a checked config pairs with still fails the scan", + files: map[string]string{ + "mise.toml": "[monorepo]\nlockfile = true\n", + "mise.lock": "[tools", + "svc/mise.toml": "[tools]\nnode = \"24\"\n", + }, + opts: Options{ExemptPaths: [][]string{{"mise.toml", "mise.lock"}}}, + wantErr: []string{"mise.lock"}, + }, + { + name: "lock entries split per platform are merged and sorted, for every config sharing the lockfile", + files: map[string]string{ + "mise.toml": "[tools.\"github:o/t\"]\nversion = \"1\"\nplatforms.linux-x64.url = \"https://example.com/t\"\n", + ".mise.toml": "[tools]\n\"github:o/t\" = \"1\"\n", + "mise.lock": `lockfile_version = 5 + +[[tools."github:o/t"]] +version = "1.0.0" +backend = "github:o/t" +specifiers = ["1"] + +[tools."github:o/t"."platforms.macos-arm64"] +checksum = "sha256:bb" +url = "https://example.com/t-mac" + +[[tools."github:o/t"]] +version = "1.0.0" +backend = "github:o/t" +specifiers = ["1"] + +[tools."github:o/t".options] +url = "https://example.com/t" + +[tools."github:o/t"."platforms.linux-x64"] +checksum = "sha256:aa" +url = "https://example.com/t" +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{ + { + Path: ".mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{Name: "github:o/t", Request: "1", Locked: mergedT}}, + }, + { + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: []ir.MiseTool{{ + Name: "github:o/t", Request: "1", Locked: mergedT, + SourceOptions: []ir.MiseToolOption{{Name: "platforms.linux-x64.url", Value: "https://example.com/t"}}, + }}, + }, + }}, + }, + { + name: "source options in every form; of the settings, only url_replacements is kept", + files: map[string]string{ + "mise.toml": `[settings] +lockfile = false +aqua.registries = ["https://github.com/my-org/aqua-registry", "registry.yaml"] +aqua.registry_url = "https://example.com/old" +node.mirror_url = "https://node-mirror.example.com/" +go.download_mirror = "https://go-mirror.example.com" +pypi.registry_url = "https://pypi.example.com/{}/json" +dotnet.registry_url = "https://nuget.example.com/v3/index.json" +ruby.precompiled_url = "my-org/ruby" +experimental = true +"conda.channel" = "my-channel" +go.repo = "https://example.com/go" +pipx.registry_url = "https://pipx.example.com/{}/json" +python.pyenv_repo = "https://example.com/pyenv" +ruby.ruby_build_repo = "https://example.com/ruby-build" +ruby.ruby_install_repo = "https://example.com/ruby-install" + +[settings.url_replacements] +"https://releases.hashicorp.com/" = "https://hashicorp-mirror.example.com/" +"https://github.com/" = "https://gh-mirror.example.com/" + +[plugins] +mytool = "https://github.com/someone/asdf-mytool" + +[env] +GOPROXY = "https://goproxy.example.com" +PIP_INDEX_URL = "https://pypi.example.com/simple" +UNRELATED = "x" + +[tools] +"github:cli/cli" = { version = "2.60.0", api_url = "https://ghe.example.com/api/v3", asset_pattern = "gh_*" } +"github:org/a[api_url=https://ghe.example.com/api/v3,exe=a]" = "1" +"http:b" = { version = "1", url = "https://example.com/b-{{ version }}.tgz" } +"http:d" = [{ version = "1", url = "https://a/x" }, { version = "2", url = "https://a/y" }] +"pipx:black" = { version = "24", registry_url = "https://r.example.com", uvx_args = "--index-url https://u.example.com", pipx_args = "--pip-args=--index-url=https://p.example.com", indexes = [{ name = "x", url = "https://idx.example.com/simple" }], install_env = { PIP_INDEX_URL = "https://env.example.com/simple", UV_EXTRA_INDEX_URL = "https://uv-extra.example.com/simple", "NPM_CONFIG_@acme:registry" = "https://npm.example.com", CFLAGS = "-O2" } } +"pipx:poetry" = { version = "1.8", pipx_args = "--include-deps --system-site-packages", uvx_args = "--prerelease=allow" } + +[tools."github:org/c"] +version = "3" +platforms.linux-x64.url = "https://example.com/c-linux" +"platforms.macos-arm64" = { url = "https://example.com/c-mac" } +`, + }, + want: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + LockfileDisabled: true, + Tools: []ir.MiseTool{ + {Name: "github:cli/cli", Request: "2.60.0", SourceOptions: []ir.MiseToolOption{{Name: "api_url", Value: "https://ghe.example.com/api/v3"}}}, + {Name: "github:org/a", Request: "1", SourceOptions: []ir.MiseToolOption{{Name: "api_url", Value: "https://ghe.example.com/api/v3"}}}, + {Name: "github:org/c", Request: "3", SourceOptions: []ir.MiseToolOption{ + {Name: "platforms.linux-x64.url", Value: "https://example.com/c-linux"}, + {Name: "platforms.macos-arm64.url", Value: "https://example.com/c-mac"}, + }}, + {Name: "http:b", Request: "1", SourceOptions: []ir.MiseToolOption{{Name: "url", Value: "https://example.com/b-{{ version }}.tgz"}}}, + {Name: "http:d", Request: "1", SourceOptions: []ir.MiseToolOption{{Name: "url", Value: "https://a/x"}}}, + {Name: "http:d", Request: "2", SourceOptions: []ir.MiseToolOption{{Name: "url", Value: "https://a/y"}}}, + {Name: "pipx:black", Request: "24", SourceOptions: []ir.MiseToolOption{ + {Name: "indexes", Value: "https://idx.example.com/simple"}, + {Name: "install_env.NPM_CONFIG_@acme:registry", Value: "https://npm.example.com"}, + {Name: "install_env.PIP_INDEX_URL", Value: "https://env.example.com/simple"}, + {Name: "install_env.UV_EXTRA_INDEX_URL", Value: "https://uv-extra.example.com/simple"}, + {Name: "pipx_args", Value: "https://p.example.com"}, + {Name: "registry_url", Value: "https://r.example.com"}, + {Name: "uvx_args", Value: "https://u.example.com"}, + }}, + {Name: "pipx:poetry", Request: "1.8"}, + }, + SourceSettings: []ir.MiseSetting{ + {Name: "url_replacements", Value: "https://gh-mirror.example.com/"}, + {Name: "url_replacements", Value: "https://hashicorp-mirror.example.com/"}, + }, + }}}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := writeRepo(t, tc.files) + for rel, target := range tc.symlinks { + if err := os.Symlink(target, filepath.Join(root, filepath.FromSlash(rel))); err != nil { + t.Fatal(err) + } + } + for _, d := range tc.lockedDirs { + if os.Geteuid() == 0 { + t.Skip("root reads any directory") + } + p := filepath.Join(root, d) + if err := os.Chmod(p, 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(p, 0o755) }) + } + opts := tc.opts + if !tc.noLockfiles { + opts.Lockfiles = true + } + got, err := scanBoth(t, root, opts, len(tc.lockedDirs) == 0) + var gotErr []string + if re, ok := errors.AsType[*ReadError](err); ok { + for _, f := range re.Files { + if f.Reason == "" { + t.Errorf("%s: empty reason", f.Path) + } + gotErr = append(gotErr, f.Path) + } + } else if err != nil { + t.Fatalf("Scan error = %v, want a *ReadError or nil", err) + } + if !reflect.DeepEqual(gotErr, tc.wantErr) { + t.Errorf("Scan unreadable files = %v, want %v", gotErr, tc.wantErr) + } + if tc.wantErr == nil && !reflect.DeepEqual(got, tc.want) { + t.Errorf("Scan =\n%#v\nwant\n%#v", got, tc.want) + } + }) + } +} + +func TestArgURLs(t *testing.T) { + cases := []struct { + name string + args string + want []string + }{ + {name: "no URL", args: "--include-deps --system-site-packages"}, + {name: "uv flag with equals", args: "--prerelease=allow"}, + {name: "pipx force is not find-links", args: "-f --include-deps"}, + {name: "index url with space", args: "--index-url https://a.example.com/simple", want: []string{"https://a.example.com/simple"}}, + {name: "index url with equals", args: "--index-url=https://a.example.com", want: []string{"https://a.example.com"}}, + {name: "nested in pip-args", args: "--pip-args=--index-url=https://p.example.com", want: []string{"https://p.example.com"}}, + {name: "quoted pip-args with short flag", args: "--pip-args '-i https://p.example.com --no-cache-dir'", want: []string{"https://p.example.com"}}, + {name: "value attached to a short flag", args: "--pip-args=-ihttps://evil.example/simple", want: []string{"https://evil.example/simple"}}, + {name: "abbreviated long flag", args: "--pip-args='--extra-index https://evil.example/simple'", want: []string{"https://evil.example/simple"}}, + {name: "force then index", args: "--force -i https://x.example.com", want: []string{"https://x.example.com"}}, + {name: "several URLs", args: "--extra-index-url https://b.example.com --default-index https://c.example.com --find-links https://d.example.com", want: []string{"https://b.example.com", "https://c.example.com", "https://d.example.com"}}, + {name: "uv named index", args: "--index internal=https://i.example.com/simple", want: []string{"https://i.example.com/simple"}}, + {name: "unknown scheme kept whole", args: "--index-url weird://host/simple", want: []string{"weird://host/simple"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := argURLs(tc.args) + if !slices.Equal(got, tc.want) { + t.Errorf("argURLs(%q) = %q, want %q", tc.args, got, tc.want) + } + }) + } +} + +func TestReadErrorError(t *testing.T) { + cases := []struct { + name string + err *ReadError + want string + }{ + { + name: "one line per file under the exemptPaths hint", + err: &ReadError{Files: []UnreadableFile{ + {Path: "mise.toml", Reason: "toml: expected character ]"}, + {Path: "svc/mise.lock", Reason: "larger than 2097152 bytes"}, + }}, + want: "cannot read the mise files below; fix them or list their paths in mise.exemptPaths:" + + "\n - mise.toml: toml: expected character ]" + + "\n - svc/mise.lock: larger than 2097152 bytes", + }, + { + name: "control characters in a path or reason are escaped", + err: &ReadError{Files: []UnreadableFile{ + {Path: "mise.\n - fake.toml: ok\x1b[2J.toml", Reason: "bad\rreason"}, + }}, + want: "cannot read the mise files below; fix them or list their paths in mise.exemptPaths:" + + ` + - mise.\n - fake.toml: ok\x1b[2J.toml: bad\rreason`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.err.Error(); got != tc.want { + t.Errorf("Error() =\n%s\nwant\n%s", got, tc.want) + } + }) + } +} + +func TestScanErrors(t *testing.T) { + cases := []struct { + name string + files map[string]string + opts Options + wantSub string + }{ + { + name: "an invalid exemptPaths glob is a config error", + opts: Options{ExemptPaths: [][]string{{"["}}}, + wantSub: "mise.exemptPaths: invalid glob", + }, + { + name: "the error names files by their repository path, not the host path", + files: map[string]string{"mise.toml": "[tools"}, + wantSub: "\n - mise.toml: ", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := writeRepo(t, tc.files) + _, err := Scan(DirFS(root), tc.opts) + if err == nil || !strings.Contains(err.Error(), tc.wantSub) { + t.Fatalf("Scan error = %v, want it to contain %q", err, tc.wantSub) + } + if strings.Contains(err.Error(), root) { + t.Errorf("Scan error %q holds the host path %q", err, root) + } + }) + } +} + +func TestOptionsWanted(t *testing.T) { + all := Options{Lockfiles: true, ToolVersions: true, Tasks: true} + none := Options{} + link := fs.ModeSymlink | 0o777 + cases := []struct { + path string + mode fs.FileMode + wantAll bool + wantNone bool + }{ + {path: "mise.toml", mode: 0o644, wantAll: true, wantNone: true}, + {path: "svc/.mise.toml", mode: 0o644, wantAll: true, wantNone: true}, + {path: ".config/mise/config.toml", mode: 0o644, wantAll: true, wantNone: true}, + {path: ".config/mise/conf.d/a.toml", mode: 0o644, wantAll: true, wantNone: true}, + {path: "mise.local.toml", mode: 0o644, wantAll: true, wantNone: true}, + {path: "mise.dev.local.toml", mode: 0o644, wantAll: true, wantNone: true}, + {path: "mise.lock", mode: 0o644, wantAll: true}, + {path: "svc/mise.dev.lock", mode: 0o644, wantAll: true}, + {path: ".tool-versions", mode: 0o644, wantAll: true}, + {path: "svc/mise-tasks/build", mode: 0o755, wantAll: true}, + {path: ".mise/tasks/build", mode: 0o755, wantAll: true}, + {path: "link", mode: link, wantAll: true, wantNone: true}, + {path: "config.toml", mode: 0o644}, + {path: "README.md", mode: 0o644}, + {path: "svc", mode: fs.ModeDir | 0o755}, + {path: "node_modules/x/mise.toml", mode: 0o644}, + {path: "vendor/link", mode: link}, + {path: ".github/mise-tasks/x", mode: 0o755}, + } + for _, tc := range cases { + if got := all.Wanted(tc.path, tc.mode); got != tc.wantAll { + t.Errorf("Wanted(%s) with every check = %v, want %v", tc.path, got, tc.wantAll) + } + if got := none.Wanted(tc.path, tc.mode); got != tc.wantNone { + t.Errorf("Wanted(%s) with configs only = %v, want %v", tc.path, got, tc.wantNone) + } + } +} diff --git a/packagemanager/mise/tasks.go b/packagemanager/mise/tasks.go new file mode 100644 index 00000000..89c8228a --- /dev/null +++ b/packagemanager/mise/tasks.go @@ -0,0 +1,519 @@ +package mise + +import ( + "bufio" + "bytes" + "errors" + "io/fs" + "path" + "regexp" + "slices" + "sort" + "strings" + "syscall" + + "github.com/gobwas/glob" + "github.com/pelletier/go-toml/v2" + + "github.com/getplumber/plumber/internal/ir" +) + +// defaultTaskDirs are the directories, relative to a config root, mise +// reads file tasks and TOML task files from when no config of that root +// sets task_config.includes. +var defaultTaskDirs = []string{"mise-tasks", ".mise-tasks", ".mise/tasks", ".config/mise/tasks", "mise/tasks"} + +// remoteIncludePrefixes mark task includes mise fetches from elsewhere, +// which Plumber cannot read from the checkout. +var remoteIncludePrefixes = []string{"git::", "oci::", "zip::"} + +// scriptExtensions are the extensions mise drops from a file task's name +// (compared case-insensitively). Any other extension stays in the name. +var scriptExtensions = map[string]bool{ + ".sh": true, ".bash": true, ".zsh": true, ".fish": true, ".ksh": true, ".nu": true, + ".js": true, ".mjs": true, ".cjs": true, ".ts": true, + ".py": true, ".rb": true, ".pl": true, ".php": true, ".lua": true, + ".ps1": true, ".bat": true, ".cmd": true, +} + +// maxTaskFiles bounds the files and directories the task walk visits in +// one scan. The repository is not trusted: past the cap, the include +// being read counts as unread, so the check fails closed. +var maxTaskFiles = 20000 + +var ( + // headerRe matches a `#MISE` header line of a file task. The marker can + // be #, // or ::, and the keyword can be bracketed (`# [MISE]`). + headerRe = regexp.MustCompile(`^\s*(?:#|//|::)\s*(?:MISE|\[MISE\])\s+(\S.*)$`) + // configRootRe matches the `{{ config_root }}` template, which is the + // project directory and so can be resolved statically. + configRootRe = regexp.MustCompile(`\{\{\s*config_root\s*\}\}`) + + errTaskBudget = errors.New("too many task files") +) + +// projectTasks is what one project directory declares itself, from the +// configs mise loads by default (not the mise..toml ones). +type projectTasks struct { + path string // the config the project's findings point at + pathLocal bool // path is a *.local.toml, kept until a shared config shows up + tasks []ir.MiseTask + includes []string + hasIncludes bool + disablePaths []string // [settings] task.disable_paths, repository paths + skip []string // [settings] task.skip, task names +} + +// addConfig records the tasks, includes and task settings of one config +// of the project. dir is the project directory. +func (p *projectTasks) addConfig(rel, dir string, local bool, doc map[string]any) { + if p.path == "" || (p.pathLocal && !local) { + p.path, p.pathLocal = rel, local + } + if table, ok := doc["tasks"].(map[string]any); ok { + p.tasks = append(p.tasks, tomlTasks(table, rel)...) + } + if settings, ok := doc["settings"].(map[string]any); ok { + for _, v := range settingValues(settings, "task.disable_paths") { + for _, s := range stringList(v) { + if !strings.HasPrefix(s, "/") && !strings.HasPrefix(s, "~") { + p.disablePaths = append(p.disablePaths, path.Join(dir, s)) + } + } + } + for _, v := range settingValues(settings, "task.skip") { + p.skip = append(p.skip, stringList(v)...) + } + } + cfg, ok := doc["task_config"].(map[string]any) + if !ok { + return + } + inc, ok := cfg["includes"].([]any) + if !ok { + return + } + p.hasIncludes = true + for _, e := range inc { + if s, ok := e.(string); ok { + p.includes = append(p.includes, s) + } + } +} + +// tomlTasks reads the tasks of a [tasks] table or of a TOML task file: +// each key is a task; a table may set alias (a string or a list). +func tomlTasks(table map[string]any, source string) []ir.MiseTask { + var out []ir.MiseTask + for name, v := range table { + t := ir.MiseTask{Name: name, Source: source} + if m, ok := v.(map[string]any); ok { + t.Aliases = stringList(m["alias"]) + } + out = append(out, t) + } + return out +} + +func stringList(v any) []string { + switch val := v.(type) { + case string: + return []string{val} + case []any: + var out []string + for _, e := range val { + if s, ok := e.(string); ok { + out = append(out, s) + } + } + return out + } + return nil +} + +// taskCollector reads task directories and files for one scan. It keeps +// every read inside the repository, reads each file once, and stops at +// maxTaskFiles. +type taskCollector struct { + fsys FS + unreadable unreadableSet + visited int + // files caches what a file declares, by its resolved path: a TOML + // task file's tasks (Source unset), or a file task's aliases. + tomlCache map[string][]ir.MiseTask + aliasCache map[string][]string +} + +// collectProjects returns one entry per project directory: the tasks +// mise offers there, its own and those of every parent directory's +// configs (mise makes a parent's tasks available in its subdirectories), +// and the includes Plumber could not read. A directory whose config, or a +// parent's config, cannot be read is left out: what it declares is +// unknown (only possible under exemptPaths: otherwise the unreadable file +// stops the run). A TOML task file that cannot be read is added to +// unreadable, which stops the run too. +func collectProjects(fsys FS, own map[string]*projectTasks, unknown map[string]bool, unreadable unreadableSet) []ir.MiseProject { + c := &taskCollector{fsys: fsys, unreadable: unreadable, tomlCache: map[string][]ir.MiseTask{}, aliasCache: map[string][]string{}} + + dirs := make([]string, 0, len(own)) + for d := range own { + dirs = append(dirs, d) + } + sort.Strings(dirs) + + type resolved struct { + tasks []ir.MiseTask + unread []string + } + byDir := map[string]resolved{} + for _, d := range dirs { + p := own[d] + r := resolved{tasks: append([]ir.MiseTask(nil), p.tasks...)} + includes := defaultTaskDirs + if p.hasIncludes { + includes = p.includes + } + seen := map[string]bool{} // resolved include targets already read + for _, inc := range includes { + tasks, unread := c.includeTasks(d, inc, seen) + r.tasks = append(r.tasks, tasks...) + if unread && !slices.Contains(r.unread, inc) { + r.unread = append(r.unread, inc) + } + } + byDir[d] = r + } + + var out []ir.MiseProject + for _, d := range dirs { + if underAny(d, unknown) { + continue + } + var disabled, skip []string + for _, a := range dirs { + if isAncestorOrSelf(a, d) { + disabled = append(disabled, own[a].disablePaths...) + skip = append(skip, own[a].skip...) + } + } + proj := ir.MiseProject{Dir: d, Path: own[d].path} + for _, a := range dirs { + if !isAncestorOrSelf(a, d) { + continue + } + for _, t := range byDir[a].tasks { + if !taskDropped(t, disabled, skip) { + proj.Tasks = append(proj.Tasks, t) + } + } + proj.UnreadIncludes = append(proj.UnreadIncludes, byDir[a].unread...) + } + sort.SliceStable(proj.Tasks, func(i, j int) bool { + if proj.Tasks[i].Name != proj.Tasks[j].Name { + return proj.Tasks[i].Name < proj.Tasks[j].Name + } + return proj.Tasks[i].Source < proj.Tasks[j].Source + }) + out = append(out, proj) + } + return out +} + +// taskDropped reports whether task.skip names the task or +// task.disable_paths holds the file that declares it. +func taskDropped(t ir.MiseTask, disabled, skip []string) bool { + for _, s := range skip { + if s == t.Name { + return true + } + } + for _, d := range disabled { + if isAncestorOrSelf(d, t.Source) { + return true + } + } + return false +} + +// isAncestorOrSelf reports whether directory a is d or one of its +// parents ("" is the repository root). +func isAncestorOrSelf(a, d string) bool { + return a == "" || a == d || strings.HasPrefix(d, a+"/") +} + +// underAny reports whether d is, or is under, one of dirs. +func underAny(d string, dirs map[string]bool) bool { + for u := range dirs { + if isAncestorOrSelf(u, d) { + return true + } + } + return false +} + +// includeTasks reads one task_config.includes entry (or default task +// directory) of the config root dir. unread is true when the entry cannot +// be read from the checkout: a remote include, a template other than +// `{{ config_root }}`, a path outside the repository, a bad glob, or more +// files than maxTaskFiles. A path that does not exist declares nothing. +// seen holds the resolved targets the project already read. +func (c *taskCollector) includeTasks(dir, inc string, seen map[string]bool) (tasks []ir.MiseTask, unread bool) { + rel := configRootRe.ReplaceAllString(inc, ".") + if strings.Contains(rel, "{{") || strings.HasPrefix(rel, "/") || strings.HasPrefix(rel, "~") { + return nil, true + } + for _, p := range remoteIncludePrefixes { + if strings.HasPrefix(rel, p) { + return nil, true + } + } + repoPath := path.Join(dir, rel) + if repoPath == ".." || strings.HasPrefix(repoPath, "../") { + return nil, true + } + matches := []string{repoPath} + if strings.ContainsAny(rel, "*?[{") { + var err error + if matches, err = c.globMatches(repoPath); err != nil { + return nil, true + } + } + for _, m := range matches { + got, err := c.pathTasks(m, seen) + // Tasks found before an error (the file cap) are real; the rest of + // the include is not read, so it counts as unread. + tasks = append(tasks, got...) + if err != nil { + return tasks, true + } + } + return tasks, false +} + +// globMatches returns the repository paths matching pattern, a +// repository path glob where `*` stays within a directory and `**` +// crosses directories, as mise reads include globs. +func (c *taskCollector) globMatches(pattern string) ([]string, error) { + g, err := glob.Compile(pattern, '/') + if err != nil { + return nil, err + } + base := pattern + if i := strings.IndexAny(pattern, "*?[{"); i >= 0 { + base = path.Dir(pattern[:i+1]) + } + if base == "." { + base = "" + } + // Without `**`, a match is exactly as deep as the pattern: the walk + // stops there instead of visiting the whole tree under base. + depth := -1 + if !strings.Contains(pattern, "**") { + depth = strings.Count(pattern, "/") - strings.Count(base, "/") + if base == "" { + depth++ + } + } + var out []string + err = c.walk(base, depth, func(repoPath string, isDir bool) error { + if g.Match(repoPath) { + out = append(out, repoPath) + } + return nil + }) + return out, err +} + +// pathTasks reads a task directory or a TOML task file at repoPath. A +// path with nothing at it declares nothing; one that resolves outside the +// repository is an error, so the include counts as unread. +func (c *taskCollector) pathTasks(repoPath string, seen map[string]bool) ([]ir.MiseTask, error) { + if _, err := c.fsys.Lstat(fsName(repoPath)); err != nil { + // ENOTDIR: a path under a file, nothing there either (the remote + // FS answers not-exist for it). + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) { + return nil, nil // nothing there: no task + } + // A path under a link out of the repository (a remote read cannot + // look past it) or a directory that cannot be read: unread. + return nil, err + } + real, err := c.fsys.Resolve(fsName(repoPath)) + if err != nil { + return nil, err + } + if seen[real] { + return nil, nil + } + seen[real] = true + info, err := fs.Stat(c.fsys, real) + if err != nil { + return nil, err + } + if info.IsDir() { + return c.dirTasks(repoPath) + } + if strings.HasSuffix(repoPath, ".toml") { + return c.taskFileTasks(repoPath, real), nil + } + return nil, nil +} + +// walk visits every entry under the repository directory base, depth +// first, following a symlinked directory only when it resolves inside the +// repository and was not visited yet. Hidden entries are skipped. maxDepth +// bounds how many levels below base are visited (-1: no bound). It stops +// with errTaskBudget past maxTaskFiles. +func (c *taskCollector) walk(base string, maxDepth int, visit func(repoPath string, isDir bool) error) error { + realBase, err := c.fsys.Resolve(fsName(base)) + if err != nil { + return nil //nolint:nilerr // nothing (readable) there + } + visitedDirs := map[string]bool{realBase: true} + var rec func(repoDir, realDir string, depth int) error + rec = func(repoDir, realDir string, depth int) error { + if maxDepth >= 0 && depth > maxDepth { + return nil + } + entries, err := fs.ReadDir(c.fsys, realDir) + if err != nil { + return nil //nolint:nilerr // an unreadable directory declares no task + } + for _, e := range entries { + if strings.HasPrefix(e.Name(), ".") { + continue + } + c.visited++ + if c.visited > maxTaskFiles { + return errTaskBudget + } + repoPath := path.Join(repoDir, e.Name()) + real, err := c.fsys.Resolve(repoPath) + if err != nil { + continue // broken, or out of the repository + } + info, err := fs.Stat(c.fsys, real) + if err != nil { + continue + } + if err := visit(repoPath, info.IsDir()); err != nil { + return err + } + if info.IsDir() && !visitedDirs[real] { + visitedDirs[real] = true + if err := rec(repoPath, real, depth+1); err != nil { + return err + } + } + } + return nil + } + return rec(base, realBase, 1) +} + +// dirTasks reads a task directory: each executable file is a file task +// named by its path below the directory (`db/migrate.sh` is `db:migrate`, +// `test/_default` is `test`), each *.toml file is a TOML task file. +func (c *taskCollector) dirTasks(dir string) ([]ir.MiseTask, error) { + var out []ir.MiseTask + err := c.walk(dir, -1, func(repoPath string, isDir bool) error { + if isDir { + return nil + } + real, err := c.fsys.Resolve(repoPath) + if err != nil { + return nil //nolint:nilerr // checked by walk + } + if strings.HasSuffix(repoPath, ".toml") { + out = append(out, c.taskFileTasks(repoPath, real)...) + return nil + } + sub := strings.TrimPrefix(repoPath, dir+"/") + if dir == "" { + sub = repoPath + } + if t, ok := c.fileTask(repoPath, real, sub); ok { + out = append(out, t) + } + return nil + }) + return out, err +} + +// taskFileTasks reads a TOML task file. One that cannot be parsed is +// added to the scan's unreadable files, which stops the run. +func (c *taskCollector) taskFileTasks(repoPath, real string) []ir.MiseTask { + cached, ok := c.tomlCache[real] + if !ok { + doc, err := readTOML(c.fsys, repoPath) + if err != nil { + c.unreadable.add(repoPath, err) + c.tomlCache[real] = nil + return nil + } + cached = tomlTasks(doc, "") + c.tomlCache[real] = cached + } + out := make([]ir.MiseTask, len(cached)) + for i, t := range cached { + t.Source = repoPath + out[i] = t + } + return out +} + +// fileTask returns the task of one file of a task directory, when mise +// would load it: a regular, executable file. +func (c *taskCollector) fileTask(repoPath, real, sub string) (ir.MiseTask, bool) { + info, err := fs.Stat(c.fsys, real) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { + return ir.MiseTask{}, false + } + name := sub + if ext := path.Ext(name); scriptExtensions[strings.ToLower(ext)] { + name = strings.TrimSuffix(name, ext) + } + if path.Base(name) == "_default" { + name = path.Dir(name) + if name == "." { + return ir.MiseTask{}, false + } + } + aliases, ok := c.aliasCache[real] + if !ok { + aliases = headerAliases(c.fsys, repoPath) + c.aliasCache[real] = aliases + } + return ir.MiseTask{Name: strings.ReplaceAll(name, "/", ":"), Aliases: aliases, Source: repoPath}, true +} + +// headerAliases reads the alias of a file task's `#MISE alias=...` +// header lines. Each header line holds TOML. +func headerAliases(fsys FS, name string) []string { + data, err := readFile(fsys, name) + if err != nil { + return nil + } + var out []string + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + m := headerRe.FindStringSubmatch(sc.Text()) + if m == nil { + continue + } + kv := map[string]any{} + if toml.Unmarshal([]byte(m[1]), &kv) != nil { + continue + } + out = append(out, stringList(kv["alias"])...) + } + return out +} + +// fsName is the FS name of a repository path, where "" is the root. +func fsName(repoPath string) string { + if repoPath == "" { + return "." + } + return repoPath +} diff --git a/packagemanager/mise/tasks_test.go b/packagemanager/mise/tasks_test.go new file mode 100644 index 00000000..7f300a03 --- /dev/null +++ b/packagemanager/mise/tasks_test.go @@ -0,0 +1,384 @@ +package mise + +import ( + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/getplumber/plumber/internal/ir" +) + +func TestCollectProjects(t *testing.T) { + cases := []struct { + name string + files map[string]string + // executables are made executable after the files are written. + executables []string + // symlinks maps a repository path to a link target. A target that + // starts with "OUTSIDE/" points into a directory outside the + // repository, holding outsideFiles. + symlinks map[string]string + outsideFiles map[string]string + // budget, when set, replaces maxTaskFiles for the case. + budget int + want []ir.MiseProject + // wantUnreadable lists the files the *ReadError names; the run + // stops, so Projects is not checked then. + wantUnreadable []string + // exemptPaths is Options.ExemptPaths. + exemptPaths [][]string + }{ + { + name: "config tasks with aliases, file tasks named as mise names them, TOML task files", + files: map[string]string{ + "mise.toml": `[tasks.lint] +alias = "l" +run = "golangci-lint run" + +[tasks.build] +alias = ["b", "bld"] +run = "go build" + +[tasks] +fmt = "gofmt -w ." +`, + "mise-tasks/test/_default": "#!/bin/sh\n#MISE alias=\"t\"\n# [MISE] description=\"tests\"\ngo test ./...\n", + "mise-tasks/test/integration": "#!/bin/sh\n", + "mise-tasks/db/migrate.sh": "#!/bin/sh\n// MISE alias=[\"m\"]\n", + "mise-tasks/check.zsh": "#!/bin/zsh\n:: MISE alias=\"c\"\n#MISE alias = [not toml\n", + "mise-tasks/pack.SH": "#!/bin/sh\n", + "mise-tasks/notes.txt": "#!/bin/sh\n", + "mise-tasks/readme": "not executable, not a task\n", + "mise-tasks/_default": "#!/bin/sh\n", + "mise-tasks/.hidden": "#!/bin/sh\n", + "mise-tasks/.cache/x": "#!/bin/sh\n", + ".mise/tasks/scan": "#!/bin/sh\n", + ".mise/tasks/extra.toml": "release = \"goreleaser\"\n\n[deploy]\nalias = \"d\"\nrun = \"x\"\n", + }, + executables: []string{ + "mise-tasks/test/_default", "mise-tasks/test/integration", "mise-tasks/db/migrate.sh", + "mise-tasks/check.zsh", "mise-tasks/pack.SH", "mise-tasks/notes.txt", "mise-tasks/_default", + "mise-tasks/.hidden", "mise-tasks/.cache/x", ".mise/tasks/scan", + }, + want: []ir.MiseProject{{ + Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{ + {Name: "build", Aliases: []string{"b", "bld"}, Source: "mise.toml"}, + {Name: "check", Aliases: []string{"c"}, Source: "mise-tasks/check.zsh"}, + {Name: "db:migrate", Aliases: []string{"m"}, Source: "mise-tasks/db/migrate.sh"}, + {Name: "deploy", Aliases: []string{"d"}, Source: ".mise/tasks/extra.toml"}, + {Name: "fmt", Source: "mise.toml"}, + {Name: "lint", Aliases: []string{"l"}, Source: "mise.toml"}, + {Name: "notes.txt", Source: "mise-tasks/notes.txt"}, + {Name: "pack", Source: "mise-tasks/pack.SH"}, + {Name: "release", Source: ".mise/tasks/extra.toml"}, + {Name: "scan", Source: ".mise/tasks/scan"}, + {Name: "test", Aliases: []string{"t"}, Source: "mise-tasks/test/_default"}, + {Name: "test:integration", Source: "mise-tasks/test/integration"}, + }, + }}, + }, + { + name: "subprojects inherit their parents' tasks, task dirs and unread includes, not their siblings'", + files: map[string]string{ + "mise.toml": "[tasks.lint]\nrun = \"x\"\n\n[task_config]\nincludes = [\"mise-tasks\", \"git::https://github.com/org/shared.git//tasks?ref=v1\"]\n", + "mise-tasks/fmt": "#!/bin/sh\n", + "svc/api/mise.toml": "[tasks.test]\nrun = \"x\"\n", + "svc/api/mise-tasks/x": "#!/bin/sh\n", + "svc/api/mise.local.toml": "[tasks.mine]\nrun = \"x\"\n", + "svc/web/mise.toml": "[tools]\nnode = \"24\"\n", + }, + executables: []string{"mise-tasks/fmt", "svc/api/mise-tasks/x"}, + want: []ir.MiseProject{ + {Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{ + {Name: "fmt", Source: "mise-tasks/fmt"}, + {Name: "lint", Source: "mise.toml"}, + }, + UnreadIncludes: []string{"git::https://github.com/org/shared.git//tasks?ref=v1"}, + }, + {Dir: "svc/api", Path: "svc/api/mise.toml", + Tasks: []ir.MiseTask{ + {Name: "fmt", Source: "mise-tasks/fmt"}, + {Name: "lint", Source: "mise.toml"}, + {Name: "mine", Source: "svc/api/mise.local.toml"}, + {Name: "test", Source: "svc/api/mise.toml"}, + {Name: "x", Source: "svc/api/mise-tasks/x"}, + }, + UnreadIncludes: []string{"git::https://github.com/org/shared.git//tasks?ref=v1"}, + }, + {Dir: "svc/web", Path: "svc/web/mise.toml", + Tasks: []ir.MiseTask{ + {Name: "fmt", Source: "mise-tasks/fmt"}, + {Name: "lint", Source: "mise.toml"}, + }, + UnreadIncludes: []string{"git::https://github.com/org/shared.git//tasks?ref=v1"}, + }, + }, + }, + { + name: "task_config.includes: files, globs, ** and config_root are read; remote, templated, outside and bad globs are not", + files: map[string]string{ + "mise.toml": `[task_config] +includes = [ + "tasks.toml", + "ci/*.toml", + "deep/**/*.toml", + "scripts", + "{{config_root}}/tpl", + "{{ config_root }}/missing", + "git::https://github.com/org/shared.git//tasks?ref=v1", + "oci::ghcr.io/org/tasks:v1", + "zip::https://example.com/tasks.zip", + "{{ env.HOME }}/more", + "/abs/tasks", + "~/tasks", + "../outside", + "ci/[.toml", + "missing-dir", +] +`, + "tasks.toml": "lint = \"x\"\n", + "ci/a.toml": "test = \"x\"\n", + "ci/sub/c.toml": "notmatched = \"x\"\n", + "deep/a/b/d.toml": "scan = \"x\"\n", + "scripts/build": "#!/bin/sh\n", + "tpl/gen": "#!/bin/sh\n", + "mise-tasks/ignored": "#!/bin/sh\n", + }, + executables: []string{"scripts/build", "tpl/gen", "mise-tasks/ignored"}, + want: []ir.MiseProject{{ + Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{ + {Name: "build", Source: "scripts/build"}, + {Name: "gen", Source: "tpl/gen"}, + {Name: "lint", Source: "tasks.toml"}, + {Name: "scan", Source: "deep/a/b/d.toml"}, + {Name: "test", Source: "ci/a.toml"}, + }, + UnreadIncludes: []string{ + "git::https://github.com/org/shared.git//tasks?ref=v1", + "oci::ghcr.io/org/tasks:v1", + "zip::https://example.com/tasks.zip", + "{{ env.HOME }}/more", + "/abs/tasks", + "~/tasks", + "../outside", + "ci/[.toml", + }, + }}, + }, + { + name: "an empty includes list drops the default task dirs, and a repeated include is read once", + files: map[string]string{ + "mise.toml": "[task_config]\nincludes = []\n", + "mise-tasks/x": "#!/bin/sh\n", + "svc/mise.toml": "[task_config]\nincludes = [\"t\", \"t\", \"./t\", \"git::x\", \"git::x\"]\n", + "svc/t/build": "#!/bin/sh\n", + }, + executables: []string{"mise-tasks/x", "svc/t/build"}, + want: []ir.MiseProject{ + {Dir: "", Path: "mise.toml"}, + {Dir: "svc", Path: "svc/mise.toml", Tasks: []ir.MiseTask{{Name: "build", Source: "svc/t/build"}}, UnreadIncludes: []string{"git::x"}}, + }, + }, + { + name: "an include under a file declares nothing, on a checkout as remotely", + files: map[string]string{ + "mise.toml": "[task_config]\nincludes = [\"tasks.toml/x\"]\n", + "tasks.toml": "[lint]\nrun = \"x\"\n", + }, + want: []ir.MiseProject{{Dir: "", Path: "mise.toml"}}, + }, + { + name: "symlinks are followed inside the repository only", + files: map[string]string{ + "mise.toml": "[task_config]\nincludes = [\"mise-tasks\", \"esc/tasks\"]\n", + "scripts/lint": "#!/bin/sh\n", + "scripts/ci/test": "#!/bin/sh\n", + "svc/mise.toml": "[tools]\nnode = \"24\"\n", + }, + executables: []string{"scripts/lint", "scripts/ci/test"}, + outsideFiles: map[string]string{"bin/true": "#!/bin/sh\n", "tasks/secret": "#!/bin/sh\n", "dotmise/tasks/leak": "#!/bin/sh\n"}, + symlinks: map[string]string{ + "mise-tasks/lint": "../scripts/lint", + "mise-tasks/ci": "../scripts/ci", + "mise-tasks/out": "OUTSIDE/bin/true", + "esc": "OUTSIDE", + }, + want: []ir.MiseProject{ + {Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{ + {Name: "ci:test", Source: "mise-tasks/ci/test"}, + {Name: "lint", Source: "mise-tasks/lint"}, + }, + UnreadIncludes: []string{"esc/tasks"}, + }, + {Dir: "svc", Path: "svc/mise.toml", + Tasks: []ir.MiseTask{ + {Name: "ci:test", Source: "mise-tasks/ci/test"}, + {Name: "lint", Source: "mise-tasks/lint"}, + }, + UnreadIncludes: []string{"esc/tasks"}, + }, + }, + }, + { + name: "env configs do not count, and task.disable_paths and task.skip drop tasks", + files: map[string]string{ + "mise.ci.toml": "[tasks.cionly]\nrun = \"x\"\n\n[task_config]\nincludes = [\"ci-tasks\"]\n", + "mise.toml": "[settings]\ntask.disable_paths = [\"mise-tasks/off\"]\ntask.skip = [\"fmt\"]\n\n[tasks]\nfmt = \"x\"\nlint = \"x\"\n", + "mise-tasks/on": "#!/bin/sh\n", + "mise-tasks/off/x": "#!/bin/sh\n", + "ci-tasks/y": "#!/bin/sh\n", + }, + executables: []string{"mise-tasks/on", "mise-tasks/off/x", "ci-tasks/y"}, + want: []ir.MiseProject{{ + Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{ + {Name: "lint", Source: "mise.toml"}, + {Name: "on", Source: "mise-tasks/on"}, + }, + }}, + }, + { + name: "a parent's task.skip and task.disable_paths apply in a subproject, a subproject's do not reach the parent", + files: map[string]string{ + "mise.toml": "[settings]\ntask.disable_paths = [\"mise-tasks/off\"]\ntask.skip = [\"fmt\"]\n\n[tasks]\nfmt = \"x\"\nlint = \"x\"\n", + "mise-tasks/on": "#!/bin/sh\n", + "mise-tasks/off/x": "#!/bin/sh\n", + "svc/mise.toml": "[settings]\ntask.skip = [\"lint\"]\n\n[tasks]\nfmt = \"x\"\ntest = \"x\"\n", + }, + executables: []string{"mise-tasks/on", "mise-tasks/off/x"}, + want: []ir.MiseProject{ + {Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{ + {Name: "lint", Source: "mise.toml"}, + {Name: "on", Source: "mise-tasks/on"}, + }, + }, + {Dir: "svc", Path: "svc/mise.toml", + Tasks: []ir.MiseTask{ + {Name: "on", Source: "mise-tasks/on"}, + {Name: "test", Source: "svc/mise.toml"}, + }, + }, + }, + }, + { + name: "past the file cap, the include counts as unread", + files: map[string]string{ + "mise.toml": "[task_config]\nincludes = [\"many\"]\n", + "many/a": "#!/bin/sh\n", + "many/b": "#!/bin/sh\n", + "many/c": "#!/bin/sh\n", + }, + executables: []string{"many/a", "many/b", "many/c"}, + budget: 2, + want: []ir.MiseProject{{ + Dir: "", Path: "mise.toml", + Tasks: []ir.MiseTask{{Name: "a", Source: "many/a"}, {Name: "b", Source: "many/b"}}, + UnreadIncludes: []string{"many"}, + }}, + }, + { + name: "a TOML task file that does not parse is an unreadable task file", + files: map[string]string{ + "mise.toml": "[tools]\nnode = \"24\"\n", + "mise-tasks/broken.toml": "not = [valid\n", + }, + want: []ir.MiseProject{{Dir: "", Path: "mise.toml"}}, + wantUnreadable: []string{"mise-tasks/broken.toml"}, + }, + { + // mise reads svc/.mise/tasks through the link, so Plumber + // cannot tell what it declares: the run stops. + name: "a .mise directory linked outside the repository stops the run", + files: map[string]string{"svc/mise.toml": "[tools]\nnode = \"24\"\n"}, + outsideFiles: map[string]string{"dotmise/tasks/leak": "#!/bin/sh\n"}, + symlinks: map[string]string{"svc/.mise": "OUTSIDE/dotmise"}, + wantUnreadable: []string{"svc/.mise"}, + }, + { + // The unreadable config is exempt, or it would stop the run. + name: "a project under an unreadable config is left out, a sibling with a longer name is not", + files: map[string]string{ + "svc/mise.toml": "not = [valid\n", + "svc/sub/mise.toml": "[tasks.lint]\nrun = \"x\"\n", + "svc2/mise.toml": "[tasks.lint]\nrun = \"x\"\n", + }, + exemptPaths: [][]string{{"svc/mise.toml"}}, + want: []ir.MiseProject{ + {Dir: "svc2", Path: "svc2/mise.toml", Tasks: []ir.MiseTask{{Name: "lint", Source: "svc2/mise.toml"}}}, + }, + }, + { + name: "a local config names the project only when no shared config does", + files: map[string]string{ + "mise.local.toml": "[tasks.mine]\nrun = \"x\"\n", + "svc/mise.toml": "[tasks.lint]\nrun = \"x\"\n", + }, + want: []ir.MiseProject{ + {Dir: "", Path: "mise.local.toml", Tasks: []ir.MiseTask{{Name: "mine", Source: "mise.local.toml"}}}, + {Dir: "svc", Path: "svc/mise.toml", Tasks: []ir.MiseTask{ + {Name: "lint", Source: "svc/mise.toml"}, + {Name: "mine", Source: "mise.local.toml"}, + }}, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := writeRepo(t, tc.files) + for _, rel := range tc.executables { + if err := os.Chmod(filepath.Join(root, filepath.FromSlash(rel)), 0o755); err != nil { + t.Fatal(err) + } + } + outside := writeRepo(t, tc.outsideFiles) + for rel := range tc.outsideFiles { + if err := os.Chmod(filepath.Join(outside, filepath.FromSlash(rel)), 0o755); err != nil { + t.Fatal(err) + } + } + for rel, target := range tc.symlinks { + if rest, ok := strings.CutPrefix(target, "OUTSIDE"); ok { + target = outside + filepath.FromSlash(rest) + } + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, p); err != nil { + t.Fatal(err) + } + } + if tc.budget > 0 { + saved := maxTaskFiles + maxTaskFiles = tc.budget + t.Cleanup(func() { maxTaskFiles = saved }) + } + got, err := scanBoth(t, root, Options{Tasks: true, Lockfiles: true, ExemptPaths: tc.exemptPaths}, true) + var gotUnreadable []string + if re, ok := errors.AsType[*ReadError](err); ok { + for _, f := range re.Files { + gotUnreadable = append(gotUnreadable, f.Path) + } + } else if err != nil { + t.Fatalf("Scan error = %v, want a *ReadError or nil", err) + } + if !reflect.DeepEqual(gotUnreadable, tc.wantUnreadable) { + t.Errorf("unreadable files = %v, want %v", gotUnreadable, tc.wantUnreadable) + } + if err != nil { + return + } + if !reflect.DeepEqual(got.Projects, tc.want) { + t.Errorf("Projects =\n%#v\nwant\n%#v", got.Projects, tc.want) + } + }) + } +} diff --git a/policies/message_style_test.go b/policies/message_style_test.go index 6bdfd4b4..94df32c5 100644 --- a/policies/message_style_test.go +++ b/policies/message_style_test.go @@ -120,6 +120,28 @@ var gitLabMessageStyleKeys = map[string][]string{ // prose, no technical token to quote. "ISSUE-507": {}, "ISSUE-601": {}, + // mise (10xx): the config or lockfile, the tool and the platform. + "ISSUE-1001": {"file", "lockfile"}, + "ISSUE-1002": {"file"}, + "ISSUE-1003": {"file", "package", "lockfile"}, + "ISSUE-1004": {"file", "package", "platform"}, + "ISSUE-1005": {"file", "package", "platform", "provenance"}, + "ISSUE-1006": {"file", "package", "platform"}, + "ISSUE-1007": {"file", "package", "platform"}, + "ISSUE-1008": {"file"}, + "ISSUE-1009": {"file", "package"}, + // No mise config: a repository-wide singleton. + "ISSUE-1010": {}, + "ISSUE-1011": {"file", "package", "request"}, + "ISSUE-1012": {"file", "package", "request"}, + "ISSUE-1013": {"file", "package"}, + "ISSUE-1014": {"file", "package", "platform", "value"}, + "ISSUE-1015": {"file", "value"}, + "ISSUE-1016": {"file", "package", "option", "value"}, + // Locked without download data: the platform only when there is one. + "ISSUE-1018": {"file", "package"}, + "ISSUE-1019": {"file"}, + "ISSUE-1017": {"file"}, } // dataArrayKinds classifies every string array a GitLab finding publishes. @@ -162,6 +184,9 @@ var dataArrayKinds = map[string]bool{ // deletion, creation). A consumer parses them; the message renders // them as clauses. "ISSUE-510.missingProtections": false, + // The required task entries a mise project misses (names or globs). A + // consumer parses them; the message lists them. + "ISSUE-1017.missing": false, } // messageBranches is the render manifest, and the answer to a defect class diff --git a/policies/mise_lockfile.rego b/policies/mise_lockfile.rego new file mode 100644 index 00000000..b63a5d94 --- /dev/null +++ b/policies/mise_lockfile.rego @@ -0,0 +1,327 @@ +# mise-lockfile — the lockfile check of mise-en-place for +# mise (#254). Every committed mise config that declares tools must have +# its lockfile committed, every tool request must have a matching lock +# entry (its `specifiers` contain the request), and every locked download +# must carry a checksum. A recorded provenance must be of a trusted kind. +# Opt-in: provenance per backend, required platforms, a minimum lockfile +# format. +# +# Fail closed: a request Plumber cannot read statically (a template) or a +# format 0 lockfile (no specifiers) is reported as not locked, never +# passed. A mise file that cannot be read or parsed stops the run before +# the policies, so every file here was read. exemptPackages (tool keys) +# and exemptPaths (repository paths) are the way out for intentional +# cases. +# +# The collector (packagemanager/mise) pairs each config with its lockfile +# and resolves the matching lock entry; the rules only judge. +package mise_lockfile + +import rego.v1 + +_mise := input.config["mise-en-place"].mise + +_check := _mise.lockfile + +# Tool keys exempted from every mise check, globs allowed. +_exempt(name) if { + some pattern in _mise.exemptPackages + glob.match(pattern, null, name) +} + +# Repository paths exempted from every mise check, globs with `/` as the +# separator ("examples/**"). +_path_exempt(p) if { + some pattern in _mise.exemptPaths + glob.match(pattern, ["/"], p) +} + +# The configs under check: those outside exemptPaths. +# A local config (*.local.toml) is personal and never paired with a +# lockfile by this check; the sources and versions checks judge it. +_configs contains cfg if { + some cfg in input.pipeline.mise.configs + not _path_exempt(cfg.path) + not cfg["local"] +} + +# A config whose tools are all exempt asserts nothing to lock. +_declares_tools(cfg) if { + some tool in cfg.tools + not _exempt(tool.name) +} + +# ISSUE-1001: a config declares tools and its lockfile is not committed. +deny contains finding if { + _check + some cfg in _configs + _declares_tools(cfg) + not cfg.lockfileDisabled + not cfg.lockfile.present + not cfg.lockfileUnknown + finding := { + "code": "ISSUE-1001", + "severity": "high", + "message": sprintf("`%s` declares tools but its lockfile `%s` is not committed", [cfg.path, cfg.lockfile.path]), + "file": cfg.path, + "lockfile": cfg.lockfile.path, + } +} + +# ISSUE-1002: the config turns lockfiles off. +deny contains finding if { + _check + some cfg in _configs + cfg.lockfileDisabled + not cfg.lockfileDisabledBy + finding := { + "code": "ISSUE-1002", + "severity": "high", + "message": sprintf("`%s` turns mise lockfiles off with `lockfile = false`", [cfg.path]), + "file": cfg.path, + } +} + +# ISSUE-1002 for a config that inherits `lockfile = false` from a parent +# directory's config. The config that sets it gets the finding above; a +# subproject is only reported itself when that config is under +# exemptPaths, so turning lockfiles off from an exempt path still shows. +deny contains finding if { + _check + some cfg in _configs + cfg.lockfileDisabled + _path_exempt(cfg.lockfileDisabledBy) + finding := { + "code": "ISSUE-1002", + "severity": "high", + "message": sprintf("`%s` inherits `lockfile = false` from `%s`, so mise lockfiles are off", [cfg.path, cfg.lockfileDisabledBy]), + "file": cfg.path, + "setBy": cfg.lockfileDisabledBy, + } +} + +# ISSUE-1003: a tool request has no matching lock entry. Only judged when +# the lockfile exists: a missing lockfile is ISSUE-1001 alone. A config +# whose lockfile is unknown (its root config is unreadable) is not judged. +deny contains finding if { + _check + some cfg in _configs + not cfg.lockfileDisabled + not cfg.lockfileUnknown + cfg.lockfile.present + some tool in cfg.tools + not _exempt(tool.name) + not tool.locked + finding := { + "code": "ISSUE-1003", + "severity": "high", + "message": _not_locked_message(cfg, tool), + "file": cfg.path, + "lockfile": cfg.lockfile.path, + "package": tool.name, + "request": tool.request, + } +} + +_not_locked_message(cfg, tool) := msg if { + tool.unreadable + msg := sprintf("Tool `%s` in `%s` cannot be matched to `%s` because %s", [tool.name, cfg.path, cfg.lockfile.path, tool.unreadable]) +} else := msg if { + cfg.lockfile.version < 1 + msg := sprintf("Tool `%s` in `%s` cannot be matched to `%s`, whose format 0 records no specifiers", [tool.name, cfg.path, cfg.lockfile.path]) +} else := sprintf("Tool `%s` = `%s` in `%s` has no entry in `%s`", [tool.name, tool.request, cfg.path, cfg.lockfile.path]) + +# The configs whose lockfile is judged (ISSUE-1004 to ISSUE-1008): a config that +# turns lockfiles off is ISSUE-1002 alone, and one whose lockfile is +# unknown (its root config is unreadable) is not paired with any. +_locking_configs contains cfg if { + some cfg in _configs + not cfg.lockfileDisabled + not cfg.lockfileUnknown +} + +# The locked platforms of the tools a config declares and does not exempt. +_locked_platforms contains [cfg, tool, platform] if { + some cfg in _locking_configs + some tool in cfg.tools + not _exempt(tool.name) + some platform in tool.locked.platforms +} + +# ISSUE-1004: a locked download has no checksum. +deny contains finding if { + _check.requireChecksums + some [cfg, tool, platform] in _locked_platforms + platform.url + not platform.checksum + finding := { + "code": "ISSUE-1004", + "severity": "high", + "message": sprintf("`%s` locks `%s` %s for `%s` without a checksum", [cfg.lockfile.path, tool.name, tool.locked.version, platform.platform]), + "file": cfg.lockfile.path, + "package": tool.name, + "platform": platform.platform, + } +} + +# ISSUE-1005: a locked download records a provenance of a kind outside +# trustedProvenance. A platform that records several kinds (a table keyed +# by kind) is read as "kind1,kind2"; each untrusted kind is reported. +deny contains finding if { + _check + some [cfg, tool, platform] in _locked_platforms + platform.provenance + some kind in split(platform.provenance, ",") + not kind in _check.trustedProvenance + finding := { + "code": "ISSUE-1005", + "severity": "medium", + "message": sprintf("`%s` locks `%s` %s for `%s` with provenance `%s`, which is not trusted", [cfg.lockfile.path, tool.name, tool.locked.version, platform.platform, kind]), + "file": cfg.lockfile.path, + "package": tool.name, + "platform": platform.platform, + "provenance": kind, + } +} + +# ISSUE-1006: a locked download of a backend listed in requireProvenance +# has no provenance. +deny contains finding if { + some [cfg, tool, platform] in _locked_platforms + some pattern in _check.requireProvenance + glob.match(pattern, null, tool.locked.backend) + platform.url + not platform.provenance + finding := { + "code": "ISSUE-1006", + "severity": "medium", + "message": sprintf("`%s` locks `%s` %s from `%s` for `%s` without provenance", [cfg.lockfile.path, tool.name, tool.locked.version, tool.locked.backend, platform.platform]), + "file": cfg.lockfile.path, + "package": tool.name, + "platform": platform.platform, + } +} + +# ISSUE-1007: a tool that locks per-platform downloads misses a platform +# listed in requiredPlatforms. Tools that lock no platform (npm, cargo, +# go, ...) record a version only and are not judged. +deny contains finding if { + some cfg in _locking_configs + some tool in cfg.tools + not _exempt(tool.name) + count(tool.locked.platforms) > 0 + some required in _check.requiredPlatforms + not _has_platform(tool.locked, required) + finding := { + "code": "ISSUE-1007", + "severity": "low", + "message": sprintf("`%s` does not lock `%s` %s for `%s`", [cfg.lockfile.path, tool.name, tool.locked.version, required]), + "file": cfg.lockfile.path, + "package": tool.name, + "platform": required, + } +} + +_has_platform(locked, name) if { + some p in locked.platforms + p.platform == name +} + +# ISSUE-1008: the lockfile format is older than minimumLockfileVersion. +# One finding per lockfile, however many configs share it. +deny contains finding if { + minimum := _check.minimumLockfileVersion + some path, version in _present_lockfiles + version < minimum + finding := { + "code": "ISSUE-1008", + "severity": "low", + "message": sprintf("`%s` uses lockfile format %d, older than the required format %d", [path, version, minimum]), + "file": path, + } +} + +_present_lockfiles[cfg.lockfile.path] := cfg.lockfile.version if { + some cfg in _locking_configs + cfg.lockfile.present +} + +# ISSUE-1009: a tool declared in asdf's .tool-versions and in no mise +# config of the same directory. mise reads the file but never locks it; +# declaring the tool in mise only fixes that. .tool-versions is read for +# this rule only. Idiomatic version files (.nvmrc, .node-version, +# .python-version, ...), which mise reads only for the tools listed in +# `idiomatic_version_file_enable_tools`, are not read. +deny contains finding if { + _check + some entry in input.pipeline.mise.toolVersions + not _exempt(entry.name) + not _path_exempt(entry.path) + finding := { + "code": "ISSUE-1009", + "severity": "medium", + "message": sprintf("`%s` declares `%s`, which mise reads but never locks", [entry.path, entry.name]), + "file": entry.path, + "package": entry.name, + } +} + +# ISSUE-1019: a mise local config is committed. mise loads it on every +# clone, CI included, but a local config is personal and not meant to be +# committed (https://mise.jdx.dev/glossary.html#mise-local-toml), and +# this check judges committed configs only through their lockfile. +deny contains finding if { + _check + some p in input.pipeline.mise.localConfigs + not _path_exempt(p) + finding := { + "code": "ISSUE-1019", + "severity": "high", + "message": sprintf("`%s` is a mise local config committed to the repository, so every clone and CI run loads it", [p]), + "file": p, + } +} + +# Backends that download a per-platform binary. Their lock entries record +# one platform table per platform, with the URL and checksum mise verifies. +_binary_backends := {"aqua", "github", "gitlab", "ubi", "http"} + +_binary_backend(backend) if { + prefix := split(backend, ":")[0] + prefix in _binary_backends +} + +# ISSUE-1018: a tool is locked without the download data mise verifies. +# ISSUE-1004 judges a platform that records a URL. A lock entry of a +# binary backend with no platform table at all, or a platform table with +# neither url nor checksum, records nothing to verify a download against. +deny contains finding if { + _check.requireChecksums + some cfg in _locking_configs + some tool in cfg.tools + not _exempt(tool.name) + _binary_backend(tool.locked.backend) + count(object.get(tool.locked, "platforms", [])) == 0 + finding := { + "code": "ISSUE-1018", + "severity": "high", + "message": sprintf("`%s` locks `%s` %s from `%s` with no platform, so no download URL or checksum", [cfg.lockfile.path, tool.name, tool.locked.version, tool.locked.backend]), + "file": cfg.lockfile.path, + "package": tool.name, + } +} + +deny contains finding if { + _check.requireChecksums + some [cfg, tool, platform] in _locked_platforms + not platform.url + not platform.checksum + finding := { + "code": "ISSUE-1018", + "severity": "high", + "message": sprintf("`%s` locks `%s` %s for `%s` with no download URL or checksum", [cfg.lockfile.path, tool.name, tool.locked.version, platform.platform]), + "file": cfg.lockfile.path, + "package": tool.name, + "platform": platform.platform, + } +} diff --git a/policies/mise_lockfile_test.go b/policies/mise_lockfile_test.go new file mode 100644 index 00000000..fc4a5a08 --- /dev/null +++ b/policies/mise_lockfile_test.go @@ -0,0 +1,457 @@ +package policies_test + +import ( + "context" + "reflect" + "sort" + "testing" + + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/policies" + + opaengine "github.com/getplumber/plumber/internal/engine/opa" +) + +// miseLockCfg is the Rego config of mise-en-place with the +// mise lockfile check on, extended by extra. +func miseLockCfg(extra map[string]any, exempt ...string) map[string]any { + lockfile := map[string]any{ + "requireChecksums": true, + "requireProvenance": []string{}, + "trustedProvenance": []string{"slsa", "github-attestations", "cosign", "minisign"}, + "requiredPlatforms": []string{}, + } + for k, v := range extra { + lockfile[k] = v + } + if exempt == nil { + exempt = []string{} + } + return map[string]any{ + "mise-en-place": map[string]any{ + "mise": map[string]any{"lockfile": lockfile, "exemptPackages": exempt}, + }, + } +} + +// withExemptPaths sets mise.exemptPaths on a config built by miseLockCfg. +func withExemptPaths(cfg map[string]any, paths ...string) map[string]any { + cfg["mise-en-place"].(map[string]any)["mise"].(map[string]any)["exemptPaths"] = paths + return cfg +} + +// locked builds a lock entry with one platform per (platform, checksum) +// pair; an empty checksum leaves it out. +func locked(version, backend string, platforms ...[2]string) *ir.MiseLockEntry { + e := &ir.MiseLockEntry{Version: version, Backend: backend} + for _, p := range platforms { + e.Platforms = append(e.Platforms, ir.MiseLockPlatform{ + Platform: p[0], URL: "https://example.com/" + p[0], Checksum: p[1], + }) + } + return e +} + +// miseConfig is mise.toml paired with a present mise.lock in format 5. +func miseConfig(tools ...ir.MiseTool) ir.MiseConfig { + return ir.MiseConfig{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, + Tools: tools, + } +} + +// miseFindingKeys renders each 10xx finding as "code file package platform". +func miseFindingKeys(findings []opaengine.Finding) []string { + out := []string{} + for _, f := range findings { + if len(f.Code) != len("ISSUE-1001") || f.Code[:7] != "ISSUE-1" { + continue + } + key := f.Code + " " + f.File + if pkg, ok := f.Data["package"].(string); ok { + key += " " + pkg + } + if p, ok := f.Data["platform"].(string); ok { + key += " " + p + } + out = append(out, key) + } + sort.Strings(out) + return out +} + +func TestIssue1001_MiseLockfile(t *testing.T) { + engine := opaengine.New() + if err := engine.LoadFromFSFiltered(policies.FS, nil); err != nil { + t.Fatalf("load embedded policies: %v", err) + } + node := ir.MiseTool{Name: "node", Request: "24", Locked: locked("24.21.0", "core:node", [2]string{"linux-x64", "sha256:aa"})} + cases := []struct { + name string + mise *ir.MiseScan + cfg map[string]any + want []string + }{ + { + name: "a locked tool with checksums passes", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(node)}}, + cfg: miseLockCfg(nil), + want: []string{}, + }, + { + name: "a config with tools and no lockfile is ISSUE-1001 only", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1001 mise.toml"}, + }, + { + name: "a config without tools needs no lockfile", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock"}}}}, + cfg: miseLockCfg(nil), + want: []string{}, + }, + { + name: "lockfile = false is ISSUE-1002 only", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + LockfileDisabled: true, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1002 mise.toml"}, + }, + { + name: "a request with no matching entry is ISSUE-1003", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(node, ir.MiseTool{Name: "terraform", Request: "1.9.8"})}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1003 mise.toml terraform"}, + }, + { + name: "a template request fails closed with ISSUE-1003", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "go", Request: "{{ env.GO_VERSION }}", Unreadable: "the version is a template", + })}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1003 mise.toml go"}, + }, + { + name: "a format 0 lockfile fails closed with ISSUE-1003", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 0}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1003 mise.toml node"}, + }, + { + name: "a download without checksum is ISSUE-1004", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "jq", Request: "1.7.1", + Locked: locked("1.7.1", "aqua:jqlang/jq", [2]string{"linux-x64", ""}, [2]string{"macos-arm64", "sha256:bb"}), + })}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1004 mise.lock jq linux-x64"}, + }, + { + name: "a binary-backend tool locked with no platform is ISSUE-1018", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "jq", Request: "1.7.1", Locked: &ir.MiseLockEntry{Version: "1.7.1", Backend: "aqua:jqlang/jq"}, + })}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1018 mise.lock jq"}, + }, + { + name: "a platform with neither url nor checksum is ISSUE-1018", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "jq", Request: "1.7.1", Locked: &ir.MiseLockEntry{ + Version: "1.7.1", Backend: "aqua:jqlang/jq", + Platforms: []ir.MiseLockPlatform{{Platform: "linux-x64"}}, + }, + })}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1018 mise.lock jq linux-x64"}, + }, + { + name: "a backend that records no platform (npm, cargo, go) passes with none", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "npm:prettier", Request: "3", Locked: &ir.MiseLockEntry{Version: "3.4.2", Backend: "npm:prettier"}, + })}}, + cfg: miseLockCfg(nil), + want: []string{}, + }, + { + name: "missing download data passes when requireChecksums is off", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "jq", Request: "1.7.1", Locked: &ir.MiseLockEntry{Version: "1.7.1", Backend: "aqua:jqlang/jq"}, + })}}, + cfg: miseLockCfg(map[string]any{"requireChecksums": false}), + want: []string{}, + }, + { + name: "a committed mise local config is ISSUE-1019", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{miseConfig(node)}, + LocalConfigs: []string{"mise.local.toml", "examples/mise.local.toml"}, + }, + cfg: withExemptPaths(miseLockCfg(nil), "examples/**"), + want: []string{"ISSUE-1019 mise.local.toml"}, + }, + { + name: "a missing checksum passes when requireChecksums is off", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "jq", Request: "1.7.1", Locked: locked("1.7.1", "aqua:jqlang/jq", [2]string{"linux-x64", ""}), + })}}, + cfg: miseLockCfg(map[string]any{"requireChecksums": false}), + want: []string{}, + }, + { + name: "a backend listed in requireProvenance without provenance is ISSUE-1006", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(node, ir.MiseTool{ + Name: "jq", Request: "1.7.1", Locked: locked("1.7.1", "aqua:jqlang/jq", [2]string{"linux-x64", "sha256:bb"}), + })}}, + cfg: miseLockCfg(map[string]any{"requireProvenance": []string{"aqua:*"}}), + want: []string{"ISSUE-1006 mise.lock jq linux-x64"}, + }, + { + name: "a backend listed in requireProvenance with provenance passes", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{{ + Platform: "linux-x64", URL: "https://example.com/linux-x64", Checksum: "sha256:aa", Provenance: "github-attestations", + }}, + }, + })}}, + cfg: miseLockCfg(map[string]any{"requireProvenance": []string{"aqua:*"}}), + want: []string{}, + }, + { + name: "a provenance kind outside trustedProvenance is ISSUE-1005", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://example.com/linux-x64", Checksum: "sha256:aa", Provenance: "minisign"}, + {Platform: "macos-arm64", URL: "https://example.com/macos-arm64", Checksum: "sha256:bb", Provenance: "slsa"}, + }, + }, + })}}, + cfg: miseLockCfg(map[string]any{"trustedProvenance": []string{"slsa", "github-attestations"}}), + want: []string{"ISSUE-1005 mise.lock age linux-x64"}, + }, + { + name: "each untrusted kind of a platform that records several is ISSUE-1005", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://example.com/linux-x64", Checksum: "sha256:aa", Provenance: "cosign,minisign,slsa"}, + }, + }, + })}}, + cfg: miseLockCfg(map[string]any{"trustedProvenance": []string{"slsa"}}), + want: []string{"ISSUE-1005 mise.lock age linux-x64", "ISSUE-1005 mise.lock age linux-x64"}, + }, + { + name: "an empty trustedProvenance trusts no kind", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "age", Request: "1.3.2", Locked: &ir.MiseLockEntry{ + Version: "1.3.2", Backend: "aqua:FiloSottile/age", + Platforms: []ir.MiseLockPlatform{ + {Platform: "linux-x64", URL: "https://example.com/linux-x64", Checksum: "sha256:aa", Provenance: "slsa"}, + }, + }, + })}}, + cfg: miseLockCfg(map[string]any{"trustedProvenance": []string{}}), + want: []string{"ISSUE-1005 mise.lock age linux-x64"}, + }, + { + name: "an unquoted numeric version fails closed with ISSUE-1003", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "node", Request: "24", Unreadable: "the version is not a quoted string, which mise rejects", + })}}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1003 mise.toml node"}, + }, + { + name: "a required platform that is not locked is ISSUE-1007", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(node, ir.MiseTool{ + Name: "npm:prettier", Request: "3", Locked: &ir.MiseLockEntry{Version: "3.3.3", Backend: "npm:prettier"}, + })}}, + cfg: miseLockCfg(map[string]any{"requiredPlatforms": []string{"linux-x64", "linux-arm64"}}), + want: []string{"ISSUE-1007 mise.lock node linux-arm64"}, + }, + { + name: "a lockfile older than minimumLockfileVersion is ISSUE-1008", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 1}, + Tools: []ir.MiseTool{node}, + }}}, + cfg: miseLockCfg(map[string]any{"minimumLockfileVersion": 4}), + want: []string{"ISSUE-1008 mise.lock"}, + }, + { + name: "a tool only in .tool-versions is ISSUE-1009", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{miseConfig(node)}, + ToolVersions: []ir.MiseToolVersionsEntry{{Path: ".tool-versions", Name: "python"}}, + }, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1009 .tool-versions python"}, + }, + { + name: "exempted tools are not judged by any check", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{Name: "aqua:my-org/tool", Request: "1"})}, + ToolVersions: []ir.MiseToolVersionsEntry{{Path: ".tool-versions", Name: "python"}}, + }, + cfg: miseLockCfg(nil, "aqua:my-org/*", "python"), + want: []string{}, + }, + { + name: "the lockfile check abstains when its block is absent", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + cfg: map[string]any{"mise-en-place": map[string]any{ + "mise": map[string]any{"exemptPackages": []string{}}, + }}, + want: []string{}, + }, + { + name: "a subproject whose lockfile is unknown is not judged for ISSUE-1001 or ISSUE-1003", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{ + { + Path: "svc/mise.toml", + Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, + LockfileUnknown: true, + Tools: []ir.MiseTool{{Name: "go", Request: "1.25"}}, + }, + { + Path: "api/mise.toml", + Lockfile: ir.MiseLockfile{Path: "api/mise.lock", Present: true, Version: 5}, + LockfileUnknown: true, + Tools: []ir.MiseTool{{Name: "go", Request: "1.25"}}, + }, + }, + }, + cfg: miseLockCfg(nil), + want: []string{}, + }, + { + name: "a subproject that inherits lockfile = false is covered by the parent's ISSUE-1002", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock"}, LockfileDisabled: true}, + { + Path: "svc/mise.toml", Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, + LockfileDisabled: true, LockfileDisabledBy: "mise.toml", + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + }}, + cfg: miseLockCfg(nil), + want: []string{"ISSUE-1002 mise.toml"}, + }, + { + name: "a subproject that inherits lockfile = false from an exempt config is ISSUE-1002 itself", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{ + {Path: "tools/mise.toml", Lockfile: ir.MiseLockfile{Path: "tools/mise.lock"}, LockfileDisabled: true}, + { + Path: "tools/svc/mise.toml", Lockfile: ir.MiseLockfile{Path: "tools/svc/mise.lock"}, + LockfileDisabled: true, LockfileDisabledBy: "tools/mise.toml", + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + }}, + cfg: withExemptPaths(miseLockCfg(nil), "tools/mise.toml"), + want: []string{"ISSUE-1002 tools/svc/mise.toml"}, + }, + { + name: "a config with lockfiles off is ISSUE-1002 alone, its committed lockfile is not judged", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 3}, + LockfileDisabled: true, + Tools: []ir.MiseTool{{ + Name: "jq", Request: "1.7.1", Locked: locked("1.7.1", "aqua:jqlang/jq", [2]string{"linux-x64", ""}), + }}, + }}}, + cfg: miseLockCfg(map[string]any{ + "requireProvenance": []string{"aqua:*"}, + "requiredPlatforms": []string{"linux-x64", "macos-arm64"}, + "minimumLockfileVersion": 5, + }), + want: []string{"ISSUE-1002 mise.toml"}, + }, + { + name: "a config whose lockfile is unknown is not judged for ISSUE-1004 to ISSUE-1008", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{{ + Path: "svc/mise.toml", + Lockfile: ir.MiseLockfile{Path: "svc/mise.lock", Present: true, Version: 3}, + LockfileUnknown: true, + Tools: []ir.MiseTool{{ + Name: "jq", Request: "1.7.1", Locked: locked("1.7.1", "aqua:jqlang/jq", [2]string{"linux-x64", ""}), + }}, + }}, + }, + cfg: miseLockCfg(map[string]any{ + "requireProvenance": []string{"aqua:*"}, + "requiredPlatforms": []string{"linux-x64", "macos-arm64"}, + "minimumLockfileVersion": 5, + }), + want: []string{}, + }, + { + name: "exemptPaths skips configs and .tool-versions under the path", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{ + { + Path: "examples/basic/mise.toml", + Lockfile: ir.MiseLockfile{Path: "examples/basic/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + { + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }, + }, + ToolVersions: []ir.MiseToolVersionsEntry{{Path: "examples/basic/.tool-versions", Name: "python"}}, + }, + cfg: withExemptPaths(miseLockCfg(nil), "examples/**"), + want: []string{"ISSUE-1001 mise.toml"}, + }, + { + name: "an exemptPaths glob does not cross directories with a single star", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "examples/basic/mise.toml", + Lockfile: ir.MiseLockfile{Path: "examples/basic/mise.lock"}, + Tools: []ir.MiseTool{{Name: "node", Request: "24"}}, + }}}, + cfg: withExemptPaths(miseLockCfg(nil), "examples/*"), + want: []string{"ISSUE-1001 examples/basic/mise.toml"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, ProjectPath: "g/p", Mise: tc.mise} + findings, err := evaluateStrict(engine, context.Background(), p, tc.cfg) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + if got := miseFindingKeys(findings); !reflect.DeepEqual(got, tc.want) { + t.Errorf("findings = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/policies/mise_presence.rego b/policies/mise_presence.rego new file mode 100644 index 00000000..2d4a13f3 --- /dev/null +++ b/policies/mise_presence.rego @@ -0,0 +1,36 @@ +# mise-presence — the presence check of mise-en-place (#678). With +# `mise.required: true`, a repository must commit at least one mise config +# outside exemptPaths. A .tool-versions file alone does not count: it is +# asdf's file, and mise never locks it. +package mise_presence + +import rego.v1 + +_mise := input.config["mise-en-place"].mise + +# Repository paths exempted from every mise check, globs with `/` as the +# separator ("examples/**"). +_path_exempt(p) if { + some pattern in _mise.exemptPaths + glob.match(pattern, ["/"], p) +} + +_configs contains cfg.path if { + some cfg in input.pipeline.mise.configs + not _path_exempt(cfg.path) +} + +# ISSUE-1010: mise is required and the repository has no mise config. +# input.pipeline.mise is only set when the files were read: a run without +# a checkout reports the control not evaluated instead. +deny contains finding if { + _mise.required + input.pipeline.mise + count(_configs) == 0 + finding := { + "code": "ISSUE-1010", + "severity": "medium", + "message": "The repository has no mise config (`mise.toml`), so the tools CI uses are not declared or locked with mise", + "file": "mise.toml", + } +} diff --git a/policies/mise_presence_test.go b/policies/mise_presence_test.go new file mode 100644 index 00000000..9cd97b87 --- /dev/null +++ b/policies/mise_presence_test.go @@ -0,0 +1,92 @@ +package policies_test + +import ( + "context" + "reflect" + "testing" + + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/policies" + + opaengine "github.com/getplumber/plumber/internal/engine/opa" +) + +// misePresenceCfg is the Rego config of mise-en-place with only +// `required` set, plus exemptPaths. +func misePresenceCfg(required bool, exemptPaths ...string) map[string]any { + if exemptPaths == nil { + exemptPaths = []string{} + } + return map[string]any{ + "mise-en-place": map[string]any{ + "mise": map[string]any{ + "required": required, + "exemptPackages": []string{}, + "exemptPaths": exemptPaths, + }, + }, + } +} + +func TestIssue1010_MisePresence(t *testing.T) { + engine := opaengine.New() + if err := engine.LoadFromFSFiltered(policies.FS, nil); err != nil { + t.Fatalf("load embedded policies: %v", err) + } + cfg := ir.MiseConfig{Path: "mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock"}} + cases := []struct { + name string + mise *ir.MiseScan + cfg map[string]any + want []string + }{ + { + name: "a repository with no mise config is ISSUE-1010 when mise is required", + mise: &ir.MiseScan{}, + cfg: misePresenceCfg(true), + want: []string{"ISSUE-1010 mise.toml"}, + }, + { + name: "a .tool-versions file alone does not count as mise", + mise: &ir.MiseScan{ToolVersions: []ir.MiseToolVersionsEntry{{Path: ".tool-versions", Name: "node"}}}, + cfg: misePresenceCfg(true), + want: []string{"ISSUE-1010 mise.toml"}, + }, + { + name: "a config under exemptPaths does not count as mise", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{Path: "examples/mise.toml"}}}, + cfg: misePresenceCfg(true, "examples/**"), + want: []string{"ISSUE-1010 mise.toml"}, + }, + { + name: "a committed mise config passes", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{cfg}}, + cfg: misePresenceCfg(true), + want: []string{}, + }, + { + name: "no mise config passes when mise is not required", + mise: &ir.MiseScan{}, + cfg: misePresenceCfg(false), + want: []string{}, + }, + { + name: "a run whose mise files were not read is not judged", + mise: nil, + cfg: misePresenceCfg(true), + want: []string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, ProjectPath: "o/r", Mise: tc.mise} + findings, err := evaluateStrict(engine, context.Background(), p, tc.cfg) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + if got := miseFindingKeys(findings); !reflect.DeepEqual(got, tc.want) { + t.Errorf("findings = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/policies/mise_sources.rego b/policies/mise_sources.rego new file mode 100644 index 00000000..5d384083 --- /dev/null +++ b/policies/mise_sources.rego @@ -0,0 +1,186 @@ +# mise-sources — the sources check of mise-en-place (#254, #678). A tool +# must be trusted (ISSUE-1013), its locked download URL must be a trusted +# registry (ISSUE-1014), a url_replacements entry must send downloads to +# a trusted URL (ISSUE-1015), and a tool option that sets a download URL +# must set a trusted one (ISSUE-1016). +# +# A tool's name is its key when the key names a backend +# ("aqua:jqlang/jq", "github:org/repo"). A shorthand ("terraform") is +# resolved by mise's registry, so its name is the `backend` of its lock +# entry, which mise keeps even when the registry later moves the tool. +# +# Fail closed: a shorthand with no matching lock entry cannot be traced to +# a backend, so it is reported, never passed. exemptPackages (tool keys) +# and exemptPaths (repository paths) are the way out for intentional +# cases. A config or lockfile that cannot be parsed stops the run before +# the policies. .tool-versions is not judged here: it is read by the +# lockfile check only (ISSUE-1009), so with that check off it is not read +# at all. +package mise_sources + +import rego.v1 + +_mise := input.config["mise-en-place"].mise + +_check := _mise.sources + +# Tool keys exempted from every mise check, globs allowed. +_exempt(name) if { + some pattern in _mise.exemptPackages + glob.match(pattern, null, name) +} + +# Repository paths exempted from every mise check, globs with `/` as the +# separator ("examples/**"). +_path_exempt(p) if { + some pattern in _mise.exemptPaths + glob.match(pattern, ["/"], p) +} + +_configs contains cfg if { + some cfg in input.pipeline.mise.configs + not _path_exempt(cfg.path) +} + +# The tools under check: those of configs outside exemptPaths, for tools +# not in exemptPackages. +_tools contains [cfg, tool] if { + some cfg in _configs + some tool in cfg.tools + not _exempt(tool.name) +} + +# The full mise name of a tool. A key with a backend prefix is its own +# name; a shorthand takes the backend of its lock entry, without any +# bracketed options. +_source(tool) := regex.replace(tool.name, `\[[^\]]*\]$`, "") if contains(tool.name, ":") + +_source(tool) := regex.replace(tool.locked.backend, `\[[^\]]*\]$`, "") if { + not contains(tool.name, ":") + tool.locked.backend != "" +} + +_matches(patterns, value) if { + some pattern in patterns + glob.match(lower(pattern), null, lower(value)) +} + +_trusted_tool(name) if _matches(_check.trustedTools, name) + +# ISSUE-1013: a tool is not trusted. +deny contains finding if { + _check + some [cfg, tool] in _tools + src := _source(tool) + not _trusted_tool(src) + finding := { + "code": "ISSUE-1013", + "severity": "high", + "message": sprintf("Tool `%s` in `%s` is `%s`, which is not a trusted tool", [tool.name, cfg.path, src]), + "file": cfg.path, + "package": tool.name, + "source": src, + } +} + +# ISSUE-1013, fail closed: a shorthand whose backend no lock entry records +# cannot be traced to a tool name. When the entry itself is missing and +# the lockfile check judges the config, that check already reports it +# (ISSUE-1001 or ISSUE-1003), so this rule stays quiet and the gap is +# reported once. A config whose lockfile is unknown (its root config is +# exempt and unreadable) is not judged by the lockfile check, so it is +# reported here. An entry that exists but records no backend is always +# reported here: no other rule sees it. +deny contains finding if { + _check + some [cfg, tool] in _tools + not _source(tool) + not _missing_entry_reported(cfg, tool) + finding := { + "code": "ISSUE-1013", + "severity": "high", + "message": _untraced_message(cfg, tool), + "file": cfg.path, + "package": tool.name, + "lockfile": cfg.lockfile.path, + } +} + +_untraced_message(cfg, tool) := msg if { + tool.locked + msg := sprintf("Tool `%s` in `%s` cannot be traced to a backend: its entry in `%s` records none", [tool.name, cfg.path, cfg.lockfile.path]) +} else := sprintf("Tool `%s` in `%s` cannot be traced to a backend: no entry in `%s` records it", [tool.name, cfg.path, cfg.lockfile.path]) + +# The lockfile check reports this tool's missing lock entry: the check is +# on, it judges the config (not a local file, lockfiles not turned off, +# lockfile known), and the tool has no entry. +_missing_entry_reported(cfg, tool) if { + _mise.lockfile + not cfg.lockfileDisabled + not cfg.lockfileUnknown + not cfg["local"] + not tool.locked +} + +# ISSUE-1014: a trusted tool's lock entry records a download URL outside +# trustedRegistries: the URL `mise install --locked` downloads. Only +# checked when trustedRegistries is set. A tool that is not trusted is +# ISSUE-1013 alone. Configs that share a lockfile give one finding per +# lock entry and platform. +deny contains finding if { + registries := _check.trustedRegistries + some [cfg, tool] in _tools + _trusted_tool(_source(tool)) + some platform in tool.locked.platforms + platform.url + not _matches(registries, platform.url) + finding := { + "code": "ISSUE-1014", + "severity": "high", + "message": sprintf("`%s` locks `%s` for `%s` from `%s`, which is not a trusted registry", [cfg.lockfile.path, tool.name, platform.platform, platform.url]), + "file": cfg.lockfile.path, + "package": tool.name, + "platform": platform.platform, + "value": platform.url, + } +} + +# ISSUE-1015: a url_replacements entry sends downloads to a URL outside +# trustedReplacement. mise requests the replacement first, while the +# lockfile keeps the original URL, so ISSUE-1014 cannot see it. +deny contains finding if { + _check + some cfg in _configs + some setting in cfg.sourceSettings + setting.name == "url_replacements" + not _matches(_check.trustedReplacement, setting.value) + finding := { + "code": "ISSUE-1015", + "severity": "high", + "message": sprintf("`%s` replaces download URLs with `%s`, which is not a trusted replacement", [cfg.path, setting.value]), + "file": cfg.path, + "setting": setting.name, + "value": setting.value, + } +} + +# ISSUE-1016: a trusted tool sets an option that points its download at a +# URL outside trustedOptions (a GitHub Enterprise api_url or an internal +# mirror listed there passes). A tool that is not trusted is ISSUE-1013 +# alone. +deny contains finding if { + _check + some [cfg, tool] in _tools + _trusted_tool(_source(tool)) + some opt in tool.sourceOptions + not _matches(_check.trustedOptions, opt.value) + finding := { + "code": "ISSUE-1016", + "severity": "medium", + "message": sprintf("Tool `%s` in `%s` sets `%s` to `%s`, which is not a trusted option", [tool.name, cfg.path, opt.name, opt.value]), + "file": cfg.path, + "package": tool.name, + "option": opt.name, + "value": opt.value, + } +} diff --git a/policies/mise_sources_test.go b/policies/mise_sources_test.go new file mode 100644 index 00000000..006c0f83 --- /dev/null +++ b/policies/mise_sources_test.go @@ -0,0 +1,340 @@ +package policies_test + +import ( + "context" + "reflect" + "sort" + "testing" + + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/policies" + + opaengine "github.com/getplumber/plumber/internal/engine/opa" +) + +// miseSourcesCfg is the Rego config of mise-en-place with only the mise +// sources check on: trustedTools, no trusted replacement or option, and +// trustedRegistries absent (not checked). +func miseSourcesCfg(trustedTools []string, exempt ...string) map[string]any { + if exempt == nil { + exempt = []string{} + } + return map[string]any{ + "mise-en-place": map[string]any{ + "mise": map[string]any{ + "sources": map[string]any{ + "trustedTools": trustedTools, + "trustedReplacement": []string{}, + "trustedOptions": []string{}, + }, + "exemptPackages": exempt, + "exemptPaths": []string{}, + }, + }, + } +} + +// withSources sets one key of the sources block of a config built by +// miseSourcesCfg. +func withSources(cfg map[string]any, key string, value []string) map[string]any { + cfg["mise-en-place"].(map[string]any)["mise"].(map[string]any)["sources"].(map[string]any)[key] = value + return cfg +} + +// withLockfileCheck turns the mise lockfile check on in a config built by +// miseSourcesCfg. +func withLockfileCheck(cfg map[string]any) map[string]any { + cfg["mise-en-place"].(map[string]any)["mise"].(map[string]any)["lockfile"] = map[string]any{ + "requireChecksums": true, "requireProvenance": []string{}, "requiredPlatforms": []string{}, + "trustedProvenance": []string{"slsa", "github-attestations", "cosign", "minisign"}, + } + return cfg +} + +// miseSourceKeys renders each finding as "code file" followed by the +// fields that name what it is about. +func miseSourceKeys(findings []opaengine.Finding) []string { + out := []string{} + for _, f := range findings { + switch f.Code { + case "ISSUE-1001", "ISSUE-1002", "ISSUE-1003", "ISSUE-1009", "ISSUE-1013", "ISSUE-1014", "ISSUE-1015", "ISSUE-1016": + default: + continue + } + key := f.Code + " " + f.File + for _, field := range []string{"package", "source", "platform", "setting", "option", "value"} { + if v, ok := f.Data[field].(string); ok { + key += " " + v + } + } + out = append(out, key) + } + sort.Strings(out) + return out +} + +func TestIssue1013_MiseSources(t *testing.T) { + engine := opaengine.New() + if err := engine.LoadFromFSFiltered(policies.FS, nil); err != nil { + t.Fatalf("load embedded policies: %v", err) + } + trusted := []string{"core:*", "aqua:*", "github:my-org/*"} + tool := func(name string) ir.MiseTool { return ir.MiseTool{Name: name, Request: "1"} } + lockedTo := func(name, backend string) ir.MiseTool { + return ir.MiseTool{Name: name, Request: "1", Locked: &ir.MiseLockEntry{Version: "1.0.0", Backend: backend}} + } + lockedFrom := func(name, backend string, urls ...[2]string) ir.MiseTool { + t := lockedTo(name, backend) + for _, u := range urls { + t.Locked.Platforms = append(t.Locked.Platforms, ir.MiseLockPlatform{Platform: u[0], URL: u[1], Checksum: "sha256:aa"}) + } + return t + } + withOpts := func(t ir.MiseTool, opts ...ir.MiseToolOption) ir.MiseTool { + t.SourceOptions = opts + return t + } + apiURL := ir.MiseToolOption{Name: "api_url", Value: "https://ghe.example.com/api/v3"} + cases := []struct { + name string + mise *ir.MiseScan + cfg map[string]any + want []string + }{ + { + name: "trusted tools pass, named by the key or by the lock entry", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + tool("aqua:jqlang/jq"), tool("github:my-org/cli"), lockedTo("node", "core:node"), lockedTo("terraform", "aqua:hashicorp/terraform"), + )}}, + cfg: miseSourcesCfg(trusted), + want: []string{}, + }, + { + name: "a tool outside trustedTools is ISSUE-1013", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("github:someone/tool"), tool("ubi:someone/other"))}}, + cfg: miseSourcesCfg(trusted), + want: []string{ + "ISSUE-1013 mise.toml github:someone/tool github:someone/tool", + "ISSUE-1013 mise.toml ubi:someone/other ubi:someone/other", + }, + }, + { + name: "a shorthand takes its lock entry's backend, options stripped", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(lockedTo("tool", "ubi:someone/tool[exe=tool]"))}}, + cfg: miseSourcesCfg(trusted), + want: []string{"ISSUE-1013 mise.toml tool ubi:someone/tool"}, + }, + { + name: "a shorthand with no lock entry fails closed", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("terraform"))}}, + cfg: miseSourcesCfg(trusted), + want: []string{"ISSUE-1013 mise.toml terraform"}, + }, + { + name: "with the lockfile check on, a shorthand with no lock entry is ISSUE-1003 alone", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("terraform"))}}, + cfg: withLockfileCheck(miseSourcesCfg(trusted)), + want: []string{"ISSUE-1003 mise.toml terraform"}, + }, + { + name: "with lockfiles turned off in the config, the shorthand fails closed again", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + LockfileDisabled: true, + Tools: []ir.MiseTool{tool("terraform")}, + }}}, + cfg: withLockfileCheck(miseSourcesCfg(trusted)), + want: []string{"ISSUE-1002 mise.toml", "ISSUE-1013 mise.toml terraform"}, + }, + { + name: "tools match case-insensitively", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("github:My-Org/CLI"))}}, + cfg: miseSourcesCfg(trusted), + want: []string{}, + }, + { + name: "exemptPackages skips a tool", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("github:someone/tool"), tool("terraform"))}}, + cfg: miseSourcesCfg(trusted, "github:someone/*", "terraform"), + want: []string{}, + }, + { + name: "exemptPaths skips a config and its settings", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "examples/a/mise.toml", + Tools: []ir.MiseTool{tool("github:someone/tool")}, + SourceSettings: []ir.MiseSetting{{Name: "url_replacements", Value: "https://mirror.example.com/"}}, + }}}, + cfg: withExemptPaths(miseSourcesCfg(trusted), "examples/**"), + want: []string{}, + }, + { + name: "trustedRegistries absent: locked URLs are not checked", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + lockedFrom("jq", "aqua:jqlang/jq", [2]string{"linux-x64", "https://evil.example/jq"}), + )}}, + cfg: miseSourcesCfg(trusted), + want: []string{}, + }, + { + name: "a locked URL outside trustedRegistries is ISSUE-1014, one per platform", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(lockedFrom("jq", "aqua:jqlang/jq", + [2]string{"linux-x64", "https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux-amd64"}, + [2]string{"macos-arm64", "https://evil.example/jq"}, + ))}}, + cfg: withSources(miseSourcesCfg(trusted), "trustedRegistries", []string{"https://GitHub.com/*"}), + want: []string{"ISSUE-1014 mise.lock jq macos-arm64 https://evil.example/jq"}, + }, + { + name: "an empty trustedRegistries trusts no URL", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(lockedFrom("node", "core:node", [2]string{"linux-x64", "https://nodejs.org/dist/node.tgz"}))}}, + cfg: withSources(miseSourcesCfg(trusted), "trustedRegistries", []string{}), + want: []string{"ISSUE-1014 mise.lock node linux-x64 https://nodejs.org/dist/node.tgz"}, + }, + { + name: "a tool that is not trusted is ISSUE-1013 alone, its URLs are not judged", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(lockedFrom("tool", "ubi:someone/tool", [2]string{"linux-x64", "https://evil.example/t"}))}}, + cfg: withSources(miseSourcesCfg(trusted), "trustedRegistries", []string{}), + want: []string{"ISSUE-1013 mise.toml tool ubi:someone/tool"}, + }, + { + name: "configs sharing a lockfile give one ISSUE-1014 per entry and platform", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{ + miseConfig(lockedFrom("jq", "aqua:jqlang/jq", [2]string{"linux-x64", "https://evil.example/jq"})), + {Path: ".mise.toml", Lockfile: ir.MiseLockfile{Path: "mise.lock", Present: true, Version: 5}, Tools: []ir.MiseTool{lockedFrom("jq", "aqua:jqlang/jq", [2]string{"linux-x64", "https://evil.example/jq"})}}, + }}, + cfg: withSources(miseSourcesCfg(trusted), "trustedRegistries", []string{}), + want: []string{"ISSUE-1014 mise.lock jq linux-x64 https://evil.example/jq"}, + }, + { + name: "a url_replacements target outside trustedReplacement is ISSUE-1015", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + SourceSettings: []ir.MiseSetting{ + {Name: "url_replacements", Value: "https://GitHub.com/My-Org/mirror/"}, + {Name: "url_replacements", Value: "https://hashicorp-mirror.example.com/"}, + }, + }}}, + cfg: withSources(miseSourcesCfg(trusted), "trustedReplacement", []string{"https://github.com/my-org/*"}), + want: []string{"ISSUE-1015 mise.toml url_replacements https://hashicorp-mirror.example.com/"}, + }, + { + name: "a URL option on a trusted tool is ISSUE-1016", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + withOpts(tool("github:my-org/cli"), apiURL, ir.MiseToolOption{Name: "platforms.linux-x64.url", Value: "https://example.com/cli"}), + )}}, + cfg: miseSourcesCfg(trusted), + want: []string{ + "ISSUE-1016 mise.toml github:my-org/cli api_url https://ghe.example.com/api/v3", + "ISSUE-1016 mise.toml github:my-org/cli platforms.linux-x64.url https://example.com/cli", + }, + }, + { + name: "a URL option on a tool that is not trusted is ISSUE-1013 alone", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(withOpts(tool("github:someone/tool"), apiURL))}}, + cfg: miseSourcesCfg(trusted), + want: []string{"ISSUE-1013 mise.toml github:someone/tool github:someone/tool"}, + }, + { + name: "an option URL inside trustedOptions passes, case-insensitively", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + withOpts(tool("github:my-org/cli"), ir.MiseToolOption{Name: "api_url", Value: "https://GHE.corp.example/api/v3"}), + withOpts(tool("http:internal"), ir.MiseToolOption{Name: "url", Value: "https://downloads.corp.example/tool.tgz"}), + )}}, + cfg: withSources(miseSourcesCfg([]string{"github:my-org/*", "http:*"}), "trustedOptions", []string{"https://ghe.corp.example/*", "https://downloads.corp.example/*"}), + want: []string{}, + }, + { + name: "an index URL from pipx_args is judged alone, so a trusted one passes", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + withOpts(tool("pipx:black"), ir.MiseToolOption{Name: "uvx_args", Value: "https://pypi.corp.example/simple"}), + withOpts(tool("pipx:ruff"), ir.MiseToolOption{Name: "pipx_args", Value: "https://evil.example/simple"}), + )}}, + cfg: withSources(miseSourcesCfg([]string{"pipx:*"}), "trustedOptions", []string{"https://pypi.corp.example/*"}), + want: []string{"ISSUE-1016 mise.toml pipx:ruff pipx_args https://evil.example/simple"}, + }, + { + name: "a lock entry that records no backend fails closed, even with the lockfile check on", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "terraform", Request: "1", Locked: &ir.MiseLockEntry{Version: "1.0.0"}, + })}}, + cfg: withLockfileCheck(miseSourcesCfg(trusted)), + want: []string{"ISSUE-1013 mise.toml terraform"}, + }, + { + name: "with the lockfile check on, a missing lockfile is ISSUE-1001 alone", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{tool("terraform")}, + }}}, + cfg: withLockfileCheck(miseSourcesCfg(trusted)), + want: []string{"ISSUE-1001 mise.toml"}, + }, + { + // The root config is exempt and unreadable, so the lockfile check + // does not judge svc/: this check reports the untraced tool. + name: "with the lockfile check on, a subproject whose lockfile is unknown is ISSUE-1013 for an untraced shorthand", + mise: &ir.MiseScan{ + Configs: []ir.MiseConfig{{ + Path: "svc/mise.toml", + Lockfile: ir.MiseLockfile{Path: "svc/mise.lock"}, + LockfileUnknown: true, + Tools: []ir.MiseTool{tool("terraform")}, + }}, + }, + cfg: withLockfileCheck(miseSourcesCfg(trusted)), + want: []string{"ISSUE-1013 svc/mise.toml terraform"}, + }, + { + name: "a local config is judged for sources, never by the lockfile check", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.local.toml", + Lockfile: ir.MiseLockfile{Path: "mise.local.lock"}, + Local: true, + Tools: []ir.MiseTool{tool("github:evil/x"), tool("terraform")}, + SourceSettings: []ir.MiseSetting{{Name: "url_replacements", Value: "https://evil.example/"}}, + }}}, + cfg: withLockfileCheck(miseSourcesCfg(trusted)), + want: []string{ + "ISSUE-1013 mise.local.toml github:evil/x github:evil/x", + "ISSUE-1013 mise.local.toml terraform", + "ISSUE-1015 mise.local.toml url_replacements https://evil.example/", + }, + }, + { + name: ".tool-versions is not judged by the sources check", + mise: &ir.MiseScan{ToolVersions: []ir.MiseToolVersionsEntry{ + {Path: ".tool-versions", Name: "github:evil-org/tool"}, + {Path: ".tool-versions", Name: "shellcheck"}, + }}, + cfg: miseSourcesCfg(trusted), + want: []string{}, + }, + { + name: "the sources check abstains when its block is absent", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Tools: []ir.MiseTool{withOpts(tool("github:someone/tool"), apiURL)}, + SourceSettings: []ir.MiseSetting{{Name: "url_replacements", Value: "https://mirror.example.com/"}}, + }}}, + cfg: map[string]any{"mise-en-place": map[string]any{ + "mise": map[string]any{"exemptPackages": []string{}}, + }}, + want: []string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, ProjectPath: "g/p", Mise: tc.mise} + findings, err := evaluateStrict(engine, context.Background(), p, tc.cfg) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + if got := miseSourceKeys(findings); !reflect.DeepEqual(got, tc.want) { + t.Errorf("findings = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/policies/mise_tasks.rego b/policies/mise_tasks.rego new file mode 100644 index 00000000..5652c58a --- /dev/null +++ b/policies/mise_tasks.rego @@ -0,0 +1,63 @@ +# mise-tasks — the tasks check of mise-en-place (#254, #678). Every mise +# project (a directory holding a mise config) must declare each task of +# `required`. One finding per project that misses any, naming them. +# +# The collector (packagemanager/mise) lists the tasks mise offers in each +# project: [tasks.] tables, TOML task files, executable file tasks +# of the task directories, and those of every parent directory. A +# required entry matches a task name or alias, globs allowed (`lint:*`). +# +# Fail closed: tasks from a remote (git::, oci::, zip::) or templated +# include are not read, so they never satisfy a requirement; the finding +# names the includes that were not read. exemptPaths is the way out. +package mise_tasks + +import rego.v1 + +_mise := input.config["mise-en-place"].mise + +_check := _mise.tasks + +# Repository paths exempted from every mise check, globs with `/` as the +# separator ("examples/**"). +_path_exempt(p) if { + some pattern in _mise.exemptPaths + glob.match(pattern, ["/"], p) +} + +# ISSUE-1017: a project misses at least one required task. +deny contains finding if { + _check + some proj in input.pipeline.mise.projects + not _path_exempt(proj.path) + missing := [required | + some required in _check.required + not _present(proj, required) + ] + count(missing) > 0 + finding := { + "code": "ISSUE-1017", + "severity": "medium", + "message": sprintf("`%s` does not declare the required tasks: missing %s%s", [proj.path, _entries_text(missing), _unread_text(proj)]), + "file": proj.path, + "missing": missing, + } +} + +_present(proj, required) if { + some task in proj.tasks + glob.match(required, null, task.name) +} + +_present(proj, required) if { + some task in proj.tasks + some alias in task.aliases + glob.match(required, null, alias) +} + +_entries_text(entries) := concat(" and ", [sprintf("`%s`", [e]) | some e in entries]) + +_unread_text(proj) := text if { + count(object.get(proj, "unreadIncludes", [])) > 0 + text := sprintf(" (tasks from %s were not read)", [_entries_text(proj.unreadIncludes)]) +} else := "" diff --git a/policies/mise_tasks_test.go b/policies/mise_tasks_test.go new file mode 100644 index 00000000..5b8b93a3 --- /dev/null +++ b/policies/mise_tasks_test.go @@ -0,0 +1,143 @@ +package policies_test + +import ( + "context" + "reflect" + "sort" + "testing" + + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/policies" + + opaengine "github.com/getplumber/plumber/internal/engine/opa" +) + +// miseTasksCfg is the Rego config of mise-en-place with only the mise +// tasks check on, requiring the given tasks. +func miseTasksCfg(required ...string) map[string]any { + return map[string]any{ + "mise-en-place": map[string]any{ + "mise": map[string]any{ + "tasks": map[string]any{"required": required}, + "exemptPackages": []string{}, + "exemptPaths": []string{}, + }, + }, + } +} + +// miseTaskFindings renders each ISSUE-1017 finding as +// "code file: message". +func miseTaskFindings(findings []opaengine.Finding) []string { + out := []string{} + for _, f := range findings { + if f.Code != "ISSUE-1017" { + continue + } + out = append(out, f.Code+" "+f.File+": "+f.Message) + } + sort.Strings(out) + return out +} + +func TestIssue1017_MiseTasks(t *testing.T) { + engine := opaengine.New() + if err := engine.LoadFromFSFiltered(policies.FS, nil); err != nil { + t.Fatalf("load embedded policies: %v", err) + } + task := func(name string, aliases ...string) ir.MiseTask { + return ir.MiseTask{Name: name, Aliases: aliases, Source: "mise.toml"} + } + project := func(path string, tasks ...ir.MiseTask) ir.MiseProject { + return ir.MiseProject{Path: path, Tasks: tasks} + } + cases := []struct { + name string + mise *ir.MiseScan + cfg map[string]any + want []string + }{ + { + name: "a project with every required task passes", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("mise.toml", task("lint"), task("test"))}}, + cfg: miseTasksCfg("lint", "test"), + want: []string{}, + }, + { + name: "the finding lists every missing task", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("mise.toml", task("lint"))}}, + cfg: miseTasksCfg("lint", "test", "scan"), + want: []string{"ISSUE-1017 mise.toml: `mise.toml` does not declare the required tasks: missing `test` and `scan`"}, + }, + { + name: "an alias and a glob satisfy a requirement", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("mise.toml", task("golangci", "lint"), task("test:unit"))}}, + cfg: miseTasksCfg("lint", "test:*"), + want: []string{}, + }, + { + name: "each project is judged on its own", + mise: &ir.MiseScan{Projects: []ir.MiseProject{ + project("mise.toml", task("lint"), task("test")), + project("svc/mise.toml", task("lint")), + }}, + cfg: miseTasksCfg("lint", "test"), + want: []string{"ISSUE-1017 svc/mise.toml: `svc/mise.toml` does not declare the required tasks: missing `test`"}, + }, + { + name: "includes that were not read are named, and never satisfy a requirement", + mise: &ir.MiseScan{Projects: []ir.MiseProject{{ + Path: "mise.toml", Tasks: []ir.MiseTask{task("lint")}, + UnreadIncludes: []string{"git::https://github.com/org/shared.git//tasks?ref=v1"}, + }}}, + cfg: miseTasksCfg("lint", "test"), + want: []string{"ISSUE-1017 mise.toml: `mise.toml` does not declare the required tasks: missing `test` (tasks from `git::https://github.com/org/shared.git//tasks?ref=v1` were not read)"}, + }, + { + name: "exemptPaths skips a project", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("examples/a/mise.toml")}}, + cfg: withExemptPaths(miseTasksCfg("lint"), "examples/**"), + want: []string{}, + }, + { + name: "a glob matches an alias", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("mise.toml", task("golangci", "lint-go"))}}, + cfg: miseTasksCfg("lint*"), + want: []string{}, + }, + { + name: "a project with no task at all", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("mise.toml")}}, + cfg: miseTasksCfg("lint"), + want: []string{"ISSUE-1017 mise.toml: `mise.toml` does not declare the required tasks: missing `lint`"}, + }, + { + name: "two unread includes are both named", + mise: &ir.MiseScan{Projects: []ir.MiseProject{{ + Path: "mise.toml", UnreadIncludes: []string{"git::a", "oci::b"}, + }}}, + cfg: miseTasksCfg("lint"), + want: []string{"ISSUE-1017 mise.toml: `mise.toml` does not declare the required tasks: missing `lint` (tasks from `git::a` and `oci::b` were not read)"}, + }, + { + name: "the tasks check abstains when its block is absent", + mise: &ir.MiseScan{Projects: []ir.MiseProject{project("mise.toml")}}, + cfg: map[string]any{"mise-en-place": map[string]any{ + "mise": map[string]any{"exemptPackages": []string{}}, + }}, + want: []string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, ProjectPath: "g/p", Mise: tc.mise} + findings, err := evaluateStrict(engine, context.Background(), p, tc.cfg) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + if got := miseTaskFindings(findings); !reflect.DeepEqual(got, tc.want) { + t.Errorf("findings =\n%v\nwant\n%v", got, tc.want) + } + }) + } +} diff --git a/policies/mise_versions.rego b/policies/mise_versions.rego new file mode 100644 index 00000000..47232bc8 --- /dev/null +++ b/policies/mise_versions.rego @@ -0,0 +1,82 @@ +# mise-versions — the versions check of mise-en-place for +# mise (#254). A tool request in a mise config must not use a forbidden +# version (`latest`, `lts`, `nightly`, ...). The check reads the request as +# written in the config, where people review it: with `latest`, the +# lockfile still pins a version, but `mise lock --bump` or `mise upgrade` +# moves it with no change in the config. +# +# Fail closed: a request Plumber cannot read statically (a template, an +# empty or unquoted version) is reported too, never passed. exemptPackages +# (tool keys) and exemptPaths (repository paths) are the way out for +# intentional cases. A config that cannot be parsed stops the run before +# the policies. .tool-versions is not judged here: it is read by the +# lockfile check only (ISSUE-1009), so with that check off it is not read +# at all. +package mise_versions + +import rego.v1 + +_mise := input.config["mise-en-place"].mise + +_check := _mise.versions + +# Tool keys exempted from every mise check, globs allowed. +_exempt(name) if { + some pattern in _mise.exemptPackages + glob.match(pattern, null, name) +} + +# Repository paths exempted from every mise check, globs with `/` as the +# separator ("examples/**"). +_path_exempt(p) if { + some pattern in _mise.exemptPaths + glob.match(pattern, ["/"], p) +} + +# The tool requests under check: those of configs outside exemptPaths, for +# tools not in exemptPackages. +_requests contains [cfg, tool] if { + some cfg in input.pipeline.mise.configs + not _path_exempt(cfg.path) + some tool in cfg.tools + not _exempt(tool.name) +} + +_forbidden(request) if { + some pattern in _check.forbiddenVersions + glob.match(pattern, null, request) +} + +# ISSUE-1011: a tool request uses a forbidden version. One finding per +# request, however many patterns it matches. +deny contains finding if { + _check + some [cfg, tool] in _requests + not tool.unreadable + _forbidden(tool.request) + finding := { + "code": "ISSUE-1011", + "severity": "high", + "message": sprintf("Tool `%s` in `%s` requests the forbidden version `%s`", [tool.name, cfg.path, tool.request]), + "file": cfg.path, + "package": tool.name, + "request": tool.request, + } +} + +# ISSUE-1012, fail closed: a request Plumber cannot read statically (a +# template, an empty or unquoted version). It cannot be checked against +# forbiddenVersions, so it is reported, never passed. +deny contains finding if { + _check + some [cfg, tool] in _requests + tool.unreadable + finding := { + "code": "ISSUE-1012", + "severity": "high", + "message": sprintf("Tool `%s` = `%s` in `%s` cannot be read statically because %s", [tool.name, tool.request, cfg.path, tool.unreadable]), + "file": cfg.path, + "package": tool.name, + "request": tool.request, + } +} diff --git a/policies/mise_versions_test.go b/policies/mise_versions_test.go new file mode 100644 index 00000000..ffaf0048 --- /dev/null +++ b/policies/mise_versions_test.go @@ -0,0 +1,189 @@ +package policies_test + +import ( + "context" + "reflect" + "sort" + "testing" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/policies" + + opaengine "github.com/getplumber/plumber/internal/engine/opa" +) + +// shippedForbiddenVersions returns the forbiddenVersions list of +// plumber:default, so the cases below pin the shipped list: dropping a +// pattern from defaultConfig/.plumber.yaml fails them. +func shippedForbiddenVersions(t *testing.T) []string { + t.Helper() + pc, _, _, err := configuration.LoadPlumberConfigFromBytes([]byte("extends: plumber:default\nversion: \"2.0\"\n"), "test") + if err != nil { + t.Fatalf("load plumber:default: %v", err) + } + if !pc.Mise.VersionsCheckEnabled() { + t.Fatal("plumber:default does not turn the mise versions check on") + } + return pc.Mise.Versions.ForbiddenVersions +} + +// miseVersionsCfg is the Rego config of mise-en-place with +// only the mise versions check on. +func miseVersionsCfg(forbidden []string, exempt ...string) map[string]any { + if exempt == nil { + exempt = []string{} + } + return map[string]any{ + "mise-en-place": map[string]any{ + "mise": map[string]any{ + "versions": map[string]any{"forbiddenVersions": forbidden}, + "exemptPackages": exempt, + "exemptPaths": []string{}, + }, + }, + } +} + +// miseVersionKeys renders each finding as "code file package request". +func miseVersionKeys(findings []opaengine.Finding) []string { + out := []string{} + for _, f := range findings { + if f.Code != "ISSUE-1011" && f.Code != "ISSUE-1012" { + continue + } + key := f.Code + " " + f.File + if pkg, ok := f.Data["package"].(string); ok { + key += " " + pkg + } + if req, ok := f.Data["request"].(string); ok { + key += " " + req + } + out = append(out, key) + } + sort.Strings(out) + return out +} + +func TestIssue1011_MiseVersions(t *testing.T) { + engine := opaengine.New() + if err := engine.LoadFromFSFiltered(policies.FS, nil); err != nil { + t.Fatalf("load embedded policies: %v", err) + } + tool := func(name, request string) ir.MiseTool { return ir.MiseTool{Name: name, Request: request} } + defaultForbiddenVersions := shippedForbiddenVersions(t) + cases := []struct { + name string + mise *ir.MiseScan + cfg map[string]any + want []string + }{ + { + name: "exact versions, bare majors and git refs pass the default list", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + tool("terraform", "1.9.8"), tool("node", "24"), tool("neovim", "ref:3f2a9c1e5b7d4a8f0e6c2b1a9d8e7f6c5b4a3d2e"), + )}}, + cfg: miseVersionsCfg(defaultForbiddenVersions), + want: []string{}, + }, + { + name: "every pattern of the default list is forbidden", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + tool("a", "latest"), tool("b", "lts"), tool("c", "lts/iron"), tool("d", "lts-iron"), + tool("e", "stable"), tool("f", "nightly"), tool("g", "beta"), tool("h", "branch:dev"), + tool("i", "path:/opt/x"), tool("j", "system"), tool("k", "sub-1:latest"), tool("l", "prefix:1.2"), + )}}, + cfg: miseVersionsCfg(defaultForbiddenVersions), + want: []string{ + "ISSUE-1011 mise.toml a latest", "ISSUE-1011 mise.toml b lts", "ISSUE-1011 mise.toml c lts/iron", + "ISSUE-1011 mise.toml d lts-iron", "ISSUE-1011 mise.toml e stable", "ISSUE-1011 mise.toml f nightly", + "ISSUE-1011 mise.toml g beta", "ISSUE-1011 mise.toml h branch:dev", "ISSUE-1011 mise.toml i path:/opt/x", + "ISSUE-1011 mise.toml j system", "ISSUE-1011 mise.toml k sub-1:latest", "ISSUE-1011 mise.toml l prefix:1.2", + }, + }, + { + name: "a request matching two patterns is one finding", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("node", "latest"))}}, + cfg: miseVersionsCfg([]string{"latest", "lat*"}), + want: []string{"ISSUE-1011 mise.toml node latest"}, + }, + { + name: "a tool with two forbidden versions is two findings", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("python", "latest"), tool("python", "system"))}}, + cfg: miseVersionsCfg(defaultForbiddenVersions), + want: []string{"ISSUE-1011 mise.toml python latest", "ISSUE-1011 mise.toml python system"}, + }, + { + name: "a template request fails closed with ISSUE-1012", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(ir.MiseTool{ + Name: "go", Request: "{{ env.GO_VERSION }}", Unreadable: "the version is a template", + })}}, + cfg: miseVersionsCfg(defaultForbiddenVersions), + want: []string{"ISSUE-1012 mise.toml go {{ env.GO_VERSION }}"}, + }, + { + name: "exemptPackages skips a tool", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("aqua:my-org/cli", "latest"), tool("node", "lts"))}}, + cfg: miseVersionsCfg(defaultForbiddenVersions, "aqua:my-org/*", "node"), + want: []string{}, + }, + { + name: "exemptPaths skips a config", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "examples/basic/mise.toml", + Tools: []ir.MiseTool{tool("node", "latest")}, + }}}, + cfg: withExemptPaths(miseVersionsCfg(defaultForbiddenVersions), "examples/**"), + want: []string{}, + }, + { + name: "a config with no lockfile is still judged", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.toml", + Lockfile: ir.MiseLockfile{Path: "mise.lock"}, + Tools: []ir.MiseTool{tool("node", "latest")}, + }}}, + cfg: miseVersionsCfg(defaultForbiddenVersions), + want: []string{"ISSUE-1011 mise.toml node latest"}, + }, + { + name: "a committed local config is judged", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{{ + Path: "mise.local.toml", + Local: true, + Tools: []ir.MiseTool{tool("node", "latest")}, + }}}, + cfg: miseVersionsCfg(defaultForbiddenVersions), + want: []string{"ISSUE-1011 mise.local.toml node latest"}, + }, + { + name: "an empty list passes every readable request but still fails closed with ISSUE-1012", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig( + tool("node", "latest"), + ir.MiseTool{Name: "go", Request: "{{ env.X }}", Unreadable: "the version is a template"}, + )}}, + cfg: miseVersionsCfg([]string{}), + want: []string{"ISSUE-1012 mise.toml go {{ env.X }}"}, + }, + { + name: "the versions check abstains when its block is absent", + mise: &ir.MiseScan{Configs: []ir.MiseConfig{miseConfig(tool("node", "latest"))}}, + cfg: map[string]any{"mise-en-place": map[string]any{ + "mise": map[string]any{"exemptPackages": []string{}}, + }}, + want: []string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, ProjectPath: "g/p", Mise: tc.mise} + findings, err := evaluateStrict(engine, context.Background(), p, tc.cfg) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + if got := miseVersionKeys(findings); !reflect.DeepEqual(got, tc.want) { + t.Errorf("findings = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/provider/github.go b/provider/github.go index 8b266776..e4c785d6 100644 --- a/provider/github.go +++ b/provider/github.go @@ -21,7 +21,7 @@ type GitHubProvider struct{} func (p *GitHubProvider) Name() string { return "github" } func (p *GitHubProvider) Controls(pc *configuration.PlumberConfig) []control.ControlEntry { - return control.GitHubControls(pc) + return control.RunControls(pc, configuration.ProviderGitHub) } func (p *GitHubProvider) ComputeCompliance(result *control.AnalysisResult, conf *configuration.Configuration) (float64, int) { @@ -32,7 +32,7 @@ func (p *GitHubProvider) ComputeCompliance(result *control.AnalysisResult, conf return 0.0, 0 } findingsByControl := control.FindingsByControl(result.Findings) - entries := control.GitHubControls(conf.PlumberConfig) + entries := control.RunControls(conf.PlumberConfig, configuration.ProviderGitHub) control.MarkSkippedByFilter(entries, conf.ControlsFilter, conf.SkipControlsFilter) totalPct := 0.0 considered := 0 diff --git a/provider/gitlab.go b/provider/gitlab.go index 581965c6..13767237 100644 --- a/provider/gitlab.go +++ b/provider/gitlab.go @@ -23,7 +23,7 @@ type GitLabProvider struct{} func (p *GitLabProvider) Name() string { return "gitlab" } func (p *GitLabProvider) Controls(pc *configuration.PlumberConfig) []control.ControlEntry { - return control.GitLabControls(pc) + return control.RunControls(pc, configuration.ProviderGitLab) } func (p *GitLabProvider) ComputeCompliance(result *control.AnalysisResult, conf *configuration.Configuration) (float64, int) { @@ -44,7 +44,7 @@ func (p *GitLabProvider) ComputeCompliance(result *control.AnalysisResult, conf } passed := 0 controlCount := 0 - entries := control.GitLabControls(conf.PlumberConfig) + entries := control.RunControls(conf.PlumberConfig, configuration.ProviderGitLab) control.MarkSkippedByFilter(entries, conf.ControlsFilter, conf.SkipControlsFilter) for _, e := range entries { if e.Skipped {