diff --git a/internal/hub/server.go b/internal/hub/server.go index b5d782e..2915480 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -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 " 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) }) } diff --git a/internal/hub/server_test.go b/internal/hub/server_test.go index 4d0e6af..6137d3f 100644 --- a/internal/hub/server_test.go +++ b/internal/hub/server_test.go @@ -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()) + } +}