fix(sec): critical tenant isolation - pgx placeholders, requireSOC hardening, plan upgrade guard

- Fix pgx/v5 SQL placeholder bug (? -> /) in tenant_handlers.go
- tenant_id was silently failing to write/read, causing empty TenantID in JWT
- Harden requireSOC middleware to BLOCK when TenantID is empty (was pass-through)
- Block paid plan upgrades without Stripe payment verification
- Add in-memory cache update for tenant_id on registration
- Add fallback tenant_id read from User object in HandleVerifyEmail
This commit is contained in:
DmitrL-dev 2026-03-27 19:11:55 +10:00
parent 1aa47da6a3
commit dd977b7d46
2 changed files with 42 additions and 5 deletions

View file

@ -78,8 +78,17 @@ func HandleRegister(userStore *UserStore, tenantStore *TenantStore, jwtSecret []
}
// Update user with tenant_id
// CRITICAL: pgx/v5 requires $1/$2 placeholders, NOT ? (silently fails with ?)
if userStore.db != nil {
userStore.db.Exec(`UPDATE users SET tenant_id = ? WHERE id = ?`, tenant.ID, user.ID)
if _, err := userStore.db.Exec(`UPDATE users SET tenant_id = $1 WHERE id = $2`, tenant.ID, user.ID); err != nil {
slog.Error("register: failed to set tenant_id on user", "user", user.ID, "tenant", tenant.ID, "error", err)
}
// Also update in-memory cache
userStore.mu.Lock()
if u, ok := userStore.users[user.Email]; ok {
u.TenantID = tenant.ID
}
userStore.mu.Unlock()
}
// Generate verification code
@ -149,9 +158,16 @@ func HandleVerifyEmail(userStore *UserStore, tenantStore *TenantStore, jwtSecret
}
// Find tenant for this user
// CRITICAL: pgx/v5 requires $1 placeholder, NOT ?
var tenantID string
if userStore.db != nil {
userStore.db.QueryRow(`SELECT tenant_id FROM users WHERE id = ?`, user.ID).Scan(&tenantID)
if err := userStore.db.QueryRow(`SELECT tenant_id FROM users WHERE id = $1`, user.ID).Scan(&tenantID); err != nil {
slog.Warn("verify: could not read tenant_id from DB", "user", user.ID, "error", err)
}
}
// Fallback: check in-memory user object
if tenantID == "" && user.TenantID != "" {
tenantID = user.TenantID
}
// Issue JWT with tenant context
@ -243,6 +259,9 @@ func HandleGetTenant(tenantStore *TenantStore) http.HandlerFunc {
// HandleUpdateTenantPlan upgrades/downgrades the tenant plan.
// POST /api/auth/tenant/plan { plan_id }
// SEC: Only allows downgrade to 'free' without payment. Paid upgrades require
// Stripe webhook confirmation (HandleStripeWebhook). This prevents users from
// clicking "Перейти" on paid plans and getting access without payment.
func HandleUpdateTenantPlan(tenantStore *TenantStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
claims := GetClaims(r.Context())
@ -250,6 +269,10 @@ func HandleUpdateTenantPlan(tenantStore *TenantStore) http.HandlerFunc {
http.Error(w, `{"error":"admin role required"}`, http.StatusForbidden)
return
}
if claims.TenantID == "" {
http.Error(w, `{"error":"no tenant context"}`, http.StatusForbidden)
return
}
var req struct {
PlanID string `json:"plan_id"`
@ -259,6 +282,12 @@ func HandleUpdateTenantPlan(tenantStore *TenantStore) http.HandlerFunc {
return
}
// SEC: Block direct upgrades to paid plans — only Stripe webhook can do that
if req.PlanID != "free" {
http.Error(w, `{"error":"paid plan upgrades require payment — visit syntrex.pro/pricing"}`, http.StatusPaymentRequired)
return
}
if err := tenantStore.UpdatePlan(claims.TenantID, req.PlanID); err != nil {
http.Error(w, `{"error":"`+err.Error()+`"}`, http.StatusBadRequest)
return

View file

@ -186,6 +186,8 @@ func (s *Server) StartEventBridge(ctx context.Context) {
// requireSOC wraps a handler to enforce SOC Dashboard plan access.
// Returns 403 for tenants on the Free plan (SOCEnabled=false).
// SEC: Also denies access when TenantID is empty — prevents data leak
// when tenant_id was not properly set during registration.
// No-op when tenantStore is nil (backward compatible with tests).
func (s *Server) requireSOC(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
@ -194,9 +196,15 @@ func (s *Server) requireSOC(next http.HandlerFunc) http.HandlerFunc {
return
}
claims := auth.GetClaims(r.Context())
if claims == nil || claims.TenantID == "" {
// Unauthenticated or no tenant context — let RBAC/JWT handle it
next(w, r)
if claims == nil {
writeError(w, http.StatusUnauthorized, "authentication required for SOC access")
return
}
if claims.TenantID == "" {
// SEC: Empty TenantID = either tenant_id wasn't saved (pgx bug)
// or user has no tenant. Block access to prevent cross-tenant leak.
writeError(w, http.StatusForbidden,
"no tenant context — re-login required. If this persists, contact support.")
return
}
tenant, err := s.tenantStore.GetTenant(claims.TenantID)