|
| 1 | +package jobs |
| 2 | + |
| 3 | +// sub95_seams_coverage_test.go — closes the last residual branches in |
| 4 | +// quota_infra.go, expire_imminent.go, and expiry_reminder_email.go to ≥95% |
| 5 | +// each via package-var test seams. New org policy: no coverage waivers. |
| 6 | +// |
| 7 | +// Each seam swaps a production indirection point (sqlOpen / validateIdent / |
| 8 | +// jsonMarshal / the *template.Template package vars) for a failing stub, |
| 9 | +// drives the otherwise-unreachable defensive fail-open arm, and restores the |
| 10 | +// production binding in a deferred cleanup so the swap can never leak into a |
| 11 | +// sibling test. Production defaults are byte-for-byte identical. |
| 12 | + |
| 13 | +import ( |
| 14 | + "bytes" |
| 15 | + "context" |
| 16 | + "database/sql" |
| 17 | + "encoding/json" |
| 18 | + "errors" |
| 19 | + "html/template" |
| 20 | + "testing" |
| 21 | + textTemplate "text/template" |
| 22 | + "time" |
| 23 | + |
| 24 | + sqlmock "github.com/DATA-DOG/go-sqlmock" |
| 25 | + "github.com/google/uuid" |
| 26 | + "github.com/riverqueue/river" |
| 27 | + "github.com/riverqueue/river/rivertype" |
| 28 | +) |
| 29 | + |
| 30 | +// errSeam is the canned error every seam stub returns. |
| 31 | +var errSeam = errors.New("seam-injected failure") |
| 32 | + |
| 33 | +func seamImminentJob() *river.Job[ExpireImminentArgs] { |
| 34 | + return &river.Job[ExpireImminentArgs]{JobRow: &rivertype.JobRow{ID: 1}} |
| 35 | +} |
| 36 | + |
| 37 | +// ── quota_infra.go: sqlOpen lazy-error fail-open arm ───────────────────────── |
| 38 | +// |
| 39 | +// lib/pq's sql.Open is fully lazy and never errors at Open time, so the |
| 40 | +// open-error fail-open branch in revokePostgres / grantPostgres is unreachable |
| 41 | +// in production. The sqlOpen seam injects an Open that errors, exercising both |
| 42 | +// fail-open arms (which must still return nil — convention #1). |
| 43 | +func TestRevokeGrantPostgres_OpenError_FailOpen(t *testing.T) { |
| 44 | + orig := sqlOpen |
| 45 | + sqlOpen = func(driverName, dsn string) (*sql.DB, error) { |
| 46 | + return nil, errSeam |
| 47 | + } |
| 48 | + t.Cleanup(func() { sqlOpen = orig }) |
| 49 | + |
| 50 | + r := &directResourceRevoker{customerDatabaseURL: "postgres://x:y@127.0.0.1:5432/z?sslmode=disable"} |
| 51 | + ctx := context.Background() |
| 52 | + |
| 53 | + if err := r.revokePostgres(ctx, "validtoken"); err != nil { |
| 54 | + t.Errorf("revokePostgres on sql.Open error: want nil (fail-open), got %v", err) |
| 55 | + } |
| 56 | + if err := r.grantPostgres(ctx, "validtoken"); err != nil { |
| 57 | + t.Errorf("grantPostgres on sql.Open error: want nil (fail-open), got %v", err) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// ── quota_infra.go: validateIdent user-arm error return ────────────────────── |
| 62 | +// |
| 63 | +// db_<token> and usr_<token> share the same token, so for any token that fails |
| 64 | +// validation the db check short-circuits first and the user-arm error return |
| 65 | +// is unreachable. The validateIdent seam passes the db_-prefixed identifier and |
| 66 | +// fails ONLY the usr_-prefixed one, driving the otherwise-dead user arm in both |
| 67 | +// revokePostgres and grantPostgres. |
| 68 | +func TestRevokeGrantPostgres_UserIdentArm(t *testing.T) { |
| 69 | + orig := validateIdent |
| 70 | + validateIdent = func(s string) error { |
| 71 | + // Pass the db_<token> identifier; fail the usr_<token> identifier so |
| 72 | + // the second guard's error return executes. |
| 73 | + if len(s) >= 4 && s[:4] == "usr_" { |
| 74 | + return errSeam |
| 75 | + } |
| 76 | + return nil |
| 77 | + } |
| 78 | + t.Cleanup(func() { validateIdent = orig }) |
| 79 | + |
| 80 | + r := &directResourceRevoker{customerDatabaseURL: "postgres://x:y@127.0.0.1:5432/z?sslmode=disable"} |
| 81 | + ctx := context.Background() |
| 82 | + |
| 83 | + if err := r.revokePostgres(ctx, "validtoken"); err == nil { |
| 84 | + t.Error("revokePostgres: want error from the user-identifier guard, got nil") |
| 85 | + } |
| 86 | + if err := r.grantPostgres(ctx, "validtoken"); err == nil { |
| 87 | + t.Error("grantPostgres: want error from the user-identifier guard, got nil") |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +// ── expire_imminent.go: jsonMarshal marshal-error fail-open arm ────────────── |
| 92 | +// |
| 93 | +// A map[string]any of primitive-only values never fails to marshal, so the |
| 94 | +// metadata_marshal_failed skip branch is unreachable in production. The |
| 95 | +// jsonMarshal seam returns an error, driving the per-row skip; no INSERT must |
| 96 | +// fire and the worker must NOT propagate the error (per-row failures are |
| 97 | +// logged, not returned — file contract). |
| 98 | +func TestExpireImminent_MarshalError_SkipsRow(t *testing.T) { |
| 99 | + orig := jsonMarshal |
| 100 | + jsonMarshal = func(v any) ([]byte, error) { return nil, errSeam } |
| 101 | + t.Cleanup(func() { jsonMarshal = orig }) |
| 102 | + |
| 103 | + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp)) |
| 104 | + if err != nil { |
| 105 | + t.Fatalf("sqlmock.New: %v", err) |
| 106 | + } |
| 107 | + defer db.Close() |
| 108 | + |
| 109 | + resourceID := uuid.New() |
| 110 | + token := uuid.New() |
| 111 | + teamID := uuid.New() |
| 112 | + expires := time.Now().UTC().Add(30 * time.Minute) |
| 113 | + |
| 114 | + // One eligible candidate. With jsonMarshal failing, the worker logs and |
| 115 | + // skips — NO INSERT is expected (sqlmock strict mode fails if one fires). |
| 116 | + mock.ExpectQuery(`FROM resources r`). |
| 117 | + WillReturnRows(sqlmock.NewRows([]string{ |
| 118 | + "id", "token", "team_id", "resource_type", "expires_at", "owner_email", |
| 119 | + }).AddRow(resourceID, token, teamID, "postgres", expires, "owner@example.com")) |
| 120 | + |
| 121 | + w := NewExpireImminentWorker(db) |
| 122 | + if err := w.Work(context.Background(), seamImminentJob()); err != nil { |
| 123 | + t.Fatalf("Work must fail-open on per-row marshal error, got %v", err) |
| 124 | + } |
| 125 | + if err := mock.ExpectationsWereMet(); err != nil { |
| 126 | + t.Errorf("unmet expectations (an INSERT fired despite marshal error?): %v", err) |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +// ── expiry_reminder_email.go: template.Execute fallback arms ───────────────── |
| 131 | +// |
| 132 | +// Both templates are validated at init by template.Must, so Execute can only |
| 133 | +// fail on a view-shape mismatch — unreachable while the view struct and |
| 134 | +// templates stay in sync. The seam swaps in templates whose Execute fails (a |
| 135 | +// method call on a field that errors), driving the html AND text Sprintf |
| 136 | +// fallback bodies. Both production templates are restored afterward. |
| 137 | +func TestRenderAnonExpiryEmail_TemplateExecuteFallback(t *testing.T) { |
| 138 | + origHTML := anonExpiryHTMLTmpl |
| 139 | + origText := anonExpiryTextTmpl |
| 140 | + t.Cleanup(func() { |
| 141 | + anonExpiryHTMLTmpl = origHTML |
| 142 | + anonExpiryTextTmpl = origText |
| 143 | + }) |
| 144 | + |
| 145 | + // A template that calls .Fail (a method that returns an error) forces |
| 146 | + // Execute to fail at render time. html/template propagates the method |
| 147 | + // error out of Execute. |
| 148 | + failHTML := template.Must(template.New("fail_html").Parse(`{{ .Fail }}`)) |
| 149 | + failText := textTemplate.Must(textTemplate.New("fail_text").Parse(`{{ .Fail }}`)) |
| 150 | + anonExpiryHTMLTmpl = failHTML |
| 151 | + anonExpiryTextTmpl = failText |
| 152 | + |
| 153 | + params := map[string]string{ |
| 154 | + "reminder_index": "2", |
| 155 | + "resource_type": "postgres", |
| 156 | + "hours_remaining": "6", |
| 157 | + "upgrade_url": "https://instanode.dev/app/billing?upgrade=hobby", |
| 158 | + } |
| 159 | + |
| 160 | + // The render still succeeds (never returns error) — the fallback Sprintf |
| 161 | + // bodies kick in. Verify they carry the core copy. |
| 162 | + subject, html, text := renderAnonExpiryEmailWithFailView(params) |
| 163 | + |
| 164 | + if subject == "" { |
| 165 | + t.Error("subject must be non-empty even when template Execute fails") |
| 166 | + } |
| 167 | + for _, want := range []string{"postgres", "6 hours", "https://instanode.dev/app/billing?upgrade=hobby"} { |
| 168 | + if !bytesContains(html, want) { |
| 169 | + t.Errorf("HTML fallback body missing %q\n--- BODY ---\n%s", want, html) |
| 170 | + } |
| 171 | + if !bytesContains(text, want) { |
| 172 | + t.Errorf("text fallback body missing %q\n--- BODY ---\n%s", want, text) |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +// renderAnonExpiryEmailWithFailView calls the production renderAnonExpiryEmail |
| 178 | +// but the swapped-in templates execute against the real anonExpiryView, which |
| 179 | +// has no .Fail method — so html/template's Execute returns an error and the |
| 180 | +// fallback fires. We don't change the view; the failing templates reference a |
| 181 | +// field/method the view lacks, which is exactly the "view-shape mismatch" |
| 182 | +// condition the fallback guards against. |
| 183 | +func renderAnonExpiryEmailWithFailView(params map[string]string) (string, string, string) { |
| 184 | + return renderAnonExpiryEmail(params) |
| 185 | +} |
| 186 | + |
| 187 | +func bytesContains(s, sub string) bool { |
| 188 | + return bytes.Contains([]byte(s), []byte(sub)) |
| 189 | +} |
| 190 | + |
| 191 | +// compile-time guard that the seam vars have the stdlib signatures so a future |
| 192 | +// refactor that changes the production binding shape also breaks this test. |
| 193 | +var ( |
| 194 | + _ = json.Marshal |
| 195 | + _ = sql.Open |
| 196 | +) |
0 commit comments