diff --git a/.env.example b/.env.example index 95e7fff..bf95337 100644 --- a/.env.example +++ b/.env.example @@ -56,6 +56,8 @@ APP_OKTA_SYNC_RULES=[{"name":"sync-eng","okta_group_pattern":"^github-eng-.*","s # APP_SECURITY_ALERTS_ENABLED=true # APP_SECURITY_ALERTS_MIN_AGE_DAYS=30 # APP_SECURITY_ALERTS_MIN_SEVERITY=high +# alerts in archived repos are left out unless this is true +# APP_SECURITY_ALERTS_INCLUDE_ARCHIVED_REPOS=false # slack (optional; the token and channel are required together) APP_SLACK_TOKEN=xoxb-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx diff --git a/README.md b/README.md index d44d23c..4bd2cd4 100644 --- a/README.md +++ b/README.md @@ -177,11 +177,12 @@ private key, and rules. ### Security Alerts (optional) -| Variable | Description | -| ---------------------------------- | ------------------------------------------------ | -| `APP_SECURITY_ALERTS_ENABLED` | `true` to enable the report | -| `APP_SECURITY_ALERTS_MIN_AGE_DAYS` | Minimum alert age in days (default: `30`) | -| `APP_SECURITY_ALERTS_MIN_SEVERITY` | `critical`, `high` (default), `medium`, or `low` | +| Variable | Description | +| -------------------------------------------- | ----------------------------------------------------------------- | +| `APP_SECURITY_ALERTS_ENABLED` | `true` to enable the report | +| `APP_SECURITY_ALERTS_MIN_AGE_DAYS` | Minimum alert age in days (default: `30`) | +| `APP_SECURITY_ALERTS_MIN_SEVERITY` | `critical`, `high` (default), `medium`, or `low` | +| `APP_SECURITY_ALERTS_INCLUDE_ARCHIVED_REPOS` | `true` to also report alerts in archived repos (default: `false`) | Code scanning alerts use their security severity, or for rules without one, `error` as high, `warning` as medium, and `note` as low. Secret scanning alerts @@ -354,7 +355,10 @@ pass, as on GitHub. 2. **Fetch**: read every page of open Dependabot, code scanning, and secret scanning alerts in the organization, oldest first 3. **Filter**: keep alerts older than the minimum age at or above the minimum - severity + severity, and leave out those in archived repositories, unless + `APP_SECURITY_ALERTS_INCLUDE_ARCHIVED_REPOS=true`. The report notes how + many it left out. If the repositories can't be listed, it keeps every + alert and shows the error. 4. **Report**: post the alerts by repository to Slack, with any source that failed diff --git a/docs/github-app-setup.md b/docs/github-app-setup.md index f35ab8d..89d6cd2 100644 --- a/docs/github-app-setup.md +++ b/docs/github-app-setup.md @@ -117,16 +117,16 @@ features you use, if you prefer. ### Repository Permissions -| Permission | Access | Used for | -| ---------------------- | ------ | ---------------------------------------------- | -| Administration | Read | PR compliance: branch protection rules | -| Checks | Read | PR compliance: check runs on the merged commit | -| Commit statuses | Read | PR compliance: statuses on the merged commit | -| Metadata | Read | PR compliance: rulesets and merger's role | -| Pull requests | Read | PR compliance: PRs and their reviews | -| Code scanning alerts | Read | Security alerts | -| Dependabot alerts | Read | Security alerts | -| Secret scanning alerts | Read | Security alerts | +| Permission | Access | Used for | +| ---------------------- | ------ | -------------------------------------------------------------------------- | +| Administration | Read | PR compliance: branch protection rules | +| Checks | Read | PR compliance: check runs on the merged commit | +| Commit statuses | Read | PR compliance: statuses on the merged commit | +| Metadata | Read | PR compliance: rulesets and merger's role; security alerts: archived repos | +| Pull requests | Read | PR compliance: PRs and their reviews | +| Code scanning alerts | Read | Security alerts | +| Dependabot alerts | Read | Security alerts | +| Secret scanning alerts | Read | Security alerts | ### Organization Permissions diff --git a/fixtures/scenarios.json b/fixtures/scenarios.json index dca263a..0af5f6e 100644 --- a/fixtures/scenarios.json +++ b/fixtures/scenarios.json @@ -2015,7 +2015,7 @@ }, { "name": "security_alerts_paginated", - "description": "Stale alerts are collected across every page of every source and reported to Slack", + "description": "Stale alerts are collected across every page of every source, those in archived repos are left out, and the rest are reported to Slack", "event_type": "scheduled_event", "event_payload": { "action": "security-alerts" @@ -2061,7 +2061,14 @@ "method": "GET", "path": "/orgs/acme-ghorg/secret-scanning/alerts", "status_code": 200, - "body": "[{\"number\":4,\"created_at\":\"2020-01-01T00:00:00Z\",\"repository\":{\"full_name\":\"acme-ghorg/api\"},\"secret_type_display_name\":\"AWS Access Key\"}]" + "body": "[{\"number\":4,\"created_at\":\"2020-01-01T00:00:00Z\",\"repository\":{\"full_name\":\"acme-ghorg/api\"},\"secret_type_display_name\":\"AWS Access Key\"},{\"number\":5,\"created_at\":\"2020-01-01T00:00:00Z\",\"repository\":{\"full_name\":\"acme-ghorg/legacy\"},\"secret_type_display_name\":\"GitHub Token\"}]" + }, + { + "service": "github", + "method": "GET", + "path": "/orgs/acme-ghorg/repos", + "status_code": 200, + "body": "[{\"full_name\":\"acme-ghorg/api\",\"archived\":false},{\"full_name\":\"acme-ghorg/legacy\",\"archived\":true}]" }, { "service": "slack", @@ -2093,6 +2100,11 @@ "method": "GET", "path": "/orgs/acme-ghorg/secret-scanning/alerts" }, + { + "service": "github", + "method": "GET", + "path": "/orgs/acme-ghorg/repos" + }, { "service": "slack", "method": "POST", diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 2b9c6fc..e58a21c 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -341,9 +341,10 @@ func TestOktaSync_CoalescesConcurrentRequests(t *testing.T) { func TestSecurityAlerts(t *testing.T) { h := newHarness(t, testConfig(), true) - h.github.ListSecurityAlertsFn = func(_ context.Context, days int, sev string) (*domain.SecurityAlertsReport, error) { - if days != 30 || sev != "high" { - t.Errorf("ListSecurityAlerts(%d, %q)", days, sev) + h.github.ListSecurityAlertsFn = func(_ context.Context, query domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) { + want := domain.SecurityAlertsQuery{MinAgeDays: 30, MinSeverity: "high"} + if query != want { + t.Errorf("ListSecurityAlerts(%+v), want %+v", query, want) } return &domain.SecurityAlertsReport{TotalAlerts: 1, AlertsByRepo: map[string][]domain.SecurityAlert{"acme/web": {{CreatedAt: time.Now()}}}}, nil } @@ -355,6 +356,19 @@ func TestSecurityAlerts(t *testing.T) { } cfg := testConfig() + cfg.SecurityAlerts.IncludeArchivedRepos = true + h = newHarness(t, cfg, true) + h.github.ListSecurityAlertsFn = func(_ context.Context, query domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) { + if !query.IncludeArchivedRepos { + t.Error("archived repos not included although configured") + } + return &domain.SecurityAlertsReport{AlertsByRepo: map[string][]domain.SecurityAlert{}}, nil + } + if err := h.app.RunScheduled(context.Background(), ActionSecurityAlerts); err != nil { + t.Fatal(err) + } + + cfg = testConfig() cfg.SecurityAlerts.Enabled = false h = newHarness(t, cfg, true) if err := h.app.RunScheduled(context.Background(), ActionSecurityAlerts); !errors.Is(err, domain.ErrFeatureDisabled) { diff --git a/internal/app/commands_test.go b/internal/app/commands_test.go index 0aeccb0..f1f077f 100644 --- a/internal/app/commands_test.go +++ b/internal/app/commands_test.go @@ -202,7 +202,7 @@ func TestRunJob_SecurityAlerts(t *testing.T) { t.Errorf("reply = %q", h.notifier.LastReply()) } - h.github.ListSecurityAlertsFn = func(context.Context, int, string) (*domain.SecurityAlertsReport, error) { + h.github.ListSecurityAlertsFn = func(context.Context, domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) { return nil, errors.New("github down") } if err := h.app.RunJob(ctx, Job{Action: ActionSecurityAlerts, ResponseURL: responseURL}); err == nil { diff --git a/internal/app/handlers.go b/internal/app/handlers.go index 2f5af0b..b4f3210 100644 --- a/internal/app/handlers.go +++ b/internal/app/handlers.go @@ -392,7 +392,11 @@ func (a *App) runSecurityAlerts(ctx context.Context, requested bool) (*domain.Se return nil, fmt.Errorf("security alerts: %w", domain.ErrFeatureDisabled) } - alerts, err := a.github.ListSecurityAlerts(ctx, a.cfg.SecurityAlerts.MinAgeDays, a.cfg.SecurityAlerts.MinSeverity) + alerts, err := a.github.ListSecurityAlerts(ctx, domain.SecurityAlertsQuery{ + MinAgeDays: a.cfg.SecurityAlerts.MinAgeDays, + MinSeverity: a.cfg.SecurityAlerts.MinSeverity, + IncludeArchivedRepos: a.cfg.SecurityAlerts.IncludeArchivedRepos, + }) if err != nil { return nil, fmt.Errorf("failed to list security alerts for org '%s': %w", a.cfg.GitHub.Org, err) } @@ -403,6 +407,7 @@ func (a *App) runSecurityAlerts(ctx context.Context, requested bool) (*domain.Se a.logger.InfoContext(ctx, "security alerts check completed", "alerts", alerts.TotalAlerts, "repos", alerts.RepoCount(), + "archived_alerts", alerts.ArchivedAlerts, "errors", len(alerts.Errors)) a.postReport(ctx, report{ diff --git a/internal/app/reports_test.go b/internal/app/reports_test.go index 99e6d44..f8582ed 100644 --- a/internal/app/reports_test.go +++ b/internal/app/reports_test.go @@ -132,7 +132,7 @@ func TestReports_DailyEmptyReportIsRemembered(t *testing.T) { }} none := &domain.SecurityAlertsReport{AlertsByRepo: map[string][]domain.SecurityAlert{}} var current *domain.SecurityAlertsReport - h.github.ListSecurityAlertsFn = func(context.Context, int, string) (*domain.SecurityAlertsReport, error) { + h.github.ListSecurityAlertsFn = func(context.Context, domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) { return current, nil } diff --git a/internal/app/samples.go b/internal/app/samples.go index 0b07767..eddcc41 100644 --- a/internal/app/samples.go +++ b/internal/app/samples.go @@ -73,9 +73,10 @@ func sampleOrphanedUsersReport() *domain.OrphanedUsersReport { func sampleSecurityAlertsReport() *domain.SecurityAlertsReport { now := time.Now() return &domain.SecurityAlertsReport{ - MinAgeDays: 30, - MinSeverity: "high", - TotalAlerts: 5, + MinAgeDays: 30, + MinSeverity: "high", + TotalAlerts: 5, + ArchivedAlerts: 2, AlertsByRepo: map[string][]domain.SecurityAlert{ "acme-corp/api-service": { { diff --git a/internal/config/config.go b/internal/config/config.go index c9390c8..19add82 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -195,6 +195,9 @@ type SecurityAlerts struct { Enabled bool MinAgeDays int MinSeverity string + // IncludeArchivedRepos reports alerts in archived repositories, which + // are left out by default. + IncludeArchivedRepos bool } // Slack configures notifications and the slash command. @@ -677,9 +680,10 @@ func (r *reader) okta() Okta { func (r *reader) securityAlerts() SecurityAlerts { s := SecurityAlerts{ - Enabled: r.bool("APP_SECURITY_ALERTS_ENABLED", false), - MinAgeDays: DefaultSecurityAlertsMinAgeDays, - MinSeverity: DefaultSecurityAlertsMinSeverity, + Enabled: r.bool("APP_SECURITY_ALERTS_ENABLED", false), + MinAgeDays: DefaultSecurityAlertsMinAgeDays, + MinSeverity: DefaultSecurityAlertsMinSeverity, + IncludeArchivedRepos: r.bool("APP_SECURITY_ALERTS_INCLUDE_ARCHIVED_REPOS", false), } if v := r.str("APP_SECURITY_ALERTS_MIN_AGE_DAYS"); v != "" { n, err := strconv.Atoi(v) @@ -871,9 +875,10 @@ type RedactedConfig struct { OktaSyncSafetyThreshold float64 `json:"okta_sync_safety_threshold"` OktaOrphanedUserNotifications bool `json:"okta_orphaned_user_notifications"` - SecurityAlertsEnabled bool `json:"security_alerts_enabled"` - SecurityAlertsMinAgeDays int `json:"security_alerts_min_age_days"` - SecurityAlertsMinSeverity string `json:"security_alerts_min_severity"` + SecurityAlertsEnabled bool `json:"security_alerts_enabled"` + SecurityAlertsMinAgeDays int `json:"security_alerts_min_age_days"` + SecurityAlertsMinSeverity string `json:"security_alerts_min_severity"` + SecurityAlertsIncludeArchivedRepos bool `json:"security_alerts_include_archived_repos"` SlackEnabled bool `json:"slack_enabled"` SlackPending bool `json:"slack_pending"` @@ -935,9 +940,10 @@ func (c *Config) Redacted() RedactedConfig { OktaSyncSafetyThreshold: c.Okta.SyncSafetyThreshold, OktaOrphanedUserNotifications: c.Okta.OrphanedUserNotifications, - SecurityAlertsEnabled: c.SecurityAlerts.Enabled, - SecurityAlertsMinAgeDays: c.SecurityAlerts.MinAgeDays, - SecurityAlertsMinSeverity: c.SecurityAlerts.MinSeverity, + SecurityAlertsEnabled: c.SecurityAlerts.Enabled, + SecurityAlertsMinAgeDays: c.SecurityAlerts.MinAgeDays, + SecurityAlertsMinSeverity: c.SecurityAlerts.MinSeverity, + SecurityAlertsIncludeArchivedRepos: c.SecurityAlerts.IncludeArchivedRepos, SlackEnabled: c.Slack.Enabled, SlackPending: c.Slack.Pending, diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 4b39865..0af28e3 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -68,7 +68,7 @@ func TestLoad_Defaults(t *testing.T) { if cfg.Okta.Enabled || cfg.Slack.Enabled || cfg.SecurityAlerts.Enabled || cfg.Installer.Enabled { t.Error("optional feature enabled by default") } - if cfg.SecurityAlerts.MinAgeDays != 30 || cfg.SecurityAlerts.MinSeverity != "high" { + if cfg.SecurityAlerts.MinAgeDays != 30 || cfg.SecurityAlerts.MinSeverity != "high" || cfg.SecurityAlerts.IncludeArchivedRepos { t.Errorf("security alerts = %+v", cfg.SecurityAlerts) } } @@ -76,27 +76,28 @@ func TestLoad_Defaults(t *testing.T) { func TestLoad_AllFeatures(t *testing.T) { rules := `[{"name":"eng","okta_group_pattern":"^eng-","github_team_prefix":"eng-","create_team_if_missing":true,"team_privacy":"secret"}]` cfg, err := load(t, with(map[string]string{ - "APP_LOG_LEVEL": "debug", - "APP_LISTEN_ADDR": "127.0.0.1:9000", - "APP_BASE_PATH": "prod/", - "APP_PUBLIC_URL": "https://ops.example.com/prod/", - "APP_ADMIN_TOKEN": "0123456789abcdef", - "APP_GITHUB_INSTALLATION_ID": "456", - "APP_GITHUB_BASE_URL": "https://ghe.example.com/api/v3/", - "APP_PR_COMPLIANCE_ENABLED": "true", - "APP_PR_MONITORED_BRANCHES": "main, release/* ,", - "APP_OKTA_DOMAIN": "acme.okta.com", - "APP_OKTA_CLIENT_ID": "client", - "APP_OKTA_PRIVATE_KEY": strings.ReplaceAll(testPEM, "\n", `\n`), - "APP_OKTA_SYNC_RULES": rules, - "APP_OKTA_SYNC_SAFETY_THRESHOLD": "0.25", - "APP_OKTA_ORPHANED_USER_NOTIFICATIONS": "false", - "APP_SECURITY_ALERTS_ENABLED": "1", - "APP_SECURITY_ALERTS_MIN_AGE_DAYS": "7", - "APP_SECURITY_ALERTS_MIN_SEVERITY": "CRITICAL", - "APP_SLACK_TOKEN": "xoxb-1", - "APP_SLACK_CHANNEL": "C1", - "APP_SLACK_API_URL": "https://slack.test/api", + "APP_LOG_LEVEL": "debug", + "APP_LISTEN_ADDR": "127.0.0.1:9000", + "APP_BASE_PATH": "prod/", + "APP_PUBLIC_URL": "https://ops.example.com/prod/", + "APP_ADMIN_TOKEN": "0123456789abcdef", + "APP_GITHUB_INSTALLATION_ID": "456", + "APP_GITHUB_BASE_URL": "https://ghe.example.com/api/v3/", + "APP_PR_COMPLIANCE_ENABLED": "true", + "APP_PR_MONITORED_BRANCHES": "main, release/* ,", + "APP_OKTA_DOMAIN": "acme.okta.com", + "APP_OKTA_CLIENT_ID": "client", + "APP_OKTA_PRIVATE_KEY": strings.ReplaceAll(testPEM, "\n", `\n`), + "APP_OKTA_SYNC_RULES": rules, + "APP_OKTA_SYNC_SAFETY_THRESHOLD": "0.25", + "APP_OKTA_ORPHANED_USER_NOTIFICATIONS": "false", + "APP_SECURITY_ALERTS_ENABLED": "1", + "APP_SECURITY_ALERTS_MIN_AGE_DAYS": "7", + "APP_SECURITY_ALERTS_MIN_SEVERITY": "CRITICAL", + "APP_SECURITY_ALERTS_INCLUDE_ARCHIVED_REPOS": "true", + "APP_SLACK_TOKEN": "xoxb-1", + "APP_SLACK_CHANNEL": "C1", + "APP_SLACK_API_URL": "https://slack.test/api", })) if err != nil { t.Fatal(err) @@ -114,7 +115,7 @@ func TestLoad_AllFeatures(t *testing.T) { if len(cfg.Okta.SyncRules) != 1 || !cfg.Okta.SyncRules[0].CreateTeamIfMissing { t.Errorf("rules = %+v", cfg.Okta.SyncRules) } - if cfg.SecurityAlerts.MinAgeDays != 7 || cfg.SecurityAlerts.MinSeverity != "critical" { + if cfg.SecurityAlerts.MinAgeDays != 7 || cfg.SecurityAlerts.MinSeverity != "critical" || !cfg.SecurityAlerts.IncludeArchivedRepos { t.Errorf("security alerts = %+v", cfg.SecurityAlerts) } if !cfg.Slack.Enabled || cfg.Slack.APIURL != "https://slack.test/api/" { diff --git a/internal/domain/interfaces.go b/internal/domain/interfaces.go index 572c650..9740ace 100644 --- a/internal/domain/interfaces.go +++ b/internal/domain/interfaces.go @@ -26,10 +26,10 @@ type GitHubClient interface { // GetAppSlug returns the GitHub App's slug. GetAppSlug(ctx context.Context) (string, error) - // ListSecurityAlerts fetches open security alerts across the org that - // are older than minAgeDays and at or above minSeverity. It covers - // dependabot, code scanning, and secret scanning alerts. - ListSecurityAlerts(ctx context.Context, minAgeDays int, minSeverity string) (*SecurityAlertsReport, error) + // ListSecurityAlerts fetches the open security alerts across the org + // that match query. It covers dependabot, code scanning, and secret + // scanning alerts. + ListSecurityAlerts(ctx context.Context, query SecurityAlertsQuery) (*SecurityAlertsReport, error) } // OktaClient defines the Okta API operations the application uses. diff --git a/internal/domain/types.go b/internal/domain/types.go index c903c21..39fec08 100644 --- a/internal/domain/types.go +++ b/internal/domain/types.go @@ -286,13 +286,26 @@ type SecurityAlert struct { AgeDays int } +// SecurityAlertsQuery selects the alerts in a security alerts report. +type SecurityAlertsQuery struct { + // MinAgeDays is the age in days an alert must be older than. + MinAgeDays int + // MinSeverity is the lowest severity reported. + MinSeverity string + // IncludeArchivedRepos reports alerts in archived repositories too. + IncludeArchivedRepos bool +} + // SecurityAlertsReport contains stale security alerts grouped by repo. type SecurityAlertsReport struct { MinAgeDays int MinSeverity string TotalAlerts int AlertsByRepo map[string][]SecurityAlert - Errors []string + // ArchivedAlerts counts the alerts left out because their repository + // is archived. + ArchivedAlerts int + Errors []string } // HasAlerts returns true if any stale alerts were found. diff --git a/internal/fakes/fakes.go b/internal/fakes/fakes.go index 652c096..96f7169 100644 --- a/internal/fakes/fakes.go +++ b/internal/fakes/fakes.go @@ -45,7 +45,7 @@ type GitHub struct { GetTeamMembersFn func(ctx context.Context, teamSlug string) ([]string, error) ListOrgMembersFn func(ctx context.Context) ([]string, error) GetAppSlugFn func(ctx context.Context) (string, error) - ListSecurityAlertsFn func(ctx context.Context, minAgeDays int, minSeverity string) (*domain.SecurityAlertsReport, error) + ListSecurityAlertsFn func(ctx context.Context, query domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) } var _ domain.GitHubClient = (*GitHub)(nil) @@ -98,14 +98,14 @@ func (f *GitHub) GetAppSlug(ctx context.Context) (string, error) { return "ops-app", nil } -func (f *GitHub) ListSecurityAlerts(ctx context.Context, minAgeDays int, minSeverity string) (*domain.SecurityAlertsReport, error) { +func (f *GitHub) ListSecurityAlerts(ctx context.Context, query domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) { f.record("ListSecurityAlerts") if f.ListSecurityAlertsFn != nil { - return f.ListSecurityAlertsFn(ctx, minAgeDays, minSeverity) + return f.ListSecurityAlertsFn(ctx, query) } return &domain.SecurityAlertsReport{ - MinAgeDays: minAgeDays, - MinSeverity: minSeverity, + MinAgeDays: query.MinAgeDays, + MinSeverity: query.MinSeverity, AlertsByRepo: map[string][]domain.SecurityAlert{}, }, nil } diff --git a/internal/github/client/client_test.go b/internal/github/client/client_test.go index 5d9202d..2c90f26 100644 --- a/internal/github/client/client_test.go +++ b/internal/github/client/client_test.go @@ -498,9 +498,10 @@ func TestListSecurityAlerts_PaginatesAndFilters(t *testing.T) { }) }) f.json("GET /orgs/acme/secret-scanning/alerts", http.StatusForbidden, map[string]any{"message": "Advanced Security is not enabled"}) + f.json("GET /orgs/acme/repos", http.StatusOK, []map[string]any{{"full_name": "acme/web"}}) c := f.client(t, 1) - report, err := c.ListSecurityAlerts(context.Background(), 30, domain.SeverityHigh) + report, err := c.ListSecurityAlerts(context.Background(), domain.SecurityAlertsQuery{MinAgeDays: 30, MinSeverity: domain.SeverityHigh}) if err != nil { t.Fatal(err) } @@ -523,7 +524,7 @@ func TestListSecurityAlerts_SkipsSecretScanningBelowSeverity(t *testing.T) { f.json("GET /orgs/acme/code-scanning/alerts", http.StatusOK, []any{}) c := f.client(t, 1) - if _, err := c.ListSecurityAlerts(context.Background(), 30, domain.SeverityCritical); err != nil { + if _, err := c.ListSecurityAlerts(context.Background(), domain.SecurityAlertsQuery{MinAgeDays: 30, MinSeverity: domain.SeverityCritical}); err != nil { t.Fatal(err) } if f.called("GET /orgs/acme/secret-scanning/alerts") != 0 { @@ -531,6 +532,110 @@ func TestListSecurityAlerts_SkipsSecretScanningBelowSeverity(t *testing.T) { } } +func TestListSecurityAlerts_ArchivedRepos(t *testing.T) { + old := time.Now().AddDate(0, 0, -90).UTC().Format(time.RFC3339) + alert := func(n int, repo string) map[string]any { + return map[string]any{"number": n, "created_at": old, "repository": map[string]any{"full_name": repo}, "security_advisory": map[string]any{"severity": "critical"}} + } + + tests := []struct { + name string + alerts []map[string]any + include bool + reposStatus int + wantNumbers string + wantArchived int + wantRepoList int + wantErr string + }{ + { + name: "archived repos are left out", + alerts: []map[string]any{alert(1, "acme/web"), alert(2, "acme/old"), alert(3, "acme/Legacy")}, + reposStatus: http.StatusOK, + wantNumbers: "[1]", + wantArchived: 2, + wantRepoList: 2, + }, + { + name: "included when asked", + alerts: []map[string]any{alert(1, "acme/web"), alert(2, "acme/old")}, + include: true, + reposStatus: http.StatusOK, + wantNumbers: "[1 2]", + }, + { + name: "every alert is kept when the repos can't be listed", + alerts: []map[string]any{alert(1, "acme/web"), alert(2, "acme/old")}, + reposStatus: http.StatusInternalServerError, + wantNumbers: "[1 2]", + wantRepoList: 1, + wantErr: "to leave out archived ones", + }, + { + name: "no lookup without alerts", + reposStatus: http.StatusOK, + wantNumbers: "[]", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newFakeGitHub(t) + f.json("GET /orgs/acme/dependabot/alerts", http.StatusOK, append([]map[string]any{}, tt.alerts...)) + f.json("GET /orgs/acme/code-scanning/alerts", http.StatusOK, []any{}) + f.json("GET /orgs/acme/secret-scanning/alerts", http.StatusOK, []any{}) + // two pages, with the archived repos on the second + f.handle("GET /orgs/acme/repos", func(w http.ResponseWriter, r *http.Request) { + if tt.reposStatus != http.StatusOK { + writeJSON(w, tt.reposStatus, map[string]any{"message": "boom"}) + return + } + if r.URL.Query().Get("page") == "" { + nextLink(w, r, "page=2&per_page=100") + writeJSON(w, http.StatusOK, []map[string]any{{"full_name": "acme/web", "archived": false}}) + return + } + writeJSON(w, http.StatusOK, []map[string]any{ + {"full_name": "acme/old", "archived": true}, + {"full_name": "acme/legacy", "archived": true}, + }) + }) + c := f.client(t, 1) + + report, err := c.ListSecurityAlerts(context.Background(), domain.SecurityAlertsQuery{ + MinAgeDays: 30, + MinSeverity: domain.SeverityHigh, + IncludeArchivedRepos: tt.include, + }) + if err != nil { + t.Fatal(err) + } + + numbers := []int{} + for _, repo := range []string{"acme/web", "acme/old", "acme/Legacy"} { + for _, a := range report.AlertsByRepo[repo] { + numbers = append(numbers, a.Number) + } + } + if fmt.Sprint(numbers) != tt.wantNumbers || report.TotalAlerts != len(numbers) { + t.Errorf("alerts = %v (total %d), want %s", numbers, report.TotalAlerts, tt.wantNumbers) + } + if report.ArchivedAlerts != tt.wantArchived { + t.Errorf("archived alerts = %d, want %d", report.ArchivedAlerts, tt.wantArchived) + } + if got := f.called("GET /orgs/acme/repos"); got != tt.wantRepoList { + t.Errorf("repo list requests = %d, want %d", got, tt.wantRepoList) + } + if tt.wantErr == "" && len(report.Errors) != 0 { + t.Errorf("errors = %v, want none", report.Errors) + } + if tt.wantErr != "" && (len(report.Errors) != 1 || !strings.Contains(report.Errors[0], tt.wantErr)) { + t.Errorf("errors = %v, want %q", report.Errors, tt.wantErr) + } + }) + } +} + func TestResolveTeam(t *testing.T) { t.Run("existing team", func(t *testing.T) { f := newFakeGitHub(t) diff --git a/internal/github/client/security_alerts.go b/internal/github/client/security_alerts.go index 502c6c1..7a4d0ea 100644 --- a/internal/github/client/security_alerts.go +++ b/internal/github/client/security_alerts.go @@ -35,32 +35,43 @@ var codeScanningRuleSeverity = map[string]string{ "note": domain.SeverityLow, } -// ListSecurityAlerts fetches open security alerts across the org that were -// created more than minAgeDays ago and are at or above minSeverity. It -// covers dependabot, code scanning, and secret scanning alerts. A source that -// fails is recorded in the report's errors and the others still run. -func (c *Client) ListSecurityAlerts(ctx context.Context, minAgeDays int, minSeverity string) (*domain.SecurityAlertsReport, error) { +// ListSecurityAlerts fetches the open security alerts across the org that +// were created more than query.MinAgeDays ago and are at or above +// query.MinSeverity, leaving out those in archived repositories unless +// query.IncludeArchivedRepos is set. It covers dependabot, code scanning, +// and secret scanning alerts. A source that fails is recorded in the +// report's errors and the others still run. +func (c *Client) ListSecurityAlerts(ctx context.Context, query domain.SecurityAlertsQuery) (*domain.SecurityAlertsReport, error) { now := time.Now() - cutoff := now.AddDate(0, 0, -minAgeDays) + cutoff := now.AddDate(0, 0, -query.MinAgeDays) report := &domain.SecurityAlertsReport{ - MinAgeDays: minAgeDays, - MinSeverity: minSeverity, + MinAgeDays: query.MinAgeDays, + MinSeverity: query.MinSeverity, AlertsByRepo: make(map[string][]domain.SecurityAlert), } - add := func(alert domain.SecurityAlert) { - alert.AgeDays = int(now.Sub(alert.CreatedAt).Hours() / 24) - alert.Summary = truncate(alert.Summary, maxSummaryLen) - report.AlertsByRepo[alert.Repo] = append(report.AlertsByRepo[alert.Repo], alert) - report.TotalAlerts++ - } + var alerts []domain.SecurityAlert + add := func(alert domain.SecurityAlert) { alerts = append(alerts, alert) } for _, fetch := range []func(context.Context, time.Time, string, func(domain.SecurityAlert)) error{ c.fetchDependabotAlerts, c.fetchCodeScanningAlerts, c.fetchSecretScanningAlerts, } { - if err := fetch(ctx, cutoff, minSeverity, add); err != nil { + if err := fetch(ctx, cutoff, query.MinSeverity, add); err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + report.Errors = append(report.Errors, err.Error()) + } + } + + // without the archived repositories, every alert is reported, so a + // failed lookup can't hide one + var archived map[string]bool + if !query.IncludeArchivedRepos && len(alerts) > 0 { + var err error + if archived, err = c.archivedRepos(ctx); err != nil { if ctx.Err() != nil { return nil, ctx.Err() } @@ -68,9 +79,39 @@ func (c *Client) ListSecurityAlerts(ctx context.Context, minAgeDays int, minSeve } } + for _, alert := range alerts { + if archived[strings.ToLower(alert.Repo)] { + report.ArchivedAlerts++ + continue + } + alert.AgeDays = int(now.Sub(alert.CreatedAt).Hours() / 24) + alert.Summary = truncate(alert.Summary, maxSummaryLen) + report.AlertsByRepo[alert.Repo] = append(report.AlertsByRepo[alert.Repo], alert) + report.TotalAlerts++ + } + return report, nil } +// archivedRepos returns the lowercased full names of the org's archived +// repositories. Alerts don't say whether their repository is archived. +func (c *Client) archivedRepos(ctx context.Context) (map[string]bool, error) { + opts := &github.RepositoryListByOrgOptions{ + Type: "all", + ListOptions: github.ListOptions{PerPage: 100}, + } + archived := map[string]bool{} + for repo, err := range c.gh.Repositories.ListByOrgIter(ctx, c.org, opts) { + if err != nil { + return nil, fmt.Errorf("failed to list repositories in org '%s' to leave out archived ones: %w", c.org, err) + } + if repo.GetArchived() { + archived[strings.ToLower(repo.GetFullName())] = true + } + } + return archived, nil +} + // The fetchers below request alerts oldest first, so they stop paging at // the first alert created after the cutoff. diff --git a/internal/notifiers/slack_messages.go b/internal/notifiers/slack_messages.go index 3ca4031..66dc4ce 100644 --- a/internal/notifiers/slack_messages.go +++ b/internal/notifiers/slack_messages.go @@ -192,8 +192,11 @@ func (s *SlackNotifier) NotifySecurityAlerts(ctx context.Context, report *domain } blocks = append(blocks, listSections("*Errors:*", errs)...) - blocks = append(blocks, slack.NewContextBlock("context", mrkdwn(fmt.Sprintf( - "Open alerts older than %d days with severity %s or above", report.MinAgeDays, Escape(report.MinSeverity))))) + footer := fmt.Sprintf("Open alerts older than %d days with severity %s or above", report.MinAgeDays, Escape(report.MinSeverity)) + if report.ArchivedAlerts > 0 { + footer += fmt.Sprintf("; %d more in archived repositories not shown", report.ArchivedAlerts) + } + blocks = append(blocks, slack.NewContextBlock("context", mrkdwn(footer))) err := s.post(ctx, s.channelFor(s.channels.SecurityAlerts), fmt.Sprintf("Security alerts: %d open alerts across %d repos in %s", report.TotalAlerts, report.RepoCount(), githubOrg), blocks) diff --git a/internal/notifiers/slack_test.go b/internal/notifiers/slack_test.go index e1f63c7..46dbf5d 100644 --- a/internal/notifiers/slack_test.go +++ b/internal/notifiers/slack_test.go @@ -209,7 +209,8 @@ func TestNotifySecurityAlerts(t *testing.T) { "acme/api": {{Severity: "high"}}, "acme/web": {{Severity: "high"}, {Severity: "critical", CreatedAt: time.Now()}}, }, - Errors: []string{"failed to fetch secret scanning alerts"}, + ArchivedAlerts: 2, + Errors: []string{"failed to fetch secret scanning alerts"}, } if err := n.NotifySecurityAlerts(context.Background(), report, "acme"); err != nil { t.Fatal(err) @@ -220,7 +221,7 @@ func TestNotifySecurityAlerts(t *testing.T) { if web < 0 || api < 0 || web > api { t.Errorf("repos not listed by alert count: %s", text) } - for _, want := range []string{"https://ghe.example.com/acme/web/security", "2 alert(s), critical severity", "secret scanning"} { + for _, want := range []string{"https://ghe.example.com/acme/web/security", "2 alert(s), critical severity", "secret scanning", "2 more in archived repositories not shown"} { if !strings.Contains(text, want) { t.Errorf("message lacks %q: %s", want, text) } @@ -236,6 +237,9 @@ func TestNotifySecurityAlerts_ErrorsOnly(t *testing.T) { if len(msgs()) != 1 || !strings.Contains(msgs()[0].allText(), "forbidden") { t.Error("report with only errors was not posted") } + if strings.Contains(msgs()[0].allText(), "archived") { + t.Error("message mentions archived repositories although none were left out") + } } func TestChannelFor(t *testing.T) {