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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
20 changes: 10 additions & 10 deletions docs/github-app-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 14 additions & 2 deletions fixtures/scenarios.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
20 changes: 17 additions & 3 deletions internal/app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion internal/app/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 6 additions & 1 deletion internal/app/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion internal/app/reports_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
7 changes: 4 additions & 3 deletions internal/app/samples.go
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
{
Expand Down
24 changes: 15 additions & 9 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"`
Expand Down Expand Up @@ -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,
Expand Down
47 changes: 24 additions & 23 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,35 +68,36 @@ 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)
}
}

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)
Expand All @@ -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/" {
Expand Down
8 changes: 4 additions & 4 deletions internal/domain/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 14 additions & 1 deletion internal/domain/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions internal/fakes/fakes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
Loading