round9-hub: add device id to --access-log lines (and make the auth ctx comment true)

- ctxKey/deviceKey *string holder pattern; AccessLogMiddleware allocates holder, injects into ctx, logs devID (or "-" for anon) as final field
- auth now sets the holder after resolving deviceID — comment updated to match reality
- TestAccessLogDeviceID: healthz logs "-", authed /v1/head logs the real device id; captures global log.Writer()
This commit is contained in:
shoemoney 2026-06-30 18:06:02 -05:00
parent 7688330fdf
commit e05f4da87d
2 changed files with 68 additions and 6 deletions

View file

@ -3,6 +3,7 @@
package hub
import (
"context"
"compress/gzip"
"crypto/ed25519"
"crypto/rand"
@ -37,6 +38,11 @@ const (
maxJSONBytes = 8 << 20 // any JSON control request
)
// ctxKey is the unexported key type for per-request context values set by this package.
type ctxKey int
const deviceKey ctxKey = iota // *string holder; auth writes deviceID; AccessLogMiddleware reads it
// Server is the devbox hub: metadata in db, blob bytes in store, change events
// fanned out via broker.
type Server struct {
@ -132,8 +138,9 @@ func (s *Server) handleReadyz(w http.ResponseWriter, _ *http.Request) {
}
// auth wraps a handler, requiring a valid "Authorization: Bearer <tok>" that
// resolves to a non-revoked device. The device id is stashed in the request
// context for the wrapped handler.
// resolves to a non-revoked device. When AccessLogMiddleware is in the outer
// chain it records the resolved device id via the *string holder stored under
// deviceKey in the request context.
func (s *Server) auth(next func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
const prefix = "Bearer "
@ -151,6 +158,9 @@ func (s *Server) auth(next func(http.ResponseWriter, *http.Request, string)) htt
writeErr(w, http.StatusUnauthorized, "invalid bearer token")
return
}
if holder, ok := r.Context().Value(deviceKey).(*string); ok {
*holder = deviceID
}
next(w, r, deviceID)
}
}
@ -756,14 +766,20 @@ func (lw *loggingResponseWriter) Write(b []byte) (int, error) {
}
// AccessLogMiddleware wraps h and logs one line per request via stdlib log:
// method, path, status, bytes, remote addr, duration. Default off; enabled by
// the --access-log serve flag.
// method, path, status, bytes, remote addr, duration, device id ("-" for
// anonymous). Default off; enabled by the --access-log serve flag.
func AccessLogMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
dev := new(string)
r = r.WithContext(context.WithValue(r.Context(), deviceKey, dev))
lw := &loggingResponseWriter{ResponseWriter: w, status: http.StatusOK}
h.ServeHTTP(lw, r)
log.Printf("%s %s %d %d %s %s",
r.Method, r.URL.Path, lw.status, lw.bytes, r.RemoteAddr, time.Since(start))
devID := *dev
if devID == "" {
devID = "-"
}
log.Printf("%s %s %d %d %s %s %s",
r.Method, r.URL.Path, lw.status, lw.bytes, r.RemoteAddr, time.Since(start), devID)
})
}

View file

@ -7,6 +7,7 @@ import (
"crypto/rand"
"encoding/json"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
@ -676,3 +677,48 @@ func TestAccessLogMiddleware(t *testing.T) {
t.Fatalf("body = %q, want 'hello'", got)
}
}
// TestAccessLogDeviceID verifies that AccessLogMiddleware includes the device id in
// the log line for authenticated requests, and "-" for anonymous ones like /healthz.
func TestAccessLogDeviceID(t *testing.T) {
db, err := meta.Open(":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
store, err := blobstore.NewDisk(t.TempDir())
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
old := log.Writer()
log.SetOutput(&buf)
t.Cleanup(func() { log.SetOutput(old) })
srv := httptest.NewServer(AccessLogMiddleware(NewServer(db, store).Handler()))
defer srv.Close()
// Anonymous request → device field must be "-".
buf.Reset()
if st, _ := do(t, "GET", srv.URL+"/healthz", "", nil); st != http.StatusOK {
t.Fatalf("healthz = %d", st)
}
if line := buf.String(); !strings.HasSuffix(strings.TrimRight(line, "\n"), " -") {
t.Fatalf("anonymous log line missing '-' sentinel: %q", line)
}
// Authenticated request → device id must appear in log line.
if err := db.CreateToken(HashToken("logtok"), time.Now().Unix()+3600); err != nil {
t.Fatal(err)
}
join := joinWith(t, srv.URL, "logtok")
buf.Reset()
// GET /v1/head goes through auth, so the device id is resolved and set.
if st, _ := do(t, "GET", srv.URL+proto.PathHead+"?share=x", join.Bearer, nil); st != http.StatusOK {
t.Fatalf("head = %d", st)
}
if !strings.Contains(buf.String(), join.DeviceID) {
t.Fatalf("authed log line missing device id %q: %q", join.DeviceID, buf.String())
}
}