caddyhttp: ignore case when matching hosts in logger_names (#8176)

* caddyhttp: ignore case when matching hosts in logger_names
* caddyhttp: test case-insensitive logger_names through App.Provision
* caddyhttp: test case-insensitive logger_names in integration harness

(cherry picked from commit 7910dd94ee)
This commit is contained in:
tbshfr 2026-10-09 23:15:23 +02:00 committed by Francis Lavoie
parent d3fb27644c
commit 4c3e75075b
No known key found for this signature in database
4 changed files with 192 additions and 0 deletions

View file

@ -0,0 +1,109 @@
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package integration
import (
"bufio"
"bytes"
"encoding/json"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/caddyserver/caddy/v2/caddytest"
)
// TestLoggerNamesCaseInsensitive loads a config whose logger_names key is
// mixed-case and asserts that a request with a differently-cased Host is
// written by the configured named logger.
func TestLoggerNamesCaseInsensitive(t *testing.T) {
logFile := filepath.Join(t.TempDir(), "access.log")
logFileJSON, err := json.Marshal(logFile)
if err != nil {
t.Fatal(err)
}
tester := caddytest.NewTester(t)
// Load a config without the file logger on cleanup so the log file is
// closed before t.TempDir removes it; Windows cant delete open files.
t.Cleanup(func() {
tester.InitServer(`{"admin": {"listen": "localhost:2999"}}`, "json")
})
// The config is JSON because the Caddyfile adapter already lowercases
// site addresses, so it would never produce a mixed-case key.
tester.InitServer(`{
"admin": {"listen": "localhost:2999"},
"logging": {
"logs": {
"mixed": {
"writer": {"output": "file", "filename": `+string(logFileJSON)+`},
"encoder": {"format": "json"},
"include": ["http.log.access.mixed"]
}
}
},
"apps": {
"http": {
"http_port": 9080,
"grace_period": 1,
"servers": {
"srv0": {
"listen": [":9080"],
"routes": [
{"handle": [{"handler": "static_response", "body": "ok"}]}
],
"logs": {
"logger_names": {"Mixed.Example.org": ["mixed"]}
}
}
}
}
}
}`, "json")
req, err := http.NewRequest(http.MethodGet, "http://localhost:9080/", nil)
if err != nil {
t.Fatal(err)
}
req.Host = "MIXED.example.org"
tester.AssertResponse(req, http.StatusOK, "ok")
// the access log entry is written after the response, so poll for it
var logs []byte
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
logs, err = os.ReadFile(logFile)
if err != nil {
continue
}
scanner := bufio.NewScanner(bytes.NewReader(logs))
for scanner.Scan() {
var entry struct {
Logger string `json:"logger"`
Request struct {
Host string `json:"host"`
} `json:"request"`
}
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
continue
}
if entry.Logger == "http.log.access.mixed" && entry.Request.Host == "MIXED.example.org" {
return
}
}
}
t.Errorf("no access log entry from logger %q for host %q, got %q", "http.log.access.mixed", "MIXED.example.org", logs)
}

View file

@ -242,6 +242,7 @@ func (app *App) Provision(ctx caddy.Context) error {
// only enable access logs if configured
if srv.Logs != nil {
srv.Logs.normalizeLoggerNames()
srv.accessLogger = app.logger.Named("log.access")
if srv.Logs.Trace {
srv.traceLogger = app.logger.Named("log.trace")

View file

@ -19,8 +19,10 @@ import (
"encoding/json"
"errors"
"log/slog"
"maps"
"net"
"net/http"
"slices"
"strings"
"sync"
@ -133,6 +135,9 @@ func (slc ServerLogConfig) wrapLogger(logger *zap.Logger, req *http.Request) []*
}
func (slc ServerLogConfig) getLoggerHosts(host string) []string {
// hostnames are case insensitive, keys were lowercased during provisioning
host = strings.ToLower(host)
// try the exact hostname first
if hosts, ok := slc.LoggerNames[host]; ok {
return hosts
@ -154,6 +159,29 @@ func (slc ServerLogConfig) getLoggerHosts(host string) []string {
return []string{slc.DefaultLoggerName}
}
// normalizeLoggerNames lowercases the hostname keys of LoggerNames
// because hostnames are case-insensitive. When two keys differ only
// by case, their logger names are merged
func (slc *ServerLogConfig) normalizeLoggerNames() {
if len(slc.LoggerNames) == 0 {
return
}
normalized := make(map[string]StringArray, len(slc.LoggerNames))
// iterate in sorted order so merged logger names are deterministic
for _, host := range slices.Sorted(maps.Keys(slc.LoggerNames)) {
lowerHost := strings.ToLower(host)
merged := normalized[lowerHost]
for _, name := range slc.LoggerNames[host] {
if !slices.Contains(merged, name) {
merged = append(merged, name)
}
}
// keep empty mappings, they disable logging for the host
normalized[lowerHost] = merged
}
slc.LoggerNames = normalized
}
func (slc *ServerLogConfig) clone() *ServerLogConfig {
clone := &ServerLogConfig{
DefaultLoggerName: slc.DefaultLoggerName,

View file

@ -0,0 +1,54 @@
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package caddyhttp
import (
"slices"
"testing"
)
func TestServerLogConfigLoggerNamesCaseInsensitive(t *testing.T) {
slc := ServerLogConfig{
DefaultLoggerName: "default",
LoggerNames: map[string]StringArray{
"example.com": {"exact"},
"Mixed.Example.org": {"mixed"},
"*.EXAMPLE.net": {"wildcard"},
"foo.example.dev": {"lower"},
"FOO.example.dev": {"upper", "lower"},
"muted.example.com": {},
},
}
slc.normalizeLoggerNames()
for i, tc := range []struct {
host string
expected []string
}{
{host: "EXAMPLE.COM", expected: []string{"exact"}},
{host: "mixed.example.org", expected: []string{"mixed"}},
{host: "Sub.example.NET", expected: []string{"wildcard"}},
// merged in sorted key order; "FOO..." sorts before "foo..."
{host: "foo.example.dev", expected: []string{"upper", "lower"}},
// mapped to no loggers, so no fallback to the default logger,
// an empty mapping can only come from a JSON config
{host: "MUTED.example.com", expected: []string{}},
} {
actual := slc.getLoggerHosts(tc.host)
if !slices.Equal(actual, tc.expected) {
t.Errorf("Test %d (%s): expected %v, got %v", i, tc.host, tc.expected, actual)
}
}
}