File size: 21,851 Bytes
56838f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 | import { convexTest } from "convex-test";
import { describe, expect, test } from "vitest";
import schema from "../schema";
import { api, internal } from "../_generated/api";
const modules = import.meta.glob("../**/*.ts");
const USER = { subject: "user-tests-alertrules", tokenIdentifier: "clerk|user-tests-alertrules" };
const VARIANT = "full";
/**
* Seed a PRO entitlement for the test user. Required before invoking any
* public alertRules mutation (setAlertRules, setDigestSettings, setQuietHours)
* β those now gate on `assertProEntitlement`. Without this seed, every
* pre-existing test would fail with PRO_REQUIRED because convex-test starts
* with an empty `entitlements` table.
*
* Call at the start of any test that uses a public mutation OR that
* exercises setNotificationConfigForUser via the HTTP path.
*/
async function seedProEntitlement(
t: ReturnType<typeof convexTest>,
userId = USER.subject,
validUntil = Date.now() + 30 * 24 * 60 * 60 * 1000,
) {
await t.run(async (ctx) => {
await ctx.db.insert("entitlements", {
userId,
planKey: "pro_monthly",
features: {
tier: 1,
maxDashboards: 10,
apiAccess: true,
apiRateLimit: 1000,
prioritySupport: true,
exportFormats: ["json", "csv"],
},
validUntil,
updatedAt: Date.now(),
});
});
}
// ---------------------------------------------------------------------------
// Cross-field invariant: realtime is for `critical`-tier events only.
// Both `(realtime, all)` and `(realtime, high)` are forbidden.
// See docs/archive/plans/forbid-realtime-all-events.md.
// ---------------------------------------------------------------------------
describe("alertRules β realtime+non-critical cross-field invariant", () => {
test("setAlertRules({sensitivity:'all'}) against existing realtime row β throws", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
const asUser = t.withIdentity(USER);
// Seed an existing row in realtime mode with critical sensitivity (compatible
// under the tightened rule β only 'critical' is allowed alongside realtime).
await asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "critical",
channels: [],
});
// Attempting to widen to 'all' must throw INCOMPATIBLE_DELIVERY.
await expect(
asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
}),
).rejects.toThrow(/INCOMPATIBLE_DELIVERY|Real-time delivery is for Critical/i);
});
test("setAlertRules({sensitivity:'high'}) against existing realtime row β throws (tightened rule)", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
const asUser = t.withIdentity(USER);
// Seed compatible realtime+critical state.
await asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "critical",
channels: [],
});
// Attempting to widen to 'high' is now ALSO forbidden β was allowed under
// the previous rule, tightened 2026-04-27.
await expect(
asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "high",
channels: [],
}),
).rejects.toThrow(/INCOMPATIBLE_DELIVERY|Real-time delivery is for Critical/i);
});
test("setAlertRules({sensitivity:'all'}) against existing daily-digest row β succeeds", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
const asUser = t.withIdentity(USER);
// Seed a daily-digest row.
await asUser.mutation(api.alertRules.setDigestSettings, {
variant: VARIANT,
digestMode: "daily",
digestHour: 8,
digestTimezone: "UTC",
});
await asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
});
const rows = await asUser.query(api.alertRules.getAlertRules, {});
expect(rows.find((r) => r.variant === VARIANT)?.sensitivity).toBe("all");
expect(rows.find((r) => r.variant === VARIANT)?.digestMode).toBe("daily");
});
test("setDigestSettings({digestMode:'realtime'}) against existing sensitivity:'all' digest β throws", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
const asUser = t.withIdentity(USER);
await asUser.mutation(api.alertRules.setDigestSettings, {
variant: VARIANT,
digestMode: "daily",
});
await asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
});
await expect(
asUser.mutation(api.alertRules.setDigestSettings, {
variant: VARIANT,
digestMode: "realtime",
}),
).rejects.toThrow(/INCOMPATIBLE_DELIVERY|Real-time delivery is for Critical/i);
});
test("setDigestSettings({digestMode:'daily'}) against existing sensitivity:'all' realtime β succeeds, sensitivity preserved", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
const asUser = t.withIdentity(USER);
// Seed via direct insert to bypass the validators (simulates pre-migration row).
await t.run(async (ctx) => {
await ctx.db.insert("alertRules", {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
updatedAt: Date.now(),
// digestMode absent β effective 'realtime'
});
});
await asUser.mutation(api.alertRules.setDigestSettings, {
variant: VARIANT,
digestMode: "daily",
digestHour: 8,
digestTimezone: "UTC",
});
const rows = await asUser.query(api.alertRules.getAlertRules, {});
const row = rows.find((r) => r.variant === VARIANT);
expect(row?.digestMode).toBe("daily");
expect(row?.sensitivity).toBe("all");
});
});
// ---------------------------------------------------------------------------
// Insert-only default: sensitivity:'critical' on fresh insert ONLY (under the
// tightened rule, was 'high' before 2026-04-27). Patch path must NEVER silently
// rewrite an existing row's
// sensitivity when the caller omits the field.
// ---------------------------------------------------------------------------
describe("alertRules β insert-only default for sensitivity", () => {
test("setAlertRulesForUser with no existing row, sensitivity omitted β defaults to 'critical'", async () => {
const t = convexTest(schema, modules);
await t.mutation(internal.alertRules.setAlertRulesForUser, {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: [],
// sensitivity intentionally omitted
channels: [],
});
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
// Under the tightened rule (2026-04-27), realtime insert default is 'critical'
// not 'high' β only 'critical' is compatible with the implicit realtime mode.
expect(rows[0]?.sensitivity).toBe("critical");
});
test("setAlertRulesForUser with existing daily+all row, sensitivity omitted β preserves 'all'", async () => {
// The patch-vs-insert subtlety: omitted sensitivity on a digest user must NOT
// silently narrow to 'high'. This is the regression Codex flagged in round 3.
const t = convexTest(schema, modules);
await t.run(async (ctx) => {
await ctx.db.insert("alertRules", {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
digestMode: "daily",
digestHour: 8,
digestTimezone: "UTC",
updatedAt: Date.now(),
});
});
await t.mutation(internal.alertRules.setAlertRulesForUser, {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: ["something"],
// sensitivity omitted β must be preserved
channels: ["email"],
});
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
expect(rows[0]?.sensitivity).toBe("all");
expect(rows[0]?.digestMode).toBe("daily");
expect(rows[0]?.eventTypes).toEqual(["something"]);
});
test("setQuietHoursForUser with no existing row β inserts with sensitivity:'critical', not 'all'/'high'", async () => {
const t = convexTest(schema, modules);
await t.mutation(internal.alertRules.setQuietHoursForUser, {
userId: USER.subject,
variant: VARIANT,
quietHoursEnabled: true,
quietHoursStart: 22,
quietHoursEnd: 7,
quietHoursTimezone: "UTC",
});
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
expect(rows[0]?.sensitivity).toBe("critical");
});
test("setQuietHoursForUser does NOT throw on pre-migration forbidden row (Greptile P1)", async () => {
// Before fix: assertCompatibleDeliveryMode was called on every quiet-hours
// save, so pre-migration (realtime, all) rows would fail with INCOMPATIBLE_DELIVERY
// β generic 500 (no passthrough on set-quiet-hours HTTP action). Quiet-hours
// updates on a forbidden row must succeed because they don't touch the pair.
const t = convexTest(schema, modules);
await t.run(async (ctx) => {
await ctx.db.insert("alertRules", {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
// digestMode absent β effective 'realtime' (forbidden pair)
updatedAt: Date.now(),
});
});
await t.mutation(internal.alertRules.setQuietHoursForUser, {
userId: USER.subject,
variant: VARIANT,
quietHoursEnabled: true,
quietHoursStart: 22,
quietHoursEnd: 7,
quietHoursTimezone: "UTC",
});
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
expect(rows[0]?.quietHoursEnabled).toBe(true);
expect(rows[0]?.quietHoursStart).toBe(22);
// Sensitivity preserved β no silent migration via this path.
expect(rows[0]?.sensitivity).toBe("all");
});
});
// ---------------------------------------------------------------------------
// Atomic mutation: setNotificationConfigForUser handles pair-flip transitions
// that the legacy two-call sequence races against.
// ---------------------------------------------------------------------------
describe("alertRules β setNotificationConfigForUser atomic pair update", () => {
test("rejects (realtime, all) atomically", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
await expect(
t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
digestMode: "realtime",
sensitivity: "all",
}),
).rejects.toThrow(/INCOMPATIBLE_DELIVERY|Real-time delivery is for Critical/i);
});
test("daily+all β realtime+critical lands atomically (no race) β tightened rule requires critical", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
// Seed daily+all (the legitimate prior state).
await t.run(async (ctx) => {
await ctx.db.insert("alertRules", {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "all",
channels: [],
digestMode: "daily",
digestHour: 8,
digestTimezone: "UTC",
updatedAt: Date.now(),
});
});
await t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
digestMode: "realtime",
sensitivity: "critical",
});
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
expect(rows[0]?.digestMode).toBe("realtime");
expect(rows[0]?.sensitivity).toBe("critical");
});
test("setNotificationConfigForUser({digestMode:'realtime', sensitivity:'high'}) β throws (tightened rule)", async () => {
// The tightened rule (2026-04-27) forbids realtime+high alongside realtime+all.
const t = convexTest(schema, modules);
await seedProEntitlement(t);
await expect(
t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
digestMode: "realtime",
sensitivity: "high",
}),
).rejects.toThrow(/INCOMPATIBLE_DELIVERY|Real-time delivery is for Critical/i);
});
test("partial update {enabled:true} against existing forbidden row β throws (re-validation)", async () => {
// Existing row in forbidden state (e.g. pre-migration). Partial update that
// doesn't touch the pair must still reject because the pair derived from
// existing+incoming is still forbidden.
const t = convexTest(schema, modules);
await seedProEntitlement(t);
await t.run(async (ctx) => {
await ctx.db.insert("alertRules", {
userId: USER.subject,
variant: VARIANT,
enabled: false,
eventTypes: [],
sensitivity: "all",
channels: [],
// digestMode absent β effective 'realtime'
updatedAt: Date.now(),
});
});
await expect(
t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
enabled: true,
// no digestMode/sensitivity in args β but existing pair is forbidden
}),
).rejects.toThrow(/INCOMPATIBLE_DELIVERY|Real-time delivery is for Critical/i);
});
test("free user (no entitlement) calling setNotificationConfigForUser β throws PRO_REQUIRED", async () => {
// Layer-2 gate: setNotificationConfigForUser is reachable from the public
// `/set-notification-config` HTTP action; a free-tier user hitting that
// endpoint must be rejected at the mutation, not just by the relay.
//
// Note on identity context: unlike the public `setAlertRules` /
// `setDigestSettings` mutations (which derive `userId` from `ctx.auth`),
// `setNotificationConfigForUser` takes `userId` as an arg β the HTTP
// action sets it from the verified Clerk JWT. The entitlement check
// reads the arg-supplied userId, so a `t.withIdentity(...)` wrapper is
// intentionally absent from these tests.
const t = convexTest(schema, modules);
// Deliberately NO seedProEntitlement β the user is free.
await expect(
t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
digestMode: "daily",
sensitivity: "high",
}),
).rejects.toThrow(/PRO_REQUIRED|Notifications are a PRO feature/i);
});
test("expired entitlement (validUntil < now) β throws PRO_REQUIRED", async () => {
// Mirrors entitlements.ts FREE_TIER_DEFAULTS fallback: an expired
// entitlement is treated identically to no entitlement. The mutation gate
// must apply the same semantics.
const t = convexTest(schema, modules);
await seedProEntitlement(t, USER.subject, Date.now() - 1000); // expired 1s ago
await expect(
t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
digestMode: "daily",
sensitivity: "high",
}),
).rejects.toThrow(/PRO_REQUIRED|Notifications are a PRO feature/i);
});
test("omitted sensitivity on patch preserves existing value", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
await t.run(async (ctx) => {
await ctx.db.insert("alertRules", {
userId: USER.subject,
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "critical",
channels: [],
digestMode: "daily",
digestHour: 8,
digestTimezone: "UTC",
updatedAt: Date.now(),
});
});
await t.mutation(internal.alertRules.setNotificationConfigForUser, {
userId: USER.subject,
variant: VARIANT,
digestHour: 14, // unrelated change
});
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
expect(rows[0]?.sensitivity).toBe("critical");
expect(rows[0]?.digestHour).toBe(14);
});
});
// ---------------------------------------------------------------------------
// Layer-2 entitlement gate: public mutations reject free-tier callers.
// (Discovered 2026-04-28: 7 of 28 enabled alertRules rows belonged to
// free-tier users despite the UI paywall β the relay's PRO filter has been
// silently masking the bug at delivery time. This gate is the primary
// defense at write time.)
// ---------------------------------------------------------------------------
describe("alertRules β layer-2 entitlement gate (PRO_REQUIRED)", () => {
test("setAlertRules from a free-tier user β throws PRO_REQUIRED", async () => {
const t = convexTest(schema, modules);
// No seedProEntitlement β the user has no entitlement row, treated as free.
const asFreeUser = t.withIdentity(USER);
await expect(
asFreeUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "critical",
channels: [],
}),
).rejects.toThrow(/PRO_REQUIRED|Notifications are a PRO feature/i);
});
test("setDigestSettings from a free-tier user β throws PRO_REQUIRED", async () => {
const t = convexTest(schema, modules);
const asFreeUser = t.withIdentity(USER);
await expect(
asFreeUser.mutation(api.alertRules.setDigestSettings, {
variant: VARIANT,
digestMode: "daily",
digestHour: 8,
digestTimezone: "UTC",
}),
).rejects.toThrow(/PRO_REQUIRED|Notifications are a PRO feature/i);
});
test("setQuietHours from a free-tier user β throws PRO_REQUIRED", async () => {
const t = convexTest(schema, modules);
const asFreeUser = t.withIdentity(USER);
await expect(
asFreeUser.mutation(api.alertRules.setQuietHours, {
variant: VARIANT,
quietHoursEnabled: true,
quietHoursStart: 22,
quietHoursEnd: 7,
quietHoursTimezone: "UTC",
}),
).rejects.toThrow(/PRO_REQUIRED|Notifications are a PRO feature/i);
});
test("setAlertRules with expired entitlement β throws PRO_REQUIRED", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t, USER.subject, Date.now() - 1000); // expired
const asUser = t.withIdentity(USER);
await expect(
asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "critical",
channels: [],
}),
).rejects.toThrow(/PRO_REQUIRED|Notifications are a PRO feature/i);
});
test("setAlertRules with PRO entitlement β succeeds (control)", async () => {
const t = convexTest(schema, modules);
await seedProEntitlement(t);
const asUser = t.withIdentity(USER);
await asUser.mutation(api.alertRules.setAlertRules, {
variant: VARIANT,
enabled: true,
eventTypes: [],
sensitivity: "critical",
channels: [],
});
const rows = await asUser.query(api.alertRules.getAlertRules, {});
expect(rows).toHaveLength(1);
});
test("INTENTIONAL: setAlertRulesForUser internal mutation stays UNGATED for operator/migration paths", async () => {
// The *ForUser internal mutations are reachable only via `npx convex run`
// (deploy-key auth) or trusted server-side code paths. They are intentionally
// NOT entitlement-gated so operator cleanup scripts (e.g. disabling
// notifications for free users that got rows in via a UI-gate hole) can
// still run. The HTTP-reachable setNotificationConfigForUser IS gated;
// see its dedicated tests above.
const t = convexTest(schema, modules);
// No seedProEntitlement β free user.
await t.mutation(internal.alertRules.setAlertRulesForUser, {
userId: USER.subject,
variant: VARIANT,
enabled: false,
eventTypes: [],
sensitivity: "critical",
channels: [],
});
// No throw expected β operator cleanup write succeeded against a free user.
const rows = await t.run(async (ctx) =>
ctx.db
.query("alertRules")
.withIndex("by_user_variant", (q) => q.eq("userId", USER.subject).eq("variant", VARIANT))
.collect(),
);
expect(rows).toHaveLength(1);
expect(rows[0]?.enabled).toBe(false);
});
});
|