Files
John T SkarbekandClaude Sonnet 5.5 c484ad2be4 fix: keep the provisioner key secret out of request paths and logs (#32532)
Linear: [PLE-94](https://linear.app/codercom/issue/PLE-94). One of three
independent PRs split out of the original masking change.

## Root cause
`codersdk.Client.GetProvisionerKey` sent the real provisioner key secret
in the URL path (`/api/v2/provisionerkeys/<key>`) as well as in the
`Coder-Provisioner-Daemon-Key` header. The path ends up in proxy/access
logs, the server request logger (`path`, `params_provisionerkey`) and
the SDK's `sdk request` debug log. The server ignores the path value:
the route uses `ExtractProvisionerDaemonAuthenticated` and
`fetchProvisionerKey` returns the header-authenticated key. Nothing
reads `{provisionerkey}` on that route (`ExtractProvisionerKeyParam` is
only mounted on the org-scoped route, where the value is a key name).

## Fix
- The SDK now sends a fixed placeholder segment,
`/api/v2/provisionerkeys/me`; the secret travels only in the header. Old
servers ignore the path, and old clients still work with new servers.
- `loggermw` masks the `provisionerkey` route param (keeping at most a 4
character prefix) in `params_*` and `path` as a backstop for old
clients. It only applies when the route pattern is the top-level
`/provisionerkeys/{provisionerkey}`; the org-scoped
`/organizations/{organization}/provisionerkeys/{provisionerkey}` carries
a key name and is left alone.
- Swagger annotation and generated docs now describe the path param as
an ignored placeholder (edited by hand, not via `make gen`).

Sibling PRs (independent, disjoint files):
- https://github.com/coder/coder/pull/32526
- https://github.com/coder/coder/pull/32533

## Follow-ups not included
- AI Gateway prompt, tool and thought content logged in
`aibridgedserver.go` (~511-613) and `aibridge/recorder/log_recorder.go`
- `rich_parameter_values` in `runner.go` (~443)
- Proxy `response_body` in `aibridgeproxyd.go` (~1102)
- Terraform `TF_LOG` output relayed to logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 08:11:09 -05:00

229 lines
6.2 KiB
Go

package loggermw
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/tracing"
)
var (
safeParams = []string{"page", "limit", "offset", "path"}
countParams = []string{"ids", "template_ids"}
)
// provisionerKeyRoute carries the provisioner key itself in the URL path, which
// was a mistake. The org-scoped route, /api/v2/organizations/{organization}/
// provisionerkeys/{provisionerkey}, carries only a key name and is not masked.
const provisionerKeyRoute = "/api/v2/provisionerkeys/{provisionerkey}"
// maskSecret keeps at most a 4 character prefix of s, enough to identify a
// token without disclosing it.
func maskSecret(s string) string {
if len(s) <= 8 {
return "..."
}
return s[:4] + "..."
}
func safeQueryParams(params url.Values) []slog.Field {
if len(params) == 0 {
return nil
}
fields := make([]slog.Field, 0, len(params))
for key, values := range params {
// Check if this parameter should be included
for _, pattern := range safeParams {
if strings.EqualFold(key, pattern) {
// Prepend query parameters in the log line to ensure we don't have issues with collisions
// in case any other internal logging fields already log fields with similar names
fieldName := "query_" + key
// Log the actual values for non-sensitive parameters
if len(values) == 1 {
fields = append(fields, slog.F(fieldName, values[0]))
continue
}
fields = append(fields, slog.F(fieldName, values))
}
}
// Some query params we just want to log the count of the params length
for _, pattern := range countParams {
if !strings.EqualFold(key, pattern) {
continue
}
count := 0
// Prepend query parameters in the log line to ensure we don't have issues with collisions
// in case any other internal logging fields already log fields with similar names
fieldName := "query_" + key
// Count comma-separated values for CSV format
for _, v := range values {
if strings.Contains(v, ",") {
count += len(strings.Split(v, ","))
continue
}
count++
}
// For logging we always want strings
fields = append(fields, slog.F(fieldName+"_count", strconv.Itoa(count)))
}
}
return fields
}
func Logger(log slog.Logger, hostResolver func(*http.Request) string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
start := time.Now()
sw, ok := rw.(*tracing.StatusWriter)
if !ok {
panic(fmt.Sprintf("ResponseWriter not a *tracing.StatusWriter; got %T", rw))
}
host := r.Host
if hostResolver != nil {
host = hostResolver(r)
}
httplog := log.With(
slog.F("user_agent", r.Header.Get("User-Agent")),
slog.F("host", host),
slog.F("received_host", r.Host),
slog.F("proto", r.Proto),
slog.F("remote_addr", r.RemoteAddr),
// Include the start timestamp in the log so that we have the
// source of truth. There is at least a theoretical chance that
// there can be a delay between `next.ServeHTTP` ending and us
// actually logging the request. This can also be useful when
// filtering logs that started at a certain time (compared to
// trying to compute the value).
slog.F("start", start),
)
// Add safe query parameters to the log
if queryFields := safeQueryParams(r.URL.Query()); len(queryFields) > 0 {
httplog = httplog.With(queryFields...)
}
logContext := NewRequestLogger(httplog, r.Method, r.URL.Path, start)
ctx := WithRequestLogger(r.Context(), logContext)
next.ServeHTTP(sw, r.WithContext(ctx))
// Don't log successful health check requests.
if r.URL.Path == "/api/v2" && sw.Status == http.StatusOK {
return
}
// For status codes 500 and higher we
// want to log the response body.
if sw.Status >= http.StatusInternalServerError {
logContext.WithFields(
slog.F("response_body", string(sw.ResponseBody())),
)
}
logContext.WriteLog(r.Context(), sw.Status)
})
}
}
type SlogRequestLogger struct {
log slog.Logger
written bool
path string
message string
start time.Time
addFields func()
}
func (c *SlogRequestLogger) WithFields(fields ...slog.Field) {
c.log = c.log.With(fields...)
}
func (c *SlogRequestLogger) WriteLog(ctx context.Context, status int) {
if c.written {
return
}
c.written = true
end := time.Now()
if c.addFields != nil {
c.addFields()
}
logger := c.log.With(
slog.F("took", end.Sub(c.start)),
slog.F("status_code", status),
slog.F("latency_ms", float64(end.Sub(c.start)/time.Millisecond)),
)
path := c.path
// If the request is routed, add the route parameters to the log.
if chiCtx := chi.RouteContext(ctx); chiCtx != nil {
urlParams := chiCtx.URLParams
routeParamsFields := make([]slog.Field, 0, len(urlParams.Keys))
for k, v := range urlParams.Keys {
val := urlParams.Values[k]
if val == "" {
continue
}
if chiCtx.RoutePattern() == provisionerKeyRoute && v == "provisionerkey" {
masked := maskSecret(val)
path = strings.ReplaceAll(path, val, masked)
val = masked
}
routeParamsFields = append(routeParamsFields, slog.F("params_"+v, val))
}
if len(routeParamsFields) > 0 {
logger = logger.With(routeParamsFields...)
}
}
if path != "" {
logger = logger.With(slog.F("path", path))
}
// We already capture most of this information in the span (minus
// the response body which we don't want to capture anyways).
tracing.RunWithoutSpan(ctx, func(ctx context.Context) {
// We should not log at level ERROR for 5xx status codes because 5xx
// includes proxy errors etc. It also causes slogtest to fail
// instantly without an error message by default.
if status >= http.StatusInternalServerError {
logger.Warn(ctx, c.message)
} else {
logger.Debug(ctx, c.message)
}
})
}
type logContextKey struct{}
func WithRequestLogger(ctx context.Context, rl RequestLogger) context.Context {
return context.WithValue(ctx, logContextKey{}, rl)
}
func RequestLoggerFromContext(ctx context.Context) RequestLogger {
val := ctx.Value(logContextKey{})
if logCtx, ok := val.(RequestLogger); ok {
return logCtx
}
return nil
}