Add --access-log <path> (env ZDDC_ACCESS_LOG). When set, every access- log record is written as a JSON line to the configured file in addition to the existing slog.Default() stderr output. Empty (default) keeps the prior behavior — stderr only. Rotation via gopkg.in/natefinch/lumberjack.v2: 100 MB per file, 10 backups, 90-day max age, gzip rotated files. Operator usage (e.g. behind a Caddy/quadlet stack): zddc-server --access-log /srv/.zddc.d/logs/access.log ... Architecture: AccessLogMiddleware now takes an optional *slog.Logger. main.go wires it via setupAccessAuditLog() which builds a slog.JSONHandler over a lumberjack rotator. Stderr emission stays via slog.Default(); the audit logger gets the same fields in line-delimited JSON, the format every standard log shipper (Vector, Loki, fluentbit, journalbeat) parses natively. Tests cover the audit logger receiving the same email/path/status fields as the stderr stream.
121 lines
3.8 KiB
Go
121 lines
3.8 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
|
|
"log/slog"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
// EmailKey is the context key for the authenticated user's email.
|
|
const EmailKey contextKey = "email"
|
|
|
|
// ACLMiddleware extracts the user email from the configured header and stores
|
|
// it in the request context. It does NOT enforce ACL itself — each handler
|
|
// performs its own ACL check via zddc.EffectivePolicy / zddc.AllowedWithChain.
|
|
func ACLMiddleware(cfg config.Config, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
email := r.Header.Get(cfg.EmailHeader)
|
|
// DEBUG-level header dump for diagnosing proxy / SSO header
|
|
// passthrough. Off by default (LogLevel info); enable with
|
|
// ZDDC_LOG_LEVEL=debug. Logs the configured header name, the
|
|
// observed value at that name, and the full request header
|
|
// map so an operator can see exactly what reached the binary.
|
|
// Note: at debug level this also captures auth tokens, cookies,
|
|
// and anything else upstream proxies forward — only enable in
|
|
// trusted environments.
|
|
slog.Debug("request headers",
|
|
"configured", cfg.EmailHeader,
|
|
"observed", email,
|
|
"headers", r.Header)
|
|
ctx := context.WithValue(r.Context(), EmailKey, email)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// EmailFromContext extracts the user email from the request context.
|
|
func EmailFromContext(r *http.Request) string {
|
|
if v, ok := r.Context().Value(EmailKey).(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// responseWriter wraps http.ResponseWriter to capture status code and bytes written.
|
|
type responseWriter struct {
|
|
http.ResponseWriter
|
|
status int
|
|
bytes int
|
|
wrote bool
|
|
}
|
|
|
|
// WriteHeader records the status code and writes it to the underlying ResponseWriter.
|
|
func (rw *responseWriter) WriteHeader(code int) {
|
|
rw.status = code
|
|
rw.wrote = true
|
|
rw.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
// Write records the bytes written and writes to the underlying ResponseWriter.
|
|
func (rw *responseWriter) Write(b []byte) (int, error) {
|
|
n, err := rw.ResponseWriter.Write(b)
|
|
rw.bytes += n
|
|
return n, err
|
|
}
|
|
|
|
// AccessLogMiddleware logs a structured line per HTTP request after the
|
|
// response is written.
|
|
//
|
|
// Always emits to slog.Default() (stderr) so server-lifecycle logs and
|
|
// access logs share an output stream by default.
|
|
//
|
|
// If `auditLogger` is non-nil, the same structured fields are also written
|
|
// to it. The intended caller wires up auditLogger with a JSON handler
|
|
// pointing at a rotating file (see cmd/zddc-server's setupAccessAuditLog),
|
|
// so an operator gets a persisted audit trail on disk in addition to the
|
|
// stderr stream — useful when stderr is not journald-captured (e.g.
|
|
// container logging where the orchestrator drops stderr after restarts).
|
|
func AccessLogMiddleware(auditLogger *slog.Logger, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Capture request start time
|
|
start := time.Now()
|
|
|
|
// Wrap the ResponseWriter
|
|
wrapped := &responseWriter{ResponseWriter: w, status: 200}
|
|
|
|
// Serve the request
|
|
next.ServeHTTP(wrapped, r)
|
|
|
|
// Calculate duration
|
|
durationMs := int(time.Since(start).Milliseconds())
|
|
|
|
// Get email from context
|
|
email := EmailFromContext(r)
|
|
if email == "" {
|
|
email = "anonymous"
|
|
}
|
|
|
|
args := []any{
|
|
"ts", start.Format(time.RFC3339),
|
|
"email", email,
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", wrapped.status,
|
|
"bytes", wrapped.bytes,
|
|
"duration_ms", durationMs,
|
|
}
|
|
|
|
// Stderr stream (existing behavior).
|
|
slog.Info("access", args...)
|
|
|
|
// Audit file (when configured). Same fields, separate handler so
|
|
// the file can be JSON-formatted regardless of stderr's handler.
|
|
if auditLogger != nil {
|
|
auditLogger.Info("access", args...)
|
|
}
|
|
})
|
|
}
|