1 Commits
Author SHA1 Message Date
clawbot 432342e963 Stop allowing credentialed cross-origin requests (closes #261)
check / check (push) Failing after 5s
CORS() allowed every origin with credentials, so a page on another
origin of the same site could read what the signed-in user sees. It
now uses the options of the CONVENTIONS.md template: every origin as
*, no credentials, and the template's request headers. corsMaxAge
stays, since AGENTS.md asks for named constants.

Model: opus-5-5
2026-11-10 22:25:40 +00:00
7 changed files with 111 additions and 283 deletions

No files matched your search

+11 -12
View File
@@ -168,10 +168,10 @@ either.
- Request bodies for `POST /api/v1/session`, `POST /api/v1/login` and - Request bodies for `POST /api/v1/session`, `POST /api/v1/login` and
`POST /api/v1/messages` are limited to `MAX_MESSAGE_SIZE` bytes (default `POST /api/v1/messages` are limited to `MAX_MESSAGE_SIZE` bytes (default
`4096`). A larger body gets `400` `invalid request body`. `4096`). A larger body gets `400` `invalid request body`.
- `GET /api/v1/server` and `GET /.well-known/healthcheck.json` answer a request - A response to a cross-origin request carries `Access-Control-Allow-Origin: *`,
from any origin with `Access-Control-Allow-Origin: *`. Every other route sends never the request's origin, and never `Access-Control-Allow-Credentials`. A
no `Access-Control-Allow-*` header, so a page on another origin cannot read page on another origin therefore cannot read the response to a request that
its responses. carries the cookie.
### The auth cookie ### The auth cookie
@@ -1724,8 +1724,7 @@ exceptions:
A `neoirc.yaml` that is not valid YAML stops the server at startup. A setting A `neoirc.yaml` that is not valid YAML stops the server at startup. A setting
that does not parse or is out of range also stops the server at startup, and the that does not parse or is out of range also stops the server at startup, and the
error names the setting. The same holds for a setting given a list or a map in error names the setting.
`neoirc.yaml`.
- `PORT` (default `8080`): the HTTP port. `0` lets the system pick a free port. - `PORT` (default `8080`): the HTTP port. `0` lets the system pick a free port.
- `IRC_LISTEN_ADDR` (default `:6667`): the address of the IRC listener. The - `IRC_LISTEN_ADDR` (default `:6667`): the address of the IRC listener. The
@@ -1895,14 +1894,14 @@ The IRC listener has no TLS.
seconds. A request still running after 60 seconds is cancelled, and the seconds. A request still running after 60 seconds is cancelled, and the
connection closes without a response. Headers may be up to 1 MiB. connection closes without a response. Headers may be up to 1 MiB.
- A long poll waits at most 30 seconds. - A long poll waits at most 30 seconds.
- Every response to a well-formed request carries a `Content-Security-Policy` - Every response to a well-formed request, except to a cross-origin preflight,
header: carries a `Content-Security-Policy` header:
`default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'`. `default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'`.
The web client works within it. The web client works within it.
- `GET /api/v1/server` and `GET /.well-known/healthcheck.json` answer a request - A response to a cross-origin request carries `Access-Control-Allow-Origin: *`,
from any origin with `Access-Control-Allow-Origin: *`. Every other route sends never the request's origin, and never `Access-Control-Allow-Credentials`. A
no `Access-Control-Allow-*` header, so a page on another origin cannot read page on another origin therefore cannot read the response to a request that
its responses. carries the cookie.
### Logging ### Logging
+1 -1
View File
@@ -13,7 +13,6 @@ require (
github.com/prometheus/client_golang v1.23.2 github.com/prometheus/client_golang v1.23.2
github.com/rivo/tview v0.42.0 github.com/rivo/tview v0.42.0
github.com/slok/go-http-metrics v0.13.0 github.com/slok/go-http-metrics v0.13.0
github.com/spf13/cast v1.10.0
github.com/spf13/viper v1.21.0 github.com/spf13/viper v1.21.0
go.uber.org/fx v1.24.0 go.uber.org/fx v1.24.0
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb go4.org/netipx v0.0.0-20260823151212-3075585bcbeb
@@ -42,6 +41,7 @@ require (
github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/pflag v1.0.10 // indirect
github.com/subosito/gotenv v1.6.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/dig v1.19.0 // indirect go.uber.org/dig v1.19.0 // indirect
+57 -99
View File
@@ -12,7 +12,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/spf13/cast"
"github.com/spf13/viper" "github.com/spf13/viper"
"go.uber.org/fx" "go.uber.org/fx"
"go4.org/netipx" "go4.org/netipx"
@@ -44,7 +43,7 @@ var errOutOfRange = errors.New("setting out of range")
var errNeverMatches = errors.New("entry can never match a connection") var errNeverMatches = errors.New("entry can never match a connection")
var errListOrMap = errors.New("a list or a map") var errNotString = errors.New("not a string")
// Params defines the dependencies for creating a Config. // Params defines the dependencies for creating a Config.
type Params struct { type Params struct {
@@ -82,9 +81,8 @@ type Config struct {
} }
// New creates a new Config by reading from files and environment variables. // New creates a new Config by reading from files and environment variables.
// It returns an error when the config file does not parse, when the file // It returns an error when a number, true/false, duration or address
// gives a setting a list or a map, and when a number, true/false, // setting does not parse or is out of range.
// duration or address setting does not parse or is out of range.
func New( func New(
_ fx.Lifecycle, params Params, _ fx.Lifecycle, params Params,
) (*Config, error) { ) (*Config, error) {
@@ -123,12 +121,25 @@ func New(
if err != nil { if err != nil {
var notFound viper.ConfigFileNotFoundError var notFound viper.ConfigFileNotFoundError
if !errors.As(err, &notFound) { if !errors.As(err, &notFound) {
return nil, fmt.Errorf("cannot read %s: %w", log.Error("config file malformed", "error", err)
viper.ConfigFileUsed(), err) panic(err)
} }
} }
cfg := &Config{ cfg := &Config{
DBURL: viper.GetString("DBURL"),
SentryDSN: viper.GetString("SENTRY_DSN"),
MetricsUsername: viper.GetString("METRICS_USERNAME"),
MetricsPassword: viper.GetString("METRICS_PASSWORD"),
MessageMaxAge: viper.GetString("MESSAGE_MAX_AGE"),
QueueMaxAge: viper.GetString("QUEUE_MAX_AGE"),
MOTD: viper.GetString("MOTD"),
ServerName: viper.GetString("SERVER_NAME"),
FederationKey: viper.GetString("FEDERATION_KEY"),
SessionIdleTimeout: viper.GetString("SESSION_IDLE_TIMEOUT"),
OperName: viper.GetString("NEOIRC_OPER_NAME"),
OperPassword: viper.GetString("NEOIRC_OPER_PASSWORD"),
IRCListenAddr: viper.GetString("IRC_LISTEN_ADDR"),
log: log, log: log,
params: &params, params: &params,
} }
@@ -138,6 +149,13 @@ func New(
return nil, err return nil, err
} }
// Viper counts an empty environment variable as unset, but an
// empty IRC_LISTEN_ADDR must turn the IRC listener off.
ircListenAddr, set := os.LookupEnv("IRC_LISTEN_ADDR")
if set {
cfg.IRCListenAddr = ircListenAddr
}
if cfg.Debug { if cfg.Debug {
params.Logger.EnableDebugLogging() params.Logger.EnableDebugLogging()
cfg.log = params.Logger.Get() cfg.log = params.Logger.Get()
@@ -146,24 +164,13 @@ func New(
return cfg, nil return cfg, nil
} }
// parseSettings reads every setting into cfg. Each number and duration // parseSettings reads the number, true/false and address settings into
// must be above zero. PORT and NEOIRC_HASHCASH_BITS may also be zero: // cfg and checks the duration settings. Each number and duration must be
// port 0 lets the system pick a port, and 0 bits turns proof of work off. // above zero. PORT and NEOIRC_HASHCASH_BITS may also be zero: port 0 lets
// The error names each setting that is a list or a map, does not parse or // the system pick a port, and 0 bits turns proof of work off. The error
// is out of range. // names each setting that does not parse or is out of range.
func parseSettings(cfg *Config) error { func parseSettings(cfg *Config) error {
return errors.Join( return errors.Join(
parseString("DBURL", &cfg.DBURL),
parseString("SENTRY_DSN", &cfg.SentryDSN),
parseString("METRICS_USERNAME", &cfg.MetricsUsername),
parseString("METRICS_PASSWORD", &cfg.MetricsPassword),
parseString("MOTD", &cfg.MOTD),
parseString("SERVER_NAME", &cfg.ServerName),
parseString("FEDERATION_KEY", &cfg.FederationKey),
parseString("NEOIRC_OPER_NAME", &cfg.OperName),
parseString("NEOIRC_OPER_PASSWORD", &cfg.OperPassword),
// The empty string turns the IRC listener off.
parseStringAllowEmptyEnv("IRC_LISTEN_ADDR", &cfg.IRCListenAddr),
parseInt("PORT", 0, &cfg.Port), parseInt("PORT", 0, &cfg.Port),
parseInt("MAX_MESSAGE_SIZE", 1, &cfg.MaxMessageSize), parseInt("MAX_MESSAGE_SIZE", 1, &cfg.MaxMessageSize),
parseInt("NEOIRC_HASHCASH_BITS", 0, &cfg.HashcashBits), parseInt("NEOIRC_HASHCASH_BITS", 0, &cfg.HashcashBits),
@@ -171,70 +178,39 @@ func parseSettings(cfg *Config) error {
parseFloat("LOGIN_RATE_LIMIT", &cfg.LoginRateLimit), parseFloat("LOGIN_RATE_LIMIT", &cfg.LoginRateLimit),
parseBool("DEBUG", &cfg.Debug), parseBool("DEBUG", &cfg.Debug),
parseBool("MAINTENANCE_MODE", &cfg.MaintenanceMode), parseBool("MAINTENANCE_MODE", &cfg.MaintenanceMode),
parseDuration("MESSAGE_MAX_AGE", &cfg.MessageMaxAge), checkDuration("MESSAGE_MAX_AGE", cfg.MessageMaxAge),
parseDuration("QUEUE_MAX_AGE", &cfg.QueueMaxAge), checkDuration("QUEUE_MAX_AGE", cfg.QueueMaxAge),
parseDuration("SESSION_IDLE_TIMEOUT", &cfg.SessionIdleTimeout), checkDuration("SESSION_IDLE_TIMEOUT", cfg.SessionIdleTimeout),
parseTrustedProxies(&cfg.TrustedProxies), parseTrustedProxies(&cfg.TrustedProxies),
) )
} }
// getString returns the setting key as a string. A number or a true/false
// value in the config file becomes its text, as with viper.GetString. A
// list or a map in the config file is an error, where viper.GetString
// would return the empty string. The error leaves out the value, which
// may be a password.
func getString(key string) (string, error) {
raw, err := cast.ToStringE(viper.Get(key))
if err != nil {
return "", fmt.Errorf("%s is %w", key, errListOrMap)
}
return raw, nil
}
// parseString sets *value to the setting key.
func parseString(key string, value *string) error {
raw, err := getString(key)
if err != nil {
return err
}
*value = raw
return nil
}
// parseStringAllowEmptyEnv sets *value to the setting key, as parseString
// does, but an environment variable set to the empty string counts as
// set. Viper counts such a variable as unset and uses the config file or
// the default instead.
func parseStringAllowEmptyEnv(key string, value *string) error {
fromEnv, set := os.LookupEnv(key)
if set {
*value = fromEnv
return nil
}
return parseString(key, value)
}
// parseTrustedProxies sets *value to the addresses in TRUSTED_PROXIES, a // parseTrustedProxies sets *value to the addresses in TRUSTED_PROXIES, a
// comma-separated list of networks such as 10.0.0.0/8 and single // comma-separated list of networks such as 10.0.0.0/8 and single
// addresses such as 192.0.2.1. The empty string trusts nothing. // addresses such as 192.0.2.1. The empty string trusts nothing. Viper
// counts an empty environment variable as unset, so the environment is
// read directly as well.
func parseTrustedProxies(value **netipx.IPSet) error { func parseTrustedProxies(value **netipx.IPSet) error {
var raw string setting := viper.Get("TRUSTED_PROXIES")
err := parseStringAllowEmptyEnv("TRUSTED_PROXIES", &raw) fromEnv, set := os.LookupEnv("TRUSTED_PROXIES")
if err != nil { if set {
return err setting = fromEnv
}
// A YAML list or map in the config file is not a string, and
// viper.GetString would turn it into the empty string.
raw, isString := setting.(string)
if !isString {
return fmt.Errorf("cannot parse TRUSTED_PROXIES: %v is %w",
setting, errNotString)
} }
var builder netipx.IPSetBuilder var builder netipx.IPSetBuilder
if strings.TrimSpace(raw) != "" { if strings.TrimSpace(raw) != "" {
for entry := range strings.SplitSeq(raw, ",") { for entry := range strings.SplitSeq(raw, ",") {
err = addTrustedProxy(&builder, strings.TrimSpace(entry)) err := addTrustedProxy(&builder, strings.TrimSpace(entry))
if err != nil { if err != nil {
return fmt.Errorf("cannot parse TRUSTED_PROXIES: %w", err) return fmt.Errorf("cannot parse TRUSTED_PROXIES: %w", err)
} }
@@ -291,10 +267,7 @@ func addTrustedProxy(builder *netipx.IPSetBuilder, entry string) error {
// parseInt sets *value to the setting key read as a whole number. It // parseInt sets *value to the setting key read as a whole number. It
// returns an error when the value does not parse or is below minimum. // returns an error when the value does not parse or is below minimum.
func parseInt(key string, minimum int, value *int) error { func parseInt(key string, minimum int, value *int) error {
raw, err := getString(key) raw := viper.GetString(key)
if err != nil {
return err
}
parsed, err := strconv.Atoi(raw) parsed, err := strconv.Atoi(raw)
if err != nil { if err != nil {
@@ -315,10 +288,7 @@ func parseInt(key string, minimum int, value *int) error {
// number. It returns an error when the value does not parse or is not a // number. It returns an error when the value does not parse or is not a
// finite number above zero. // finite number above zero.
func parseFloat(key string, value *float64) error { func parseFloat(key string, value *float64) error {
raw, err := getString(key) raw := viper.GetString(key)
if err != nil {
return err
}
parsed, err := strconv.ParseFloat(raw, 64) parsed, err := strconv.ParseFloat(raw, 64)
if err != nil { if err != nil {
@@ -338,12 +308,7 @@ func parseFloat(key string, value *float64) error {
// parseBool sets *value to the setting key read as true or false. // parseBool sets *value to the setting key read as true or false.
func parseBool(key string, value *bool) error { func parseBool(key string, value *bool) error {
raw, err := getString(key) parsed, err := strconv.ParseBool(viper.GetString(key))
if err != nil {
return err
}
parsed, err := strconv.ParseBool(raw)
if err != nil { if err != nil {
return fmt.Errorf("cannot parse %s: %w", key, err) return fmt.Errorf("cannot parse %s: %w", key, err)
} }
@@ -353,25 +318,18 @@ func parseBool(key string, value *bool) error {
return nil return nil
} }
// parseDuration sets *value to the setting key. It returns an error when // checkDuration returns an error naming the setting key when value is
// the value is not a Go duration above zero. // not a Go duration above zero.
func parseDuration(key string, value *string) error { func checkDuration(key, value string) error {
raw, err := getString(key) duration, err := time.ParseDuration(value)
if err != nil {
return err
}
duration, err := time.ParseDuration(raw)
if err != nil { if err != nil {
return fmt.Errorf("cannot parse %s: %w", key, err) return fmt.Errorf("cannot parse %s: %w", key, err)
} }
if duration <= 0 { if duration <= 0 {
return fmt.Errorf("%w: %s is %s, but must be above zero", return fmt.Errorf("%w: %s is %s, but must be above zero",
errOutOfRange, key, raw) errOutOfRange, key, value)
} }
*value = raw
return nil return nil
} }
+21 -125
View File
@@ -287,153 +287,49 @@ func TestTrustedProxies(t *testing.T) {
} }
} }
// unsetEnv removes the environment variable key for the rest of the func TestTrustedProxiesNotAStringInYAMLStopsStartup(t *testing.T) {
// test, so that config.New reads key from the config file. // YAML reads the first value as a list and the second as a map.
func unsetEnv(t *testing.T, key string) { values := []string{"[10.0.0.1]", "{proxy: 10.0.0.1}"}
t.Helper()
// t.Setenv puts back whatever value was there after the test, for _, value := range values {
// including when Unsetenv removes it. t.Run(value, func(t *testing.T) {
t.Setenv(key, "") // t.Setenv puts back whatever value was there after the
// test, including when Unsetenv removes it.
t.Setenv("TRUSTED_PROXIES", "")
err := os.Unsetenv(key) err := os.Unsetenv("TRUSTED_PROXIES")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
}
// writeConfigFile writes content to the config file config.New reads
// when HOME is home, and returns the file's path.
func writeConfigFile(t *testing.T, home, content string) string {
t.Helper()
// loadConfig names the app neoirc-test, so config.New reads // loadConfig names the app neoirc-test, so config.New reads
// $HOME/.config/neoirc-test/neoirc-test.yaml. // $HOME/.config/neoirc-test/neoirc-test.yaml.
home := t.TempDir()
t.Setenv("HOME", home)
dir := filepath.Join(home, ".config", "neoirc-test") dir := filepath.Join(home, ".config", "neoirc-test")
err := os.MkdirAll(dir, 0o700) err = os.MkdirAll(dir, 0o700)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
path := filepath.Join(dir, "neoirc-test.yaml") err = os.WriteFile(
filepath.Join(dir, "neoirc-test.yaml"),
err = os.WriteFile(path, []byte(content), 0o600) []byte("TRUSTED_PROXIES: "+value+"\n"), 0o600,
)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Viper keeps the file and the values it read from it after the // Viper keeps the values it read from this file after the
// file is gone. Reset clears them for later tests. // file is gone. Reset clears them for later tests.
t.Cleanup(viper.Reset) t.Cleanup(viper.Reset)
return path _, err = loadConfig(t)
} if err == nil || !strings.Contains(err.Error(), "TRUSTED_PROXIES") {
t.Errorf("error = %v, want one naming TRUSTED_PROXIES", err)
func TestListOrMapInConfigFileStopsStartup(t *testing.T) {
// YAML reads the first value as a list and the second as a map.
values := []string{`[":6667"]`, `{addr: ":6667"}`}
keys := []string{"IRC_LISTEN_ADDR", "MOTD", "TRUSTED_PROXIES"}
for _, key := range keys {
for _, value := range values {
t.Run(key+"="+value, func(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
unsetEnv(t, key)
writeConfigFile(t, home, key+": "+value+"\n")
_, err := loadConfig(t)
if err == nil || !strings.Contains(err.Error(), key) {
t.Errorf("error = %v, want one naming %s", err, key)
} }
}) })
} }
} }
}
func TestListOrMapErrorLeavesOutValue(t *testing.T) {
const key = "NEOIRC_OPER_PASSWORD"
home := t.TempDir()
t.Setenv("HOME", home)
unsetEnv(t, key)
// YAML reads an unquoted {hunter2} as a map.
writeConfigFile(t, home, key+": {hunter2}\n")
_, err := loadConfig(t)
if err == nil || !strings.Contains(err.Error(), key) {
t.Fatalf("error = %v, want one naming %s", err, key)
}
if strings.Contains(err.Error(), "hunter2") {
t.Errorf("error %q shows the password", err)
}
}
func TestEmptyEnvironmentValueWinsOverConfigFile(t *testing.T) {
const (
ircListenAddr = "IRC_LISTEN_ADDR"
trustedProxies = "TRUSTED_PROXIES"
)
// Each setting is the empty string in the environment and a list in
// the config file. The environment wins, so the list is never read.
tests := []struct {
key string
empty func(cfg *config.Config) bool
}{
{
key: ircListenAddr,
empty: func(cfg *config.Config) bool {
return cfg.IRCListenAddr == ""
},
},
{
key: trustedProxies,
empty: func(cfg *config.Config) bool {
return len(cfg.TrustedProxies.Prefixes()) == 0
},
},
}
for _, test := range tests {
t.Run(test.key, func(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv(test.key, "")
writeConfigFile(t, home, test.key+": [\":6667\"]\n")
cfg := newConfig(t)
if !test.empty(cfg) {
t.Errorf("%s is not the empty string", test.key)
}
})
}
}
func TestSingleValuesInConfigFileAreUsed(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
unsetEnv(t, "PORT")
unsetEnv(t, "DEBUG")
unsetEnv(t, "MOTD")
writeConfigFile(t, home, "PORT: 9000\nDEBUG: true\nMOTD: hello\n")
cfg := newConfig(t)
if cfg.Port != 9000 || !cfg.Debug || cfg.MOTD != "hello" {
t.Errorf("Port, Debug, MOTD = %d, %t, %q, want 9000, true, %q",
cfg.Port, cfg.Debug, cfg.MOTD, "hello")
}
}
func TestConfigFileThatDoesNotParseStopsStartup(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
path := writeConfigFile(t, home, "MOTD: [unclosed\n")
_, err := loadConfig(t)
if err == nil || !strings.Contains(err.Error(), path) {
t.Errorf("error = %v, want one naming %s", err, path)
}
}
+3 -2
View File
@@ -200,8 +200,9 @@ func (mware *Middleware) Logging() func(http.Handler) http.Handler {
} }
} }
// CORS returns middleware that lets a page on any origin read the // CORS returns middleware that handles Cross-Origin Resource Sharing.
// response. Use it only on public, read-only routes. // It allows every origin, without credentials, so a page on another
// origin cannot read what the signed-in user sees.
func (mware *Middleware) CORS() func(http.Handler) http.Handler { func (mware *Middleware) CORS() func(http.Handler) http.Handler {
return cors.Handler(cors.Options{ //nolint:exhaustruct // optional fields return cors.Handler(cors.Options{ //nolint:exhaustruct // optional fields
AllowedOrigins: []string{"*"}, AllowedOrigins: []string{"*"},
+3 -2
View File
@@ -30,6 +30,7 @@ func (srv *Server) SetupRoutes() {
srv.router.Use(srv.mw.Metrics()) srv.router.Use(srv.mw.Metrics())
} }
srv.router.Use(srv.mw.CORS())
srv.router.Use(srv.mw.CSP()) srv.router.Use(srv.mw.CSP())
srv.router.Use(middleware.Timeout(routeTimeout)) srv.router.Use(middleware.Timeout(routeTimeout))
@@ -44,7 +45,7 @@ func (srv *Server) SetupRoutes() {
} }
// Health check. // Health check.
srv.router.With(srv.mw.CORS()).Get( srv.router.Get(
"/.well-known/healthcheck.json", "/.well-known/healthcheck.json",
srv.handlers.HandleHealthCheck(), srv.handlers.HandleHealthCheck(),
) )
@@ -68,7 +69,7 @@ func (srv *Server) SetupRoutes() {
} }
func (srv *Server) setupAPIv1(router chi.Router) { func (srv *Server) setupAPIv1(router chi.Router) {
router.With(srv.mw.CORS()).Get( router.Get(
"/server", "/server",
srv.handlers.HandleServerInfo(), srv.handlers.HandleServerInfo(),
) )
+15 -42
View File
@@ -6,7 +6,6 @@ package server_test
import ( import (
"fmt" "fmt"
"maps"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -190,11 +189,11 @@ func TestServeAfterStopDoesNotStopApp(t *testing.T) {
} }
} }
// TestCORSHeaders checks the Access-Control-Allow-* headers on the // TestCORSAllowsAnyOriginWithoutCredentials checks that the
// answers to requests from another origin. The public, read-only // responses to a request from another origin and to a preflight
// routes answer with Access-Control-Allow-Origin: * alone. Routes // both carry Access-Control-Allow-Origin: *, never the request's
// that need the cookie, and a preflight to one, answer with none. // origin, and no Access-Control-Allow-Credentials.
func TestCORSHeaders(t *testing.T) { func TestCORSAllowsAnyOriginWithoutCredentials(t *testing.T) {
var srv *server.Server var srv *server.Server
startApp(t, fx.Populate(&srv)) startApp(t, fx.Populate(&srv))
@@ -202,36 +201,15 @@ func TestCORSHeaders(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
method string method string
path string
requestMethod string requestMethod string
wantHeaders map[string]string
}{ }{
{ {
name: "server information", name: "request",
method: http.MethodGet, method: http.MethodGet,
path: "/api/v1/server",
wantHeaders: map[string]string{"Access-Control-Allow-Origin": "*"},
}, },
{ {
name: "health check", name: "preflight",
method: http.MethodGet,
path: "/.well-known/healthcheck.json",
wantHeaders: map[string]string{"Access-Control-Allow-Origin": "*"},
},
{
name: "send",
method: http.MethodPost,
path: "/api/v1/messages",
},
{
name: "state",
method: http.MethodGet,
path: "/api/v1/state",
},
{
name: "preflight for send",
method: http.MethodOptions, method: http.MethodOptions,
path: "/api/v1/messages",
requestMethod: http.MethodPost, requestMethod: http.MethodPost,
}, },
} }
@@ -240,7 +218,7 @@ func TestCORSHeaders(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
request := httptest.NewRequestWithContext( request := httptest.NewRequestWithContext(
t.Context(), test.method, t.Context(), test.method,
"http://chat.example.com"+test.path, nil, "http://chat.example.com/api/v1/server", nil,
) )
request.Header.Set("Origin", "http://blog.example.com") request.Header.Set("Origin", "http://blog.example.com")
@@ -254,20 +232,15 @@ func TestCORSHeaders(t *testing.T) {
srv.ServeHTTP(recorder, request) srv.ServeHTTP(recorder, request)
gotHeaders := map[string]string{} for header, want := range map[string]string{
"Access-Control-Allow-Origin": "*",
for name := range recorder.Header() { "Access-Control-Allow-Credentials": "",
if strings.HasPrefix(name, "Access-Control-Allow-") { } {
gotHeaders[name] = recorder.Header().Get(name) got := recorder.Header().Get(header)
if got != want {
t.Errorf("%s is %q, want %q", header, got, want)
} }
} }
if !maps.Equal(gotHeaders, test.wantHeaders) {
t.Errorf(
"Access-Control-Allow-* headers are %v, want %v",
gotHeaders, test.wantHeaders,
)
}
}) })
} }
} }