|
| 1 | +package handlers_test |
| 2 | + |
| 3 | +// billing_block_no_cancel_downgrade_test.go — W3 §E10: there is NO self-serve |
| 4 | +// cancel or downgrade path. |
| 5 | +// |
| 6 | +// Policy (memory: project_no_self_serve_cancel_downgrade): cancellation and |
| 7 | +// downgrade are SUPPORT-ONLY. Downgrade flows through the Razorpay |
| 8 | +// subscription.cancelled / .updated webhook or a support agent; a paying team |
| 9 | +// must NOT be able to drop itself to a cheaper tier or cancel via any |
| 10 | +// session-authenticated endpoint. The self-serve POST /billing/cancel was |
| 11 | +// REMOVED (router.go documents the removal next to /billing/change-plan). |
| 12 | +// |
| 13 | +// Two complementary assertions: |
| 14 | +// 1. ROUTE NEGATIVE: string-parse the live router.go and prove no route |
| 15 | +// registers a self-serve cancel/downgrade verb. This is the same |
| 16 | +// source-scan technique the OpenAPI route-parity test uses |
| 17 | +// (extractRouterRoutes) so it tracks the real registration table, not a |
| 18 | +// stale mental model. If someone re-adds POST /billing/cancel, this reds. |
| 19 | +// 2. HANDLER NEGATIVE: drive the real ChangePlanAPI with a lower-or-equal |
| 20 | +// target tier and assert it is rejected with downgrade_not_self_serve + |
| 21 | +// a mailto:support agent_action — the exact policy in |
| 22 | +// billing.go:ChangePlanAPI. This is verified against the code, not |
| 23 | +// assumed: a downgrade returns 400 downgrade_not_self_serve, NOT a |
| 24 | +// silent tier drop. |
| 25 | + |
| 26 | +import ( |
| 27 | + "net/http" |
| 28 | + "os" |
| 29 | + "path/filepath" |
| 30 | + "regexp" |
| 31 | + "strings" |
| 32 | + "testing" |
| 33 | + |
| 34 | + "github.com/stretchr/testify/assert" |
| 35 | + "github.com/stretchr/testify/require" |
| 36 | + |
| 37 | + "instant.dev/internal/config" |
| 38 | +) |
| 39 | + |
| 40 | +// blockRouterRoute is a (method, path, isAdmin) tuple parsed from router.go. |
| 41 | +// Local to this W3 file because the OpenAPI test's identically-shaped parser |
| 42 | +// lives in the white-box `handlers` test package and is not reachable from |
| 43 | +// this black-box `handlers_test` package. |
| 44 | +type blockRouterRoute struct { |
| 45 | + method string |
| 46 | + path string |
| 47 | + isAdmin bool |
| 48 | +} |
| 49 | + |
| 50 | +// blockExtractRouterRoutes string-parses router.go and returns every literal |
| 51 | +// route registration. Same conservative technique the OpenAPI route-parity |
| 52 | +// test uses: it expects a literal "(" after the verb and a quoted path as the |
| 53 | +// first arg, skipping any dynamic registration (router.go uses only literal |
| 54 | +// paths today). Groups carry their URL prefix so the returned path is fully |
| 55 | +// qualified. |
| 56 | +func blockExtractRouterRoutes(src string) []blockRouterRoute { |
| 57 | + patterns := []struct { |
| 58 | + groupRe *regexp.Regexp |
| 59 | + urlPrefix string |
| 60 | + isAdmin bool |
| 61 | + }{ |
| 62 | + {regexp.MustCompile(`\bapp\.(Get|Post|Put|Patch|Delete)\("([^"]+)"`), "", false}, |
| 63 | + {regexp.MustCompile(`\bapi\.(Get|Post|Put|Patch|Delete)\("([^"]+)"`), "/api/v1", false}, |
| 64 | + {regexp.MustCompile(`\badminGroup\.(Get|Post|Put|Patch|Delete)\("([^"]+)"`), "/api/v1/<admin>", true}, |
| 65 | + {regexp.MustCompile(`\bdeployGroup\.(Get|Post|Put|Patch|Delete)\("([^"]+)"`), "/deploy", false}, |
| 66 | + {regexp.MustCompile(`\binternal\.(Get|Post|Put|Patch|Delete)\("([^"]+)"`), "/internal", false}, |
| 67 | + } |
| 68 | + var out []blockRouterRoute |
| 69 | + for _, p := range patterns { |
| 70 | + for _, m := range p.groupRe.FindAllStringSubmatch(src, -1) { |
| 71 | + path := m[2] |
| 72 | + if p.urlPrefix != "" { |
| 73 | + if !strings.HasPrefix(path, "/") { |
| 74 | + path = "/" + path |
| 75 | + } |
| 76 | + path = p.urlPrefix + path |
| 77 | + } |
| 78 | + out = append(out, blockRouterRoute{method: strings.ToUpper(m[1]), path: path, isAdmin: p.isAdmin}) |
| 79 | + } |
| 80 | + } |
| 81 | + return out |
| 82 | +} |
| 83 | + |
| 84 | +// forbiddenSelfServeBillingPaths is the set of route SUFFIXES that, if they |
| 85 | +// ever appear as a registered self-serve (session-authenticated, non-admin, |
| 86 | +// non-webhook) route, would constitute a self-serve cancel/downgrade surface |
| 87 | +// the policy forbids. Matched as a suffix against the parsed router path so |
| 88 | +// both the legacy alias and the /api/v1 group form are caught. |
| 89 | +var forbiddenSelfServeBillingPaths = []string{ |
| 90 | + "/billing/cancel", |
| 91 | + "/billing/downgrade", |
| 92 | + "/billing/subscription/cancel", |
| 93 | + "/subscription/cancel", |
| 94 | +} |
| 95 | + |
| 96 | +// TestBillingBlock_NoSelfServeCancelOrDowngradeRoute parses router.go and |
| 97 | +// asserts none of the forbidden self-serve cancel/downgrade paths are |
| 98 | +// registered on a non-admin route. Admin routes (e.g. an operator demote) are |
| 99 | +// allowed and excluded — cancellation IS supported, just support/operator-side. |
| 100 | +// |
| 101 | +// This does not require a DB — it reads the router source, the same way |
| 102 | +// TestOpenAPI route-parity does, so it runs even in the -short unit lane. |
| 103 | +func TestBillingBlock_NoSelfServeCancelOrDowngradeRoute(t *testing.T) { |
| 104 | + routerPath := filepath.Join("..", "router", "router.go") |
| 105 | + src, err := os.ReadFile(routerPath) |
| 106 | + require.NoError(t, err, "read router.go") |
| 107 | + |
| 108 | + routes := blockExtractRouterRoutes(string(src)) |
| 109 | + require.NotEmpty(t, routes, |
| 110 | + "blockExtractRouterRoutes returned 0 — parser is out of sync with router.go (the negative assertion would pass vacuously)") |
| 111 | + |
| 112 | + // Guard against a vacuous pass: confirm the parser actually sees the |
| 113 | + // billing block by requiring the legitimate change-plan route to be |
| 114 | + // present. If the parser silently broke, this trips before the negative |
| 115 | + // assertion can give a false green. |
| 116 | + var sawChangePlan bool |
| 117 | + for _, r := range routes { |
| 118 | + if strings.HasSuffix(r.path, "/billing/change-plan") { |
| 119 | + sawChangePlan = true |
| 120 | + break |
| 121 | + } |
| 122 | + } |
| 123 | + require.True(t, sawChangePlan, |
| 124 | + "expected the router parser to see POST /billing/change-plan — if it doesn't, the no-cancel negative assertion is meaningless") |
| 125 | + |
| 126 | + for _, r := range routes { |
| 127 | + if r.isAdmin { |
| 128 | + continue // operator/support-side cancellation is allowed. |
| 129 | + } |
| 130 | + for _, forbidden := range forbiddenSelfServeBillingPaths { |
| 131 | + assert.Falsef(t, strings.HasSuffix(r.path, forbidden), |
| 132 | + "self-serve cancel/downgrade is support-only (§E10, memory project_no_self_serve_cancel_downgrade) — "+ |
| 133 | + "router.go must not register a non-admin route ending in %q, but found %s %s", |
| 134 | + forbidden, r.method, r.path) |
| 135 | + } |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +// TestBillingBlock_ChangePlanRejectsDowngrade pins the handler-level policy: a |
| 140 | +// paying team requesting a LOWER or EQUAL tier via the in-app change-plan path |
| 141 | +// is rejected with downgrade_not_self_serve and routed to support, NOT |
| 142 | +// silently dropped. Verified against billing.go:ChangePlanAPI (it returns 400 |
| 143 | +// downgrade_not_self_serve + a mailto:support@instanode.dev agent_action for |
| 144 | +// any target whose rank ≤ the current tier's rank). |
| 145 | +func TestBillingBlock_ChangePlanRejectsDowngrade(t *testing.T) { |
| 146 | + if billingBlockSkipNoDB(t) { |
| 147 | + return |
| 148 | + } |
| 149 | + |
| 150 | + cases := []struct { |
| 151 | + name string |
| 152 | + startTier string |
| 153 | + target string |
| 154 | + }{ |
| 155 | + {"pro → hobby is a downgrade", "pro", "hobby"}, |
| 156 | + {"pro → hobby_plus is a downgrade", "pro", "hobby_plus"}, |
| 157 | + {"hobby_plus → hobby is a downgrade", "hobby_plus", "hobby"}, |
| 158 | + } |
| 159 | + for _, tc := range cases { |
| 160 | + t.Run(tc.name, func(t *testing.T) { |
| 161 | + db, clean := billingBlockDB(t) |
| 162 | + defer clean() |
| 163 | + teamID := mustSeedTeam(t, db, tc.startTier) |
| 164 | + cfg := &config.Config{ |
| 165 | + JWTSecret: billingBlockJWTSecret, |
| 166 | + RazorpayKeyID: "rzp_test_k", |
| 167 | + RazorpayKeySecret: "s", |
| 168 | + RazorpayPlanIDHobby: "plan_hobby", |
| 169 | + RazorpayPlanIDHobbyPlus: "plan_hobby_plus", |
| 170 | + RazorpayPlanIDPro: "plan_pro", |
| 171 | + } |
| 172 | + app := changePlanAppReal(t, db, cfg, teamID) |
| 173 | + code, body := changePlanReq(t, app, map[string]any{"target_plan": tc.target}) |
| 174 | + |
| 175 | + assert.Equal(t, http.StatusBadRequest, code, "downgrade must be a 400, body=%v", body) |
| 176 | + assert.Equal(t, "downgrade_not_self_serve", body["error"], |
| 177 | + "%s must be rejected as a support-only downgrade, not applied", tc.name) |
| 178 | + // The agent_action must route the user to support so an agent does |
| 179 | + // not retry or invent a different path. |
| 180 | + action, _ := body["agent_action"].(string) |
| 181 | + assert.Contains(t, strings.ToLower(action), "support", |
| 182 | + "downgrade rejection must carry a support-routing agent_action (got %q)", action) |
| 183 | + |
| 184 | + // And CRITICALLY: the team's tier must be UNCHANGED — a downgrade |
| 185 | + // rejection that still mutated the row would be the worst outcome. |
| 186 | + assert.Equal(t, tc.startTier, billingBlockTeamTier(t, db, teamID), |
| 187 | + "a rejected downgrade must not mutate the team's plan_tier") |
| 188 | + }) |
| 189 | + } |
| 190 | +} |
| 191 | + |
| 192 | +// TestBillingBlock_ChangePlanSamePlanRejected covers the lateral/no-op edge: |
| 193 | +// requesting the tier the team already holds is rejected with same_plan (not |
| 194 | +// treated as a downgrade, not a no-op success that churns the Razorpay |
| 195 | +// subscription). Part of the §E10 surface — no self-serve tier mutation that |
| 196 | +// isn't a genuine upgrade. |
| 197 | +func TestBillingBlock_ChangePlanSamePlanRejected(t *testing.T) { |
| 198 | + if billingBlockSkipNoDB(t) { |
| 199 | + return |
| 200 | + } |
| 201 | + db, clean := billingBlockDB(t) |
| 202 | + defer clean() |
| 203 | + teamID := mustSeedTeam(t, db, "pro") |
| 204 | + cfg := &config.Config{ |
| 205 | + JWTSecret: billingBlockJWTSecret, |
| 206 | + RazorpayKeyID: "rzp_test_k", |
| 207 | + RazorpayKeySecret: "s", |
| 208 | + RazorpayPlanIDPro: "plan_pro", |
| 209 | + } |
| 210 | + app := changePlanAppReal(t, db, cfg, teamID) |
| 211 | + code, body := changePlanReq(t, app, map[string]any{"target_plan": "pro"}) |
| 212 | + assert.Equal(t, http.StatusBadRequest, code, "body=%v", body) |
| 213 | + assert.Equal(t, "same_plan", body["error"], |
| 214 | + "requesting the current tier must return same_plan, not a no-op success") |
| 215 | + assert.Equal(t, "pro", billingBlockTeamTier(t, db, teamID)) |
| 216 | +} |
0 commit comments