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
8 changes: 8 additions & 0 deletions .plumber.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,14 @@ gitlab:
printingMergeRequestLinkEnabled: true
removeSourceBranchAfterMerge: true # clean up the branch after merge
# ===========================================
# Number of project members must respect a quota
# ===========================================
# Per-role member bounds, all optional and inclusive. Reads members/all
# with the run's token; a CI job token cannot, so it reports not-evaluable
# in a plain pipeline run. Off for the self-scan: this repo is GitHub-hosted.
numberOfProjectMembersMustRespectQuota:
enabled: false
# ===========================================
# Project must have a security policy source
# ===========================================
# Requires the project to link a GitLab security policy project (Settings >
Expand Down
4 changes: 3 additions & 1 deletion cmd/analyze_shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,9 @@ func buildProviderControlSummariesAndGroups(p provider.Provider, result *control
dismissed++
}
}
skipped := e.Skipped || dataCollectionFailed
// A control decided without the pipeline (the member quota, on an
// invalid CI file) is not part of the blanket skip: its verdict is real.
skipped := e.Skipped || (dataCollectionFailed && !result.DecidedOffPipeline(e.ControlName))
Comment thread
thomasboni marked this conversation as resolved.
Resolved
stats := provider.BuildControlStats(p.Name(), e.ControlName, result, pc, findings)
// A control whose lane supplied nothing must not render as passed.
//
Expand Down
26 changes: 26 additions & 0 deletions cmd/legacy_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ func buildLegacyResult(e control.ControlEntry, result *control.AnalysisResult, p
return "mrSettingsResult", buildMRSettingsBlock(common, findings)
case "tagMustBeProtected":
return "tagProtectionResult", buildTagProtectionBlock(common, result, findings)
case "numberOfProjectMembersMustRespectQuota":
return "projectMemberQuotaResult", buildProjectMemberQuotaBlock(common, result, findings)
}
return "", nil
}
Expand Down Expand Up @@ -426,6 +428,30 @@ func buildTagProtectionBlock(c legacyCommon, result *control.AnalysisResult, fin
}
}

// buildProjectMemberQuotaBlock emits the legacy JSON block for the project
// member quota control (ISSUE-507). Findings are project-level (no file/job);
// each issue carries role / currentCount / authorizedMin / authorizedMax from
// f.Data, preserved by projectFindings. The metrics repeat the four counts the
// verdict was computed over, or nothing when the listing was not read.
func buildProjectMemberQuotaBlock(c legacyCommon, result *control.AnalysisResult, findings []opaengine.Finding) map[string]any {
metrics := map[string]any{}
if result != nil && result.MembersData != nil && result.MembersData.Known {
metrics["rolesOutOfQuota"] = len(findings)
metrics["owners"] = result.MembersData.Counts.Owners
metrics["maintainers"] = result.MembersData.Counts.Maintainers
metrics["developers"] = result.MembersData.Counts.Developers
metrics["total"] = result.MembersData.Counts.Total
}
return map[string]any{
"issues": projectFindings(findings, "job"),
"metrics": metrics,
"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
95 changes: 95 additions & 0 deletions cmd/legacy_json_gitlab_test.go
Comment thread
thomasboni marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package cmd

import (
"fmt"
"testing"

"github.com/getplumber/plumber/control"
"github.com/getplumber/plumber/gitlab"
opaengine "github.com/getplumber/plumber/internal/engine/opa"
"github.com/getplumber/plumber/internal/ir"
)
Expand Down Expand Up @@ -446,3 +448,96 @@ func TestTagProtectionJSONBlock(t *testing.T) {
})
}
}

// TestProjectMemberQuotaJSONBlock is the ISSUE-507 twin of
// TestMRSettingsJSONBlock: it pins the dispatch route, the legacy block name
// external consumers parse, and the metrics/issues shape for the member
// quota control.
func TestProjectMemberQuotaJSONBlock(t *testing.T) {
result := &control.AnalysisResult{
MembersData: &gitlab.GitlabMembersAnalysisData{
Known: true,
Counts: gitlab.MemberCounts{Owners: 4, Maintainers: 1, Developers: 2, Total: 9},
},
}
entry := control.ControlEntry{
DisplayName: "Number of project members must respect a quota",
ControlName: "numberOfProjectMembersMustRespectQuota",
}
findings := []opaengine.Finding{{
Code: "ISSUE-507",
Message: "The project has 4 owners, above the quota maximum of 3.",
Data: map[string]any{
"role": "owner",
"currentCount": 4,
"authorizedMax": 3,
},
}}

name, block := buildLegacyResult(entry, result, nil, findings)
if name != "projectMemberQuotaResult" {
t.Fatalf("507 block name = %q, want projectMemberQuotaResult (dispatch dropped the block)", name)
}
m, ok := block.(map[string]any)
if !ok {
t.Fatalf("507 block is %T, want map[string]any", block)
}
issues, ok := m["issues"].([]map[string]any)
if !ok || len(issues) != 1 {
t.Fatalf("507 issues = %v, want exactly 1 entry", m["issues"])
}
if issues[0]["code"] != "ISSUE-507" {
Comment thread
thomasboni marked this conversation as resolved.
Resolved
t.Errorf("507 issue code = %v, want ISSUE-507", issues[0]["code"])
}
if issues[0]["role"] != "owner" {
t.Errorf("507 issue role = %v, want owner", issues[0]["role"])
}
if fmt.Sprint(issues[0]["currentCount"]) != "4" {
t.Errorf("507 issue currentCount = %v, want 4", issues[0]["currentCount"])
}
if fmt.Sprint(issues[0]["authorizedMax"]) != "3" {
t.Errorf("507 issue authorizedMax = %v, want 3", issues[0]["authorizedMax"])
}
if _, present := issues[0]["authorizedMin"]; present {
t.Errorf("507 issue authorizedMin must be absent, got %v", issues[0]["authorizedMin"])
}
metrics, ok := m["metrics"].(map[string]any)
if !ok {
t.Fatalf("507 metrics is %T, want map[string]any", m["metrics"])
}
if metrics["rolesOutOfQuota"] != 1 || metrics["owners"] != 4 || metrics["total"] != 9 {
t.Fatalf("507 metrics = %v", metrics)
}
if metrics["maintainers"] != 1 {
t.Errorf("507 metrics maintainers = %v, want 1 (got %v)", metrics["maintainers"], metrics)
}
if metrics["developers"] != 2 {
t.Errorf("507 metrics developers = %v, want 2 (got %v)", metrics["developers"], metrics)
}

// The listing was not read (nil MembersData): the count metrics must be
// absent, not zeroed, so a consumer cannot mistake "not evaluated" for a
// clean project.
unreadableName, unreadableBlock := buildLegacyResult(entry, &control.AnalysisResult{}, nil, nil)
if unreadableName != "projectMemberQuotaResult" {
t.Fatalf("507 unreadable: name=%q, want projectMemberQuotaResult", unreadableName)
}
um, ok := unreadableBlock.(map[string]any)
if !ok {
t.Fatalf("507 unreadable block is %T, want map[string]any", unreadableBlock)
}
umetrics := um["metrics"].(map[string]any)
if _, present := umetrics["owners"]; present {
t.Errorf("507 unreadable metrics must omit counts, got %v", umetrics)
}
// rolesOutOfQuota: 0 would read as a clean project when the listing was
// never read (a 403, the page cap), so it is omitted with the counts.
if _, present := umetrics["rolesOutOfQuota"]; present {
t.Errorf("507 unreadable metrics must omit rolesOutOfQuota, got %v", umetrics)
}
notKnown := &control.AnalysisResult{MembersData: &gitlab.GitlabMembersAnalysisData{Known: false}}
_, nkBlock := buildLegacyResult(entry, notKnown, nil, nil)
if _, present := nkBlock.(map[string]any)["metrics"].(map[string]any)["rolesOutOfQuota"]; present {
t.Errorf("507 with Known=false must omit rolesOutOfQuota")
}
}
108 changes: 108 additions & 0 deletions cmd/member_quota_limited_summary_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package cmd

import (
"testing"

"github.com/getplumber/plumber/configuration"
"github.com/getplumber/plumber/control"
"github.com/getplumber/plumber/gitlab"
opaengine "github.com/getplumber/plumber/internal/engine/opa"
"github.com/getplumber/plumber/provider"
)

const quotaTitle = "Number of project members must respect a quota"

func quotaSummaryFor(t *testing.T, result *control.AnalysisResult) (controlSummary, findingGroup) {
t.Helper()
pc := &configuration.PlumberConfig{Version: "2.0", GitLab: &configuration.ProviderConfig{Controls: configuration.ControlsConfig{
NumberOfProjectMembersMustRespectQuota: &configuration.ProjectMemberQuotaControlConfig{Enabled: boolPtr(true), OwnerMax: intPtr(3)},
CicdVariablesMustBeMasked: &configuration.EnabledOnlyControlConfig{Enabled: boolPtr(true)},
}}}
controls, groups := buildProviderControlSummariesAndGroups(&provider.GitLabProvider{}, result, pc, false, nil, nil, false)
var cs controlSummary
var g findingGroup
for _, c := range controls {
if c.name == quotaTitle {
cs = c
}
}
for _, x := range groups {
if x.Title == quotaTitle {
g = x
}
}
return cs, g
}

func intPtr(i int) *int { return &i }

// With an INVALID CI file (CiValid false, CiMissing false) every control used
// to be listed as skipped, so the member quota finding that the limited path
// now produces never reached the terminal. The control whose verdict was
// decided off the pipeline is listed with its finding; another control stays
// skipped, as before.
func TestMemberQuotaShowsInSummaryWithInvalidCI(t *testing.T) {
result := &control.AnalysisResult{
CiValid: false, CiMissing: false,
MembersData: &gitlab.GitlabMembersAnalysisData{Known: true, Counts: gitlab.MemberCounts{Owners: 5, Total: 5}},
Findings: []opaengine.Finding{{Code: "ISSUE-507", Data: map[string]any{
"role": "owner", "currentCount": 5, "authorizedMax": 3,
}}},
}
cs, g := quotaSummaryFor(t, result)
if cs.skipped || g.Skipped {
t.Fatalf("the member quota control was decided on the limited path and must not be listed as skipped")
}
if cs.issues != 1 || len(g.Findings) != 1 {
t.Errorf("want the finding listed, got issues=%d findings=%d", cs.issues, len(g.Findings))
}

pc := &configuration.PlumberConfig{Version: "2.0", GitLab: &configuration.ProviderConfig{Controls: configuration.ControlsConfig{
CicdVariablesMustBeMasked: &configuration.EnabledOnlyControlConfig{Enabled: boolPtr(true)},
}}}
_, groups := buildProviderControlSummariesAndGroups(&provider.GitLabProvider{}, result, pc, false, nil, nil, false)
for _, x := range groups {
if x.Title == "CI/CD variables must be masked" && !x.Skipped {
t.Errorf("a control not decided on the limited path stays skipped on an invalid CI file")
}
}
}

// Same invalid-CI run, counts never read and nothing marked: stays skipped.
func TestMemberQuotaStaysSkippedWhenNotDecidedOnInvalidCI(t *testing.T) {
_, g := quotaSummaryFor(t, &control.AnalysisResult{CiValid: false, CiMissing: false})
if !g.Skipped {
t.Errorf("with no data read and no mark, the control stays skipped on an invalid CI file")
}
}

// Missing CI file: not skipped before either; the finding is listed.
func TestMemberQuotaShowsInSummaryWithMissingCI(t *testing.T) {
result := &control.AnalysisResult{
CiValid: true, CiMissing: true,
MembersData: &gitlab.GitlabMembersAnalysisData{Known: true},
Findings: []opaengine.Finding{{Code: "ISSUE-507", Data: map[string]any{"role": "owner", "currentCount": 5, "authorizedMax": 3}}},
}
cs, g := quotaSummaryFor(t, result)
if cs.skipped || g.Skipped || cs.issues != 1 {
t.Errorf("want listed with its finding, got skipped=%v/%v issues=%d", cs.skipped, g.Skipped, cs.issues)
}
}

// The control carries a not-evaluable reason and its counts were never read
// (the limited path marks it): its row is a decided row, not a skipped one,
// for both a failed collection and a missing bound.
func TestMemberQuotaMarkedNotEvaluableIsNotSkippedOnInvalidCI(t *testing.T) {
for _, reason := range []string{control.ReasonCollectionFailed, control.ReasonConfigRequired} {
t.Run(reason, func(t *testing.T) {
result := &control.AnalysisResult{
CiValid: false, CiMissing: false,
NotEvaluable: map[string]string{"numberOfProjectMembersMustRespectQuota": reason},
}
cs, g := quotaSummaryFor(t, result)
if cs.skipped || g.Skipped {
t.Errorf("a marked control must not be listed as skipped, got skipped=%v/%v", cs.skipped, g.Skipped)
}
})
}
}
27 changes: 27 additions & 0 deletions cmd/render_details.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,21 @@ func mrSettingsUnreadableCaveat(result *control.AnalysisResult) []statLine {
}}
}

// membersUnreadableCaveat returns a single caveat stat line when the member
// listing could not be read (nil MembersData, or Known false from a 403/404,
// the page cap or a degraded snapshot lane). The JSON status is already error
// via StatusFor; this closes the terminal gap so the block never shows a bare
// green pass over counts nobody read. Returns nil when the listing was read.
func membersUnreadableCaveat(result *control.AnalysisResult) []statLine {
if result != nil && result.MembersData != nil && result.MembersData.Known {
return nil
}
return []statLine{{
Label: statCaveatPrefix + " Project members not evaluated",
Value: "the members listing could not be read: token lacks permission, GitLab answered with a server error, the project has more than 2000 members, or the platform could not collect it",
}}
}

// renderSkippedControlsSummary prints the "Skipped Controls" section: a
// top-level section header followed by each skipped control with its
// skip reason.
Expand Down Expand Up @@ -1441,6 +1456,18 @@ func buildGitLabControlStats(controlName string, result *control.AnalysisResult,
return []statLine{
{Label: "Non-Compliant MR Settings", Value: fmt.Sprintf("%d", findingsCount)},
}
case "numberOfProjectMembersMustRespectQuota":
if lines := membersUnreadableCaveat(result); lines != nil {
return lines
}
c := result.MembersData.Counts
return []statLine{
{Label: "Owners", Value: fmt.Sprintf("%d", c.Owners)},
{Label: "Maintainers", Value: fmt.Sprintf("%d", c.Maintainers)},
{Label: "Developers", Value: fmt.Sprintf("%d", c.Developers)},
{Label: "Total Members", Value: fmt.Sprintf("%d", c.Total)},
{Label: "Roles Out Of Quota", Value: fmt.Sprintf("%d", findingsCount)},
}
case "branchMustBeProtected":
total, toProtect, protected, unprotected := _branchProtectionCounts(result, pc)
nonCompliant := 0
Expand Down
Loading