|
| 1 | +package handlers_test |
| 2 | + |
| 3 | +// billing_test_cohort_test.go — W0 / PR-1 (cohort-isolation foundation). |
| 4 | +// |
| 5 | +// Proves the api-side synthetic-cohort skip-guard on the two self-serve |
| 6 | +// charge-initiation handlers (CreateCheckoutAPI, ChangePlanAPI): a team with |
| 7 | +// teams.is_test_cohort=true (migration 067) is rejected with a deterministic |
| 8 | +// 403 synthetic_test_cohort BEFORE any Razorpay call, while a normal team |
| 9 | +// sails past the guard. See |
| 10 | +// docs/sessions/2026-06-04/TEST-ACCOUNTS-AND-NR-SYNTHETICS-PLAN.md §1.6. |
| 11 | + |
| 12 | +import ( |
| 13 | + "context" |
| 14 | + "database/sql" |
| 15 | + "encoding/json" |
| 16 | + "errors" |
| 17 | + "net/http" |
| 18 | + "net/http/httptest" |
| 19 | + "os" |
| 20 | + "strings" |
| 21 | + "testing" |
| 22 | + |
| 23 | + sqlmock "github.com/DATA-DOG/go-sqlmock" |
| 24 | + "github.com/gofiber/fiber/v2" |
| 25 | + "github.com/google/uuid" |
| 26 | + "github.com/stretchr/testify/assert" |
| 27 | + "github.com/stretchr/testify/require" |
| 28 | + |
| 29 | + "instant.dev/internal/config" |
| 30 | + "instant.dev/internal/email" |
| 31 | + "instant.dev/internal/handlers" |
| 32 | + "instant.dev/internal/middleware" |
| 33 | + "instant.dev/internal/models" |
| 34 | + "instant.dev/internal/testhelpers" |
| 35 | +) |
| 36 | + |
| 37 | +// errCodeSyntheticTestCohort mirrors the unexported handler constant — the |
| 38 | +// stable wire code the synthetic runner asserts on. |
| 39 | +const errCodeSyntheticTestCohort = "synthetic_test_cohort" |
| 40 | + |
| 41 | +func cohortNeedsDB(t *testing.T) (*sql.DB, func()) { |
| 42 | + t.Helper() |
| 43 | + if os.Getenv("TEST_DATABASE_URL") == "" { |
| 44 | + t.Skip("billing_test_cohort_test: TEST_DATABASE_URL not set — skipping integration test") |
| 45 | + } |
| 46 | + return testhelpers.SetupTestDB(t) |
| 47 | +} |
| 48 | + |
| 49 | +// cohortBillingApp wires both charge-initiation endpoints with a fake-auth |
| 50 | +// middleware that injects only team_id (no user_id, so the email-verify gate |
| 51 | +// fails OPEN — isolating the cohort guard as the only blocker under test). |
| 52 | +// Razorpay creds are intentionally empty so a normal team that passes the |
| 53 | +// guard halts at billing_not_configured (503) without any network call. |
| 54 | +func cohortBillingApp(t *testing.T, db *sql.DB, teamID string) *fiber.App { |
| 55 | + t.Helper() |
| 56 | + cfg := &config.Config{JWTSecret: testhelpers.TestJWTSecret} // no Razorpay creds |
| 57 | + bh := handlers.NewBillingHandler(db, cfg, email.NewNoop()) |
| 58 | + app := fiber.New(fiber.Config{ |
| 59 | + ErrorHandler: func(c *fiber.Ctx, err error) error { |
| 60 | + if errors.Is(err, handlers.ErrResponseWritten) { |
| 61 | + return nil |
| 62 | + } |
| 63 | + code := fiber.StatusInternalServerError |
| 64 | + if e, ok := err.(*fiber.Error); ok { |
| 65 | + code = e.Code |
| 66 | + } |
| 67 | + return c.Status(code).JSON(fiber.Map{"ok": false, "error": "internal_error"}) |
| 68 | + }, |
| 69 | + }) |
| 70 | + app.Use(func(c *fiber.Ctx) error { |
| 71 | + if teamID != "" { |
| 72 | + c.Locals(middleware.LocalKeyTeamID, teamID) |
| 73 | + } |
| 74 | + return c.Next() |
| 75 | + }) |
| 76 | + app.Post("/api/v1/billing/checkout", bh.CreateCheckoutAPI) |
| 77 | + app.Post("/api/v1/billing/change-plan", bh.ChangePlanAPI) |
| 78 | + return app |
| 79 | +} |
| 80 | + |
| 81 | +func cohortPost(t *testing.T, app *fiber.App, path, body string) (int, map[string]any) { |
| 82 | + t.Helper() |
| 83 | + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) |
| 84 | + req.Header.Set("Content-Type", "application/json") |
| 85 | + resp, err := app.Test(req, 5000) |
| 86 | + require.NoError(t, err) |
| 87 | + defer resp.Body.Close() |
| 88 | + var out map[string]any |
| 89 | + _ = json.NewDecoder(resp.Body).Decode(&out) |
| 90 | + return resp.StatusCode, out |
| 91 | +} |
| 92 | + |
| 93 | +// TestCheckout_TestCohortGuard_FailsOpenOnDBError: a DB blip on the cohort |
| 94 | +// lookup must NOT block a real customer's checkout. The guard fails open |
| 95 | +// (treats the lookup error as "not a test cohort") and execution proceeds |
| 96 | +// past it — so the response is anything OTHER than synthetic_test_cohort. |
| 97 | +// Uses sqlmock so the error branch is deterministic and DB-independent. |
| 98 | +func TestCheckout_TestCohortGuard_FailsOpenOnDBError(t *testing.T) { |
| 99 | + db, mock, err := sqlmock.New() |
| 100 | + require.NoError(t, err) |
| 101 | + defer db.Close() |
| 102 | + |
| 103 | + teamID := uuid.NewString() |
| 104 | + mock.ExpectQuery("SELECT is_test_cohort FROM teams WHERE id"). |
| 105 | + WillReturnError(errors.New("db blip")) |
| 106 | + |
| 107 | + app := cohortBillingApp(t, db, teamID) // no Razorpay creds → halts at not_configured |
| 108 | + status, body := cohortPost(t, app, "/api/v1/billing/checkout", `{"plan":"pro"}`) |
| 109 | + |
| 110 | + assert.NotEqual(t, errCodeSyntheticTestCohort, body["error"], |
| 111 | + "a DB error on the cohort lookup must fail OPEN, not block the customer") |
| 112 | + assert.NotEqual(t, http.StatusForbidden, status) |
| 113 | +} |
| 114 | + |
| 115 | +// TestCheckout_TestCohortTeam_Rejected: a synthetic team is 403'd with the |
| 116 | +// distinct code on the checkout path before any Razorpay call. |
| 117 | +func TestCheckout_TestCohortTeam_Rejected(t *testing.T) { |
| 118 | + db, cleanup := cohortNeedsDB(t) |
| 119 | + defer cleanup() |
| 120 | + |
| 121 | + teamID := testhelpers.MustCreateTeamDB(t, db, "hobby") |
| 122 | + require.NoError(t, models.SetTestCohort(context.Background(), db, uuid.MustParse(teamID), true)) |
| 123 | + |
| 124 | + app := cohortBillingApp(t, db, teamID) |
| 125 | + status, body := cohortPost(t, app, "/api/v1/billing/checkout", `{"plan":"pro"}`) |
| 126 | + |
| 127 | + assert.Equal(t, http.StatusForbidden, status) |
| 128 | + assert.Equal(t, errCodeSyntheticTestCohort, body["error"]) |
| 129 | +} |
| 130 | + |
| 131 | +// TestChangePlan_TestCohortTeam_Rejected: same guard on the change-plan path. |
| 132 | +func TestChangePlan_TestCohortTeam_Rejected(t *testing.T) { |
| 133 | + db, cleanup := cohortNeedsDB(t) |
| 134 | + defer cleanup() |
| 135 | + |
| 136 | + teamID := testhelpers.MustCreateTeamDB(t, db, "hobby") |
| 137 | + require.NoError(t, models.SetTestCohort(context.Background(), db, uuid.MustParse(teamID), true)) |
| 138 | + |
| 139 | + app := cohortBillingApp(t, db, teamID) |
| 140 | + status, body := cohortPost(t, app, "/api/v1/billing/change-plan", `{"target_plan":"pro"}`) |
| 141 | + |
| 142 | + assert.Equal(t, http.StatusForbidden, status) |
| 143 | + assert.Equal(t, errCodeSyntheticTestCohort, body["error"]) |
| 144 | +} |
| 145 | + |
| 146 | +// TestCheckout_NormalTeam_NotSkipped: a normal (default is_test_cohort=false) |
| 147 | +// team is NOT caught by the guard — it passes through and halts later |
| 148 | +// (billing_not_configured, since Razorpay creds are empty). The assertion is |
| 149 | +// that the response is anything OTHER than synthetic_test_cohort, proving the |
| 150 | +// guard is cohort-specific and inert for real teams. |
| 151 | +func TestCheckout_NormalTeam_NotSkipped(t *testing.T) { |
| 152 | + db, cleanup := cohortNeedsDB(t) |
| 153 | + defer cleanup() |
| 154 | + |
| 155 | + teamID := testhelpers.MustCreateTeamDB(t, db, "hobby") // is_test_cohort defaults false |
| 156 | + |
| 157 | + app := cohortBillingApp(t, db, teamID) |
| 158 | + status, body := cohortPost(t, app, "/api/v1/billing/checkout", `{"plan":"pro"}`) |
| 159 | + |
| 160 | + assert.NotEqual(t, errCodeSyntheticTestCohort, body["error"], |
| 161 | + "a normal team must NOT be rejected by the synthetic-cohort guard") |
| 162 | + assert.NotEqual(t, http.StatusForbidden, status, |
| 163 | + "a normal team must pass the guard (halts later at billing_not_configured)") |
| 164 | +} |
| 165 | + |
| 166 | +// TestChangePlan_NormalTeam_NotSkipped: change-plan twin of the above. |
| 167 | +func TestChangePlan_NormalTeam_NotSkipped(t *testing.T) { |
| 168 | + db, cleanup := cohortNeedsDB(t) |
| 169 | + defer cleanup() |
| 170 | + |
| 171 | + teamID := testhelpers.MustCreateTeamDB(t, db, "hobby") |
| 172 | + |
| 173 | + app := cohortBillingApp(t, db, teamID) |
| 174 | + status, body := cohortPost(t, app, "/api/v1/billing/change-plan", `{"target_plan":"pro"}`) |
| 175 | + |
| 176 | + assert.NotEqual(t, errCodeSyntheticTestCohort, body["error"], |
| 177 | + "a normal team must NOT be rejected by the synthetic-cohort guard") |
| 178 | + _ = status |
| 179 | +} |
0 commit comments