Files
Jyotisha/frontend/tests/database-redeem-code-kinds-330.test.ts
T
ClaudeandClaude Opus 5.5 5a1b08ad1e
Independent Staging Quality Gate / validate-python (push) Failing after 8m33s
Independent Staging Quality Gate / validate-frontend (push) Successful in 12m49s
Independent Staging Quality Gate / publish (push) Skipped
test: gate 8376 follow-ups — column-level admin grant check; the layer test ignores VedAstro-dependent fields
redemption_code_uses is granted to admin_runtime per column, so the
table-level privilege check is false by design; check any-column and that
credit_transaction_id stays hidden. The native-layer comparison now also
drops VedAstro/official fields, whose external result and cache timing can
differ between two runs after the BUG-2172 echo check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-22 18:31:46 +08:00

176 lines
10 KiB
TypeScript

import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import test from "node:test";
import {
closeLocalPostgresDataPools,
createLocalPostgresDataClient,
} from "../src/lib/db/local-postgres-client-core.ts";
import { startPostgresFixture } from "./helpers/postgres-fixture.ts";
// #330 (owner 2026-11-22): campaign codes (many users, each once, start time,
// cap), single codes (one redemption), batches of single codes, prefix-free
// random codes hashed after normalisation, old exact-hash codes still
// redeeming, and per-code success content. Needs Docker (test:db).
const runnerPath = fileURLToPath(new URL("../scripts/db-migrate.mjs", import.meta.url));
function dockerAvailable(): boolean {
return spawnSync("docker", ["version", "--format", "{{.Server.Version}}"], { encoding: "utf8", stdio: "ignore" }).status === 0;
}
function hash(code: string): string {
return createHash("sha256").update(code, "utf8").digest("hex");
}
function normalized(code: string): string {
return hash(code.replace(/[\s-]/g, "").toUpperCase());
}
type RedeemRow = {
success: boolean;
credits: number | null;
awarded_credits: number | null;
error_code: string | null;
success_title: string | null;
success_message: string | null;
success_style: string | null;
};
test("redeem code kinds: campaign cap under concurrency, once per user, window, revoke, legacy and new hashes", { skip: dockerAvailable() ? false : "docker unavailable on this host" }, async () => {
const fixture = startPostgresFixture();
try {
const migration = spawnSync(process.execPath, [runnerPath], {
encoding: "utf8",
env: {
...process.env,
SCHEMA_DATABASE_URL: fixture.connectionUrl("schema_owner", "schema-owner-test-password"),
},
});
assert.equal(migration.status, 0, migration.stderr);
assert.match(migration.stdout, /applied 20261122140000_redemption_code_kinds\.sql/);
const emails = Array.from({ length: 6 }, (_, index) => `kinds-${index}@example.com`);
fixture.psqlAs("identity_runtime", "identity-runtime-test-password", `
insert into identity.users (name, email, email_verified, email_verified_at)
values ${emails.map((email, index) => `('User ${index}', '${email}', true, now())`).join(",")}
`);
const ids = emails.map((email) => fixture.psql(`select id from identity.users where email = '${email}'`));
const clients = ids.map((id, index) =>
createLocalPostgresDataClient(
fixture.connectionUrl("app_runtime", "app-runtime-test-password"),
{ id, email: emails[index] },
));
const redeem = async (index: number, code: string) =>
((await clients[index].rpc("redeem_code_v2", {
p_code_hash: hash(code),
p_normalized_hash: normalized(code),
})).data as RedeemRow[])[0];
// A campaign code with a cap of 3 and its own success content.
fixture.psql(`
insert into public.redemption_codes (code_hash, code_mask, credits, kind, campaign_name, max_redemptions,
success_title, success_message, success_style)
values ('${normalized("SPRING2026")}', 'SPRING2026', 50, 'campaign', '春季活动', 3,
'春天快乐', '送你 50 点', 'stars')
`);
// 1) Six users race for a cap of 3: exactly 3 succeed, the rest see exhausted.
const raced = await Promise.all(ids.map((_, index) => redeem(index, index % 2 ? "spring-2026" : "SPRING2026")));
assert.equal(raced.filter((row) => row.success).length, 3);
assert.equal(raced.filter((row) => row.error_code === "exhausted").length, 3);
assert.equal(fixture.psql("select redemption_count from public.redemption_codes where code_mask='SPRING2026'"), "3");
assert.equal(fixture.psql("select count(*) from public.redemption_code_uses u join public.redemption_codes c on c.id=u.code_id where c.code_mask='SPRING2026'"), "3");
const winner = raced.find((row) => row.success)!;
assert.deepEqual(
[winner.awarded_credits, winner.success_title, winner.success_message, winner.success_style],
[50, "春天快乐", "送你 50 点", "stars"],
);
// exhausted is not a guessing failure
assert.equal(fixture.psql("select count(*) from public.redemption_attempts"), "0");
// 2) Once per user, even while the cap has room.
fixture.psql(`
insert into public.redemption_codes (code_hash, code_mask, credits, kind, campaign_name)
values ('${normalized("OPEN2026")}', 'OPEN2026', 10, 'campaign', '不限量活动')
`);
assert.equal((await redeem(0, "open2026")).success, true);
const twice = await redeem(0, "OPEN-2026");
assert.equal(twice.error_code, "already_redeemed_by_you");
assert.equal(fixture.psql(`select count(*) from public.credit_transactions where user_id='${ids[0]}' and redemption_code_id = (select id from public.redemption_codes where code_mask='OPEN2026')`), "1");
assert.equal(fixture.psql(`select count(*) from public.redemption_attempts where user_id='${ids[0]}'`), "0");
// 3) Start time and end time.
fixture.psql(`
insert into public.redemption_codes (code_hash, code_mask, credits, kind, campaign_name, starts_at, expires_at)
values ('${normalized("LATER2026")}', 'LATER2026', 10, 'campaign', '未开始', now() + interval '1 day', now() + interval '2 days'),
('${normalized("GONE2026")}', 'GONE2026', 10, 'campaign', '已结束', now() - interval '2 days', now() - interval '1 day')
`);
assert.equal((await redeem(1, "LATER2026")).error_code, "not_started");
assert.equal((await redeem(1, "GONE2026")).error_code, "expired_code");
// 4) Revoked campaign code.
fixture.psql(`
insert into public.redemption_codes (code_hash, code_mask, credits, kind, campaign_name, revoked_at, revoked_by)
values ('${normalized("STOP2026")}', 'STOP2026', 10, 'campaign', '撤销', now(), '${ids[5]}')
`);
assert.equal((await redeem(2, "STOP2026")).error_code, "revoked_code");
// 5) A new random single code: typed with or without the dash, in any case; once only.
fixture.psql(`
insert into public.redemption_codes (code_hash, code_mask, credits)
values ('${normalized("K7QM-2HXP")}', 'K7QM-****', 7)
`);
const single = await redeem(3, "k7qm2hxp");
assert.deepEqual([single.success, single.awarded_credits, single.success_title, single.success_style], [true, 7, null, "default"]);
assert.equal((await redeem(3, "K7QM-2HXP")).error_code, "already_redeemed_by_you");
assert.equal((await redeem(4, "K7QM-2HXP")).error_code, "already_redeemed");
// 6) An old JYOTISH-XXXX-XXXX code (exact hash) still redeems, and the old
// one-argument entry point keeps its result shape.
fixture.psql(`
insert into public.redemption_codes (code_hash, code_mask, credits)
values ('${hash("JYOTISH-OLDC-ABCD")}', 'JYOTISH-****-ABCD', 9)
`);
const legacy = await clients[4].rpc("redeem_code", { p_code_hash: hash("JYOTISH-OLDC-ABCD") });
// 原值 credits: 9;新值:兑换后余额 = 兑换前余额 + 9;原因:credits 是兑换后的余额(旧合同),这个用户前面已经兑过别的码。
const balanceAfter = Number(fixture.psql(`select credits from public.profiles where id='${ids[4]}'`));
assert.deepEqual(legacy.data, [{ success: true, credits: balanceAfter, awarded_credits: 9, error_code: null }]);
// The old entry point keeps the old wording for a reused single code (no per-user variant).
const legacyAgain = await clients[4].rpc("redeem_code", { p_code_hash: hash("JYOTISH-OLDC-ABCD") });
assert.deepEqual(legacyAgain.data, [{ success: false, credits: null, awarded_credits: null, error_code: "already_redeemed" }]);
assert.equal(fixture.psql("select count(*) from public.redemption_code_uses u join public.redemption_codes c on c.id=u.code_id where c.code_mask='JYOTISH-****-ABCD'"), "1");
// 7) Constraints: a campaign code cannot carry a single redemption, a single code cannot carry a cap,
// the success fields are bounded, and the old exact-text mask rule still holds for single codes.
const violation = (sql: string) => {
try {
fixture.psql(sql);
return false;
} catch {
return true;
}
};
assert.equal(violation(`insert into public.redemption_codes (code_hash, code_mask, credits, max_redemptions) values ('${"1".repeat(64)}', 'ABCD-****', 1, 5)`), true);
assert.equal(violation(`insert into public.redemption_codes (code_hash, code_mask, credits, kind, success_title) values ('${"2".repeat(64)}', 'TITLELONG1', 1, 'campaign', '${"字".repeat(21)}')`), true);
assert.equal(violation(`insert into public.redemption_codes (code_hash, code_mask, credits, kind, success_style) values ('${"3".repeat(64)}', 'STYLE2026', 1, 'campaign', 'fireworks')`), true);
assert.equal(violation(`insert into public.redemption_codes (code_hash, code_mask, credits) values ('${"4".repeat(64)}', 'free text', 1)`), true);
// 8) Grants: app users call the functions, never the tables.
assert.equal(fixture.psql("select has_function_privilege('authenticated', 'public.redeem_code_v2(text, text)', 'execute')"), "t");
assert.equal(fixture.psql("select has_function_privilege('anon', 'public.redeem_code_v2(text, text)', 'execute')"), "f");
assert.equal(fixture.psql("select has_table_privilege('authenticated', 'public.redemption_code_uses', 'select')"), "f");
assert.equal(fixture.psql("select has_table_privilege('app_runtime', 'public.redemption_code_uses', 'insert')"), "f");
// 原值 has_table_privilege(… 'select') = t;新值 has_any_column_privilege;原因:迁移按列授权给 admin_runtime(不含 credit_transaction_id),表级 select 判定为 f。
assert.equal(fixture.psql("select has_any_column_privilege('admin_runtime', 'public.redemption_code_uses', 'select')"), "t");
assert.equal(fixture.psql("select has_column_privilege('admin_runtime', 'public.redemption_code_uses', 'credit_transaction_id', 'select')"), "f");
assert.equal(fixture.psql("select 'redemption_code_uses' = any(public.account_deletion_kept_tables())"), "t");
// The per-code uniqueness moved off the ledger column.
assert.equal(fixture.psql("select count(*) from pg_constraint where conname = 'credit_transactions_redemption_code_id_key'"), "0");
} finally {
await closeLocalPostgresDataPools();
fixture.stop();
}
});