-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
215 lines (185 loc) · 6.21 KB
/
main.go
File metadata and controls
215 lines (185 loc) · 6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Package main provides the AWS Lambda entry point for the GitHub bot.
// This Lambda handler supports API Gateway HTTP API (v2.0) and EventBridge
// (scheduled sync) events.
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strings"
"sync"
awsevents "github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/cruxstack/github-ops-app/internal/app"
"github.com/cruxstack/github-ops-app/internal/config"
"github.com/cruxstack/github-ops-app/internal/github"
)
var (
initOnce sync.Once
appInst *app.App
logger *slog.Logger
initErr error
)
// initApp initializes the application instance once using sync.Once.
// stores any initialization error in the initErr global variable.
func initApp() {
initOnce.Do(func() {
logger = config.NewLogger()
cfg, err := config.NewConfig()
if err != nil {
initErr = fmt.Errorf("config init failed: %w", err)
return
}
appInst, initErr = app.New(context.Background(), cfg)
})
}
// APIGatewayHandler processes incoming API Gateway HTTP API (v2.0) requests.
// handles GitHub webhook events, status checks, and config endpoints.
// validates webhook signatures before processing events.
func APIGatewayHandler(ctx context.Context, req awsevents.APIGatewayV2HTTPRequest) (awsevents.APIGatewayV2HTTPResponse, error) {
initApp()
if initErr != nil {
logger.Error("initialization failed", slog.String("error", initErr.Error()))
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 500,
Body: "service initialization failed",
}, nil
}
if appInst.Config.DebugEnabled {
j, _ := json.Marshal(req)
logger.Debug("received api gateway request", slog.String("request", string(j)))
}
path := req.RawPath
if appInst.Config.BasePath != "" {
path = strings.TrimPrefix(path, appInst.Config.BasePath)
if path == "" {
path = "/"
}
}
if path == "/server/status" {
return handleServerStatus(ctx, req)
}
if path == "/server/config" {
return handleServerConfig(ctx, req)
}
if req.RequestContext.HTTP.Method != "POST" {
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 405,
Body: "method not allowed",
}, nil
}
eventType := req.Headers["x-github-event"]
signature := req.Headers["x-hub-signature-256"]
if err := github.ValidateWebhookSignature(
[]byte(req.Body),
signature,
appInst.Config.GitHubWebhookSecret,
); err != nil {
logger.Warn("webhook signature validation failed", slog.String("error", err.Error()))
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 401,
Body: "unauthorized",
}, nil
}
if err := appInst.ProcessWebhook(ctx, []byte(req.Body), eventType); err != nil {
logger.Error("webhook processing failed",
slog.String("event_type", eventType),
slog.String("error", err.Error()))
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 500,
Body: "webhook processing failed",
}, nil
}
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 200,
Body: "ok",
}, nil
}
// handleServerStatus returns the application status and feature flags.
// responds with JSON containing configuration state and enabled features.
func handleServerStatus(ctx context.Context, req awsevents.APIGatewayV2HTTPRequest) (awsevents.APIGatewayV2HTTPResponse, error) {
if req.RequestContext.HTTP.Method != "GET" {
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 405,
Body: "method not allowed",
}, nil
}
status := appInst.GetStatus()
body, err := json.Marshal(status)
if err != nil {
logger.Error("failed to marshal status response", slog.String("error", err.Error()))
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 500,
Body: "failed to generate status response",
}, nil
}
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 200,
Headers: map[string]string{"Content-Type": "application/json"},
Body: string(body),
}, nil
}
// handleServerConfig returns the application configuration with secrets
// redacted. useful for debugging and verifying environment settings.
func handleServerConfig(ctx context.Context, req awsevents.APIGatewayV2HTTPRequest) (awsevents.APIGatewayV2HTTPResponse, error) {
if req.RequestContext.HTTP.Method != "GET" {
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 405,
Body: "method not allowed",
}, nil
}
redacted := appInst.Config.Redacted()
body, err := json.Marshal(redacted)
if err != nil {
logger.Error("failed to marshal config response", slog.String("error", err.Error()))
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 500,
Body: "failed to generate config response",
}, nil
}
return awsevents.APIGatewayV2HTTPResponse{
StatusCode: 200,
Headers: map[string]string{"Content-Type": "application/json"},
Body: string(body),
}, nil
}
// EventBridgeHandler processes EventBridge scheduled events.
// typically handles scheduled Okta group sync operations.
func EventBridgeHandler(ctx context.Context, evt awsevents.CloudWatchEvent) error {
initApp()
if initErr != nil {
return initErr
}
if appInst.Config.DebugEnabled {
j, _ := json.Marshal(evt)
logger.Debug("received eventbridge event", slog.String("event", string(j)))
}
var detail app.ScheduledEvent
if err := json.Unmarshal(evt.Detail, &detail); err != nil {
logger.Error("failed to parse event detail", slog.String("error", err.Error()))
return err
}
return appInst.ProcessScheduledEvent(ctx, detail)
}
// UniversalHandler detects the event type and routes to the appropriate
// handler. supports API Gateway HTTP API (v2.0) and EventBridge events.
func UniversalHandler(ctx context.Context, event json.RawMessage) (any, error) {
if initErr != nil {
return nil, initErr
}
// try API Gateway HTTP API (v2.0)
var apiGatewayReq awsevents.APIGatewayV2HTTPRequest
if err := json.Unmarshal(event, &apiGatewayReq); err == nil && apiGatewayReq.RequestContext.HTTP.Method != "" {
return APIGatewayHandler(ctx, apiGatewayReq)
}
// try EventBridge
var eventBridgeEvent awsevents.CloudWatchEvent
if err := json.Unmarshal(event, &eventBridgeEvent); err == nil && eventBridgeEvent.DetailType != "" {
return nil, EventBridgeHandler(ctx, eventBridgeEvent)
}
return nil, fmt.Errorf("unknown lambda event type")
}
func main() {
lambda.Start(UniversalHandler)
}