-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
237 lines (205 loc) · 6.85 KB
/
Copy pathrequest.go
File metadata and controls
237 lines (205 loc) · 6.85 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package app
import (
"context"
"encoding/json"
"log/slog"
"strings"
"github.com/cruxstack/github-ops-app/internal/github/webhooks"
)
// RequestType identifies the category of incoming request.
type RequestType string
const (
// RequestTypeHTTP represents HTTP requests (webhooks, status, config).
RequestTypeHTTP RequestType = "http"
// RequestTypeScheduled represents scheduled/cron events.
RequestTypeScheduled RequestType = "scheduled"
)
// Request is a unified request type that abstracts HTTP and scheduled events.
// Runtimes (server, lambda) convert their native formats to this type.
type Request struct {
Type RequestType `json:"type"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body []byte `json:"body,omitempty"`
// ScheduledAction is used for scheduled events (e.g., "okta-sync").
ScheduledAction string `json:"scheduled_action,omitempty"`
// ScheduledData contains optional payload for scheduled events.
ScheduledData json.RawMessage `json:"scheduled_data,omitempty"`
}
// Response is a unified response type returned by HandleRequest.
// Runtimes convert this to their native response format.
type Response struct {
StatusCode int `json:"status_code"`
Headers map[string]string `json:"headers,omitempty"`
Body []byte `json:"body,omitempty"`
ContentType string `json:"content_type,omitempty"`
}
// HandleRequest routes incoming requests to the appropriate handler.
// This is the single entry point for all request processing.
func (a *App) HandleRequest(ctx context.Context, req Request) Response {
if a.Config.DebugEnabled {
j, _ := json.Marshal(req)
a.Logger.Debug("handling request", slog.String("request", string(j)))
}
switch req.Type {
case RequestTypeScheduled:
return a.handleScheduledRequest(ctx, req)
case RequestTypeHTTP:
return a.handleHTTPRequest(ctx, req)
default:
return errorResponse(400, "unknown request type")
}
}
// handleScheduledRequest processes scheduled/cron events.
func (a *App) handleScheduledRequest(ctx context.Context, req Request) Response {
evt := ScheduledEvent{
Action: req.ScheduledAction,
Data: req.ScheduledData,
}
if err := a.ProcessScheduledEvent(ctx, evt); err != nil {
a.Logger.Error("scheduled event processing failed",
slog.String("action", evt.Action),
slog.String("error", err.Error()))
return errorResponse(500, "scheduled event processing failed")
}
return jsonResponse(200, map[string]string{
"status": "success",
"message": evt.Action + " completed",
})
}
// handleHTTPRequest routes HTTP requests based on path.
// strips BasePath prefix if configured (e.g., "/api/v1" -> "/").
func (a *App) handleHTTPRequest(ctx context.Context, req Request) Response {
path := req.Path
if a.Config.BasePath != "" {
path = strings.TrimPrefix(path, a.Config.BasePath)
if path == "" {
path = "/"
}
}
switch path {
case "/server/status":
return a.handleStatusRequest(req)
case "/server/config":
return a.handleConfigRequest(req)
case "/webhooks", "/":
return a.handleWebhookRequest(ctx, req)
default:
if strings.HasPrefix(path, "/scheduled/") {
return a.handleScheduledHTTPRequest(ctx, req, path)
}
return errorResponse(404, "not found")
}
}
// handleStatusRequest returns application status.
func (a *App) handleStatusRequest(req Request) Response {
if req.Method != "GET" {
return errorResponse(405, "method not allowed")
}
if resp := a.checkAdminAuth(req); resp != nil {
return *resp
}
return jsonResponse(200, a.GetStatus())
}
// handleConfigRequest returns redacted configuration.
func (a *App) handleConfigRequest(req Request) Response {
if req.Method != "GET" {
return errorResponse(405, "method not allowed")
}
if resp := a.checkAdminAuth(req); resp != nil {
return *resp
}
return jsonResponse(200, a.Config.Redacted())
}
// handleWebhookRequest processes GitHub webhook POST requests.
func (a *App) handleWebhookRequest(ctx context.Context, req Request) Response {
if req.Method != "POST" {
return errorResponse(405, "method not allowed")
}
eventType := req.Headers["x-github-event"]
signature := req.Headers["x-hub-signature-256"]
if err := webhooks.ValidateWebhookSignature(
req.Body,
signature,
a.Config.GitHubWebhookSecret,
); err != nil {
a.Logger.Warn("webhook signature validation failed",
slog.String("error", err.Error()))
return errorResponse(401, "unauthorized")
}
if err := a.ProcessWebhook(ctx, req.Body, eventType); err != nil {
a.Logger.Error("webhook processing failed",
slog.String("event_type", eventType),
slog.String("error", err.Error()))
return errorResponse(500, "webhook processing failed")
}
return Response{
StatusCode: 200,
ContentType: "text/plain",
Body: []byte("ok"),
}
}
// handleScheduledHTTPRequest processes scheduled events via HTTP POST.
// path is the normalized path with BasePath already stripped.
func (a *App) handleScheduledHTTPRequest(ctx context.Context, req Request, path string) Response {
if req.Method != "POST" {
return errorResponse(405, "method not allowed")
}
if resp := a.checkAdminAuth(req); resp != nil {
return *resp
}
// extract action from path (e.g., "/scheduled/okta-sync" -> "okta-sync")
action := strings.TrimPrefix(path, "/scheduled/")
if action == "" {
return errorResponse(400, "missing scheduled action")
}
scheduledReq := Request{
Type: RequestTypeScheduled,
ScheduledAction: action,
}
return a.handleScheduledRequest(ctx, scheduledReq)
}
// jsonResponse creates a JSON response with the given status and data.
func jsonResponse(status int, data any) Response {
body, err := json.Marshal(data)
if err != nil {
return errorResponse(500, "failed to marshal response")
}
return Response{
StatusCode: status,
ContentType: "application/json",
Headers: map[string]string{"Content-Type": "application/json"},
Body: body,
}
}
// errorResponse creates an error response with the given status and message.
func errorResponse(status int, message string) Response {
return Response{
StatusCode: status,
ContentType: "text/plain",
Body: []byte(message),
}
}
// checkAdminAuth validates the admin token from the request.
// returns nil if auth is disabled (no token configured) or if token is valid.
// returns an error response if token is required but missing or invalid.
func (a *App) checkAdminAuth(req Request) *Response {
if a.Config.AdminToken == "" {
return nil
}
authHeader := req.Headers["authorization"]
if authHeader == "" {
resp := errorResponse(401, "unauthorized")
return &resp
}
token := strings.TrimPrefix(authHeader, "Bearer ")
if token == authHeader {
token = strings.TrimPrefix(authHeader, "bearer ")
}
if token != a.Config.AdminToken {
resp := errorResponse(401, "unauthorized")
return &resp
}
return nil
}