From 66fd5c5e8fddad063f00806c74c1da3f172fe3e7 Mon Sep 17 00:00:00 2001 From: Brian Ojeda <9335829+sgtoj@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:14:35 -0500 Subject: [PATCH 1/2] feat: add a slack setup page, slash command resync, and daily reports Slack setup: - /slack/setup creates the Slack app from a manifest, with an app configuration token or by hand, runs the OAuth install, and saves the token and signing secret where the GitHub App installer saves its credentials (env file or SSM), then reloads the configuration - it never replaces an installed app's credentials or moves it to another workspace; while it is enabled, missing Slack credentials leave Slack off instead of failing to load Slash command: - /github-ops sync and /github-ops security-alerts run the action after answering Slack, post the report even if unchanged, and reply to who asked with a summary - requests are signature-checked; only APP_SLACK_COMMAND_ALLOWED_USERS may run actions, and replies leave out error details - the server runs jobs in the background; Lambda invokes itself asynchronously, and doesn't fail (so retry) a job that already replied Reports: - APP_REPORT_REPEAT=daily posts a report when the run changed team members or the report differs from the last one posted, and otherwise once a day at the first run after APP_REPORT_DAILY_TIME - alert ages and error text don't count as changes; empty reports never post but are remembered - what each report last posted is kept in SSM (APP_STATE_SSM_PREFIX, required in Lambda), a file, or memory Co-Authored-By: Claude Opus 5.5 --- assets/assets.go | 9 + cmd/lambda/handler.go | 70 ++++- cmd/lambda/handler_test.go | 66 ++++ cmd/lambda/main.go | 27 +- go.mod | 8 +- go.sum | 4 + internal/app/app.go | 77 ++++- internal/app/commands.go | 257 +++++++++++++++ internal/app/commands_test.go | 258 +++++++++++++++ internal/app/handlers.go | 165 ++++++---- internal/app/http.go | 2 + internal/app/reports.go | 185 +++++++++++ internal/app/reports_test.go | 242 ++++++++++++++ internal/config/config.go | 302 +++++++++++++++--- internal/config/config_test.go | 146 ++++++++- internal/domain/interfaces.go | 15 + internal/fakes/fakes.go | 33 ++ internal/notifiers/slack.go | 41 ++- internal/notifiers/slack_messages.go | 24 +- internal/notifiers/slack_test.go | 29 +- internal/service/service.go | 107 ++++++- internal/service/service_test.go | 107 +++++++ internal/slackapp/api.go | 123 ++++++++ internal/slackapp/manifest.go | 59 ++++ internal/slackapp/setup.go | 450 +++++++++++++++++++++++++++ internal/slackapp/setup_test.go | 421 +++++++++++++++++++++++++ internal/slackapp/store.go | 209 +++++++++++++ internal/slackapp/template.go | 132 ++++++++ internal/state/state.go | 198 ++++++++++++ internal/state/state_test.go | 121 +++++++ 30 files changed, 3738 insertions(+), 149 deletions(-) create mode 100644 assets/assets.go create mode 100644 internal/app/commands.go create mode 100644 internal/app/commands_test.go create mode 100644 internal/app/reports.go create mode 100644 internal/app/reports_test.go create mode 100644 internal/slackapp/api.go create mode 100644 internal/slackapp/manifest.go create mode 100644 internal/slackapp/setup.go create mode 100644 internal/slackapp/setup_test.go create mode 100644 internal/slackapp/store.go create mode 100644 internal/slackapp/template.go create mode 100644 internal/state/state.go create mode 100644 internal/state/state_test.go diff --git a/assets/assets.go b/assets/assets.go new file mode 100644 index 0000000..4ab798c --- /dev/null +++ b/assets/assets.go @@ -0,0 +1,9 @@ +// Package assets holds files built into the binary. +package assets + +import _ "embed" + +// SlackIcon is the Slack app's icon, a 1024x1024 PNG. +// +//go:embed slack/icon.png +var SlackIcon []byte diff --git a/cmd/lambda/handler.go b/cmd/lambda/handler.go index d9e7cc6..c616bd7 100644 --- a/cmd/lambda/handler.go +++ b/cmd/lambda/handler.go @@ -14,16 +14,22 @@ import ( "unicode/utf8" awsevents "github.com/aws/aws-lambda-go/events" + "github.com/aws/aws-lambda-go/lambdacontext" + "github.com/aws/aws-sdk-go-v2/aws" + awslambda "github.com/aws/aws-sdk-go-v2/service/lambda" + lambdatypes "github.com/aws/aws-sdk-go-v2/service/lambda/types" + + "github.com/cruxstack/github-ops-app/internal/app" ) -// scheduler runs scheduled actions. -type scheduler interface { - RunScheduled(ctx context.Context, action string) error -} +// jobKey is the key of the job in the event that runs a job started from +// Slack. +const jobKey = "github_ops_app_job" // backend is what the Lambda handler needs from service.Service. type backend interface { - scheduler + RunScheduled(ctx context.Context, action string) error + RunJob(ctx context.Context, job app.Job) error Handler() http.Handler } @@ -38,6 +44,7 @@ func newHandler(svc backend, logger *slog.Logger) *handler { // event holds the fields that tell the supported event types apart. type event struct { + Job *app.Job `json:"github_ops_app_job"` RequestContext struct { HTTP struct { Method string `json:"method"` @@ -61,6 +68,10 @@ func (h *handler) invoke(ctx context.Context, raw json.RawMessage) (any, error) } switch { + case e.Job != nil: + h.runJob(ctx, *e.Job) + return nil, nil + case e.RequestContext.HTTP.Method != "": var req awsevents.APIGatewayV2HTTPRequest if err := json.Unmarshal(raw, &req); err != nil { @@ -76,7 +87,7 @@ func (h *handler) invoke(ctx context.Context, raw json.RawMessage) (any, error) return nil, h.runScheduled(ctx, evt) default: - return nil, errors.New("unsupported lambda event: expected an api gateway http api (2.0) request or an eventbridge event") + return nil, errors.New("unsupported lambda event: expected an api gateway http api (2.0) request, an eventbridge event, or a job") } } @@ -98,6 +109,53 @@ func (h *handler) runScheduled(ctx context.Context, evt awsevents.CloudWatchEven return nil } +// runJob runs a job started from Slack. A failure is logged, not returned: +// the job already told who asked, and lambda would retry it. +func (h *handler) runJob(ctx context.Context, job app.Job) { + if err := h.svc.RunJob(ctx, job); err != nil { + h.logger.ErrorContext(ctx, "job requested in slack failed", + "action", job.Action, + "slack_user", job.SlackUser, + "error", err.Error()) + } +} + +// invoker is the part of the Lambda API the dispatcher uses. +type invoker interface { + Invoke(ctx context.Context, in *awslambda.InvokeInput, opts ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) +} + +// newDispatcher returns an app.Dispatcher that runs each job in an +// asynchronous invocation of this function, since an invocation ends when +// it responds to Slack. client returns the Lambda client, which is created +// on first use. +func newDispatcher(client func(ctx context.Context) (invoker, error)) app.Dispatcher { + return func(ctx context.Context, job app.Job) error { + lc, ok := lambdacontext.FromContext(ctx) + if !ok || lc.InvokedFunctionArn == "" { + return errors.New("failed to dispatch job: not running in a lambda invocation") + } + c, err := client(ctx) + if err != nil { + return fmt.Errorf("failed to dispatch job '%s': %w", job.Action, err) + } + payload, err := json.Marshal(map[string]app.Job{jobKey: job}) + if err != nil { + return fmt.Errorf("failed to encode job '%s': %w", job.Action, err) + } + _, err = c.Invoke(ctx, &awslambda.InvokeInput{ + // the invoked arn names the same version or alias + FunctionName: aws.String(lc.InvokedFunctionArn), + InvocationType: lambdatypes.InvocationTypeEvent, + Payload: payload, + }) + if err != nil { + return fmt.Errorf("failed to invoke %s for job '%s': %w", lc.InvokedFunctionArn, job.Action, err) + } + return nil + } +} + // serveHTTP passes an API Gateway request through the HTTP handler. func (h *handler) serveHTTP(ctx context.Context, e awsevents.APIGatewayV2HTTPRequest) awsevents.APIGatewayV2HTTPResponse { req, err := toHTTPRequest(ctx, e) diff --git a/cmd/lambda/handler_test.go b/cmd/lambda/handler_test.go index ed30d79..812edaf 100644 --- a/cmd/lambda/handler_test.go +++ b/cmd/lambda/handler_test.go @@ -10,11 +10,19 @@ import ( "net/http" "strings" "testing" + + "github.com/aws/aws-lambda-go/lambdacontext" + "github.com/aws/aws-sdk-go-v2/aws" + awslambda "github.com/aws/aws-sdk-go-v2/service/lambda" + lambdatypes "github.com/aws/aws-sdk-go-v2/service/lambda/types" + + "github.com/cruxstack/github-ops-app/internal/app" ) type fakeService struct { handler http.HandlerFunc actions []string + jobs []app.Job actionErr error } @@ -25,6 +33,11 @@ func (f *fakeService) RunScheduled(_ context.Context, action string) error { return f.actionErr } +func (f *fakeService) RunJob(_ context.Context, job app.Job) error { + f.jobs = append(f.jobs, job) + return f.actionErr +} + func invoke(t *testing.T, svc *fakeService, event string) (any, error) { t.Helper() h := newHandler(svc, slog.New(slog.DiscardHandler)) @@ -130,3 +143,56 @@ func TestInvoke_Unsupported(t *testing.T) { t.Error("invalid json returned no error") } } + +func TestInvoke_Job(t *testing.T) { + svc := &fakeService{actionErr: errors.New("sync failed")} + event := `{"github_ops_app_job":{"action":"okta-sync","slack_user":"U1","response_url":"https://hooks.slack.com/x"}}` + // a failed job isn't returned, so lambda doesn't retry it + if _, err := invoke(t, svc, event); err != nil { + t.Fatal(err) + } + want := app.Job{Action: "okta-sync", SlackUser: "U1", ResponseURL: "https://hooks.slack.com/x"} + if len(svc.jobs) != 1 || svc.jobs[0] != want { + t.Errorf("jobs = %+v", svc.jobs) + } +} + +type fakeInvoker struct { + in *awslambda.InvokeInput + err error +} + +func (f *fakeInvoker) Invoke(_ context.Context, in *awslambda.InvokeInput, _ ...func(*awslambda.Options)) (*awslambda.InvokeOutput, error) { + f.in = in + return &awslambda.InvokeOutput{}, f.err +} + +func TestDispatcher(t *testing.T) { + inv := &fakeInvoker{} + dispatch := newDispatcher(func(context.Context) (invoker, error) { return inv, nil }) + job := app.Job{Action: "okta-sync", SlackUser: "U1"} + + if err := dispatch(context.Background(), job); err == nil { + t.Error("dispatched outside a lambda invocation") + } + + arn := "arn:aws:lambda:us-east-1:123456789012:function:ops:live" + ctx := lambdacontext.NewContext(context.Background(), &lambdacontext.LambdaContext{InvokedFunctionArn: arn}) + if err := dispatch(ctx, job); err != nil { + t.Fatal(err) + } + if aws.ToString(inv.in.FunctionName) != arn || inv.in.InvocationType != lambdatypes.InvocationTypeEvent { + t.Errorf("invoke input = %+v", inv.in) + } + + // the payload is an event the handler runs as a job + svc := &fakeService{} + if _, err := invoke(t, svc, string(inv.in.Payload)); err != nil || len(svc.jobs) != 1 || svc.jobs[0] != job { + t.Errorf("payload %s ran jobs %+v, err %v", inv.in.Payload, svc.jobs, err) + } + + inv.err = errors.New("AccessDenied") + if err := dispatch(ctx, job); err == nil { + t.Error("failed invoke returned no error") + } +} diff --git a/cmd/lambda/main.go b/cmd/lambda/main.go index 7363731..6db8226 100644 --- a/cmd/lambda/main.go +++ b/cmd/lambda/main.go @@ -1,15 +1,21 @@ // Command lambda runs github-ops-app as an AWS Lambda function. It handles // API Gateway HTTP API (payload format 2.0) requests, which carry GitHub -// webhooks and admin requests, and EventBridge events, which run scheduled -// actions. +// webhooks, Slack commands, and admin requests; EventBridge events, which +// run scheduled actions; and its own asynchronous invocations, which run +// jobs started from Slack. package main import ( + "context" "log/slog" "os" + "sync" "github.com/aws/aws-lambda-go/lambda" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + awslambda "github.com/aws/aws-sdk-go-v2/service/lambda" + "github.com/cruxstack/github-ops-app/internal/app" "github.com/cruxstack/github-ops-app/internal/config" "github.com/cruxstack/github-ops-app/internal/service" ) @@ -31,7 +37,22 @@ func main() { // the application configuration loads on the first invocation, and is // retried on later ones until it succeeds - svc, err := service.New(boot, service.Options{Mode: service.ModeLambda, Logger: logger}) + var newClient sync.Once + var client invoker + var clientErr error + dispatcher := newDispatcher(func(ctx context.Context) (invoker, error) { + newClient.Do(func() { + cfg, err := awsconfig.LoadDefaultConfig(ctx) + client, clientErr = awslambda.NewFromConfig(cfg), err + }) + return client, clientErr + }) + + svc, err := service.New(boot, service.Options{ + Mode: service.ModeLambda, + Logger: logger, + AppOptions: []app.Option{app.WithDispatcher(dispatcher)}, + }) if err != nil { logger.Error("failed to create service", "version", version, "error", err.Error()) os.Exit(1) diff --git a/go.mod b/go.mod index f26b65d..19ebc0e 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,10 @@ go 1.27.3 require ( github.com/aws/aws-lambda-go v1.55.1 + github.com/aws/aws-sdk-go-v2 v1.47.8 + github.com/aws/aws-sdk-go-v2/config v1.33.16 + github.com/aws/aws-sdk-go-v2/service/lambda v1.114.3 + github.com/aws/aws-sdk-go-v2/service/ssm v1.82.0 github.com/cruxstack/github-app-setup-go v0.7.1 github.com/go-chi/chi/v5 v5.5.0 github.com/golang-jwt/jwt/v5 v5.3.1 @@ -14,8 +18,7 @@ require ( ) require ( - github.com/aws/aws-sdk-go-v2 v1.47.8 // indirect - github.com/aws/aws-sdk-go-v2/config v1.33.16 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.26 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.20.16 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.8 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.11 // indirect @@ -24,7 +27,6 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.24 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.11 // indirect github.com/aws/aws-sdk-go-v2/service/signin v1.12.4 // indirect - github.com/aws/aws-sdk-go-v2/service/ssm v1.82.0 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.39.4 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.4 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.51.9 // indirect diff --git a/go.sum b/go.sum index d57f481..6c95831 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ github.com/aws/aws-lambda-go v1.55.1 h1:We2cCp4BwqqH/JW+bEEo1FhgG71rslvjfi4y7Kml github.com/aws/aws-lambda-go v1.55.1/go.mod h1:V+NzkHNR6vBC8C1PDloqSLE+7jYWFiPvJJFiCiTm8nE= github.com/aws/aws-sdk-go-v2 v1.47.8 h1:fuClo7Un+Bi0EDTnSIPWxVEoJcze+wkGzNA4Vo3jRcQ= github.com/aws/aws-sdk-go-v2 v1.47.8/go.mod h1:I8lFSH4MGrZiw2m7miCrRYHsgpC1+HW8uiVGOiPYPcw= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.26 h1:SJNA4XaM8Z09adeTHf/vME93jzl44lJV70pSawIBXac= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.26/go.mod h1:l0ME5pd2QytH8UZzETcrt90x9Bm+3TyBVeWfVEcZ82c= github.com/aws/aws-sdk-go-v2/config v1.33.16 h1:fKRsu9Pj2IPIHzTcUdWB7JHY34q9+4XEGCy7WfZaLV4= github.com/aws/aws-sdk-go-v2/config v1.33.16/go.mod h1:wdEdQ9RBH3fnD/vicCDUIJqv8Ck3zOpxNz8e3/NtkG8= github.com/aws/aws-sdk-go-v2/credentials v1.20.16 h1:cqRWTY4fcctJGqZedMC1Khu4h2VsgRODUOIZwn39n3Y= @@ -18,6 +20,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.24 h1:jGzHjc github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.24/go.mod h1:uJt75pK2cEyY80F5C+DK9YkCkJWsMkJViHxLYZRHl8Y= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.11 h1:PO7Tx443ecMI00nIxDrT99DVcbeMBQ6BUtJlDMRnY24= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.11/go.mod h1:n/9RixikO12YvNomZLP8k4TgUSoEkT1W23QIrpFAPvw= +github.com/aws/aws-sdk-go-v2/service/lambda v1.114.3 h1:K0waQ/l0mZ/qjTFsIfbifurYEVb5eUEo/jCjh/7cUIE= +github.com/aws/aws-sdk-go-v2/service/lambda v1.114.3/go.mod h1:nrKEzey36x3k1cR+3SQ3eMdjsGIjSo74GPopn3YTHdQ= github.com/aws/aws-sdk-go-v2/service/signin v1.12.4 h1:uo84u6f6YatFOBwk3DKM+ToqgVEB0cDjHQLsfrRm44A= github.com/aws/aws-sdk-go-v2/service/signin v1.12.4/go.mod h1:PCRJucC12nFWle7wRGhSj0cw3OKB84M0EBwTrv34dhg= github.com/aws/aws-sdk-go-v2/service/ssm v1.82.0 h1:Ev6Ncm630UzzxAZ9qqzNlUeXKKFC6aSdh+6q85d5x/s= diff --git a/internal/app/app.go b/internal/app/app.go index 6d982e4..f8ea1b6 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -18,6 +18,7 @@ import ( ghclient "github.com/cruxstack/github-ops-app/internal/github/client" "github.com/cruxstack/github-ops-app/internal/notifiers" "github.com/cruxstack/github-ops-app/internal/okta" + "github.com/cruxstack/github-ops-app/internal/state" ) // Scheduled actions. @@ -44,7 +45,10 @@ type deps struct { github domain.GitHubClient okta domain.OktaClient notifier domain.Notifier + state domain.StateStore background Background + dispatcher Dispatcher + now func() time.Time } // WithBackground runs webhook-triggered syncs in the background, so the @@ -74,6 +78,24 @@ func WithNotifier(n domain.Notifier) Option { return func(d *deps) { d.notifier = n } } +// WithStateStore replaces the store that remembers what each report last +// posted. +func WithStateStore(s domain.StateStore) Option { + return func(d *deps) { d.state = s } +} + +// WithDispatcher runs jobs started from Slack with d, such as in another +// Lambda invocation. Without it they run in the Background, or, without +// that, before the response. +func WithDispatcher(dispatch Dispatcher) Option { + return func(d *deps) { d.dispatcher = dispatch } +} + +// WithClock replaces the clock, for tests. +func WithClock(now func() time.Time) Option { + return func(d *deps) { d.now = now } +} + // App is the configured application. It is safe for concurrent use. type App struct { cfg *config.Config @@ -81,18 +103,25 @@ type App struct { github domain.GitHubClient okta domain.OktaClient // nil when okta sync is not configured notifier domain.Notifier // nil when slack is not configured + // state remembers what each report last posted; nil unless reports + // repeat daily + state domain.StateStore // background runs webhook-triggered syncs; nil runs them inline background Background + // dispatcher runs jobs started from slack; nil uses background + dispatcher Dispatcher + now func() time.Time handler http.Handler // syncMu guards syncRunning and syncPending, which coalesce okta syncs - // requested while one is running into a single follow-up sync, and - // managedTeams, the slugs the last complete sync managed (nil before - // one). - syncMu sync.Mutex - syncRunning bool - syncPending bool - managedTeams map[string]bool + // requested while one is running into a single follow-up sync, whether + // someone asked for the follow-up, and managedTeams, the slugs the last + // complete sync managed (nil before one). + syncMu sync.Mutex + syncRunning bool + syncPending bool + syncPendingRequested bool + managedTeams map[string]bool } // New builds the application. It makes no network calls, so it fails only @@ -109,7 +138,20 @@ func New(cfg *config.Config, logger *slog.Logger, opts ...Option) (*App, error) opt(&d) } - a := &App{cfg: cfg, logger: logger, github: d.github, okta: d.okta, notifier: d.notifier, background: d.background} + a := &App{ + cfg: cfg, + logger: logger, + github: d.github, + okta: d.okta, + notifier: d.notifier, + state: d.state, + background: d.background, + dispatcher: d.dispatcher, + now: d.now, + } + if a.now == nil { + a.now = time.Now + } if a.github == nil { gh, err := ghclient.New(ghclient.Options{ @@ -160,6 +202,21 @@ func New(cfg *config.Config, logger *slog.Logger, opts ...Option) (*App, error) }) } + if a.state == nil && cfg.Reports.Repeat == config.ReportRepeatDaily { + switch { + case cfg.Reports.StateSSMPrefix != "": + st, err := state.NewSSM(context.Background(), cfg.Reports.StateSSMPrefix, nil) + if err != nil { + return nil, fmt.Errorf("failed to create report state store: %w", err) + } + a.state = st + case cfg.Reports.StateFile != "": + a.state = state.NewFile(cfg.Reports.StateFile) + default: + a.state = state.NewMemory() + } + } + a.handler = a.newRouter() return a, nil } @@ -182,6 +239,8 @@ type Status struct { PRComplianceEnabled bool `json:"pr_compliance_enabled"` SecurityAlertsEnabled bool `json:"security_alerts_enabled"` SlackEnabled bool `json:"slack_enabled"` + SlackCommandsEnabled bool `json:"slack_commands_enabled"` + ReportRepeat string `json:"report_repeat"` } // Status returns the application's status. @@ -193,5 +252,7 @@ func (a *App) Status() Status { PRComplianceEnabled: a.cfg.PRCompliance.Enabled, SecurityAlertsEnabled: a.cfg.SecurityAlerts.Enabled, SlackEnabled: a.notifier != nil, + SlackCommandsEnabled: a.notifier != nil && a.cfg.Slack.CommandsEnabled(), + ReportRepeat: a.cfg.Reports.Repeat, } } diff --git a/internal/app/commands.go b/internal/app/commands.go new file mode 100644 index 0000000..2d4a4bb --- /dev/null +++ b/internal/app/commands.go @@ -0,0 +1,257 @@ +package app + +import ( + "cmp" + "context" + "fmt" + "io" + "net/http" + "net/url" + "slices" + "strings" + + "github.com/slack-go/slack" + + "github.com/cruxstack/github-ops-app/internal/domain" + "github.com/cruxstack/github-ops-app/internal/notifiers" +) + +// maxSlackCommandBytes is the largest slash command request accepted. +const maxSlackCommandBytes = 64 << 10 + +// Job is an action someone asked for in Slack. It runs after Slack gets +// its response, since Slack waits only three seconds for one. +type Job struct { + Action string `json:"action"` + // SlackUser is the Slack user ID of who asked. + SlackUser string `json:"slack_user,omitempty"` + // ResponseURL is where the result goes, as a reply only that user sees. + ResponseURL string `json:"response_url,omitempty"` +} + +// Dispatcher starts a job outside the request that asked for it, such as in +// another Lambda invocation. +type Dispatcher func(ctx context.Context, job Job) error + +// commandActions maps the slash command's words to actions. +var commandActions = map[string]string{ + "sync": ActionOktaSync, + "resync": ActionOktaSync, + "okta-sync": ActionOktaSync, + "security-alerts": ActionSecurityAlerts, + "alerts": ActionSecurityAlerts, +} + +// slashCommand is the part of a slash command request the app reads. +type slashCommand struct { + command string + text string + userID string + responseURL string +} + +// handleSlackCommand answers the slash command. Requests must carry Slack's +// signature; the reply is shown only to who ran the command. +func (a *App) handleSlackCommand(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + if !a.cfg.Slack.CommandsEnabled() { + writeError(w, http.StatusNotFound, "not found") + return + } + + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxSlackCommandBytes)) + if err != nil { + writeError(w, http.StatusBadRequest, "failed to read request body") + return + } + if err := verifySlackRequest(r.Header, body, a.cfg.Slack.SigningSecret); err != nil { + a.logger.WarnContext(ctx, "rejected slack request with invalid signature", "error", err.Error()) + writeError(w, http.StatusUnauthorized, "unauthorized") + return + } + form, err := url.ParseQuery(string(body)) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid request") + return + } + + text := a.runSlackCommand(ctx, slashCommand{ + command: form.Get("command"), + text: form.Get("text"), + userID: form.Get("user_id"), + responseURL: form.Get("response_url"), + }) + writeJSON(w, http.StatusOK, map[string]string{"response_type": slack.ResponseTypeEphemeral, "text": text}) +} + +// verifySlackRequest checks a request's signature and that it was signed +// within the last five minutes. +func verifySlackRequest(header http.Header, body []byte, secret string) error { + sv, err := slack.NewSecretsVerifier(header, secret) + if err != nil { + return fmt.Errorf("failed to verify slack request: %w", err) + } + if _, err := sv.Write(body); err != nil { + return fmt.Errorf("failed to verify slack request: %w", err) + } + if err := sv.Ensure(); err != nil { + return fmt.Errorf("failed to verify slack request: %w", err) + } + return nil +} + +// runSlackCommand starts what a slash command asks for and returns the +// reply. Anyone may ask for help; only allowed users may start an action. +func (a *App) runSlackCommand(ctx context.Context, cmd slashCommand) string { + name := cmd.command + if name == "" { + name = a.cfg.SlackApp.Command + } + args := strings.Fields(strings.ToLower(cmd.text)) + if len(args) == 0 || args[0] == "help" { + return a.commandHelp(name) + } + action, ok := commandActions[args[0]] + if !ok { + return fmt.Sprintf("I don't know `%s`.\n\n%s", notifiers.Escape(args[0]), a.commandHelp(name)) + } + + log := a.logger.With("action", action, "slack_user", cmd.userID) + if !slices.Contains(a.cfg.Slack.CommandAllowedUsers, cmd.userID) { + log.WarnContext(ctx, "refused slack command from a user who isn't allowed to run it") + return fmt.Sprintf("You aren't allowed to run `%s %s`. An admin can allow it by adding your Slack user ID, `%s`, to `APP_SLACK_COMMAND_ALLOWED_USERS`.", + notifiers.Escape(name), notifiers.Escape(args[0]), notifiers.Escape(cmd.userID)) + } + if !a.actionEnabled(action) { + return fmt.Sprintf("The %s isn't turned on here.", actionName(action)) + } + + job := Job{Action: action, SlackUser: cmd.userID, ResponseURL: cmd.responseURL} + if err := a.dispatch(ctx, job); err != nil { + log.ErrorContext(ctx, "failed to start job requested in slack", "error", err.Error()) + return fmt.Sprintf("Couldn't start the %s. The app's logs have the details.", actionName(action)) + } + log.InfoContext(ctx, "started job requested in slack") + return fmt.Sprintf("Started the %s. The report will be posted in %s, and I'll reply here when it's done.", + actionName(action), a.channelMention(action)) +} + +func (a *App) commandHelp(name string) string { + name = notifiers.Escape(name) + lines := []string{fmt.Sprintf("*%s* commands:", name)} + if a.actionEnabled(ActionOktaSync) { + lines = append(lines, fmt.Sprintf("• `%s sync` syncs Okta groups to GitHub teams now and posts the report", name)) + } + if a.actionEnabled(ActionSecurityAlerts) { + lines = append(lines, fmt.Sprintf("• `%s security-alerts` posts the security alerts report now", name)) + } + lines = append(lines, fmt.Sprintf("• `%s help` shows this", name)) + return strings.Join(lines, "\n") +} + +func (a *App) actionEnabled(action string) bool { + switch action { + case ActionOktaSync: + return a.okta != nil + case ActionSecurityAlerts: + return a.cfg.SecurityAlerts.Enabled + } + return false +} + +func actionName(action string) string { + switch action { + case ActionOktaSync: + return "Okta sync" + case ActionSecurityAlerts: + return "security alerts report" + } + return action +} + +// channelMention returns a mention of the channel an action's report is +// posted in. +func (a *App) channelMention(action string) string { + channel := a.cfg.Slack.Channel + switch action { + case ActionOktaSync: + channel = cmp.Or(a.cfg.Slack.ChannelOktaSync, channel) + case ActionSecurityAlerts: + channel = cmp.Or(a.cfg.Slack.ChannelSecurityAlerts, channel) + } + return "<#" + channel + ">" +} + +// dispatch starts a job after the response: with the Dispatcher, in the +// background, or, with neither, before the response. +func (a *App) dispatch(ctx context.Context, job Job) error { + switch { + case a.dispatcher != nil: + return a.dispatcher(ctx, job) + case a.background != nil: + a.background.Go(func(ctx context.Context) { a.runJobAndLog(ctx, job) }) + default: + a.runJobAndLog(ctx, job) + } + return nil +} + +func (a *App) runJobAndLog(ctx context.Context, job Job) { + if err := a.RunJob(ctx, job); err != nil { + a.logger.ErrorContext(ctx, "job requested in slack failed", + "action", job.Action, + "slack_user", job.SlackUser, + "error", err.Error()) + } +} + +// RunJob runs a job started from Slack, posts its report whether or not it +// changed, and replies to who asked. The reply leaves out error details, +// which are returned and logged instead. +func (a *App) RunJob(ctx context.Context, job Job) error { + a.logger.InfoContext(ctx, "running job requested in slack", "action", job.Action, "slack_user", job.SlackUser) + + var reply string + var err error + switch job.Action { + case ActionOktaSync: + var s syncSummary + s, err = a.runOktaSync(ctx, true) + switch { + case err != nil: + reply = "The Okta sync failed. The app's logs have the details." + case s.queued: + reply = fmt.Sprintf("An Okta sync was already running, so another will run when it finishes. Its report will be posted in %s.", + a.channelMention(job.Action)) + default: + reply = fmt.Sprintf("Okta sync finished: %d team(s), %d member(s) added, %d removed, %d team(s) with errors. The report is in %s.", + s.teams, s.added, s.removed, s.failed, a.channelMention(job.Action)) + } + case ActionSecurityAlerts: + var alerts *domain.SecurityAlertsReport + alerts, err = a.runSecurityAlerts(ctx, true) + switch { + case err != nil: + reply = "The security alerts report failed. The app's logs have the details." + case !alerts.HasAlerts() && !alerts.HasErrors(): + reply = fmt.Sprintf("No open alerts older than %d days with severity %s or above.", + alerts.MinAgeDays, notifiers.Escape(alerts.MinSeverity)) + default: + reply = fmt.Sprintf("Found %d open alert(s) across %d repository(s), and %d source(s) failed. The report is in %s.", + alerts.TotalAlerts, alerts.RepoCount(), len(alerts.Errors), a.channelMention(job.Action)) + } + default: + err = fmt.Errorf("%w '%s'", domain.ErrUnknownAction, job.Action) + reply = "That command isn't supported." + } + + if job.ResponseURL != "" && a.notifier != nil { + if replyErr := a.notifier.ReplyToCommand(ctx, job.ResponseURL, reply); replyErr != nil { + a.logger.WarnContext(ctx, "failed to reply to slack command", "action", job.Action, "error", replyErr.Error()) + } + } + if err != nil { + return fmt.Errorf("failed to run %s requested by slack user %s: %w", job.Action, job.SlackUser, err) + } + return nil +} diff --git a/internal/app/commands_test.go b/internal/app/commands_test.go new file mode 100644 index 0000000..0aeccb0 --- /dev/null +++ b/internal/app/commands_test.go @@ -0,0 +1,258 @@ +package app + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/cruxstack/github-ops-app/internal/config" + "github.com/cruxstack/github-ops-app/internal/domain" + "github.com/cruxstack/github-ops-app/internal/fakes" + "github.com/cruxstack/github-ops-app/internal/state" +) + +const ( + testSigningSecret = "slack-signing-secret" + allowedUser = "U0ALLOWED" + responseURL = "https://hooks.slack.com/commands/T1/1/abc" +) + +func commandConfig() *config.Config { + cfg := testConfig() + cfg.SlackApp = config.SlackApp{Name: "GitHub Ops", Command: "/github-ops"} + cfg.Slack = config.Slack{ + Enabled: true, + Token: "xoxb-1", + SigningSecret: testSigningSecret, + CommandAllowedUsers: []string{allowedUser}, + Channel: "C0DEFAULT", + ChannelOktaSync: "C0OKTA", + } + return cfg +} + +// commandRequest builds a slash command request signed at ts. +func commandRequest(t *testing.T, user, text, secret string, ts time.Time) *http.Request { + t.Helper() + body := url.Values{ + "command": {"/github-ops"}, + "text": {text}, + "user_id": {user}, + "response_url": {responseURL}, + }.Encode() + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/slack/commands", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if secret != "" { + stamp := strconv.FormatInt(ts.Unix(), 10) + mac := hmac.New(sha256.New, []byte(secret)) + fmt.Fprintf(mac, "v0:%s:%s", stamp, body) + req.Header.Set("X-Slack-Request-Timestamp", stamp) + req.Header.Set("X-Slack-Signature", "v0="+hex.EncodeToString(mac.Sum(nil))) + } + return req +} + +// command sends a signed slash command and returns its reply text. +func (h *harness) command(t *testing.T, user, text string) string { + t.Helper() + rec := h.do(t, commandRequest(t, user, text, testSigningSecret, time.Now())) + if rec.Code != http.StatusOK { + t.Fatalf("status %d (%s)", rec.Code, rec.Body) + } + var reply struct { + ResponseType string `json:"response_type"` + Text string `json:"text"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &reply); err != nil { + t.Fatal(err) + } + if reply.ResponseType != "ephemeral" { + t.Errorf("response_type = %q, want ephemeral", reply.ResponseType) + } + return reply.Text +} + +func TestSlackCommand_Signature(t *testing.T) { + h := newHarness(t, commandConfig(), true) + for name, req := range map[string]*http.Request{ + "unsigned": commandRequest(t, allowedUser, "sync", "", time.Now()), + "wrong secret": commandRequest(t, allowedUser, "sync", "other-secret", time.Now()), + "stale": commandRequest(t, allowedUser, "sync", testSigningSecret, time.Now().Add(-10*time.Minute)), + } { + if rec := h.do(t, req); rec.Code != http.StatusUnauthorized { + t.Errorf("%s: status %d, want 401", name, rec.Code) + } + } + if h.okta.Count("GetGroupInfo") != 0 { + t.Error("a sync ran for an unverified request") + } + + cfg := commandConfig() + cfg.Slack.SigningSecret = "" + h = newHarness(t, cfg, true) + if rec := h.do(t, commandRequest(t, allowedUser, "sync", testSigningSecret, time.Now())); rec.Code != http.StatusNotFound { + t.Errorf("commands off: status %d, want 404", rec.Code) + } +} + +func TestSlackCommand_HelpAndUnknown(t *testing.T) { + cfg := commandConfig() + cfg.SecurityAlerts.Enabled = false + h := newHarness(t, cfg, true) + + // anyone may ask for help + for _, text := range []string{"", "help", " HELP "} { + reply := h.command(t, "U0SOMEONE", text) + if !strings.Contains(reply, "/github-ops sync") || strings.Contains(reply, "security-alerts") { + t.Errorf("help for %q = %q", text, reply) + } + } + if reply := h.command(t, allowedUser, ""); !strings.Contains(reply, "I don't know `<!channel>`") { + t.Errorf("unknown command reply = %q", reply) + } +} + +func TestSlackCommand_RefusesUsersNotAllowed(t *testing.T) { + h := newHarness(t, commandConfig(), true) + reply := h.command(t, "U0SOMEONE", "sync") + if !strings.Contains(reply, "aren't allowed") || !strings.Contains(reply, "U0SOMEONE") { + t.Errorf("reply = %q", reply) + } + if h.okta.Count("GetGroupInfo") != 0 || h.notifier.Sent() != 0 { + t.Error("a sync ran for a user who isn't allowed") + } +} + +func TestSlackCommand_DisabledAction(t *testing.T) { + cfg := commandConfig() + cfg.SecurityAlerts.Enabled = false + h := newHarness(t, cfg, true) + if reply := h.command(t, allowedUser, "security-alerts"); !strings.Contains(reply, "isn't turned on") { + t.Errorf("reply = %q", reply) + } +} + +func TestSlackCommand_RunsSyncAndReplies(t *testing.T) { + h := newHarness(t, commandConfig(), true) + + // without a dispatcher or background, the job runs before the response + reply := h.command(t, allowedUser, "Sync") + if !strings.Contains(reply, "Started the Okta sync") || !strings.Contains(reply, "<#C0OKTA>") { + t.Errorf("reply = %q", reply) + } + if len(h.notifier.OktaSyncs) != 1 { + t.Errorf("okta sync reports = %d, want 1", len(h.notifier.OktaSyncs)) + } + if len(h.notifier.Replies) != 1 || h.notifier.Replies[0].ResponseURL != responseURL || + !strings.Contains(h.notifier.LastReply(), "Okta sync finished: 1 team(s)") { + t.Errorf("replies = %+v", h.notifier.Replies) + } +} + +func TestSlackCommand_Dispatches(t *testing.T) { + var got []Job + dispatchErr := error(nil) + h := &harness{github: &fakes.GitHub{}, okta: &fakes.Okta{}, notifier: &fakes.Notifier{}} + a, err := New(commandConfig(), slog.New(slog.DiscardHandler), + WithGitHubClient(h.github), WithOktaClient(h.okta), WithNotifier(h.notifier), + WithDispatcher(func(_ context.Context, job Job) error { + got = append(got, job) + return dispatchErr + })) + if err != nil { + t.Fatal(err) + } + h.app = a + + h.command(t, allowedUser, "alerts") + want := Job{Action: ActionSecurityAlerts, SlackUser: allowedUser, ResponseURL: responseURL} + if len(got) != 1 || got[0] != want { + t.Errorf("dispatched = %+v, want %+v", got, want) + } + if h.github.Count("ListSecurityAlerts") != 0 { + t.Error("the job ran in the request") + } + + dispatchErr = errors.New("invoke failed") + if reply := h.command(t, allowedUser, "sync"); !strings.Contains(reply, "Couldn't start the Okta sync") { + t.Errorf("reply = %q", reply) + } +} + +func TestRunJob_SecurityAlerts(t *testing.T) { + h := newHarness(t, commandConfig(), true) + ctx := context.Background() + if err := h.app.RunJob(ctx, Job{Action: ActionSecurityAlerts, ResponseURL: responseURL}); err != nil { + t.Fatal(err) + } + if !strings.Contains(h.notifier.LastReply(), "No open alerts older than 30 days") { + t.Errorf("reply = %q", h.notifier.LastReply()) + } + + h.github.ListSecurityAlertsFn = func(context.Context, int, string) (*domain.SecurityAlertsReport, error) { + return nil, errors.New("github down") + } + if err := h.app.RunJob(ctx, Job{Action: ActionSecurityAlerts, ResponseURL: responseURL}); err == nil { + t.Error("failed report returned no error") + } + if reply := h.notifier.LastReply(); !strings.Contains(reply, "failed") || strings.Contains(reply, "github down") { + t.Errorf("failure reply = %q, want no error details", reply) + } + + if err := h.app.RunJob(ctx, Job{Action: "nope"}); !errors.Is(err, domain.ErrUnknownAction) { + t.Errorf("unknown action: error = %v", err) + } +} + +func TestRunJob_QueuedSyncIsPostedWhenItRuns(t *testing.T) { + cfg := commandConfig() + cfg.Okta.OrphanedUserNotifications = false + cfg.Reports = config.Reports{Repeat: config.ReportRepeatDaily, DailyTime: config.TimeOfDay{Hour: 9}, Location: time.UTC} + h, _ := newDailyHarness(t, cfg, state.NewMemory()) + + // a scheduled sync posts once and then blocks while the job is queued + started := make(chan struct{}, 2) + release := make(chan struct{}) + var once sync.Once + h.okta.GetGroupInfoFn = func(_ context.Context, name string) (*domain.GroupInfo, error) { + once.Do(func() { + started <- struct{}{} + <-release + }) + return &domain.GroupInfo{Name: name}, nil + } + + var wg sync.WaitGroup + wg.Go(func() { + if err := h.app.RunScheduled(context.Background(), ActionOktaSync); err != nil { + t.Errorf("scheduled sync: %v", err) + } + }) + <-started + if err := h.app.RunJob(context.Background(), Job{Action: ActionOktaSync, ResponseURL: responseURL}); err != nil { + t.Fatal(err) + } + if !strings.Contains(h.notifier.LastReply(), "already running") { + t.Errorf("reply = %q", h.notifier.LastReply()) + } + close(release) + wg.Wait() + + // the follow-up changed nothing, but someone asked for it + if got := len(h.notifier.OktaSyncs); got != 2 { + t.Errorf("okta sync reports = %d, want 2", got) + } +} diff --git a/internal/app/handlers.go b/internal/app/handlers.go index f1cf254..2f5af0b 100644 --- a/internal/app/handlers.go +++ b/internal/app/handlers.go @@ -18,9 +18,11 @@ func (a *App) RunScheduled(ctx context.Context, action string) error { a.logger.InfoContext(ctx, "running scheduled action", "action", action) switch action { case ActionOktaSync: - return a.runOktaSync(ctx) + _, err := a.runOktaSync(ctx, false) + return err case ActionSecurityAlerts: - return a.runSecurityAlerts(ctx) + _, err := a.runSecurityAlerts(ctx, false) + return err case ActionSlackTest: return a.runSlackTest(ctx) default: @@ -178,13 +180,13 @@ func (a *App) syncAfterExternalChange(ctx context.Context, eventType, action str log.InfoContext(ctx, "external team change detected, syncing okta groups") if a.background != nil { a.background.Go(func(ctx context.Context) { - if err := a.runOktaSync(ctx); err != nil { + if _, err := a.runOktaSync(ctx, false); err != nil { a.logger.ErrorContext(ctx, "okta sync failed", "trigger", eventType, "error", err.Error()) } }) return WebhookQueued, nil } - if err := a.runOktaSync(ctx); err != nil { + if _, err := a.runOktaSync(ctx, false); err != nil { return "", err } return WebhookProcessed, nil @@ -236,60 +238,77 @@ func (a *App) setManagedTeams(result *domain.SyncResult) { a.managedTeams = managed } +// syncSummary counts what an okta sync did. +type syncSummary struct { + // queued is true when another sync was running, so this one was queued + // to run after it + queued bool + teams, added, removed, failed int +} + // runOktaSync syncs Okta groups to GitHub teams. A sync requested while // another is running doesn't start a second one: the running sync runs once // more when it finishes, whether or not it failed, so it picks up the latest -// changes. The follow-up gets its own JobTimeout. -func (a *App) runOktaSync(ctx context.Context) error { +// changes. The follow-up gets its own JobTimeout. requested is true when +// someone asked for the sync, so its reports are posted even if unchanged. +func (a *App) runOktaSync(ctx context.Context, requested bool) (syncSummary, error) { if a.okta == nil { - return fmt.Errorf("okta sync: %w", domain.ErrFeatureDisabled) + return syncSummary{}, fmt.Errorf("okta sync: %w", domain.ErrFeatureDisabled) } a.syncMu.Lock() if a.syncRunning { a.syncPending = true + a.syncPendingRequested = a.syncPendingRequested || requested a.syncMu.Unlock() a.logger.InfoContext(ctx, "okta sync already running, queued a follow-up sync") - return nil + return syncSummary{queued: true}, nil } a.syncRunning = true a.syncMu.Unlock() - err := a.oktaSyncOnce(ctx) - for a.takePendingSync() { + summary, err := a.oktaSyncOnce(ctx, requested) + for { + followUpRequested, ok := a.takePendingSync() + if !ok { + break + } a.logger.InfoContext(ctx, "running queued okta sync") followUp, cancel := context.WithTimeout(context.WithoutCancel(ctx), JobTimeout) - err = errors.Join(err, a.oktaSyncOnce(followUp)) + s, followUpErr := a.oktaSyncOnce(followUp, followUpRequested) cancel() + summary, err = s, errors.Join(err, followUpErr) } - return err + return summary, err } -// takePendingSync returns true and clears the pending flag if a sync was -// queued; otherwise it marks the sync as finished. -func (a *App) takePendingSync() bool { +// takePendingSync returns true, and whether someone asked for it, and +// clears the pending flag if a sync was queued; otherwise it marks the sync +// as finished. +func (a *App) takePendingSync() (requested, ok bool) { a.syncMu.Lock() defer a.syncMu.Unlock() if a.syncPending { - a.syncPending = false - return true + requested = a.syncPendingRequested + a.syncPending, a.syncPendingRequested = false, false + return requested, true } a.syncRunning = false - return false + return false, false } -func (a *App) oktaSyncOnce(ctx context.Context) error { +func (a *App) oktaSyncOnce(ctx context.Context, requested bool) (syncSummary, error) { syncer := teamsync.NewSyncer(a.okta, a.github, a.cfg.Okta.SyncRules, a.cfg.Okta.SyncSafetyThreshold, a.logger) result, syncErr := syncer.Sync(ctx) if result == nil { - return fmt.Errorf("okta sync failed: %w", syncErr) + return syncSummary{}, fmt.Errorf("okta sync failed: %w", syncErr) } a.setManagedTeams(result) - var added, removed, failed int + summary := syncSummary{teams: len(result.Reports)} for _, r := range result.Reports { - added += len(r.MembersAdded) - removed += len(r.MembersRemoved) + summary.added += len(r.MembersAdded) + summary.removed += len(r.MembersRemoved) attrs := []any{ "rule", r.Rule, "okta_group", r.OktaGroup, @@ -300,38 +319,43 @@ func (a *App) oktaSyncOnce(ctx context.Context) error { "skipped_no_github_username", len(r.MembersSkippedNoGHUsername), } if r.HasErrors() { - failed++ + summary.failed++ a.logger.WarnContext(ctx, "okta group synced with errors", append(attrs, "errors", r.Errors)...) } else { a.logger.InfoContext(ctx, "okta group synced", attrs...) } } a.logger.InfoContext(ctx, "okta sync completed", - "teams", len(result.Reports), - "teams_with_errors", failed, - "members_added", added, - "members_removed", removed) - - if a.notifier != nil { - if err := a.notifier.NotifyOktaSync(ctx, result.Reports, a.cfg.GitHub.Org); err != nil { - a.logger.ErrorContext(ctx, "failed to send okta sync notification", "error", err.Error()) - } - } + "teams", summary.teams, + "teams_with_errors", summary.failed, + "members_added", summary.added, + "members_removed", summary.removed) + + a.postReport(ctx, report{ + key: reportOktaSync, + fingerprint: oktaSyncFingerprint(result.Reports), + empty: len(result.Reports) == 0, + changed: summary.added+summary.removed > 0, + requested: requested, + send: func(ctx context.Context) error { + return a.notifier.NotifyOktaSync(ctx, result.Reports, a.cfg.GitHub.Org) + }, + }) if syncErr != nil { - return fmt.Errorf("okta sync failed: %w", syncErr) + return summary, fmt.Errorf("okta sync failed: %w", syncErr) } if a.cfg.Okta.OrphanedUserNotifications { - a.reportOrphanedUsers(ctx, syncer, result) + a.reportOrphanedUsers(ctx, syncer, result, requested) } - return nil + return summary, nil } // reportOrphanedUsers reports organization members in none of the synced // teams. It is skipped when a team could not be found, since its members // would be reported as orphaned. Failures are logged, since the sync itself // succeeded. -func (a *App) reportOrphanedUsers(ctx context.Context, syncer *teamsync.Syncer, result *domain.SyncResult) { +func (a *App) reportOrphanedUsers(ctx context.Context, syncer *teamsync.Syncer, result *domain.SyncResult, requested bool) { if len(result.Reports) == 0 { return } @@ -339,51 +363,58 @@ func (a *App) reportOrphanedUsers(ctx context.Context, syncer *teamsync.Syncer, a.logger.WarnContext(ctx, "skipping orphaned user detection because not every synced team was found") return } - report, err := syncer.DetectOrphanedUsers(ctx, result) + orphans, err := syncer.DetectOrphanedUsers(ctx, result) if err != nil { a.logger.ErrorContext(ctx, "failed to detect orphaned users", "error", err.Error()) return } - if len(report.OrphanedUsers) == 0 { - return - } - - a.logger.InfoContext(ctx, "orphaned users detected", - "count", len(report.OrphanedUsers), - "users", report.OrphanedUsers) - if a.notifier != nil { - if err := a.notifier.NotifyOrphanedUsers(ctx, report); err != nil { - a.logger.ErrorContext(ctx, "failed to send orphaned users notification", "error", err.Error()) - } - } + if len(orphans.OrphanedUsers) > 0 { + a.logger.InfoContext(ctx, "orphaned users detected", + "count", len(orphans.OrphanedUsers), + "users", orphans.OrphanedUsers) + } + a.postReport(ctx, report{ + key: reportOrphanedUsers, + fingerprint: orphanedUsersFingerprint(orphans.OrphanedUsers), + empty: len(orphans.OrphanedUsers) == 0, + requested: requested, + send: func(ctx context.Context) error { + return a.notifier.NotifyOrphanedUsers(ctx, orphans) + }, + }) } // runSecurityAlerts reports open security alerts older than the configured -// age across the organization. -func (a *App) runSecurityAlerts(ctx context.Context) error { +// age across the organization. requested is true when someone asked for the +// report, so it is posted even if unchanged. +func (a *App) runSecurityAlerts(ctx context.Context, requested bool) (*domain.SecurityAlertsReport, error) { if !a.cfg.SecurityAlerts.Enabled { - return fmt.Errorf("security alerts: %w", domain.ErrFeatureDisabled) + return nil, fmt.Errorf("security alerts: %w", domain.ErrFeatureDisabled) } - report, err := a.github.ListSecurityAlerts(ctx, a.cfg.SecurityAlerts.MinAgeDays, a.cfg.SecurityAlerts.MinSeverity) + alerts, err := a.github.ListSecurityAlerts(ctx, a.cfg.SecurityAlerts.MinAgeDays, a.cfg.SecurityAlerts.MinSeverity) if err != nil { - return fmt.Errorf("failed to list security alerts for org '%s': %w", a.cfg.GitHub.Org, err) + return nil, fmt.Errorf("failed to list security alerts for org '%s': %w", a.cfg.GitHub.Org, err) } - for _, e := range report.Errors { + for _, e := range alerts.Errors { a.logger.ErrorContext(ctx, "failed to fetch security alerts", "error", e) } a.logger.InfoContext(ctx, "security alerts check completed", - "alerts", report.TotalAlerts, - "repos", report.RepoCount(), - "errors", len(report.Errors)) - - if a.notifier != nil { - if err := a.notifier.NotifySecurityAlerts(ctx, report, a.cfg.GitHub.Org); err != nil { - a.logger.ErrorContext(ctx, "failed to send security alerts notification", "error", err.Error()) - } - } - return nil + "alerts", alerts.TotalAlerts, + "repos", alerts.RepoCount(), + "errors", len(alerts.Errors)) + + a.postReport(ctx, report{ + key: reportSecurityAlerts, + fingerprint: securityAlertsFingerprint(alerts), + empty: !alerts.HasAlerts() && !alerts.HasErrors(), + requested: requested, + send: func(ctx context.Context) error { + return a.notifier.NotifySecurityAlerts(ctx, alerts, a.cfg.GitHub.Org) + }, + }) + return alerts, nil } // runSlackTest sends every notification type with sample data, to check diff --git a/internal/app/http.go b/internal/app/http.go index 8c148c7..a3eb719 100644 --- a/internal/app/http.go +++ b/internal/app/http.go @@ -22,6 +22,7 @@ const maxWebhookBytes = 25 << 20 // newRouter builds the application's routes under the base path: // // POST /webhooks GitHub webhooks, verified by signature +// POST /slack/commands the Slack slash command, verified by signature // GET /server/status status and enabled features (admin) // GET /server/config configuration, secrets redacted (admin) // POST /scheduled/{action} run a scheduled action (admin) @@ -40,6 +41,7 @@ func (a *App) newRouter() http.Handler { } r.Route(mount, func(r chi.Router) { r.Post("/webhooks", a.handleWebhook) + r.Post("/slack/commands", a.handleSlackCommand) r.Group(func(r chi.Router) { r.Use(a.requireAdmin) diff --git a/internal/app/reports.go b/internal/app/reports.go new file mode 100644 index 0000000..d1a7f49 --- /dev/null +++ b/internal/app/reports.go @@ -0,0 +1,185 @@ +package app + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "slices" + "strings" + "time" + + "github.com/cruxstack/github-ops-app/internal/config" + "github.com/cruxstack/github-ops-app/internal/domain" +) + +// Report keys name each report's record in the state store. +const ( + reportOktaSync = "okta-sync" + reportOrphanedUsers = "orphaned-users" + reportSecurityAlerts = "security-alerts" +) + +// report is the result of a scheduled check, to post to Slack. +type report struct { + key string + // fingerprint identifies what the report says, apart from changes the + // run made, so an unchanged report can be told apart from a new one + fingerprint string + // empty is true when there is nothing to post, such as no stale alerts + empty bool + // changed is true when the run made changes, such as adding team + // members, which are always posted + changed bool + // requested is true when someone asked for the run, which is always + // posted + requested bool + send func(ctx context.Context) error +} + +// reportState is what a report last posted, and when. +type reportState struct { + Fingerprint string `json:"fingerprint"` + PostedAt time.Time `json:"posted_at"` +} + +// postReport sends a report. When reports repeat daily, a report that +// hasn't changed since it was last posted is sent only if it hasn't been +// posted since the day's report time. An empty report is never sent, but +// is remembered, so the report is posted when it has something again. +func (a *App) postReport(ctx context.Context, r report) { + if a.notifier == nil { + return + } + log := a.logger.With("report", r.key) + daily := a.cfg.Reports.Repeat == config.ReportRepeatDaily + if !daily { + if !r.empty { + a.sendReport(ctx, r) + } + return + } + + now := a.now() + last, err := a.reportState(ctx, r.key) + if err != nil { + // a duplicate post is better than a missed one + log.WarnContext(ctx, "failed to read report state, posting the report", "error", err.Error()) + } + unchanged := err == nil && last.Fingerprint == r.fingerprint + switch { + case r.empty: + if !unchanged { + a.saveReportState(ctx, r.key, reportState{Fingerprint: r.fingerprint, PostedAt: now}) + } + return + case unchanged && !r.changed && !r.requested && !last.PostedAt.Before(a.reportsDue(now)): + log.DebugContext(ctx, "report unchanged since it was last posted, skipping", "posted_at", last.PostedAt) + return + } + if a.sendReport(ctx, r) { + a.saveReportState(ctx, r.key, reportState{Fingerprint: r.fingerprint, PostedAt: now}) + } +} + +// sendReport sends a report and returns true if it was sent. A failure is +// logged, since notifications are optional. +func (a *App) sendReport(ctx context.Context, r report) bool { + if err := r.send(ctx); err != nil { + a.logger.ErrorContext(ctx, "failed to send report notification", "report", r.key, "error", err.Error()) + return false + } + return true +} + +// reportsDue returns the latest daily report time at or before now. A report +// posted before it is due again. +func (a *App) reportsDue(now time.Time) time.Time { + at, loc := a.cfg.Reports.DailyTime, a.cfg.Reports.Location + if loc == nil { + loc = time.UTC + } + local := now.In(loc) + due := time.Date(local.Year(), local.Month(), local.Day(), at.Hour, at.Minute, 0, 0, loc) + if due.After(now) { + due = time.Date(local.Year(), local.Month(), local.Day()-1, at.Hour, at.Minute, 0, 0, loc) + } + return due +} + +func (a *App) reportState(ctx context.Context, key string) (reportState, error) { + var st reportState + raw, err := a.state.Get(ctx, key) + if err != nil || raw == nil { + return st, err + } + if err := json.Unmarshal(raw, &st); err != nil { + return reportState{}, fmt.Errorf("failed to parse state of report '%s': %w", key, err) + } + return st, nil +} + +// saveReportState records what a report posted. A failure is logged: at +// worst, the report is posted again on the next run. +func (a *App) saveReportState(ctx context.Context, key string, st reportState) { + raw, err := json.Marshal(st) + if err == nil { + err = a.state.Put(ctx, key, raw) + } + if err != nil { + a.logger.WarnContext(ctx, "failed to save report state", "report", key, "error", err.Error()) + } +} + +// fingerprint hashes lines regardless of their order. +func fingerprint(lines []string) string { + slices.Sort(lines) + sum := sha256.Sum256([]byte(strings.Join(lines, "\n"))) + return hex.EncodeToString(sum[:16]) +} + +// oktaSyncFingerprint covers the teams synced, which of them failed, and +// the members skipped. Members added and removed are changes, which are +// posted anyway. Error text is left out, since it can differ from one run to +// the next for the same failure. +func oktaSyncFingerprint(reports []*domain.SyncReport) string { + var lines []string + for _, r := range reports { + team := strings.Join([]string{r.Rule, r.OktaGroup, r.GitHubTeam}, "|") + lines = append(lines, "team "+team) + if r.HasErrors() { + lines = append(lines, "failed "+team) + } + for _, m := range r.MembersSkippedExternal { + lines = append(lines, "external "+team+" "+m) + } + for _, m := range r.MembersSkippedNoGHUsername { + lines = append(lines, "no-github-username "+team+" "+m) + } + } + return fingerprint(lines) +} + +func orphanedUsersFingerprint(users []string) string { + lines := make([]string, 0, len(users)) + for _, u := range users { + lines = append(lines, strings.ToLower(u)) + } + return fingerprint(lines) +} + +// securityAlertsFingerprint covers which alerts are open and which sources +// failed, but not the alerts' ages, which change every day. +func securityAlertsFingerprint(r *domain.SecurityAlertsReport) string { + var lines []string + for repo, alerts := range r.AlertsByRepo { + for _, alert := range alerts { + lines = append(lines, fmt.Sprintf("alert %s %s #%d %s", alert.Type, repo, alert.Number, alert.Severity)) + } + } + for _, e := range r.Errors { + lines = append(lines, "error "+e) + } + return fingerprint(lines) +} diff --git a/internal/app/reports_test.go b/internal/app/reports_test.go new file mode 100644 index 0000000..99e6d44 --- /dev/null +++ b/internal/app/reports_test.go @@ -0,0 +1,242 @@ +package app + +import ( + "context" + "errors" + "log/slog" + "sync" + "testing" + "time" + + "github.com/cruxstack/github-ops-app/internal/config" + "github.com/cruxstack/github-ops-app/internal/domain" + "github.com/cruxstack/github-ops-app/internal/fakes" + "github.com/cruxstack/github-ops-app/internal/state" +) + +// clock is a settable test clock. +type clock struct { + mu sync.Mutex + now time.Time +} + +func (c *clock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *clock) Set(t time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = t +} + +func dailyConfig() *config.Config { + cfg := testConfig() + cfg.Okta.OrphanedUserNotifications = false + cfg.Reports = config.Reports{Repeat: config.ReportRepeatDaily, DailyTime: config.TimeOfDay{Hour: 9}, Location: time.UTC} + return cfg +} + +func newDailyHarness(t *testing.T, cfg *config.Config, store domain.StateStore) (*harness, *clock) { + t.Helper() + h := &harness{github: &fakes.GitHub{}, okta: &fakes.Okta{}, notifier: &fakes.Notifier{}} + c := &clock{} + a, err := New(cfg, slog.New(slog.DiscardHandler), + WithGitHubClient(h.github), WithOktaClient(h.okta), WithNotifier(h.notifier), + WithStateStore(store), WithClock(c.Now)) + if err != nil { + t.Fatal(err) + } + h.app = a + // by default a sync changes nothing + h.github.SyncTeamMembersFn = func(_ context.Context, slug string, desired []string, _ float64) (*domain.TeamSyncResult, error) { + return &domain.TeamSyncResult{TeamName: slug, Members: desired}, nil + } + return h, c +} + +func at(day, hour, minute int) time.Time { + return time.Date(2026, time.March, day, hour, minute, 0, 0, time.UTC) +} + +func TestReports_EveryRunPostsEveryRun(t *testing.T) { + h := newHarness(t, testConfig(), true) + for range 3 { + if err := h.app.RunScheduled(context.Background(), ActionOktaSync); err != nil { + t.Fatal(err) + } + } + if got := len(h.notifier.OktaSyncs); got != 3 { + t.Errorf("posts = %d, want 3", got) + } +} + +func TestReports_DailyPostsChangesAndOnceADay(t *testing.T) { + h, c := newDailyHarness(t, dailyConfig(), state.NewMemory()) + ctx := context.Background() + + steps := []struct { + name string + now time.Time + setup func() + want int // posts so far + }{ + {"first run posts", at(10, 8, 0), nil, 1}, + {"unchanged before the day's time", at(10, 8, 30), nil, 1}, + {"due at the day's time", at(10, 9, 5), nil, 2}, + {"unchanged after", at(10, 10, 0), nil, 2}, + {"members added", at(10, 11, 0), func() { + h.github.SyncTeamMembersFn = func(_ context.Context, slug string, desired []string, _ float64) (*domain.TeamSyncResult, error) { + return &domain.TeamSyncResult{TeamName: slug, MembersAdded: []string{"new"}, Members: desired}, nil + } + }, 3}, + {"no change after members added", at(10, 12, 0), func() { + h.github.SyncTeamMembersFn = func(_ context.Context, slug string, desired []string, _ float64) (*domain.TeamSyncResult, error) { + return &domain.TeamSyncResult{TeamName: slug, Members: desired}, nil + } + }, 3}, + {"a group starts failing", at(10, 13, 0), func() { + h.okta.GetGroupInfoFn = func(context.Context, string) (*domain.GroupInfo, error) { return nil, errors.New("okta down") } + }, 4}, + {"still failing", at(10, 14, 0), nil, 4}, + {"next day", at(11, 9, 0), nil, 5}, + } + for _, step := range steps { + if step.setup != nil { + step.setup() + } + c.Set(step.now) + _ = h.app.RunScheduled(ctx, ActionOktaSync) + if got := len(h.notifier.OktaSyncs); got != step.want { + t.Fatalf("%s: posts = %d, want %d", step.name, got, step.want) + } + } + + // someone asking for a sync always gets its report + if err := h.app.RunJob(ctx, Job{Action: ActionOktaSync}); err == nil { + t.Error("failing sync returned no error") + } + if got := len(h.notifier.OktaSyncs); got != 6 { + t.Errorf("requested sync: posts = %d, want 6", got) + } +} + +func TestReports_DailyEmptyReportIsRemembered(t *testing.T) { + h, c := newDailyHarness(t, dailyConfig(), state.NewMemory()) + ctx := context.Background() + + open := &domain.SecurityAlertsReport{TotalAlerts: 1, AlertsByRepo: map[string][]domain.SecurityAlert{ + "acme/web": {{Type: "dependabot", Number: 1, Severity: "high"}}, + }} + none := &domain.SecurityAlertsReport{AlertsByRepo: map[string][]domain.SecurityAlert{}} + var current *domain.SecurityAlertsReport + h.github.ListSecurityAlertsFn = func(context.Context, int, string) (*domain.SecurityAlertsReport, error) { + return current, nil + } + + for i, step := range []struct { + alerts *domain.SecurityAlertsReport + want int + }{ + {open, 1}, + {open, 1}, // unchanged + {none, 1}, // nothing to post, but remembered + {open, 2}, // back, so it's news again + } { + current = step.alerts + c.Set(at(10, 10+i, 0)) + if err := h.app.RunScheduled(ctx, ActionSecurityAlerts); err != nil { + t.Fatal(err) + } + if got := len(h.notifier.SecurityAlerts); got != step.want { + t.Fatalf("step %d: posts = %d, want %d", i, got, step.want) + } + } +} + +func TestReports_EveryRunSkipsEmptyReports(t *testing.T) { + h := newHarness(t, testConfig(), true) + if err := h.app.RunScheduled(context.Background(), ActionSecurityAlerts); err != nil { + t.Fatal(err) + } + if got := len(h.notifier.SecurityAlerts); got != 0 { + t.Errorf("empty report posted %d times", got) + } +} + +// brokenStore fails every read and write. +type brokenStore struct{} + +func (brokenStore) Get(context.Context, string) ([]byte, error) { return nil, errors.New("denied") } +func (brokenStore) Put(context.Context, string, []byte) error { return errors.New("denied") } + +func TestReports_StateFailurePostsAnyway(t *testing.T) { + h, c := newDailyHarness(t, dailyConfig(), brokenStore{}) + for i := range 2 { + c.Set(at(10, 10+i, 0)) + if err := h.app.RunScheduled(context.Background(), ActionOktaSync); err != nil { + t.Fatal(err) + } + } + if got := len(h.notifier.OktaSyncs); got != 2 { + t.Errorf("posts = %d, want 2", got) + } +} + +func TestReports_ReportsDue(t *testing.T) { + ny, err := time.LoadLocation("America/New_York") + if err != nil { + t.Fatal(err) + } + cfg := dailyConfig() + cfg.Reports.Location = ny + cfg.Reports.DailyTime = config.TimeOfDay{Hour: 9, Minute: 30} + a, err := New(cfg, slog.New(slog.DiscardHandler), WithGitHubClient(&fakes.GitHub{}), WithOktaClient(&fakes.Okta{}), WithStateStore(state.NewMemory())) + if err != nil { + t.Fatal(err) + } + + // daylight saving time starts on 2026-03-08 in new york + for now, want := range map[time.Time]time.Time{ + at(8, 14, 0): time.Date(2026, time.March, 8, 9, 30, 0, 0, ny), + at(8, 13, 0): time.Date(2026, time.March, 7, 9, 30, 0, 0, ny), + at(10, 3, 0): time.Date(2026, time.March, 9, 9, 30, 0, 0, ny), + at(10, 13, 30): time.Date(2026, time.March, 10, 9, 30, 0, 0, ny), + } { + if got := a.reportsDue(now); !got.Equal(want) { + t.Errorf("reportsDue(%v) = %v, want %v", now, got, want.UTC()) + } + } +} + +func TestReports_Fingerprints(t *testing.T) { + alerts := func(age int, order ...string) *domain.SecurityAlertsReport { + r := &domain.SecurityAlertsReport{AlertsByRepo: map[string][]domain.SecurityAlert{}} + for i, repo := range order { + r.AlertsByRepo[repo] = append(r.AlertsByRepo[repo], domain.SecurityAlert{Type: "dependabot", Number: i % 2, Severity: "high", AgeDays: age}) + } + return r + } + if securityAlertsFingerprint(alerts(30, "a", "b")) != securityAlertsFingerprint(alerts(31, "a", "b")) { + t.Error("alert age changed the fingerprint") + } + if securityAlertsFingerprint(alerts(30, "a", "b")) == securityAlertsFingerprint(alerts(30, "a", "c")) { + t.Error("different alerts have the same fingerprint") + } + + sync := func(errText string, skipped ...string) []*domain.SyncReport { + return []*domain.SyncReport{{Rule: "r", OktaGroup: "g", GitHubTeam: "t", Errors: []string{errText}, MembersSkippedExternal: skipped}} + } + if oktaSyncFingerprint(sync("timeout")) != oktaSyncFingerprint(sync("502 bad gateway")) { + t.Error("error text changed the fingerprint") + } + if oktaSyncFingerprint(sync("x")) == oktaSyncFingerprint(sync("x", "bob")) { + t.Error("a skipped member didn't change the fingerprint") + } + + if orphanedUsersFingerprint([]string{"Bob", "alice"}) != orphanedUsersFingerprint([]string{"alice", "bob"}) { + t.Error("orphaned users fingerprint depends on order or case") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 1e1b41e..c9390c8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -23,7 +23,13 @@ import ( "slices" "strconv" "strings" + "time" + // report time zones load from the binary, since lambda's runtime has + // no zoneinfo + _ "time/tzdata" + + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" "github.com/cruxstack/github-app-setup-go/configstore" "github.com/cruxstack/github-app-setup-go/ssmresolver" @@ -38,10 +44,24 @@ const ( DefaultOktaSyncSafetyThreshold = 0.5 DefaultSecurityAlertsMinAgeDays = 30 DefaultSecurityAlertsMinSeverity = domain.SeverityHigh + DefaultSlackAppName = "GitHub Ops" + DefaultSlackCommand = "/github-ops" // MinAdminTokenLength is the shortest admin token accepted. MinAdminTokenLength = 16 ) +// How often a scheduled report that hasn't changed is posted again. +const ( + // ReportRepeatEveryRun posts every report after every run. + ReportRepeatEveryRun = "every-run" + // ReportRepeatDaily posts a report when it changes, and once a day + // when it hasn't. + ReportRepeatDaily = "daily" +) + +// DefaultReportDailyTime is when the day's unchanged reports are due. +var DefaultReportDailyTime = TimeOfDay{Hour: 9} + // Default lists for unset variables. var ( DefaultPRMonitoredBranches = []string{"main", "master"} @@ -70,6 +90,7 @@ type Config struct { Okta Okta SecurityAlerts SecurityAlerts Slack Slack + Reports Reports } // Bootstrap is the configuration needed before the rest can be loaded: how @@ -81,6 +102,7 @@ type Bootstrap struct { LogLevel slog.Level Server Server Installer Installer + SlackApp SlackApp } // Server configures the HTTP server. @@ -96,20 +118,40 @@ type Server struct { PublicURL string } -// Installer configures the GitHub App manifest installer. +// Installer configures the GitHub App manifest installer, and where it and +// the Slack setup save credentials. type Installer struct { Enabled bool - // StorageMode is where the installer saves credentials: envfile or + // StorageMode is where the installers save credentials: envfile or // aws-ssm. StorageMode string // StorageDir is the env file path for the envfile mode. StorageDir string + // SSMParameterPrefix is the parameter path for the aws-ssm mode. + SSMParameterPrefix string + // SSMKMSKeyID encrypts the parameters the aws-ssm mode writes; empty + // uses the aws/ssm key. + SSMKMSKeyID string // GitHubOrg is the organization the app is created in. GitHubOrg string // GitHubURL is the GitHub web URL the app is created on. GitHubURL string } +// SlackApp describes the Slack app: what the setup page creates, and the +// slash command it answers. +type SlackApp struct { + // SetupEnabled serves /slack/setup, which creates and installs the + // Slack app and saves its credentials where the GitHub App installer + // saves its own. While it is enabled, Slack credentials it hasn't saved + // yet are not an error. + SetupEnabled bool + // Name is the app's name in Slack. + Name string + // Command is the slash command, such as /github-ops. + Command string +} + // GitHub configures the GitHub App. type GitHub struct { Org string @@ -155,10 +197,20 @@ type SecurityAlerts struct { MinSeverity string } -// Slack configures notifications. +// Slack configures notifications and the slash command. type Slack struct { - Enabled bool - Token string + // Enabled is true when the token and channel are set. + Enabled bool + // Pending is true while the Slack setup is enabled and the token or + // channel isn't set yet. Slack stays off until both are. + Pending bool + Token string + // SigningSecret verifies requests from Slack. Setting it, with Enabled, + // turns on the slash command. + SigningSecret string + // CommandAllowedUsers are the Slack user IDs that may run the slash + // command's actions. Anyone may ask it for help. + CommandAllowedUsers []string Channel string ChannelPRBypass string ChannelOktaSync string @@ -168,6 +220,34 @@ type Slack struct { APIURL string } +// CommandsEnabled returns true when the slash command is turned on. +func (s Slack) CommandsEnabled() bool { + return s.Enabled && s.SigningSecret != "" +} + +// Reports configures how often scheduled reports are posted to Slack. +type Reports struct { + // Repeat is ReportRepeatEveryRun or ReportRepeatDaily. + Repeat string + // DailyTime is when, in Location, the day's unchanged reports are due. + // They post at the first run on or after it. + DailyTime TimeOfDay + Location *time.Location + // StateSSMPrefix or StateFile is where what each report last posted is + // kept. With neither, it is kept in memory and lost on restart. + StateSSMPrefix string + StateFile string +} + +// TimeOfDay is a wall clock time. +type TimeOfDay struct { + Hour, Minute int +} + +func (t TimeOfDay) String() string { + return fmt.Sprintf("%02d:%02d", t.Hour, t.Minute) +} + // Env is where configuration is read from. type Env struct { // Lookup has the signature of os.LookupEnv. @@ -219,7 +299,8 @@ func Load(ctx context.Context, env Env) (*Config, error) { } cfg.Okta = r.okta() cfg.SecurityAlerts = r.securityAlerts() - cfg.Slack = r.slack() + cfg.Slack = r.slack(cfg.SlackApp.SetupEnabled) + cfg.Reports = r.reports() if err := r.err(); err != nil { return nil, err @@ -379,6 +460,12 @@ func (r *reader) pem(key string) []byte { var ( basePathPattern = regexp.MustCompile(`^(/[A-Za-z0-9._~-]+)+$`) + // slackCommandPattern matches the slash commands Slack accepts + slackCommandPattern = regexp.MustCompile(`^/[a-z0-9][a-z0-9_-]{0,30}$`) + // slackUserPattern matches Slack user IDs + slackUserPattern = regexp.MustCompile(`^[UW][A-Z0-9]{2,}$`) + // ssmPrefixPattern matches parameter paths that end with a slash + ssmPrefixPattern = regexp.MustCompile(`^/([A-Za-z0-9_.-]+/)+$`) // githubOrgPattern matches organization logins. githubOrgPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$`) hostnamePattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$`) @@ -433,22 +520,41 @@ func (r *reader) bootstrap() *Bootstrap { if b.Installer.StorageDir == "" { b.Installer.StorageDir = "./.env" } + b.Installer.SSMParameterPrefix = r.plain(configstore.EnvAWSSSMParameterPfx) + b.Installer.SSMKMSKeyID = r.plain(configstore.EnvAWSSSMKMSKeyID) b.Installer.GitHubOrg = r.str("APP_GITHUB_ORG") b.Installer.GitHubURL = DefaultGitHubWebURL if api := r.str("APP_GITHUB_BASE_URL"); api != "" { b.Installer.GitHubURL = webURLFromAPI(api) } - if b.Installer.Enabled { - if b.Installer.GitHubOrg == "" { - r.fail(errors.New("APP_GITHUB_ORG is required when the installer is enabled")) - } + + b.SlackApp = SlackApp{ + SetupEnabled: r.bool("APP_SLACK_SETUP_ENABLED", false), + Name: r.str("APP_SLACK_APP_NAME"), + Command: r.str("APP_SLACK_COMMAND"), + } + if b.SlackApp.Name == "" { + b.SlackApp.Name = DefaultSlackAppName + } else if len([]rune(b.SlackApp.Name)) > 35 { + r.fail(fmt.Errorf("APP_SLACK_APP_NAME: %q is longer than slack's 35 characters", b.SlackApp.Name)) + } + if b.SlackApp.Command == "" { + b.SlackApp.Command = DefaultSlackCommand + } else if !slackCommandPattern.MatchString(b.SlackApp.Command) { + r.fail(fmt.Errorf("APP_SLACK_COMMAND: %q is not a slash command, such as /github-ops", b.SlackApp.Command)) + } + + if b.Installer.Enabled && b.Installer.GitHubOrg == "" { + r.fail(errors.New("APP_GITHUB_ORG is required when the installer is enabled")) + } + if b.Installer.Enabled || b.SlackApp.SetupEnabled { switch b.Installer.StorageMode { case configstore.StorageModeEnvFile: if r.has("AWS_LAMBDA_FUNCTION_NAME") { r.fail(fmt.Errorf("%s=%s does not persist in lambda: use %s", configstore.EnvStorageMode, configstore.StorageModeEnvFile, configstore.StorageModeAWSSSM)) } case configstore.StorageModeAWSSSM: - if r.plain(configstore.EnvAWSSSMParameterPfx) == "" { + if b.Installer.SSMParameterPrefix == "" { r.fail(fmt.Errorf("%s is required when %s is %s", configstore.EnvAWSSSMParameterPfx, configstore.EnvStorageMode, configstore.StorageModeAWSSSM)) } default: @@ -593,9 +699,11 @@ func (r *reader) securityAlerts() SecurityAlerts { return s } -func (r *reader) slack() Slack { +func (r *reader) slack(setup bool) Slack { s := Slack{ - Token: r.raw("APP_SLACK_TOKEN"), + Token: strings.TrimSpace(r.credential("APP_SLACK_TOKEN", setup)), + SigningSecret: strings.TrimSpace(r.credential("APP_SLACK_SIGNING_SECRET", setup)), + CommandAllowedUsers: r.list("APP_SLACK_COMMAND_ALLOWED_USERS", nil), Channel: r.str("APP_SLACK_CHANNEL"), ChannelPRBypass: r.str("APP_SLACK_CHANNEL_PR_BYPASS"), ChannelOktaSync: r.str("APP_SLACK_CHANNEL_OKTA_SYNC"), @@ -604,16 +712,32 @@ func (r *reader) slack() Slack { PRBypassFooterNote: r.str("APP_SLACK_FOOTER_NOTE_PR_BYPASS"), APIURL: r.url("APP_SLACK_API_URL"), } - s.Token = strings.TrimSpace(s.Token) - s.Enabled = s.Token != "" || s.Channel != "" - if s.Enabled { - if s.Token == "" { - r.fail(errors.New("APP_SLACK_TOKEN is required when APP_SLACK_CHANNEL is set")) + for _, user := range s.CommandAllowedUsers { + if !slackUserPattern.MatchString(user) { + r.fail(fmt.Errorf("APP_SLACK_COMMAND_ALLOWED_USERS: %q is not a slack user id, such as U0123ABCD", user)) } - if s.Channel == "" { - r.fail(errors.New("APP_SLACK_CHANNEL is required when APP_SLACK_TOKEN is set")) + } + + switch { + case s.Token != "" && s.Channel != "": + s.Enabled = true + case setup: + // the setup page saves the token, and the channel may be set after + s.Pending = true + case s.Token != "": + r.fail(errors.New("APP_SLACK_CHANNEL is required when APP_SLACK_TOKEN is set")) + case s.Channel != "": + r.fail(errors.New("APP_SLACK_TOKEN is required when APP_SLACK_CHANNEL is set")) + } + if !setup { + if s.SigningSecret != "" && !s.Enabled { + r.fail(errors.New("APP_SLACK_SIGNING_SECRET requires APP_SLACK_TOKEN and APP_SLACK_CHANNEL")) + } + if len(s.CommandAllowedUsers) > 0 && s.SigningSecret == "" { + r.fail(errors.New("APP_SLACK_COMMAND_ALLOWED_USERS requires APP_SLACK_SIGNING_SECRET")) } } + if s.APIURL != "" { // the slack client appends method names to this url s.APIURL += "/" @@ -621,6 +745,86 @@ func (r *reader) slack() Slack { return s } +// credential returns a secret value. While pending is true, the secret may +// not have been saved yet, so an SSM parameter that doesn't exist reads as +// unset instead of failing. +func (r *reader) credential(key string, pending bool) string { + v := r.plain(key) + if !pending || !ssmresolver.IsSSMARN(v) { + return r.raw(key) + } + resolved, err := r.resolveSSM(v) + var notFound *ssmtypes.ParameterNotFound + if errors.As(err, ¬Found) { + return "" + } + if err != nil { + r.fail(fmt.Errorf("%s: %w", key, err)) + return "" + } + return resolved +} + +func (r *reader) reports() Reports { + rep := Reports{Repeat: ReportRepeatEveryRun, DailyTime: DefaultReportDailyTime, Location: time.UTC} + switch v := strings.ToLower(r.str("APP_REPORT_REPEAT")); v { + case "": + case ReportRepeatEveryRun, ReportRepeatDaily: + rep.Repeat = v + default: + r.fail(fmt.Errorf("APP_REPORT_REPEAT: %q is not one of %s, %s", v, ReportRepeatEveryRun, ReportRepeatDaily)) + } + daily := rep.Repeat == ReportRepeatDaily + + // settings that only apply to daily reports are errors otherwise, so a + // typo in APP_REPORT_REPEAT doesn't go unnoticed + dailyOnly := func(key string) { + if !daily { + r.fail(fmt.Errorf("%s requires APP_REPORT_REPEAT=%s", key, ReportRepeatDaily)) + } + } + if v := r.str("APP_REPORT_DAILY_TIME"); v != "" { + dailyOnly("APP_REPORT_DAILY_TIME") + t, err := time.Parse("15:04", v) + if err != nil { + r.fail(fmt.Errorf("APP_REPORT_DAILY_TIME: %q is not a 24-hour time, such as 09:00", v)) + } else { + rep.DailyTime = TimeOfDay{Hour: t.Hour(), Minute: t.Minute()} + } + } + if v := r.str("APP_REPORT_TIMEZONE"); v != "" { + dailyOnly("APP_REPORT_TIMEZONE") + loc, err := time.LoadLocation(v) + if err != nil { + r.fail(fmt.Errorf("APP_REPORT_TIMEZONE: %q is not a time zone, such as America/New_York", v)) + } else { + rep.Location = loc + } + } + + rep.StateSSMPrefix = r.str("APP_STATE_SSM_PREFIX") + rep.StateFile = r.str("APP_STATE_FILE") + if rep.StateSSMPrefix != "" { + dailyOnly("APP_STATE_SSM_PREFIX") + if !ssmPrefixPattern.MatchString(rep.StateSSMPrefix) { + r.fail(fmt.Errorf("APP_STATE_SSM_PREFIX: %q must start and end with a slash, such as /github-ops-app/state/", rep.StateSSMPrefix)) + } + } + if rep.StateFile != "" { + dailyOnly("APP_STATE_FILE") + } + inLambda := r.has("AWS_LAMBDA_FUNCTION_NAME") + switch { + case rep.StateSSMPrefix != "" && rep.StateFile != "": + r.fail(errors.New("APP_STATE_SSM_PREFIX and APP_STATE_FILE are mutually exclusive")) + case inLambda && rep.StateFile != "": + r.fail(errors.New("APP_STATE_FILE does not persist in lambda: use APP_STATE_SSM_PREFIX")) + case inLambda && daily && rep.StateSSMPrefix == "": + r.fail(fmt.Errorf("APP_STATE_SSM_PREFIX is required in lambda when APP_REPORT_REPEAT is %s", ReportRepeatDaily)) + } + return rep +} + // ShouldMonitorBranch returns true if merges into branch are checked for // compliance. func (c *Config) ShouldMonitorBranch(branch string) bool { @@ -639,11 +843,12 @@ func (c *Config) ShouldMonitorBranch(branch string) bool { // RedactedConfig is the configuration with secrets redacted, safe to log or // return from the admin API. type RedactedConfig struct { - LogLevel string `json:"log_level"` - BasePath string `json:"base_path"` - PublicURL string `json:"public_url"` - InstallerEnabled bool `json:"installer_enabled"` - AdminToken string `json:"admin_token"` + LogLevel string `json:"log_level"` + BasePath string `json:"base_path"` + PublicURL string `json:"public_url"` + InstallerEnabled bool `json:"installer_enabled"` + SlackSetupEnabled bool `json:"slack_setup_enabled"` + AdminToken string `json:"admin_token"` GitHubOrg string `json:"github_org"` GitHubAppID int64 `json:"github_app_id"` @@ -670,13 +875,24 @@ type RedactedConfig struct { SecurityAlertsMinAgeDays int `json:"security_alerts_min_age_days"` SecurityAlertsMinSeverity string `json:"security_alerts_min_severity"` - SlackEnabled bool `json:"slack_enabled"` - SlackToken string `json:"slack_token"` - SlackChannel string `json:"slack_channel"` - SlackChannelPRBypass string `json:"slack_channel_pr_bypass"` - SlackChannelOktaSync string `json:"slack_channel_okta_sync"` - SlackChannelOrphanedUsers string `json:"slack_channel_orphaned_users"` - SlackChannelSecurityAlerts string `json:"slack_channel_security_alerts"` + SlackEnabled bool `json:"slack_enabled"` + SlackPending bool `json:"slack_pending"` + SlackToken string `json:"slack_token"` + SlackSigningSecret string `json:"slack_signing_secret"` + SlackAppName string `json:"slack_app_name"` + SlackCommand string `json:"slack_command"` + SlackCommandAllowedUsers []string `json:"slack_command_allowed_users"` + SlackChannel string `json:"slack_channel"` + SlackChannelPRBypass string `json:"slack_channel_pr_bypass"` + SlackChannelOktaSync string `json:"slack_channel_okta_sync"` + SlackChannelOrphanedUsers string `json:"slack_channel_orphaned_users"` + SlackChannelSecurityAlerts string `json:"slack_channel_security_alerts"` + + ReportRepeat string `json:"report_repeat"` + ReportDailyTime string `json:"report_daily_time"` + ReportTimezone string `json:"report_timezone"` + ReportStateSSMPrefix string `json:"report_state_ssm_prefix"` + ReportStateFile string `json:"report_state_file"` } const redactedValue = "***REDACTED***" @@ -691,11 +907,12 @@ func redact[T string | []byte](v T) string { // Redacted returns the configuration with secrets redacted. func (c *Config) Redacted() RedactedConfig { return RedactedConfig{ - LogLevel: c.LogLevel.String(), - BasePath: c.Server.BasePath, - PublicURL: c.Server.PublicURL, - InstallerEnabled: c.Installer.Enabled, - AdminToken: redact(c.AdminToken), + LogLevel: c.LogLevel.String(), + BasePath: c.Server.BasePath, + PublicURL: c.Server.PublicURL, + InstallerEnabled: c.Installer.Enabled, + SlackSetupEnabled: c.SlackApp.SetupEnabled, + AdminToken: redact(c.AdminToken), GitHubOrg: c.GitHub.Org, GitHubAppID: c.GitHub.AppID, @@ -723,11 +940,22 @@ func (c *Config) Redacted() RedactedConfig { SecurityAlertsMinSeverity: c.SecurityAlerts.MinSeverity, SlackEnabled: c.Slack.Enabled, + SlackPending: c.Slack.Pending, SlackToken: redact(c.Slack.Token), + SlackSigningSecret: redact(c.Slack.SigningSecret), + SlackAppName: c.SlackApp.Name, + SlackCommand: c.SlackApp.Command, + SlackCommandAllowedUsers: c.Slack.CommandAllowedUsers, SlackChannel: c.Slack.Channel, SlackChannelPRBypass: c.Slack.ChannelPRBypass, SlackChannelOktaSync: c.Slack.ChannelOktaSync, SlackChannelOrphanedUsers: c.Slack.ChannelOrphanedUsers, SlackChannelSecurityAlerts: c.Slack.ChannelSecurityAlerts, + + ReportRepeat: c.Reports.Repeat, + ReportDailyTime: c.Reports.DailyTime.String(), + ReportTimezone: c.Reports.Location.String(), + ReportStateSSMPrefix: c.Reports.StateSSMPrefix, + ReportStateFile: c.Reports.StateFile, } } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a9815ab..4b39865 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -4,11 +4,15 @@ import ( "context" "encoding/json" "errors" + "fmt" "log/slog" "os" "path/filepath" "strings" "testing" + "time" + + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" ) const testPEM = "-----BEGIN RSA PRIVATE KEY-----\nMIIB\n-----END RSA PRIVATE KEY-----" @@ -179,6 +183,23 @@ func TestLoad_Errors(t *testing.T) { {"installer files mode", with(map[string]string{"GITHUB_APP_INSTALLER_ENABLED": "true", "STORAGE_MODE": "files"}), "not supported"}, {"installer ssm without prefix", with(map[string]string{"GITHUB_APP_INSTALLER_ENABLED": "true", "STORAGE_MODE": "aws-ssm"}), "AWS_SSM_PARAMETER_PREFIX"}, {"installer envfile in lambda", with(map[string]string{"GITHUB_APP_INSTALLER_ENABLED": "true", "AWS_LAMBDA_FUNCTION_NAME": "fn"}), "does not persist in lambda"}, + {"slack setup ssm without prefix", with(map[string]string{"APP_SLACK_SETUP_ENABLED": "true", "STORAGE_MODE": "aws-ssm"}), "AWS_SSM_PARAMETER_PREFIX"}, + {"slack setup envfile in lambda", with(map[string]string{"APP_SLACK_SETUP_ENABLED": "true", "AWS_LAMBDA_FUNCTION_NAME": "fn"}), "does not persist in lambda"}, + {"slack command", with(map[string]string{"APP_SLACK_COMMAND": "github-ops"}), "APP_SLACK_COMMAND"}, + {"slack app name", with(map[string]string{"APP_SLACK_APP_NAME": strings.Repeat("x", 36)}), "35 characters"}, + {"slack signing secret alone", with(map[string]string{"APP_SLACK_SIGNING_SECRET": "s"}), "APP_SLACK_SIGNING_SECRET requires"}, + {"slack allowed users alone", with(map[string]string{"APP_SLACK_TOKEN": "xoxb", "APP_SLACK_CHANNEL": "C1", "APP_SLACK_COMMAND_ALLOWED_USERS": "U1AB"}), "requires APP_SLACK_SIGNING_SECRET"}, + {"slack allowed user id", with(map[string]string{"APP_SLACK_COMMAND_ALLOWED_USERS": "@alice"}), "not a slack user id"}, + {"report repeat", with(map[string]string{"APP_REPORT_REPEAT": "hourly"}), "APP_REPORT_REPEAT"}, + {"report time without daily", with(map[string]string{"APP_REPORT_DAILY_TIME": "08:00"}), "requires APP_REPORT_REPEAT=daily"}, + {"report zone without daily", with(map[string]string{"APP_REPORT_TIMEZONE": "UTC"}), "requires APP_REPORT_REPEAT=daily"}, + {"state without daily", with(map[string]string{"APP_STATE_FILE": "state.json"}), "requires APP_REPORT_REPEAT=daily"}, + {"report time", with(map[string]string{"APP_REPORT_REPEAT": "daily", "APP_REPORT_DAILY_TIME": "9am"}), "24-hour time"}, + {"report zone", with(map[string]string{"APP_REPORT_REPEAT": "daily", "APP_REPORT_TIMEZONE": "Mars/Olympus"}), "not a time zone"}, + {"state prefix", with(map[string]string{"APP_REPORT_REPEAT": "daily", "APP_STATE_SSM_PREFIX": "/ops/state"}), "start and end with a slash"}, + {"state both", with(map[string]string{"APP_REPORT_REPEAT": "daily", "APP_STATE_SSM_PREFIX": "/s/", "APP_STATE_FILE": "s.json"}), "mutually exclusive"}, + {"state file in lambda", with(map[string]string{"APP_REPORT_REPEAT": "daily", "APP_STATE_FILE": "s.json", "AWS_LAMBDA_FUNCTION_NAME": "fn"}), "does not persist in lambda"}, + {"no state in lambda", with(map[string]string{"APP_REPORT_REPEAT": "daily", "AWS_LAMBDA_FUNCTION_NAME": "fn"}), "APP_STATE_SSM_PREFIX is required in lambda"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -190,6 +211,127 @@ func TestLoad_Errors(t *testing.T) { } } +func TestLoad_SlackCommands(t *testing.T) { + cfg, err := load(t, with(map[string]string{ + "APP_SLACK_TOKEN": "xoxb-1", + "APP_SLACK_CHANNEL": "C1", + "APP_SLACK_SIGNING_SECRET": "signing", + "APP_SLACK_COMMAND_ALLOWED_USERS": "U0123ABCD, W0123ABCD", + "APP_SLACK_COMMAND": "/ops", + "APP_SLACK_APP_NAME": "Ops", + })) + if err != nil { + t.Fatal(err) + } + if !cfg.Slack.CommandsEnabled() || cfg.Slack.Pending || strings.Join(cfg.Slack.CommandAllowedUsers, ",") != "U0123ABCD,W0123ABCD" { + t.Errorf("slack = %+v", cfg.Slack) + } + if cfg.SlackApp.Command != "/ops" || cfg.SlackApp.Name != "Ops" || cfg.SlackApp.SetupEnabled { + t.Errorf("slack app = %+v", cfg.SlackApp) + } + + cfg, err = load(t, baseEnv()) + if err != nil { + t.Fatal(err) + } + if cfg.Slack.CommandsEnabled() || cfg.SlackApp.Command != DefaultSlackCommand || cfg.SlackApp.Name != DefaultSlackAppName { + t.Errorf("defaults: slack = %+v, slack app = %+v", cfg.Slack, cfg.SlackApp) + } +} + +func TestLoad_SlackSetupPending(t *testing.T) { + tokenARN := "arn:aws:ssm:us-east-1:123456789012:parameter/ops/APP_SLACK_TOKEN" + secretARN := "arn:aws:ssm:us-east-1:123456789012:parameter/ops/APP_SLACK_SIGNING_SECRET" + m := with(map[string]string{ + "APP_SLACK_SETUP_ENABLED": "true", + "STORAGE_MODE": "aws-ssm", + "AWS_SSM_PARAMETER_PREFIX": "/ops/", + "APP_SLACK_TOKEN": tokenARN, + "APP_SLACK_SIGNING_SECRET": secretARN, + "APP_SLACK_CHANNEL": "C1", + }) + saved := map[string]string{} + env := envOf(m) + env.ResolveSSM = func(_ context.Context, arn string) (string, error) { + if v, ok := saved[arn]; ok { + return v, nil + } + return "", fmt.Errorf("failed to get parameter: %w", &ssmtypes.ParameterNotFound{}) + } + + // before the setup page saves the credentials, slack is pending + cfg, err := Load(context.Background(), env) + if err != nil { + t.Fatal(err) + } + if cfg.Slack.Enabled || !cfg.Slack.Pending || cfg.Slack.CommandsEnabled() { + t.Errorf("before setup: slack = %+v", cfg.Slack) + } + if cfg.Installer.SSMParameterPrefix != "/ops/" { + t.Errorf("installer = %+v", cfg.Installer) + } + + saved[tokenARN], saved[secretARN] = "xoxb-1", "signing" + cfg, err = Load(context.Background(), env) + if err != nil { + t.Fatal(err) + } + if !cfg.Slack.Enabled || cfg.Slack.Pending || !cfg.Slack.CommandsEnabled() { + t.Errorf("after setup: slack = %+v", cfg.Slack) + } + + // a channel can be set after the app is installed + delete(m, "APP_SLACK_CHANNEL") + if cfg, err = Load(context.Background(), env); err != nil || !cfg.Slack.Pending { + t.Errorf("without a channel: err = %v, slack = %+v", err, cfg.Slack) + } + + // other ssm failures are still errors + env.ResolveSSM = func(context.Context, string) (string, error) { return "", errors.New("access denied") } + if _, err := Load(context.Background(), env); err == nil || !strings.Contains(err.Error(), "access denied") { + t.Errorf("error = %v, want the ssm failure", err) + } + + // without the setup page, a missing parameter is an error + m["APP_SLACK_SETUP_ENABLED"] = "false" + env.ResolveSSM = func(context.Context, string) (string, error) { + return "", fmt.Errorf("failed to get parameter: %w", &ssmtypes.ParameterNotFound{}) + } + if _, err := Load(context.Background(), env); err == nil { + t.Error("missing slack token parameter loaded without the setup page") + } +} + +func TestLoad_Reports(t *testing.T) { + cfg, err := load(t, baseEnv()) + if err != nil { + t.Fatal(err) + } + if r := cfg.Reports; r.Repeat != ReportRepeatEveryRun || r.DailyTime != DefaultReportDailyTime || r.Location != time.UTC { + t.Errorf("defaults = %+v", r) + } + + cfg, err = load(t, with(map[string]string{ + "APP_REPORT_REPEAT": "Daily", + "APP_REPORT_DAILY_TIME": "08:30", + "APP_REPORT_TIMEZONE": "America/New_York", + "APP_STATE_SSM_PREFIX": "/ops/state/", + "AWS_LAMBDA_FUNCTION_NAME": "fn", + })) + if err != nil { + t.Fatal(err) + } + r := cfg.Reports + if r.Repeat != ReportRepeatDaily || r.DailyTime.String() != "08:30" || r.Location.String() != "America/New_York" || r.StateSSMPrefix != "/ops/state/" { + t.Errorf("reports = %+v", r) + } + + // outside lambda, state may be kept in memory + if _, err := load(t, with(map[string]string{"APP_REPORT_REPEAT": "daily"})); err != nil { + t.Errorf("daily without a state store: %v", err) + } +} + func TestLoad_ReportsEveryProblem(t *testing.T) { _, err := load(t, map[string]string{"APP_LOG_LEVEL": "loud"}) if err == nil { @@ -301,7 +443,7 @@ func TestWebURLFromAPI(t *testing.T) { } func TestRedacted(t *testing.T) { - cfg, err := load(t, with(map[string]string{"APP_ADMIN_TOKEN": "0123456789abcdef", "APP_SLACK_TOKEN": "xoxb-secret", "APP_SLACK_CHANNEL": "C1"})) + cfg, err := load(t, with(map[string]string{"APP_ADMIN_TOKEN": "0123456789abcdef", "APP_SLACK_TOKEN": "xoxb-secret", "APP_SLACK_CHANNEL": "C1", "APP_SLACK_SIGNING_SECRET": "signing-secret"})) if err != nil { t.Fatal(err) } @@ -309,7 +451,7 @@ func TestRedacted(t *testing.T) { if err != nil { t.Fatal(err) } - for _, secret := range []string{"0123456789abcdef", "xoxb-secret", "whsec", "BEGIN RSA"} { + for _, secret := range []string{"0123456789abcdef", "xoxb-secret", "signing-secret", "whsec", "BEGIN RSA"} { if strings.Contains(string(raw), secret) { t.Errorf("redacted config leaks %q", secret) } diff --git a/internal/domain/interfaces.go b/internal/domain/interfaces.go index 5d4c8ae..572c650 100644 --- a/internal/domain/interfaces.go +++ b/internal/domain/interfaces.go @@ -59,4 +59,19 @@ type Notifier interface { // NotifySecurityAlerts sends a notification about stale security // alerts across the organization. NotifySecurityAlerts(ctx context.Context, report *SecurityAlertsReport, githubOrg string) error + + // ReplyToCommand answers a Slack slash command through the response + // URL Slack sent with it. Only the user who ran the command sees the + // reply. + ReplyToCommand(ctx context.Context, responseURL, text string) error +} + +// StateStore keeps small records that must outlive a run, such as what each +// report last posted and when. Implemented by internal/state. +type StateStore interface { + // Get returns the record stored under key, or nil if there is none. + Get(ctx context.Context, key string) ([]byte, error) + + // Put stores a record under key, replacing any record already there. + Put(ctx context.Context, key string, value []byte) error } diff --git a/internal/fakes/fakes.go b/internal/fakes/fakes.go index 0045589..652c096 100644 --- a/internal/fakes/fakes.go +++ b/internal/fakes/fakes.go @@ -147,6 +147,7 @@ type Notifier struct { OktaSyncs [][]*domain.SyncReport OrphanedUsers []*domain.OrphanedUsersReport SecurityAlerts []*domain.SecurityAlertsReport + Replies []Reply } var _ domain.Notifier = (*Notifier)(nil) @@ -182,3 +183,35 @@ func (f *Notifier) NotifySecurityAlerts(_ context.Context, report *domain.Securi f.SecurityAlerts = append(f.SecurityAlerts, report) return f.Err } + +func (f *Notifier) ReplyToCommand(_ context.Context, responseURL, text string) error { + f.record("ReplyToCommand") + f.mu.Lock() + defer f.mu.Unlock() + f.Replies = append(f.Replies, Reply{ResponseURL: responseURL, Text: text}) + return f.Err +} + +// Reply is a slash command reply the fake Notifier was asked to send. +type Reply struct { + ResponseURL string + Text string +} + +// Sent returns how many notifications of every kind were sent, not +// counting command replies. +func (f *Notifier) Sent() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.PRBypasses) + len(f.OktaSyncs) + len(f.OrphanedUsers) + len(f.SecurityAlerts) +} + +// LastReply returns the text of the last command reply, or "". +func (f *Notifier) LastReply() string { + f.mu.Lock() + defer f.mu.Unlock() + if len(f.Replies) == 0 { + return "" + } + return f.Replies[len(f.Replies)-1].Text +} diff --git a/internal/notifiers/slack.go b/internal/notifiers/slack.go index 91b1e4e..3cea54b 100644 --- a/internal/notifiers/slack.go +++ b/internal/notifiers/slack.go @@ -2,8 +2,10 @@ package notifiers import ( + "context" "fmt" "net/http" + "net/url" "strings" "time" @@ -59,11 +61,18 @@ type Options struct { // SlackNotifier sends formatted messages to Slack channels. type SlackNotifier struct { client *slack.Client + httpClient *http.Client channels SlackChannels messages SlackMessages githubWebURL string + // replyHost is the only host command replies are sent to + replyHost string } +// slackReplyHost is the host of the response URLs Slack sends with slash +// commands. +const slackReplyHost = "hooks.slack.com" + var _ domain.Notifier = (*SlackNotifier)(nil) // New creates a SlackNotifier. @@ -81,12 +90,36 @@ func New(opts Options) *SlackNotifier { if webURL == "" { webURL = "https://github.com" } + replyHost := slackReplyHost + if opts.APIURL != "" { + // tests point both at one mock server + if u, err := url.Parse(opts.APIURL); err == nil { + replyHost = u.Host + } + } return &SlackNotifier{ client: slack.New(opts.Token, slackOpts...), + httpClient: httpClient, channels: opts.Channels, messages: opts.Messages, githubWebURL: webURL, + replyHost: replyHost, + } +} + +// ReplyToCommand answers a slash command through its response URL, which +// must be a Slack URL, so a forged job cannot make the app send requests +// elsewhere. +func (s *SlackNotifier) ReplyToCommand(ctx context.Context, responseURL, text string) error { + u, err := url.Parse(responseURL) + if err != nil || u.Host != s.replyHost || (u.Scheme != "https" && s.replyHost == slackReplyHost) { + return fmt.Errorf("failed to reply to slack command: response url is not a slack url") + } + msg := &slack.WebhookMessage{Text: text, ResponseType: slack.ResponseTypeEphemeral} + if err := slack.PostWebhookCustomHTTPContext(ctx, responseURL, s.httpClient, msg); err != nil { + return fmt.Errorf("failed to reply to slack command: %w", err) } + return nil } // channelFor returns the channel for a notification type, falling back to @@ -98,18 +131,18 @@ func (s *SlackNotifier) channelFor(typeChannel string) string { return s.channels.Default } -// escape makes untrusted text safe to include in Slack mrkdwn, so text such +// Escape makes untrusted text safe to include in Slack mrkdwn, so text such // as a PR title cannot mention channels or users or add links. -func escape(s string) string { +func Escape(s string) string { return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(s) } // link returns a mrkdwn link with escaped text. func link(url, text string) string { if url == "" { - return escape(text) + return Escape(text) } - return fmt.Sprintf("<%s|%s>", escape(url), escape(text)) + return fmt.Sprintf("<%s|%s>", Escape(url), Escape(text)) } func mrkdwn(text string) *slack.TextBlockObject { diff --git a/internal/notifiers/slack_messages.go b/internal/notifiers/slack_messages.go index 57724b0..3ca4031 100644 --- a/internal/notifiers/slack_messages.go +++ b/internal/notifiers/slack_messages.go @@ -32,21 +32,21 @@ func (s *SlackNotifier) NotifyPRBypass(ctx context.Context, result *domain.PRCom if mergedBy == "" { mergedBy = "unknown" } - mergedByText := "Merged by " + escape(mergedBy) + mergedByText := "Merged by " + Escape(mergedBy) if result.UserHasBypass && result.UserBypassReason != "" { - mergedByText += " (" + escape(result.UserBypassReason) + ")" + mergedByText += " (" + Escape(result.UserBypassReason) + ")" } title := fmt.Sprintf("%s#%d", repoFullName, pr.GetNumber()) blocks := []slack.Block{ slack.NewHeaderBlock(slack.NewTextBlockObject(slack.PlainTextType, "🚨 Branch Protection Bypassed", false, false)), - section(fmt.Sprintf("%s — %s", link(pr.GetHTMLURL(), title), escape(pr.GetTitle()))), - section(mergedByText + " into `" + escape(result.BaseBranch) + "`"), + section(fmt.Sprintf("%s — %s", link(pr.GetHTMLURL(), title), Escape(pr.GetTitle()))), + section(mergedByText + " into `" + Escape(result.BaseBranch) + "`"), } violations := make([]string, 0, len(result.Violations)) for _, v := range result.Violations { - violations = append(violations, "• "+escape(v.Description)) + violations = append(violations, "• "+Escape(v.Description)) } blocks = append(blocks, listSections("*Violations:*", violations)...) @@ -82,13 +82,13 @@ func (s *SlackNotifier) NotifyOktaSync(ctx context.Context, reports []*domain.Sy unchanged = append(unchanged, "• "+team) } for _, err := range report.Errors { - errs = append(errs, fmt.Sprintf("• %s: %s", escape(report.Rule), escape(err))) + errs = append(errs, fmt.Sprintf("• %s: %s", Escape(report.Rule), Escape(err))) } for _, m := range report.MembersSkippedExternal { - skippedExternal = append(skippedExternal, "• "+escape(m)) + skippedExternal = append(skippedExternal, "• "+Escape(m)) } for _, m := range report.MembersSkippedNoGHUsername { - skippedNoUsername = append(skippedNoUsername, "• "+escape(m)) + skippedNoUsername = append(skippedNoUsername, "• "+Escape(m)) } } @@ -145,7 +145,7 @@ func (s *SlackNotifier) NotifyOrphanedUsers(ctx context.Context, report *domain. slices.SortFunc(users, func(a, b string) int { return strings.Compare(strings.ToLower(a), strings.ToLower(b)) }) lines := make([]string, 0, len(users)) for _, user := range users { - lines = append(lines, "• `"+escape(user)+"`") + lines = append(lines, "• `"+Escape(user)+"`") } blocks := []slack.Block{ @@ -174,7 +174,7 @@ func (s *SlackNotifier) NotifySecurityAlerts(ctx context.Context, report *domain blocks := []slack.Block{ slack.NewHeaderBlock(slack.NewTextBlockObject(slack.PlainTextType, "Security Alerts Report", false, false)), section(fmt.Sprintf("*%d* open alert(s) across *%d* repository(s) in `%s`", - report.TotalAlerts, report.RepoCount(), escape(githubOrg))), + report.TotalAlerts, report.RepoCount(), Escape(githubOrg))), } repos := sortedReposByAlertCount(report.AlertsByRepo) @@ -188,12 +188,12 @@ func (s *SlackNotifier) NotifySecurityAlerts(ctx context.Context, report *domain errs := make([]string, 0, len(report.Errors)) for _, e := range report.Errors { - errs = append(errs, "• "+escape(e)) + errs = append(errs, "• "+Escape(e)) } 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))))) + "Open alerts older than %d days with severity %s or above", report.MinAgeDays, Escape(report.MinSeverity))))) 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 a8dd240..e1f63c7 100644 --- a/internal/notifiers/slack_test.go +++ b/internal/notifiers/slack_test.go @@ -74,7 +74,7 @@ func checkLimits(t *testing.T, p posted) { } func TestEscape(t *testing.T) { - got := escape(" & ") + got := Escape(" & ") want := "<!channel> & <https://evil.example|click>" if got != want { t.Errorf("escape = %q, want %q", got, want) @@ -256,3 +256,30 @@ func TestTruncateRunes(t *testing.T) { t.Errorf("truncateRunes = %q", got) } } + +func TestReplyToCommand(t *testing.T) { + var got map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Errorf("decode reply: %v", err) + } + _, _ = w.Write([]byte("ok")) + })) + t.Cleanup(srv.Close) + + n := New(Options{Token: "xoxb-test", APIURL: srv.URL + "/api/"}) + if err := n.ReplyToCommand(context.Background(), srv.URL+"/commands/T1/1/abc", "done"); err != nil { + t.Fatal(err) + } + if got["text"] != "done" || got["response_type"] != "ephemeral" || got["replace_original"] != false { + t.Errorf("reply = %v", got) + } + + // only slack's response urls are accepted + n = New(Options{Token: "xoxb-test"}) + for _, u := range []string{srv.URL + "/commands", "http://hooks.slack.com/commands/T1", "https://example.com/commands", "::"} { + if err := n.ReplyToCommand(context.Background(), u, "done"); err == nil { + t.Errorf("reply sent to %q", u) + } + } +} diff --git a/internal/service/service.go b/internal/service/service.go index 58b8e1d..dfb00f2 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -1,8 +1,8 @@ // Package service runs the application for both entry points, the HTTP // server and the Lambda function. It loads the configuration through a // github-app-setup-go runtime, so the configuration can be loaded lazily, -// retried, and reloaded after the installer saves new credentials, and it -// serves the health, installer, and application routes. +// retried, and reloaded after an installer saves new credentials, and it +// serves the health, installer, Slack setup, and application routes. package service import ( @@ -26,9 +26,11 @@ import ( "github.com/go-chi/chi/v5" "github.com/joho/godotenv" + "github.com/cruxstack/github-ops-app/assets" "github.com/cruxstack/github-ops-app/internal/app" "github.com/cruxstack/github-ops-app/internal/config" "github.com/cruxstack/github-ops-app/internal/setup" + "github.com/cruxstack/github-ops-app/internal/slackapp" ) // JobTimeout bounds a webhook, a scheduled action, or a background job. @@ -56,6 +58,10 @@ type Options struct { Env config.Env // Store replaces the installer's credential store, for tests. Store configstore.Store + // SlackStore and SlackAPI replace the Slack setup's credential store + // and Slack API, for tests. + SlackStore slackapp.Store + SlackAPI slackapp.API // AppOptions are passed to app.New. AppOptions []app.Option // RetryInterval is the wait between load attempts in ModeLambda. @@ -97,7 +103,8 @@ func New(boot *config.Bootstrap, opts Options) (*Service, error) { s.jobs = &jobs{logger: opts.Logger} s.appOpts = append(s.appOpts, app.WithBackground(s.jobs)) - if boot.Installer.Enabled && boot.Installer.StorageMode == configstore.StorageModeEnvFile { + installing := boot.Installer.Enabled || boot.SlackApp.SetupEnabled + if installing && boot.Installer.StorageMode == configstore.StorageModeEnvFile { s.envFile = boot.Installer.StorageDir s.explicit = make(map[string]bool) for _, kv := range os.Environ() { @@ -130,13 +137,18 @@ func New(boot *config.Bootstrap, opts Options) (*Service, error) { } s.runtime = runtime - var installerHandler http.Handler + var installerHandler, slackSetup http.Handler if boot.Installer.Enabled { if installerHandler, err = s.newInstaller(); err != nil { return nil, err } } - s.handler = s.newRouter(installerHandler) + if boot.SlackApp.SetupEnabled { + if slackSetup, err = s.newSlackSetup(); err != nil { + return nil, err + } + } + s.handler = s.newRouter(installerHandler, slackSetup) return s, nil } @@ -176,7 +188,13 @@ func (s *Service) load(ctx context.Context) error { "pr_compliance", cfg.PRCompliance.Enabled, "security_alerts", cfg.SecurityAlerts.Enabled, "slack", cfg.Slack.Enabled, + "slack_commands", cfg.Slack.CommandsEnabled(), + "report_repeat", cfg.Reports.Repeat, "admin_api", cfg.AdminToken != "") + if cfg.Slack.Pending { + s.logger.WarnContext(ctx, "slack is off until its setup is finished: the token or channel is not set", + "setup_url", s.boot.Server.BasePath+slackapp.PathSetup) + } return nil } @@ -272,6 +290,17 @@ func (s *Service) RunScheduled(ctx context.Context, action string) error { return a.RunScheduled(ctx, action) } +// RunJob runs a job started from Slack with a detached, bounded context. +func (s *Service) RunJob(ctx context.Context, job app.Job) error { + a, err := s.EnsureLoaded(ctx) + if err != nil { + return fmt.Errorf("service not ready: %w", err) + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), JobTimeout) + defer cancel() + return a.RunJob(ctx, job) +} + func (s *Service) newInstaller() (http.Handler, error) { cfg := installer.Config{ Store: s.runtime.Store(), @@ -292,13 +321,72 @@ func (s *Service) newInstaller() (http.Handler, error) { return h, nil } +// newSlackSetup creates the Slack setup, which saves credentials where the +// GitHub App installer does and reloads the configuration once the app is +// installed. +func (s *Service) newSlackSetup() (http.Handler, error) { + store := s.opts.SlackStore + if store == nil { + if s.boot.Installer.StorageMode == configstore.StorageModeAWSSSM { + ssmStore, err := slackapp.NewSSMStore(context.Background(), s.boot.Installer.SSMParameterPrefix, s.boot.Installer.SSMKMSKeyID, nil) + if err != nil { + return nil, fmt.Errorf("failed to create slack setup credential store: %w", err) + } + store = ssmStore + } else { + store = slackapp.NewEnvFileStore(s.boot.Installer.StorageDir) + } + } + api := s.opts.SlackAPI + if api == nil { + api = slackapp.NewSlackAPI(nil, "") + } + h, err := slackapp.New(slackapp.Options{ + Name: s.boot.SlackApp.Name, + Command: s.boot.SlackApp.Command, + PublicURL: s.boot.Server.PublicURL, + BasePath: s.boot.Server.BasePath, + Store: store, + API: api, + Icon: assets.SlackIcon, + Logger: s.logger, + OnInstalled: func(ctx context.Context) { + if err := s.runtime.Reload(ctx); err != nil { + s.logger.WarnContext(ctx, "failed to reload the configuration after the slack app was installed", "error", err.Error()) + } + }, + Channels: s.slackChannels, + }) + if err != nil { + return nil, fmt.Errorf("failed to create slack setup: %w", err) + } + return h, nil +} + +// slackChannels returns the channels the loaded application posts in. +func (s *Service) slackChannels() []string { + a := s.current.Load() + if a == nil { + return nil + } + sc := a.Config().Slack + var channels []string + for _, ch := range []string{sc.Channel, sc.ChannelPRBypass, sc.ChannelOktaSync, sc.ChannelOrphanedUsers, sc.ChannelSecurityAlerts} { + if ch != "" && !slices.Contains(channels, ch) { + channels = append(channels, ch) + } + } + return channels +} + // newRouter serves, under the base path: // // GET /healthz liveness, always 200 // GET /readyz 200 once the configuration is loaded // GET /setup, /callback, ... the installer, when enabled +// GET /slack/setup, /slack/oauth/... the slack setup, when enabled // everything else the application, once loaded -func (s *Service) newRouter(installerHandler http.Handler) http.Handler { +func (s *Service) newRouter(installerHandler, slackSetup http.Handler) http.Handler { base := s.boot.Server.BasePath r := chi.NewRouter() r.Use(s.recoverer, s.detach) @@ -321,6 +409,13 @@ func (s *Service) newRouter(installerHandler http.Handler) http.Handler { r.Post(base+"/setup/disable", h.ServeHTTP) r.Get(base+"/callback", h.ServeHTTP) } + if slackSetup != nil { + h := http.StripPrefix(base, slackSetup) + r.Get(base+slackapp.PathSetup, h.ServeHTTP) + r.Post(base+slackapp.PathSetup, h.ServeHTTP) + r.Get(base+slackapp.PathOAuthInstall, h.ServeHTTP) + r.Get(base+slackapp.PathOAuthCallback, h.ServeHTTP) + } r.NotFound(s.serveApp) r.MethodNotAllowed(s.serveApp) diff --git a/internal/service/service_test.go b/internal/service/service_test.go index 6471e25..9c16b8b 100644 --- a/internal/service/service_test.go +++ b/internal/service/service_test.go @@ -5,10 +5,12 @@ import ( "crypto/rand" "crypto/rsa" "crypto/x509" + "encoding/json" "encoding/pem" "log/slog" "net/http" "net/http/httptest" + "net/url" "os" "path/filepath" "regexp" @@ -22,6 +24,7 @@ import ( "github.com/cruxstack/github-ops-app/internal/app" "github.com/cruxstack/github-ops-app/internal/config" "github.com/cruxstack/github-ops-app/internal/fakes" + "github.com/cruxstack/github-ops-app/internal/slackapp" ) var discard = slog.New(slog.DiscardHandler) @@ -343,3 +346,107 @@ func TestDetach_SurvivesClientCancel(t *testing.T) { t.Errorf("job context canceled with the request: %v", jobErr) } } + +// slackAPI is a fake slackapp.API that installs into one workspace. +type slackAPI struct{} + +func (slackAPI) CreateApp(context.Context, string, json.RawMessage) (slackapp.CreatedApp, error) { + return slackapp.CreatedApp{}, nil +} + +func (slackAPI) SetIcon(context.Context, string, string, []byte) error { return nil } + +func (slackAPI) ExchangeCode(context.Context, string, string, string, string) (slackapp.Installation, error) { + return slackapp.Installation{BotToken: "xoxb-installed", TeamID: "T1", TeamName: "Acme", UserID: "U0ME"}, nil +} + +func TestSlackSetup_InstallTurnsSlackOn(t *testing.T) { + envFile := filepath.Join(t.TempDir(), ".env") + e := &mapEnv{m: map[string]string{ + "APP_GITHUB_ORG": "acme", + "APP_GITHUB_APP_ID": "1", + "APP_GITHUB_APP_PRIVATE_KEY": keyPEM(t), + "APP_GITHUB_WEBHOOK_SECRET": "s", + "APP_BASE_PATH": "/prod", + "APP_PUBLIC_URL": "https://ops.example.com/prod", + "APP_SLACK_SETUP_ENABLED": "true", + "APP_SLACK_CHANNEL": "C0OPS", + "STORAGE_MODE": "envfile", + "STORAGE_DIR": envFile, + }} + boot, err := config.LoadBootstrap(e.env()) + if err != nil { + t.Fatal(err) + } + svc, err := New(boot, Options{ + Mode: ModeServer, + Logger: discard, + Env: e.env(), + SlackAPI: slackAPI{}, + AppOptions: []app.Option{app.WithGitHubClient(&fakes.GitHub{})}, + }) + if err != nil { + t.Fatal(err) + } + if err := svc.Start(t.Context()); err != nil { + t.Fatal(err) + } + if sc := svc.current.Load().Config().Slack; sc.Enabled || !sc.Pending { + t.Fatalf("before setup: slack = %+v", sc) + } + h := svc.Handler() + + rec := get(t, h, http.MethodGet, "/prod/slack/setup") + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Create the Slack app") { + t.Fatalf("setup page: %d", rec.Code) + } + + // as if the page had created the app + err = slackapp.NewEnvFileStore(envFile).Save(t.Context(), map[string]string{ + slackapp.EnvClientID: "1.2", + slackapp.EnvClientSecret: strings.Repeat("c", 32), + slackapp.EnvSigningSecret: strings.Repeat("s", 32), + }) + if err != nil { + t.Fatal(err) + } + rec = get(t, h, http.MethodGet, "/prod/slack/oauth/install") + loc, err := url.Parse(rec.Header().Get("Location")) + if rec.Code != http.StatusSeeOther || err != nil { + t.Fatalf("install: %d %s", rec.Code, rec.Header().Get("Location")) + } + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/prod/slack/oauth/callback?code=c&state="+loc.Query().Get("state"), nil) + for _, c := range rec.Result().Cookies() { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Installed in Acme") { + t.Fatalf("callback: %d %s", rec.Code, rec.Body) + } + + // the install reloads the configuration with the saved credentials + sc := svc.current.Load().Config().Slack + if !sc.Enabled || sc.Pending || sc.Token != "xoxb-installed" || !sc.CommandsEnabled() { + t.Errorf("after setup: slack = %+v", sc) + } + if rec := get(t, h, http.MethodPost, "/prod/slack/commands"); rec.Code != http.StatusUnauthorized { + t.Errorf("unsigned slash command: %d, want 401 from the app", rec.Code) + } +} + +func TestSlackSetup_OffByDefault(t *testing.T) { + e := &mapEnv{m: map[string]string{ + "APP_GITHUB_ORG": "acme", + "APP_GITHUB_APP_ID": "1", + "APP_GITHUB_APP_PRIVATE_KEY": keyPEM(t), + "APP_GITHUB_WEBHOOK_SECRET": "s", + }} + svc := newService(t, e.env(), ModeServer, nil) + if err := svc.Start(t.Context()); err != nil { + t.Fatal(err) + } + if rec := get(t, svc.Handler(), http.MethodGet, "/slack/setup"); rec.Code != http.StatusNotFound { + t.Errorf("slack setup without APP_SLACK_SETUP_ENABLED: %d, want 404", rec.Code) + } +} diff --git a/internal/slackapp/api.go b/internal/slackapp/api.go new file mode 100644 index 0000000..0d2eaa7 --- /dev/null +++ b/internal/slackapp/api.go @@ -0,0 +1,123 @@ +package slackapp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/slack-go/slack" +) + +// API is the part of Slack's Web API the setup uses. +type API interface { + // CreateApp creates an app from a manifest with an app configuration + // token. + CreateApp(ctx context.Context, configToken string, manifest json.RawMessage) (CreatedApp, error) + // SetIcon sets an app's icon with an app configuration token. + SetIcon(ctx context.Context, configToken, appID string, png []byte) error + // ExchangeCode finishes an OAuth install and returns its bot token. + ExchangeCode(ctx context.Context, clientID, clientSecret, code, redirectURI string) (Installation, error) +} + +// CreatedApp is a new app's ID and credentials. +type CreatedApp struct { + AppID string + ClientID string + ClientSecret string + SigningSecret string +} + +// Installation is the result of an OAuth install. +type Installation struct { + BotToken string + TeamID string + TeamName string + AppID string + // UserID is who installed the app. + UserID string +} + +// SlackAPI calls Slack's Web API. +type SlackAPI struct { + client *slack.Client + httpClient *http.Client + apiURL string +} + +var _ API = (*SlackAPI)(nil) + +// NewSlackAPI creates a SlackAPI. apiURL overrides Slack's API URL, for +// tests; it ends with a slash. +func NewSlackAPI(httpClient *http.Client, apiURL string) *SlackAPI { + if httpClient == nil { + httpClient = &http.Client{Timeout: 30 * time.Second} + } + opts := []slack.Option{slack.OptionHTTPClient(httpClient)} + if apiURL != "" { + opts = append(opts, slack.OptionAPIURL(apiURL)) + } + return &SlackAPI{client: slack.New("", opts...), httpClient: httpClient, apiURL: apiURL} +} + +// CreateApp creates an app from a manifest. +func (s *SlackAPI) CreateApp(ctx context.Context, configToken string, manifest json.RawMessage) (CreatedApp, error) { + resp, err := s.client.CreateManifestRawContext(ctx, manifest, configToken) + if err != nil { + // slack explains a manifest it rejects + var details []string + if resp != nil { + for _, e := range resp.Errors { + details = append(details, e.Pointer+": "+e.Message) + } + } + if len(details) > 0 { + err = fmt.Errorf("%w (%s)", err, strings.Join(details, "; ")) + } + return CreatedApp{}, fmt.Errorf("failed to create slack app: %w", err) + } + if resp.Credentials == nil { + return CreatedApp{}, errors.New("failed to create slack app: slack returned no credentials") + } + return CreatedApp{ + AppID: resp.AppId, + ClientID: resp.Credentials.ClientId, + ClientSecret: resp.Credentials.ClientSecret, + SigningSecret: resp.Credentials.SigningSecret, + }, nil +} + +// SetIcon sets an app's icon. +func (s *SlackAPI) SetIcon(ctx context.Context, configToken, appID string, png []byte) error { + err := s.client.SetAppIconContext(ctx, configToken, appID, slack.SetAppIconParameters{File: bytes.NewReader(png), Filename: "icon.png"}) + if err != nil { + return fmt.Errorf("failed to set icon of slack app %s: %w", appID, err) + } + return nil +} + +// ExchangeCode finishes an OAuth install. +func (s *SlackAPI) ExchangeCode(ctx context.Context, clientID, clientSecret, code, redirectURI string) (Installation, error) { + var opts []slack.OAuthOption + if s.apiURL != "" { + opts = append(opts, slack.OAuthOptionAPIURL(s.apiURL)) + } + resp, err := slack.GetOAuthV2ResponseContext(ctx, s.httpClient, clientID, clientSecret, code, redirectURI, opts...) + if err != nil { + return Installation{}, fmt.Errorf("failed to finish slack install: %w", err) + } + if resp.TokenType != "bot" || !strings.HasPrefix(resp.AccessToken, "xoxb-") { + return Installation{}, errors.New("failed to finish slack install: slack returned no bot token") + } + return Installation{ + BotToken: resp.AccessToken, + TeamID: resp.Team.ID, + TeamName: resp.Team.Name, + AppID: resp.AppID, + UserID: resp.AuthedUser.ID, + }, nil +} diff --git a/internal/slackapp/manifest.go b/internal/slackapp/manifest.go new file mode 100644 index 0000000..4c60bd2 --- /dev/null +++ b/internal/slackapp/manifest.go @@ -0,0 +1,59 @@ +// Package slackapp creates and installs the Slack app from a setup page, +// like the GitHub App installer does for the GitHub App: the page creates +// the app from a manifest, runs Slack's OAuth install, and saves the +// credentials where the installer saves the GitHub App's. +package slackapp + +import ( + "encoding/json" + "strings" +) + +// Paths the setup serves, under the service's base path. +const ( + PathSetup = "/slack/setup" + PathOAuthInstall = "/slack/oauth/install" + PathOAuthCallback = "/slack/oauth/callback" + // PathCommands is where the application answers the slash command. + PathCommands = "/slack/commands" +) + +// BotScopes are the OAuth scopes the app asks for when it is installed: +// posting messages, also to public channels it hasn't joined, and the slash +// command. +var BotScopes = []string{"chat:write", "chat:write.public", "commands"} + +// Manifest returns the Slack app manifest for a deployment whose external +// URL, including its base path, is baseURL. +func Manifest(name, command, baseURL string) json.RawMessage { + base := strings.TrimRight(baseURL, "/") + manifest := map[string]any{ + "_metadata": map[string]any{"major_version": 2, "minor_version": 1}, + "display_information": map[string]any{ + "name": name, + "description": "Okta team sync, PR compliance, and security alert reports for GitHub.", + "background_color": "#10203B", + }, + "features": map[string]any{ + "bot_user": map[string]any{"display_name": name, "always_online": false}, + "slash_commands": []any{map[string]any{ + "command": command, + "url": base + PathCommands, + "description": "Resync Okta groups or post the security alerts report now", + "usage_hint": "sync | security-alerts | help", + "should_escape": false, + }}, + }, + "oauth_config": map[string]any{ + "redirect_urls": []string{base + PathOAuthCallback}, + "scopes": map[string]any{"bot": BotScopes}, + }, + "settings": map[string]any{ + "org_deploy_enabled": false, + "socket_mode_enabled": false, + "token_rotation_enabled": false, + }, + } + raw, _ := json.Marshal(manifest) + return raw +} diff --git a/internal/slackapp/setup.go b/internal/slackapp/setup.go new file mode 100644 index 0000000..1e0cefc --- /dev/null +++ b/internal/slackapp/setup.go @@ -0,0 +1,450 @@ +package slackapp + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "html/template" + "log/slog" + "net/http" + "net/url" + "regexp" + "strings" + "sync" +) + +// slackAuthorizeURL is where the OAuth install starts. +const slackAuthorizeURL = "https://slack.com/oauth/v2/authorize" + +var ( + clientIDPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+$`) + secretPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) +) + +// Options configures the setup Handler. +type Options struct { + // Name and Command are the app's name and slash command. + Name string + Command string + // PublicURL is the service's external URL, including its base path. + // When empty, it is derived from each request and BasePath. + PublicURL string + BasePath string + Store Store + API API + // Icon is the app's icon, a PNG of 512 to 2000 pixels a side. + Icon []byte + Logger *slog.Logger + // OnInstalled runs after the bot token is saved, to load it. + OnInstalled func(ctx context.Context) + // Channels returns the channel IDs the app posts in, when they are + // known. + Channels func() []string +} + +// Handler serves the setup pages. Like the GitHub App installer, it is +// meant to be enabled only until the app is installed. Until then, anyone +// who can reach it can create and install the app, so the installed app's +// credentials are never replaced, and it can't be moved to another +// workspace. +type Handler struct { + opts Options + // mu makes app creation one at a time, so a double click creates one + // app + mu sync.Mutex +} + +// New creates a Handler. +func New(opts Options) (*Handler, error) { + if opts.Store == nil || opts.API == nil { + return nil, errors.New("slack setup needs a credential store and the slack api") + } + if opts.Logger == nil { + opts.Logger = slog.Default() + } + opts.PublicURL = strings.TrimRight(opts.PublicURL, "/") + return &Handler{opts: opts}, nil +} + +// ServeHTTP serves the setup paths, which are relative to the base path. +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + get := r.Method == http.MethodGet || r.Method == http.MethodHead + switch { + case r.URL.Path == PathSetup && get: + notice := setupNotices[r.URL.Query().Get("done")] + h.page(w, r, pageState{notice: notice}) + case r.URL.Path == PathSetup && r.Method == http.MethodPost: + h.submit(w, r) + case r.URL.Path == PathOAuthInstall && get: + h.install(w, r) + case r.URL.Path == PathOAuthCallback && get: + h.callback(w, r) + default: + http.NotFound(w, r) + } +} + +// setupNotices are shown after a form redirects back to the page. +var setupNotices = map[string]string{ + "created": "The Slack app is created. Install it to finish.", + "credentials": "The credentials are saved. Install the app to finish.", + "existing": "This deployment already has a Slack app, so no new one was created. Install it below.", +} + +// status is how far setup has got. +type status struct { + HasApp bool + Installed bool + TeamID string + TeamName string +} + +func (h *Handler) status(ctx context.Context) (status, error) { + var st status + values := make(map[string]string) + for _, name := range []string{EnvSigningSecret, EnvClientID, EnvClientSecret, EnvToken, EnvTeam} { + v, err := h.opts.Store.Get(ctx, name) + if err != nil { + return st, err + } + values[name] = v + } + st.HasApp = values[EnvSigningSecret] != "" && values[EnvClientID] != "" && values[EnvClientSecret] != "" + st.Installed = values[EnvToken] != "" + st.TeamID, st.TeamName, _ = strings.Cut(values[EnvTeam], "|") + return st, nil +} + +// baseURL is the service's external URL, including its base path. +func (h *Handler) baseURL(r *http.Request) string { + if h.opts.PublicURL != "" { + return h.opts.PublicURL + } + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + if proto := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0]); proto == "https" || proto == "http" { + scheme = proto + } + return scheme + "://" + r.Host + h.opts.BasePath +} + +// Cookies are host-only and, over https, Secure with the __Host- prefix. +// Over http, as in local tests, browsers drop Secure cookies. +func cookieName(base, name string) string { + if strings.HasPrefix(base, "https://") { + return "__Host-" + name + } + return name +} + +func setCookie(w http.ResponseWriter, base, name, value string, maxAge int) { + http.SetCookie(w, &http.Cookie{ + Name: cookieName(base, name), + Value: value, + Path: "/", + MaxAge: maxAge, + Secure: strings.HasPrefix(base, "https://"), + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + }) +} + +func cookieValue(r *http.Request, base, name string) string { + c, err := r.Cookie(cookieName(base, name)) + if err != nil { + return "" + } + return c.Value +} + +func equal(a, b string) bool { + return a != "" && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} + +func redirect(w http.ResponseWriter, to string) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Location", to) + w.WriteHeader(http.StatusSeeOther) +} + +const ( + csrfCookie = "github_ops_slack_csrf" + stateCookie = "github_ops_slack_state" +) + +// submit creates the app from a configuration token, or saves the +// credentials of an app created by hand. +func (h *Handler) submit(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + base := h.baseURL(r) + r.Body = http.MaxBytesReader(w, r.Body, 64<<10) + if err := r.ParseForm(); err != nil { + h.page(w, r, pageState{err: "The form couldn't be read. Load the page again and retry."}) + return + } + if !equal(cookieValue(r, base, csrfCookie), r.PostForm.Get("csrf")) { + h.page(w, r, pageState{err: "This form expired. Load the page again and retry."}) + return + } + + h.mu.Lock() + defer h.mu.Unlock() + st, err := h.status(ctx) + if err != nil { + h.storeError(w, r, err) + return + } + if st.Installed { + h.page(w, r, pageState{err: "The app is already installed, so its credentials can't be replaced here."}) + return + } + + var app CreatedApp + done := "credentials" + switch r.PostForm.Get("action") { + case "create": + token := strings.TrimSpace(r.PostForm.Get("config_token")) + if !strings.HasPrefix(token, "xoxe") { + h.page(w, r, pageState{err: "That isn't an app configuration token. They start with xoxe."}) + return + } + // a second click or a stale tab must not create a second app + if st.HasApp { + redirect(w, base+PathSetup+"?done=existing") + return + } + created, err := h.opts.API.CreateApp(ctx, token, Manifest(h.opts.Name, h.opts.Command, base)) + if err != nil { + h.opts.Logger.WarnContext(ctx, "failed to create slack app", "error", err.Error()) + h.page(w, r, pageState{err: fmt.Sprintf("Slack didn't create the app: %s. Generate a fresh token and try again, or create the app yourself below.", err)}) + return + } + app, done = created, "created" + // the icon is cosmetic, so setup goes on without it + if len(h.opts.Icon) > 0 { + if err := h.opts.API.SetIcon(ctx, token, created.AppID, h.opts.Icon); err != nil { + h.opts.Logger.WarnContext(ctx, "failed to set slack app icon", "app_id", created.AppID, "error", err.Error()) + } + } + case "credentials": + app = CreatedApp{ + ClientID: strings.TrimSpace(r.PostForm.Get("client_id")), + ClientSecret: strings.TrimSpace(r.PostForm.Get("client_secret")), + SigningSecret: strings.TrimSpace(r.PostForm.Get("signing_secret")), + } + if !clientIDPattern.MatchString(app.ClientID) || !secretPattern.MatchString(app.ClientSecret) || !secretPattern.MatchString(app.SigningSecret) { + h.page(w, r, pageState{err: "Those don't look like Slack credentials. Copy the Client ID, Client Secret, and Signing Secret from Basic Information, under App Credentials."}) + return + } + default: + h.page(w, r, pageState{err: "Unknown action."}) + return + } + + err = h.opts.Store.Save(ctx, map[string]string{ + EnvSigningSecret: app.SigningSecret, + EnvClientID: app.ClientID, + EnvClientSecret: app.ClientSecret, + }) + if err != nil { + h.storeError(w, r, err) + return + } + h.opts.Logger.InfoContext(ctx, "slack app credentials saved", "app_id", app.AppID) + redirect(w, base+PathSetup+"?done="+done) +} + +// install starts Slack's OAuth install. +func (h *Handler) install(w http.ResponseWriter, r *http.Request) { + base := h.baseURL(r) + clientID, err := h.opts.Store.Get(r.Context(), EnvClientID) + if err != nil { + h.storeError(w, r, err) + return + } + if clientID == "" { + redirect(w, base+PathSetup) + return + } + state := rand.Text() + setCookie(w, base, stateCookie, state, 600) + q := url.Values{ + "client_id": {clientID}, + "scope": {strings.Join(BotScopes, ",")}, + "redirect_uri": {base + PathOAuthCallback}, + "state": {state}, + } + redirect(w, slackAuthorizeURL+"?"+q.Encode()) +} + +// callback finishes the OAuth install and saves the bot token. +func (h *Handler) callback(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + base := h.baseURL(r) + q := r.URL.Query() + if e := q.Get("error"); e != "" { + h.page(w, r, pageState{err: fmt.Sprintf("Slack didn't install the app (%s). Try Install again.", e)}) + return + } + if !equal(cookieValue(r, base, stateCookie), q.Get("state")) { + h.page(w, r, pageState{err: "This install link expired or came from another browser. Start the install again."}) + return + } + + clientID, err := h.opts.Store.Get(ctx, EnvClientID) + if err != nil { + h.storeError(w, r, err) + return + } + clientSecret, err := h.opts.Store.Get(ctx, EnvClientSecret) + if err != nil { + h.storeError(w, r, err) + return + } + inst, err := h.opts.API.ExchangeCode(ctx, clientID, clientSecret, q.Get("code"), base+PathOAuthCallback) + if err != nil { + h.opts.Logger.WarnContext(ctx, "failed to finish slack install", "error", err.Error()) + h.page(w, r, pageState{err: fmt.Sprintf("Slack didn't finish the install: %s", err)}) + return + } + + st, err := h.status(ctx) + if err != nil { + h.storeError(w, r, err) + return + } + if st.TeamID != "" && st.TeamID != inst.TeamID { + h.opts.Logger.WarnContext(ctx, "refused slack install into another workspace", "team_id", inst.TeamID, "installed_team_id", st.TeamID) + h.page(w, r, pageState{err: fmt.Sprintf("This app is already installed in %s. It can't be moved to another workspace from here.", st.TeamName)}) + return + } + err = h.opts.Store.Save(ctx, map[string]string{ + EnvToken: inst.BotToken, + EnvTeam: inst.TeamID + "|" + inst.TeamName, + }) + if err != nil { + h.storeError(w, r, err) + return + } + h.opts.Logger.InfoContext(ctx, "slack app installed", "team_id", inst.TeamID, "app_id", inst.AppID, "slack_user", inst.UserID) + if h.opts.OnInstalled != nil { + h.opts.OnInstalled(ctx) + } + setCookie(w, base, stateCookie, "", -1) + h.page(w, r, pageState{notice: "Installed. The app can post now.", installer: inst.UserID}) +} + +// storeError logs a credential store failure and shows a page without its +// details. +func (h *Handler) storeError(w http.ResponseWriter, r *http.Request, err error) { + h.opts.Logger.ErrorContext(r.Context(), "slack setup failed to read or save credentials", "error", err.Error()) + h.page(w, r, pageState{err: "Couldn't read or save the Slack credentials. The app's logs have the details.", code: http.StatusInternalServerError}) +} + +// pageState is what a page shows besides the setup's status. +type pageState struct { + notice string + err string + code int + // installer is the Slack user ID of who just installed the app + installer string +} + +type pageView struct { + AppName string + Command string + Status status + Notice string + Error string + CSRF string + FormAction string + ManifestURL string + ManifestJSON string + InstallURL string + IconURL template.URL + Channels []channelLink + Installer string +} + +type channelLink struct { + ID, URL string +} + +func (h *Handler) page(w http.ResponseWriter, r *http.Request, ps pageState) { + ctx := r.Context() + base := h.baseURL(r) + st, err := h.status(ctx) + if err != nil && ps.err == "" { + h.storeError(w, r, err) + return + } + + csrf := cookieValue(r, base, csrfCookie) + if csrf == "" { + csrf = rand.Text() + } + manifest := Manifest(h.opts.Name, h.opts.Command, base) + var pretty bytes.Buffer + _ = json.Indent(&pretty, manifest, "", " ") + formAction := PathSetup + if u, err := url.Parse(base); err == nil { + formAction = u.Path + PathSetup + } + + v := pageView{ + AppName: h.opts.Name, + Command: h.opts.Command, + Status: st, + Notice: ps.notice, + Error: ps.err, + CSRF: csrf, + FormAction: formAction, + ManifestURL: "https://api.slack.com/apps?new_app=1&manifest_json=" + url.QueryEscape(string(manifest)), + ManifestJSON: pretty.String(), + InstallURL: base + PathOAuthInstall, + Installer: ps.installer, + } + if len(h.opts.Icon) > 0 { + // the page's own data, so it is safe to mark as a url + v.IconURL = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(h.opts.Icon)) + } + if h.opts.Channels != nil { + for _, ch := range h.opts.Channels() { + link := channelLink{ID: ch} + if st.TeamID != "" { + link.URL = "https://app.slack.com/client/" + url.PathEscape(st.TeamID) + "/" + url.PathEscape(ch) + } + v.Channels = append(v.Channels, link) + } + } + + var buf bytes.Buffer + if err := setupTemplate.Execute(&buf, v); err != nil { + h.opts.Logger.ErrorContext(ctx, "failed to render slack setup page", "error", err.Error()) + http.Error(w, "failed to render the setup page", http.StatusInternalServerError) + return + } + setCookie(w, base, csrfCookie, csrf, 3600) + header := w.Header() + header.Set("Content-Type", "text/html; charset=utf-8") + header.Set("Cache-Control", "no-store") + header.Set("Referrer-Policy", "no-referrer") + header.Set("X-Content-Type-Options", "nosniff") + header.Set("Content-Security-Policy", "default-src 'none'; img-src data:; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'") + code := ps.code + if code == 0 { + code = http.StatusOK + if ps.err != "" { + code = http.StatusBadRequest + } + } + w.WriteHeader(code) + _, _ = w.Write(buf.Bytes()) +} diff --git a/internal/slackapp/setup_test.go b/internal/slackapp/setup_test.go new file mode 100644 index 0000000..246488b --- /dev/null +++ b/internal/slackapp/setup_test.go @@ -0,0 +1,421 @@ +package slackapp + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "maps" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ssm" + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + "github.com/joho/godotenv" +) + +// memStore is an in-memory Store. +type memStore struct { + mu sync.Mutex + values map[string]string + err error +} + +func (m *memStore) Get(_ context.Context, name string) (string, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.values[name], m.err +} + +func (m *memStore) Save(_ context.Context, values map[string]string) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.err != nil { + return m.err + } + if m.values == nil { + m.values = map[string]string{} + } + maps.Copy(m.values, values) + return nil +} + +// fakeAPI is a fake Slack API. +type fakeAPI struct { + created int + manifests []json.RawMessage + icons int + team string + createErr error +} + +func (f *fakeAPI) CreateApp(_ context.Context, token string, manifest json.RawMessage) (CreatedApp, error) { + if f.createErr != nil { + return CreatedApp{}, f.createErr + } + f.created++ + f.manifests = append(f.manifests, manifest) + return CreatedApp{ + AppID: "A1", + ClientID: "123.456", + ClientSecret: strings.Repeat("c", 32), + SigningSecret: strings.Repeat("s", 32), + }, nil +} + +func (f *fakeAPI) SetIcon(context.Context, string, string, []byte) error { + f.icons++ + return nil +} + +func (f *fakeAPI) ExchangeCode(_ context.Context, clientID, clientSecret, code, redirectURI string) (Installation, error) { + if clientID != "123.456" || clientSecret != strings.Repeat("c", 32) || code != "the-code" || + redirectURI != "https://ops.example.com/prod/slack/oauth/callback" { + return Installation{}, errors.New("bad exchange") + } + team := f.team + if team == "" { + team = "T1" + } + return Installation{BotToken: "xoxb-1", TeamID: team, TeamName: "Acme", AppID: "A1", UserID: "U0INSTALLER"}, nil +} + +type setupHarness struct { + h *Handler + store *memStore + api *fakeAPI + installed int + cookies map[string]*http.Cookie +} + +func newSetup(t *testing.T) *setupHarness { + t.Helper() + s := &setupHarness{store: &memStore{}, api: &fakeAPI{}, cookies: map[string]*http.Cookie{}} + h, err := New(Options{ + Name: "GitHub Ops", + Command: "/github-ops", + BasePath: "/prod", + Store: s.store, + API: s.api, + Icon: []byte("png"), + Logger: slog.New(slog.DiscardHandler), + OnInstalled: func(context.Context) { s.installed++ }, + Channels: func() []string { return []string{"C0OPS"} }, + }) + if err != nil { + t.Fatal(err) + } + s.h = h + return s +} + +// do sends a request as a browser behind an https proxy would, keeping +// cookies between requests. +func (s *setupHarness) do(t *testing.T, method, target string, form url.Values) *httptest.ResponseRecorder { + t.Helper() + var req *http.Request + if form != nil { + req = httptest.NewRequestWithContext(context.Background(), method, target, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } else { + req = httptest.NewRequestWithContext(context.Background(), method, target, nil) + } + req.Host = "ops.example.com" + req.Header.Set("X-Forwarded-Proto", "https") + for _, c := range s.cookies { + req.AddCookie(c) + } + rec := httptest.NewRecorder() + s.h.ServeHTTP(rec, req) + for _, c := range rec.Result().Cookies() { + s.cookies[c.Name] = c + } + return rec +} + +func (s *setupHarness) csrf(t *testing.T) string { + t.Helper() + c, ok := s.cookies["__Host-"+csrfCookie] + if !ok { + t.Fatal("no csrf cookie") + } + if !c.Secure || !c.HttpOnly || c.Path != "/" { + t.Errorf("csrf cookie = %+v", c) + } + return c.Value +} + +func TestSetup_CreateInstallFinish(t *testing.T) { + s := newSetup(t) + + rec := s.do(t, http.MethodGet, PathSetup, nil) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Create the Slack app") || + !strings.Contains(rec.Body.String(), `action="/prod/slack/setup"`) { + t.Fatalf("setup page: %d %s", rec.Code, rec.Body) + } + if csp := rec.Header().Get("Content-Security-Policy"); !strings.Contains(csp, "form-action 'self'") { + t.Errorf("csp = %q", csp) + } + csrf := s.csrf(t) + + // the form must carry the cookie's token + rec = s.do(t, http.MethodPost, PathSetup, url.Values{"csrf": {"forged"}, "action": {"create"}, "config_token": {"xoxe.xoxp-1"}}) + if rec.Code != http.StatusBadRequest || s.api.created != 0 { + t.Fatalf("forged form: %d, created %d", rec.Code, s.api.created) + } + rec = s.do(t, http.MethodPost, PathSetup, url.Values{"csrf": {csrf}, "action": {"create"}, "config_token": {"xoxb-1"}}) + if !strings.Contains(rec.Body.String(), "start with xoxe") { + t.Errorf("wrong token kind: %s", rec.Body) + } + + rec = s.do(t, http.MethodPost, PathSetup, url.Values{"csrf": {csrf}, "action": {"create"}, "config_token": {"xoxe.xoxp-1"}}) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "https://ops.example.com/prod/slack/setup?done=created" { + t.Fatalf("create: %d %s", rec.Code, rec.Header().Get("Location")) + } + if s.api.created != 1 || s.api.icons != 1 || s.store.values[EnvSigningSecret] == "" || s.store.values[EnvClientID] != "123.456" { + t.Fatalf("created %d, icons %d, store %v", s.api.created, s.api.icons, s.store.values) + } + if m := string(s.api.manifests[0]); !strings.Contains(m, "https://ops.example.com/prod/slack/commands") || + !strings.Contains(m, `"command":"/github-ops"`) { + t.Errorf("manifest = %s", m) + } + + // a second click doesn't create another app + rec = s.do(t, http.MethodPost, PathSetup, url.Values{"csrf": {csrf}, "action": {"create"}, "config_token": {"xoxe.xoxp-1"}}) + if !strings.HasSuffix(rec.Header().Get("Location"), "done=existing") || s.api.created != 1 { + t.Errorf("second create: %s, created %d", rec.Header().Get("Location"), s.api.created) + } + + rec = s.do(t, http.MethodGet, PathSetup+"?done=created", nil) + if !strings.Contains(rec.Body.String(), "Install to Slack") || !strings.Contains(rec.Body.String(), "The Slack app is created") { + t.Errorf("install page: %s", rec.Body) + } + + rec = s.do(t, http.MethodGet, PathOAuthInstall, nil) + loc, err := url.Parse(rec.Header().Get("Location")) + if rec.Code != http.StatusSeeOther || err != nil || loc.Host != "slack.com" { + t.Fatalf("install: %d %s", rec.Code, rec.Header().Get("Location")) + } + q := loc.Query() + if q.Get("client_id") != "123.456" || q.Get("scope") != "chat:write,chat:write.public,commands" || + q.Get("redirect_uri") != "https://ops.example.com/prod/slack/oauth/callback" { + t.Errorf("authorize query = %v", q) + } + state := q.Get("state") + + rec = s.do(t, http.MethodGet, PathOAuthCallback+"?code=the-code&state=wrong", nil) + if !strings.Contains(rec.Body.String(), "expired") || s.store.values[EnvToken] != "" { + t.Fatalf("wrong state: %s", rec.Body) + } + rec = s.do(t, http.MethodGet, PathOAuthCallback+"?code=the-code&state="+state, nil) + body := rec.Body.String() + if rec.Code != http.StatusOK || !strings.Contains(body, "Installed in Acme") || !strings.Contains(body, "U0INSTALLER") || + !strings.Contains(body, "https://app.slack.com/client/T1/C0OPS") { + t.Fatalf("callback: %d %s", rec.Code, body) + } + if s.store.values[EnvToken] != "xoxb-1" || s.store.values[EnvTeam] != "T1|Acme" || s.installed != 1 { + t.Errorf("store %v, installed %d", s.store.values, s.installed) + } + + // once installed, the credentials can't be replaced + rec = s.do(t, http.MethodPost, PathSetup, url.Values{ + "csrf": {csrf}, "action": {"credentials"}, + "client_id": {"9.9"}, "client_secret": {strings.Repeat("a", 32)}, "signing_secret": {strings.Repeat("b", 32)}, + }) + if !strings.Contains(rec.Body.String(), "already installed") || s.store.values[EnvClientID] != "123.456" { + t.Errorf("replace after install: %s", rec.Body) + } + + // nor moved to another workspace + s.api.team = "T2" + rec = s.do(t, http.MethodGet, PathOAuthInstall, nil) + loc, _ = url.Parse(rec.Header().Get("Location")) + rec = s.do(t, http.MethodGet, PathOAuthCallback+"?code=the-code&state="+loc.Query().Get("state"), nil) + if !strings.Contains(rec.Body.String(), "already installed in Acme") || s.store.values[EnvTeam] != "T1|Acme" { + t.Errorf("other workspace: %s", rec.Body) + } +} + +func TestSetup_Credentials(t *testing.T) { + s := newSetup(t) + s.do(t, http.MethodGet, PathSetup, nil) + csrf := s.csrf(t) + + rec := s.do(t, http.MethodPost, PathSetup, url.Values{"csrf": {csrf}, "action": {"credentials"}, "client_id": {"x"}}) + if !strings.Contains(rec.Body.String(), "don't look like Slack credentials") { + t.Errorf("bad credentials: %s", rec.Body) + } + rec = s.do(t, http.MethodPost, PathSetup, url.Values{ + "csrf": {csrf}, "action": {"credentials"}, + "client_id": {"1.2"}, "client_secret": {strings.Repeat("a", 32)}, "signing_secret": {strings.Repeat("b", 32)}, + }) + if !strings.HasSuffix(rec.Header().Get("Location"), "done=credentials") || s.store.values[EnvSigningSecret] != strings.Repeat("b", 32) { + t.Errorf("credentials: %s, store %v", rec.Header().Get("Location"), s.store.values) + } +} + +func TestSetup_Errors(t *testing.T) { + s := newSetup(t) + s.do(t, http.MethodGet, PathSetup, nil) + csrf := s.csrf(t) + + s.api.createErr = errors.New("invalid_manifest") + rec := s.do(t, http.MethodPost, PathSetup, url.Values{"csrf": {csrf}, "action": {"create"}, "config_token": {"xoxe.xoxp-1"}}) + if !strings.Contains(rec.Body.String(), "invalid_manifest") { + t.Errorf("create error: %s", rec.Body) + } + + // store failures don't show their details + s.store.err = errors.New("AccessDeniedException: arn:aws:iam::123") + rec = s.do(t, http.MethodGet, PathSetup, nil) + if rec.Code != http.StatusInternalServerError || strings.Contains(rec.Body.String(), "AccessDenied") { + t.Errorf("store error: %d %s", rec.Code, rec.Body) + } + + if rec := s.do(t, http.MethodGet, "/slack/other", nil); rec.Code != http.StatusNotFound { + t.Errorf("unknown path: %d", rec.Code) + } +} + +func TestSetup_BaseURL(t *testing.T) { + h, err := New(Options{Store: &memStore{}, API: &fakeAPI{}, BasePath: "/prod"}) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, PathSetup, nil) + req.Host = "localhost:8080" + if got := h.baseURL(req); got != "http://localhost:8080/prod" { + t.Errorf("baseURL = %q", got) + } + req.Header.Set("X-Forwarded-Proto", "https, http") + if got := h.baseURL(req); got != "https://localhost:8080/prod" { + t.Errorf("baseURL behind a proxy = %q", got) + } + + h, _ = New(Options{Store: &memStore{}, API: &fakeAPI{}, PublicURL: "https://ops.example.com/prod/"}) + if got := h.baseURL(req); got != "https://ops.example.com/prod" { + t.Errorf("baseURL with a public url = %q", got) + } +} + +func TestManifest(t *testing.T) { + var m struct { + Features struct { + SlashCommands []struct { + Command string `json:"command"` + URL string `json:"url"` + } `json:"slash_commands"` + } `json:"features"` + OAuth struct { + RedirectURLs []string `json:"redirect_urls"` + Scopes struct { + Bot []string `json:"bot"` + } `json:"scopes"` + } `json:"oauth_config"` + } + if err := json.Unmarshal(Manifest("Ops", "/ops", "https://ops.example.com/"), &m); err != nil { + t.Fatal(err) + } + if len(m.Features.SlashCommands) != 1 || m.Features.SlashCommands[0].Command != "/ops" || + m.Features.SlashCommands[0].URL != "https://ops.example.com/slack/commands" { + t.Errorf("slash commands = %+v", m.Features.SlashCommands) + } + if len(m.OAuth.RedirectURLs) != 1 || m.OAuth.RedirectURLs[0] != "https://ops.example.com/slack/oauth/callback" || + strings.Join(m.OAuth.Scopes.Bot, ",") != strings.Join(BotScopes, ",") { + t.Errorf("oauth = %+v", m.OAuth) + } +} + +func TestEnvFileStore(t *testing.T) { + path := filepath.Join(t.TempDir(), ".env") + original := "# github app\nGITHUB_APP_ID=1\nAPP_SLACK_TOKEN=old # inline\n" + if err := os.WriteFile(path, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + s := NewEnvFileStore(path) + ctx := context.Background() + if err := s.Save(ctx, map[string]string{EnvToken: "xoxb-new", EnvTeam: `T1|Acme "Ops" $HOME #1`}); err != nil { + t.Fatal(err) + } + if v, err := s.Get(ctx, EnvTeam); err != nil || v != `T1|Acme "Ops" $HOME #1` { + t.Errorf("Get(team) = %q, %v", v, err) + } + values, err := godotenv.Read(path) + if err != nil { + t.Fatal(err) + } + if values["GITHUB_APP_ID"] != "1" || values[EnvToken] != "xoxb-new" { + t.Errorf("file values = %v", values) + } + b, _ := os.ReadFile(path) + if !strings.HasPrefix(string(b), "# github app\nGITHUB_APP_ID=1\n") || strings.Count(string(b), EnvToken) != 1 { + t.Errorf("file = %q", b) + } + + if v, err := NewEnvFileStore(filepath.Join(t.TempDir(), "missing")).Get(ctx, EnvToken); err != nil || v != "" { + t.Errorf("missing file: %q, %v", v, err) + } +} + +type fakeSSM struct { + puts []*ssm.PutParameterInput + params map[string]string +} + +func (f *fakeSSM) GetParameter(_ context.Context, in *ssm.GetParameterInput, _ ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) { + v, ok := f.params[aws.ToString(in.Name)] + if !ok { + return nil, &ssmtypes.ParameterNotFound{} + } + return &ssm.GetParameterOutput{Parameter: &ssmtypes.Parameter{Value: aws.String(v)}}, nil +} + +func (f *fakeSSM) PutParameter(_ context.Context, in *ssm.PutParameterInput, _ ...func(*ssm.Options)) (*ssm.PutParameterOutput, error) { + f.puts = append(f.puts, in) + if f.params == nil { + f.params = map[string]string{} + } + f.params[aws.ToString(in.Name)] = aws.ToString(in.Value) + return &ssm.PutParameterOutput{}, nil +} + +func TestSSMStore(t *testing.T) { + client := &fakeSSM{} + s, err := NewSSMStore(context.Background(), "/ops", "alias/ops", client) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if v, err := s.Get(ctx, EnvToken); err != nil || v != "" { + t.Fatalf("missing parameter: %q, %v", v, err) + } + if err := s.Save(ctx, map[string]string{EnvToken: "xoxb-1", EnvTeam: "T1|Acme"}); err != nil { + t.Fatal(err) + } + for _, in := range client.puts { + name := aws.ToString(in.Name) + secure := in.Type == ssmtypes.ParameterTypeSecureString + switch name { + case "/ops/" + EnvToken: + if !secure || aws.ToString(in.KeyId) != "alias/ops" || !aws.ToBool(in.Overwrite) { + t.Errorf("token parameter = %+v", in) + } + case "/ops/" + EnvTeam: + if secure || in.KeyId != nil { + t.Errorf("team parameter = %+v", in) + } + default: + t.Errorf("unexpected parameter %s", name) + } + } + if v, err := s.Get(ctx, EnvToken); err != nil || v != "xoxb-1" { + t.Errorf("Get = %q, %v", v, err) + } +} diff --git a/internal/slackapp/store.go b/internal/slackapp/store.go new file mode 100644 index 0000000..d8ae4da --- /dev/null +++ b/internal/slackapp/store.go @@ -0,0 +1,209 @@ +package slackapp + +import ( + "bufio" + "context" + "errors" + "fmt" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/ssm" + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + "github.com/joho/godotenv" +) + +// The names the credentials are saved under, which are also the variables +// the application reads them from. +const ( + EnvToken = "APP_SLACK_TOKEN" + EnvSigningSecret = "APP_SLACK_SIGNING_SECRET" + EnvClientID = "APP_SLACK_CLIENT_ID" + EnvClientSecret = "APP_SLACK_CLIENT_SECRET" + // EnvTeam is the workspace the app is installed in, as "id|name". It + // is not secret. + EnvTeam = "APP_SLACK_TEAM" +) + +// Store reads and writes the Slack app's credentials. +type Store interface { + // Get returns the saved value of a credential, or "". + Get(ctx context.Context, name string) (string, error) + // Save saves credentials, replacing saved values. + Save(ctx context.Context, values map[string]string) error +} + +// SSMClient is the part of the SSM API the SSM store uses. +type SSMClient interface { + GetParameter(ctx context.Context, in *ssm.GetParameterInput, opts ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) + PutParameter(ctx context.Context, in *ssm.PutParameterInput, opts ...func(*ssm.Options)) (*ssm.PutParameterOutput, error) +} + +// SSMStore keeps each credential in a parameter named prefix + name, as +// SecureStrings, except the team, which isn't secret. +type SSMStore struct { + client SSMClient + prefix string + kmsKeyID string +} + +var _ Store = (*SSMStore)(nil) + +// NewSSMStore creates a store under prefix. kmsKeyID encrypts the +// parameters; empty uses the aws/ssm key. A nil client is created from the +// default AWS configuration, which makes no network calls. +func NewSSMStore(ctx context.Context, prefix, kmsKeyID string, client SSMClient) (*SSMStore, error) { + if prefix == "" { + return nil, errors.New("ssm parameter prefix is required") + } + if !strings.HasSuffix(prefix, "/") { + prefix += "/" + } + if client == nil { + cfg, err := awsconfig.LoadDefaultConfig(ctx) + if err != nil { + return nil, fmt.Errorf("failed to load aws configuration: %w", err) + } + client = ssm.NewFromConfig(cfg) + } + return &SSMStore{client: client, prefix: prefix, kmsKeyID: kmsKeyID}, nil +} + +// Get returns a credential's value, or "" if its parameter doesn't exist. +func (s *SSMStore) Get(ctx context.Context, name string) (string, error) { + param := s.prefix + name + out, err := s.client.GetParameter(ctx, &ssm.GetParameterInput{Name: aws.String(param), WithDecryption: aws.Bool(true)}) + if err != nil { + var notFound *ssmtypes.ParameterNotFound + if errors.As(err, ¬Found) { + return "", nil + } + return "", fmt.Errorf("failed to read parameter '%s': %w", param, err) + } + if out.Parameter == nil { + return "", nil + } + return aws.ToString(out.Parameter.Value), nil +} + +// Save writes each credential to its parameter. +func (s *SSMStore) Save(ctx context.Context, values map[string]string) error { + for _, name := range slices.Sorted(maps.Keys(values)) { + param := s.prefix + name + in := &ssm.PutParameterInput{ + Name: aws.String(param), + Value: aws.String(values[name]), + Type: ssmtypes.ParameterTypeSecureString, + Overwrite: aws.Bool(true), + } + if name == EnvTeam { + in.Type = ssmtypes.ParameterTypeString + } else if s.kmsKeyID != "" { + in.KeyId = aws.String(s.kmsKeyID) + } + if _, err := s.client.PutParameter(ctx, in); err != nil { + return fmt.Errorf("failed to write parameter '%s': %w", param, err) + } + } + return nil +} + +// EnvFileStore keeps credentials in an env file, the one the GitHub App +// installer writes. Saving replaces the lines of the saved names and keeps +// every other line as it is. +type EnvFileStore struct { + path string + mu sync.Mutex +} + +var _ Store = (*EnvFileStore)(nil) + +// NewEnvFileStore creates a store that keeps credentials in the env file at +// path. +func NewEnvFileStore(path string) *EnvFileStore { + return &EnvFileStore{path: path} +} + +// Get returns a credential's value, or "" if the file or name is missing. +func (s *EnvFileStore) Get(_ context.Context, name string) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + values, err := godotenv.Read(s.path) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("failed to read env file '%s': %w", s.path, err) + } + return values[name], nil +} + +// Save writes credentials to the env file. +func (s *EnvFileStore) Save(_ context.Context, values map[string]string) error { + s.mu.Lock() + defer s.mu.Unlock() + + var lines []string + f, err := os.Open(s.path) + switch { + case errors.Is(err, os.ErrNotExist): + case err != nil: + return fmt.Errorf("failed to read env file '%s': %w", s.path, err) + default: + scanner := bufio.NewScanner(f) + scanner.Buffer(make([]byte, 0, 64<<10), 1<<20) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + _ = f.Close() + if err := scanner.Err(); err != nil { + return fmt.Errorf("failed to read env file '%s': %w", s.path, err) + } + } + + written := make(map[string]bool) + for i, line := range lines { + key, _, ok := strings.Cut(strings.TrimSpace(line), "=") + key = strings.TrimSpace(strings.TrimPrefix(key, "export ")) + if _, saving := values[key]; ok && saving { + if lines[i], err = envLine(key, values[key]); err != nil { + return err + } + written[key] = true + } + } + for _, key := range slices.Sorted(maps.Keys(values)) { + if !written[key] { + line, err := envLine(key, values[key]) + if err != nil { + return err + } + lines = append(lines, line) + } + } + + dir := filepath.Dir(s.path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("failed to create directory '%s': %w", dir, err) + } + content := strings.Join(lines, "\n") + "\n" + if err := os.WriteFile(s.path, []byte(content), 0o600); err != nil { + return fmt.Errorf("failed to write env file '%s': %w", s.path, err) + } + return nil +} + +// envLine formats one line the way godotenv reads it back. +func envLine(key, value string) (string, error) { + line, err := godotenv.Marshal(map[string]string{key: value}) + if err != nil { + return "", fmt.Errorf("failed to format %s for the env file: %w", key, err) + } + return line, nil +} diff --git a/internal/slackapp/template.go b/internal/slackapp/template.go new file mode 100644 index 0000000..1f767a0 --- /dev/null +++ b/internal/slackapp/template.go @@ -0,0 +1,132 @@ +package slackapp + +import "html/template" + +var setupTemplate = template.Must(template.New("setup").Parse(` + + + + +Set up {{.AppName}} for Slack + + + +
+
+

Set up {{.AppName}} for Slack

+

This page creates the Slack app for this deployment and saves its credentials where the GitHub App installer saves its own. Nothing is stored in your browser.

+
+
+ 1 · Create the app + 2 · Install it + 3 · Finish +
+ {{if .Notice}}
{{.Notice}}
{{end}} + {{if .Error}}
{{.Error}}
{{end}} + + {{if not .Status.HasApp}} +
+

Create the app

+

Do this in the Slack workspace the bot should post in, with an account that may create apps there. Both ways below make the same app from this deployment's manifest.

+
+

Let this page create it fastest

+
    +
  1. Open api.slack.com/apps in a new tab.
  2. +
  3. Below your list of apps, find Your App Configuration Tokens and click Generate Token.
  4. +
  5. Choose the workspace and generate the token.
  6. +
  7. Copy the access token (it starts with xoxe.xoxp-), not the refresh token, and paste it here. The page creates the app with its icon and every URL filled in.
  8. +
+
+ + + +

+
+

The token is used once, right now, and isn't saved; it expires by itself after 12 hours.

+
+
+ Can't generate a token? Create the app yourself instead +
    +
  1. Open Slack with this app's manifest
    Slack's Create an app page opens in a new tab with everything filled in.
  2. +
  3. Choose the workspace, click Next, check the summary, and click Create.
  4. +
  5. On the new app's Basic Information page, under App Credentials, copy the Client ID. Click Show next to Client Secret and Signing Secret and copy those too.
  6. + {{if .IconURL}}
  7. On the same page, under Display Information, add the app icon. Download the icon.
    The app icon
  8. {{end}} +
  9. Paste all three here and click Save credentials.
  10. +
+
+ + + + + +

+
+
+
+ See the manifest +
{{.ManifestJSON}}
+
+

Next you'll install the app, which takes one click in Slack.

+
+ {{else if not .Status.Installed}} +
+

Install it in your workspace

+
    +
  1. Click Install to Slack. Slack lists what the app may do: post messages and add the {{.Command}} command.
  2. +
  3. Check the workspace in the top right of Slack's page and click Allow.
  4. +
  5. Slack sends you back here when it's done.
  6. +
+

Install to Slack

+

If your workspace needs an admin to approve new apps, Slack offers to request approval instead. Once an admin approves, come back to this page and click Install to Slack again.

+
+ {{else}} +
+

Installed{{if .Status.TeamName}} in {{.Status.TeamName}}{{end}}

+
    + {{if .Channels}}
  1. The app posts in {{range $i, $c := .Channels}}{{if $i}}, {{end}}{{if $c.URL}}{{$c.ID}}{{else}}{{$c.ID}}{{end}}{{end}}. Invite it to the private ones: type /invite @{{.AppName}} there. Public channels need no invite.
  2. + {{else}}
  3. Set APP_SLACK_CHANNEL to the ID of the channel the app posts in, and invite the app to it if it's private: type /invite @{{.AppName}} there.
  4. {{end}} +
  5. Let people run {{.Command}} sync by adding their Slack user IDs to APP_SLACK_COMMAND_ALLOWED_USERS.{{if .Installer}} Yours is {{.Installer}}.{{end}} Anyone can run {{.Command}} help.
  6. +
  7. Turn this page off (APP_SLACK_SETUP_ENABLED=false) and redeploy.
  8. +
+

Changed the app's scopes or command? Reinstall. It stays in this workspace.

+
+ {{end}} +
+ + +`)) diff --git a/internal/state/state.go b/internal/state/state.go new file mode 100644 index 0000000..d7a0a52 --- /dev/null +++ b/internal/state/state.go @@ -0,0 +1,198 @@ +// Package state keeps small records that must outlive a run, such as what +// each report last posted and when, in memory, in a file, or in AWS SSM +// Parameter Store. +package state + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/ssm" + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + + "github.com/cruxstack/github-ops-app/internal/domain" +) + +// Memory keeps records in memory, so they are lost when the process exits. +type Memory struct { + mu sync.Mutex + records map[string][]byte +} + +var _ domain.StateStore = (*Memory)(nil) + +// NewMemory creates an empty Memory store. +func NewMemory() *Memory { + return &Memory{records: make(map[string][]byte)} +} + +// Get returns the record stored under key, or nil. +func (m *Memory) Get(_ context.Context, key string) ([]byte, error) { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.records[key]), nil +} + +// Put stores a record under key. +func (m *Memory) Put(_ context.Context, key string, value []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + m.records[key] = slices.Clone(value) + return nil +} + +// File keeps records in one JSON file. Writes replace the file atomically. +// It is for a single process; separate processes sharing the file can lose +// each other's writes. +type File struct { + path string + mu sync.Mutex +} + +var _ domain.StateStore = (*File)(nil) + +// NewFile creates a store that keeps records in the file at path. The file +// and its directory are created on the first write. +func NewFile(path string) *File { + return &File{path: path} +} + +func (f *File) read() (map[string]string, error) { + b, err := os.ReadFile(f.path) + if errors.Is(err, os.ErrNotExist) { + return map[string]string{}, nil + } + if err != nil { + return nil, fmt.Errorf("failed to read state file '%s': %w", f.path, err) + } + records := map[string]string{} + if err := json.Unmarshal(b, &records); err != nil { + return nil, fmt.Errorf("failed to parse state file '%s': %w", f.path, err) + } + return records, nil +} + +// Get returns the record stored under key, or nil. +func (f *File) Get(_ context.Context, key string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + records, err := f.read() + if err != nil { + return nil, err + } + v, ok := records[key] + if !ok { + return nil, nil + } + return []byte(v), nil +} + +// Put stores a record under key. +func (f *File) Put(_ context.Context, key string, value []byte) error { + f.mu.Lock() + defer f.mu.Unlock() + records, err := f.read() + if err != nil { + return err + } + records[key] = string(value) + + b, err := json.MarshalIndent(records, "", " ") + if err != nil { + return fmt.Errorf("failed to encode state file '%s': %w", f.path, err) + } + dir := filepath.Dir(f.path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("failed to create state directory '%s': %w", dir, err) + } + tmp, err := os.CreateTemp(dir, ".state-*") + if err != nil { + return fmt.Errorf("failed to write state file '%s': %w", f.path, err) + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.Write(append(b, '\n')); err != nil { + _ = tmp.Close() + return fmt.Errorf("failed to write state file '%s': %w", f.path, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("failed to write state file '%s': %w", f.path, err) + } + if err := os.Rename(tmp.Name(), f.path); err != nil { + return fmt.Errorf("failed to write state file '%s': %w", f.path, err) + } + return nil +} + +// SSMClient is the part of the SSM API the SSM store uses. +type SSMClient interface { + GetParameter(ctx context.Context, in *ssm.GetParameterInput, opts ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) + PutParameter(ctx context.Context, in *ssm.PutParameterInput, opts ...func(*ssm.Options)) (*ssm.PutParameterOutput, error) +} + +// SSM keeps each record in a String parameter named prefix + key. Records +// are not secret, so they are not encrypted. +type SSM struct { + client SSMClient + prefix string +} + +var _ domain.StateStore = (*SSM)(nil) + +// NewSSM creates a store that keeps records under prefix, a path that +// starts and ends with a slash, such as /github-ops-app/state/. A nil client +// is created from the default AWS configuration, which makes no network +// calls. +func NewSSM(ctx context.Context, prefix string, client SSMClient) (*SSM, error) { + if !strings.HasPrefix(prefix, "/") || !strings.HasSuffix(prefix, "/") { + return nil, fmt.Errorf("state parameter prefix '%s' must start and end with a slash", prefix) + } + if client == nil { + cfg, err := awsconfig.LoadDefaultConfig(ctx) + if err != nil { + return nil, fmt.Errorf("failed to load aws configuration: %w", err) + } + client = ssm.NewFromConfig(cfg) + } + return &SSM{client: client, prefix: prefix}, nil +} + +// Get returns the record stored under key, or nil. +func (s *SSM) Get(ctx context.Context, key string) ([]byte, error) { + name := s.prefix + key + out, err := s.client.GetParameter(ctx, &ssm.GetParameterInput{Name: aws.String(name)}) + if err != nil { + var notFound *ssmtypes.ParameterNotFound + if errors.As(err, ¬Found) { + return nil, nil + } + return nil, fmt.Errorf("failed to read state parameter '%s': %w", name, err) + } + if out.Parameter == nil || out.Parameter.Value == nil { + return nil, nil + } + return []byte(*out.Parameter.Value), nil +} + +// Put stores a record under key. +func (s *SSM) Put(ctx context.Context, key string, value []byte) error { + name := s.prefix + key + _, err := s.client.PutParameter(ctx, &ssm.PutParameterInput{ + Name: aws.String(name), + Value: aws.String(string(value)), + Type: ssmtypes.ParameterTypeString, + Overwrite: aws.Bool(true), + }) + if err != nil { + return fmt.Errorf("failed to write state parameter '%s': %w", name, err) + } + return nil +} diff --git a/internal/state/state_test.go b/internal/state/state_test.go new file mode 100644 index 0000000..e0cf0bf --- /dev/null +++ b/internal/state/state_test.go @@ -0,0 +1,121 @@ +package state + +import ( + "context" + "errors" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ssm" + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + + "github.com/cruxstack/github-ops-app/internal/domain" +) + +func roundTrip(t *testing.T, s domain.StateStore) { + t.Helper() + ctx := context.Background() + if v, err := s.Get(ctx, "missing"); err != nil || v != nil { + t.Fatalf("Get(missing) = %q, %v; want nil, nil", v, err) + } + if err := s.Put(ctx, "okta-sync", []byte(`{"a":1}`)); err != nil { + t.Fatal(err) + } + if err := s.Put(ctx, "okta-sync", []byte(`{"a":2}`)); err != nil { + t.Fatal(err) + } + if v, err := s.Get(ctx, "okta-sync"); err != nil || string(v) != `{"a":2}` { + t.Fatalf("Get = %q, %v", v, err) + } +} + +func TestMemory(t *testing.T) { + roundTrip(t, NewMemory()) +} + +func TestFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "nested", "state.json") + roundTrip(t, NewFile(path)) + + // a new store reads what the first one wrote + if v, err := NewFile(path).Get(context.Background(), "okta-sync"); err != nil || string(v) != `{"a":2}` { + t.Fatalf("reopened Get = %q, %v", v, err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if perm := info.Mode().Perm(); perm&0o077 != 0 { + t.Errorf("state file mode %v is readable by others", perm) + } +} + +func TestFile_Corrupt(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + if err := os.WriteFile(path, []byte("not json"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := NewFile(path).Get(context.Background(), "k"); err == nil { + t.Error("corrupt file read without error") + } +} + +type fakeSSM struct { + mu sync.Mutex + params map[string]string + err error +} + +func (f *fakeSSM) GetParameter(_ context.Context, in *ssm.GetParameterInput, _ ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.err != nil { + return nil, f.err + } + v, ok := f.params[aws.ToString(in.Name)] + if !ok { + return nil, &ssmtypes.ParameterNotFound{} + } + return &ssm.GetParameterOutput{Parameter: &ssmtypes.Parameter{Value: aws.String(v)}}, nil +} + +func (f *fakeSSM) PutParameter(_ context.Context, in *ssm.PutParameterInput, _ ...func(*ssm.Options)) (*ssm.PutParameterOutput, error) { + f.mu.Lock() + defer f.mu.Unlock() + if in.Type != ssmtypes.ParameterTypeString || !aws.ToBool(in.Overwrite) { + return nil, errors.New("unexpected put parameter input") + } + if f.params == nil { + f.params = map[string]string{} + } + f.params[aws.ToString(in.Name)] = aws.ToString(in.Value) + return &ssm.PutParameterOutput{}, nil +} + +func TestSSM(t *testing.T) { + client := &fakeSSM{} + s, err := NewSSM(context.Background(), "/ops/state/", client) + if err != nil { + t.Fatal(err) + } + roundTrip(t, s) + if _, ok := client.params["/ops/state/okta-sync"]; !ok { + t.Errorf("parameters = %v, want /ops/state/okta-sync", client.params) + } + + client.err = errors.New("access denied") + if _, err := s.Get(context.Background(), "okta-sync"); err == nil { + t.Error("read error was not returned") + } +} + +func TestNewSSM_Prefix(t *testing.T) { + for _, prefix := range []string{"", "ops/state/", "/ops/state"} { + if _, err := NewSSM(context.Background(), prefix, &fakeSSM{}); err == nil { + t.Errorf("prefix %q accepted", prefix) + } + } +} From babf83f256ec2314ea358b5388ba1e5f85952e56 Mon Sep 17 00:00:00 2001 From: Brian Ojeda <9335829+sgtoj@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:14:35 -0500 Subject: [PATCH 2/2] docs: document the slack setup page, slash command, and daily reports - README: the new endpoints, Slack and report variables, how reports decide to post, the slash command, and troubleshooting - slack setup: the setup page, creating the app by hand, adding the slash command to an existing app, and finding user IDs - lambda: job events and the role permissions each feature needs - the Slack manifest asset gains the slash command and commands scope - AGENTS.md: the slackapp and state packages and the command's rules Co-Authored-By: Claude Opus 5.5 --- .env.example | 21 +++ AGENTS.md | 14 +- README.md | 126 +++++++++++--- assets/slack/manifest.json | 27 ++- cmd/lambda/README.md | 48 +++++- docs/slack-setup.md | 327 +++++++++++++++++-------------------- 6 files changed, 340 insertions(+), 223 deletions(-) diff --git a/.env.example b/.env.example index 18d6905..95e7fff 100644 --- a/.env.example +++ b/.env.example @@ -60,6 +60,16 @@ APP_OKTA_SYNC_RULES=[{"name":"sync-eng","okta_group_pattern":"^github-eng-.*","s # slack (optional; the token and channel are required together) APP_SLACK_TOKEN=xoxb-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx APP_SLACK_CHANNEL=C01234ABCDE +# the slash command: the signing secret turns it on, and only these slack +# user ids may run its actions +# APP_SLACK_SIGNING_SECRET=0123456789abcdef0123456789abcdef +# APP_SLACK_COMMAND_ALLOWED_USERS=U01234ABCDE,U05678FGHIJ +# APP_SLACK_COMMAND=/github-ops +# slack app setup (optional): serves /slack/setup to create and install the +# slack app and saves its token and signing secret where the github app +# installer saves credentials (STORAGE_MODE); disable it once installed +# APP_SLACK_SETUP_ENABLED=true +# APP_SLACK_APP_NAME=GitHub Ops # per notification type; each falls back to APP_SLACK_CHANNEL # APP_SLACK_CHANNEL_PR_BYPASS=C01234ABCDE # APP_SLACK_CHANNEL_OKTA_SYNC=C01234ABCDE @@ -67,3 +77,14 @@ APP_SLACK_CHANNEL=C01234ABCDE # APP_SLACK_CHANNEL_SECURITY_ALERTS=C01234ABCDE # footer for pr bypass notifications, in slack mrkdwn # APP_SLACK_FOOTER_NOTE_PR_BYPASS=_Please review the ._ + +# reports (optional): every-run posts every report after every run; daily +# posts a report when it changes, and otherwise once a day, at the first run +# after the daily time +# APP_REPORT_REPEAT=daily +# APP_REPORT_DAILY_TIME=09:00 +# APP_REPORT_TIMEZONE=America/New_York +# where daily reports remember what they last posted: an ssm path (required +# in lambda) or a file; the server keeps it in memory without either +# APP_STATE_SSM_PREFIX=/github-ops-app/state/ +# APP_STATE_FILE=./.local/state.json diff --git a/AGENTS.md b/AGENTS.md index a0da8ae..23f328f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,14 +3,14 @@ ## Architecture Overview - **Deployment**: HTTP server (container, K8s, VM) or AWS Lambda; both serve the same router - **GitHub**: GitHub App (JWT + installation tokens); created by hand or with the github-app-setup-go installer -- **Features**: Okta group sync, PR compliance monitoring, stale security alert reports, Slack notifications (all optional) +- **Features**: Okta group sync, PR compliance monitoring, stale security alert reports, Slack notifications, a Slack slash command and setup page (all optional) - **Entry points**: - `cmd/server/main.go` - HTTP server with graceful shutdown - - `cmd/lambda/` - Lambda adapter: API Gateway HTTP API (2.0) requests and EventBridge scheduled events + - `cmd/lambda/` - Lambda adapter: API Gateway HTTP API (2.0) requests, EventBridge scheduled events, and its own async invocations for jobs started from Slack - `cmd/sample/main.go` - **DO NOT RUN** (requires live credentials) - **Packages**: - - `internal/service/` - composition root shared by both entry points: github-app-setup-go runtime (load, retry, reload), health and installer routes, swaps the app on reload - - `internal/app/` - the application: builds clients from config, router (`/webhooks`, admin, `/scheduled/{action}`), feature handlers + - `internal/service/` - composition root shared by both entry points: github-app-setup-go runtime (load, retry, reload), health, installer, and Slack setup routes, swaps the app on reload + - `internal/app/` - the application: builds clients from config, router (`/webhooks`, `/slack/commands`, admin, `/scheduled/{action}`), feature handlers, report posting (every run, or on change and daily) - `internal/config/` - reads and validates all configuration; resolves SSM parameter ARNs - `internal/domain/` - shared types, interfaces, and error kinds; imports no internal package - `internal/github/client/` - GitHub API client: auth, PR compliance, teams, security alerts @@ -19,6 +19,8 @@ - `internal/teamsync/` - Okta group to GitHub team sync and orphaned user detection - `internal/notifiers/` - Slack messages - `internal/setup/` - GitHub App manifest and installer credential store + - `internal/slackapp/` - Slack app manifest and `/slack/setup` (create from manifest, OAuth install, saves credentials where the installer does) + - `internal/state/` - small records that outlive a run (what each report last posted): memory, file, or SSM - `internal/fakes/` - in-memory domain fakes for tests - **Tests**: unit tests beside each package; `e2e/` runs `fixtures/scenarios.json` against the real service with mock GitHub, Okta, and Slack servers @@ -88,7 +90,9 @@ live credentials and make real API calls to GitHub/Okta/Slack. - Webhooks are always signature-checked; there is no unsigned mode - Admin endpoints require `APP_ADMIN_TOKEN` (constant-time compare) and are disabled without it - Only events from `APP_GITHUB_ORG` are acted on -- Escape GitHub and Okta text in Slack mrkdwn with `escape`/`link` in `internal/notifiers` +- Escape GitHub and Okta text in Slack mrkdwn with `Escape`/`link` in `internal/notifiers` +- Slash commands are signature-checked (`APP_SLACK_SIGNING_SECRET`); only users in `APP_SLACK_COMMAND_ALLOWED_USERS` may run actions, and replies never include error details +- The Slack setup never replaces an installed app's credentials or moves it to another workspace - Validate GitHub logins (`domain.IsValidGitHubLogin`) before putting them in API paths - Auth headers are only sent to the configured GitHub API host diff --git a/README.md b/README.md index fd07602..51849f5 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,12 @@ AWS Lambda function. with one click, using [github-app-setup-go](https://github.com/cruxstack/github-app-setup-go) - **Slack notifications** - Reports for each feature, in per-feature channels +- **Slack app setup** - Optionally create and install the Slack app from a + setup page, with its slash command and icon +- **Slack slash command** - Let allowed users resync Okta groups or post the + security alerts report on demand +- **Quiet reports** - Run the checks as often as you like, and post a report + when it changes, and otherwise once a day ## Quick Start @@ -62,6 +68,9 @@ curl -X POST -H "Authorization: Bearer $APP_ADMIN_TOKEN" \ https://github-ops.example.com/scheduled/okta-sync ``` +To check often without a message every time, set `APP_REPORT_REPEAT=daily` +(see [Reports](#reports)). + ### AWS Lambda ```bash @@ -76,19 +85,23 @@ API Gateway delivers webhooks and EventBridge runs the scheduled actions. See Every route is served under `APP_BASE_PATH`, if set. -| Method | Path | Auth | Description | -| ------ | ---------------------------- | -------------- | ------------------------------------ | -| POST | `/webhooks` | Signature | GitHub webhooks | -| GET | `/healthz` | None | Liveness; always `200` | -| GET | `/readyz` | None | `200` once the configuration loads | -| POST | `/scheduled/okta-sync` | Admin token | Sync Okta groups to teams | -| POST | `/scheduled/security-alerts` | Admin token | Report stale security alerts | -| POST | `/scheduled/slack-test` | Admin token | Send a sample of every notification | -| GET | `/server/status` | Admin token | Status and enabled features | -| GET | `/server/config` | Admin token | Configuration, secrets redacted | -| GET | `/setup` | None | GitHub App installer, when enabled | +| Method | Path | Auth | Description | +| ------ | ---------------------------- | --------------- | ----------------------------------- | +| POST | `/webhooks` | Signature | GitHub webhooks | +| GET | `/healthz` | None | Liveness; always `200` | +| GET | `/readyz` | None | `200` once the configuration loads | +| POST | `/scheduled/okta-sync` | Admin token | Sync Okta groups to teams | +| POST | `/scheduled/security-alerts` | Admin token | Report stale security alerts | +| POST | `/scheduled/slack-test` | Admin token | Send a sample of every notification | +| GET | `/server/status` | Admin token | Status and enabled features | +| GET | `/server/config` | Admin token | Configuration, secrets redacted | +| GET | `/setup` | None | GitHub App installer, when enabled | +| POST | `/slack/commands` | Slack signature | The slash command, when enabled | +| GET | `/slack/setup` | None | Slack app setup, when enabled | Webhooks must carry a valid `X-Hub-Signature-256`; there is no unsigned mode. +Slash commands must carry a valid `X-Slack-Signature` signed in the last five +minutes. The admin endpoints require `Authorization: Bearer ` and are disabled when no admin token is set. Webhooks from organizations other than `APP_GITHUB_ORG` are ignored. @@ -175,17 +188,44 @@ have no severity and count as high. ### Slack (optional) -The token and channel are required together. - -| Variable | Description | -| ----------------------------------- | ----------------------------------------- | -| `APP_SLACK_TOKEN` | Bot token (`xoxb-...`) | -| `APP_SLACK_CHANNEL` | Default channel ID | -| `APP_SLACK_CHANNEL_PR_BYPASS` | Channel for PR bypass reports | -| `APP_SLACK_CHANNEL_OKTA_SYNC` | Channel for sync reports | -| `APP_SLACK_CHANNEL_ORPHANED_USERS` | Channel for orphaned user reports | -| `APP_SLACK_CHANNEL_SECURITY_ALERTS` | Channel for security alert reports | -| `APP_SLACK_FOOTER_NOTE_PR_BYPASS` | Footer for PR bypass reports, in mrkdwn | +The token and channel are required together. The signing secret turns on the +slash command, whose actions only the allowed users may run. + +| Variable | Description | +| ----------------------------------- | ----------------------------------------------- | +| `APP_SLACK_TOKEN` | Bot token (`xoxb-...`) | +| `APP_SLACK_CHANNEL` | Default channel ID | +| `APP_SLACK_CHANNEL_PR_BYPASS` | Channel for PR bypass reports | +| `APP_SLACK_CHANNEL_OKTA_SYNC` | Channel for sync reports | +| `APP_SLACK_CHANNEL_ORPHANED_USERS` | Channel for orphaned user reports | +| `APP_SLACK_CHANNEL_SECURITY_ALERTS` | Channel for security alert reports | +| `APP_SLACK_FOOTER_NOTE_PR_BYPASS` | Footer for PR bypass reports, in mrkdwn | +| `APP_SLACK_SIGNING_SECRET` | Signing secret; turns on the slash command | +| `APP_SLACK_COMMAND_ALLOWED_USERS` | Slack user IDs that may run its actions | +| `APP_SLACK_COMMAND` | Slash command (default: `/github-ops`) | +| `APP_SLACK_APP_NAME` | App name the setup gives it (`GitHub Ops`) | +| `APP_SLACK_SETUP_ENABLED` | `true` to serve `/slack/setup` | + +The setup page creates the Slack app from a manifest, installs it, and saves +the token and signing secret where the GitHub App installer saves its +credentials (`STORAGE_MODE`), then loads them without a restart. While it is +enabled, Slack stays off instead of failing until the token and channel are +set. See [Slack Setup](docs/slack-setup.md#option-a-setup-page). + +### Reports (optional) + +| Variable | Description | +| ----------------------- | -------------------------------------------------------- | +| `APP_REPORT_REPEAT` | `every-run` (default) or `daily` | +| `APP_REPORT_DAILY_TIME` | When the day's unchanged reports are due (`09:00`) | +| `APP_REPORT_TIMEZONE` | Time zone of the daily time (default: `UTC`) | +| `APP_STATE_SSM_PREFIX` | SSM path for report state, such as `/github-ops/state/` | +| `APP_STATE_FILE` | Or a file for report state (server only) | + +With `daily`, the app remembers what each report last posted. In Lambda it +needs `APP_STATE_SSM_PREFIX`, and the role needs `ssm:GetParameter` and +`ssm:PutParameter` on it; the server keeps it in memory unless a state file or +prefix is set. See [Reports](#reports). ### Service @@ -278,8 +318,8 @@ ignored. ### Okta Sync -1. **Trigger**: the schedule, or a `team` or `membership` webhook from a - person, not a bot, about a team a rule manages +1. **Trigger**: the schedule, the slash command, or a `team` or `membership` + webhook from a person, not a bot, about a team a rule manages 2. **Fetch**: read the Okta groups each rule matches, with their members 3. **Map**: derive each group's GitHub team, creating it if allowed 4. **Sync**: add and remove team members to match the group @@ -309,7 +349,7 @@ pass, as on GitHub. ### Security Alerts -1. **Trigger**: the schedule +1. **Trigger**: the schedule, or the slash command 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 @@ -317,6 +357,34 @@ pass, as on GitHub. 4. **Report**: post the alerts by repository to Slack, with any source that failed +### Reports + +The Okta sync, orphaned users, and security alerts reports post after every +run by default. With `APP_REPORT_REPEAT=daily`, run the checks as often as +you like, such as hourly; a report posts when: + +- the run added or removed team members; +- it differs from the one last posted, such as a new alert, a newly orphaned + user, or a team that started or stopped failing; or +- it hasn't posted since the day's `APP_REPORT_DAILY_TIME`, at the first run + on or after it. + +Alert ages and error messages don't count as changes, so a report doesn't +repost each day an alert ages or each time a failing API words its error +differently. A report with nothing in it, such as no stale alerts, never +posts, but is remembered, so the report posts again when something comes back. +A run someone asked for with the slash command always posts. + +### Slash Command + +`/github-ops sync` runs the Okta sync now and `/github-ops security-alerts` +posts the security alerts report now. Each answers at once, runs afterwards, +posts its report to the usual channel, and then replies to who asked with a +summary. Anyone can run `/github-ops help`; only the users in +`APP_SLACK_COMMAND_ALLOWED_USERS` may run the rest. In Lambda, the job runs +in an asynchronous invocation of the function, so its role needs +`lambda:InvokeFunction` on itself. + ## Development ```bash @@ -343,7 +411,13 @@ to cover a new behavior. [permissions](docs/github-app-setup.md#permissions). - **Group not found from Okta**: check the domain, scopes, and the group name. - **No Slack messages**: check the token has `chat:write` and the bot is in - the channel, or add `chat:write.public`. + the channel, or add `chat:write.public`. With `APP_REPORT_REPEAT=daily`, an + unchanged report posts once a day. +- **Slash command fails with `dispatch_failed`**: Slack can't reach + `/slack/commands`, or `APP_SLACK_SIGNING_SECRET` is wrong or unset; the + service logs rejected signatures. +- **"You aren't allowed to run"**: add the Slack user ID from the reply to + `APP_SLACK_COMMAND_ALLOWED_USERS`. Upgrading from v0? See [Upgrading to v1](docs/upgrading-to-v1.md). diff --git a/assets/slack/manifest.json b/assets/slack/manifest.json index 15f5b65..252aaa8 100644 --- a/assets/slack/manifest.json +++ b/assets/slack/manifest.json @@ -1,20 +1,37 @@ { + "_metadata": { + "major_version": 2, + "minor_version": 1 + }, "display_information": { - "name": "GitHub Ops Bot", - "description": "GitHub automation bot with user sync and compliance monitoring", + "name": "GitHub Ops", + "description": "Okta team sync, PR compliance, and security alert reports for GitHub.", "background_color": "#10203B" }, "features": { "bot_user": { - "display_name": "GitHub Ops Bot", + "display_name": "GitHub Ops", "always_online": false - } + }, + "slash_commands": [ + { + "command": "/github-ops", + "url": "https://github-ops.example.com/slack/commands", + "description": "Resync Okta groups or post the security alerts report now", + "usage_hint": "sync | security-alerts | help", + "should_escape": false + } + ] }, "oauth_config": { + "redirect_urls": [ + "https://github-ops.example.com/slack/oauth/callback" + ], "scopes": { "bot": [ "chat:write", - "chat:write.public" + "chat:write.public", + "commands" ] } }, diff --git a/cmd/lambda/README.md b/cmd/lambda/README.md index 67f5e75..1e10663 100644 --- a/cmd/lambda/README.md +++ b/cmd/lambda/README.md @@ -8,12 +8,18 @@ module deploys everything below. ## Events -- **API Gateway HTTP API** (payload format 2.0) requests carry GitHub webhooks - and admin requests. They are converted to HTTP requests, with their query - string, headers, cookies, and base64 bodies, and served by the same router - as the server. +- **API Gateway HTTP API** (payload format 2.0) requests carry GitHub webhooks, + Slack slash commands, and admin requests. They are converted to HTTP + requests, with their query string, headers, cookies, and base64 bodies, and + served by the same router as the server. - **EventBridge** events run a scheduled action named in their detail. AWS authorizes these invocations, so they don't need the admin token. +- **Jobs** started by the slash command run in an asynchronous invocation of + the function itself, since Slack waits only three seconds for an answer + and an invocation ends when it answers. The event is + `{"github_ops_app_job": {"action": "okta-sync", ...}}`. A failed job replies + to who asked and is logged, but doesn't fail the invocation, so Lambda + doesn't retry it. The configuration loads on the first invocation. If it fails, such as when an SSM parameter is unavailable, it is retried on the next invocation instead of @@ -47,10 +53,22 @@ Set the [configuration](../../README.md#configuration) as environment variables. Keep secrets in SSM Parameter Store and set their variables to the parameter ARNs, so they don't appear in the function's configuration. +Some features need more of the role: + +| Feature | Permission | +| -------------------------- | ----------------------------------------------------- | +| Slash command | `lambda:InvokeFunction` on the function itself | +| `APP_REPORT_REPEAT=daily` | `ssm:GetParameter`, `ssm:PutParameter` on the prefix | +| Installer or Slack setup | `ssm:PutParameter` on `AWS_SSM_PARAMETER_PREFIX` | + +Daily reports need `APP_STATE_SSM_PREFIX`, such as `/github-ops-app/state/`, +since memory doesn't last between invocations. + ### API Gateway 1. Create an **HTTP API** with a Lambda proxy integration. -2. Add the route `ANY /{proxy+}`, or at least `POST /webhooks`. +2. Add the route `ANY /{proxy+}`, or at least `POST /webhooks`, and + `POST /slack/commands` for the slash command. 3. If the stage is not `$default`, set `APP_BASE_PATH` to `/`. 4. Set the GitHub App's webhook URL to `https:////webhooks`. @@ -67,10 +85,13 @@ target and an input whose detail names the action: } ``` -| Action | Suggested schedule | -| ----------------- | ---------------------------- | -| `okta-sync` | `rate(1 hour)` | -| `security-alerts` | `cron(0 13 ? * MON *)` | +| Action | Suggested schedule | +| ----------------- | ----------------------------------------------- | +| `okta-sync` | `rate(1 hour)` | +| `security-alerts` | `cron(0 13 ? * MON *)`, or `rate(1 hour)` daily | + +With `APP_REPORT_REPEAT=daily`, run both hourly: each report posts when it +changes, and otherwise once a day. A failed action fails the invocation, so EventBridge retries it and it shows in the function's error metrics. @@ -94,6 +115,13 @@ The next invocation after the app is created loads its credentials. When `APP_BASE_PATH` is set, the installer's "disable" button posts to a path without the stage; set `GITHUB_APP_INSTALLER_ENABLED=false` instead. +The [Slack setup](../../docs/slack-setup.md#option-a-setup-page) works the +same way with `APP_SLACK_SETUP_ENABLED=true`: set `APP_SLACK_TOKEN` and +`APP_SLACK_SIGNING_SECRET` to the ARNs of `APP_SLACK_TOKEN` and +`APP_SLACK_SIGNING_SECRET`, and visit +`https:////slack/setup`. The invocation that finishes the +install loads the token; redeploy afterwards so every instance does. + ## Troubleshooting - **`401` on webhooks**: check `APP_GITHUB_WEBHOOK_SECRET`, and that API @@ -102,3 +130,5 @@ without the stage; set `GITHUB_APP_INSTALLER_ENABLED=false` instead. list every problem. - **`404` on every route**: `APP_BASE_PATH` doesn't match the stage. - **Timeouts**: raise the timeout; a sync of many large groups takes minutes. +- **The slash command answers but nothing runs**: the role can't invoke the + function; the logs show the failed dispatch. diff --git a/docs/slack-setup.md b/docs/slack-setup.md index 1190b11..67ee0e0 100644 --- a/docs/slack-setup.md +++ b/docs/slack-setup.md @@ -1,180 +1,175 @@ # Slack Setup -This guide walks through creating a Slack app for github-ops-app notifications. +This guide sets up the Slack app that posts github-ops-app's reports and +answers its slash command. The service can create and install the app itself +from a setup page (Option A), or you can create it by hand (Option B). ## Prerequisites -- Slack workspace with admin access (or ability to request app approval) -- Channel where notifications will be posted - -## Step 1: Create Slack App - -### Option A: Use App Manifest (Recommended) - -1. Go to [api.slack.com/apps](https://api.slack.com/apps) -2. Click **Create New App** -3. Select **From an app manifest** -4. Select your workspace -5. Copy the contents of - [`assets/slack/manifest.json`](../assets/slack/manifest.json) and paste into - the manifest editor -6. Click **Create** - -### Option B: Manual Setup - -1. Go to [api.slack.com/apps](https://api.slack.com/apps) -2. Click **Create New App** → **From scratch** -3. Enter app name: `GitHub Ops Bot` -4. Select your workspace -5. Click **Create App** - -Then continue to configure OAuth scopes manually (Step 2). - -## Step 2: Configure OAuth Scopes - -If you used the manifest, scopes are pre-configured. Otherwise: - -1. Go to **OAuth & Permissions** in the sidebar - -2. Scroll to **Scopes** → **Bot Token Scopes** - -3. Add the following scopes: - - | Scope | Purpose | - | ------------------- | ------------------------------------------ | - | `chat:write` | Post messages to channels bot is member of | - | `chat:write.public` | Post to public channels without joining | - - The app only posts messages, so it needs no other scopes. Leave out - `chat:write.public` to limit it to channels it is invited to. - -## Step 3: Install to Workspace - -1. Go to **OAuth & Permissions** -2. Click **Install to Workspace** -3. Review permissions and click **Allow** - -If your workspace requires admin approval: - -- Submit the app for approval -- Wait for workspace admin to approve -- Return to install after approval - -## Step 4: Get Bot Token - -After installation: - -1. Go to **OAuth & Permissions** -2. Copy the **Bot User OAuth Token** - - Starts with `xoxb-` - - Example: `xoxb-1234567890-...` - -This is your `APP_SLACK_TOKEN`. - -## Step 5: Get Channel ID - -You need the channel ID (not the name) for `APP_SLACK_CHANNEL`. - -### Method 1: From Slack UI - -1. Open Slack in a browser or desktop app -2. Right-click the channel name -3. Select **View channel details** (or **Open channel details**) -4. Scroll to the bottom - Channel ID is shown (e.g., `C01ABC2DEFG`) - -### Method 2: From Channel Link - -1. Right-click the channel name -2. Select **Copy link** -3. The link contains the channel ID: - `https://workspace.slack.com/archives/C01ABC2DEFG` - -### Method 3: Using Slack API +- A Slack workspace where you may create apps, or can request approval +- The channels the reports should go to +- For the slash command and the setup page, an HTTPS URL Slack can reach, such + as an API Gateway endpoint + +## Option A: Setup Page + +The setup page works like the [GitHub App installer](github-app-setup.md): it +creates the app from this deployment's manifest, with the slash command, its +URLs, and the icon filled in, runs Slack's install, and saves the credentials +where the installer saves the GitHub App's. + +1. Configure the service: + + ```bash + APP_SLACK_SETUP_ENABLED=true + APP_SLACK_CHANNEL=C01ABC2DEFG + # the external url of the service, including APP_BASE_PATH + APP_PUBLIC_URL=https://github-ops.example.com + # where the credentials are saved: envfile (default) or aws-ssm + STORAGE_MODE=envfile + STORAGE_DIR=./.env + ``` + + With `STORAGE_MODE=aws-ssm`, also set `AWS_SSM_PARAMETER_PREFIX`, and set + `APP_SLACK_TOKEN` and `APP_SLACK_SIGNING_SECRET` to the ARNs of the + parameters the setup will create under that prefix, such as + `arn:aws:ssm:us-east-1:123456789012:parameter/github-ops-app/APP_SLACK_TOKEN`. + Until the setup saves them, Slack stays off instead of failing. The role + needs `ssm:PutParameter` on the prefix while the setup is enabled. + +2. Visit `https://github-ops.example.com/slack/setup`. + +3. Create the app, either way: + - **With a configuration token**: on + [api.slack.com/apps](https://api.slack.com/apps), under **Your App + Configuration Tokens**, generate a token for the workspace and paste its + access token (`xoxe.xoxp-...`). The page creates the app and sets its + icon. The token is used once and not saved. + - **By hand**: open Slack with the page's manifest, create the app, and + paste its Client ID, Client Secret, and Signing Secret into the page. + +4. Click **Install to Slack**, check the workspace, and click **Allow**. + Slack sends you back to the page, the service loads the new token, and the + page shows your Slack user ID. + +5. Finish: + - Add the user IDs that may run `/github-ops sync` to + `APP_SLACK_COMMAND_ALLOWED_USERS`. + - Invite the app to private channels: `/invite @GitHub Ops`. + - Set `APP_SLACK_SETUP_ENABLED=false` and redeploy. + +Once the app is installed, the page refuses to replace its credentials or +install it into another workspace. Still, anyone who can reach the page before +then can create and install their own app, so only enable it while you set +the app up. In Lambda, other running instances load the token when they +restart, such as after the redeploy. + +## Option B: By Hand + +### 1. Create the App + +1. Go to [api.slack.com/apps](https://api.slack.com/apps) and click + **Create New App**, then **From an app manifest**. +2. Choose the workspace and paste + [`assets/slack/manifest.json`](../assets/slack/manifest.json), with + `github-ops.example.com` replaced by your service's host and base path. + Leave out `features.slash_commands`, the `commands` scope, and + `redirect_urls` if you don't want the slash command. +3. Click **Create**. + +To add the slash command to an app you already have, add to its manifest, under +**App Manifest**, the `slash_commands` entry and the `commands` scope from +[`assets/slack/manifest.json`](../assets/slack/manifest.json), then reinstall +the app. + +### 2. Install It and Copy the Credentials + +1. Under **OAuth & Permissions**, click **Install to Workspace** and + **Allow**. If your workspace needs approval, request it and install once an + admin approves. +2. Copy the **Bot User OAuth Token** (`xoxb-...`); this is `APP_SLACK_TOKEN`. +3. For the slash command, copy the **Signing Secret** from **Basic + Information**, under **App Credentials**; this is + `APP_SLACK_SIGNING_SECRET`. + +The app needs these scopes and no others: + +| Scope | Purpose | +| ------------------- | ------------------------------------------------ | +| `chat:write` | Post messages to channels the bot is a member of | +| `chat:write.public` | Post to public channels without joining | +| `commands` | The slash command | + +Leave out `chat:write.public` to limit the app to channels it is invited to. + +### 3. Configure the Service ```bash -curl -H "Authorization: Bearer xoxb-your-token" \ - "https://slack.com/api/conversations.list?types=public_channel,private_channel" \ - | jq '.channels[] | select(.name=="your-channel-name") | .id' -``` - -## Step 6: Add Bot to Private Channels - -For private channels, you must invite the bot: - -1. Open the private channel -2. Type `/invite @GitHub Ops Bot` (or your bot's display name) -3. Or click the channel name → **Integrations** → **Add apps** - -Public channels work without invitation when using `chat:write.public`. - -## Step 7: Configure Environment Variables - -```bash -# Required Slack configuration APP_SLACK_TOKEN=xoxb-1234567890-... APP_SLACK_CHANNEL=C01ABC2DEFG -# Optional: per-notification-type channels (override APP_SLACK_CHANNEL) +# optional: per-report channels, each falling back to APP_SLACK_CHANNEL APP_SLACK_CHANNEL_PR_BYPASS=C01234ABCDE APP_SLACK_CHANNEL_OKTA_SYNC=C01234ABCDE APP_SLACK_CHANNEL_ORPHANED_USERS=C01234ABCDE APP_SLACK_CHANNEL_SECURITY_ALERTS=C01234ABCDE + +# optional: the slash command +APP_SLACK_SIGNING_SECRET=0123456789abcdef0123456789abcdef +APP_SLACK_COMMAND_ALLOWED_USERS=U01ABC2DEFG,U04HIJ5KLMN ``` For AWS deployments, use SSM parameters: ```bash -APP_SLACK_TOKEN=arn:aws:ssm:us-east-1:123456789:parameter/github-bot/slack-token +APP_SLACK_TOKEN=arn:aws:ssm:us-east-1:123456789012:parameter/github-ops-app/slack-token ``` -## Step 8: Customize App Appearance (Optional) +## Finding IDs -Make notifications more recognizable: +### Channel IDs -1. Go to **Basic Information** -2. Under **Display Information**: - - **App name**: `GitHub Ops Bot` (or your preference) - - **Short description**: Brief description of the bot - - **App icon**: Upload a custom icon (use `assets/slack/icon.png` or your - own) - - **Background color**: `#10203B` or your brand color +`APP_SLACK_CHANNEL` takes a channel ID, not a name. In Slack, open the channel +details: the ID, such as `C01ABC2DEFG`, is at the bottom. A channel's link also +ends with it: `https://workspace.slack.com/archives/C01ABC2DEFG`. -## Verification +### User IDs -Test your Slack configuration: +`APP_SLACK_COMMAND_ALLOWED_USERS` takes user IDs, such as `U01ABC2DEFG`. Open +a person's profile, click the **⋮** menu, and choose **Copy member ID**. When +someone not on the list runs a command, the reply shows their ID too. -```bash -# Test message posting -curl -X POST https://slack.com/api/chat.postMessage \ - -H "Authorization: Bearer xoxb-your-token" \ - -H "Content-Type: application/json" \ - -d '{ - "channel": "C01ABC2DEFG", - "text": "GitHub Bot test message" - }' -``` +## Private Channels -Expected response: +Invite the bot to private channels it posts in: type `/invite @GitHub Ops` in +the channel, or use the channel's **Integrations** tab. Public channels work +without an invitation through `chat:write.public`. -```json -{ - "ok": true, - "channel": "C01ABC2DEFG", - "ts": "1234567890.123456", - "message": { ... } -} -``` +## Slash Command + +| Command | Who | Does | +| ----------------------------- | ------------- | --------------------------------------------------- | +| `/github-ops sync` | Allowed users | Syncs Okta groups to GitHub teams and posts results | +| `/github-ops security-alerts` | Allowed users | Posts the security alerts report | +| `/github-ops help` | Anyone | Lists the commands | -Then send a sample of every notification from the running service: +The command answers at once, only to who ran it, runs the job afterwards, +posts the report to its usual channel even if it hasn't changed, and replies +with a summary when it's done. Rename the command with `APP_SLACK_COMMAND`, in +the service and the app's manifest. + +## Verification + +Send a sample of every notification from the running service: ```bash curl -X POST -H "Authorization: Bearer $APP_ADMIN_TOKEN" \ https://github-ops.example.com/scheduled/slack-test ``` -## Notification Types +Then run `/github-ops help` in Slack. -The bot sends these notification types: +## Notification Types | Event | Description | | ---------------------- | --------------------------------------------------- | @@ -187,49 +182,25 @@ Text from GitHub and Okta, such as PR titles and group names, is escaped, so it can't mention channels or add links. Long reports are cut to fit Slack's message limits; the logs have the full report. +To check often without a message every time, set `APP_REPORT_REPEAT=daily`: +the reports then post when they change, and otherwise once a day. See +[Reports](../README.md#reports). + ## Troubleshooting ### "not_in_channel" error -- Bot needs to be in the channel to post -- For private channels: `/invite @GitHub Bot` -- For public channels: Ensure `chat:write.public` scope is granted +- The bot needs to be in the channel to post +- For private channels: `/invite @GitHub Ops` +- For public channels: check the app has the `chat:write.public` scope ### "invalid_auth" error -- Token may be expired or revoked -- Regenerate token: **OAuth & Permissions** → **Reinstall to Workspace** -- Verify token starts with `xoxb-` - -### "channel_not_found" error - -- Verify channel ID is correct (not channel name) -- Channel IDs start with `C` (public), `G` (private), or `D` (DM) -- Check the channel still exists - -### "missing_scope" error - -- Add the required scope in **OAuth & Permissions** -- Reinstall the app after adding scopes - -### Messages not appearing - -- Check the channel ID is correct -- Verify bot is in the channel (for private channels) -- Check app logs for API response errors -- Test with curl command above to isolate the issue - -### Rate limiting - -Slack allows about one message per second per channel. The app posts one -message per report, so it rarely reaches the limit; a rate-limited message is -logged as a failure and not retried. +- The token may be expired or revoked -## Security Considerations +### The slash command fails with "dispatch_failed" -- **Token security**: Store `APP_SLACK_TOKEN` securely (environment variable, - SSM parameter, or secrets manager) -- **Channel access**: Bot can only post to channels it has access to -- **No incoming webhooks**: This setup uses bot tokens, not incoming webhooks, - providing better security and audit trails -- **Minimal scopes**: Only request scopes actually needed +- Slack couldn't reach `https://YOUR_HOST/slack/commands`: check the command's + request URL in the app's settings +- `APP_SLACK_SIGNING_SECRET` is unset, so the service answers `404`, or wrong, + so it answers `401` and logs the rejected request