Skip to content

Commit 120178b

Browse files
Generate UUID request ID when absent; reuse existing.
Co-authored-by: danmoz <danmoz@users.noreply.github.com>
1 parent 99b4dde commit 120178b

4 files changed

Lines changed: 83 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,22 @@ it does not trim a base path. AWS invocation errors, Lambda function
167167
errors, timeouts, throttling, and malformed responses are returned as Caddy
168168
handler errors and are not silently converted to successful responses.
169169

170+
### Request IDs
171+
172+
Every invocation carries a request ID, sourced from the incoming
173+
`X-Request-ID` header when present. When the header is absent, caddy-lambda
174+
generates a UUID in the same format as an AWS API Gateway request ID. The
175+
resulting value is used consistently for `requestContext.requestId`, the
176+
structured logs, and is returned to the client as an `X-Request-ID` response
177+
header.
178+
170179
## Logging
171180

172181
HTTP access logging remains Caddy's responsibility. This module does not log
173182
credentials, headers, or request/response bodies.
174183

175184
At `DEBUG` level, every attempted Lambda invocation emits the function name,
176-
invocation duration, and an incoming `X-Request-ID` when present. Failed
185+
invocation duration, and a request ID. Failed
177186
invocations also include the contextual error. At `INFO`, `WARN`, and `ERROR`
178187
levels, the module does not emit a separate per-invocation record. Invocation
179188
failures are returned as contextual handler errors for Caddy to log and convert

‎go.mod‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ require (
1111
github.com/aws/smithy-go v1.28.1
1212
github.com/caddyserver/caddy/v2 v2.11.4
1313
github.com/dustin/go-humanize v1.0.1
14+
github.com/google/uuid v1.6.0
1415
go.uber.org/zap v1.28.0
1516
)
1617

@@ -64,7 +65,6 @@ require (
6465
github.com/golang/snappy v0.0.4 // indirect
6566
github.com/google/cel-go v0.28.1 // indirect
6667
github.com/google/s2a-go v0.1.9 // indirect
67-
github.com/google/uuid v1.6.0 // indirect
6868
github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect
6969
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
7070
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect

‎middleware.go‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"github.com/aws/smithy-go"
2121
"github.com/caddyserver/caddy/v2"
2222
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
23+
"github.com/google/uuid"
2324
"go.uber.org/zap"
2425
)
2526

@@ -155,16 +156,22 @@ func (m *Lambda) Validate() error {
155156
// This is a terminal handler: it writes the response directly and never
156157
// calls next, so subsequent handlers in a route chain are not executed.
157158
func (m *Lambda) ServeHTTP(w http.ResponseWriter, r *http.Request, _ caddyhttp.Handler) error {
159+
requestID := r.Header.Get("X-Request-ID")
160+
if requestID == "" {
161+
requestID = newRequestID()
162+
r.Header.Set("X-Request-ID", requestID)
163+
}
164+
158165
req, err := newRequestForFormat(w, r, m.eventFormat(), m.MaxBodySize, m.UpstreamHeaders)
159166
if err != nil {
160167
return err
161168
}
162169

163-
requestID := r.Header.Get("X-Request-ID")
164-
if len(requestID) > maxLoggedRequestIDLength {
165-
requestID = requestID[:maxLoggedRequestIDLength]
170+
loggedRequestID := requestID
171+
if len(loggedRequestID) > maxLoggedRequestIDLength {
172+
loggedRequestID = loggedRequestID[:maxLoggedRequestIDLength]
166173
}
167-
resp, err := m.invokeLambda(r.Context(), req, requestID)
174+
resp, err := m.invokeLambda(r.Context(), req, loggedRequestID)
168175

169176
if err != nil {
170177
return caddyhttp.Error(lambdaErrorStatus(err), err)
@@ -208,6 +215,8 @@ func (m *Lambda) ServeHTTP(w http.ResponseWriter, r *http.Request, _ caddyhttp.H
208215
reply.Meta.Status = http.StatusOK
209216
}
210217

218+
w.Header().Set("X-Request-ID", requestID)
219+
211220
w.WriteHeader(reply.Meta.Status)
212221

213222
// Write the response body
@@ -218,6 +227,12 @@ func (m *Lambda) ServeHTTP(w http.ResponseWriter, r *http.Request, _ caddyhttp.H
218227
return err
219228
}
220229

230+
// newRequestID returns a collision-resistant correlation ID in the same
231+
// format as an AWS API Gateway request ID (a UUID).
232+
func newRequestID() string {
233+
return uuid.NewString()
234+
}
235+
221236
func lambdaErrorStatus(err error) int {
222237
if errors.Is(err, context.DeadlineExceeded) {
223238
return http.StatusGatewayTimeout

‎middleware_test.go‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/aws/aws-sdk-go-v2/service/lambda"
1515
"github.com/aws/smithy-go"
1616
"github.com/caddyserver/caddy/v2"
17+
"github.com/google/uuid"
1718
"go.uber.org/zap"
1819
"go.uber.org/zap/zaptest/observer"
1920
)
@@ -228,6 +229,58 @@ func TestServeHTTPReturnsApplicationResponse(t *testing.T) {
228229
}
229230
}
230231

232+
func TestServeHTTPGeneratesRequestIDWhenAbsent(t *testing.T) {
233+
fake := &fakeLambdaInvoker{output: &lambda.InvokeOutput{Payload: []byte(`{"statusCode":200,"body":"ok"}`)}}
234+
m := &Lambda{FunctionName: "test-function", EventFormat: eventFormatAPIGatewayV2, Timeout: caddy.Duration(time.Second), log: zap.NewNop(), svc: fake}
235+
w := httptest.NewRecorder()
236+
237+
if err := m.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/", nil), nil); err != nil {
238+
t.Fatalf("ServeHTTP() error = %v", err)
239+
}
240+
241+
var event APIGatewayV2Request
242+
if err := json.Unmarshal(fake.input.Payload, &event); err != nil {
243+
t.Fatalf("decode request payload: %v", err)
244+
}
245+
requestID := event.RequestContext.RequestID
246+
if requestID == "" {
247+
t.Fatal("request ID is empty, want generated ID")
248+
}
249+
if _, err := uuid.Parse(requestID); err != nil {
250+
t.Fatalf("request ID %q is not a UUID: %v", requestID, err)
251+
}
252+
if got := w.Header().Get("X-Request-ID"); got != requestID {
253+
t.Errorf("X-Request-ID response header = %q, want %q", got, requestID)
254+
}
255+
}
256+
257+
func TestServeHTTPPreservesExistingRequestID(t *testing.T) {
258+
core, logs := observer.New(zap.DebugLevel)
259+
fake := &fakeLambdaInvoker{output: &lambda.InvokeOutput{Payload: []byte(`{"statusCode":200,"body":"ok"}`)}}
260+
m := &Lambda{FunctionName: "test-function", EventFormat: eventFormatAPIGatewayV2, Timeout: caddy.Duration(time.Second), log: zap.New(core), svc: fake}
261+
w := httptest.NewRecorder()
262+
r := httptest.NewRequest(http.MethodGet, "/", nil)
263+
r.Header.Set("X-Request-ID", "existing-id")
264+
265+
if err := m.ServeHTTP(w, r, nil); err != nil {
266+
t.Fatalf("ServeHTTP() error = %v", err)
267+
}
268+
269+
var event APIGatewayV2Request
270+
if err := json.Unmarshal(fake.input.Payload, &event); err != nil {
271+
t.Fatalf("decode request payload: %v", err)
272+
}
273+
if got := event.RequestContext.RequestID; got != "existing-id" {
274+
t.Errorf("request ID = %q, want %q", got, "existing-id")
275+
}
276+
if got := w.Header().Get("X-Request-ID"); got != "existing-id" {
277+
t.Errorf("X-Request-ID response header = %q, want %q", got, "existing-id")
278+
}
279+
if got := logs.All()[0].ContextMap()["request_id"]; got != "existing-id" {
280+
t.Errorf("logged request_id = %#v, want existing-id", got)
281+
}
282+
}
283+
231284
func TestServeHTTPLimitsLoggedRequestID(t *testing.T) {
232285
core, logs := observer.New(zap.DebugLevel)
233286
fake := &fakeLambdaInvoker{output: &lambda.InvokeOutput{Payload: []byte(`{"type":"HTTPJSON-REP","meta":{"status":200},"body":"ok"}`)}}

0 commit comments

Comments
 (0)