Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/pkg/handler/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var errAdminUnauthorized = errors.New("admin authorization failed")
// CheckAdminAuth checks if the request is authorized to perform admin actions.
// On failure it writes the 401 JSON body AND returns a non-nil error so the
// caller can bail out without touching any state.
func (h *handler) CheckAdminAuth(ctx *fasthttp.RequestCtx) error {
func (h *Handler) CheckAdminAuth(ctx *fasthttp.RequestCtx) error {
authCode, err := base64.StdEncoding.DecodeString(string(ctx.Request.Header.Peek("Authorization")))
if err != nil {
log.Error().Err(fmt.Errorf("error decoding authorization code: %w", err)).Send()
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/claim_hub_for_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
// "hub id already exists", any other error -> 500 "create hub error".
// Returns (nil, false) whenever a response has already been written and the
// caller must stop; (hub, true) on success.
func (h *handler) claimHubForCreate(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string, isPermanent bool) (hub.Hub, bool) {
func (h *Handler) claimHubForCreate(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string, isPermanent bool) (hub.Hub, bool) {
hubMetadata := string(ctx.QueryArgs().Peek("hubMetadata"))
newHub, err, rejected := h.claimUserChosenHubId(ctx, hubId, h.siblingInstances(zh),
func() (hub.Hub, error) {
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/create_hub_by_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
// exactly one wins and the rest get 409. Random-hub callers pass a fresh
// uuid that cannot collide, so the 409 branch is unreachable there — the
// shared path just stays safe.
func (h *handler) CreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error {
func (h *Handler) CreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error {
// Static callers pass the `id` param verbatim; random-hub callers pass
// a generated uuid. The shared validation helper rejects an
// empty/whitespace id and oversized params before any hub state is
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/create_hub_permanent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
// migration endpoints) on a random local port so requests land in fasthttp
// worker goroutines, exactly like production. This is what a real unauthenticated
// WebSocket client would hit.
func startStaticCreateTestServer(t *testing.T, h *handler) string {
func startStaticCreateTestServer(t *testing.T, h *Handler) string {
t.Helper()

requestHandler := func(ctx *fasthttp.RequestCtx) {
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/create_hub_random.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

// CreateHubRandom creates a new hub with a random ID.
func (h *handler) CreateHubRandom(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
func (h *Handler) CreateHubRandom(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
if h.isMigrating.Load() {
return h.ForwardMigrate(ctx)
}
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/create_static_hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
// create goes through the atomic CreateHubIfAbsent primitive, so
// concurrent requests for the same ID never orphan a hub: exactly one wins
// and the rest get 409.
func (h *handler) CreateStaticHub(ctx *fasthttp.RequestCtx) error {
func (h *Handler) CreateStaticHub(ctx *fasthttp.RequestCtx) error {
// Auth runs before the migration check so an unauthenticated request is
// answered with 401 instead of a WebSocket close whose reason is the
// internal backup host. No state is mutated between the two checks, so
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/get_hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

// GetHub returns the hub with the given ID.
func (h *handler) GetHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
func (h *Handler) GetHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
hubId := string(ctx.QueryArgs().Peek("id"))
// Reject a missing/empty ID up front with 400 for consistency with the
// other hub endpoints.
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/get_hub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
// startGetHubTestServer serves the plain-HTTP hub-metadata read endpoint on a
// random local port, mirroring the routing in handler.go:
// /v1/random-hubs/get against the random instance.
func startGetHubTestServer(t *testing.T, h *handler) string {
func startGetHubTestServer(t *testing.T, h *Handler) string {
t.Helper()

requestHandler := func(ctx *fasthttp.RequestCtx) {
Expand Down
29 changes: 11 additions & 18 deletions server/pkg/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,12 @@ import (
"github.com/valyala/fasthttp"
)

// Handler is the entrypoint contract for the signaling server. It exposes
// the HTTP route set documented in the package comment
// Handler is the HTTP handler for the signaling server. It exposes the
// HTTP route set documented in the package comment
// (/v1/status, /v1/admin/migrate, /v1/static-hubs/{create,join},
// /v1/random-hubs/{create,get,join}, /v1/ip-hubs/join-or-create). The
// per-route handlers live on the unexported handler type and are wired
// inside Serve.
type Handler interface {
// Serve starts the fasthttp server on the configured address.
Serve() error
}

// handler implements the Handler interface.
type handler struct {
// per-route handlers are wired inside Serve.
type Handler struct {
// address is the address to listen on.
address string
// clientSecret is the client secret to use for authentication.
Expand Down Expand Up @@ -132,14 +125,14 @@ type handler struct {
// idleTimeout / pingInterval return the effective probe timings, falling
// back to the config defaults when the handler was built by NewHandler
// (which leaves the fields at zero).
func (h *handler) idleTimeout() time.Duration {
func (h *Handler) idleTimeout() time.Duration {
if h.wsIdleTimeout > 0 {
return h.wsIdleTimeout
}
return config.WSIdleTimeout
}

func (h *handler) pingInterval() time.Duration {
func (h *Handler) pingInterval() time.Duration {
if h.wsPingInterval > 0 {
return h.wsPingInterval
}
Expand All @@ -151,12 +144,12 @@ func (h *handler) pingInterval() time.Duration {
return config.WSIdleTimeout / 4
}

// NewHandler create a new handler
func NewHandler(cfg *config.Config, zeroHubStatic zerohub.ZeroHub, zeroHubRandom zerohub.ZeroHub, zeroHubIP zerohub.ZeroHub) (Handler, error) {
// NewHandler creates a new Handler.
func NewHandler(cfg *config.Config, zeroHubStatic zerohub.ZeroHub, zeroHubRandom zerohub.ZeroHub, zeroHubIP zerohub.ZeroHub) (*Handler, error) {
if cfg.App.ClientSecret == "" {
return nil, fmt.Errorf("APP_CLIENT_SECRET must not be empty: an empty secret would leave admin endpoints open to unauthenticated requests")
}
return &handler{
return &Handler{
address: fmt.Sprintf("%s:%s", cfg.App.Host, cfg.App.Port),
clientSecret: cfg.App.ClientSecret,
trustProxy: cfg.App.TrustProxy,
Expand Down Expand Up @@ -186,7 +179,7 @@ func NewHandler(cfg *config.Config, zeroHubStatic zerohub.ZeroHub, zeroHubRandom
// SECURITY: safe only behind a proxy that strips or replaces
// X-Forwarded-For; in front of an untrusted hop any client could forge a
// fresh hub IP per request.
func (h *handler) clientIP(ctx *fasthttp.RequestCtx) string {
func (h *Handler) clientIP(ctx *fasthttp.RequestCtx) string {
if h.trustProxy {
if ip := ipFromForwardedHeader(ctx); ip != "" {
return ip
Expand Down Expand Up @@ -240,7 +233,7 @@ func ipFromForwardedHeader(ctx *fasthttp.RequestCtx) string {
return ip.String()
}

func (h *handler) Serve() error {
func (h *Handler) Serve() error {
rateLimitMiddleware := newRateLimitMiddleware(h.trustProxy)

requestHandler := func(ctx *fasthttp.RequestCtx) {
Expand Down
4 changes: 2 additions & 2 deletions server/pkg/handler/hub_id_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestCreateStaticHubRejectsEmptyHubId(t *testing.T) {
ctrl := gomock.NewController(t)
staticMock := zerohub.NewMockZeroHub(ctrl)
// No expectations: the 400 must be written before CreateHubIfAbsent.
h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}
h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=")
ctx.Request.Header.Set("Authorization", adminAuthHeader())
Expand All @@ -44,7 +44,7 @@ func TestCreateStaticHubRejectsEmptyHubId(t *testing.T) {
func TestCreateStaticHubAuthPrecedenceOverInvalidId(t *testing.T) {
ctrl := gomock.NewController(t)
staticMock := zerohub.NewMockZeroHub(ctrl)
h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}
h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create")
// No Authorization header.
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/join_hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

// JoinHub joins an existing hub with the given ID.
func (h *handler) JoinHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
func (h *Handler) JoinHub(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
hubId := string(ctx.QueryArgs().Peek("id"))
// Reject a missing/empty ID up front with 400 for consistency: before
// this, such a request degraded to 404 (or a migration forward).
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/join_or_create_hub_by_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
// JoinOrCreateHubByID joins an existing hub with the given ID or creates a new one if it does not exist.
// The get-or-create is atomic at the ZeroHub layer, so concurrent join-or-create
// calls for the same ID always land in the same hub.
func (h *handler) JoinOrCreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error {
func (h *Handler) JoinOrCreateHubByID(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub, hubId string) error {
// Static callers pass the `id` param verbatim; IP-hub callers pass a
// generated FNV hash. The shared validation helper rejects an
// empty/whitespace id and oversized params before any hub state is
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/join_or_create_hub_ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func fnvHash64a(s string) string {
// connections from one client IP share a hub; that is intentionally
// different from the rate limiter, which keys by the full socket address
// (IP:port) so each connection gets its own DoS budget. See clientIP.
func (h *handler) JoinOrCreateHubIP(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
func (h *Handler) JoinOrCreateHubIP(ctx *fasthttp.RequestCtx, zh zerohub.ZeroHub) error {
if h.isMigrating.Load() {
return h.ForwardMigrate(ctx)
}
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/join_or_create_hub_ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func captureHubKey(t *testing.T, got *string) zerohub.ZeroHub {
// joinOrCreateHubIPRequest assembles a handler-level request with the given
// socket peer address and optional X-Forwarded-For value, then invokes
// JoinOrCreateHubIP on it, returning the hub ID the handler derived.
func joinOrCreateHubIPRequest(t *testing.T, h *handler, got *string, socketIP, xff string) string {
func joinOrCreateHubIPRequest(t *testing.T, h *Handler, got *string, socketIP, xff string) string {
t.Helper()

ctx := &fasthttp.RequestCtx{}
Expand Down
4 changes: 2 additions & 2 deletions server/pkg/handler/metadata_size_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func TestCreateStaticHubRejectsOversizedHubMetadata(t *testing.T) {
ctrl := gomock.NewController(t)
staticMock := zerohub.NewMockZeroHub(ctrl)
// No expectations: the 413 must be written before any hub-state access.
h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}
h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=static-hub&hubMetadata=" + oversizedValue)
ctx.Request.Header.Set("Authorization", adminAuthHeader())
Expand Down Expand Up @@ -181,7 +181,7 @@ func TestOversizedIdRejected(t *testing.T) {
staticMock := zerohub.NewMockZeroHub(ctrl)
// The 413 for the oversized id must win over the cross-mode
// collision guard, so zeroHubRandom can stay nil.
h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}
h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=" + oversizedID)
ctx.Request.Header.Set("Authorization", adminAuthHeader())
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/metadata_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func TestCreateStaticHubRejectsMalformedHubMetadata(t *testing.T) {
staticMock := zerohub.NewMockZeroHub(ctrl)
// No expectations: the 400 for malformed metadata must be written
// before any hub-state access (CreateHubIfAbsent).
h := &handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}
h := &Handler{clientSecret: testClientSecret, zeroHubStatic: staticMock}

ctx := newRequestCtx("http://127.0.0.1/v1/static-hubs/create?id=static-hub&hubMetadata=not-json")
ctx.Request.Header.Set("Authorization", adminAuthHeader())
Expand Down
8 changes: 4 additions & 4 deletions server/pkg/handler/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
// 4. Wait until no hub left.
// 5. Graceful shutdown.
// 6. redeploy the new version of server.
func (h *handler) Migrate(ctx *fasthttp.RequestCtx) error {
func (h *Handler) Migrate(ctx *fasthttp.RequestCtx) error {
if err := h.CheckAdminAuth(ctx); err != nil {
return err
}
Expand Down Expand Up @@ -57,7 +57,7 @@ func (h *handler) Migrate(ctx *fasthttp.RequestCtx) error {
return nil
}

func (h *handler) ForwardMigrate(ctx *fasthttp.RequestCtx) error {
func (h *Handler) ForwardMigrate(ctx *fasthttp.RequestCtx) error {
backupHost := h.getBackupHost()

// The 301 status is not working on multi library following the rfc6455
Expand Down Expand Up @@ -109,14 +109,14 @@ func (h *handler) ForwardMigrate(ctx *fasthttp.RequestCtx) error {
// attempting an upgrade would fail the handshake and surface as a 503
// "websocket handshake". Plain-HTTP handlers must return this response
// instead and must never call ForwardMigrate.
func (h *handler) migrateHTTPResponse(ctx *fasthttp.RequestCtx) error {
func (h *Handler) migrateHTTPResponse(ctx *fasthttp.RequestCtx) error {
return h.Response(ctx, fasthttp.StatusMovedPermanently,
map[string]string{"status": "migrating", "backupHost": h.getBackupHost()})
}

// getBackupHost returns the current backup host under a read lock so it is
// safe to read concurrently with Migrate.
func (h *handler) getBackupHost() string {
func (h *Handler) getBackupHost() string {
h.migrateMu.RLock()
defer h.migrateMu.RUnlock()
return h.backupHost
Expand Down
6 changes: 3 additions & 3 deletions server/pkg/handler/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ const (

// newTestHandler builds a handler with a known client secret, matching how
// handler.go constructs the handler from the config's client secret.
func newTestHandler() *handler {
return &handler{clientSecret: testClientSecret}
func newTestHandler() *Handler {
return &Handler{clientSecret: testClientSecret}
}

// adminAuthHeader returns the base64-encoded admin authorization header value.
Expand All @@ -33,7 +33,7 @@ func adminAuthHeader() string {
// startTestServer serves the handler's real migration endpoints on a random
// local port. Requests therefore land in fasthttp worker goroutines, exactly
// like production, which is what the regression test below hammers.
func startTestServer(t *testing.T, h *handler) string {
func startTestServer(t *testing.T, h *Handler) string {
t.Helper()

requestHandler := func(ctx *fasthttp.RequestCtx) {
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

// Response is a helper function to write a JSON response to the client.
func (h *handler) Response(ctx *fasthttp.RequestCtx, statusCode int, body interface{}) error {
func (h *Handler) Response(ctx *fasthttp.RequestCtx, statusCode int, body interface{}) error {
data, err := json.Marshal(body)
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
Expand Down
2 changes: 1 addition & 1 deletion server/pkg/handler/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
// anti-pattern, and is unnecessary here since the endpoint is open to all
// origins anyway. The exposed data (status + backupHost) is considered
// public.
func (h *handler) Status(ctx *fasthttp.RequestCtx) error {
func (h *Handler) Status(ctx *fasthttp.RequestCtx) error {
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
ctx.Response.Header.Add("Vary", "Origin")

Expand Down
Loading
Loading