feat(gateway,ui): client-version gate — turn away too-old builds
Introduce a minimum-supported-client gate so a future incompatible wire change can turn away installed builds too old to speak it, cleanly, instead of letting them crash on decode. It rides the outermost stable layer (an HTTP header), never the FlatBuffers payload. Gateway: - New internal/clientver: dependency-free parse + compare of the leading MAJOR.MINOR.PATCH (a git-describe suffix is tolerated). - GATEWAY_MIN_CLIENT_VERSION config (empty => gate dormant; validated at load). - connectsrv checks the X-Client-Version header before decoding the payload: Execute returns result_code="update_required" (before the registry lookup), Subscribe returns FailedPrecondition. It fails open on an absent or garbled header — the header is a client-controlled compatibility signal, not an access control. Client: - Attach X-Client-Version on every call. - A terminal update.svelte.ts store + a non-dismissable UpdateOverlay (native opens VITE_STORE_URL, web reloads); retry.ts maps FailedPrecondition to the update_required sentinel; a mock __update hook drives the e2e. Wire-additive and contour-safe: no FBS/proto regen, no schema migration; the gate stays dormant until GATEWAY_MIN_CLIENT_VERSION is deliberately set, so web / VK / Telegram behaviour is unchanged. The silent reconciliation seam is deferred to the offline-first work (its only caller). Tests: Go clientver/config/connectsrv gate tests, retry.test.ts, Playwright update.spec.ts.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
// Package clientver parses and compares the leading MAJOR.MINOR.PATCH of a client
|
||||
// version string so the edge can turn away a build too old to speak the current wire
|
||||
// contract. It is deliberately dependency-free and tolerant: the version rides an HTTP
|
||||
// header (X-Client-Version) that a build stamps from `git describe --tags`, so any
|
||||
// `-N-gSHA` or `+meta` suffix is ignored, and anything unparseable is reported as such
|
||||
// (the caller fails open — an absent or garbled header is never treated as too old).
|
||||
package clientver
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Version is a parsed semantic version triple. Only MAJOR.MINOR.PATCH participate in the
|
||||
// ordering; any pre-release or build suffix is dropped at parse time.
|
||||
type Version struct {
|
||||
Major, Minor, Patch int
|
||||
}
|
||||
|
||||
// Parse extracts the leading MAJOR.MINOR.PATCH from s, tolerating an optional leading
|
||||
// "v" and any `-N-gSHA` or `+meta` suffix (as produced by `git describe --tags`). It
|
||||
// reports ok=false when s has fewer than three numeric components or any component is not
|
||||
// an integer, so the caller can distinguish a real version from a dev/empty string.
|
||||
func Parse(s string) (Version, bool) {
|
||||
s = strings.TrimPrefix(strings.TrimSpace(s), "v")
|
||||
if i := strings.IndexAny(s, "-+"); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
p := strings.SplitN(s, ".", 4)
|
||||
if len(p) < 3 {
|
||||
return Version{}, false
|
||||
}
|
||||
var v Version
|
||||
var err error
|
||||
if v.Major, err = strconv.Atoi(p[0]); err != nil {
|
||||
return Version{}, false
|
||||
}
|
||||
if v.Minor, err = strconv.Atoi(p[1]); err != nil {
|
||||
return Version{}, false
|
||||
}
|
||||
if v.Patch, err = strconv.Atoi(p[2]); err != nil {
|
||||
return Version{}, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// Less reports whether a orders before b by MAJOR, then MINOR, then PATCH. Equal versions
|
||||
// are not Less than each other, so a client exactly at the minimum passes the gate.
|
||||
func Less(a, b Version) bool {
|
||||
if a.Major != b.Major {
|
||||
return a.Major < b.Major
|
||||
}
|
||||
if a.Minor != b.Minor {
|
||||
return a.Minor < b.Minor
|
||||
}
|
||||
return a.Patch < b.Patch
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package clientver
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestParse covers the version strings the edge actually sees: a plain and a "v"-prefixed
|
||||
// triple, a `git describe --tags` suffix, build metadata, surrounding space, and the
|
||||
// non-version strings (dev/empty/too-few/non-numeric) that must report ok=false so the
|
||||
// gate fails open.
|
||||
func TestParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want Version
|
||||
wantK bool
|
||||
}{
|
||||
{"plain", "1.16.0", Version{1, 16, 0}, true},
|
||||
{"v-prefixed", "v1.16.0", Version{1, 16, 0}, true},
|
||||
{"git describe suffix", "v1.16.0-3-gabc1234", Version{1, 16, 0}, true},
|
||||
{"build metadata", "1.16.0+ci42", Version{1, 16, 0}, true},
|
||||
{"surrounding space", " v2.0.1 ", Version{2, 0, 1}, true},
|
||||
{"extra component ignored", "v1.16.0.4", Version{1, 16, 0}, true},
|
||||
{"dev", "dev", Version{}, false},
|
||||
{"empty", "", Version{}, false},
|
||||
{"too few components", "1.16", Version{}, false},
|
||||
{"non-numeric patch", "1.16.x", Version{}, false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, ok := Parse(tc.in)
|
||||
if ok != tc.wantK {
|
||||
t.Fatalf("Parse(%q) ok = %v, want %v", tc.in, ok, tc.wantK)
|
||||
}
|
||||
if ok && got != tc.want {
|
||||
t.Errorf("Parse(%q) = %+v, want %+v", tc.in, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLess covers the ordering by MAJOR, then MINOR, then PATCH, and that an equal version
|
||||
// is not Less (a client exactly at the minimum passes the gate).
|
||||
func TestLess(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
a, b Version
|
||||
want bool
|
||||
}{
|
||||
{"equal", Version{1, 16, 0}, Version{1, 16, 0}, false},
|
||||
{"major less", Version{1, 9, 9}, Version{2, 0, 0}, true},
|
||||
{"major greater", Version{2, 0, 0}, Version{1, 9, 9}, false},
|
||||
{"minor less", Version{1, 16, 5}, Version{1, 17, 0}, true},
|
||||
{"minor greater", Version{1, 17, 0}, Version{1, 16, 9}, false},
|
||||
{"patch less", Version{1, 16, 0}, Version{1, 16, 1}, true},
|
||||
{"patch greater", Version{1, 16, 2}, Version{1, 16, 1}, false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := Less(tc.a, tc.b); got != tc.want {
|
||||
t.Errorf("Less(%+v, %+v) = %v, want %v", tc.a, tc.b, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"scrabble/gateway/internal/clientver"
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
)
|
||||
|
||||
@@ -54,6 +55,11 @@ type Config struct {
|
||||
// MaxBodyBytes caps one inbound request body on the public listener and one
|
||||
// Connect message read; oversized requests are refused without buffering.
|
||||
MaxBodyBytes int
|
||||
// MinClientVersion, when non-empty, is the lowest client version (MAJOR.MINOR.PATCH)
|
||||
// the edge serves. A client reporting an older X-Client-Version is turned away with an
|
||||
// "update required" signal before its payload is decoded. Empty leaves the gate dormant
|
||||
// (every client is served) — the default for web-only deployments.
|
||||
MinClientVersion string
|
||||
// RateLimit configures the in-memory anti-abuse limiter.
|
||||
RateLimit RateLimitConfig
|
||||
// Abuse configures the temporary IP ban and the honeytoken (prod-only).
|
||||
@@ -226,14 +232,15 @@ func (c VKIDConfig) Enabled() bool {
|
||||
func Load() (Config, error) {
|
||||
var err error
|
||||
c := Config{
|
||||
HTTPAddr: envOr("GATEWAY_HTTP_ADDR", defaultHTTPAddr),
|
||||
LogLevel: envOr("GATEWAY_LOG_LEVEL", defaultLogLevel),
|
||||
BackendHTTPURL: envOr("GATEWAY_BACKEND_HTTP_URL", defaultBackendHTTPURL),
|
||||
BackendGRPCAddr: envOr("GATEWAY_BACKEND_GRPC_ADDR", defaultBackendGRPCAddr),
|
||||
AdminUser: os.Getenv("GATEWAY_ADMIN_USER"),
|
||||
AdminPassword: os.Getenv("GATEWAY_ADMIN_PASSWORD"),
|
||||
ValidatorAddr: os.Getenv("GATEWAY_VALIDATOR_ADDR"),
|
||||
VKAppSecret: os.Getenv("GATEWAY_VK_APP_SECRET"),
|
||||
HTTPAddr: envOr("GATEWAY_HTTP_ADDR", defaultHTTPAddr),
|
||||
LogLevel: envOr("GATEWAY_LOG_LEVEL", defaultLogLevel),
|
||||
BackendHTTPURL: envOr("GATEWAY_BACKEND_HTTP_URL", defaultBackendHTTPURL),
|
||||
BackendGRPCAddr: envOr("GATEWAY_BACKEND_GRPC_ADDR", defaultBackendGRPCAddr),
|
||||
AdminUser: os.Getenv("GATEWAY_ADMIN_USER"),
|
||||
AdminPassword: os.Getenv("GATEWAY_ADMIN_PASSWORD"),
|
||||
ValidatorAddr: os.Getenv("GATEWAY_VALIDATOR_ADDR"),
|
||||
VKAppSecret: os.Getenv("GATEWAY_VK_APP_SECRET"),
|
||||
MinClientVersion: os.Getenv("GATEWAY_MIN_CLIENT_VERSION"),
|
||||
VKID: VKIDConfig{
|
||||
AppID: os.Getenv("GATEWAY_VK_ID_APP_ID"),
|
||||
ClientSecret: os.Getenv("GATEWAY_VK_ID_CLIENT_SECRET"),
|
||||
@@ -332,6 +339,11 @@ func (c Config) validate() error {
|
||||
if c.MaxBodyBytes <= 0 {
|
||||
return fmt.Errorf("config: GATEWAY_MAX_BODY_BYTES must be positive")
|
||||
}
|
||||
if c.MinClientVersion != "" {
|
||||
if _, ok := clientver.Parse(c.MinClientVersion); !ok {
|
||||
return fmt.Errorf("config: GATEWAY_MIN_CLIENT_VERSION %q is not a MAJOR.MINOR.PATCH version", c.MinClientVersion)
|
||||
}
|
||||
}
|
||||
if c.Abuse.BanEnabled && (c.Abuse.BanThreshold <= 0 || c.Abuse.BanWindow <= 0 || c.Abuse.BanDuration <= 0) {
|
||||
return fmt.Errorf("config: GATEWAY_ABUSE_BAN_THRESHOLD/_WINDOW/_DURATION must be positive when GATEWAY_ABUSE_BAN_ENABLED")
|
||||
}
|
||||
|
||||
@@ -47,6 +47,29 @@ func TestLoadMaxBodyBytes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadMinClientVersion verifies the client-version gate config: dormant (empty) by
|
||||
// default, a parseable version accepted, and an unparseable one rejected.
|
||||
func TestLoadMinClientVersion(t *testing.T) {
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if c.MinClientVersion != "" {
|
||||
t.Errorf("MinClientVersion = %q, want empty (gate dormant)", c.MinClientVersion)
|
||||
}
|
||||
t.Setenv("GATEWAY_MIN_CLIENT_VERSION", "v1.16.0")
|
||||
if c, err = Load(); err != nil {
|
||||
t.Fatalf("Load with a valid min version: %v", err)
|
||||
}
|
||||
if c.MinClientVersion != "v1.16.0" {
|
||||
t.Errorf("MinClientVersion = %q, want %q", c.MinClientVersion, "v1.16.0")
|
||||
}
|
||||
t.Setenv("GATEWAY_MIN_CLIENT_VERSION", "dev")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load: expected an error for an unparseable GATEWAY_MIN_CLIENT_VERSION, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadAbuseDefaults verifies the anti-abuse ban defaults: disabled (prod-only),
|
||||
// the agreed thresholds, and no honeytoken.
|
||||
func TestLoadAbuseDefaults(t *testing.T) {
|
||||
|
||||
@@ -12,6 +12,7 @@ var (
|
||||
errInternal = errors.New("internal error")
|
||||
errMissingToken = errors.New("missing session token")
|
||||
errInvalidSession = errors.New("invalid or expired session")
|
||||
errUpdateRequired = errors.New("client too old, update required")
|
||||
)
|
||||
|
||||
// errUnknownMessageType reports an unregistered message type.
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"golang.org/x/net/http2/h2c"
|
||||
|
||||
"scrabble/gateway/internal/backendclient"
|
||||
"scrabble/gateway/internal/clientver"
|
||||
"scrabble/gateway/internal/config"
|
||||
"scrabble/gateway/internal/push"
|
||||
"scrabble/gateway/internal/ratelimit"
|
||||
@@ -46,6 +47,16 @@ const heartbeatKind = "heartbeat"
|
||||
// spoofer, so trusting it is safe.
|
||||
const honeypotHeader = "X-Scrabble-Honeypot"
|
||||
|
||||
// clientVersionHeader carries the client build version (stamped from `git describe --tags`) so
|
||||
// the edge can turn away a build too old to speak the current wire contract, before it decodes
|
||||
// the payload. resultUpdateRequired is the stable envelope result_code — with the Subscribe
|
||||
// counterpart connect.CodeFailedPrecondition — that any build, however old, recognises as
|
||||
// "you must update". Both are part of the frozen wire contract (docs/ARCHITECTURE.md §2).
|
||||
const (
|
||||
clientVersionHeader = "X-Client-Version"
|
||||
resultUpdateRequired = "update_required"
|
||||
)
|
||||
|
||||
// Limiter classes, the `class` attribute of gateway_rate_limited_total and the
|
||||
// class field of the periodic rejection report.
|
||||
const (
|
||||
@@ -88,6 +99,11 @@ type Server struct {
|
||||
|
||||
maxBodyBytes int
|
||||
|
||||
// minClient is the lowest client version served; gateOn is false when the gate is dormant
|
||||
// (GATEWAY_MIN_CLIENT_VERSION empty or unparseable).
|
||||
minClient clientver.Version
|
||||
gateOn bool
|
||||
|
||||
publicPolicy ratelimit.Policy
|
||||
userPolicy ratelimit.Policy
|
||||
emailPolicy ratelimit.Policy
|
||||
@@ -128,6 +144,10 @@ type Deps struct {
|
||||
// MaxBodyBytes caps one inbound request body and one Connect message read;
|
||||
// zero or negative selects config.DefaultMaxBodyBytes.
|
||||
MaxBodyBytes int
|
||||
// MinClientVersion is the lowest client version (MAJOR.MINOR.PATCH) the edge serves; an
|
||||
// older X-Client-Version is turned away with "update required". Empty or unparseable leaves
|
||||
// the gate dormant.
|
||||
MinClientVersion string
|
||||
}
|
||||
|
||||
// NewServer constructs the edge service.
|
||||
@@ -160,6 +180,18 @@ func NewServer(d Deps) *Server {
|
||||
if rl == (config.RateLimitConfig{}) {
|
||||
rl = config.DefaultRateLimit()
|
||||
}
|
||||
// Parse the minimum client version once. Config.validate already rejects an unparseable
|
||||
// value, so the warn branch only guards a direct (test) construction; an empty value leaves
|
||||
// the gate dormant.
|
||||
var minClient clientver.Version
|
||||
gateOn := false
|
||||
if d.MinClientVersion != "" {
|
||||
if v, ok := clientver.Parse(d.MinClientVersion); ok {
|
||||
minClient, gateOn = v, true
|
||||
} else {
|
||||
log.Warn("ignoring unparseable MinClientVersion; client-version gate disabled", zap.String("value", d.MinClientVersion))
|
||||
}
|
||||
}
|
||||
return &Server{
|
||||
registry: d.Registry,
|
||||
sessions: d.Sessions,
|
||||
@@ -176,6 +208,8 @@ func NewServer(d Deps) *Server {
|
||||
adminProxy: d.AdminProxy,
|
||||
metrics: newServerMetrics(d.Meter, blocklist),
|
||||
maxBodyBytes: maxBody,
|
||||
minClient: minClient,
|
||||
gateOn: gateOn,
|
||||
publicPolicy: ratelimit.PerMinute(rl.PublicPerMinute, rl.PublicBurst),
|
||||
userPolicy: ratelimit.PerMinute(rl.UserPerMinute, rl.UserBurst),
|
||||
emailPolicy: ratelimit.Per(rl.EmailPer10Min, 10*time.Minute, rl.EmailBurst),
|
||||
@@ -285,6 +319,22 @@ func (s *Server) abuseGuard(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// clientTooOld reports whether the X-Client-Version header names a version below the configured
|
||||
// minimum. It fails open: with the gate dormant, or an absent or unparseable header, it returns
|
||||
// false. The header is a client-controlled compatibility signal, not an access control (it is
|
||||
// trivially spoofable), so a missing or garbled value — an old build predating the header, or a
|
||||
// non-browser caller — must never be blocked spuriously.
|
||||
func (s *Server) clientTooOld(header string) bool {
|
||||
if !s.gateOn {
|
||||
return false
|
||||
}
|
||||
v, ok := clientver.Parse(header)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return clientver.Less(v, s.minClient)
|
||||
}
|
||||
|
||||
// Execute runs one unary operation. Domain failures are returned in the envelope
|
||||
// (result_code != "ok", HTTP 200); only edge failures (rate limit, missing
|
||||
// session, unknown type, internal) become Connect errors.
|
||||
@@ -294,6 +344,17 @@ func (s *Server) Execute(ctx context.Context, req *connect.Request[edgev1.Execut
|
||||
result := "internal"
|
||||
defer func() { s.metrics.recordEdge(ctx, msgType, result, start) }()
|
||||
|
||||
// The version gate rides the outermost stable layer (an HTTP header) and is checked before
|
||||
// the payload is decoded, so a too-old client makes zero successful calls but sees the
|
||||
// recognizable update_required envelope rather than a decode crash (docs/ARCHITECTURE.md §2).
|
||||
if s.clientTooOld(req.Header().Get(clientVersionHeader)) {
|
||||
result = resultUpdateRequired
|
||||
return connect.NewResponse(&edgev1.ExecuteResponse{
|
||||
RequestId: req.Msg.GetRequestId(),
|
||||
ResultCode: resultUpdateRequired,
|
||||
}), nil
|
||||
}
|
||||
|
||||
op, ok := s.registry.Lookup(msgType)
|
||||
if !ok {
|
||||
result = "unknown_type"
|
||||
@@ -363,6 +424,11 @@ func (s *Server) Execute(ctx context.Context, req *connect.Request[edgev1.Execut
|
||||
// Subscribe streams the authenticated user's live events with a keep-alive
|
||||
// heartbeat until the client disconnects.
|
||||
func (s *Server) Subscribe(ctx context.Context, req *connect.Request[edgev1.SubscribeRequest], stream *connect.ServerStream[edgev1.Event]) error {
|
||||
// A stream carries no result_code, so a too-old client is refused with the Connect
|
||||
// FailedPrecondition counterpart of the update_required sentinel.
|
||||
if s.clientTooOld(req.Header().Get(clientVersionHeader)) {
|
||||
return connect.NewError(connect.CodeFailedPrecondition, errUpdateRequired)
|
||||
}
|
||||
uid, _, _, err := s.resolve(ctx, req.Header(), peerIP(req.Peer().Addr, req.Header()))
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -22,8 +22,13 @@ import (
|
||||
)
|
||||
|
||||
// newEdge wires a connectsrv.Server over a fake backend and returns a Connect
|
||||
// client plus a cleanup func.
|
||||
// client plus a cleanup func. The client-version gate is off.
|
||||
func newEdge(t *testing.T, backendHandler http.HandlerFunc) (edgev1connect.GatewayClient, func()) {
|
||||
return newEdgeMin(t, "", backendHandler)
|
||||
}
|
||||
|
||||
// newEdgeMin is newEdge with the client-version gate armed at minVersion (empty leaves it off).
|
||||
func newEdgeMin(t *testing.T, minVersion string, backendHandler http.HandlerFunc) (edgev1connect.GatewayClient, func()) {
|
||||
t.Helper()
|
||||
backendSrv := httptest.NewServer(backendHandler)
|
||||
backend, err := backendclient.New(backendSrv.URL, "localhost:9090", 2*time.Second)
|
||||
@@ -31,12 +36,13 @@ func newEdge(t *testing.T, backendHandler http.HandlerFunc) (edgev1connect.Gatew
|
||||
t.Fatalf("backendclient: %v", err)
|
||||
}
|
||||
edge := connectsrv.NewServer(connectsrv.Deps{
|
||||
Registry: transcode.NewRegistry(backend, nil),
|
||||
Sessions: session.NewCache(backend, time.Minute, 100),
|
||||
Limiter: ratelimit.New(),
|
||||
Hub: push.NewHub(0),
|
||||
RateLimit: config.DefaultRateLimit(),
|
||||
Heartbeat: 15 * time.Second,
|
||||
Registry: transcode.NewRegistry(backend, nil),
|
||||
Sessions: session.NewCache(backend, time.Minute, 100),
|
||||
Limiter: ratelimit.New(),
|
||||
Hub: push.NewHub(0),
|
||||
RateLimit: config.DefaultRateLimit(),
|
||||
Heartbeat: 15 * time.Second,
|
||||
MinClientVersion: minVersion,
|
||||
})
|
||||
edgeSrv := httptest.NewServer(edge.HTTPHandler())
|
||||
client := edgev1connect.NewGatewayClient(http.DefaultClient, edgeSrv.URL)
|
||||
@@ -108,6 +114,84 @@ func TestExecuteGuestGate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecuteVersionGate verifies the client-version gate on the unary path: a build older
|
||||
// than the configured minimum is turned away with the update_required result code before the
|
||||
// registry lookup (an unknown message type is gated too, proving the short-circuit), while an
|
||||
// equal, newer, absent, or unparseable version passes; and the gate is dormant when unset.
|
||||
func TestExecuteVersionGate(t *testing.T) {
|
||||
// The backend answers auth.guest with a session; a gated call never reaches it.
|
||||
backend := func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"token":"tok","user_id":"u-1","is_guest":true,"display_name":"Guest"}`))
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
min string
|
||||
header string
|
||||
msgType string
|
||||
want string
|
||||
}{
|
||||
{"too old is gated before lookup", "v1.16.0", "v1.0.0", "bogus.unknown", "update_required"},
|
||||
{"equal passes", "v1.16.0", "v1.16.0", transcode.MsgAuthGuest, "ok"},
|
||||
{"newer passes", "v1.16.0", "v2.0.0", transcode.MsgAuthGuest, "ok"},
|
||||
{"absent header fails open", "v1.16.0", "", transcode.MsgAuthGuest, "ok"},
|
||||
{"unparseable header fails open", "v1.16.0", "dev", transcode.MsgAuthGuest, "ok"},
|
||||
{"gate dormant when unset", "", "v1.0.0", transcode.MsgAuthGuest, "ok"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client, cleanup := newEdgeMin(t, tc.min, backend)
|
||||
defer cleanup()
|
||||
req := connect.NewRequest(&edgev1.ExecuteRequest{MessageType: tc.msgType, RequestId: "rq"})
|
||||
if tc.header != "" {
|
||||
req.Header().Set("X-Client-Version", tc.header)
|
||||
}
|
||||
resp, err := client.Execute(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
if got := resp.Msg.GetResultCode(); got != tc.want {
|
||||
t.Fatalf("result_code = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubscribeVersionGate verifies the streaming path: a too-old client is refused with
|
||||
// FailedPrecondition, while an equal or absent version is admitted and proceeds to auth (which
|
||||
// fails Unauthenticated with no session, proving it passed the version gate).
|
||||
func TestSubscribeVersionGate(t *testing.T) {
|
||||
noBackend := func(_ http.ResponseWriter, _ *http.Request) {}
|
||||
tests := []struct {
|
||||
name string
|
||||
min string
|
||||
header string
|
||||
want connect.Code
|
||||
}{
|
||||
{"too old refused", "v1.16.0", "v1.0.0", connect.CodeFailedPrecondition},
|
||||
{"equal admitted then auth-gated", "v1.16.0", "v1.16.0", connect.CodeUnauthenticated},
|
||||
{"gate dormant admits", "", "v1.0.0", connect.CodeUnauthenticated},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client, cleanup := newEdgeMin(t, tc.min, noBackend)
|
||||
defer cleanup()
|
||||
req := connect.NewRequest(&edgev1.SubscribeRequest{})
|
||||
if tc.header != "" {
|
||||
req.Header().Set("X-Client-Version", tc.header)
|
||||
}
|
||||
stream, err := client.Subscribe(context.Background(), req)
|
||||
if err == nil {
|
||||
for stream.Receive() {
|
||||
}
|
||||
err = stream.Err()
|
||||
}
|
||||
if got := connect.CodeOf(err); got != tc.want {
|
||||
t.Fatalf("code = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteAuthedRequiresSession(t *testing.T) {
|
||||
client, cleanup := newEdge(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("backend must not be called without a session")
|
||||
|
||||
Reference in New Issue
Block a user