Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions .plumber.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
# ============================================================================
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
19 changes: 19 additions & 0 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Comment thread
thomasboni marked this conversation as resolved.
Resolved
if st.MRApprovalMinEnabled {
gl.Controls.MergeRequestApprovalRulesMustRequireMinimumApprovals = &configuration.MRApprovalRulesMinApprovalsControlConfig{
Enabled: boolPtrInit(true),
Expand Down Expand Up @@ -1336,6 +1354,7 @@ func (st *initWizardState) applyAccessControls(gl, gh *configuration.ProviderCon
AllowForcePush: boolPtrInit(st.BranchAllowForcePush),
CodeOwnerApprovalRequired: boolPtrInit(st.BranchCodeOwnerApprovalRequiredGitHub),
}
gh.Controls.TagMustBeProtected = defaultTagProtection()
}
}

Expand Down
20 changes: 20 additions & 0 deletions cmd/init_mr_approval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
32 changes: 32 additions & 0 deletions cmd/legacy_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
thomasboni marked this conversation as resolved.
Resolved
}
return "", nil
}
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions cmd/legacy_json_github.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
78 changes: 78 additions & 0 deletions cmd/legacy_json_gitlab_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}
61 changes: 61 additions & 0 deletions cmd/testdata/catalog_golden.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading