Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions cmd/aegora/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,19 @@ func buildAppWithRegistry(cfg *config.Config, logger *slog.Logger, reg *promethe
middleware.AccessLog(logger),
)

// CORS: answer browser preflights before shedding, rate limiting or queue
// capacity are spent; ordinary cross-origin responses get the headers and
// continue down the chain.
if cfg.CORS.Enabled {
mws = append(mws, middleware.CORS(middleware.CORSConfig{
Enabled: true,
AllowedOrigins: cfg.CORS.AllowedOrigins,
AllowedMethods: cfg.CORS.AllowedMethods,
AllowedHeaders: cfg.CORS.AllowedHeaders,
MaxAge: cfg.CORS.MaxAge.Duration(),
}))
}

// Request body limit: reject oversized bodies with 413 before they spend
// shedding, rate-limit, or queue capacity. Still logged and counted above.
if cfg.Server.MaxRequestBodyBytes > 0 {
Expand Down Expand Up @@ -365,17 +378,20 @@ func buildAppWithRegistry(cfg *config.Config, logger *slog.Logger, reg *promethe
// with their exact final status code.
// 5. AccessLog: Positioned after Tracing and Metrics to capture the assigned request_id, and
// measure exact routing and handler execution latency while capturing the final HTTP status code.
// 6. Request Body Limit (optional): Positioned after AccessLog and before Load Shedding so that
// 6. CORS (optional): Positioned after AccessLog and before the body limit, shedding,
// rate limiting and queue so preflight OPTIONS is logged and counted but never spends
// admission capacity.
// 7. Request Body Limit (optional): Positioned after CORS and before Load Shedding so that
// oversized bodies (413) are logged and counted but never consume shedding, rate-limit,
// or queue capacity, and never reach an upstream.
// 7. Load Shedding (optional): Positioned immediately after the body limit and before RateLimit to shed
// 8. Load Shedding (optional): Positioned immediately after the body limit and before RateLimit to shed
// globally before spending per-key rate-limit budget or queue capacity.
// 8. RateLimit (optional): Positioned between Load Shedding and Cache / mux / gateway to enforce
// 9. RateLimit (optional): Positioned between Load Shedding and Cache / mux / gateway to enforce
// per-key rate limits uniformly on all incoming requests. Routes with a rate_limit override
// use their own limiter (matched with the same router as the gateway); others use the global one.
// 9. Cache (optional): Positioned between RateLimit and Queue.Admit so that hits skip
// 10. Cache (optional): Positioned between RateLimit and Queue.Admit so that hits skip
// queueing and backend load (the expensive parts) while per-key rate limiting still applies uniformly.
// 10. Queue Admission (optional): Positioned between Cache and the upstream gateway to enforce
// 11. Queue Admission (optional): Positioned between Cache and the upstream gateway to enforce
// concurrency limits and CoDel bufferbloat drops on traffic routed to backend targets, while
// bypassing /livez and /readyz health probes.
func buildHandler(cfg *config.Config, logger *slog.Logger) (http.Handler, error) {
Expand Down
31 changes: 31 additions & 0 deletions cmd/aegora/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1589,3 +1589,34 @@ func requireJSONError(t *testing.T, rec *httptest.ResponseRecorder, wantError st
t.Fatal("expected a non-empty request_id in the error body")
}
}

func TestBuildHandler_CORS(t *testing.T) {
cfg := newTestConfig()
cfg.CORS = config.CORSConfig{
Enabled: true,
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{http.MethodGet, http.MethodOptions},
}

handler, q, err := buildApp(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatalf("buildApp: %v", err)
}
if q != nil {
q.Start()
defer q.Stop()
}

req := httptest.NewRequest(http.MethodOptions, "/api", nil)
req.Header.Set("Origin", "https://app.example.com")
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
}
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://app.example.com" {
t.Fatalf("allow-origin = %q", got)
}
}
30 changes: 30 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,33 @@ Configures the administrative management HTTP server.
Environment variable overrides:
- `AEGORA_ADMIN_ENABLED`
- `AEGORA_ADMIN_ADDR`

---

## 10. CORS (`cors`)

Configures cross-origin response headers and preflight handling for browser clients. Disabled by default; when disabled, responses are unchanged.

| Field | Type | Default | Reloadable | Description |
|---|---|---|---|---|
| `enabled` | bool | `false` | Yes | Enables CORS headers and preflight handling. |
| `allowed_origins` | []string | none (required if enabled) | Yes | Exact origins allowed (for example, `"https://app.example.com"`), or `"*"` for any origin. |
| `allowed_methods` | []string | `GET, POST, PUT, PATCH, DELETE, OPTIONS` | Yes | Methods advertised in `Access-Control-Allow-Methods` on preflight. |
| `allowed_headers` | []string | echo requested | Yes | Headers advertised in `Access-Control-Allow-Headers`. When empty, the request's `Access-Control-Request-Headers` value is echoed. |
| `max_age` | Duration | `0` | Yes | How long a browser may cache a preflight result (for example, `"1h"`). Emitted as `Access-Control-Max-Age` in seconds; zero omits the header. |

Behavior:
- Preflight `OPTIONS` requests (those carrying `Access-Control-Request-Method`) are answered with `204` before shedding, rate limiting and queue admission, so they never consume admission capacity.
- A request from an origin that is not allowed passes through unchanged without CORS headers; the browser then blocks the response.
- Restricted origins receive `Vary: Origin` so a cached response is never served to a different origin.
- `Access-Control-Allow-Credentials` is not set: this implementation covers public APIs, not cookie-authenticated cross-origin requests.

```yaml
cors:
enabled: true
allowed_origins:
- "https://app.example.com"
allowed_methods: ["GET", "POST", "OPTIONS"]
allowed_headers: ["Authorization", "Content-Type"]
max_age: "1h"
```
34 changes: 34 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ type Config struct {
Shedding SheddingConfig `yaml:"shedding,omitempty"`
Cache CacheConfig `yaml:"cache,omitempty"`
Admin AdminConfig `yaml:"admin,omitempty"`
CORS CORSConfig `yaml:"cors,omitempty"`
}

// CORSConfig configures cross-origin response headers and preflight handling.
type CORSConfig struct {
Enabled bool `yaml:"enabled"`
AllowedOrigins []string `yaml:"allowed_origins,omitempty"`
AllowedMethods []string `yaml:"allowed_methods,omitempty"`
AllowedHeaders []string `yaml:"allowed_headers,omitempty"`
MaxAge Duration `yaml:"max_age,omitempty"`
}

// AdminConfig configures the dedicated administrative HTTP server.
Expand Down Expand Up @@ -479,6 +489,30 @@ func (c *Config) Validate() error {
}
}

if c.CORS.Enabled {
if len(c.CORS.AllowedOrigins) == 0 {
return errors.New("config: cors.allowed_origins: must list at least one origin when cors is enabled")
}
for i, origin := range c.CORS.AllowedOrigins {
if strings.TrimSpace(origin) == "" {
return fmt.Errorf("config: cors.allowed_origins[%d]: cannot be empty", i)
}
}
for i, method := range c.CORS.AllowedMethods {
if strings.TrimSpace(method) == "" {
return fmt.Errorf("config: cors.allowed_methods[%d]: cannot be empty", i)
}
}
for i, header := range c.CORS.AllowedHeaders {
if strings.TrimSpace(header) == "" {
return fmt.Errorf("config: cors.allowed_headers[%d]: cannot be empty", i)
}
}
if c.CORS.MaxAge < 0 {
return fmt.Errorf("config: cors.max_age: must be non-negative, got %s", c.CORS.MaxAge)
}
}

return nil
}

Expand Down
85 changes: 85 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config_test

import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -155,6 +156,48 @@ func TestValidate_MutatedNegativeCases(t *testing.T) {
},
wantFieldInErr: "server.max_request_body_bytes",
},
{
name: "cors enabled without origins",
mutate: func(c *config.Config) {
c.CORS.Enabled = true
},
wantFieldInErr: "cors.allowed_origins",
},
{
name: "cors empty origin",
mutate: func(c *config.Config) {
c.CORS.Enabled = true
c.CORS.AllowedOrigins = []string{"https://app.example.com", " "}
},
wantFieldInErr: "cors.allowed_origins[1]",
},
{
name: "cors empty method",
mutate: func(c *config.Config) {
c.CORS.Enabled = true
c.CORS.AllowedOrigins = []string{"https://app.example.com"}
c.CORS.AllowedMethods = []string{"GET", ""}
},
wantFieldInErr: "cors.allowed_methods[1]",
},
{
name: "cors empty header",
mutate: func(c *config.Config) {
c.CORS.Enabled = true
c.CORS.AllowedOrigins = []string{"https://app.example.com"}
c.CORS.AllowedHeaders = []string{" "}
},
wantFieldInErr: "cors.allowed_headers[0]",
},
{
name: "cors negative max age",
mutate: func(c *config.Config) {
c.CORS.Enabled = true
c.CORS.AllowedOrigins = []string{"https://app.example.com"}
c.CORS.MaxAge = -1
},
wantFieldInErr: "cors.max_age",
},
{
name: "zero routes configured",
mutate: func(c *config.Config) {
Expand Down Expand Up @@ -265,6 +308,48 @@ func TestLoad_MissingFile(t *testing.T) {
}
}

func TestLoad_CORSYAML(t *testing.T) {
const raw = `
server:
addr: "127.0.0.1:8080"
read_timeout: "15s"
write_timeout: "30s"
idle_timeout: "60s"
routes:
- name: api
path_prefix: /api
targets:
- "http://127.0.0.1:8081"
observability:
log_level: info
cors:
enabled: true
allowed_origins:
- "https://app.example.com"
allowed_methods: ["GET", "POST"]
allowed_headers: ["Authorization"]
max_age: "1h"
`
path := filepath.Join(t.TempDir(), "cors.yaml")
if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
t.Fatalf("write fixture: %v", err)
}

cfg, err := config.Load(path)
if err != nil {
t.Fatalf("config.Load() unexpected error: %v", err)
}
if !cfg.CORS.Enabled {
t.Fatal("CORS.Enabled = false")
}
if len(cfg.CORS.AllowedOrigins) != 1 || cfg.CORS.AllowedOrigins[0] != "https://app.example.com" {
t.Fatalf("AllowedOrigins = %v", cfg.CORS.AllowedOrigins)
}
if cfg.CORS.MaxAge.Duration() != time.Hour {
t.Fatalf("MaxAge = %v", cfg.CORS.MaxAge.Duration())
}
}

func TestLoad_EnvOverrides(t *testing.T) {
t.Setenv("AEGORA_SERVER_ADDR", "127.0.0.1:9999")
t.Setenv("AEGORA_SERVER_READ_TIMEOUT", "45s")
Expand Down
106 changes: 106 additions & 0 deletions internal/middleware/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package middleware

import (
"net/http"
"strconv"
"strings"
"time"
)

// CORSConfig configures cross-origin response headers. Origins are matched
// exactly; "*" allows every origin. An empty AllowedMethods uses the common
// browser methods, and an empty AllowedHeaders echoes the requested headers.
type CORSConfig struct {
Enabled bool
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
MaxAge time.Duration
}

var defaultCORSMethods = []string{
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodOptions,
}

// CORS adds Access-Control-* headers to cross-origin responses and answers
// preflight requests with 204 without invoking the rest of the chain. A
// request from an origin that is not allowed passes through untouched, so the
// browser still sees the gateway's normal response and blocks it client-side.
func CORS(cfg CORSConfig) Middleware {
if !cfg.Enabled {
return func(next http.Handler) http.Handler { return next }
}

origins := make(map[string]struct{}, len(cfg.AllowedOrigins))
wildcard := false
for _, origin := range cfg.AllowedOrigins {
if origin == "*" {
wildcard = true
continue
}
origins[origin] = struct{}{}
}

methods := cfg.AllowedMethods
if len(methods) == 0 {
methods = defaultCORSMethods
}
allowMethods := strings.Join(methods, ", ")
allowHeaders := strings.Join(cfg.AllowedHeaders, ", ")

maxAge := ""
if cfg.MaxAge >= time.Second {
maxAge = strconv.Itoa(int(cfg.MaxAge / time.Second))
}

return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r)
return
}

allowed := wildcard
if !allowed {
_, allowed = origins[origin]
}
if !allowed {
next.ServeHTTP(w, r)
return
}

if wildcard {
w.Header().Set("Access-Control-Allow-Origin", "*")
} else {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Add("Vary", "Origin")
}

if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
w.Header().Set("Access-Control-Allow-Methods", allowMethods)
if allowHeaders != "" {
w.Header().Set("Access-Control-Allow-Headers", allowHeaders)
} else if requested := r.Header.Get("Access-Control-Request-Headers"); requested != "" {
w.Header().Set("Access-Control-Allow-Headers", requested)
}
if maxAge != "" {
w.Header().Set("Access-Control-Max-Age", maxAge)
}
if !wildcard {
w.Header().Add("Vary", "Access-Control-Request-Method")
w.Header().Add("Vary", "Access-Control-Request-Headers")
}
w.WriteHeader(http.StatusNoContent)
return
}

next.ServeHTTP(w, r)
})
}
}
Loading
Loading