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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
|
package cors
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestCORSPreflightRequest tests CORS preflight OPTIONS requests
func TestCORSPreflightRequest(t *testing.T) {
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
// Set up CORS configuration
corsConfig := &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedOrigins: []string{"https://example.com"},
ExposeHeaders: []string{"ETag", "Content-Length"},
MaxAgeSeconds: aws.Int32(3600),
},
},
}
_, err := client.PutBucketCors(context.TODO(), &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: corsConfig,
})
require.NoError(t, err, "Should be able to put CORS configuration")
// Wait for metadata subscription to update cache
time.Sleep(50 * time.Millisecond)
// Test preflight request with raw HTTP
httpClient := &http.Client{Timeout: 10 * time.Second}
// Create OPTIONS request
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
// Add CORS preflight headers
req.Header.Set("Origin", "https://example.com")
req.Header.Set("Access-Control-Request-Method", "PUT")
req.Header.Set("Access-Control-Request-Headers", "Content-Type, Authorization")
// Send the request
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp.Body.Close()
// Verify CORS headers in response
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Methods"), "PUT", "Should allow PUT method")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Headers"), "Content-Type", "Should allow Content-Type header")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Headers"), "Authorization", "Should allow Authorization header")
assert.Equal(t, "3600", resp.Header.Get("Access-Control-Max-Age"), "Should have correct Max-Age header")
assert.Contains(t, resp.Header.Get("Access-Control-Expose-Headers"), "ETag", "Should expose ETag header")
assert.Equal(t, http.StatusOK, resp.StatusCode, "OPTIONS request should return 200")
}
// TestCORSActualRequest tests CORS behavior with actual requests
func TestCORSActualRequest(t *testing.T) {
// Temporarily clear AWS environment variables to ensure truly anonymous requests
// This prevents AWS SDK from auto-signing requests in GitHub Actions
originalAccessKey := os.Getenv("AWS_ACCESS_KEY_ID")
originalSecretKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
originalSessionToken := os.Getenv("AWS_SESSION_TOKEN")
originalProfile := os.Getenv("AWS_PROFILE")
originalRegion := os.Getenv("AWS_REGION")
os.Setenv("AWS_ACCESS_KEY_ID", "")
os.Setenv("AWS_SECRET_ACCESS_KEY", "")
os.Setenv("AWS_SESSION_TOKEN", "")
os.Setenv("AWS_PROFILE", "")
os.Setenv("AWS_REGION", "")
defer func() {
// Restore original environment variables
os.Setenv("AWS_ACCESS_KEY_ID", originalAccessKey)
os.Setenv("AWS_SECRET_ACCESS_KEY", originalSecretKey)
os.Setenv("AWS_SESSION_TOKEN", originalSessionToken)
os.Setenv("AWS_PROFILE", originalProfile)
os.Setenv("AWS_REGION", originalRegion)
}()
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
// Set up CORS configuration
corsConfig := &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "PUT"},
AllowedOrigins: []string{"https://example.com"},
ExposeHeaders: []string{"ETag", "Content-Length"},
MaxAgeSeconds: aws.Int32(3600),
},
},
}
_, err := client.PutBucketCors(context.TODO(), &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: corsConfig,
})
require.NoError(t, err, "Should be able to put CORS configuration")
// Wait for CORS configuration to be fully processed
time.Sleep(100 * time.Millisecond)
// First, put an object using S3 client
objectKey := "test-cors-object"
_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Body: strings.NewReader("Test CORS content"),
})
require.NoError(t, err, "Should be able to put object")
// Test GET request with CORS headers using raw HTTP
// Create a completely isolated HTTP client to avoid AWS SDK auto-signing
transport := &http.Transport{
// Completely disable any proxy or middleware
Proxy: nil,
}
httpClient := &http.Client{
Timeout: 10 * time.Second,
// Use a completely clean transport to avoid any AWS SDK middleware
Transport: transport,
}
// Create URL manually to avoid any AWS SDK endpoint processing
// Use the same endpoint as the S3 client to ensure compatibility with GitHub Actions
config := getDefaultConfig()
endpoint := config.Endpoint
// Remove any protocol prefix and ensure it's http for anonymous requests
if strings.HasPrefix(endpoint, "https://") {
endpoint = strings.Replace(endpoint, "https://", "http://", 1)
}
if !strings.HasPrefix(endpoint, "http://") {
endpoint = "http://" + endpoint
}
requestURL := fmt.Sprintf("%s/%s/%s", endpoint, bucketName, objectKey)
req, err := http.NewRequest("GET", requestURL, nil)
require.NoError(t, err, "Should be able to create GET request")
// Add Origin header to simulate CORS request
req.Header.Set("Origin", "https://example.com")
// Explicitly ensure no AWS headers are present (defensive programming)
// Clear ALL potential AWS-related headers that might be auto-added
req.Header.Del("Authorization")
req.Header.Del("X-Amz-Content-Sha256")
req.Header.Del("X-Amz-Date")
req.Header.Del("Amz-Sdk-Invocation-Id")
req.Header.Del("Amz-Sdk-Request")
req.Header.Del("X-Amz-Security-Token")
req.Header.Del("X-Amz-Session-Token")
req.Header.Del("AWS-Session-Token")
req.Header.Del("X-Amz-Target")
req.Header.Del("X-Amz-User-Agent")
// Ensure User-Agent doesn't indicate AWS SDK
req.Header.Set("User-Agent", "anonymous-cors-test/1.0")
// Verify no AWS-related headers are present
for name := range req.Header {
headerLower := strings.ToLower(name)
if strings.Contains(headerLower, "aws") ||
strings.Contains(headerLower, "amz") ||
strings.Contains(headerLower, "authorization") {
t.Fatalf("Found AWS-related header in anonymous request: %s", name)
}
}
// Send the request
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send GET request")
defer resp.Body.Close()
// Verify CORS headers are present
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
assert.Contains(t, resp.Header.Get("Access-Control-Expose-Headers"), "ETag", "Should expose ETag header")
// Anonymous requests should succeed when anonymous read permission is configured in IAM
// The server configuration allows anonymous users to have Read permissions
assert.Equal(t, http.StatusOK, resp.StatusCode, "Anonymous GET request should succeed when anonymous read is configured")
}
// TestCORSOriginMatching tests origin matching with different patterns
func TestCORSOriginMatching(t *testing.T) {
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
testCases := []struct {
name string
allowedOrigins []string
requestOrigin string
shouldAllow bool
}{
{
name: "exact match",
allowedOrigins: []string{"https://example.com"},
requestOrigin: "https://example.com",
shouldAllow: true,
},
{
name: "wildcard match",
allowedOrigins: []string{"*"},
requestOrigin: "https://example.com",
shouldAllow: true,
},
{
name: "subdomain wildcard match",
allowedOrigins: []string{"https://*.example.com"},
requestOrigin: "https://api.example.com",
shouldAllow: true,
},
{
name: "no match",
allowedOrigins: []string{"https://example.com"},
requestOrigin: "https://malicious.com",
shouldAllow: false,
},
{
name: "subdomain wildcard no match",
allowedOrigins: []string{"https://*.example.com"},
requestOrigin: "https://example.com",
shouldAllow: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Set up CORS configuration for this test case
corsConfig := &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET"},
AllowedOrigins: tc.allowedOrigins,
ExposeHeaders: []string{"ETag"},
MaxAgeSeconds: aws.Int32(3600),
},
},
}
_, err := client.PutBucketCors(context.TODO(), &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: corsConfig,
})
require.NoError(t, err, "Should be able to put CORS configuration")
// Wait for metadata subscription to update cache
time.Sleep(50 * time.Millisecond)
// Test preflight request
httpClient := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
req.Header.Set("Origin", tc.requestOrigin)
req.Header.Set("Access-Control-Request-Method", "GET")
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp.Body.Close()
if tc.shouldAllow {
assert.Equal(t, tc.requestOrigin, resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Methods"), "GET", "Should allow GET method")
} else {
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"), "Should not have Allow-Origin header for disallowed origin")
}
})
}
}
// TestCORSHeaderMatching tests header matching with different patterns
func TestCORSHeaderMatching(t *testing.T) {
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
testCases := []struct {
name string
allowedHeaders []string
requestHeaders string
shouldAllow bool
expectedHeaders string
}{
{
name: "wildcard headers",
allowedHeaders: []string{"*"},
requestHeaders: "Content-Type, Authorization",
shouldAllow: true,
expectedHeaders: "Content-Type, Authorization",
},
{
name: "specific headers match",
allowedHeaders: []string{"Content-Type", "Authorization"},
requestHeaders: "Content-Type, Authorization",
shouldAllow: true,
expectedHeaders: "Content-Type, Authorization",
},
{
name: "partial header match",
allowedHeaders: []string{"Content-Type"},
requestHeaders: "Content-Type",
shouldAllow: true,
expectedHeaders: "Content-Type",
},
{
name: "case insensitive match",
allowedHeaders: []string{"content-type"},
requestHeaders: "Content-Type",
shouldAllow: true,
expectedHeaders: "Content-Type",
},
{
name: "disallowed header",
allowedHeaders: []string{"Content-Type"},
requestHeaders: "Authorization",
shouldAllow: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Set up CORS configuration for this test case
corsConfig := &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: tc.allowedHeaders,
AllowedMethods: []string{"GET", "POST"},
AllowedOrigins: []string{"https://example.com"},
ExposeHeaders: []string{"ETag"},
MaxAgeSeconds: aws.Int32(3600),
},
},
}
_, err := client.PutBucketCors(context.TODO(), &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: corsConfig,
})
require.NoError(t, err, "Should be able to put CORS configuration")
// Wait for metadata subscription to update cache
time.Sleep(50 * time.Millisecond)
// Test preflight request
httpClient := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
req.Header.Set("Origin", "https://example.com")
req.Header.Set("Access-Control-Request-Method", "POST")
req.Header.Set("Access-Control-Request-Headers", tc.requestHeaders)
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp.Body.Close()
if tc.shouldAllow {
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
allowedHeaders := resp.Header.Get("Access-Control-Allow-Headers")
for _, header := range strings.Split(tc.expectedHeaders, ", ") {
assert.Contains(t, allowedHeaders, header, "Should allow header: %s", header)
}
} else {
// Even if headers are not allowed, the origin should still be in the response
// but the headers should not be echoed back
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
allowedHeaders := resp.Header.Get("Access-Control-Allow-Headers")
assert.NotContains(t, allowedHeaders, "Authorization", "Should not allow Authorization header")
}
})
}
}
// TestCORSWithoutConfiguration tests CORS behavior when no bucket-level configuration is set
// With the fallback feature, buckets without explicit CORS config will use the global CORS settings
func TestCORSWithoutConfiguration(t *testing.T) {
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
// Test preflight request without bucket-level CORS configuration
// The global CORS fallback (default: "*") should be used
httpClient := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
req.Header.Set("Origin", "https://example.com")
req.Header.Set("Access-Control-Request-Method", "GET")
req.Header.Set("Access-Control-Request-Headers", "Content-Type")
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp.Body.Close()
// With fallback CORS (global default: "*"), CORS headers should be present
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have Allow-Origin header from global fallback")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Methods"), "GET", "Should have GET in Allow-Methods from global fallback")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Headers"), "Content-Type", "Should have requested headers in Allow-Headers from global fallback")
}
// TestCORSMethodMatching tests method matching
func TestCORSMethodMatching(t *testing.T) {
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
// Set up CORS configuration with limited methods
corsConfig := &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "POST"},
AllowedOrigins: []string{"https://example.com"},
ExposeHeaders: []string{"ETag"},
MaxAgeSeconds: aws.Int32(3600),
},
},
}
_, err := client.PutBucketCors(context.TODO(), &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: corsConfig,
})
require.NoError(t, err, "Should be able to put CORS configuration")
// Wait for metadata subscription to update cache
time.Sleep(50 * time.Millisecond)
testCases := []struct {
method string
shouldAllow bool
}{
{"GET", true},
{"POST", true},
{"PUT", false},
{"DELETE", false},
{"HEAD", false},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("method_%s", tc.method), func(t *testing.T) {
httpClient := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
req.Header.Set("Origin", "https://example.com")
req.Header.Set("Access-Control-Request-Method", tc.method)
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp.Body.Close()
if tc.shouldAllow {
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Methods"), tc.method, "Should allow method: %s", tc.method)
} else {
// Even if method is not allowed, the origin should still be in the response
// but the method should not be in the allowed methods
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should have correct Allow-Origin header")
allowedMethods := resp.Header.Get("Access-Control-Allow-Methods")
assert.NotContains(t, allowedMethods, tc.method, "Should not allow method: %s", tc.method)
}
})
}
}
// TestCORSMultipleRulesMatching tests CORS with multiple rules
func TestCORSMultipleRulesMatching(t *testing.T) {
client := getS3Client(t)
bucketName := createTestBucket(t, client)
defer cleanupTestBucket(t, client, bucketName)
// Set up CORS configuration with multiple rules
corsConfig := &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: []string{"Content-Type"},
AllowedMethods: []string{"GET"},
AllowedOrigins: []string{"https://example.com"},
ExposeHeaders: []string{"ETag"},
MaxAgeSeconds: aws.Int32(3600),
},
{
AllowedHeaders: []string{"Authorization"},
AllowedMethods: []string{"POST", "PUT"},
AllowedOrigins: []string{"https://api.example.com"},
ExposeHeaders: []string{"Content-Length"},
MaxAgeSeconds: aws.Int32(7200),
},
},
}
_, err := client.PutBucketCors(context.TODO(), &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: corsConfig,
})
require.NoError(t, err, "Should be able to put CORS configuration")
// Wait for metadata subscription to update cache
time.Sleep(50 * time.Millisecond)
// Test first rule
httpClient := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
req.Header.Set("Origin", "https://example.com")
req.Header.Set("Access-Control-Request-Method", "GET")
req.Header.Set("Access-Control-Request-Headers", "Content-Type")
resp, err := httpClient.Do(req)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp.Body.Close()
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"), "Should match first rule")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Methods"), "GET", "Should allow GET method")
assert.Contains(t, resp.Header.Get("Access-Control-Allow-Headers"), "Content-Type", "Should allow Content-Type header")
assert.Equal(t, "3600", resp.Header.Get("Access-Control-Max-Age"), "Should have first rule's max age")
// Test second rule
req2, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/%s/test-object", getDefaultConfig().Endpoint, bucketName), nil)
require.NoError(t, err, "Should be able to create OPTIONS request")
req2.Header.Set("Origin", "https://api.example.com")
req2.Header.Set("Access-Control-Request-Method", "POST")
req2.Header.Set("Access-Control-Request-Headers", "Authorization")
resp2, err := httpClient.Do(req2)
require.NoError(t, err, "Should be able to send OPTIONS request")
defer resp2.Body.Close()
assert.Equal(t, "https://api.example.com", resp2.Header.Get("Access-Control-Allow-Origin"), "Should match second rule")
assert.Contains(t, resp2.Header.Get("Access-Control-Allow-Methods"), "POST", "Should allow POST method")
assert.Contains(t, resp2.Header.Get("Access-Control-Allow-Headers"), "Authorization", "Should allow Authorization header")
assert.Equal(t, "7200", resp2.Header.Get("Access-Control-Max-Age"), "Should have second rule's max age")
}
// TestServiceLevelCORS tests that service-level endpoints (like /status) get proper CORS headers
func TestServiceLevelCORS(t *testing.T) {
assert := assert.New(t)
endpoints := []string{
"/",
"/status",
"/healthz",
}
for _, endpoint := range endpoints {
t.Run(fmt.Sprintf("endpoint_%s", strings.ReplaceAll(endpoint, "/", "_")), func(t *testing.T) {
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s%s", getDefaultConfig().Endpoint, endpoint), nil)
assert.NoError(err)
// Add Origin header to trigger CORS
req.Header.Set("Origin", "http://example.com")
client := &http.Client{}
resp, err := client.Do(req)
assert.NoError(err)
defer resp.Body.Close()
// Should return 200 OK
assert.Equal(http.StatusOK, resp.StatusCode)
// Should have CORS headers set
assert.Equal("*", resp.Header.Get("Access-Control-Allow-Origin"))
assert.Equal("*", resp.Header.Get("Access-Control-Expose-Headers"))
assert.Equal("*", resp.Header.Get("Access-Control-Allow-Methods"))
assert.Equal("*", resp.Header.Get("Access-Control-Allow-Headers"))
})
}
}
// TestServiceLevelCORSWithoutOrigin tests that service-level endpoints without Origin header don't get CORS headers
func TestServiceLevelCORSWithoutOrigin(t *testing.T) {
assert := assert.New(t)
req, err := http.NewRequest("OPTIONS", fmt.Sprintf("%s/status", getDefaultConfig().Endpoint), nil)
assert.NoError(err)
// No Origin header
client := &http.Client{}
resp, err := client.Do(req)
assert.NoError(err)
defer resp.Body.Close()
// Should return 200 OK
assert.Equal(http.StatusOK, resp.StatusCode)
// Should not have CORS headers set (or have empty values)
corsHeaders := []string{
"Access-Control-Allow-Origin",
"Access-Control-Expose-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Headers",
}
for _, header := range corsHeaders {
value := resp.Header.Get(header)
// Headers should either be empty or not present
assert.True(value == "" || value == "*", "Header %s should be empty or wildcard, got: %s", header, value)
}
}
|