import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import path from "node:path"; import { domainToASCII, fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { readBaselineLegacyMigration } from "./baseline-legacy-migration.test-helper"; const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); const capabilitySql = readFileSync(path.join(packageRoot, "prisma/rls/portal-domain-capabilities.sql"), "utf8"); const reclaimMigrationSql = readBaselineLegacyMigration("20260717050000_va_p26_domain_claim_expiry_reclaim"); const tldtsPackage = JSON.parse(readFileSync(path.join(packageRoot, "apps/web/node_modules/tldts/package.json"), "utf8")) as { version: string }; const tldtsTrieSource = readFileSync(path.join(packageRoot, "apps/web/node_modules/tldts/src/data/trie.ts"), "utf8"); function functionBody(name: string, nextMarker: string): string { const start = capabilitySql.indexOf(`CREATE OR REPLACE FUNCTION public.${name}`); const end = capabilitySql.indexOf(nextMarker, start); expect(start).toBeGreaterThanOrEqual(0); expect(end).toBeGreaterThan(start); return capabilitySql.slice(start, end); } function numericArray(name: string): number[] { const body = new RegExp(`export const ${name}[^\\[]*\\[([^\\]]*)\\]`, "su").exec(tldtsTrieSource)?.[1]; if (!body) throw new Error(`Missing tldts trie array: ${name}`); return [...body.matchAll(/\d+/gu)].map((match) => Number(match[0])); } function scalar(name: string): number { const value = new RegExp(`export const ${name} = (\\d+);`, "u").exec(tldtsTrieSource)?.[1]; if (!value) throw new Error(`Missing tldts trie scalar: ${name}`); return Number(value); } function icannRules(rootName: "rulesRoot" | "exceptionsRoot"): string[] { const nodeFlags = numericArray("nodeFlags"); const edgeStart = numericArray("edgeStart"); const edgeLength = numericArray("edgeLength"); const edgeChild = numericArray("edgeChild"); const encodedLabelText = /export const labelText = ("(?:[^"\\]|\\.)*");/su.exec(tldtsTrieSource)?.[1]; if (!encodedLabelText) throw new Error("Missing tldts trie label text"); const labelText = JSON.parse(encodedLabelText) as string; const edgeOffset: number[] = []; let offset = 0; for (const length of edgeLength) { edgeOffset.push(offset); offset += length; } const rules: string[] = []; const visit = (node: number, pathLabels: readonly string[]): void => { for (let edge = edgeStart[node] ?? 0; edge < (edgeStart[node + 1] ?? 0); edge += 1) { const child = edgeChild[edge]; const start = edgeOffset[edge]; const length = edgeLength[edge]; if (child === undefined || start === undefined || length === undefined) throw new Error("Malformed tldts trie edge"); const nextPath = [...pathLabels, labelText.slice(start, start + length)]; if (((nodeFlags[child] ?? 0) & 1) !== 0) rules.push([...nextPath].reverse().join(".")); visit(child, nextPath); } }; visit(scalar(rootName), []); return rules.sort(); } function asciiIcannRule(rule: string): string { const wildcard = rule.startsWith("*."); const asciiRule = domainToASCII(wildcard ? rule.slice(2) : rule); if (!asciiRule || !/^[a-z0-9.-]+$/u.test(asciiRule)) throw new Error(`Cannot normalize ICANN rule: ${rule}`); return wildcard ? `*.${asciiRule}` : asciiRule; } function sqlSnapshot(tag: "icann_exact" | "icann_wildcard" | "icann_exception"): string[] { const body = new RegExp(`\\$${tag}\\$\\n([\\s\\S]*?)\\n\\$${tag}\\$`, "u").exec(capabilitySql)?.[1]; if (!body) throw new Error(`Missing SQL ICANN snapshot: ${tag}`); return body.split("\n").filter(Boolean); } describe("portal custom-domain RLS capabilities", () => { it("ships the canonical claim capability through a new forward-only migration", () => { const startMarker = "CREATE OR REPLACE FUNCTION public.hivegrid_portal_claim_hostname"; const endMarker = "GRANT EXECUTE ON FUNCTION public.hivegrid_portal_claim_hostname(text,text,text,text,text,timestamptz,text,timestamptz,text) TO hivegrid_app;"; const canonicalStart = capabilitySql.indexOf(startMarker); const migrationStart = reclaimMigrationSql.indexOf(startMarker); const canonicalEnd = capabilitySql.indexOf(endMarker, canonicalStart) + endMarker.length; const migrationEnd = reclaimMigrationSql.indexOf(endMarker, migrationStart) + endMarker.length; expect(canonicalStart).toBeGreaterThanOrEqual(0); expect(migrationStart).toBeGreaterThanOrEqual(0); expect(canonicalEnd).toBeGreaterThan(canonicalStart); expect(migrationEnd).toBeGreaterThan(migrationStart); expect(reclaimMigrationSql.slice(migrationStart, migrationEnd)).toBe(capabilitySql.slice(canonicalStart, canonicalEnd)); expect(reclaimMigrationSql).toContain('GRANT SELECT ON "TenantSubscription", "TenantProductAcquisition", "SubscriptionProduct" TO hivegrid_rls_definer;'); expect(reclaimMigrationSql).toContain('REVOKE SELECT ON "TenantProductAcquisition" FROM hivegrid_rls_definer;'); expect(reclaimMigrationSql).toContain('REVOKE SELECT ON "SubscriptionProduct" FROM hivegrid_rls_definer;'); expect(reclaimMigrationSql).not.toContain('REVOKE SELECT ON "TenantSubscription" FROM hivegrid_rls_definer;'); expect(reclaimMigrationSql).toContain("Inverse SQL (manual coordinated rollback only)"); }); it("keeps the artifact transactional, hardened, migrations-only input", () => { expect(capabilitySql).toContain("This file is reviewed merge-migration input"); expect(capabilitySql).toContain("BEGIN;"); expect(capabilitySql).toContain("COMMIT;"); expect(capabilitySql).toContain("pg_has_role(current_user, 'hivegrid_rls_definer', 'MEMBER')"); expect(capabilitySql.match(/SECURITY DEFINER/g)).toHaveLength(2); expect(capabilitySql.match(/SET search_path = pg_catalog, public/g)).toHaveLength(3); expect(capabilitySql.match(/SET row_security = off/g)).toHaveLength(2); expect(capabilitySql).not.toMatch(/GRANT (?:SELECT|INSERT|UPDATE|DELETE).* TO hivegrid_(?:app|worker);/u); expect(capabilitySql).toContain("REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;"); expect(capabilitySql.indexOf("RESET ROLE;")).toBeLessThan( capabilitySql.indexOf("REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;") ); expect(capabilitySql.indexOf("REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;")).toBeLessThan( capabilitySql.indexOf("COMMIT;") ); }); it("pins the complete application ICANN public-suffix policy into the database claim boundary", () => { const trieDigest = createHash("sha256").update(tldtsTrieSource).digest("hex"); // tldts carries both Unicode and A-label spellings for current IDN rules. // The application always calls domainToASCII before parse(), so compare the // SQL snapshot with the normalized full trie rather than silently dropping // non-ASCII entries. const trieRules = icannRules("rulesRoot"); const allRules = [...new Set(trieRules.map(asciiIcannRule))].sort(); const exactRules = allRules.filter((rule) => !rule.startsWith("*.")); const wildcardBases = allRules.filter((rule) => rule.startsWith("*.")).map((rule) => rule.slice(2)).sort(); const exceptionRules = [...new Set(icannRules("exceptionsRoot").map(asciiIcannRule))].sort(); expect(capabilitySql).toContain(`tldts ${tldtsPackage.version} (ICANN-only PSL)`); expect(capabilitySql).toContain(trieDigest); expect(sqlSnapshot("icann_exact")).toEqual(exactRules); expect(sqlSnapshot("icann_wildcard")).toEqual(wildcardBases); expect(sqlSnapshot("icann_exception")).toEqual(exceptionRules); expect(trieRules.some((rule) => /[^\x00-\x7F]/u.test(rule))).toBe(true); expect(exactRules).toHaveLength(6_909); expect(wildcardBases).toHaveLength(16); expect(exceptionRules).toHaveLength(8); const startMarker = "CREATE OR REPLACE FUNCTION public.hivegrid_portal_hostname_is_icann_subdomain"; const endMarker = "REVOKE ALL ON FUNCTION public.hivegrid_portal_hostname_is_icann_subdomain(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_portal, hivegrid_authentik_jit;"; const canonicalStart = capabilitySql.indexOf(startMarker); const migrationStart = reclaimMigrationSql.indexOf(startMarker); const canonicalEnd = capabilitySql.indexOf(endMarker, canonicalStart) + endMarker.length; const migrationEnd = reclaimMigrationSql.indexOf(endMarker, migrationStart) + endMarker.length; expect(reclaimMigrationSql.slice(migrationStart, migrationEnd)).toBe(capabilitySql.slice(canonicalStart, canonicalEnd)); const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); expect(claim).toContain("NOT public.hivegrid_portal_hostname_is_icann_subdomain(p_hostname)"); expect(claim).not.toContain("p_hostname LIKE '%.localhost'"); expect(capabilitySql).toContain("'app.hivegrid.de'"); expect(capabilitySql).toContain("p_hostname LIKE '%.internal'"); expect(capabilitySql).toContain("label !~ '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$'"); }); it("binds the global claim to a real active portal administrator", () => { const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); expect(claim).toContain("session_user <> 'hivegrid_app'"); expect(claim).toContain("current_setting('app.tenant_id', true)"); expect(claim).toContain("current_setting('app.user_id', true)"); expect(claim).toContain("current_setting('app.portal_session_id', true)"); expect(claim).toContain("current_setting('app.public_knowledge_base_id', true)"); expect(claim).toContain("current_setting('app.platform_analytics', true)"); expect(claim).toContain('membership."status" = 2'); expect(claim).toContain('actor."active" = true'); expect(claim).toContain("permission.\"name\" = 'portal.admin'"); expect(claim).toContain('portal."isPublished" = true'); expect(claim).toContain("p_requested_at < CURRENT_TIMESTAMP - INTERVAL '5 minutes'"); expect(claim).toContain("p_verification_token_hash IS NULL"); expect(claim).toContain("p_verification_token_expires_at IS NULL"); expect(claim).toContain("p_requested_at IS NULL"); expect(claim).not.toContain("p_verification_token_hash, p_verification_token_hash"); }); it("serializes hostname and idempotency races and stores only a proof hash", () => { const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); expect(claim).toContain("pg_advisory_xact_lock(hashtextextended('portal-domain-portal:'"); expect(claim).toContain("pg_advisory_xact_lock(hashtextextended('portal-domain-idempotency:'"); expect(claim).toContain("pg_advisory_xact_lock(hashtextextended('portal-domain-hostname:'"); expect(claim).toContain('"verificationTokenHash"'); expect(claim).toContain("p_verification_token_hash !~ '^[a-f0-9]{64}$'"); expect(claim).not.toMatch(/verificationTokenValue|txtRecordValue|verification[_ ]?token[^_ ]+\s+text/iu); expect(claim).toContain('RETURN QUERY SELECT replay_claim."id", replay_claim."generation", true, replay_claim."verificationTokenExpiresAt"'); expect(claim).toContain("Portal already has a pending hostname claim"); expect(claim).toContain("acquisition.\"status\" = 'active'"); expect(claim).toContain("acquisition.\"status\" IN ('pending', 'provider_pending', 'payment_pending')"); expect(claim).toContain('acquisition."reservationExpiresAt" > database_now'); expect(claim).toContain('FROM public."TenantProductAcquisition" AS acquisition'); expect(claim).toContain('pending_bound_domain."id" IS NOT NULL'); expect(claim).toContain('p_expected_current_domain_id <> current_domain."id"'); expect(claim).toContain("current_domain.\"status\" NOT IN ('cooldown', 'released')"); expect(claim.indexOf('RETURN QUERY SELECT replay_claim."id"')).toBeLessThan(claim.indexOf("SELECT domain.* INTO current_domain")); }); it("reclaims only after acknowledged deprovisioning and the complete cooldown", () => { const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); expect(claim).toContain("hostname_domain.\"status\" NOT IN ('cooldown', 'released')"); expect(claim).toContain('hostname_domain."activeOrigin" IS NOT NULL'); expect(claim).toContain('hostname_domain."deprovisionedAt" IS NULL'); expect(claim).toContain('hostname_claim."cooldownUntil" < hostname_claim."releasedAt" + INTERVAL \'30 days\''); expect(claim).toContain('hostname_domain."cooldownUntil" < hostname_domain."deprovisionedAt" + INTERVAL \'30 days\''); expect(claim).toContain('hostname_domain."cooldownUntil" > database_now'); expect(claim).toContain('hostname_claim."deprovisionedAt" <> hostname_claim."releasedAt"'); expect(claim).toContain('hostname_claim."deprovisionCommandHash" !~ \'^[a-f0-9]{64}$\''); expect(claim).toContain('hostname_claim."deprovisionResultHash" !~ \'^[a-f0-9]{64}$\''); expect(claim).toContain('DELETE FROM public."PortalCustomDomain"'); const boundReclaim = claim.indexOf("-- Ownership proof precedes checkout"); const domainDelete = claim.indexOf('DELETE FROM public."PortalCustomDomain"', boundReclaim); const claimDelete = claim.indexOf('DELETE FROM public."PortalDomainHostnameClaim"', domainDelete); expect(domainDelete).toBeGreaterThan(boundReclaim); expect(domainDelete).toBeLessThan(claimDelete); }); it("permits claim-only cooldown reclaim while still validating the durable tombstone", () => { const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); const strictCooldownStart = claim.indexOf("-- Claims that were verified or ever routed retain the strict 30-day"); const newClaimInsert = claim.indexOf('INSERT INTO public."PortalDomainHostnameClaim"', strictCooldownStart); expect(strictCooldownStart).toBeGreaterThanOrEqual(0); expect(newClaimInsert).toBeGreaterThan(strictCooldownStart); const strictCooldown = claim.slice(strictCooldownStart, newClaimInsert); expect(strictCooldown).toContain('hostname_claim."deprovisionedAt" <> hostname_claim."releasedAt"'); expect(strictCooldown).toContain('claim."deprovisionedAt" = claim."releasedAt"'); expect(strictCooldown).toContain('hostname_claim."deprovisionCommandHash"'); expect(strictCooldown).toContain('hostname_claim."deprovisionResultHash"'); expect(strictCooldown).toContain('hostname_domain."id" IS NOT NULL\n AND ('); expect(strictCooldown).toContain('IF hostname_domain."id" IS NOT NULL THEN'); expect(strictCooldown).toContain('AND NOT EXISTS (\n SELECT 1 FROM public."PortalCustomDomain" AS remaining_domain'); expect(strictCooldown).not.toContain('hostname_domain."id" IS NULL'); }); it("protects paid quarantined acquisitions from every destructive expiry reclaim path", () => { const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); expect(claim.match(/acquisition\."providerPaidAt" IS NOT NULL/gu)).toHaveLength(3); expect(claim.match(/acquisition\."failureCode" IS NOT NULL/gu)).toHaveLength(3); expect(claim.match(/acquisition\."status" NOT IN \('refunded', 'cancelled', 'expired'\)/gu)).toHaveLength(3); const firstPaidFence = claim.indexOf('acquisition."providerPaidAt" IS NOT NULL'); const secondPaidFence = claim.indexOf('acquisition."providerPaidAt" IS NOT NULL', firstPaidFence + 1); const thirdPaidFence = claim.indexOf('acquisition."providerPaidAt" IS NOT NULL', secondPaidFence + 1); expect(firstPaidFence).toBeGreaterThanOrEqual(0); expect(secondPaidFence).toBeGreaterThan(firstPaidFence); expect(thirdPaidFence).toBeGreaterThan(secondPaidFence); expect(thirdPaidFence).toBeLessThan(claim.indexOf("-- Claims that were verified or ever routed retain the strict 30-day")); }); it("expires never-verified reservations without weakening routed-domain cooldowns", () => { const claim = functionBody("hivegrid_portal_claim_hostname", "CREATE OR REPLACE FUNCTION public.hivegrid_portal_domain_due_candidates"); expect(claim).toContain('claim."verificationTokenExpiresAt" <= database_now'); expect(claim).toContain('hostname_claim."verificationTokenExpiresAt" <= database_now'); expect(claim).toContain("hostname_claim.\"claimedAt\" <= database_now - INTERVAL '7 days'"); expect(claim).toContain('hostname_claim."verifiedAt" IS NULL'); expect(claim).toContain('hostname_domain."controllerCommandId" IS NULL'); expect(claim).toContain('hostname_domain."provisionedAt" IS NULL'); expect(claim).toContain('hostname_domain."lastHealthAckAt" IS NULL'); expect(claim).toContain('hostname_domain."entitlementValidatedAt" IS NULL'); expect(claim).toContain('hostname_domain."paymentAcquisitionId" IS NULL'); expect(claim).toContain('FROM public."TenantProductAcquisition" AS acquisition'); expect(claim).toContain("acquisition.\"status\" = 'active'"); expect(claim).toContain('FROM public."TenantSubscription" AS subscription'); expect(claim).toContain('subscription."status" = \'active\''); expect(claim).toContain('subscription."cancelledAt" IS NULL'); expect(claim).toContain('acquisition."scopeKey" = hostname_claim."billingScopeKey"'); expect(claim).toContain('\'enterprise-contract:\' || acquisition."id" = hostname_claim."billingScopeKey"'); expect(claim).toContain("Portal hostname expiry reclaim lost its proof precondition"); expect(claim.indexOf('hostname_claim."verificationTokenExpiresAt" <= database_now')).toBeLessThan( claim.indexOf('hostname_claim."cooldownUntil" < hostname_claim."releasedAt" + INTERVAL \'30 days\'') ); }); it("gives only the worker a bounded opaque due-candidate scan", () => { const sweep = functionBody("hivegrid_portal_domain_due_candidates", "RESET ROLE;"); expect(sweep).toContain("session_user <> 'hivegrid_worker'"); expect(sweep).toContain("current_setting('app.portal_session_id', true)"); expect(sweep).toContain("current_setting('app.public_knowledge_base_id', true)"); expect(sweep).toContain("current_setting('app.platform_analytics', true)"); expect(sweep).toContain("p_requested_at IS NULL"); expect(sweep).toContain("p_take NOT BETWEEN 1 AND 1000"); expect(sweep).toContain('RETURNS TABLE ("tenantId" text, "claimId" text)'); expect(sweep).toContain('domain."killSwitchEnabled" = true'); expect(sweep).toContain('domain."nextRevalidationAt"'); expect(sweep).toContain("domain.\"status\" IN ('active', 'awaiting_dns')"); expect(sweep).toContain('domain."nextRetryAt"'); expect(sweep).toContain("INTERVAL '21 days'"); expect(sweep).not.toContain('claim."hostname"'); expect(capabilitySql).toContain("GRANT EXECUTE ON FUNCTION public.hivegrid_portal_domain_due_candidates(timestamptz,integer) TO hivegrid_worker;"); expect(capabilitySql).not.toContain("GRANT EXECUTE ON FUNCTION public.hivegrid_portal_domain_due_candidates(timestamptz,integer) TO hivegrid_app;"); }); });