refactor: remove httpStatus dupes, dead defaultBPS code, obvious comments, nil-guard relay

C1: Replace local httpStatus* constants with net/http in registry service C2: Extract formatDuration/formatLastSeen as package functions C3: Remove obvious doc comments from MetadataOption With* functions C4: Nil-guard bpsManager in EstablishRelayWithBPS C5: Remove dead defaultBPS field, SetDefaultBPS, GetDefaultBPS, and -lease-bps CLI flag (was never consulted by GetBucket)

cognitive committed Mar 5, 2026 at 03:58 UTC 8ff029a994f44193dd88b9f65bccbd729c7b6d5d
11 files changed +87 -89
.pre-commit-config.yaml
+16
@@ -27,6 +27,22 @@ repos:
27 entry: golangci-lint config verify
28 files: '\.golangci\.(?:yml|yaml|toml|json)'
29 language: golang
30 + - id: golangci-lint
31 + name: golangci-lint
32 + description: Fast linters runner for Go. Note that only modified files are linted, so linters like 'unused' that need to scan all files won't work as expected.
33 + entry: golangci-lint run --new-from-rev HEAD --fix
34 + types: [go]
35 + language: golang
36 + require_serial: true
37 + pass_filenames: false
38 + - id: golangci-lint-full
39 + name: golangci-lint-full
40 + description: Fast linters runner for Go. Runs on all files in the module. Use this hook if you use pre-commit in CI.
41 + entry: golangci-lint run --fix
42 + types: [go]
43 + language: golang
44 + require_serial: true
45 + pass_filenames: false
46
47 - repo: local
48 hooks:
cmd/demo-app/static/index.html
+1 -1
@@ -128,4 +128,4 @@
128 </script>
129 </body>
130
131 -</html>
\ No newline at end of file
131 +</html>
cmd/relay-server/admin.go
+2 -2
@@ -15,8 +15,8 @@ type Admin struct {
15 handler *portaladmin.Handler
16 }
17
18 -func NewAdmin(defaultLeaseBPS int64, frontend *Frontend, authManager *policy.Authenticator, portalURL string, trustProxy bool) *Admin {
19 - service := portaladmin.NewService(defaultLeaseBPS, authManager)
18 +func NewAdmin(frontend *Frontend, authManager *policy.Authenticator, portalURL string, trustProxy bool) *Admin {
19 + service := portaladmin.NewService(authManager)
20 normalizedPortalURL := strings.TrimSpace(portalURL)
21 admin := &Admin{
22 service: service,
cmd/relay-server/main.go
+1 -3
@@ -35,7 +35,6 @@ type relayServerConfig struct {
35 CloudflareToken string
36 Bootstraps []string
37 AdminPort int
38 - LeaseBPS int
38 SNIPort int
39 TrustProxyHeaders bool
40 }
@@ -65,7 +64,6 @@ func main() {
64
65 flag.IntVar(&cfg.AdminPort, "adminport", defaultAPIPort, "Admin/HTTP server port")
66 flag.StringVar(&cfg.AdminSecretKey, "admin-secret-key", adminSecretKey, "admin auth secret (env: ADMIN_SECRET_KEY)")
68 - flag.IntVar(&cfg.LeaseBPS, "lease-bps", 0, "bytes-per-second limit per lease (0=unlimited)")
67 flag.StringVar(&cfg.PortalURL, "portal-url", portalURL, "portal base URL (env: PORTAL_URL)")
68 flag.BoolVar(&cfg.TrustProxyHeaders, "trust-proxy-headers", trustProxyHeaders, "trust X-Forwarded-* and X-Real-IP headers (env: TRUST_PROXY_HEADERS)")
69 flag.StringVar(&cfg.TrustedProxyCIDRs, "trusted-proxy-cidrs", trustedProxyCIDRs, "trusted proxy CIDR allowlist for forwarded headers, comma-separated (env: TRUSTED_PROXY_CIDRS)")
@@ -107,7 +105,7 @@ func runServer(cfg relayServerConfig) error {
105
106 frontend := NewFrontend(cfg.PortalURL)
107 authManager := policy.NewAuthenticator(cfg.AdminSecretKey)
110 - admin := NewAdmin(int64(cfg.LeaseBPS), frontend, authManager, cfg.PortalURL, cfg.TrustProxyHeaders)
108 + admin := NewAdmin(frontend, authManager, cfg.PortalURL, cfg.TrustProxyHeaders)
109 frontend.SetAdmin(admin)
110
111 // Load persisted admin settings (ban list, BPS limits, IP bans)
cmd/relay-server/utils.go
+4 -4
@@ -109,7 +109,7 @@ type leaseRow struct {
109 }
110
111 // formatDuration formats a duration for TTL display.
112 -func (leaseRow) formatDuration(d time.Duration) string {
112 +func formatDuration(d time.Duration) string {
113 if d <= 0 {
114 return ""
115 }
@@ -123,7 +123,7 @@ func (leaseRow) formatDuration(d time.Duration) string {
123 }
124
125 // formatLastSeen formats a duration since last seen.
126 -func (leaseRow) formatLastSeen(d time.Duration) string {
126 +func formatLastSeen(d time.Duration) string {
127 if d >= time.Hour {
128 h := int(d / time.Hour)
129 m := int((d % time.Hour) / time.Minute)
@@ -189,10 +189,10 @@ func (r *leaseRow) fromLeaseEntry(entry *types.LeaseEntry, admin *Admin, portalU
189 r.Kind = kind
190 r.Connected = connected
191 r.DNS = dnsLabel
192 - r.LastSeen = r.formatLastSeen(since)
192 + r.LastSeen = formatLastSeen(since)
193 r.LastSeenISO = entry.LastSeen.UTC().Format(time.RFC3339)
194 r.FirstSeenISO = entry.FirstSeen.UTC().Format(time.RFC3339)
195 - r.TTL = r.formatDuration(time.Until(entry.Expires))
195 + r.TTL = formatDuration(time.Until(entry.Expires))
196 linkLabel := identityID
197 if normalized, ok := types.NormalizeServiceName(lease.Name); ok {
198 linkLabel = normalized
portal/admin/handler_test.go
+4 -4
@@ -13,7 +13,7 @@ import (
13 )
14
15 func TestHandleAdminRequestLoginSuccessSetsSessionCookie(t *testing.T) {
16 - service := NewService(0, policy.NewAuthenticator("test-secret"))
16 + service := NewService(policy.NewAuthenticator("test-secret"))
17 handler := newTestHandler(t, service, true, nil)
18
19 req := httptest.NewRequest(http.MethodPost, types.PathAdminPrefix+"/login", strings.NewReader(`{"key":"test-secret"}`))
@@ -53,7 +53,7 @@ func TestHandleAdminRequestLoginSuccessSetsSessionCookie(t *testing.T) {
53 }
54
55 func TestHandleAdminRequestProtectedRouteUnauthorized(t *testing.T) {
56 - service := NewService(0, policy.NewAuthenticator("test-secret"))
56 + service := NewService(policy.NewAuthenticator("test-secret"))
57 handler := newTestHandler(t, service, false, func(_ *portal.RelayServer) any {
58 t.Fatalf("list leases should not be called for unauthorized request")
59 return nil
@@ -74,7 +74,7 @@ func TestHandleAdminRequestProtectedRouteUnauthorized(t *testing.T) {
74 }
75
76 func TestHandleAdminRequestApprovalModeInvalidMode(t *testing.T) {
77 - service := NewService(0, policy.NewAuthenticator("test-secret"))
77 + service := NewService(policy.NewAuthenticator("test-secret"))
78 handler := newTestHandler(t, service, false, nil)
79 token := service.GetAuthManager().CreateSession()
80
@@ -94,7 +94,7 @@ func TestHandleAdminRequestApprovalModeInvalidMode(t *testing.T) {
94 }
95
96 func TestHandleAdminRequestLeaseActionInvalidLeaseID(t *testing.T) {
97 - service := NewService(0, policy.NewAuthenticator("test-secret"))
97 + service := NewService(policy.NewAuthenticator("test-secret"))
98 handler := newTestHandler(t, service, false, nil)
99 token := service.GetAuthManager().CreateSession()
100
portal/admin/service.go
+1 -4
@@ -35,11 +35,8 @@ type settings struct {
35 BannedIPs []string `json:"banned_ips,omitempty"`
36 }
37
38 -func NewService(defaultLeaseBPS int64, authManager *policy.Authenticator) *Service {
38 +func NewService(authManager *policy.Authenticator) *Service {
39 bpsManager := policy.NewRateLimiter()
40 - if defaultLeaseBPS > 0 {
41 - bpsManager.SetDefaultBPS(defaultLeaseBPS)
42 - }
40
41 return &Service{
42 settingsPath: "admin_settings.json",
portal/admin/service_test.go
+2 -2
@@ -11,7 +11,7 @@ import (
11 )
12
13 func TestServiceSaveLoadSettingsRoundTrip(t *testing.T) {
14 - service := NewService(0, policy.NewAuthenticator("test-secret"))
14 + service := NewService(policy.NewAuthenticator("test-secret"))
15 settingsPath := filepath.Join(t.TempDir(), "admin_settings.json")
16 service.SetSettingsPath(settingsPath)
17
@@ -28,7 +28,7 @@ func TestServiceSaveLoadSettingsRoundTrip(t *testing.T) {
28 service.SaveSettings(sourceServer)
29
30 targetServer := mustNewTestRelayServer(t)
31 - loaded := NewService(0, policy.NewAuthenticator("test-secret"))
31 + loaded := NewService(policy.NewAuthenticator("test-secret"))
32 loaded.SetSettingsPath(settingsPath)
33 loaded.LoadSettings(targetServer)
34
portal/policy/rate_limiter.go
+38 -38
@@ -15,7 +15,6 @@ import (
15 type RateLimiter struct {
16 bpsLimits map[string]int64
17 bpsBuckets map[string]*Bucket
18 - defaultBPS int64
18 mu sync.Mutex
19 }
20
@@ -24,7 +23,6 @@ func NewRateLimiter() *RateLimiter {
23 return &RateLimiter{
24 bpsLimits: make(map[string]int64),
25 bpsBuckets: make(map[string]*Bucket),
27 - defaultBPS: 0,
26 }
27 }
28
@@ -61,23 +59,6 @@ func (m *RateLimiter) GetAllBPSLimits() map[string]int64 {
59 return result
60 }
61
64 -// SetDefaultBPS sets the default BPS limit for new leases.
65 -func (m *RateLimiter) SetDefaultBPS(bps int64) {
66 - m.mu.Lock()
67 - defer m.mu.Unlock()
68 - if bps < 0 {
69 - bps = 0
70 - }
71 - m.defaultBPS = bps
72 -}
73 -
74 -// GetDefaultBPS returns the default BPS limit.
75 -func (m *RateLimiter) GetDefaultBPS() int64 {
76 - m.mu.Lock()
77 - defer m.mu.Unlock()
78 - return m.defaultBPS
79 -}
80 -
62 // GetBucket returns a rate limit bucket for a lease, creating one if needed.
63 func (m *RateLimiter) GetBucket(leaseID string) *Bucket {
64 m.mu.Lock()
@@ -119,10 +100,8 @@ func (m *RateLimiter) Copy(dst io.Writer, src io.Reader, leaseID string) (int64,
100 // EstablishRelayWithBPS sets up bidirectional relay with BPS limiting.
101 // In the new TLS passthrough architecture, this uses net.Conn.
102 func EstablishRelayWithBPS(clientConn, leaseConn net.Conn, leaseID string, bpsManager *RateLimiter) {
122 - bpsLimit := bpsManager.GetBPSLimit(leaseID)
103 log.Info().
104 Str("lease_id", leaseID).
125 - Int64("bps_limit", bpsLimit).
105 Msg("[Relay] Starting relay connection")
106
107 defer func() {
@@ -134,23 +113,44 @@ func EstablishRelayWithBPS(clientConn, leaseConn net.Conn, leaseID string, bpsMa
113 var wg sync.WaitGroup
114 wg.Add(2)
115
137 - // Client -> Lease
138 - go func() {
139 - defer wg.Done()
140 - _, _ = bpsManager.Copy(leaseConn, clientConn, leaseID)
141 - if err := leaseConn.Close(); err != nil {
142 - log.Debug().Err(err).Str("lease_id", leaseID).Msg("[Relay] failed to close lease connection")
143 - }
144 - }()
145 -
146 - // Lease -> Client
147 - go func() {
148 - defer wg.Done()
149 - _, _ = bpsManager.Copy(clientConn, leaseConn, leaseID)
150 - if err := clientConn.Close(); err != nil {
151 - log.Debug().Err(err).Str("lease_id", leaseID).Msg("[Relay] failed to close client connection")
152 - }
153 - }()
116 + if bpsManager == nil {
117 + // No BPS manager - direct copy without rate limiting
118 + go func() {
119 + defer wg.Done()
120 + _, _ = io.Copy(leaseConn, clientConn)
121 + _ = leaseConn.Close()
122 + }()
123 +
124 + go func() {
125 + defer wg.Done()
126 + _, _ = io.Copy(clientConn, leaseConn)
127 + _ = clientConn.Close()
128 + }()
129 + } else {
130 + bpsLimit := bpsManager.GetBPSLimit(leaseID)
131 + log.Info().
132 + Str("lease_id", leaseID).
133 + Int64("bps_limit", bpsLimit).
134 + Msg("[Relay] Starting relay connection with rate limit")
135 +
136 + // Client -> Lease
137 + go func() {
138 + defer wg.Done()
139 + _, _ = bpsManager.Copy(leaseConn, clientConn, leaseID)
140 + if err := leaseConn.Close(); err != nil {
141 + log.Debug().Err(err).Str("lease_id", leaseID).Msg("[Relay] failed to close lease connection")
142 + }
143 + }()
144 +
145 + // Lease -> Client
146 + go func() {
147 + defer wg.Done()
148 + _, _ = bpsManager.Copy(clientConn, leaseConn, leaseID)
149 + if err := clientConn.Close(); err != nil {
150 + log.Debug().Err(err).Str("lease_id", leaseID).Msg("[Relay] failed to close client connection")
151 + }
152 + }()
153 + }
154
155 wg.Wait()
156 }
portal/registry.go
+18 -26
@@ -4,6 +4,7 @@ import (
4 "crypto/subtle"
5 "fmt"
6 "net"
7 + "net/http"
8 "strings"
9 "time"
10
@@ -50,20 +51,20 @@ func (g *RelayServer) AdmitControlPlane(input RegistryAdmissionInput) (RegistryA
51 }
52
53 if input.IsClientIPBanned {
53 - return RegistryAdmissionResult{}, registryAPIError(httpStatusForbidden, "ip_banned", "ip is banned")
54 + return RegistryAdmissionResult{}, registryAPIError(http.StatusForbidden, "ip_banned", "ip is banned")
55 }
56
57 if g == nil || g.leaseManager == nil {
57 - return RegistryAdmissionResult{}, registryAPIError(httpStatusInternalServerError, "registry_unavailable", "registry service unavailable")
58 + return RegistryAdmissionResult{}, registryAPIError(http.StatusInternalServerError, "registry_unavailable", "registry service unavailable")
59 }
60
61 entry, exists := g.leaseManager.GetLeaseByID(leaseID)
62 if input.RequireExisting && !exists {
62 - return RegistryAdmissionResult{}, registryAPIError(httpStatusNotFound, "lease_not_found", "lease not found")
63 + return RegistryAdmissionResult{}, registryAPIError(http.StatusNotFound, "lease_not_found", "lease not found")
64 }
65
66 if exists && !matchLeaseToken(entry.Lease.ReverseToken, reverseToken) {
66 - return RegistryAdmissionResult{}, registryAPIError(httpStatusUnauthorized, "unauthorized", "unauthorized reverse connect")
67 + return RegistryAdmissionResult{}, registryAPIError(http.StatusUnauthorized, "unauthorized", "unauthorized reverse connect")
68 }
69
70 return RegistryAdmissionResult{
@@ -77,15 +78,15 @@ func (g *RelayServer) AdmitControlPlane(input RegistryAdmissionInput) (RegistryA
78 // RegisterLease creates a new lease and associated SNI route.
79 func (g *RelayServer) RegisterLease(input RegistryRegisterInput) (types.RegisterResponse, *types.APIError) {
80 if g == nil || g.leaseManager == nil || g.reverseHub == nil || g.sniRouter == nil {
80 - return types.RegisterResponse{}, registryAPIError(httpStatusInternalServerError, "registry_unavailable", "registry service unavailable")
81 + return types.RegisterResponse{}, registryAPIError(http.StatusInternalServerError, "registry_unavailable", "registry service unavailable")
82 }
83
84 name := strings.TrimSpace(input.Name)
85 if !types.IsValidServiceName(name) {
85 - return types.RegisterResponse{}, registryAPIError(httpStatusBadRequest, "invalid_name", "name must be a DNS label (letters, digits, hyphen; no dots or underscores)")
86 + return types.RegisterResponse{}, registryAPIError(http.StatusBadRequest, "invalid_name", "name must be a DNS label (letters, digits, hyphen; no dots or underscores)")
87 }
88 if !input.TLS {
88 - return types.RegisterResponse{}, registryAPIError(httpStatusBadRequest, "tls_required", "tls must be enabled")
89 + return types.RegisterResponse{}, registryAPIError(http.StatusBadRequest, "tls_required", "tls must be enabled")
90 }
91
92 metadata := types.Metadata{}
@@ -103,18 +104,18 @@ func (g *RelayServer) RegisterLease(input RegistryRegisterInput) (types.Register
104 }
105
106 if !g.leaseManager.UpdateLease(lease) {
106 - return types.RegisterResponse{}, registryAPIError(httpStatusConflict, "lease_rejected", "failed to register lease (name conflict or policy violation)")
107 + return types.RegisterResponse{}, registryAPIError(http.StatusConflict, "lease_rejected", "failed to register lease (name conflict or policy violation)")
108 }
109 g.reverseHub.ClearDropped(input.LeaseID)
110
111 sniName := types.BuildSNIName(name, g.BaseHost)
112 if sniName == "" {
113 g.leaseManager.DeleteLease(input.LeaseID)
113 - return types.RegisterResponse{}, registryAPIError(httpStatusInternalServerError, "sni_name_invalid", "failed to build SNI route name")
114 + return types.RegisterResponse{}, registryAPIError(http.StatusInternalServerError, "sni_name_invalid", "failed to build SNI route name")
115 }
116 if err := g.sniRouter.RegisterRoute(sniName, input.LeaseID, name); err != nil {
117 g.leaseManager.DeleteLease(input.LeaseID)
117 - return types.RegisterResponse{}, registryAPIError(httpStatusInternalServerError, "sni_register_failed", fmt.Sprintf("failed to register SNI route: %v", err))
118 + return types.RegisterResponse{}, registryAPIError(http.StatusInternalServerError, "sni_register_failed", fmt.Sprintf("failed to register SNI route: %v", err))
119 }
120
121 log.Info().
@@ -153,15 +154,15 @@ func (g *RelayServer) UnregisterLease(leaseID string) {
154 // RenewLease extends lease expiry and opportunistically refreshes SNI routing.
155 func (g *RelayServer) RenewLease(entry *types.LeaseEntry) *types.APIError {
156 if entry == nil || entry.Lease == nil {
156 - return registryAPIError(httpStatusNotFound, "lease_not_found", "lease not found")
157 + return registryAPIError(http.StatusNotFound, "lease_not_found", "lease not found")
158 }
159 if g == nil || g.leaseManager == nil || g.sniRouter == nil {
159 - return registryAPIError(httpStatusInternalServerError, "registry_unavailable", "registry service unavailable")
160 + return registryAPIError(http.StatusInternalServerError, "registry_unavailable", "registry service unavailable")
161 }
162
163 entry.Lease.Expires = time.Now().Add(DefaultLeaseTTL)
164 if !g.leaseManager.UpdateLease(entry.Lease) {
164 - return registryAPIError(httpStatusInternalServerError, "renew_failed", "failed to renew lease")
165 + return registryAPIError(http.StatusInternalServerError, "renew_failed", "failed to renew lease")
166 }
167
168 sniName := types.BuildSNIName(entry.Lease.Name, g.BaseHost)
@@ -186,11 +187,11 @@ func (g *RelayServer) RenewLease(entry *types.LeaseEntry) *types.APIError {
187 // RegistryDomain returns the configured relay base domain.
188 func (g *RelayServer) RegistryDomain() (types.DomainResponse, *types.APIError) {
189 if g == nil {
189 - return types.DomainResponse{}, registryAPIError(httpStatusServiceUnavailable, "base_domain_missing", "base domain not configured")
190 + return types.DomainResponse{}, registryAPIError(http.StatusServiceUnavailable, "base_domain_missing", "base domain not configured")
191 }
192 baseHost := strings.TrimSpace(g.BaseHost)
193 if baseHost == "" {
193 - return types.DomainResponse{}, registryAPIError(httpStatusServiceUnavailable, "base_domain_missing", "base domain not configured")
194 + return types.DomainResponse{}, registryAPIError(http.StatusServiceUnavailable, "base_domain_missing", "base domain not configured")
195 }
196 return types.DomainResponse{
197 Success: true,
@@ -225,10 +226,10 @@ func normalizeRegistryCredentials(rawLeaseID, rawReverseToken string) (leaseID,
226
227 func validateRegistryCredentials(leaseID, reverseToken string) *types.APIError {
228 if leaseID == "" {
228 - return registryAPIError(httpStatusBadRequest, "missing_lease_id", "lease_id is required")
229 + return registryAPIError(http.StatusBadRequest, "missing_lease_id", "lease_id is required")
230 }
231 if reverseToken == "" {
231 - return registryAPIError(httpStatusBadRequest, "missing_reverse_token", "reverse_token is required")
232 + return registryAPIError(http.StatusBadRequest, "missing_reverse_token", "reverse_token is required")
233 }
234 return nil
235 }
@@ -241,12 +242,3 @@ func registryAPIError(statusCode int, code, message string) *types.APIError {
242 }
243 }
244
244 -const (
245 - httpStatusBadRequest = 400
246 - httpStatusUnauthorized = 401
247 - httpStatusForbidden = 403
248 - httpStatusNotFound = 404
249 - httpStatusConflict = 409
250 - httpStatusInternalServerError = 500
251 - httpStatusServiceUnavailable = 503
252 -)
types/types.go
-5
@@ -40,35 +40,30 @@ type Metadata struct {
40 // MetadataOption configures Metadata.
41 type MetadataOption func(*Metadata)
42
43 -// WithDescription sets the lease description.
43 func WithDescription(description string) MetadataOption {
44 return func(m *Metadata) {
45 m.Description = description
46 }
47 }
48
50 -// WithTags sets the lease tags.
49 func WithTags(tags []string) MetadataOption {
50 return func(m *Metadata) {
51 m.Tags = tags
52 }
53 }
54
57 -// WithThumbnail sets the lease thumbnail URL.
55 func WithThumbnail(thumbnail string) MetadataOption {
56 return func(m *Metadata) {
57 m.Thumbnail = thumbnail
58 }
59 }
60
64 -// WithOwner sets the lease owner.
61 func WithOwner(owner string) MetadataOption {
62 return func(m *Metadata) {
63 m.Owner = owner
64 }
65 }
66
71 -// WithHide sets whether to hide the lease from public listings.
67 func WithHide(hide bool) MetadataOption {
68 return func(m *Metadata) {
69 m.Hide = hide