diff --git a/.plumber.yaml b/.plumber.yaml index 06b95133..9d277ccb 100644 --- a/.plumber.yaml +++ b/.plumber.yaml @@ -192,6 +192,34 @@ gitlab: # Minimum access level required to push (0=No one, 30=Developer, 40=Maintainer) minPushAccessLevel: 40 # =========================================== + # Tag must be protected + # =========================================== + # Checks that tags are protected, so nobody with push access can move, + # delete or create a release tag (Settings > Repository > Protected + # tags). A protected tag already blocks updates and deletions; creation + # must be limited to Maintainers or a narrower set. + # + # By default (no namePatterns) every tag must be covered by one + # protected tag `*`, the recommended setup. List patterns to check + # those instead, each on its own. + # + # Only checked once the project has a tag or a job runs on tags, so + # projects that never tag stay quiet. A job that runs on tag pipelines + # (only: tags, or a rule on $CI_COMMIT_TAG) raises the finding to + # critical. + # + # Needs a token with read_api to list protected tags and tags; without + # one the control reports "not evaluated", never a false positive. Not + # evaluated in platform mode yet (the snapshot has no tag lane). + tagMustBeProtected: + # Set to false to disable this control + enabled: true + # Tag name patterns that must be protected (supports wildcards). + # Empty: a protected tag `*` must cover all tags. + namePatterns: [] + # Also require tag creation to be restricted + requireCreationRestricted: true + # =========================================== # MR approval rules must require a minimum number of approvals # =========================================== # Flags approval rules covering all protected branches that require fewer @@ -977,6 +1005,31 @@ github: allowForcePush: false codeOwnerApprovalRequired: false + # =========================================== + # Tag must be protected (project governance) + # =========================================== + # Reads the repository's tag rulesets (its own and the organization's) + # and its tags. Tags must be covered by active rulesets that restrict + # updates, deletions and creations. + # + # By default (no namePatterns) the rulesets must target All tags + # (~ALL) with no exclusion, the recommended setup. List patterns to + # check those instead, each on its own. Workflow tag triggers never add + # a pattern: they make the finding critical. + # + # Only checked once the repository has a tag or a workflow runs on + # tags, so repositories that never tag stay quiet. + # + # Needs only "Metadata: read" (every GITHUB_TOKEN has it): listing + # rulesets and tags needs no admin rights. Without access the control + # reports "not evaluated", never a false positive. + tagMustBeProtected: + enabled: true + # Tag name patterns that must be protected (supports wildcards). + # Empty: rulesets on All tags (~ALL) must cover every tag. + namePatterns: [] + requireCreationRestricted: true + # ============================================================================ # Workflows must include required actions # ============================================================================ diff --git a/README.md b/README.md index 9b6fa938..7dada83a 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,7 @@ include: score_push: true ``` -Add `GITLAB_TOKEN` in **Settings -> CI/CD -> Variables**: `plumber` environment, `read_api` + `read_repository` for scanning, or `api` if you want Plumber to post MR comments or badges. +Add `GITLAB_TOKEN` in **Settings -> CI/CD -> Variables**: `plumber` environment, `read_api` + `read_repository` for scanning (`read_api` also covers the protected tags `tagMustBeProtected` reads), or `api` if you want Plumber to post MR comments or badges. **Full guide:** [getplumber.io/docs/cli/gitlab#run-with-the-gitlab-ci-component](https://getplumber.io/docs/cli/gitlab#run-with-the-gitlab-ci-component) diff --git a/action.yml b/action.yml index e626d565..039f406f 100644 --- a/action.yml +++ b/action.yml @@ -22,7 +22,7 @@ inputs: description: "Verify the downloaded binary's build-provenance attestation (sigstore/SLSA) against the getplumber/plumber release workflow, using the gh CLI. This anchors the binary to a trusted build regardless of the mutable release tag. Disable for air-gapped or GHES setups without attestation access." default: "true" github-token: - description: "Token for the GitHub API (branch protection, advisory DB, workflow states, runs, releases) and SARIF upload. Needs Administration:read for full branchMustBeProtected, actions:read to resolve a job's claims (whether it can run, and the repository default token's real write) from workflow states, the latest runs and one run's job log, and the job needs security-events:write to upload SARIF. A refused read on any of these is never an error: the claim it would have settled stays unknown." + description: "Token for the GitHub API (branch protection, advisory DB, workflow states, runs, releases) and SARIF upload. Needs Administration:read for full branchMustBeProtected (tagMustBeProtected needs only Metadata:read, which every token has), actions:read to resolve a job's claims (whether it can run, and the repository default token's real write) from workflow states, the latest runs and one run's job log, and the job needs security-events:write to upload SARIF. A refused read on any of these is never an error: the claim it would have settled stays unknown." default: ${{ github.token }} metadata-token: description: "Optional token (public-repo read is enough) used only to resolve third-party action versions for the known-CVE check. Set it when an action is hosted in an org with an IP allow list that blocks the runner's GITHUB_TOKEN; it also raises the API rate limit. Default: none, Plumber falls back to an anonymous read and, if that fails too, skips the version check rather than guessing." diff --git a/cmd/init.go b/cmd/init.go index 5947f2fa..2197d4d4 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1056,6 +1056,23 @@ func defaultBranchPatterns() string { return "" } +// defaultTagProtection is the tagMustBeProtected block the wizard writes +// with the access controls, enabled. The wizard asks nothing about it. +// The embedded default lists no pattern, which requires rules on all tags +// (the recommended setup); an empty list is omitted from the YAML, and an +// absent namePatterns means the same thing. +func defaultTagProtection() *configuration.TagProtectionControlConfig { + var patterns []string + if c := defaultGitLabControls().TagMustBeProtected; c != nil && len(c.NamePatterns) > 0 { + patterns = c.NamePatterns + } + return &configuration.TagProtectionControlConfig{ + Enabled: boolPtrInit(true), + NamePatterns: patterns, + RequireCreationRestricted: boolPtrInit(true), + } +} + // defaultTrustedActionsMinimumStars sources the star floor for // githubActionMustComeFromAuthorizedSources from the embedded default. func defaultTrustedActionsMinimumStars() int { @@ -1300,6 +1317,7 @@ func (st *initWizardState) applyAccessControls(gl, gh *configuration.ProviderCon MinMergeAccessLevel: intPtrInit(parseIntInit(st.BranchMinMergeAccessLevel, 30)), MinPushAccessLevel: intPtrInit(parseIntInit(st.BranchMinPushAccessLevel, 40)), } + gl.Controls.TagMustBeProtected = defaultTagProtection() if st.MRApprovalMinEnabled { gl.Controls.MergeRequestApprovalRulesMustRequireMinimumApprovals = &configuration.MRApprovalRulesMinApprovalsControlConfig{ Enabled: boolPtrInit(true), @@ -1336,6 +1354,7 @@ func (st *initWizardState) applyAccessControls(gl, gh *configuration.ProviderCon AllowForcePush: boolPtrInit(st.BranchAllowForcePush), CodeOwnerApprovalRequired: boolPtrInit(st.BranchCodeOwnerApprovalRequiredGitHub), } + gh.Controls.TagMustBeProtected = defaultTagProtection() } } diff --git a/cmd/init_mr_approval_test.go b/cmd/init_mr_approval_test.go index fbf40491..1072260c 100644 --- a/cmd/init_mr_approval_test.go +++ b/cmd/init_mr_approval_test.go @@ -117,3 +117,23 @@ func TestApplyAccessControls_MRApprovalSettingsMapping(t *testing.T) { } }) } + +// applyAccessControls writes tagMustBeProtected on both providers. A +// dropped assignment or a regressed defaultTagProtection would silently +// leave the control out of the .plumber.yaml `plumber config init` emits. +func TestApplyAccessControls_TagProtection(t *testing.T) { + gl, gh := &configuration.ProviderConfig{}, &configuration.ProviderConfig{} + (&initWizardState{}).applyAccessControls(gl, gh) + for provider, pc := range map[string]*configuration.ProviderConfig{"gitlab": gl, "github": gh} { + c := pc.Controls.TagMustBeProtected + if c == nil || !c.IsEnabled() { + t.Fatalf("%s: tagMustBeProtected should be emitted enabled, got %+v", provider, c) + } + if got := c.EffectiveNamePatterns(); len(got) != 0 { + t.Errorf("%s: namePatterns = %v, want none (rules on all tags)", provider, got) + } + if !c.IsCreationRestrictionRequired() { + t.Errorf("%s: requireCreationRestricted should default to true", provider) + } + } +} diff --git a/cmd/legacy_json.go b/cmd/legacy_json.go index 15149850..6e3b761e 100644 --- a/cmd/legacy_json.go +++ b/cmd/legacy_json.go @@ -278,6 +278,8 @@ func buildLegacyResult(e control.ControlEntry, result *control.AnalysisResult, p return "mrApprovalSettingsResult", buildMRApprovalSettingsBlock(common, findings) case "mergeRequestSettingsMustBeCompliant": return "mrSettingsResult", buildMRSettingsBlock(common, findings) + case "tagMustBeProtected": + return "tagProtectionResult", buildTagProtectionBlock(common, result, findings) } return "", nil } @@ -394,6 +396,36 @@ func buildMRSettingsBlock(c legacyCommon, findings []opaengine.Finding) map[stri } } +// buildTagProtectionBlock emits the tagMustBeProtected (ISSUE-510) block on +// both providers. The findings are repository-level (no file/job): each +// issue carries the tagPattern and its missingProtections. tagRules and +// tagsChecked describe what the collection read; both stay 0 when it did +// not run or could not read the provider. +func buildTagProtectionBlock(c legacyCommon, result *control.AnalysisResult, findings []opaengine.Finding) map[string]any { + rules, tags := 0, 0 + if result != nil { + p := result.Pipeline + if p == nil { + p = result.GitHubPipeline + } + if tp := p.TagProtectionOrNil(); tp != nil && tp.Known { + rules, tags = len(tp.Rules), len(tp.Tags) + } + } + return map[string]any{ + "issues": projectFindings(findings, "job"), + "metrics": map[string]any{ + "unprotectedTagPatterns": len(findings), + "tagRules": rules, + "tagsChecked": tags, + }, + "version": "0.1.0", + "ciValid": c.CiValid, + "ciMissing": c.CiMissing, + "skipped": c.Skipped, + } +} + // legacyCommon carries the bookkeeping fields shared by every // `*Result` block: ciValid, ciMissing, skipped. type legacyCommon struct { diff --git a/cmd/legacy_json_github.go b/cmd/legacy_json_github.go index 5ee91bbf..6196cbe8 100644 --- a/cmd/legacy_json_github.go +++ b/cmd/legacy_json_github.go @@ -75,6 +75,8 @@ func buildLegacyResultGitHub(e control.ControlEntry, result *control.AnalysisRes return "debugTraceResult", buildDebugTraceBlockGitHub(common, result, findings) case "pipelineMustNotExecuteUnverifiedScripts": return "unverifiedScriptsResult", buildUnverifiedScriptsBlockGitHub(common, result, findings) + case "tagMustBeProtected": + return "tagProtectionResult", buildTagProtectionBlock(common, result, findings) } return "", nil } diff --git a/cmd/legacy_json_gitlab_test.go b/cmd/legacy_json_gitlab_test.go index 6ae9960a..089a2970 100644 --- a/cmd/legacy_json_gitlab_test.go +++ b/cmd/legacy_json_gitlab_test.go @@ -368,3 +368,81 @@ func TestAuthorizedSourcesJSONBlocks(t *testing.T) { }) } } + +// TestTagProtectionJSONBlock locks the tagMustBeProtected (ISSUE-510) +// results.json block on both providers. An unrouted control falls through +// to ("", nil) and its block silently leaves results.json; the metrics +// must also come from whichever pipeline carries the collection and stay +// 0 when the provider could not be read. +func TestTagProtectionJSONBlock(t *testing.T) { + entry := control.ControlEntry{DisplayName: "Tag pattern must be protected", ControlName: "tagMustBeProtected"} + findings := []opaengine.Finding{{ + Code: "ISSUE-510", + Data: map[string]any{"tagPattern": "v*", "missingProtections": []any{"update", "deletion", "creation"}}, + }} + known := func() *ir.TagProtection { + return &ir.TagProtection{ + Known: true, + Rules: []ir.TagProtectionRule{{ID: "1"}, {ID: "2"}}, + Tags: []string{"v1", "v2", "v3"}, + } + } + cases := map[string]struct { + build func(*control.AnalysisResult, []opaengine.Finding) (string, any) + result func(*ir.TagProtection) *control.AnalysisResult + }{ + "gitlab": { + build: func(r *control.AnalysisResult, f []opaengine.Finding) (string, any) { + return buildLegacyResult(entry, r, nil, f) + }, + result: func(tp *ir.TagProtection) *control.AnalysisResult { + return &control.AnalysisResult{CiValid: true, Pipeline: &ir.NormalizedPipeline{TagProtection: tp}} + }, + }, + "github": { + build: func(r *control.AnalysisResult, f []opaengine.Finding) (string, any) { + return buildLegacyResultGitHub(entry, r, nil, f) + }, + result: func(tp *ir.TagProtection) *control.AnalysisResult { + return &control.AnalysisResult{CiValid: true, GitHubPipeline: &ir.NormalizedPipeline{TagProtection: tp}} + }, + }, + } + for provider, tc := range cases { + t.Run(provider, func(t *testing.T) { + name, block := tc.build(tc.result(known()), findings) + if name != "tagProtectionResult" { + t.Fatalf("block name = %q, want tagProtectionResult (dispatch dropped the block)", name) + } + m, ok := block.(map[string]any) + if !ok { + t.Fatalf("block is %T, want map[string]any", block) + } + issues, ok := m["issues"].([]map[string]any) + if !ok || len(issues) != 1 || issues[0]["code"] != "ISSUE-510" { + t.Fatalf("issues = %v, want the one ISSUE-510 finding", m["issues"]) + } + if issues[0]["tagPattern"] != "v*" { + t.Errorf("issue lost tagPattern; got keys %v", issues[0]) + } + metrics := m["metrics"].(map[string]any) + if metrics["unprotectedTagPatterns"] != 1 || metrics["tagRules"] != 2 || metrics["tagsChecked"] != 3 { + t.Errorf("metrics = %v, want 1 unprotected pattern, 2 rules, 3 tags", metrics) + } + + // An unreadable collection reports no counts. + _, unknownBlock := tc.build(tc.result(&ir.TagProtection{Known: false, Tags: []string{"v1"}}), findings) + um := unknownBlock.(map[string]any)["metrics"].(map[string]any) + if um["tagRules"] != 0 || um["tagsChecked"] != 0 { + t.Errorf("unknown collection metrics = %v, want tagRules and tagsChecked at 0", um) + } + + // A clean run still emits the block: a missing block reads as a + // control that never ran. + cleanName, cleanBlock := tc.build(tc.result(known()), nil) + if cleanName != "tagProtectionResult" || cleanBlock == nil { + t.Fatalf("clean run: name=%q block=%v, want tagProtectionResult with a non-nil block", cleanName, cleanBlock) + } + }) + } +} diff --git a/cmd/testdata/catalog_golden.json b/cmd/testdata/catalog_golden.json index c7588fee..170edb08 100644 --- a/cmd/testdata/catalog_golden.json +++ b/cmd/testdata/catalog_golden.json @@ -1843,6 +1843,58 @@ }, "issueCodeEntryKinds": {} }, + { + "id": "CTRL-510", + "name": "tagMustBeProtected", + "displayName": "Tag must be protected", + "category": "Access and Authorization", + "providers": [ + "gitlab", + "github" + ], + "description": "Verifies that release tag patterns in use (configured ones and those workflows trigger on) are protected: tag updates and deletions blocked and tag creation restricted.", + "requiresConfig": false, + "configSchema": { + "control": "tagMustBeProtected", + "fields": [ + { + "name": "enabled", + "type": "bool", + "optional": true, + "nullable": true, + "toggle": true, + "description": "Turns the control on; when false or absent the control is skipped." + }, + { + "name": "namePatterns", + "type": "array", + "optional": true, + "description": "List of tag name patterns that must be protected; supports wildcards. Empty or unset (the default): rules on all tags (a GitHub ruleset on ~ALL, a GitLab protected tag `*`) with no exclusion must protect every tag. Otherwise each pattern is checked on its own, once an existing tag matches it or a workflow triggers on it. Workflow tag triggers never add a pattern.", + "elem": { + "type": "string", + "optional": false + }, + "default": "[]" + }, + { + "name": "requireCreationRestricted", + "type": "bool", + "optional": true, + "nullable": true, + "toggle": true, + "description": "When true, tag creation must also be restricted, on top of tag updates and deletions being blocked.", + "default": "true" + } + ] + }, + "issueCodes": [ + "ISSUE-510" + ], + "issueCodeRoles": { + "ISSUE-510": "gate" + }, + "issueCodeEntryKinds": {} + }, { "id": "CTRL-705", "name": "untrustedTriggersMustNotWriteCache", @@ -2876,6 +2928,15 @@ "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-506", "controlName": "mergeRequestSettingsMustBeCompliant" }, + { + "code": "ISSUE-510", + "severity": "critical", + "title": "Tag pattern not protected", + "description": "Tags in use (all tags by default, or the configured patterns) are not fully protected: anyone with push access can move, delete or create a release tag, and ship code that consumers pinned to that tag, or that a tag-triggered release workflow publishes, without review.", + "remediation": "Protect all tags with one rule. On GitLab: Settings \u003e Repository \u003e Protected tags, add `*` with Maintainers (or a narrower set) allowed to create. On GitHub: Settings \u003e Rules \u003e Rulesets, add an active tag ruleset targeting All tags with Restrict creations, Restrict updates and Restrict deletions, and grant your release automation a bypass. With namePatterns configured, target those patterns instead.", + "docUrl": "https://getplumber.io/docs/cli/issues/ISSUE-510", + "controlName": "tagMustBeProtected" + }, { "code": "ISSUE-601", "severity": "critical", diff --git a/configuration/plumberconfig.go b/configuration/plumberconfig.go index 34ac76a1..7bd101c3 100644 --- a/configuration/plumberconfig.go +++ b/configuration/plumberconfig.go @@ -38,6 +38,9 @@ var validControlSchema = map[string][]string{ "allowForcePush", "codeOwnerApprovalRequired", "minMergeAccessLevel", "minPushAccessLevel", }, + "tagMustBeProtected": { + "enabled", "namePatterns", "requireCreationRestricted", + }, "mergeRequestApprovalRulesMustRequireMinimumApprovals": { "enabled", "minimumRequiredApprovals", }, @@ -313,6 +316,11 @@ type ControlsConfig struct { // BranchMustBeProtected control configuration BranchMustBeProtected *BranchProtectionControlConfig `yaml:"branchMustBeProtected,omitempty"` + // TagMustBeProtected control configuration: release tag patterns must + // be immutable (update and deletion blocked) with creation restricted + // (ISSUE-510). + TagMustBeProtected *TagProtectionControlConfig `yaml:"tagMustBeProtected,omitempty"` + // MergeRequestApprovalRulesMustRequireMinimumApprovals control // configuration (GitLab only). Flags approval rules covering all // protected branches that require fewer approvals than the configured @@ -955,6 +963,50 @@ type BranchProtectionControlConfig struct { MinPushAccessLevel *int `yaml:"minPushAccessLevel,omitempty"` } +// TagProtectionControlConfig configuration for the tag protection control +type TagProtectionControlConfig struct { + // Enabled controls whether this check runs + Enabled *bool `yaml:"enabled,omitempty"` + + // NamePatterns is a list of tag name patterns that must be protected + // (supports wildcards), each checked on its own. Empty or unset (the + // default) requires instead that rules on all tags (a GitHub ruleset + // on ~ALL, a GitLab protected tag `*`) protect every tag. + NamePatterns []string `yaml:"namePatterns,omitempty"` + + // RequireCreationRestricted, when true (the default), also requires + // tag creation to be restricted, on top of update and deletion. + RequireCreationRestricted *bool `yaml:"requireCreationRestricted,omitempty"` +} + +// IsEnabled returns whether the control is enabled +// Returns false if not properly configured +func (c *TagProtectionControlConfig) IsEnabled() bool { + if c == nil || c.Enabled == nil { + return false + } + return *c.Enabled +} + +// EffectiveNamePatterns returns the configured tag patterns, or an empty +// (non-nil) list when namePatterns is unset: empty selects the all-tags +// check. +func (c *TagProtectionControlConfig) EffectiveNamePatterns() []string { + if c == nil || c.NamePatterns == nil { + return []string{} + } + return c.NamePatterns +} + +// IsCreationRestrictionRequired reports whether tag creation must be +// restricted. Defaults to true when unset. +func (c *TagProtectionControlConfig) IsCreationRestrictionRequired() bool { + if c == nil || c.RequireCreationRestricted == nil { + return true + } + return *c.RequireCreationRestricted +} + // HardcodedJobsControlConfig configuration for the hardcoded jobs control type HardcodedJobsControlConfig struct { // Enabled controls whether this check runs diff --git a/configuration/plumberconfig_test.go b/configuration/plumberconfig_test.go index 3bb2ec76..dfff1ace 100644 --- a/configuration/plumberconfig_test.go +++ b/configuration/plumberconfig_test.go @@ -437,6 +437,7 @@ func TestValidControlNames(t *testing.T) { "pullRequestTargetMustNotCheckoutHead", "reusableWorkflowsMustNotInheritSecrets", "securityJobsMustNotBeWeakened", + "tagMustBeProtected", "untrustedTriggersMustNotWriteCache", "workflowMustIncludeRequiredActions", "workflowMustNotExportEntireSecretsContext", @@ -459,6 +460,39 @@ func TestValidControlNames(t *testing.T) { } } +// tagMustBeProtected has no default pattern: unset and empty both give a +// non-nil empty list, which the rule reads as "rules on all tags". A nil +// would reach Rego as null. requireCreationRestricted defaults to on. +func TestTagProtectionControlConfigDefaults(t *testing.T) { + var nilCfg *TagProtectionControlConfig + if got := nilCfg.EffectiveNamePatterns(); got == nil || len(got) != 0 { + t.Errorf("nil config EffectiveNamePatterns() = %#v, want []string{}", got) + } + if !nilCfg.IsCreationRestrictionRequired() { + t.Error("nil config must require creation to be restricted") + } + + unset := &TagProtectionControlConfig{} + if got := unset.EffectiveNamePatterns(); got == nil || len(got) != 0 { + t.Errorf("unset namePatterns EffectiveNamePatterns() = %#v, want []string{}", got) + } + + empty := &TagProtectionControlConfig{NamePatterns: []string{}} + if got := empty.EffectiveNamePatterns(); len(got) != 0 { + t.Errorf("explicit empty namePatterns EffectiveNamePatterns() = %v, want []", got) + } + + custom := &TagProtectionControlConfig{NamePatterns: []string{"release-*"}} + if got := custom.EffectiveNamePatterns(); len(got) != 1 || got[0] != "release-*" { + t.Errorf("custom namePatterns EffectiveNamePatterns() = %v, want [release-*]", got) + } + + off := false + if (&TagProtectionControlConfig{RequireCreationRestricted: &off}).IsCreationRestrictionRequired() { + t.Error("requireCreationRestricted: false must turn the creation requirement off") + } +} + // behaviorWhenCommitIsAdded is validated AT CONFIG LOAD because the Rego rule // looks the value up in a rank map: an unknown string would make the lookup // undefined and silently disable the check, so a typo must fail loudly here diff --git a/configuration/registry.go b/configuration/registry.go index 25614bbc..6b97e57d 100644 --- a/configuration/registry.go +++ b/configuration/registry.go @@ -123,6 +123,13 @@ var controlsMeta = map[string]ControlMeta{ Description: "Verifies that the analyzed branch is protected and that the protection settings are compliant: direct pushes and force pushes blocked, access levels tight enough, and code owner approval enforced where required.", RequiresConfig: true, }, + "tagMustBeProtected": { + Providers: []string{ProviderGitLab, ProviderGitHub}, + DisplayName: "Tag must be protected", + Category: CategoryAccessAndAuthorization, + ID: "CTRL-510", + Description: "Verifies that release tag patterns in use (configured ones and those workflows trigger on) are protected: tag updates and deletions blocked and tag creation restricted.", + }, "mergeRequestApprovalRulesMustRequireMinimumApprovals": { Providers: []string{ProviderGitLab}, DisplayName: "MR approval rules must require a minimum number of approvals", @@ -672,13 +679,13 @@ var RenamedControls = map[string]string{ // on/off, also add a typed struct in configuration/plumberconfig.go // and wire it through buildEngineConfig. // -// As of 2026-10-27 (after v0.7.14), counted from this file and control/catalog.go: -// - controlsMeta declares 69 controls: 7 cross-provider, 45 +// As of 2026-10-29 (tagMustBeProtected added), counted from this file and control/catalog.go: +// - controlsMeta declares 70 controls: 8 cross-provider, 45 // GitHub-only, 17 GitLab-only. -// - GitLab: zero benched. All 24 GitLab-applicable controls ship, and -// GitLabControls returns exactly those 24. -// - GitHub: 27 benched, so 25 of the 52 GitHub-applicable controls -// reach users, and GitHubControls returns exactly those 25. None of +// - GitLab: zero benched. All 25 GitLab-applicable controls ship, and +// GitLabControls returns exactly those 25. +// - GitHub: 27 benched, so 26 of the 53 GitHub-applicable controls +// reach users, and GitHubControls returns exactly those 26. None of // the 27 is cross-provider: the eight GitLab-shaped controls that // used to sit here (includes, components, templates, hardcoded jobs, // job variables, unsafe expansion, image sources) now declare diff --git a/configuration/schema_docs.go b/configuration/schema_docs.go index 3bc364f2..51e62bbd 100644 --- a/configuration/schema_docs.go +++ b/configuration/schema_docs.go @@ -78,6 +78,18 @@ var controlFieldDocs = map[string]FieldDoc{ "branchMustBeProtected.minPushAccessLevel": { Description: "Minimum access level required to push (0 = No one, 30 = Developer, 40 = Maintainer).", }, + "tagMustBeProtected.enabled": { + Description: "Turns the control on; when false or absent the control is skipped.", + }, + "tagMustBeProtected.namePatterns": { + Description: "List of tag name patterns that must be protected; supports wildcards. Empty or unset (the default): rules on all tags (a GitHub ruleset on ~ALL, a GitLab protected tag `*`) with no exclusion must protect every tag. Otherwise each pattern is checked on its own, once an existing tag matches it or a workflow triggers on it. Workflow tag triggers never add a pattern.", + Default: "[]", + }, + "tagMustBeProtected.requireCreationRestricted": { + Description: "When true, tag creation must also be restricted, on top of tag updates and deletions being blocked.", + Default: "true", + Toggle: true, + }, "mergeRequestApprovalRulesMustRequireMinimumApprovals.enabled": { Description: "Turns the control on; when false or absent the control is skipped.", }, diff --git a/configuration/schema_toggle_test.go b/configuration/schema_toggle_test.go index f4c6d28e..fd5416a1 100644 --- a/configuration/schema_toggle_test.go +++ b/configuration/schema_toggle_test.go @@ -51,6 +51,7 @@ func TestSchemaExportsToggleOnBehaviorSwitches(t *testing.T) { {"securityJobsMustNotBeWeakened", []string{"allowFailureMustBeFalse", "enabled"}}, {"securityJobsMustNotBeWeakened", []string{"rulesMustNotBeRedefined", "enabled"}}, {"securityJobsMustNotBeWeakened", []string{"whenMustNotBeManual", "enabled"}}, + {"tagMustBeProtected", []string{"requireCreationRestricted"}}, } for _, tc := range toggles { f := fieldAt(t, tc.control, tc.path...) diff --git a/configuration/testdata/control_ids_golden.txt b/configuration/testdata/control_ids_golden.txt index 42fc4c8c..6c32d54d 100644 --- a/configuration/testdata/control_ids_golden.txt +++ b/configuration/testdata/control_ids_golden.txt @@ -44,6 +44,7 @@ CTRL-502 mergeRequestApprovalRulesMustRequireMinimumApprovals CTRL-503 mergeRequestApprovalSettingsMustBeCompliant CTRL-504 mergeRequestApprovalRulesMustCoverAllProtectedBranches CTRL-506 mergeRequestSettingsMustBeCompliant +CTRL-510 tagMustBeProtected CTRL-601 projectMustHaveSecurityPolicySource CTRL-701 actionsMustBePinnedByCommitSha CTRL-702 actionsMustNotBeArchived diff --git a/configuration/v1_to_v2.go b/configuration/v1_to_v2.go index 22530c2d..365c1f26 100644 --- a/configuration/v1_to_v2.go +++ b/configuration/v1_to_v2.go @@ -71,6 +71,7 @@ func controlsConfigIsZero(c ControlsConfig) bool { return c.ContainerImageMustNotUseForbiddenTags == nil && c.ContainerImageMustComeFromAuthorizedSources == nil && c.BranchMustBeProtected == nil && + c.TagMustBeProtected == nil && c.MergeRequestApprovalRulesMustRequireMinimumApprovals == nil && c.MergeRequestApprovalRulesMustCoverAllProtectedBranches == nil && c.MergeRequestApprovalSettingsMustBeCompliant == nil && @@ -105,6 +106,7 @@ func controlsConfigEqual(a, b ControlsConfig) bool { return a.ContainerImageMustNotUseForbiddenTags == b.ContainerImageMustNotUseForbiddenTags && a.ContainerImageMustComeFromAuthorizedSources == b.ContainerImageMustComeFromAuthorizedSources && a.BranchMustBeProtected == b.BranchMustBeProtected && + a.TagMustBeProtected == b.TagMustBeProtected && a.MergeRequestApprovalRulesMustRequireMinimumApprovals == b.MergeRequestApprovalRulesMustRequireMinimumApprovals && a.MergeRequestApprovalRulesMustCoverAllProtectedBranches == b.MergeRequestApprovalRulesMustCoverAllProtectedBranches && a.MergeRequestApprovalSettingsMustBeCompliant == b.MergeRequestApprovalSettingsMustBeCompliant && diff --git a/control/bestfix.go b/control/bestfix.go index 03eb9de2..4d85fb5f 100644 --- a/control/bestfix.go +++ b/control/bestfix.go @@ -93,7 +93,7 @@ func (b BestFix) MarshalJSON() ([]byte, error) { // subject without ever carrying a secret or settings value, includePath // included, so a job-less include finding (ISSUE-404) names its include // path instead of falling through to an empty subject. -var bestFixSubjectKeys = []string{"uses", "image", "expression", "variableName", "branchName", "url", "includePath"} +var bestFixSubjectKeys = []string{"uses", "image", "expression", "variableName", "branchName", "tagPattern", "url", "includePath"} // bestFixWins reports whether a candidate (gain, code, hash) beats // whatever ComputeBestFix has kept as best so far: the largest gain diff --git a/control/catalog.go b/control/catalog.go index f6e52a7c..2d08ac14 100644 --- a/control/catalog.go +++ b/control/catalog.go @@ -54,6 +54,11 @@ func GitLabControls(pc *configuration.PlumberConfig) []ControlEntry { ControlName: "branchMustBeProtected", Skipped: c.BranchMustBeProtected == nil || !c.BranchMustBeProtected.IsEnabled(), }) + entries = append(entries, ControlEntry{ + DisplayName: "Tag must be protected", + ControlName: "tagMustBeProtected", + Skipped: c.TagMustBeProtected == nil || !c.TagMustBeProtected.IsEnabled(), + }) entries = append(entries, ControlEntry{ DisplayName: "MR approval rules must require a minimum number of approvals", ControlName: "mergeRequestApprovalRulesMustRequireMinimumApprovals", @@ -201,6 +206,11 @@ func GitHubControls(pc *configuration.PlumberConfig) []ControlEntry { ControlName: "branchMustBeProtected", Skipped: c.BranchMustBeProtected == nil || !c.BranchMustBeProtected.IsEnabled(), }) + entries = append(entries, ControlEntry{ + DisplayName: "Tag must be protected", + ControlName: "tagMustBeProtected", + Skipped: c.TagMustBeProtected == nil || !c.TagMustBeProtected.IsEnabled(), + }) entries = append(entries, ControlEntry{ DisplayName: "Security jobs must not be weakened", ControlName: "securityJobsMustNotBeWeakened", diff --git a/control/codes.go b/control/codes.go index 49985960..c8b1d3c2 100644 --- a/control/codes.go +++ b/control/codes.go @@ -215,6 +215,8 @@ const ( CodeBranchNonCompliant ErrorCode = "ISSUE-505" // ISSUE-506: The project's merge-request/merge settings do not meet the configured expectations CodeMRSettingsNonCompliant ErrorCode = "ISSUE-506" + // ISSUE-510: A release tag pattern in use is not protected (updates, deletions or creation left open) + CodeTagUnprotected ErrorCode = "ISSUE-510" // ISSUE-803: Job runs with overly broad permissions (write-all) CodeExcessivePermissions ErrorCode = "ISSUE-803" ) @@ -754,6 +756,16 @@ var errorCodeRegistry = map[ErrorCode]ErrorCodeInfo{ ControlName: "branchMustBeProtected", Role: RoleGate, }, + CodeTagUnprotected: { + Code: CodeTagUnprotected, + Severity: SeverityCritical, + Title: "Tag pattern not protected", + Description: "Tags in use (all tags by default, or the configured patterns) are not fully protected: anyone with push access can move, delete or create a release tag, and ship code that consumers pinned to that tag, or that a tag-triggered release workflow publishes, without review.", + Remediation: "Protect all tags with one rule. On GitLab: Settings > Repository > Protected tags, add `*` with Maintainers (or a narrower set) allowed to create. On GitHub: Settings > Rules > Rulesets, add an active tag ruleset targeting All tags with Restrict creations, Restrict updates and Restrict deletions, and grant your release automation a bypass. With namePatterns configured, target those patterns instead.", + DocURL: docsBaseURL + string(CodeTagUnprotected), + ControlName: "tagMustBeProtected", + Role: RoleGate, + }, CodeMRSettingsNonCompliant: { Code: CodeMRSettingsNonCompliant, Severity: SeverityMedium, diff --git a/control/collection_scope.go b/control/collection_scope.go index 37c40f11..83f68462 100644 --- a/control/collection_scope.go +++ b/control/collection_scope.go @@ -56,8 +56,10 @@ const ( laneGitLabProtection = "gitlab_protection" laneGitLabVariables = "gitlab_variables" laneGitLabSecurityPolicy = "gitlab_security_policy" + laneGitLabTagProtection = "gitlab_tag_protection" laneGitHubBranches = "github_branches" laneGitHubActionSource = "github_action_source" + laneGitHubTags = "github_tags" ) // markLaneCollected records that a gated collection ran this run. @@ -88,6 +90,24 @@ func markGitHubLanes(result *AnalysisResult, conf *configuration.Configuration, if branchLaneCollected(conf, projectPath, branchScope) { result.markLaneCollected(laneGitHubBranches) } + if tagLaneCollected(conf, projectPath) { + result.markLaneCollected(laneGitHubTags) + } +} + +// tagLaneCollected reports whether this run collects GitHub's tag +// protection (enrichGitHubTags): some collecting configuration enables +// tagMustBeProtected, it is not benched, and projectPath names a +// repository. Unlike the branch lane it needs no scope merge: the fetch +// reads every tag ruleset and tag whatever the patterns. +func tagLaneCollected(conf *configuration.Configuration, projectPath string) bool { + if conf == nil || configuration.IsBenched(configuration.ProviderGitHub, controlTagMustBeProtected) { + return false + } + if _, _, ok := gitHubOwnerRepo(projectPath); !ok { + return false + } + return anyCollectionConfig(conf, tagProtectionControlEnabledFor(configuration.ProviderGitHub)) } // collectionBranchProtectionConfig returns the configuration GitHub's @@ -194,10 +214,12 @@ var controlsByGatedLane = map[string]map[string][]string{ controlCicdVariablesMustBeMasked, }, laneGitLabSecurityPolicy: {controlSecurityPolicy}, + laneGitLabTagProtection: {controlTagMustBeProtected}, }, configuration.ProviderGitHub: { laneGitHubBranches: {controlBranchMustBeProtected}, laneGitHubActionSource: {controlMutableRemoteExec}, + laneGitHubTags: {controlTagMustBeProtected}, }, } diff --git a/control/collection_scope_test.go b/control/collection_scope_test.go index f49ab8dc..3e6e6c49 100644 --- a/control/collection_scope_test.go +++ b/control/collection_scope_test.go @@ -679,6 +679,7 @@ func TestControlsByGatedLane_Row62_MirrorsTheGatesItStandsFor(t *testing.T) { laneGitLabProtection: protectionDataNeeded, laneGitLabVariables: cicdVariableControlEnabled, laneGitLabSecurityPolicy: securityPolicyControlEnabled, + laneGitLabTagProtection: tagProtectionControlEnabledFor(configuration.ProviderGitLab), }, configuration.ProviderGitHub: { // The one lane whose gate needs the collector's own inputs: the @@ -687,6 +688,9 @@ func TestControlsByGatedLane_Row62_MirrorsTheGatesItStandsFor(t *testing.T) { return branchLaneCollected(conf, "acme/app", collectionBranchProtectionConfig(conf)) }, laneGitHubActionSource: shouldScanMutableExec, + laneGitHubTags: func(conf *configuration.Configuration) bool { + return tagLaneCollected(conf, "acme/app") + }, }, } diff --git a/control/degraded.go b/control/degraded.go index b52ba944..eea99e73 100644 --- a/control/degraded.go +++ b/control/degraded.go @@ -81,6 +81,12 @@ const degradedReasonVariablesPrefix = "CI/CD variables could not be fetched" // keeps every unrelated control from flipping to error over it. const degradedReasonSecurityPolicyPrefix = "security policy project could not be fetched" +// degradedReasonTagProtectionPrefix is the shared prefix of the tag +// protection fetch degraded reason, on both providers. Same contract as the +// prefixes above: StatusFor's degradedReasonIsTagProtection carve-out keeps +// a failed tag fetch from flipping every unrelated control to error. +const degradedReasonTagProtectionPrefix = "tag protection could not be fetched" + // invalidWorkflowDegradedSuffix is the fixed tail of the "could not be // parsed" degraded reason, after the varying file count. It is the // contract between invalidWorkflowDegradedReason (the one writer, used diff --git a/control/explain_test.go b/control/explain_test.go index 64f026ab..cac511f8 100644 --- a/control/explain_test.go +++ b/control/explain_test.go @@ -931,6 +931,23 @@ func TestBestFixSubjectUsesIncludePathForAJobLessFinding(t *testing.T) { } } +// ISSUE-510 is job-less too (a tag pattern is not a job), so its subject +// comes from tagPattern in bestFixSubjectKeys. +func TestBestFixSubjectUsesTagPatternForATagFinding(t *testing.T) { + sit := includeSituation(ir.VisibilityPublic, "build") + f := finding("ISSUE-510", "", map[string]any{"tagPattern": "v*"}) + in := ScoreInputV4{Findings: []opaengine.Finding{f}} + in.Paths = assemblePaths(in.Findings, sit) + current := ComputePlumberScoreV4(in) + fix := ComputeBestFix(in, sit, current) + if fix == nil || fix.Subject != "v*" { + t.Fatalf("want tagPattern as the subject, got %+v", fix) + } + if strings.Contains(fix.Sentence, "(``)") { + t.Errorf("sentence = %q, empty backticks", fix.Sentence) + } +} + // A name rendered in backticks is attacker text on a merge-request // pipeline (the CI configuration is the author's), so code() strips every // backtick and control character (a newline, a carriage return) to a diff --git a/control/gitlab_shaped_providers_test.go b/control/gitlab_shaped_providers_test.go index 3d759886..a38fb8a5 100644 --- a/control/gitlab_shaped_providers_test.go +++ b/control/gitlab_shaped_providers_test.go @@ -28,11 +28,13 @@ var gitLabShapedControls = []string{ // The sets below are snapshots taken on v0.7.14 before the change: what // GitHubControls renders, what reaches users on each provider (applicable // and not benched). The metadata fix must leave all three untouched. +// tagMustBeProtected (#398) was added to both providers since. var wantGitHubControlsOrder = []string{ "containerImageMustNotUseForbiddenTags", "actionsMustBePinnedByCommitSha", "githubActionMustComeFromAuthorizedSources", "branchMustBeProtected", + "tagMustBeProtected", "securityJobsMustNotBeWeakened", "pipelineMustNotUseDockerInDocker", "pipelineMustNotExecuteUnverifiedScripts", @@ -81,6 +83,7 @@ var wantLiveGitLab = []string{ "pipelineMustNotUseUnsafeVariableExpansion", "projectMustHaveSecurityPolicySource", "securityJobsMustNotBeWeakened", + "tagMustBeProtected", } func liveControls(provider string) []string { diff --git a/control/lanes.go b/control/lanes.go index b400b979..9dba9ab4 100644 --- a/control/lanes.go +++ b/control/lanes.go @@ -528,6 +528,26 @@ func (r *AnalysisResult) MarkFailedCollections(entries []ControlEntry) { r.DropNotEvaluableFindings() } +// markTagProtectionGap flags tagMustBeProtected when its collection ran but +// could not read the rules or the tags authoritatively (a token without +// scope, an instance without rulesets): the rule already abstains there, and +// this mark is what makes the control report not evaluated rather than pass, +// in a standalone run too (whose summary reads NotEvaluable, not StatusFor). +// A collection that never ran is left to the lane markers. +func markTagProtectionGap(r *AnalysisResult, entries []ControlEntry) { + tp := r.evaluatedPipeline().TagProtectionOrNil() + if tp == nil || tp.Known { + return + } + for _, e := range entries { + if e.ControlName == controlTagMustBeProtected && e.Skipped { + return + } + } + r.MarkNotEvaluable(controlTagMustBeProtected, ReasonCollectionFailed) + r.DropNotEvaluableFindings() +} + // NotEvaluableReason returns the machine-readable reason this control's own // data lane could not feed it, and whether it was marked at all. // @@ -607,6 +627,11 @@ var controlsIndependentOfMergedConfig = map[string]bool{ "mergeRequestSettingsMustBeCompliant": true, // Reads the project's linked security policy project over GraphQL. "projectMustHaveSecurityPolicySource": true, + // Reads the provider's tag protection rules and tag names. It also + // reads the pipeline's tag triggers, but only for severity and to put + // an untagged pattern in use: without them a finding can only be + // understated or hidden, never invented. + "tagMustBeProtected": true, } // snapshotLaneControls maps each platform snapshot lane identifier to the @@ -706,8 +731,11 @@ func laneUnusableReason(run *platform.RunContext, lane string) string { // exist, so in platform mode there is nothing they could honestly evaluate // against and they must say so rather than pass. // -// It is EMPTY today, and that is the point of keeping it. Its two entries -// were projectMustHaveSecurityPolicySource and +// tagMustBeProtected is here (#398): the snapshot has no protected_tags or +// tags lane yet, and a CI job token cannot read them itself. +// +// It was EMPTY before that, and that is the point of keeping it. Its two +// earlier entries were projectMustHaveSecurityPolicySource and // mergeRequestSettingsMustBeCompliant, written off on the strength of a // contract that had moved on: the platform has served // security_policy_project and project_details since 2026-08-27, and the @@ -725,7 +753,9 @@ func laneUnusableReason(run *platform.RunContext, lane string) string { // ReasonLaneNotServed, for the same reason - the data was never on offer. // Whatever is added, check first that the contract has not already grown // the lane. -var controlsWithNoPlatformLane = map[string]string{} +var controlsWithNoPlatformLane = map[string]string{ + controlTagMustBeProtected: ReasonLaneNotServed, +} // MarkDegradedSnapshotLanes flags the controls whose platform snapshot lane // failed collection, plus the controls the snapshot has no lane for at all. @@ -897,6 +927,8 @@ func ReEvaluateForConfig( entries = GitHubControls(pc) } MarkUnconfiguredControls(&scopedResult, entries, pc, provider) + // The run marked a failed tag read only against the local config. + markTagProtectionGap(&scopedResult, entries) // Every workflow file invalid: this policy's own workflow controls had // nothing parsed to judge either (review of PR 560). if provider == configuration.ProviderGitHub { diff --git a/control/mrcomment.go b/control/mrcomment.go index 52c720dc..eff6a715 100644 --- a/control/mrcomment.go +++ b/control/mrcomment.go @@ -654,6 +654,7 @@ var mrCommentControlOrder = []struct { {"containerImageMustNotUseForbiddenTags", "Container images must not use forbidden reference"}, {"containerImageMustComeFromAuthorizedSources", "Container images must come from authorized sources"}, {"branchMustBeProtected", "Branch must be protected"}, + {"tagMustBeProtected", "Tag must be protected"}, {"projectMustHaveSecurityPolicySource", "Project must have a security policy source"}, {"mergeRequestApprovalRulesMustRequireMinimumApprovals", "MR approval rules must require a minimum number of approvals"}, {"mergeRequestApprovalRulesMustCoverAllProtectedBranches", "MR approval rules must cover all protected branches"}, diff --git a/control/phrases.go b/control/phrases.go index 93e3472d..6a4d2a91 100644 --- a/control/phrases.go +++ b/control/phrases.go @@ -1249,6 +1249,7 @@ var findingFixes = map[ErrorCode]string{ "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", diff --git a/control/platform_call_inventory_test.go b/control/platform_call_inventory_test.go index 2dd8d8b0..03d1673b 100644 --- a/control/platform_call_inventory_test.go +++ b/control/platform_call_inventory_test.go @@ -48,6 +48,19 @@ type gitlabRecorder struct { // than answer, which is what a token that can read this project but not // the include's SOURCE project produces. failRefProbes bool + // tags and protectedTags are the JSON bodies of the tag listing and the + // protected tags listing. Empty serves `[]`, which leaves no tag + // pattern in use. + tags string + protectedTags string +} + +// jsonOrEmptyList returns body, or `[]` when it is empty. +func jsonOrEmptyList(body string) []byte { + if body == "" { + return []byte(`[]`) + } + return []byte(body) } // A ledger has to name ENDPOINTS, not URLs, or the same run against a @@ -139,7 +152,7 @@ func (g *gitlabRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { case strings.HasSuffix(path, "/repository/branches"): _, _ = w.Write([]byte(`[{"name":"main"}]`)) case strings.HasSuffix(path, "/repository/tags"): - _, _ = w.Write([]byte(`[]`)) + _, _ = w.Write(jsonOrEmptyList(g.tags)) case strings.Contains(path, "/repository/tags/"), strings.Contains(path, "/repository/branches/"): if g.failRefProbes { // NOT a 404. A 404 means "not that kind of ref", which is an @@ -156,6 +169,8 @@ func (g *gitlabRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"message":"404 Not Found"}`)) case strings.HasSuffix(path, "/protected_branches"): _, _ = w.Write([]byte(`[]`)) + case strings.HasSuffix(path, "/protected_tags"): + _, _ = w.Write(jsonOrEmptyList(g.protectedTags)) case strings.HasSuffix(path, "/approval_rules"): _, _ = w.Write([]byte(`[]`)) case strings.HasSuffix(path, "/approvals"): @@ -261,6 +276,8 @@ gitlab: enabled: true projectMustHaveSecurityPolicySource: enabled: true + tagMustBeProtected: + enabled: true containerImageMustNotUseForbiddenTags: enabled: true tags: [latest] @@ -504,7 +521,9 @@ func TestGitLabCallInventory(t *testing.T) { "1x GET /api/v4/projects/:id/approval_rules", "1x GET /api/v4/projects/:id/approvals", "1x GET /api/v4/projects/:id/protected_branches", + "1x GET /api/v4/projects/:id/protected_tags", "1x GET /api/v4/projects/:id/repository/branches", + "1x GET /api/v4/projects/:id/repository/tags", // Two single-branch reads: the head sha of the analysed ref, and the // image collection asking whether that ref is protected, which // decides if a protected variable's value may expand a placeholder. @@ -582,7 +601,7 @@ func TestPlatformModeRemovesMostGitLabRequests(t *testing.T) { standalone := totalRequests(runInventory(t, false)) platformRun := totalRequests(runInventory(t, true)) - const wantStandaloneTotal = 18 + const wantStandaloneTotal = 20 const wantPlatformTotal = 3 if standalone != wantStandaloneTotal || platformRun != wantPlatformTotal { @@ -1384,6 +1403,14 @@ func TestObservationsReachTheSameVerdictAsProbing(t *testing.T) { probedFindings, probedGaps := verdicts(false) observedFindings, observedGaps := verdicts(true) + // The one gap that differs by design, and not about includes: the + // snapshot carries no tag lane, so platform mode never reads tag + // protection and the control says so (controlsWithNoPlatformLane). + if got := observedGaps[controlTagMustBeProtected]; got != ReasonLaneNotServed { + t.Errorf("platform mode: %s = %q, want %q", controlTagMustBeProtected, got, ReasonLaneNotServed) + } + delete(observedGaps, controlTagMustBeProtected) + if !maps.Equal(probedFindings, observedFindings) { t.Errorf("findings differ:\n probed: %v\n observed: %v", probedFindings, observedFindings) } diff --git a/control/policy_failure_gitlab_test.go b/control/policy_failure_gitlab_test.go index 4c301a03..ef42b556 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, result) + runRegoEngine(logrus.NewEntry(logrus.New()), conf, project, 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/roles_test.go b/control/roles_test.go index 0f521f4c..d8de8db6 100644 --- a/control/roles_test.go +++ b/control/roles_test.go @@ -38,6 +38,7 @@ func TestSpecAnchoredRoles(t *testing.T) { "ISSUE-415": {RoleHygiene, ""}, "ISSUE-802": {RoleEntry, EntryPRTarget}, "ISSUE-501": {RoleGate, ""}, + "ISSUE-510": {RoleGate, ""}, "ISSUE-505": {RoleGate, ""}, "ISSUE-305": {RoleGate, ""}, "ISSUE-704": {RoleGate, ""}, diff --git a/control/status.go b/control/status.go index 780b1b38..958307f4 100644 --- a/control/status.go +++ b/control/status.go @@ -43,6 +43,12 @@ func degradedReasonIsSecurityPolicy(reason string) bool { return strings.HasPrefix(reason, degradedReasonSecurityPolicyPrefix) } +// degradedReasonIsTagProtection classifies a DegradedReasons entry as the +// tag protection fetch failure, so it taints only tagMustBeProtected. +func degradedReasonIsTagProtection(reason string) bool { + return strings.HasPrefix(reason, degradedReasonTagProtectionPrefix) +} + // StatusFor derives a control's evaluation status for a run. // // Order matters: findings trump degradation — when a control found real @@ -185,6 +191,22 @@ func StatusFor(e ControlEntry, result *AnalysisResult, findingCount int) string } return StatusError } + if e.ControlName == controlTagMustBeProtected { + // Reached only with zero findings. Like the branch control it reads + // the provider's API, not the CI file, so CiMissing / CiValid do not + // apply. A failed fetch, or rules and tags this token could not read + // (Known false), or no collection at all (platform mode on GitLab) + // means the control never truly evaluated. + for _, r := range result.DegradedReasons { + if degradedReasonIsTagProtection(r) { + return StatusError + } + } + if tp := result.evaluatedPipeline().TagProtectionOrNil(); tp == nil || !tp.Known { + return StatusError + } + return StatusPassed + } if result.CiMissing || !result.CiValid { return StatusError } @@ -195,7 +217,7 @@ func StatusFor(e ControlEntry, result *AnalysisResult, findingCount int) string } continue } - if !degradedReasonIsBranchProtection(r) && !degradedReasonIsVariables(r) && !degradedReasonIsSecurityPolicy(r) && !degradedReasonIsPolicyFailure(r) { + if !degradedReasonIsBranchProtection(r) && !degradedReasonIsVariables(r) && !degradedReasonIsSecurityPolicy(r) && !degradedReasonIsTagProtection(r) && !degradedReasonIsPolicyFailure(r) { return StatusError } } diff --git a/control/tag_collection_test.go b/control/tag_collection_test.go new file mode 100644 index 00000000..d26ea04a --- /dev/null +++ b/control/tag_collection_test.go @@ -0,0 +1,361 @@ +package control + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/sirupsen/logrus" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/gitlab" + opaengine "github.com/getplumber/plumber/internal/engine/opa" + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/internal/platform" +) + +// tagControlOn enables tagMustBeProtected on one provider; an absent +// control block collects nothing. +func tagControlOn(provider string) *configuration.PlumberConfig { + on := true + pc := &configuration.PlumberConfig{Version: "2.0", GitLab: &configuration.ProviderConfig{}, GitHub: &configuration.ProviderConfig{}} + c := &configuration.TagProtectionControlConfig{Enabled: &on} + if provider == configuration.ProviderGitLab { + pc.GitLab.Controls.TagMustBeProtected = c + } else { + pc.GitHub.Controls.TagMustBeProtected = c + } + return pc +} + +func hasTagDegradedReason(r *AnalysisResult) bool { + for _, reason := range r.DegradedReasons { + if strings.HasPrefix(reason, degradedReasonTagProtectionPrefix) { + return true + } + } + return false +} + +// The GitLab tag collection splits its failures like the other GitLab +// collectors: a network failure degrades the run, a permission failure +// only leaves tagMustBeProtected not evaluated. Run against the real +// collector so the error classification is tested end to end. +func TestCollectGitLabTagProtection(t *testing.T) { + l := logrus.NewEntry(logrus.New()) + var hits atomic.Int32 + server := func(protectedStatus int) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + if strings.HasSuffix(r.URL.Path, "/protected_tags") && protectedStatus != http.StatusOK { + w.WriteHeader(protectedStatus) + return + } + _, _ = w.Write([]byte(`[]`)) + })) + } + conf := func(url string) *configuration.Configuration { + return &configuration.Configuration{ + GitlabURL: url, + ProjectPath: "group/project", + HTTPClientTimeout: 5 * time.Second, + PlumberConfig: tagControlOn(configuration.ProviderGitLab), + } + } + // notEvaluable runs the gap marker the way RunAnalysis does once the + // engine has the collection in its pipeline. + notEvaluable := func(data *gitlab.GitlabTagProtectionData) (string, bool) { + r := &AnalysisResult{Pipeline: &ir.NormalizedPipeline{TagProtection: gitlab.BuildTagProtection(data)}} + markTagProtectionGap(r, []ControlEntry{{ControlName: controlTagMustBeProtected}}) + reason, ok := r.NotEvaluable[controlTagMustBeProtected] + return reason, ok + } + + t.Run("network failure degrades the run", func(t *testing.T) { + srv := server(http.StatusOK) + url := srv.URL + srv.Close() // connection refused + + result := &AnalysisResult{} + data := collectGitLabTagProtection(l, conf(url), result) + if data == nil || data.Known { + t.Fatalf("want Known=false, got %+v", data) + } + if !result.DataCollectionDegraded || !hasTagDegradedReason(result) { + t.Fatalf("want the run degraded with a tag reason, got degraded=%v reasons=%v", result.DataCollectionDegraded, result.DegradedReasons) + } + if reason, ok := notEvaluable(data); !ok || reason != ReasonCollectionFailed { + t.Errorf("want not evaluable (%s), got %q, %v", ReasonCollectionFailed, reason, ok) + } + }) + + t.Run("permission failure only leaves the control not evaluated", func(t *testing.T) { + srv := server(http.StatusForbidden) + defer srv.Close() + + result := &AnalysisResult{} + data := collectGitLabTagProtection(l, conf(srv.URL), result) + if data == nil || data.Known { + t.Fatalf("want Known=false, got %+v", data) + } + if result.DataCollectionDegraded { + t.Fatalf("a 403 must not degrade the run, got reasons %v", result.DegradedReasons) + } + if reason, ok := notEvaluable(data); !ok || reason != ReasonCollectionFailed { + t.Errorf("want not evaluable (%s), got %q, %v", ReasonCollectionFailed, reason, ok) + } + }) + + t.Run("a readable project is known", func(t *testing.T) { + srv := server(http.StatusOK) + defer srv.Close() + + result := &AnalysisResult{} + data := collectGitLabTagProtection(l, conf(srv.URL), result) + if data == nil || !data.Known || result.DataCollectionDegraded { + t.Fatalf("want Known data and no degradation, got %+v, degraded=%v", data, result.DataCollectionDegraded) + } + if !result.CollectedLanes[laneGitLabTagProtection] { + t.Error("the tag lane must be marked collected") + } + if _, ok := notEvaluable(data); ok { + t.Error("known data must not be marked not evaluable") + } + }) + + t.Run("a platform run fetches nothing", func(t *testing.T) { + srv := server(http.StatusOK) + defer srv.Close() + hits.Store(0) + + c := conf(srv.URL) + c.PlatformRun = &platform.RunContext{Context: &platform.ProjectContext{}} + result := &AnalysisResult{} + if data := collectGitLabTagProtection(l, c, result); data != nil { + t.Fatalf("want no collection in platform mode, got %+v", data) + } + if hits.Load() != 0 { + t.Errorf("platform mode made %d requests, want 0", hits.Load()) + } + if !result.CollectedLanes[laneGitLabTagProtection] { + t.Error("the lane is still marked: lane_not_served comes from controlsWithNoPlatformLane") + } + }) + + t.Run("a disabled control fetches nothing", func(t *testing.T) { + srv := server(http.StatusOK) + defer srv.Close() + hits.Store(0) + + c := conf(srv.URL) + c.PlumberConfig = &configuration.PlumberConfig{Version: "2.0", GitLab: &configuration.ProviderConfig{}} + result := &AnalysisResult{} + if data := collectGitLabTagProtection(l, c, result); data != nil || hits.Load() != 0 || result.CollectedLanes[laneGitLabTagProtection] { + t.Fatalf("want nothing collected, got data=%+v hits=%d lanes=%v", data, hits.Load(), result.CollectedLanes) + } + }) +} + +// tagFindingPatterns returns the tagPattern of every ISSUE-510 finding. +func tagFindingPatterns(findings []opaengine.Finding) []string { + var out []string + for _, f := range findings { + if f.Code == "ISSUE-510" { + p, _ := f.Data["tagPattern"].(string) + out = append(out, p) + } + } + return out +} + +// The collected GitLab tags reach the policy through RunAnalysis. With +// the default (no namePatterns) every tag needs a protected tag `*`: none, +// or only `v*`, is a finding keyed `*`; `*` is clean. Without the pipeline +// wiring in runRegoEngine the policy reads no tag data and every case +// comes out clean. +func TestRunAnalysis_TagProtectionReachesThePolicy(t *testing.T) { + cases := []struct { + name string + protectedTags string + want []string + }{ + {name: "no protected tag", want: []string{"*"}}, + {name: "a protected v* is not all tags", protectedTags: `[{"name":"v*","create_access_levels":[{"access_level":40}]}]`, want: []string{"*"}}, + {name: "a protected * covers all tags", protectedTags: `[{"name":"*","create_access_levels":[{"access_level":40}]}]`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := &gitlabRecorder{ + sha: "0123456789abcdef0123456789abcdef01234567", + tags: `[{"name":"v1.0.0"}]`, + protectedTags: tc.protectedTags, + } + srv := httptest.NewServer(rec) + defer srv.Close() + + result, err := RunAnalysis(inventoryConf(t, srv.URL)) + if err != nil { + t.Fatalf("analysis failed: %v", err) + } + if got := tagFindingPatterns(result.Findings); strings.Join(got, ",") != strings.Join(tc.want, ",") { + t.Fatalf("ISSUE-510 patterns = %v, want %v", got, tc.want) + } + }) + } +} + +// swapTagFetch replaces the GitHub tag protection fetch so the remote +// analysis tests never need network or auth. Restores via t.Cleanup. +func swapTagFetch(t *testing.T, fn func(host, owner, repo string) (*ir.TagProtection, error)) { + t.Helper() + orig := fetchGitHubTagProtection + fetchGitHubTagProtection = fn + t.Cleanup(func() { fetchGitHubTagProtection = orig }) +} + +// On GitHub the tag enrichment fills the pipeline, and its outcome reaches +// the run: an unprotected tag is a finding, a fully protecting ruleset is +// clean, a failed fetch degrades the run, an unreadable answer (no scope, a +// plan without rulesets) leaves tagMustBeProtected not evaluated only. +func TestRunGitHubAnalysisRemote_TagProtection(t *testing.T) { + cases := []struct { + name string + tp *ir.TagProtection + err error + wantKnown bool + wantPatterns []string + wantDegraded bool + wantGap bool + }{ + { + name: "unprotected tags", + tp: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}, + wantKnown: true, + wantPatterns: []string{"~ALL"}, + }, + { + name: "readable repository", + tp: &ir.TagProtection{Known: true, Rules: []ir.TagProtectionRule{{ID: "1", Include: []string{"**"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true}}, Tags: []string{"v1.0.0"}}, + wantKnown: true, + }, + { + name: "fetch failure", + tp: &ir.TagProtection{Known: false}, + err: errors.New("tag rulesets: HTTP 500"), + wantDegraded: true, + wantGap: true, + }, + { + name: "unreadable answer", + tp: &ir.TagProtection{Known: false}, + wantGap: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + swapRemoteScan(t, remoteScanStub) + swapDefaultBranchFetch(t, func(string, string, string) (string, error) { return "main", nil }) + var asked string + swapTagFetch(t, func(host, owner, repo string) (*ir.TagProtection, error) { + asked = owner + "/" + repo + return tc.tp, tc.err + }) + + conf := &configuration.Configuration{PlumberConfig: tagControlOn(configuration.ProviderGitHub)} + result, err := RunGitHubAnalysisRemote(conf, "owner", "repo", "main") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if asked != "owner/repo" { + t.Fatalf("tag fetch asked for %q, want owner/repo", asked) + } + tp := result.GitHubPipeline.TagProtectionOrNil() + if tp == nil || tp.Known != tc.wantKnown { + t.Fatalf("pipeline tag protection = %+v, want Known=%v", tp, tc.wantKnown) + } + if got := tagFindingPatterns(result.Findings); strings.Join(got, ",") != strings.Join(tc.wantPatterns, ",") { + t.Errorf("ISSUE-510 patterns = %v, want %v", got, tc.wantPatterns) + } + if got := result.DataCollectionDegraded && hasTagDegradedReason(result); got != tc.wantDegraded { + t.Errorf("degraded with a tag reason = %v, want %v (reasons %v)", got, tc.wantDegraded, result.DegradedReasons) + } + reason, gap := result.NotEvaluable[controlTagMustBeProtected] + if gap != tc.wantGap || (gap && reason != ReasonCollectionFailed) { + t.Errorf("not evaluable = %v (%q), want %v (%s)", gap, reason, tc.wantGap, ReasonCollectionFailed) + } + }) + } +} + +// The local GitHub path (RunGitHubAnalysis, a checkout on disk) runs its +// own copy of the tag enrichment, degrade and gap wiring: an unprotected +// tag is a finding, a failed fetch degrades the run, an unreadable answer +// only leaves tagMustBeProtected not evaluated. +func TestRunGitHubAnalysis_TagProtection(t *testing.T) { + cases := []struct { + name string + tp *ir.TagProtection + err error + wantPatterns []string + wantDegraded bool + wantGap bool + }{ + { + name: "unprotected tags", + tp: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}, + wantPatterns: []string{"~ALL"}, + }, + { + name: "fetch failure", + tp: &ir.TagProtection{Known: false}, + err: errors.New("tag rulesets: HTTP 500"), + wantDegraded: true, + wantGap: true, + }, + { + name: "unreadable answer", + tp: &ir.TagProtection{Known: false}, + wantGap: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var asked string + swapTagFetch(t, func(host, owner, repo string) (*ir.TagProtection, error) { + asked = owner + "/" + repo + return tc.tp, tc.err + }) + + conf := &configuration.Configuration{ + ProjectPath: "owner/repo", + Branch: "main", + GitRepoRoot: writeMinimalGitHubWorkflowRow62(t), + PlumberConfig: tagControlOn(configuration.ProviderGitHub), + } + result, err := RunGitHubAnalysis(conf) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if asked != "owner/repo" { + t.Fatalf("tag fetch asked for %q, want owner/repo", asked) + } + if got := tagFindingPatterns(result.Findings); strings.Join(got, ",") != strings.Join(tc.wantPatterns, ",") { + t.Errorf("ISSUE-510 patterns = %v, want %v", got, tc.wantPatterns) + } + if tp := result.GitHubPipeline.TagProtectionOrNil(); tp == nil || tp.Known != tc.tp.Known { + t.Errorf("pipeline tag protection = %+v, want Known=%v", tp, tc.tp.Known) + } + if got := result.DataCollectionDegraded && hasTagDegradedReason(result); got != tc.wantDegraded { + t.Errorf("degraded with a tag reason = %v, want %v (reasons %v)", got, tc.wantDegraded, result.DegradedReasons) + } + reason, gap := result.NotEvaluable[controlTagMustBeProtected] + if gap != tc.wantGap || (gap && reason != ReasonCollectionFailed) { + t.Errorf("not evaluable = %v (%q), want %v (%s)", gap, reason, tc.wantGap, ReasonCollectionFailed) + } + }) + } +} diff --git a/control/tag_protection_test.go b/control/tag_protection_test.go new file mode 100644 index 00000000..b19a78cc --- /dev/null +++ b/control/tag_protection_test.go @@ -0,0 +1,122 @@ +package control + +import ( + "testing" + + "github.com/getplumber/plumber/configuration" + opaengine "github.com/getplumber/plumber/internal/engine/opa" + "github.com/getplumber/plumber/internal/ir" +) + +// tagMustBeProtected (ISSUE-510) reads the provider's API, never the CI +// file: it passes only on rules and tags read authoritatively, errors on +// its own fetch failure or an unreadable answer, and its degraded reason +// never taints the CI-file controls. +func TestStatusFor_TagMustBeProtected(t *testing.T) { + tag := ControlEntry{ControlName: controlTagMustBeProtected} + content := ControlEntry{ControlName: "actionsMustBePinnedByCommitSha"} + known := &ir.NormalizedPipeline{TagProtection: &ir.TagProtection{Known: true}} + unknown := &ir.NormalizedPipeline{TagProtection: &ir.TagProtection{Known: false}} + tagDegraded := []string{degradedReasonTagProtectionPrefix + " (network or timeout)"} + + cases := []struct { + name string + entry ControlEntry + result *AnalysisResult + findings int + want string + }{ + {"known data, no findings: passed", tag, &AnalysisResult{CiValid: true, GitHubPipeline: known}, 0, StatusPassed}, + {"known data passes with no CI config at all", tag, &AnalysisResult{CiMissing: true, Pipeline: known}, 0, StatusPassed}, + {"findings mean failed", tag, &AnalysisResult{CiValid: true, GitHubPipeline: known}, 1, StatusFailed}, + {"unreadable rules or tags: error", tag, &AnalysisResult{CiValid: true, GitHubPipeline: unknown}, 0, StatusError}, + {"collection never ran (platform mode on GitLab): error", tag, &AnalysisResult{CiValid: true, Pipeline: &ir.NormalizedPipeline{}}, 0, StatusError}, + {"own fetch failure: error", tag, &AnalysisResult{CiValid: true, GitHubPipeline: unknown, DegradedReasons: tagDegraded}, 0, StatusError}, + {"tag degradation does not taint content controls", content, &AnalysisResult{CiValid: true, DegradedReasons: tagDegraded}, 0, StatusPassed}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := StatusFor(tc.entry, tc.result, tc.findings); got != tc.want { + t.Errorf("StatusFor = %q, want %q", got, tc.want) + } + }) + } +} + +// A collection that ran but could not read the rules or the tags marks the +// control not evaluated (what a standalone summary reads) and drops its +// findings; known data, no collection, or a skipped control are left alone. +func TestMarkTagProtectionGap(t *testing.T) { + finding := opaengine.Finding{Code: "ISSUE-510"} + cases := []struct { + name string + pipeline *ir.NormalizedPipeline + skipped bool + want bool + }{ + {"unknown data is marked", &ir.NormalizedPipeline{TagProtection: &ir.TagProtection{Known: false}}, false, true}, + {"known data is not marked", &ir.NormalizedPipeline{TagProtection: &ir.TagProtection{Known: true}}, false, false}, + {"no collection is left to the lane markers", &ir.NormalizedPipeline{}, false, false}, + {"a skipped control is not marked", &ir.NormalizedPipeline{TagProtection: &ir.TagProtection{Known: false}}, true, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := &AnalysisResult{GitHubPipeline: tc.pipeline, Findings: []opaengine.Finding{finding}} + markTagProtectionGap(r, []ControlEntry{{ControlName: controlTagMustBeProtected, Skipped: tc.skipped}}) + reason, marked := r.NotEvaluable[controlTagMustBeProtected] + if marked != tc.want { + t.Fatalf("marked = %v (%q), want %v", marked, reason, tc.want) + } + if marked && (reason != ReasonCollectionFailed || len(r.Findings) != 0) { + t.Errorf("want reason %q and the findings dropped, got %q and %d findings", ReasonCollectionFailed, reason, len(r.Findings)) + } + }) + } +} + +// The GitHub tag lane runs when some collecting configuration enables the +// control and the project path names a repository, and never otherwise. +func TestTagLaneCollected(t *testing.T) { + on, off := true, false + conf := func(enabled *bool) *configuration.Configuration { + pc := &configuration.PlumberConfig{Version: "2.0", GitHub: &configuration.ProviderConfig{}} + if enabled != nil { + pc.GitHub.Controls.TagMustBeProtected = &configuration.TagProtectionControlConfig{Enabled: enabled} + } + return &configuration.Configuration{PlumberConfig: pc} + } + if !tagLaneCollected(conf(&on), "acme/app") { + t.Error("enabled control on an addressable repo must collect") + } + if tagLaneCollected(conf(&off), "acme/app") { + t.Error("disabled control must not collect") + } + if tagLaneCollected(conf(nil), "acme/app") { + t.Error("absent control must not collect") + } + if tagLaneCollected(conf(&on), "not-a-repo") { + t.Error("an unaddressable project path must not collect") + } + if tagLaneCollected(nil, "acme/app") { + t.Error("nil configuration must not collect") + } +} + +// The control's engine config carries the effective patterns (an empty +// list when unset, never null) and the creation requirement. +func TestBuildEngineConfig_TagMustBeProtected(t *testing.T) { + off := false + cfg := buildEngineConfig(&configuration.ControlsConfig{ + TagMustBeProtected: &configuration.TagProtectionControlConfig{RequireCreationRestricted: &off}, + }, "") + entry, ok := cfg["tagMustBeProtected"].(map[string]any) + if !ok { + t.Fatalf("tagMustBeProtected missing from engine config: %v", cfg) + } + if p, ok := entry["namePatterns"].([]string); !ok || p == nil || len(p) != 0 { + t.Errorf("namePatterns = %#v, want []string{}", entry["namePatterns"]) + } + if entry["requireCreationRestricted"] != false { + t.Errorf("requireCreationRestricted = %v, want false", entry["requireCreationRestricted"]) + } +} diff --git a/control/task.go b/control/task.go index 28a75701..6d2223d9 100644 --- a/control/task.go +++ b/control/task.go @@ -156,6 +156,25 @@ func mrSettingsPremiumFieldsNeedingUpgrade(conf *configuration.Configuration, pr const controlSecurityPolicy = "projectMustHaveSecurityPolicySource" +// controlTagMustBeProtected is referenced directly to decide whether to +// collect the tag protection rules and tag names (ISSUE-510) before +// invoking the Rego engine. The collection reads no control field, so a +// plain gate is enough: there is no per-policy scope to merge. +const controlTagMustBeProtected = "tagMustBeProtected" + +// tagProtectionControlEnabledFor returns the gate reporting whether +// tagMustBeProtected is active on provider for a configuration, for +// anyCollectionConfig. +func tagProtectionControlEnabledFor(provider string) func(*configuration.Configuration) bool { + return func(conf *configuration.Configuration) bool { + if conf == nil || conf.PlumberConfig == nil { + return false + } + c := conf.PlumberConfig.ControlsFor(provider).TagMustBeProtected + return c != nil && c.IsEnabled() && shouldRunControl(controlTagMustBeProtected, conf) + } +} + // securityPolicyControlEnabled reports whether the security-policy-project // linkage control (ISSUE-601) is active for this run. Its linkage is read by // its own GraphQL collection, independent of the REST protection endpoints, so @@ -346,6 +365,31 @@ func applyGitLabRegistryHost(pipeline *ir.NormalizedPipeline, project *gitlab.Pr } } +// collectGitLabTagProtection reads the tag protection for +// tagMustBeProtected when its lane is collected and the run is not a +// platform run. nil means not fetched. A failed read returns Known=false: +// a network failure also degrades the run, a permission failure only +// leaves the control not evaluated (markTagProtectionGap). +func collectGitLabTagProtection(l *logrus.Entry, conf *configuration.Configuration, result *AnalysisResult) *gitlab.GitlabTagProtectionData { + if !anyCollectionConfig(conf, tagProtectionControlEnabledFor(configuration.ProviderGitLab)) { + return nil + } + result.markLaneCollected(laneGitLabTagProtection) + if conf.PlatformRun.Engaged() { + return nil + } + tagData, err := gitlab.CollectGitlabTagProtection(conf.ProjectPath, conf.GitlabToken, conf) + if err != nil { + if isNetworkError(err) { + // Same split as the other collectors: a network failure degrades + // the run, a permission failure leaves the control not evaluated. + markDegraded(result, degradedReasonTagProtectionPrefix+" (network or timeout)") + } + l.WithError(err).Warn("Tag protection could not be read; tagMustBeProtected will report not evaluated") + } + return tagData +} + // runRegoEngine invokes the experimental Rego/OPA rule engine on the // GitLab collector outputs and returns the aggregated findings. The // legacy Go controls always run and remain authoritative until parity @@ -361,6 +405,7 @@ func runRegoEngine( protectionData *gitlab.GitlabProtectionAnalysisData, variablesData *gitlab.GitlabVariablesAnalysisData, securityPolicyData *gitlab.SecurityPolicyData, + tagData *gitlab.GitlabTagProtectionData, result *AnalysisResult, ) []opaengine.Finding { pipeline := gitlab.ToNormalizedPipeline( @@ -375,6 +420,7 @@ func runRegoEngine( ) applyGitLabVisibility(pipeline, project) applyGitLabRegistryHost(pipeline, project, conf.GitlabURL) + pipeline.TagProtection = gitlab.BuildTagProtection(tagData) // 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. @@ -596,6 +642,13 @@ func buildEngineConfig(controls *configuration.ControlsConfig, gitlabURL string) cfg["branchMustBeProtected"] = entry } + if c := controls.TagMustBeProtected; c != nil { + cfg["tagMustBeProtected"] = map[string]any{ + "namePatterns": c.EffectiveNamePatterns(), + "requireCreationRestricted": c.IsCreationRestrictionRequired(), + } + } + if c := controls.MergeRequestApprovalRulesMustRequireMinimumApprovals; c != nil { entry := map[string]any{} if c.MinimumRequiredApprovals != nil { @@ -1251,10 +1304,19 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { } } + // Tag protection (ISSUE-510) is read on its own, outside the protection + // collection, for the same reason as the security-policy linkage: a + // failure there must not cost the branch and approval controls their + // data, nor theirs this one. The platform snapshot carries no tag lane + // yet, so platform mode never fetches it (a CI job token holds no rights + // to it either): the control reports lane_not_served through + // controlsWithNoPlatformLane instead. + tagData := collectGitLabTagProtection(l, conf, result) + // 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, result) + result.Findings = runRegoEngine(l, conf, project, pipelineOriginData, pipelineImageData, protectionData, variablesData, securityPolicyData, tagData, result) 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 @@ -1290,6 +1352,7 @@ func RunAnalysis(conf *configuration.Configuration) (*AnalysisResult, error) { // Likewise unconditional: these are checks this run makes itself, and a // standalone run that could not complete one was reporting a pass on it. MarkOwnCollectionGaps(result, GitLabControls(conf.PlumberConfig)) + markTagProtectionGap(result, GitLabControls(conf.PlumberConfig)) markPlatformLaneGaps(result, conf) diff --git a/control/task_github.go b/control/task_github.go index c38c65b3..9b17ae2a 100644 --- a/control/task_github.go +++ b/control/task_github.go @@ -26,6 +26,10 @@ var fetchGitHubDefaultBranch = func(host, owner, repo string) (string, error) { // which otherwise needs network and auth. var scanGitHubWorkflowsRemote = githubpkg.ScanGitHubWorkflowsRemote +// fetchGitHubTagProtection is a test seam over the tag rulesets and tags +// fetch, which otherwise needs network and auth. +var fetchGitHubTagProtection = githubpkg.FetchGitHubTagProtection + // fetchGitHubEnvironments is a test seam over the environments lookup. // The default honors PLUMBER_DISABLE_GITHUB_API (same contract as // fetchGitHubDefaultBranch above) so offline test suites never hit the @@ -323,6 +327,30 @@ func eligibleDefaultTokenWorkflow(pipeline *ir.NormalizedPipeline, workflowPath return matched } +// enrichGitHubTags fills pipeline.TagProtection for tagMustBeProtected +// (ISSUE-510) when tagLaneCollected says this run collects it. A token +// that cannot read the rulesets or the tags leaves TagProtection with +// Known=false, which the rule abstains on and markTagProtectionGap turns +// into "not evaluated". Returns true when the fetch failed outright +// (network, 5xx, rate limit), so the caller degrades the run instead of +// letting an empty answer pass (#220). +func enrichGitHubTags(l *logrus.Entry, pipeline *ir.NormalizedPipeline, host string, conf *configuration.Configuration, projectPath string) (fetchFailed bool) { + if pipeline == nil || !tagLaneCollected(conf, projectPath) { + return false + } + owner, repo, _ := gitHubOwnerRepo(projectPath) + tp, err := fetchGitHubTagProtection(host, owner, repo) + pipeline.TagProtection = tp + if err != nil { + l.WithError(err).Warn("GitHub tag protection fetch failed; tagMustBeProtected will report not evaluated") + return true + } + if tp != nil && !tp.Known { + l.Info("GitHub tag rulesets or tags are not readable with this token; tagMustBeProtected will report not evaluated") + } + return false +} + // enrichGitHubBranches populates pipeline.Branches via the GitHub // REST API when the user has enabled the branchMustBeProtected // control AND that control is currently shipping (not benched) on @@ -533,6 +561,7 @@ func RunGitHubAnalysis(conf *configuration.Configuration) (*AnalysisResult, erro } branchFetchFailed = enrichGitHubBranches(l, pipeline, conf.GithubAPIHost, branchScope, conf.ProjectPath, onProgress) } + tagFetchFailed := enrichGitHubTags(l, pipeline, conf.GithubAPIHost, conf, conf.ProjectPath) // After every enrichment lane above (environments, workflow states, // branches) and before the situation facts are evaluated below: a job @@ -580,6 +609,10 @@ func RunGitHubAnalysis(conf *configuration.Configuration) (*AnalysisResult, erro invalidInactive = len(pipeline.InvalidWorkflows) } applyGitHubDegraded(result, 0, invalidInactive, branchFetchFailed) + if tagFetchFailed { + markDegraded(result, degradedReasonTagProtectionPrefix+"; tag controls were not evaluated") + } + markTagProtectionGap(result, GitHubControls(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 @@ -683,6 +716,7 @@ func RunGitHubAnalysisRemote(conf *configuration.Configuration, owner, repo, ref } branchFetchFailed = enrichGitHubBranches(l, pipeline, conf.GithubAPIHost, branchScope, owner+"/"+repo, onProgress) } + tagFetchFailed := enrichGitHubTags(l, pipeline, conf.GithubAPIHost, conf, owner+"/"+repo) // Same ordering as the local path: after every enrichment lane, before // the situation facts are evaluated below. @@ -725,6 +759,10 @@ func RunGitHubAnalysisRemote(conf *configuration.Configuration, owner, repo, ref invalidInactive = len(pipeline.InvalidWorkflows) } applyGitHubDegraded(result, len(partial), invalidInactive, branchFetchFailed) + if tagFetchFailed { + markDegraded(result, degradedReasonTagProtectionPrefix+"; tag controls were not evaluated") + } + markTagProtectionGap(result, GitHubControls(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/testdata/corpus/plumber-own-ci/plumber.yaml b/control/testdata/corpus/plumber-own-ci/plumber.yaml index eedfa9cb..5a45219e 100644 --- a/control/testdata/corpus/plumber-own-ci/plumber.yaml +++ b/control/testdata/corpus/plumber-own-ci/plumber.yaml @@ -192,6 +192,34 @@ gitlab: # Minimum access level required to push (0=No one, 30=Developer, 40=Maintainer) minPushAccessLevel: 40 # =========================================== + # Tag must be protected + # =========================================== + # Checks that tags are protected, so nobody with push access can move, + # delete or create a release tag (Settings > Repository > Protected + # tags). A protected tag already blocks updates and deletions; creation + # must be limited to Maintainers or a narrower set. + # + # By default (no namePatterns) every tag must be covered by one + # protected tag `*`, the recommended setup. List patterns to check + # those instead, each on its own. + # + # Only checked once the project has a tag or a job runs on tags, so + # projects that never tag stay quiet. A job that runs on tag pipelines + # (only: tags, or a rule on $CI_COMMIT_TAG) raises the finding to + # critical. + # + # Needs a token with read_api to list protected tags and tags; without + # one the control reports "not evaluated", never a false positive. Not + # evaluated in platform mode yet (the snapshot has no tag lane). + tagMustBeProtected: + # Set to false to disable this control + enabled: true + # Tag name patterns that must be protected (supports wildcards). + # Empty: a protected tag `*` must cover all tags. + namePatterns: [] + # Also require tag creation to be restricted + requireCreationRestricted: true + # =========================================== # MR approval rules must require a minimum number of approvals # =========================================== # Flags approval rules covering all protected branches that require fewer @@ -903,6 +931,31 @@ github: allowForcePush: false codeOwnerApprovalRequired: false + # =========================================== + # Tag must be protected (project governance) + # =========================================== + # Reads the repository's tag rulesets (its own and the organization's) + # and its tags. Tags must be covered by active rulesets that restrict + # updates, deletions and creations. + # + # By default (no namePatterns) the rulesets must target All tags + # (~ALL) with no exclusion, the recommended setup. List patterns to + # check those instead, each on its own. Workflow tag triggers never add + # a pattern: they make the finding critical. + # + # Only checked once the repository has a tag or a workflow runs on + # tags, so repositories that never tag stay quiet. + # + # Needs only "Metadata: read" (every GITHUB_TOKEN has it): listing + # rulesets and tags needs no admin rights. Without access the control + # reports "not evaluated", never a false positive. + tagMustBeProtected: + enabled: true + # Tag name patterns that must be protected (supports wildcards). + # Empty: rulesets on All tags (~ALL) must cover every tag. + namePatterns: [] + requireCreationRestricted: true + # ============================================================================ # Workflows must include required actions # ============================================================================ diff --git a/defaultConfig/.plumber.yaml b/defaultConfig/.plumber.yaml index 32f6e710..65877aa2 100644 --- a/defaultConfig/.plumber.yaml +++ b/defaultConfig/.plumber.yaml @@ -278,6 +278,34 @@ gitlab: # Minimum access level required to push (0=No one, 30=Developer, 40=Maintainer) minPushAccessLevel: 40 # =========================================== + # Tag must be protected + # =========================================== + # Checks that tags are protected, so nobody with push access can move, + # delete or create a release tag (Settings > Repository > Protected + # tags). A protected tag already blocks updates and deletions; creation + # must be limited to Maintainers or a narrower set. + # + # By default (no namePatterns) every tag must be covered by one + # protected tag `*`, the recommended setup. List patterns to check + # those instead, each on its own. + # + # Only checked once the project has a tag or a job runs on tags, so + # projects that never tag stay quiet. A job that runs on tag pipelines + # (only: tags, or a rule on $CI_COMMIT_TAG) raises the finding to + # critical. + # + # Needs a token with read_api to list protected tags and tags; without + # one the control reports "not evaluated", never a false positive. Not + # evaluated in platform mode yet (the snapshot has no tag lane). + tagMustBeProtected: + # Set to false to disable this control + enabled: true + # Tag name patterns that must be protected (supports wildcards). + # Empty: a protected tag `*` must cover all tags. + namePatterns: [] + # Also require tag creation to be restricted + requireCreationRestricted: true + # =========================================== # MR approval rules must require a minimum number of approvals # =========================================== # Flags GitLab merge-request approval rules that cover all protected @@ -1209,6 +1237,31 @@ github: # code-owner approval on protected branches. codeOwnerApprovalRequired: false + # =========================================== + # Tag must be protected (project governance) + # =========================================== + # Reads the repository's tag rulesets (its own and the organization's) + # and its tags. Tags must be covered by active rulesets that restrict + # updates, deletions and creations. + # + # By default (no namePatterns) the rulesets must target All tags + # (~ALL) with no exclusion, the recommended setup. List patterns to + # check those instead, each on its own. Workflow tag triggers never add + # a pattern: they make the finding critical. + # + # Only checked once the repository has a tag or a workflow runs on + # tags, so repositories that never tag stay quiet. + # + # Needs only "Metadata: read" (every GITHUB_TOKEN has it): listing + # rulesets and tags needs no admin rights. Without access the control + # reports "not evaluated", never a false positive. + tagMustBeProtected: + enabled: true + # Tag name patterns that must be protected (supports wildcards). + # Empty: rulesets on All tags (~ALL) must cover every tag. + namePatterns: [] + requireCreationRestricted: true + # ============================================================================ # Workflows must include required actions # ============================================================================ diff --git a/docs/GITHUB_ISSUES.md b/docs/GITHUB_ISSUES.md index fdf7b031..2c2c072b 100644 --- a/docs/GITHUB_ISSUES.md +++ b/docs/GITHUB_ISSUES.md @@ -72,6 +72,7 @@ reading the upstream docs. | Code | Name | Severity | | :--- | :--- | :--- | | [ISSUE-803](#issue-803--excessive-permissions) | `excessive-permissions` | high | +| [ISSUE-510](#issue-510--tag-unprotected) | `tag-unprotected` | **critical** _(API)_ | ### Workflow hygiene — `6xx` @@ -1854,6 +1855,79 @@ jobs: --- +## ISSUE-510 — `tag-unprotected` + +**Severity:** `critical` (`high` when no workflow runs on a tag push) • **Control:** `tagMustBeProtected` + +Tags are in use but anyone with push access can move, delete or create +them. Tags are what release workflows run on and what consumers pin to, +so a moved tag ships code nobody reviewed under a name everyone trusts: +the tj-actions/changed-files compromise re-pointed existing version tags +to a malicious commit. + +Tags are protected when active tag +[rulesets](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets) +(the repository's own or inherited from the organization) cover them with +**Restrict updates**, **Restrict deletions** and, unless +`requireCreationRestricted: false`, **Restrict creations**. The rules may +come from different rulesets. A ruleset in `evaluate` mode does not +count: it reports, it does not block. + +What must be covered depends on `namePatterns`: + +- **Empty (the default):** all tags. The rulesets must target **All tags** + (`~ALL`) and exclude nothing; a ruleset on `v*` or `*` does not count. + One finding, `tagPattern: "~ALL"`. This is the recommended setup: one + ruleset protects every tag, including the ones nobody thought to list. +- **A list of patterns:** each pattern on its own, one finding per + pattern. A ruleset covers a pattern when it targets the pattern itself + (or all tags) and every existing tag the pattern matches. + +Nothing is checked until tags are in use: the repository has a tag, or a +workflow runs on tags (for a configured pattern, an existing tag matches +it or a workflow triggers on exactly it). Workflow `on.push.tags` +patterns never add a pattern of their own. The finding is critical when +a workflow runs on a matching tag push (`on.push.tags`, +`on.push.tags-ignore`, or `on: release`), high otherwise. + +```yaml +# ❌ before — release workflow on v* tags, no tag ruleset +on: + push: + tags: ["v*"] +jobs: + publish: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + - run: ./publish.sh +``` + +**Fix.** Settings > Rules > Rulesets > New tag ruleset: enforcement +**Active**, target **All tags** (or the configured patterns), enable Restrict creations, +Restrict updates and Restrict deletions, and add the release automation +(a GitHub App or the repository admin role) to the bypass list. + +**Token.** Listing rulesets and tags needs only **Metadata: read** +([fine-grained permissions](https://docs.github.com/en/rest/authentication/permissions-required-for-fine-grained-personal-access-tokens#repository-permissions-for-metadata)), +which every `GITHUB_TOKEN` carries. Without access, or on a GHES version +without rulesets, the control reports "not evaluated", never a false +positive. + +**Config.** + +```yaml +tagMustBeProtected: + enabled: true + # Tag name patterns that must be protected, each on its own. + # Empty (default): rulesets on All tags (~ALL) must cover every tag. + namePatterns: [] + # Also require tag creation to be restricted + requireCreationRestricted: true +``` + +--- + ## ISSUE-422 — `anonymous-definition` **Severity:** `low` • **Control:** `workflowsMustHaveExplicitName` diff --git a/docs/GITLAB_ISSUES.md b/docs/GITLAB_ISSUES.md index 7063ba45..5e251f61 100644 --- a/docs/GITLAB_ISSUES.md +++ b/docs/GITLAB_ISSUES.md @@ -16,6 +16,12 @@ absence from this file does not mean a rule doesn't exist — see | [ISSUE-414](#issue-414--component-authorized-sources) | `component-authorized-sources` | high | | [ISSUE-415](#issue-415--function-authorized-sources) | `function-authorized-sources` | high | +### Access & authorisation — `5xx` + +| Code | Name | Severity | +| :--- | :--- | :--- | +| [ISSUE-510](#issue-510--tag-unprotected) | `tag-unprotected` | **critical** | + ### Run / output conventions - Every finding prints a clickable `↳ at :` — `Ctrl+click` @@ -183,3 +189,59 @@ functionMustComeFromAuthorizedSources: # supported), e.g. registry.example.com/platform-team/* trustedFunctions: [] ``` + +--- + +## ISSUE-510 — `tag-unprotected` + +**Severity:** `critical` (`high` when no job runs on tag pipelines) • **Control:** `tagMustBeProtected` + +Tags are in use but are not covered by a +[protected tag](https://docs.gitlab.com/user/project/protected_tags/), or +the protection lets Developers create them. Anyone allowed to push a tag +can then move a release or forge one, and a tag pipeline publishes it. + +What must be covered depends on `namePatterns`: + +- **Empty (the default):** all tags, through a protected tag `*`. A + protected tag `v*` does not count. One finding, `tagPattern: "*"`. + This is the recommended setup: one rule protects every tag. +- **A list of patterns:** each pattern on its own, one finding per + pattern. + +Nothing is checked until tags are in use: the project has a tag (one +matching the pattern, for a configured pattern), or a job runs on tag +pipelines. The finding is critical when a job runs on tag pipelines +(`only: [tags]`, or a `rules:` entry on `$CI_COMMIT_TAG`), high +otherwise. A protected tag blocks updates and deletions by itself; +creation counts as restricted when it is left to Maintainers (the +default), No one, or named users, groups or deploy keys. + +```yaml +# ❌ before — tag pipeline publishes, v* tags are not protected +publish: + rules: + - if: $CI_COMMIT_TAG + script: + - ./publish.sh +``` + +**Fix.** Settings > Repository > Protected tags: protect `*` (or each +configured pattern) with **Allowed to create** set to Maintainers (or a +narrower set). + +**Token.** `read_api`, to list protected tags and tags. Without it the +control reports "not evaluated", never a false positive. Not evaluated +in platform mode yet: the platform snapshot carries no tag data. + +**Config.** + +```yaml +tagMustBeProtected: + enabled: true + # Tag name patterns that must be protected, each on its own. + # Empty (default): a protected tag `*` must cover every tag. + namePatterns: [] + # Also require tag creation to be restricted + requireCreationRestricted: true +``` diff --git a/finding/identity/declarations.go b/finding/identity/declarations.go index 5e2ecada..58ab5883 100644 --- a/finding/identity/declarations.go +++ b/finding/identity/declarations.go @@ -193,6 +193,8 @@ var declarations = map[string][]string{ "ISSUE-505": {"file", "job", "branchName"}, // MR settings not compliant: singleton finding (one per project); the platform IdOnly was empty, so the identity is the code alone. Deliberate consequence: changing WHICH settings deviate does not re-key the finding. "ISSUE-506": {}, + // Tag pattern not protected: one finding per configured tag pattern, keyed on the pattern; with no pattern configured, one finding keyed on the provider's all-tags target (`~ALL` on GitHub, `*` on GitLab). Which protections are missing is data only, so tightening one of them does not re-key the finding. + "ISSUE-510": {"tagPattern"}, // Security policy project not linked: singleton finding (one per project); the platform IdOnly was empty, so the identity is the code alone. "ISSUE-601": {}, // Workflow has no explicit name: one finding per workflow file, keyed on the file (benched, not yet live: declaration provisional, revisit on unbench). Renumbered from 601 when the security-policy control took 601 (#417). diff --git a/finding/identity/identity_test.go b/finding/identity/identity_test.go index 6ba2b728..3ed75280 100644 --- a/finding/identity/identity_test.go +++ b/finding/identity/identity_test.go @@ -373,6 +373,7 @@ func TestDeclarations_EveryCodeFingerprintIsPinned(t *testing.T) { "ISSUE-504": "b698c0c9440ef0f5", "ISSUE-505": "4e929715c61fcba6", "ISSUE-506": "aa6378b9df051002", + "ISSUE-510": "624e0e1cc44935c6", "ISSUE-601": "3a68700e66069498", "ISSUE-422": "ade0bea017f69d56", "ISSUE-423": "b30503f030b41d3a", diff --git a/github/github_tag_protection.go b/github/github_tag_protection.go new file mode 100644 index 00000000..704dfeab --- /dev/null +++ b/github/github_tag_protection.go @@ -0,0 +1,255 @@ +package github + +import ( + "errors" + "fmt" + "path" + "strconv" + "strings" + + "github.com/cli/go-gh/v2/pkg/api" + + "github.com/getplumber/plumber/internal/ir" +) + +// maxTagListingPages caps the /tags pagination: 10 pages × 100 entries. +// A repository with more tags than that is reported with TagsTruncated, +// which can only hide a finding (a matching tag not seen), never invent +// one. +const maxTagListingPages = 10 + +// remoteRulesetSummary is one entry of the rulesets listing. The listing +// carries no conditions and no rules; those need the per-ruleset call. +type remoteRulesetSummary struct { + ID int64 `json:"id"` + Name string `json:"name"` + Target string `json:"target"` + SourceType string `json:"source_type"` + Enforcement string `json:"enforcement"` +} + +// remoteRuleset is a ruleset as GET /repos/{o}/{r}/rulesets/{id} returns +// it, reduced to what tagMustBeProtected reads. bypass_actors is +// deliberately absent: it needs admin rights, and the control does not +// depend on it. +type remoteRuleset struct { + remoteRulesetSummary + Conditions struct { + RefName *remoteIncludeExclude `json:"ref_name"` + RepositoryName *remoteIncludeExclude `json:"repository_name"` + } `json:"conditions"` + Rules []struct { + Type string `json:"type"` + } `json:"rules"` +} + +type remoteIncludeExclude struct { + Include []string `json:"include"` + Exclude []string `json:"exclude"` +} + +type remoteTag struct { + Name string `json:"name"` +} + +// FetchGitHubTagProtection reads the repository's active tag rulesets +// (its own and those inherited from the organization or enterprise) and +// its existing tag names, for tagMustBeProtected (ISSUE-510). +// +// The legacy tag protection API is not used: GitHub retired it in 2024 +// and migrated its rules to rulesets. +// +// Error contract, the same as the branch protection collector: +// - no auth, or a 401/403/404 on any call (missing scope, a GHES +// version without rulesets, an invisible repo): Known=false and a nil +// error, so the control reports "not evaluated" without degrading the +// run, and never a finding built on missing data. +// - any other failure (network, 5xx, rate limit): Known=false and the +// error, so the caller marks the run degraded. +func FetchGitHubTagProtection(host, owner, repo string) (*ir.TagProtection, error) { + if owner == "" || repo == "" { + return nil, fmt.Errorf("owner and repo are required") + } + unknown := &ir.TagProtection{Known: false} + rest, err := newGitHubRESTClient(host) + if err != nil { + if errors.Is(err, ErrAuthRequired) { + return unknown, nil + } + return unknown, fmt.Errorf("github api client: %w", err) + } + + summaries, ok, err := listTagRulesets(rest, owner, repo) + if err != nil || !ok { + return unknown, err + } + out := &ir.TagProtection{} + for _, s := range summaries { + if s.Enforcement != "active" { + // "evaluate" only reports and "disabled" does nothing: neither + // stops a tag from moving. + continue + } + rs, ok, err := fetchRuleset(rest, owner, repo, s.ID) + if err != nil || !ok { + return unknown, err + } + if !rulesetAppliesToRepo(rs, repo) { + continue + } + out.Rules = append(out.Rules, rulesetToTagRule(rs)) + } + + tags, truncated, ok, err := listTagNames(rest, owner, repo) + if err != nil || !ok { + return unknown, err + } + out.Tags = tags + out.TagsTruncated = truncated + out.Known = true + return out, nil +} + +// listTagRulesets pages GET /repos/{o}/{r}/rulesets for tag rulesets, +// parents included. Returns (nil, false, nil) on 401/403/404, and when the +// listing outruns maxBranchListingPages: a ruleset past the cap could be +// the one protecting a pattern. +func listTagRulesets(rest *api.RESTClient, owner, repo string) ([]remoteRulesetSummary, bool, error) { + const perPage = 100 + var out []remoteRulesetSummary + for page := 1; page <= maxBranchListingPages; page++ { + endpoint := fmt.Sprintf("repos/%s/%s/rulesets?includes_parents=true&targets=tag&per_page=%d&page=%d", owner, repo, perPage, page) + var batch []remoteRulesetSummary + if err := rest.Get(endpoint, &batch); err != nil { + if isUnauthorized(err) || isNotFound(err) { + return nil, false, nil + } + return nil, false, fmt.Errorf("tag rulesets: %w", err) + } + for _, s := range batch { + // Older GHES versions ignore the targets filter. + if s.Target == "tag" { + out = append(out, s) + } + } + if len(batch) < perPage { + return out, true, nil + } + } + return nil, false, nil +} + +// fetchRuleset reads one ruleset's conditions and rules. Returns +// (nil, false, nil) on 401/403/404. +func fetchRuleset(rest *api.RESTClient, owner, repo string, id int64) (*remoteRuleset, bool, error) { + endpoint := fmt.Sprintf("repos/%s/%s/rulesets/%d?includes_parents=true", owner, repo, id) + var rs remoteRuleset + if err := rest.Get(endpoint, &rs); err != nil { + if isUnauthorized(err) || isNotFound(err) { + return nil, false, nil + } + return nil, false, fmt.Errorf("ruleset %d: %w", id, err) + } + return &rs, true, nil +} + +// listTagNames pages GET /repos/{o}/{r}/tags, capped at +// maxTagListingPages. Returns ok=false on 401/403/404. +func listTagNames(rest *api.RESTClient, owner, repo string) (names []string, truncated, ok bool, err error) { + const perPage = 100 + for page := 1; page <= maxTagListingPages; page++ { + endpoint := fmt.Sprintf("repos/%s/%s/tags?per_page=%d&page=%d", owner, repo, perPage, page) + var batch []remoteTag + if err := rest.Get(endpoint, &batch); err != nil { + if isUnauthorized(err) || isNotFound(err) { + return nil, false, false, nil + } + return nil, false, false, fmt.Errorf("tags: %w", err) + } + for _, t := range batch { + names = append(names, t.Name) + } + if len(batch) < perPage { + return names, false, true, nil + } + } + return names, true, true, nil +} + +// rulesetAppliesToRepo honours an organization ruleset's repository_name +// condition. Rulesets targeting repositories by id or by custom property +// are trusted as returned: GitHub only lists a parent ruleset for a +// repository it applies to, and getting this wrong could only hide a +// finding. +func rulesetAppliesToRepo(rs *remoteRuleset, repo string) bool { + c := rs.Conditions.RepositoryName + if c == nil { + return true + } + if len(c.Include) > 0 && !anyRepoPatternMatches(c.Include, repo) { + return false + } + return !anyRepoPatternMatches(c.Exclude, repo) +} + +func anyRepoPatternMatches(patterns []string, repo string) bool { + for _, p := range patterns { + if p == "~ALL" { + return true + } + if ok, err := path.Match(p, repo); err == nil && ok { + return true + } + } + return false +} + +// rulesetToTagRule maps a tag ruleset onto the provider-neutral rule +// tagMustBeProtected reads. +func rulesetToTagRule(rs *remoteRuleset) ir.TagProtectionRule { + rule := ir.TagProtectionRule{ + ID: strconv.FormatInt(rs.ID, 10), + Name: rs.Name, + Source: rulesetSource(rs.SourceType), + } + if c := rs.Conditions.RefName; c != nil { + for _, p := range c.Include { + rule.Include = append(rule.Include, normalizeGitHubTagPattern(p)) + } + for _, p := range c.Exclude { + rule.Exclude = append(rule.Exclude, normalizeGitHubTagPattern(p)) + } + } + for _, r := range rs.Rules { + switch r.Type { + case "update": + rule.BlocksUpdate = true + case "deletion": + rule.BlocksDeletion = true + case "creation": + rule.RestrictsCreation = true + } + } + return rule +} + +func rulesetSource(sourceType string) string { + switch sourceType { + case "Organization": + return ir.TagRuleSourceOrganizationRuleset + case "Enterprise": + return ir.TagRuleSourceEnterpriseRuleset + default: + return ir.TagRuleSourceRepositoryRuleset + } +} + +// normalizeGitHubTagPattern turns a ruleset ref_name pattern into the +// shared glob dialect: refs/tags/ stripped, ~ALL as "**". GitHub's fnmatch +// already stops `*` at a slash, as the dialect does. +func normalizeGitHubTagPattern(p string) string { + if p == "~ALL" { + return "**" + } + return strings.TrimPrefix(p, "refs/tags/") +} diff --git a/github/github_tag_protection_test.go b/github/github_tag_protection_test.go new file mode 100644 index 00000000..90b8a0a5 --- /dev/null +++ b/github/github_tag_protection_test.go @@ -0,0 +1,275 @@ +package github + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strconv" + "strings" + "testing" + + "github.com/getplumber/plumber/internal/ir" +) + +// tagAPI is a fake GitHub serving the rulesets listing, per-ruleset +// details and the tags listing. status overrides the response code per +// path prefix (e.g. "/repos/o/r/rulesets" → 403). +type tagAPI struct { + summaries []map[string]any + details map[int64]map[string]any + tags []string + status map[string]int + hits map[string]int +} + +func (a *tagAPI) server(t *testing.T) *httptest.Server { + t.Helper() + a.hits = map[string]int{} + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p := r.URL.Path + a.hits[p]++ + for prefix, code := range a.status { + if p == prefix { + w.WriteHeader(code) + _, _ = w.Write([]byte(`{"message":"nope"}`)) + return + } + } + w.Header().Set("Content-Type", "application/json") + switch { + case p == "/repos/o/r/rulesets": + if r.URL.Query().Get("includes_parents") != "true" || r.URL.Query().Get("targets") != "tag" { + t.Errorf("rulesets listing query = %q, want includes_parents=true and targets=tag", r.URL.RawQuery) + } + _ = json.NewEncoder(w).Encode(pageOf(r, a.summaries)) + case strings.HasPrefix(p, "/repos/o/r/rulesets/"): + id, _ := strconv.ParseInt(strings.TrimPrefix(p, "/repos/o/r/rulesets/"), 10, 64) + d, ok := a.details[id] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _ = json.NewEncoder(w).Encode(d) + case p == "/repos/o/r/tags": + named := make([]map[string]string, len(a.tags)) + for i, tag := range a.tags { + named[i] = map[string]string{"name": tag} + } + _ = json.NewEncoder(w).Encode(pageOf(r, named)) + default: + t.Errorf("unexpected request %s", p) + w.WriteHeader(http.StatusNotFound) + } + })) +} + +// pageOf serves the page and per_page the request asks for. +func pageOf[T any](r *http.Request, all []T) []T { + page, _ := strconv.Atoi(r.URL.Query().Get("page")) + per, _ := strconv.Atoi(r.URL.Query().Get("per_page")) + start := min((page-1)*per, len(all)) + return all[start:min(start+per, len(all))] +} + +func summary(id int64, enforcement, sourceType string) map[string]any { + return map[string]any{"id": id, "name": fmt.Sprintf("rs-%d", id), "target": "tag", "source_type": sourceType, "enforcement": enforcement} +} + +func detail(id int64, sourceType string, include, exclude []string, rules ...string) map[string]any { + rs := []map[string]any{} + for _, r := range rules { + rs = append(rs, map[string]any{"type": r}) + } + return map[string]any{ + "id": id, "name": fmt.Sprintf("rs-%d", id), "target": "tag", "source_type": sourceType, "enforcement": "active", + "conditions": map[string]any{"ref_name": map[string]any{"include": include, "exclude": exclude}}, + "rules": rs, + } +} + +func TestFetchGitHubTagProtection_MapsActiveRulesetsAndTags(t *testing.T) { + org := detail(2, "Organization", []string{"~ALL"}, nil, "creation") + // An organization ruleset on every repository: GitHub's ~ALL sentinel. + org["conditions"].(map[string]any)["repository_name"] = map[string]any{"include": []string{"~ALL"}, "exclude": []string{}} + otherRepo := detail(4, "Organization", []string{"~ALL"}, nil, "update") + otherRepo["conditions"].(map[string]any)["repository_name"] = map[string]any{"include": []string{"elsewhere"}} + api := &tagAPI{ + summaries: []map[string]any{ + summary(1, "active", "Repository"), + summary(2, "active", "Organization"), + summary(3, "evaluate", "Repository"), + summary(4, "active", "Organization"), + // A branch ruleset an old GHES returns despite targets=tag. + {"id": 5, "target": "branch", "enforcement": "active", "source_type": "Repository"}, + }, + details: map[int64]map[string]any{ + 1: detail(1, "Repository", []string{"refs/tags/v*"}, []string{"refs/tags/v*-rc*"}, "update", "deletion", "non_fast_forward"), + 2: org, + 4: otherRepo, + }, + tags: []string{"v1.0.0", "v0.9.0"}, + } + srv := api.server(t) + defer srv.Close() + swapRESTClient(t, srv) + + got, err := FetchGitHubTagProtection("", "o", "r") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := &ir.TagProtection{ + Known: true, + Rules: []ir.TagProtectionRule{ + {ID: "1", Name: "rs-1", Source: ir.TagRuleSourceRepositoryRuleset, Include: []string{"v*"}, Exclude: []string{"v*-rc*"}, BlocksUpdate: true, BlocksDeletion: true}, + {ID: "2", Name: "rs-2", Source: ir.TagRuleSourceOrganizationRuleset, Include: []string{"**"}, RestrictsCreation: true}, + }, + Tags: []string{"v1.0.0", "v0.9.0"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v\nwant %+v", got, want) + } + if api.hits["/repos/o/r/rulesets/3"] != 0 || api.hits["/repos/o/r/rulesets/5"] != 0 { + t.Error("evaluate-mode and branch rulesets must not be fetched in detail") + } +} + +// No rulesets and no tags is an authoritative answer, not missing data. +func TestFetchGitHubTagProtection_EmptyIsKnown(t *testing.T) { + api := &tagAPI{} + srv := api.server(t) + defer srv.Close() + swapRESTClient(t, srv) + + got, err := FetchGitHubTagProtection("", "o", "r") + if err != nil || got == nil || !got.Known || len(got.Rules) != 0 || len(got.Tags) != 0 { + t.Fatalf("got %+v, %v; want Known with nothing in it", got, err) + } +} + +// Missing scope or a GHES without rulesets: not evaluated, no error, so +// the run is not degraded and nothing is flagged. +func TestFetchGitHubTagProtection_ForbiddenOrMissingIsUnknown(t *testing.T) { + cases := map[string]map[string]int{ + "rulesets 403": {"/repos/o/r/rulesets": http.StatusForbidden}, + "rulesets 404": {"/repos/o/r/rulesets": http.StatusNotFound}, + "ruleset detail 404": {"/repos/o/r/rulesets/1": http.StatusNotFound}, + "tags 401": {"/repos/o/r/tags": http.StatusUnauthorized}, + } + for name, status := range cases { + t.Run(name, func(t *testing.T) { + api := &tagAPI{ + summaries: []map[string]any{summary(1, "active", "Repository")}, + details: map[int64]map[string]any{1: detail(1, "Repository", []string{"~ALL"}, nil, "update")}, + status: status, + } + srv := api.server(t) + defer srv.Close() + swapRESTClient(t, srv) + + got, err := FetchGitHubTagProtection("", "o", "r") + if err != nil { + t.Fatalf("want no error, got %v", err) + } + if got == nil || got.Known { + t.Fatalf("want Known=false, got %+v", got) + } + }) + } +} + +// A server error is a failed collection: the caller degrades the run. +func TestFetchGitHubTagProtection_ServerErrorIsReturned(t *testing.T) { + api := &tagAPI{status: map[string]int{"/repos/o/r/tags": http.StatusInternalServerError}} + srv := api.server(t) + defer srv.Close() + swapRESTClient(t, srv) + + got, err := FetchGitHubTagProtection("", "o", "r") + if err == nil { + t.Fatal("want an error on a 500") + } + if got == nil || got.Known { + t.Fatalf("want Known=false alongside the error, got %+v", got) + } +} + +func TestFetchGitHubTagProtection_TagListingCap(t *testing.T) { + api := &tagAPI{} + for i := range maxTagListingPages*100 + 5 { + api.tags = append(api.tags, fmt.Sprintf("t%d", i)) + } + srv := api.server(t) + defer srv.Close() + swapRESTClient(t, srv) + + got, err := FetchGitHubTagProtection("", "o", "r") + if err != nil { + t.Fatal(err) + } + if !got.Known || !got.TagsTruncated || len(got.Tags) != maxTagListingPages*100 { + t.Fatalf("want Known, truncated, %d tags; got known=%v truncated=%v n=%d", maxTagListingPages*100, got.Known, got.TagsTruncated, len(got.Tags)) + } +} + +// Past the listing cap a ruleset protecting a pattern could be missed: +// not evaluated rather than a finding invented from a partial list. +func TestFetchGitHubTagProtection_RulesetListingCapIsUnknown(t *testing.T) { + api := &tagAPI{} + for i := range maxBranchListingPages * 100 { + api.summaries = append(api.summaries, summary(int64(i+1), "disabled", "Repository")) + } + srv := api.server(t) + defer srv.Close() + swapRESTClient(t, srv) + + got, err := FetchGitHubTagProtection("", "o", "r") + if err != nil { + t.Fatalf("want no error, got %v", err) + } + if got == nil || got.Known { + t.Fatalf("want Known=false, got %+v", got) + } +} + +// Dropping an organization ruleset that applies would invent a finding, +// keeping one that does not would hide one. +func TestRulesetAppliesToRepo(t *testing.T) { + cases := []struct { + name string + cond *remoteIncludeExclude + want bool + }{ + {"no repository condition", nil, true}, + {"every repository", &remoteIncludeExclude{Include: []string{"~ALL"}}, true}, + {"name pattern matching", &remoteIncludeExclude{Include: []string{"r*"}}, true}, + {"name pattern not matching", &remoteIncludeExclude{Include: []string{"elsewhere"}}, false}, + {"every repository but this one", &remoteIncludeExclude{Include: []string{"~ALL"}, Exclude: []string{"r"}}, false}, + {"every repository but others", &remoteIncludeExclude{Include: []string{"~ALL"}, Exclude: []string{"other*"}}, true}, + {"exclude only, matching", &remoteIncludeExclude{Exclude: []string{"r*"}}, false}, + {"exclude only, not matching", &remoteIncludeExclude{Exclude: []string{"other"}}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rs := &remoteRuleset{} + rs.Conditions.RepositoryName = tc.cond + if got := rulesetAppliesToRepo(rs, "r"); got != tc.want { + t.Fatalf("rulesetAppliesToRepo = %v, want %v", got, tc.want) + } + }) + } +} + +func TestNormalizeGitHubTagPattern(t *testing.T) { + for in, want := range map[string]string{ + "~ALL": "**", + "refs/tags/v*": "v*", + "v*": "v*", + "refs/tags/**/x": "**/x", + } { + if got := normalizeGitHubTagPattern(in); got != want { + t.Errorf("normalizeGitHubTagPattern(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/gitlab/collect_tag_protection.go b/gitlab/collect_tag_protection.go new file mode 100644 index 00000000..a25809df --- /dev/null +++ b/gitlab/collect_tag_protection.go @@ -0,0 +1,193 @@ +package gitlab + +import ( + "errors" + "fmt" + "strings" + + "github.com/sirupsen/logrus" + glab "gitlab.com/gitlab-org/api/client-go" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/ir" +) + +// maxTagListingPages caps the tag listing at 10 pages × 100 entries, most +// recently updated first. A project with more tags than that is reported +// with TagsTruncated, which can only hide a finding, never invent one. +const maxTagListingPages = 10 + +// errProtectedTagsTruncated: the protected tags outran maxTagListingPages. +// One past the cap could be the protection a pattern relies on, so the +// collection is unknown rather than partial. +var errProtectedTagsTruncated = errors.New("protected tags listing truncated") + +// TagProtection is one GitLab protected tag (Settings > Repository > +// Protected tags): an exact name or a `*` wildcard, and who may create +// matching tags. +type TagProtection struct { + Name string `json:"name"` + CreateAccessLevels []BranchProtectionAccessLevel `json:"createAccessLevels"` +} + +// GitlabTagProtectionData is what tagMustBeProtected reads on GitLab: the +// protected tags and the existing tag names. Known is false when either +// listing could not be read, so the control reports not evaluated rather +// than read an unreadable listing as "nothing is protected". +type GitlabTagProtectionData struct { + Known bool `json:"known"` + Tags []string `json:"tags"` + TagsTruncated bool `json:"tagsTruncated"` + Protections []TagProtection `json:"protections"` +} + +// CollectGitlabTagProtection reads the project's protected tags and its +// tag names. On any failure it returns Known=false alongside the error; +// the caller decides whether the error degrades the run (network) or only +// leaves the control not evaluated (a 401/403 on a token without scope). +func CollectGitlabTagProtection(projectPath, token string, conf *configuration.Configuration) (*GitlabTagProtectionData, error) { + tags, truncated, protections, err := FetchProjectTagProtectionData(projectPath, token, conf.GitlabURL, conf) + if err != nil { + return &GitlabTagProtectionData{Known: false}, err + } + return &GitlabTagProtectionData{Known: true, Tags: tags, TagsTruncated: truncated, Protections: protections}, nil +} + +// FetchProjectTagProtectionData fetches the protected tags and the tag +// names, both capped at maxTagListingPages; protected tags past the cap +// are an error, tags past it set truncated. A failed read returns +// an error, never an empty list: "no protected tags" is the exact +// violation tagMustBeProtected reports, so a read that failed must not +// arrive looking like one. +func FetchProjectTagProtectionData(projectPath, token, apiURL string, conf *configuration.Configuration) (tags []string, truncated bool, protections []TagProtection, err error) { + l := logger.WithFields(logrus.Fields{ + "action": "FetchProjectTagProtectionData", + "projectPath": projectPath, + "apiURL": apiURL, + }) + + client, err := GetNewGitlabClient(token, apiURL, conf) + if err != nil { + l.WithError(err).Error("Unable to get a Gitlab client") + return nil, false, nil, err + } + + var perPage int64 = 100 + protOptions := &glab.ListProtectedTagsOptions{ListOptions: glab.ListOptions{PerPage: perPage}} + for page := int64(1); ; page++ { + if page > maxTagListingPages { + l.Warnf("Protected tags exceed %d pages; the tag protection is unknown", maxTagListingPages) + return nil, false, nil, fmt.Errorf("%w at %d pages", errProtectedTagsTruncated, maxTagListingPages) + } + protOptions.Page = page + batch, _, err := client.ProtectedTags.ListProtectedTags(projectPath, protOptions) + if err != nil { + l.WithError(err).Warn("Failed to fetch protected tags; the tag protection is unknown, not empty") + return nil, false, nil, err + } + for _, p := range batch { + protections = append(protections, toTagProtection(p)) + } + if int64(len(batch)) < perPage { + break + } + } + + orderBy := "updated" + sort := "desc" + tagOptions := &glab.ListTagsOptions{ListOptions: glab.ListOptions{PerPage: perPage}, OrderBy: &orderBy, Sort: &sort} + for page := int64(1); page <= maxTagListingPages; page++ { + tagOptions.Page = page + batch, _, err := client.Tags.ListTags(projectPath, tagOptions) + if err != nil { + l.WithError(err).Warn("Failed to fetch tags; the tag protection is unknown") + return nil, false, nil, err + } + for _, t := range batch { + tags = append(tags, t.Name) + } + if int64(len(batch)) < perPage { + return tags, false, protections, nil + } + } + l.Warnf("Tag listing capped at %d pages; older tags were not checked", maxTagListingPages) + return tags, true, protections, nil +} + +func toTagProtection(p *glab.ProtectedTag) TagProtection { + tp := TagProtection{Name: p.Name} + for _, a := range p.CreateAccessLevels { + if a == nil { + continue + } + if a.UserID != 0 || a.GroupID != 0 || a.DeployKeyID != 0 { + // A user, group or deploy key entry: no role is let in. + continue + } + tp.CreateAccessLevels = append(tp.CreateAccessLevels, BranchProtectionAccessLevel{ + AccessLevel: int(a.AccessLevel), + AccessLevelDescription: a.AccessLevelDescription, + }) + } + return tp +} + +// maintainerAccessLevel is GitLab's Maintainer role. A create access +// level below it (Developer, Reporter, Guest) leaves tag creation open to +// people who cannot otherwise change protected settings; 0 is "No one". +const maintainerAccessLevel = 40 + +// BuildTagProtection maps the GitLab collection onto the provider-neutral +// IR. nil in, nil out: the collection did not run and the rule abstains. +// +// A protected tag cannot be updated or deleted by a push, so every one +// blocks both. Creation counts as restricted unless some role entry lets +// Developers (or below) create; no entry at all is GitLab's default, +// Maintainers. +func BuildTagProtection(d *GitlabTagProtectionData) *ir.TagProtection { + if d == nil { + return nil + } + out := &ir.TagProtection{Known: d.Known, Tags: d.Tags, TagsTruncated: d.TagsTruncated} + if !d.Known { + return out + } + for _, p := range d.Protections { + restricted := true + for _, a := range p.CreateAccessLevels { + if a.AccessLevel > 0 && a.AccessLevel < maintainerAccessLevel { + restricted = false + } + } + out.Rules = append(out.Rules, ir.TagProtectionRule{ + ID: p.Name, + Name: p.Name, + Source: ir.TagRuleSourceProtectedTag, + Include: []string{gitlabWildcardToGlob(p.Name)}, + BlocksUpdate: true, + BlocksDeletion: true, + RestrictsCreation: restricted, + }) + } + return out +} + +// gitlabWildcardToGlob turns a GitLab protected tag name into the shared +// glob dialect. GitLab's only wildcard is `*`, and it matches across +// slashes, so it becomes `**`; every other glob metacharacter is literal +// on GitLab and is escaped. +func gitlabWildcardToGlob(name string) string { + var b strings.Builder + for _, r := range name { + switch r { + case '*': + b.WriteString("**") + case '\\', '?', '[', ']', '{', '}': + b.WriteByte('\\') + b.WriteRune(r) + default: + b.WriteRune(r) + } + } + return b.String() +} diff --git a/gitlab/collect_tag_protection_test.go b/gitlab/collect_tag_protection_test.go new file mode 100644 index 00000000..f7d70689 --- /dev/null +++ b/gitlab/collect_tag_protection_test.go @@ -0,0 +1,180 @@ +package gitlab + +import ( + "errors" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/getplumber/plumber/configuration" + "github.com/getplumber/plumber/internal/ir" +) + +func tagProtectionServer(protectedStatus int, protectedBody, tagsBody string) *httptest.Server { + return tagProtectionServerWithTags(protectedStatus, protectedBody, http.StatusOK, tagsBody) +} + +func tagProtectionServerWithTags(protectedStatus int, protectedBody string, tagsStatus int, tagsBody string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/protected_tags"): + if protectedStatus != http.StatusOK { + w.WriteHeader(protectedStatus) + return + } + _, _ = w.Write([]byte(protectedBody)) + case strings.HasSuffix(r.URL.Path, "/repository/tags"): + if tagsStatus != http.StatusOK { + w.WriteHeader(tagsStatus) + return + } + _, _ = w.Write([]byte(tagsBody)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) +} + +func TestCollectGitlabTagProtection(t *testing.T) { + t.Run("success maps protected tags and tag names", func(t *testing.T) { + srv := tagProtectionServer(http.StatusOK, + `[{"name":"v*","create_access_levels":[{"access_level":40,"access_level_description":"Maintainers"}]}, + {"name":"release-*","create_access_levels":[{"access_level":30},{"user_id":7,"access_level":40}]}]`, + `[{"name":"v1.0.0"},{"name":"release-2"}]`) + defer srv.Close() + conf := &configuration.Configuration{GitlabURL: srv.URL, HTTPClientTimeout: 30 * time.Second} + + data, err := CollectGitlabTagProtection("group/project", "tok", conf) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := &GitlabTagProtectionData{ + Known: true, + Tags: []string{"v1.0.0", "release-2"}, + Protections: []TagProtection{ + {Name: "v*", CreateAccessLevels: []BranchProtectionAccessLevel{{AccessLevel: 40, AccessLevelDescription: "Maintainers"}}}, + {Name: "release-*", CreateAccessLevels: []BranchProtectionAccessLevel{{AccessLevel: 30}}}, + }, + } + if !reflect.DeepEqual(data, want) { + t.Fatalf("got %+v\nwant %+v", data, want) + } + }) + + t.Run("protected tags past the page cap are unknown, not partial", func(t *testing.T) { + entries := make([]string, 100) + for i := range entries { + entries[i] = fmt.Sprintf(`{"name":"p%d"}`, i) + } + // Every page comes back full, so the listing never ends. + srv := tagProtectionServer(http.StatusOK, "["+strings.Join(entries, ",")+"]", `[]`) + defer srv.Close() + conf := &configuration.Configuration{GitlabURL: srv.URL, HTTPClientTimeout: 30 * time.Second} + + data, err := CollectGitlabTagProtection("group/project", "tok", conf) + if !errors.Is(err, errProtectedTagsTruncated) { + t.Fatalf("want errProtectedTagsTruncated, got %v", err) + } + if data == nil || data.Known { + t.Fatalf("want Known=false, got %+v", data) + } + }) + + t.Run("a failed tag listing is unknown, not partial", func(t *testing.T) { + srv := tagProtectionServerWithTags(http.StatusOK, `[]`, http.StatusInternalServerError, "") + defer srv.Close() + conf := &configuration.Configuration{GitlabURL: srv.URL, HTTPClientTimeout: 30 * time.Second} + + data, err := CollectGitlabTagProtection("group/project", "tok", conf) + if err == nil { + t.Fatal("want the error surfaced") + } + if data == nil || data.Known { + t.Fatalf("want Known=false, got %+v", data) + } + }) + + t.Run("tags past the page cap are checked up to the cap", func(t *testing.T) { + entries := make([]string, 100) + for i := range entries { + entries[i] = fmt.Sprintf(`{"name":"t%d"}`, i) + } + // Every page comes back full: the listing stops at the cap and says so. + srv := tagProtectionServer(http.StatusOK, `[]`, "["+strings.Join(entries, ",")+"]") + defer srv.Close() + conf := &configuration.Configuration{GitlabURL: srv.URL, HTTPClientTimeout: 30 * time.Second} + + data, err := CollectGitlabTagProtection("group/project", "tok", conf) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !data.Known || !data.TagsTruncated || len(data.Tags) != maxTagListingPages*100 { + t.Fatalf("want Known, truncated, %d tags; got known=%v truncated=%v n=%d", maxTagListingPages*100, data.Known, data.TagsTruncated, len(data.Tags)) + } + }) + + t.Run("403 on protected tags is unknown, not empty", func(t *testing.T) { + srv := tagProtectionServer(http.StatusForbidden, "", `[]`) + defer srv.Close() + conf := &configuration.Configuration{GitlabURL: srv.URL, HTTPClientTimeout: 30 * time.Second} + + data, err := CollectGitlabTagProtection("group/project", "tok", conf) + if err == nil { + t.Fatal("want the error surfaced") + } + if data == nil || data.Known { + t.Fatalf("want Known=false, got %+v", data) + } + }) +} + +func TestBuildTagProtection(t *testing.T) { + if BuildTagProtection(nil) != nil { + t.Fatal("nil collection must map to nil (rule abstains)") + } + if got := BuildTagProtection(&GitlabTagProtectionData{Known: false, Tags: []string{"v1"}}); got == nil || got.Known || len(got.Rules) != 0 { + t.Fatalf("unknown collection must stay unknown with no rules, got %+v", got) + } + + got := BuildTagProtection(&GitlabTagProtectionData{ + Known: true, + Tags: []string{"v1.0.0"}, + Protections: []TagProtection{ + {Name: "v*"}, // no entry: GitLab's default, Maintainers + {Name: "release-*", CreateAccessLevels: []BranchProtectionAccessLevel{{AccessLevel: 30}}}, + {Name: "stable", CreateAccessLevels: []BranchProtectionAccessLevel{{AccessLevel: 0}}}, + {Name: "rc-*"}, // only user, group or deploy key entries + }, + }) + want := &ir.TagProtection{ + Known: true, + Tags: []string{"v1.0.0"}, + Rules: []ir.TagProtectionRule{ + {ID: "v*", Name: "v*", Source: ir.TagRuleSourceProtectedTag, Include: []string{"v**"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true}, + {ID: "release-*", Name: "release-*", Source: ir.TagRuleSourceProtectedTag, Include: []string{"release-**"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: false}, + {ID: "stable", Name: "stable", Source: ir.TagRuleSourceProtectedTag, Include: []string{"stable"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true}, + {ID: "rc-*", Name: "rc-*", Source: ir.TagRuleSourceProtectedTag, Include: []string{"rc-**"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true}, + }, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v\nwant %+v", got, want) + } +} + +func TestGitlabWildcardToGlob(t *testing.T) { + for in, want := range map[string]string{ + "v*": "v**", + "*-stable": "**-stable", + "v1.0": "v1.0", + "v[1]?": `v\[1\]\?`, + "a{b}": `a\{b\}`, + } { + if got := gitlabWildcardToGlob(in); got != want { + t.Errorf("gitlabWildcardToGlob(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/ir/pipeline.go b/internal/ir/pipeline.go index 2ce60127..738f5803 100644 --- a/internal/ir/pipeline.go +++ b/internal/ir/pipeline.go @@ -25,6 +25,11 @@ type NormalizedPipeline struct { Branches []Branch `json:"branches,omitempty"` Dependabot *DependabotConfig `json:"dependabot,omitempty"` + // TagProtection is the repository's tag protection rules and its + // existing tag names, read by tagMustBeProtected (ISSUE-510). nil when + // the collection did not run, so the rule abstains. + TagProtection *TagProtection `json:"tagProtection,omitempty"` + // WorkflowStates maps a GitHub Actions workflow file's path, exactly // as the workflows listing endpoint returns it (e.g. // ".github/workflows/ci.yml", matching Job.OriginFile), to its state @@ -935,6 +940,62 @@ type Branch struct { ProtectionDetailsKnown bool `json:"protectionDetailsKnown,omitempty"` } +// TagProtection is what tagMustBeProtected reads: the provider's tag +// protection rules and the repository's existing tags. Known is false when +// either could not be read authoritatively (missing token scope, a 404 on +// an instance without rulesets), and the rule then abstains rather than +// flag every pattern: no data never reads as "no protection". +// +// Patterns in Include, Exclude and Tags share one glob dialect, matched +// with "/" as the separator: `*` stops at a slash, `**` crosses it. Each +// collector translates its provider's own wildcard syntax into it +// (GitHub's fnmatch already stops at a slash; GitLab's `*` does not, so it +// becomes `**`), so the rule never has to know which provider it reads. +type TagProtection struct { + Known bool `json:"known"` + Rules []TagProtectionRule `json:"rules,omitempty"` + // Tags are the existing tag names, refs/tags/ stripped. The listing + // is capped; TagsTruncated says the cap was hit, which can only hide + // a finding (a matching tag not seen), never invent one. + Tags []string `json:"tags,omitempty"` + TagsTruncated bool `json:"tagsTruncated,omitempty"` +} + +// TagProtectionOrNil returns p.TagProtection, nil-safe on p. +func (p *NormalizedPipeline) TagProtectionOrNil() *TagProtection { + if p == nil { + return nil + } + return p.TagProtection +} + +// TagProtectionRule is one rule protecting tags: a GitLab protected tag, +// or an active GitHub tag ruleset (repository or inherited from the +// organization). Rules are judged per protection across all of them, the +// way GitHub layers rulesets: one rule blocking updates and another +// restricting creation on the same pattern together protect it. +type TagProtectionRule struct { + // ID is the protected tag's name on GitLab, the ruleset id on GitHub. + ID string `json:"id"` + Name string `json:"name,omitempty"` + Source string `json:"source"` + // Include and Exclude are the tag name patterns the rule targets, + // in the shared glob dialect above. + Include []string `json:"include"` + Exclude []string `json:"exclude,omitempty"` + BlocksUpdate bool `json:"blocksUpdate"` + BlocksDeletion bool `json:"blocksDeletion"` + RestrictsCreation bool `json:"restrictsCreation"` +} + +// TagProtectionRule.Source values. +const ( + TagRuleSourceProtectedTag = "protected_tag" + TagRuleSourceRepositoryRuleset = "repository_ruleset" + TagRuleSourceOrganizationRuleset = "organization_ruleset" + TagRuleSourceEnterpriseRuleset = "enterprise_ruleset" +) + // MRApprovalRule is one merge-request approval rule (GitLab: Settings > // Merge requests > Approval rules). It carries the rule's stable identity // and the fields the approval-rule controls check: how many approvals it diff --git a/policies/message_style_test.go b/policies/message_style_test.go index cfa2ff3f..00eaf656 100644 --- a/policies/message_style_test.go +++ b/policies/message_style_test.go @@ -114,6 +114,8 @@ var gitLabMessageStyleKeys = map[string][]string{ "ISSUE-504": {}, "ISSUE-505": {"branchName"}, "ISSUE-506": {}, + // Tag pattern not protected: the pattern. + "ISSUE-510": {"tagPattern"}, "ISSUE-601": {}, } @@ -153,6 +155,10 @@ var dataArrayKinds = map[string]bool{ // 2026-10-16 section 6): `uses:` references a consumer parses (the // identity, the paths), rendered for a reader by the message's clause. "ISSUE-402.via": false, + // The protections a tag pattern lacks, as stable tokens (update, + // deletion, creation). A consumer parses them; the message renders + // them as clauses. + "ISSUE-510.missingProtections": false, } // messageBranches is the render manifest, and the answer to a defect class @@ -256,6 +262,11 @@ var messageBranches = []messageBranch{ {"ISSUE-506", "subject resolveOutdatedDiffDiscussions", "Resolving outdated diff discussions is", ""}, {"ISSUE-506", "subject printingMergeRequestLinkEnabled", "Printing the merge request link on push is", ""}, {"ISSUE-506", "subject removeSourceBranchAfterMerge", "Removing the source branch after merge is", ""}, + {"ISSUE-510", "nothing protected", "` is not protected.", ""}, + {"ISSUE-510", "partly protected", "` is not fully protected, ", ""}, + {"ISSUE-510", "clause update", "tag updates are not blocked", ""}, + {"ISSUE-510", "clause deletion", "tag deletions are not blocked", ""}, + {"ISSUE-510", "clause creation", "tag creation is not restricted", ""}, {"ISSUE-601", "nothing linked, no expectation", "is linked to this project", ""}, {"ISSUE-601", "nothing linked, expectation set", "is linked (expected", ""}, {"ISSUE-601", "wrong project, id only", ") is not the expected one (expected id", ""}, diff --git a/policies/tag_unprotected.rego b/policies/tag_unprotected.rego new file mode 100644 index 00000000..ce703bbc --- /dev/null +++ b/policies/tag_unprotected.rego @@ -0,0 +1,326 @@ +# tag-unprotected — flag release tags anyone with push access can move, +# delete or create (#398). +# +# Two modes, chosen by tagMustBeProtected.namePatterns: +# +# - empty or unset (the default): all tags must be protected by rules +# that target every tag (a GitHub ruleset on ~ALL, a GitLab protected +# tag `*`, both collected as `**`) and exclude none. One finding, +# keyed on that all-tags target. See "All-tags mode" below. +# - a list of patterns: each pattern is checked on its own, one finding +# per pattern. +# +# Workflow tag triggers never add a pattern to check. They raise a +# finding to critical, and a trigger on exactly a configured pattern puts +# it in use before any tag exists. Either way a repository that never +# tags and never runs on tags stays quiet. +# +# A pattern is protected when the provider's rules block tag updates and +# deletions on it, and restrict tag creation unless +# requireCreationRestricted is false. Each protection is judged across +# every rule, the way GitHub layers rulesets. A rule covers a pattern when +# it matches the pattern itself (a rule on `v*` or `**` covers `v*`, one +# on `v[0-9]*` does not) and every existing tag the pattern matches. +# +# The collectors translate both providers' wildcards into one glob +# dialect (see ir.TagProtection), so nothing here is provider specific +# except the GitLab tag-trigger shape in _gitlab_runs_on_tags and the +# all-tags label each provider's UI shows (_all_tags_label). +package tag_unprotected + +import rego.v1 + +deny contains finding if { + tp := input.pipeline.tagProtection + tp.known == true + some pattern in _required_patterns + _in_use(pattern, tp) + missing := _missing(pattern, tp) + count(missing) > 0 + finding := { + "code": "ISSUE-510", + "severity": "critical", + "message": _message(pattern, missing), + # No "job": a tag pattern is not a job. tagPattern names what this + # finding is about and is what the identity recipe selects. + "type": "unprotected", + "tagPattern": pattern, + # missingProtections: the protections the pattern lacks, as stable + # tokens a consumer parses ("update", "deletion", "creation"). + "missingProtections": missing, + # occurrenceSeverity: critical when a workflow runs on a tag push, + # since a moved or forged tag then ships through the release + # itself; high otherwise. + "triggered": _is_triggered(pattern, tp), + "occurrenceSeverity": _occurrence_severity(pattern, tp), + } +} + +_config := object.get(input.config, "tagMustBeProtected", {}) + +_jobs := object.get(input.pipeline, "jobs", []) + +_strip(s) := trim_prefix(s, "refs/tags/") + +_live(job) if object.get(job, "inert", "") == "" + +# _required_patterns: the configured patterns, the only ones a finding +# is ever raised on. Empty selects the all-tags mode. +_required_patterns contains p if { + some raw in object.get(_config, "namePatterns", []) + p := _strip(raw) + p != "" +} + +# _workflow_tag_patterns: the tag patterns live GitHub workflows run on, +# read for severity only. A `!` entry negates an earlier one and an +# expression cannot be read statically; neither names tags. +_workflow_tag_patterns contains p if { + some job in _jobs + _live(job) + some raw in object.get(job, "pushTags", []) + not startswith(raw, "!") + not contains(raw, "${{") + p := _strip(raw) + p != "" +} + +_matching_tags(pattern, tp) := {t | + some t in object.get(tp, "tags", []) + _tag_matches(pattern, t) +} + +# _tag_matches: a configured pattern is a glob. +_tag_matches(pattern, t) if glob.match(pattern, ["/"], t) + +# _filter_regex: a workflow pattern is a GitHub filter pattern, where `+` +# and `?` quantify the character before them, read here as an anchored +# regex to tell which existing tags a trigger fires on. `*` stops +# at `/`, `**` does not; `+`, `?`, `[...]` and `\` escapes read the same +# in both. +_filter_regex(p) := concat("", ["^", body, "$"]) if { + escaped := strings.replace_n( + {".": `\.`, "(": `\(`, ")": `\)`, "{": `\{`, "}": `\}`, "|": `\|`, "^": `\^`, "$": `\$`}, + p, + ) + body := replace(replace(replace(escaped, "**", "\u0000"), "*", "[^/]*"), "\u0000", ".*") +} +_in_use(pattern, tp) if count(_matching_tags(pattern, tp)) > 0 + +_in_use(pattern, tp) if _pattern_triggered(pattern, tp) + +# _pattern_triggered: a workflow triggers on this very pattern, or on one +# that matches an existing tag this pattern matches too. +_pattern_triggered(pattern, _) if pattern in _workflow_tag_patterns + +_pattern_triggered(pattern, tp) if { + some wp in _workflow_tag_patterns + some t in _matching_tags(pattern, tp) + regex.match(_filter_regex(wp), t) +} + +# _triggered: the pattern's own trigger, or a workflow that runs on tags +# without naming a pattern (a GitHub release or tags-ignore push, a GitLab +# tag pipeline). +# Those raise the severity but never put a pattern in use on their own. +_triggered(pattern, tp) if _pattern_triggered(pattern, tp) + +_triggered(_, _) if _runs_on_unnamed_tags + +# _runs_on_unnamed_tags: a live job runs on tags without naming a pattern. +_runs_on_unnamed_tags if { + some job in _jobs + _live(job) + "release" in object.get(job, "triggers", []) +} + +# A push trigger with tags-ignore runs on every tag it does not ignore +# (GitHub rejects tags and tags-ignore on the same event). +_runs_on_unnamed_tags if { + some job in _jobs + _live(job) + count(object.get(job, "pushTagsIgnore", [])) > 0 +} + +_runs_on_unnamed_tags if { + some job in _jobs + _live(job) + _gitlab_runs_on_tags(job) +} + +_is_triggered(pattern, tp) if { + _triggered(pattern, tp) +} else := false + +_occurrence_severity(pattern, tp) := "critical" if { + _triggered(pattern, tp) +} else := "high" + +# _gitlab_runs_on_tags: `only: [tags]`, or a rule whose `if:` reads +# $CI_COMMIT_TAG positively and does not exclude the job (`when: never`). +# A bare job with no rules runs on tag pipelines too, but so does almost +# every job: only explicit tag intent counts. +_gitlab_runs_on_tags(job) if "tags" in object.get(job, "only", []) + +_gitlab_runs_on_tags(job) if { + some rule in object.get(job, "rules", []) + object.get(rule, "when", "") != "never" + cond := object.get(rule, "if", "") + is_string(cond) + _positive_tag_condition(cond) +} + +# _positive_tag_condition: some $CI_COMMIT_TAG reference that is neither +# negated (`!$CI_COMMIT_TAG`) nor compared equal to an empty value +# (`$CI_COMMIT_TAG == null`, `== ""`), the shapes that mean "not a tag". +_positive_tag_condition(cond) if { + some m in regex.find_all_string_submatch_n(`(!?)\$(?:\{CI_COMMIT_TAG\}|CI_COMMIT_TAG\b)(\s*(==|!=)\s*(null|""|''))?`, cond, -1) + m[1] == "" + not m[3] == "==" +} + +_missing(pattern, tp) := [m | + some m in ["update", "deletion", "creation"] + _lacks(m, pattern, tp) +] + +_lacks("update", pattern, tp) if not _has("blocksUpdate", pattern, tp) + +_lacks("deletion", pattern, tp) if not _has("blocksDeletion", pattern, tp) + +_lacks("creation", pattern, tp) if { + object.get(_config, "requireCreationRestricted", true) == true + not _has("restrictsCreation", pattern, tp) +} + +_has(protection, pattern, tp) if { + some rule in object.get(tp, "rules", []) + object.get(rule, protection, false) == true + _rule_covers_pattern(rule, pattern) + not _uncovered_tag(protection, pattern, tp) +} + +# _rule_covers_pattern: the rule names the pattern verbatim (a class like +# `v[0-9]*` does not glob-match its own text), or its globs match the +# pattern's text. +_rule_covers_pattern(rule, pattern) if { + pattern in object.get(rule, "include", []) + not _rule_excludes(rule, pattern) +} + +_rule_covers_pattern(rule, pattern) if _rule_matches(rule, pattern) +_uncovered_tag(protection, pattern, tp) if { + some t in _matching_tags(pattern, tp) + not _tag_has(protection, t, tp) +} + +_tag_has(protection, t, tp) if { + some rule in object.get(tp, "rules", []) + object.get(rule, protection, false) == true + _rule_matches(rule, t) +} + +_rule_matches(rule, s) if { + some inc in object.get(rule, "include", []) + glob.match(inc, ["/"], s) + not _rule_excludes(rule, s) +} + +_rule_excludes(rule, s) if { + some exc in object.get(rule, "exclude", []) + glob.match(exc, ["/"], s) +} + +_clauses := { + "update": "tag updates are not blocked", + "deletion": "tag deletions are not blocked", + "creation": "tag creation is not restricted", +} + +_message(pattern, missing) := sprintf("Tag pattern `%s` is not protected.", [pattern]) if { + count(missing) == count(_required_protections) +} else := sprintf("Tag pattern `%s` is not fully protected, %s.", [pattern, concat(" and ", [_clauses[m] | some m in missing])]) + +_required_protections := ["update", "deletion", "creation"] if { + object.get(_config, "requireCreationRestricted", true) == true +} else := ["update", "deletion"] + +# --- All-tags mode (namePatterns empty or unset, the default) --- +# +# One rule on every tag is the recommended setup, so with no configured +# pattern the question becomes: do active rules targeting all tags, with +# no exclusion, provide every required protection? Such rules layer, one +# protection each, like the per-pattern check. A rule on `v*` or `*` +# does not count: `*` stops at a slash, and neither covers every tag. + +_all_tags_mode if count(_required_patterns) == 0 + +deny contains finding if { + _all_tags_mode + tp := input.pipeline.tagProtection + tp.known == true + _all_tags_in_use(tp) + missing := _all_tags_missing(tp) + count(missing) > 0 + finding := { + "code": "ISSUE-510", + "severity": "critical", + "message": _all_tags_message(missing), + "type": "unprotected", + # The all-tags target as the provider's UI names it: the finding's + # identity, stable across runs on one provider. + "tagPattern": _all_tags_label, + "missingProtections": missing, + "triggered": _is_all_tags_triggered, + "occurrenceSeverity": _all_tags_occurrence_severity, + } +} + +_all_tags_label := "~ALL" if input.pipeline.provider == "github" + +else := "*" + +# _all_tags_in_use: the repository has a tag, or a live job runs on tags. +_all_tags_in_use(tp) if count(object.get(tp, "tags", [])) > 0 + +_all_tags_in_use(_) if _runs_on_any_tags + +# _runs_on_any_tags: a live job runs on a tag push, whatever its patterns +# (expressions and `!` entries included), or on tags without naming one. +_runs_on_any_tags if { + some job in _jobs + _live(job) + count(object.get(job, "pushTags", [])) > 0 +} + +_runs_on_any_tags if _runs_on_unnamed_tags + +_is_all_tags_triggered if { + _runs_on_any_tags +} else := false + +_all_tags_occurrence_severity := "critical" if { + _runs_on_any_tags +} else := "high" + +_all_tags_missing(tp) := [m | + some m in _required_protections + not _all_tags_has(m, tp) +] + +_protection_field := { + "update": "blocksUpdate", + "deletion": "blocksDeletion", + "creation": "restrictsCreation", +} + +_all_tags_has(m, tp) if { + some rule in object.get(tp, "rules", []) + object.get(rule, _protection_field[m], false) == true + "**" in object.get(rule, "include", []) + count(object.get(rule, "exclude", [])) == 0 +} + +_all_tags_message(missing) := sprintf("Tags are not protected by a rule on all tags (`%s`).", [_all_tags_label]) if { + count(missing) == count(_required_protections) +} else := sprintf("Tags are not fully protected by rules on all tags (`%s`), %s.", [_all_tags_label, concat(" and ", [_clauses[m] | some m in missing])]) diff --git a/policies/tag_unprotected_test.go b/policies/tag_unprotected_test.go new file mode 100644 index 00000000..edbb8b78 --- /dev/null +++ b/policies/tag_unprotected_test.go @@ -0,0 +1,433 @@ +package policies_test + +import ( + "context" + "maps" + "reflect" + "sort" + "testing" + + opaengine "github.com/getplumber/plumber/internal/engine/opa" + "github.com/getplumber/plumber/internal/ir" + "github.com/getplumber/plumber/policies" +) + +// fullTagRule is a rule that blocks updates and deletions and restricts +// creation on the given include patterns. +func fullTagRule(include ...string) ir.TagProtectionRule { + return ir.TagProtectionRule{ + ID: "1", Source: ir.TagRuleSourceRepositoryRuleset, Include: include, + BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true, + } +} + +func evalTagFindings(t *testing.T, p *ir.NormalizedPipeline, cfg map[string]any) []opaengine.Finding { + t.Helper() + engine := opaengine.New() + if err := engine.LoadFromFSFiltered(policies.FS, nil); err != nil { + t.Fatalf("load embedded policies: %v", err) + } + if cfg == nil { + cfg = map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"v*"}}} + } + findings, err := evaluateStrict(engine, context.Background(), p, cfg) + if err != nil { + t.Fatalf("evaluate: %v", err) + } + var out []opaengine.Finding + for _, f := range findings { + if f.Code == "ISSUE-510" { + out = append(out, f) + } + } + return out +} + +// tagPatterns returns the flagged patterns, sorted. +func tagPatterns(findings []opaengine.Finding) []string { + out := []string{} + for _, f := range findings { + out = append(out, f.Data["tagPattern"].(string)) + } + sort.Strings(out) + return out +} + +func TestIssue507_TagProtection(t *testing.T) { + gh := func(tp *ir.TagProtection, jobs ...ir.Job) *ir.NormalizedPipeline { + return &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, ProjectPath: "o/r", TagProtection: tp, Jobs: jobs} + } + cases := []struct { + name string + p *ir.NormalizedPipeline + cfg map[string]any + want []string + }{ + { + name: "unprotected pattern with a matching tag is flagged", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}), + want: []string{"v*"}, + }, + { + name: "a repository that never tagged stays quiet", + p: gh(&ir.TagProtection{Known: true}), + want: []string{}, + }, + { + name: "tags matching no pattern stay quiet", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"nightly", "latest"}}), + want: []string{}, + }, + { + name: "a trigger on a configured pattern puts it in use with no tag yet", + p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "release/publish", PushTags: []string{"v*"}}), + want: []string{"v*"}, + }, + { + name: "a trigger on a pattern that is not configured is never flagged", + p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "release/publish", PushTags: []string{"release-*"}}), + want: []string{}, + }, + { + name: "negated and expression trigger patterns put nothing in use", + p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "release/publish", PushTags: []string{"!v*", "${{ inputs.x }}"}}), + want: []string{}, + }, + { + name: "an inert job's trigger does not count", + p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "release/publish", PushTags: []string{"v*"}, Inert: "disabled"}), + want: []string{}, + }, + { + name: "refs/tags/ prefixes are stripped", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{fullTagRule("v*")}}, ir.Job{Name: "release/publish", PushTags: []string{"refs/tags/v*"}}), + cfg: map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"refs/tags/v*"}}}, + want: []string{}, + }, + { + name: "a refs/tags/ prefixed configured pattern is flagged under its stripped name", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}), + cfg: map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"refs/tags/v*"}}}, + want: []string{"v*"}, + }, + { + name: "unknown protection abstains", + p: gh(&ir.TagProtection{Known: false, Tags: []string{"v1.0.0"}}), + want: []string{}, + }, + { + name: "no collection abstains", + p: gh(nil, ir.Job{Name: "release/publish", PushTags: []string{"v*"}}), + want: []string{}, + }, + { + name: "a full rule on the pattern protects it", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{fullTagRule("v*")}}), + want: []string{}, + }, + { + name: "an all-tags rule protects every pattern", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0", "release/2"}, Rules: []ir.TagProtectionRule{fullTagRule("**")}}, ir.Job{Name: "r/p", PushTags: []string{"release/*"}}), + want: []string{}, + }, + { + name: "a narrower rule does not cover the pattern", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{fullTagRule("v[0-9]*")}}), + want: []string{"v*"}, + }, + { + name: "an exclude leaving an existing tag open flags the pattern", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0", "v1.1.0-rc1"}, Rules: []ir.TagProtectionRule{{ + ID: "1", Include: []string{"**"}, Exclude: []string{"*-rc*"}, + BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true, + }}}), + want: []string{"v*"}, + }, + { + name: "protections layered across rules add up", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{ + {ID: "1", Include: []string{"v*"}, BlocksUpdate: true, BlocksDeletion: true}, + {ID: "2", Include: []string{"**"}, RestrictsCreation: true}, + }}), + want: []string{}, + }, + { + name: "a GitLab protected tag translated to v** covers nested tags", + p: &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: &ir.TagProtection{Known: true, Tags: []string{"v1/hotfix"}, Rules: []ir.TagProtectionRule{{ + ID: "v*", Source: ir.TagRuleSourceProtectedTag, Include: []string{"v**"}, + BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true, + }}}}, + want: []string{}, + }, + { + name: "creation left open passes when not required", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{ + {ID: "1", Include: []string{"v*"}, BlocksUpdate: true, BlocksDeletion: true}, + }}), + cfg: map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"v*"}, "requireCreationRestricted": false}}, + want: []string{}, + }, + { + name: "creation left open is flagged by default", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{ + {ID: "1", Include: []string{"v*"}, BlocksUpdate: true, BlocksDeletion: true}, + }}), + want: []string{"v*"}, + }, + { + name: "only configured patterns are flagged, never workflow ones", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0", "release-1"}}, ir.Job{Name: "a/x", PushTags: []string{"v*", "release-*"}}, ir.Job{Name: "b/y", PushTags: []string{"v[0-9]+.[0-9]+.[0-9]+"}}), + want: []string{"v*"}, + }, + { + name: "several configured patterns are each checked", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.0.0", "release-1"}, Rules: []ir.TagProtectionRule{fullTagRule("v*")}}), + cfg: map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"v*", "release-*"}}}, + want: []string{"release-*"}, + }, + { + // A configured pattern is a glob even when a workflow names the + // same text: `+` is literal here, so it matches no tag. + name: "a configured pattern is read as a glob, not a filter", + p: gh(&ir.TagProtection{Known: true, Tags: []string{"v1.2.3"}}), + cfg: map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"v[0-9]+.[0-9]+.[0-9]+"}}}, + want: []string{}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := tagPatterns(evalTagFindings(t, tc.p, tc.cfg)) + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("flagged patterns = %v, want %v", got, tc.want) + } + }) + } +} + +// The message names every missing protection when only some are, and the +// missingProtections tokens follow the fixed update, deletion, creation +// order a consumer can rely on. +func TestIssue507_MessageAndMissingProtections(t *testing.T) { + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}} + f := evalTagFindings(t, p, nil) + if len(f) != 1 { + t.Fatalf("want 1 finding, got %d", len(f)) + } + if got := f[0].Message; got != "Tag pattern `v*` is not protected." { + t.Errorf("message = %q", got) + } + if got := f[0].Data["missingProtections"]; !reflect.DeepEqual(got, []any{"update", "deletion", "creation"}) { + t.Errorf("missingProtections = %v", got) + } + + p.TagProtection.Rules = []ir.TagProtectionRule{{ID: "1", Include: []string{"v*"}, BlocksDeletion: true}} + f = evalTagFindings(t, p, nil) + if len(f) != 1 { + t.Fatalf("want 1 finding, got %d", len(f)) + } + if got, want := f[0].Message, "Tag pattern `v*` is not fully protected, tag updates are not blocked and tag creation is not restricted."; got != want { + t.Errorf("message = %q, want %q", got, want) + } + if got := f[0].Data["missingProtections"]; !reflect.DeepEqual(got, []any{"update", "creation"}) { + t.Errorf("missingProtections = %v", got) + } + + p.TagProtection.Rules = []ir.TagProtectionRule{{ID: "1", Include: []string{"v*"}, BlocksUpdate: true, RestrictsCreation: true}} + f = evalTagFindings(t, p, nil) + if len(f) != 1 || f[0].Message != "Tag pattern `v*` is not fully protected, tag deletions are not blocked." { + t.Fatalf("want the deletion clause alone, got %+v", f) + } + + // With creation not required, missing update and deletion is the whole + // requirement, so the short message applies. + p.TagProtection.Rules = []ir.TagProtectionRule{{ID: "1", Include: []string{"v*"}, RestrictsCreation: true}} + cfg := map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"v*"}, "requireCreationRestricted": false}} + f = evalTagFindings(t, p, cfg) + if len(f) != 1 || f[0].Message != "Tag pattern `v*` is not protected." { + t.Fatalf("want the short message, got %+v", f) + } +} + +// occurrenceSeverity is critical when a workflow runs on a tag push (the +// pattern's own trigger, a GitHub release, a GitLab tag pipeline) and high +// otherwise; the registered severity stays critical. +func TestIssue507_OccurrenceSeverity(t *testing.T) { + tp := func() *ir.TagProtection { return &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}} } + cases := []struct { + name string + p *ir.NormalizedPipeline + want string + }{ + {"untriggered", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp()}, "high"}, + {"GitHub push tags on the pattern", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp(), Jobs: []ir.Job{{Name: "r/p", PushTags: []string{"v*"}}}}, "critical"}, + // The trigger pattern itself is protected, so only v* is flagged: it + // shares the tag v1.0.0 with the trigger, which makes it critical. + {"GitHub push tags overlapping through a tag", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{fullTagRule("v[0-9]*")}}, Jobs: []ir.Job{{Name: "r/p", PushTags: []string{"v[0-9]*"}}}}, "critical"}, + // The v*.* rule covers the trigger, not v*; v* is critical because + // the quantified trigger fires on its tag v1.0.0. + {"GitHub filter quantifiers overlapping through a tag", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}, Rules: []ir.TagProtectionRule{fullTagRule("v*.*")}}, Jobs: []ir.Job{{Name: "r/p", PushTags: []string{"v[0-9]+.[0-9]+.[0-9]+"}}}}, "critical"}, + {"GitHub release trigger", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp(), Jobs: []ir.Job{{Name: "r/p", Triggers: []string{"release"}}}}, "critical"}, + {"inert release job", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp(), Jobs: []ir.Job{{Name: "r/p", Triggers: []string{"release"}, Inert: "disabled"}}}, "high"}, + {"GitHub push tags-ignore", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp(), Jobs: []ir.Job{{Name: "r/p", Triggers: []string{"push"}, PushTagsIgnore: []string{"*-rc*"}}}}, "critical"}, + {"inert push tags-ignore job", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp(), Jobs: []ir.Job{{Name: "r/p", Triggers: []string{"push"}, PushTagsIgnore: []string{"*-rc*"}, Inert: "disabled"}}}, "high"}, + {"GitHub bare push", &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: tp(), Jobs: []ir.Job{{Name: "r/p", Triggers: []string{"push"}}}}, "high"}, + {"GitLab only tags", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "release", Only: []string{"tags"}}}}, "critical"}, + {"GitLab rule on CI_COMMIT_TAG", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "release", Rules: []map[string]any{{"if": "$CI_COMMIT_TAG"}}}}}, "critical"}, + {"GitLab rule on braced CI_COMMIT_TAG regex", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "release", Rules: []map[string]any{{"if": `${CI_COMMIT_TAG} =~ /^v/`}}}}}, "critical"}, + {"GitLab rule CI_COMMIT_TAG not null", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "release", Rules: []map[string]any{{"if": `$CI_COMMIT_TAG != null`}}}}}, "critical"}, + {"GitLab rule on negated CI_COMMIT_TAG", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "build", Rules: []map[string]any{{"if": "!$CI_COMMIT_TAG"}}}}}, "high"}, + {"GitLab rule on a longer variable name", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "notes", Rules: []map[string]any{{"if": `$CI_COMMIT_TAG_MESSAGE =~ /release/`}}}}}, "high"}, + {"GitLab rule CI_COMMIT_TAG null", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "build", Rules: []map[string]any{{"if": `$CI_COMMIT_TAG == null`}}}}}, "high"}, + {"GitLab rule CI_COMMIT_TAG empty", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "build", Rules: []map[string]any{{"if": `$CI_COMMIT_TAG == ""`}}}}}, "high"}, + {"GitLab tag rule with when never", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "build", Rules: []map[string]any{{"if": "$CI_COMMIT_TAG", "when": "never"}}}}}, "high"}, + {"GitLab job with no rules", &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: tp(), Jobs: []ir.Job{{Name: "build"}}}, "high"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := evalTagFindings(t, tc.p, nil) + if len(f) != 1 { + t.Fatalf("want 1 finding, got %d", len(f)) + } + if f[0].Severity != "critical" { + t.Errorf("ISSUE-510 keeps its registered severity, got %q", f[0].Severity) + } + if got := f[0].Data["occurrenceSeverity"]; got != tc.want { + t.Errorf("occurrenceSeverity = %v, want %s", got, tc.want) + } + if got := f[0].Data["triggered"]; got != (tc.want == "critical") { + t.Errorf("triggered = %v, want %v", got, tc.want == "critical") + } + }) + } +} + +// With namePatterns empty or unset (the default), every tag must be +// protected by rules on all tags (GitHub ~ALL, GitLab `*`, both `**`) +// that exclude none. One finding, keyed on the provider's all-tags label. +func TestIssue510_AllTags(t *testing.T) { + emptyCfg := func(extra map[string]any) map[string]any { + c := map[string]any{"namePatterns": []any{}} + maps.Copy(c, extra) + return map[string]any{"tagMustBeProtected": c} + } + gh := func(tp *ir.TagProtection, jobs ...ir.Job) *ir.NormalizedPipeline { + return &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, ProjectPath: "o/r", TagProtection: tp, Jobs: jobs} + } + gl := func(tp *ir.TagProtection, jobs ...ir.Job) *ir.NormalizedPipeline { + return &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, ProjectPath: "g/p", TagProtection: tp, Jobs: jobs} + } + tagged := func(rules ...ir.TagProtectionRule) *ir.TagProtection { + return &ir.TagProtection{Known: true, Tags: []string{"v1.0.0", "nightly"}, Rules: rules} + } + withExclude := fullTagRule("**") + withExclude.Exclude = []string{"nightly"} + all := []any{"update", "deletion", "creation"} + + cases := []struct { + name string + p *ir.NormalizedPipeline + cfg map[string]any + want []string + wantMissing []any + }{ + {name: "an all-tags rule passes", p: gh(tagged(fullTagRule("**"))), cfg: emptyCfg(nil), want: []string{}}, + {name: "unset namePatterns means all tags", p: gh(tagged(fullTagRule("v*"))), cfg: map[string]any{"tagMustBeProtected": map[string]any{}}, want: []string{"~ALL"}, wantMissing: all}, + {name: "no control config at all means all tags", p: gh(tagged()), cfg: map[string]any{}, want: []string{"~ALL"}, wantMissing: all}, + {name: "blank patterns only mean all tags", p: gh(tagged()), cfg: emptyCfg(map[string]any{"namePatterns": []any{"", "refs/tags/"}}), want: []string{"~ALL"}, wantMissing: all}, + {name: "a v* rule is not all tags", p: gh(tagged(fullTagRule("v*"))), cfg: emptyCfg(nil), want: []string{"~ALL"}, wantMissing: all}, + {name: "a * rule is not all tags", p: gh(tagged(fullTagRule("*"))), cfg: emptyCfg(nil), want: []string{"~ALL"}, wantMissing: all}, + {name: "an all-tags rule with an exclusion does not count", p: gh(tagged(withExclude)), cfg: emptyCfg(nil), want: []string{"~ALL"}, wantMissing: all}, + { + name: "all-tags rules layer per protection", + p: gh(tagged( + ir.TagProtectionRule{ID: "1", Include: []string{"**"}, BlocksUpdate: true, BlocksDeletion: true}, + ir.TagProtectionRule{ID: "2", Include: []string{"**"}, RestrictsCreation: true}, + )), + cfg: emptyCfg(nil), + want: []string{}, + }, + { + name: "a missing creation rule is reported alone", + p: gh(tagged(ir.TagProtectionRule{ID: "1", Include: []string{"**"}, BlocksUpdate: true, BlocksDeletion: true})), + cfg: emptyCfg(nil), + want: []string{"~ALL"}, + wantMissing: []any{"creation"}, + }, + { + name: "no creation rule passes when creation is not required", + p: gh(tagged(ir.TagProtectionRule{ID: "1", Include: []string{"**"}, BlocksUpdate: true, BlocksDeletion: true})), + cfg: emptyCfg(map[string]any{"requireCreationRestricted": false}), + want: []string{}, + }, + {name: "a repository that never tags stays quiet", p: gh(&ir.TagProtection{Known: true}), cfg: emptyCfg(nil), want: []string{}}, + {name: "unknown protection abstains", p: gh(&ir.TagProtection{Known: false, Tags: []string{"v1.0.0"}}), cfg: emptyCfg(nil), want: []string{}}, + {name: "no collection abstains", p: gh(nil, ir.Job{Name: "r/p", PushTags: []string{"v*"}}), cfg: emptyCfg(nil), want: []string{}}, + {name: "a tag trigger alone puts tags in use", p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "r/p", PushTags: []string{"release-*"}}), cfg: emptyCfg(nil), want: []string{"~ALL"}, wantMissing: all}, + {name: "a release trigger alone puts tags in use", p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "r/p", Triggers: []string{"release"}}), cfg: emptyCfg(nil), want: []string{"~ALL"}, wantMissing: all}, + {name: "an inert tag trigger does not", p: gh(&ir.TagProtection{Known: true}, ir.Job{Name: "r/p", PushTags: []string{"v*"}, Inert: "disabled"}), cfg: emptyCfg(nil), want: []string{}}, + {name: "workflow patterns add no finding of their own", p: gh(tagged(fullTagRule("**")), ir.Job{Name: "r/p", PushTags: []string{"release-*"}}), cfg: emptyCfg(nil), want: []string{}}, + {name: "a configured pattern leaves all-tags mode", p: gh(tagged(fullTagRule("v*"))), cfg: map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{"v*"}}}, want: []string{}}, + {name: "a GitLab protected tag * (collected as **) passes", p: gl(tagged(ir.TagProtectionRule{ID: "*", Source: ir.TagRuleSourceProtectedTag, Include: []string{"**"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true})), cfg: emptyCfg(nil), want: []string{}}, + {name: "a GitLab protected tag v* is not all tags", p: gl(tagged(ir.TagProtectionRule{ID: "v*", Source: ir.TagRuleSourceProtectedTag, Include: []string{"v**"}, BlocksUpdate: true, BlocksDeletion: true, RestrictsCreation: true})), cfg: emptyCfg(nil), want: []string{"*"}, wantMissing: all}, + {name: "a GitLab tag job alone puts tags in use", p: gl(&ir.TagProtection{Known: true}, ir.Job{Name: "release", Only: []string{"tags"}}), cfg: emptyCfg(nil), want: []string{"*"}, wantMissing: all}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := evalTagFindings(t, tc.p, tc.cfg) + if got := tagPatterns(f); !reflect.DeepEqual(got, tc.want) { + t.Fatalf("flagged patterns = %v, want %v", got, tc.want) + } + if tc.wantMissing != nil { + if got := f[0].Data["missingProtections"]; !reflect.DeepEqual(got, tc.wantMissing) { + t.Errorf("missingProtections = %v, want %v", got, tc.wantMissing) + } + } + }) + } +} + +// The all-tags messages name the provider's all-tags target, and the +// finding is critical when any live job runs on tags, whatever its +// pattern, high otherwise. +func TestIssue510_AllTagsMessageAndSeverity(t *testing.T) { + cfg := map[string]any{"tagMustBeProtected": map[string]any{"namePatterns": []any{}}} + p := &ir.NormalizedPipeline{Provider: ir.ProviderGitHub, TagProtection: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}} + + f := evalTagFindings(t, p, cfg) + if len(f) != 1 { + t.Fatalf("want 1 finding, got %d", len(f)) + } + if got, want := f[0].Message, "Tags are not protected by a rule on all tags (`~ALL`)."; got != want { + t.Errorf("message = %q, want %q", got, want) + } + if f[0].Severity != "critical" || f[0].Data["occurrenceSeverity"] != "high" || f[0].Data["triggered"] != false { + t.Errorf("untriggered: severity = %v, occurrenceSeverity = %v, triggered = %v", f[0].Severity, f[0].Data["occurrenceSeverity"], f[0].Data["triggered"]) + } + + p.TagProtection.Rules = []ir.TagProtectionRule{{ID: "1", Include: []string{"**"}, BlocksDeletion: true}} + f = evalTagFindings(t, p, cfg) + if len(f) != 1 { + t.Fatalf("want 1 finding, got %d", len(f)) + } + if got, want := f[0].Message, "Tags are not fully protected by rules on all tags (`~ALL`), tag updates are not blocked and tag creation is not restricted."; got != want { + t.Errorf("message = %q, want %q", got, want) + } + + for name, job := range map[string]ir.Job{ + "push tags expression": {Name: "r/p", PushTags: []string{"${{ inputs.tag }}"}}, + "tags-ignore": {Name: "r/p", Triggers: []string{"push"}, PushTagsIgnore: []string{"*-rc*"}}, + "release": {Name: "r/p", Triggers: []string{"release"}}, + } { + p.Jobs = []ir.Job{job} + f = evalTagFindings(t, p, cfg) + if len(f) != 1 || f[0].Data["occurrenceSeverity"] != "critical" || f[0].Data["triggered"] != true { + t.Errorf("%s: want one critical, triggered finding, got %+v", name, f) + } + } + + gl := &ir.NormalizedPipeline{Provider: ir.ProviderGitLab, TagProtection: &ir.TagProtection{Known: true, Tags: []string{"v1.0.0"}}} + f = evalTagFindings(t, gl, cfg) + if len(f) != 1 || f[0].Message != "Tags are not protected by a rule on all tags (`*`)." { + t.Errorf("GitLab: want the `*` label, got %+v", f) + } +}