Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { deleteManagedEmailProvider } from "@/lib/managed-email-onboarding";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { adaptSchema, adminAuthTypeSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
},
request: yupObject({
auth: yupObject({
type: adminAuthTypeSchema.defined(),
tenancy: adaptSchema.defined(),
}).defined(),
body: yupObject({
resend_domain_id: yupString().defined(),
}).defined(),
Comment on lines +14 to +16
method: yupString().oneOf(["POST"]).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
status: yupString().oneOf(["deleted"]).defined(),
}).defined(),
}),
handler: async ({ auth, body }) => {
const result = await deleteManagedEmailProvider({
tenancy: auth.tenancy,
resendDomainId: body.resend_domain_id,
});

return {
statusCode: 200,
bodyType: "json",
body: {
status: result.status,
},
};
},
});
25 changes: 25 additions & 0 deletions apps/backend/src/lib/managed-email-domains.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,28 @@ export async function listManagedEmailDomainsForTenancy(tenancyId: string): Prom
`);
return rows.map(mapRow);
}

export async function deleteManagedEmailDomainById(id: string): Promise<ManagedEmailDomain | null> {
const rows = await globalPrismaClient.$queryRaw<ManagedEmailDomainRow[]>(Prisma.sql`
DELETE FROM "ManagedEmailDomain"
WHERE "id" = ${id}
RETURNING *
`);
if (rows.length === 0) {
return null;
}
return mapRow(rows[0]!);
}

export async function countManagedEmailDomainsBySubdomainExcludingId(options: {
subdomain: string,
excludeId: string,
}): Promise<number> {
const rows = await globalPrismaClient.$queryRaw<{ count: bigint }[]>(Prisma.sql`
SELECT COUNT(*)::bigint AS count
FROM "ManagedEmailDomain"
WHERE "subdomain" = ${options.subdomain}
AND "id" <> ${options.excludeId}
`);
Comment on lines +244 to +249
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Exclude inactive rows from the sibling count.

This query currently counts every row with the same subdomain. If an archived/inactive ManagedEmailDomain remains, the deletion flow will think the zone is still referenced and skip DNSimple cleanup even after the last live domain is removed.

Suggested fix
   const rows = await globalPrismaClient.$queryRaw<{ count: bigint }[]>(Prisma.sql`
     SELECT COUNT(*)::bigint AS count
     FROM "ManagedEmailDomain"
     WHERE "subdomain" = ${options.subdomain}
       AND "id" <> ${options.excludeId}
+      AND "isActive" = true
   `);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const rows = await globalPrismaClient.$queryRaw<{ count: bigint }[]>(Prisma.sql`
SELECT COUNT(*)::bigint AS count
FROM "ManagedEmailDomain"
WHERE "subdomain" = ${options.subdomain}
AND "id" <> ${options.excludeId}
`);
const rows = await globalPrismaClient.$queryRaw<{ count: bigint }[]>(Prisma.sql`
SELECT COUNT(*)::bigint AS count
FROM "ManagedEmailDomain"
WHERE "subdomain" = ${options.subdomain}
AND "id" <> ${options.excludeId}
AND "isActive" = true
`);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/backend/src/lib/managed-email-domains.tsx` around lines 244 - 249, The
COUNT query in globalPrismaClient.$queryRaw against "ManagedEmailDomain" counts
archived/inactive rows, causing the deletion flow to think a zone is still
referenced; update the WHERE clause in that query (the one using
options.subdomain and options.excludeId) to exclude archived/inactive records
(for example add AND "archivedAt" IS NULL or AND "isArchived" = false depending
on the actual schema column used for soft-deletes) so only live domains are
counted; make sure to use the same archived/active column and semantics used
elsewhere in the codebase.

return Number(rows[0]?.count ?? 0n);
}
84 changes: 83 additions & 1 deletion apps/backend/src/lib/managed-email-onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
getManagedEmailDomainByTenancyAndSubdomain,
listManagedEmailDomainsForTenancy,
markManagedEmailDomainApplied,
countManagedEmailDomainsBySubdomainExcludingId,
deleteManagedEmailDomainById,
updateManagedEmailDomainWebhookStatus,
} from "@/lib/managed-email-domains";
import { Tenancy } from "@/lib/tenancies";
Expand Down Expand Up @@ -225,6 +227,26 @@ async function createDnsimpleZone(subdomain: string): Promise<DnsimpleZone> {
};
}

async function deleteDnsimpleZoneByName(zoneName: string): Promise<{ status: "deleted" | "not_found" }> {
const dnsimpleBaseUrl = getDnsimpleBaseUrl();
const dnsimpleAccountId = getDnsimpleAccountId();
const response = await fetch(`${dnsimpleBaseUrl}/${encodeURIComponent(dnsimpleAccountId)}/zones/${encodeURIComponent(zoneName)}`, {
method: "DELETE",
headers: getDnsimpleHeaders(),
});
if (response.status === 404) {
return { status: "not_found" };
}
if (!response.ok) {
const responseBody = await response.text();
throw new StatusError(
502,
`DNSimple returned ${response.status} when deleting managed email zone ${zoneName}: ${responseBody.slice(0, 500)}`,
);
}
return { status: "deleted" };
}

async function createOrReuseDnsimpleZone(subdomain: string): Promise<DnsimpleZone> {
const existingZones = await listDnsimpleZones(subdomain);
if (existingZones.length > 1) {
Expand Down Expand Up @@ -650,6 +672,67 @@ export async function applyManagedEmailProvider(options: {
return { status: "applied" };
}

function isManagedEmailDomainInUseForTenancy(options: {
tenancy: Tenancy,
subdomain: string,
senderLocalPart: string,
}): boolean {
const emailServer = options.tenancy.config.emails.server;
return emailServer.provider === "managed"
&& emailServer.managedSubdomain === options.subdomain
&& emailServer.managedSenderLocalPart === options.senderLocalPart;
}

export async function deleteManagedEmailProvider(options: {
tenancy: Tenancy,
resendDomainId: string,
}): Promise<{ status: "deleted" }> {
const domain = await getManagedEmailDomainByResendDomainId(options.resendDomainId);
if (!domain || domain.tenancyId !== options.tenancy.id) {
throw new StatusError(404, "Managed domain not found for this project/branch");
}
if (isManagedEmailDomainInUseForTenancy({
tenancy: options.tenancy,
subdomain: domain.subdomain,
senderLocalPart: domain.senderLocalPart,
})) {
throw new StatusError(409, "Cannot delete a managed domain that is currently in use for sending email");
}

// External cleanup must succeed before we drop the DB row; otherwise a failure here
// would leak provider-side resources with no record left to retry against.
if (!shouldUseMockManagedEmailOnboarding()) {
const resendApiKey = getEnvVariable("STACK_RESEND_API_KEY");
const resendResponse = await fetch(`https://api.resend.com/domains/${encodeURIComponent(domain.resendDomainId)}`, {
method: "DELETE",
headers: {
"Authorization": `Bearer ${resendApiKey}`,
},
});
if (!resendResponse.ok && resendResponse.status !== 404) {
const responseBody = await resendResponse.text();
throw new StatusError(
502,
`Upstream email provider returned ${resendResponse.status} when deleting managed domain ${domain.resendDomainId}: ${responseBody.slice(0, 500)}`,
);
}

// createOrReuseDnsimpleZone lets multiple ManagedEmailDomain rows share a zone (when
// two tenancies pick the same subdomain). Only delete the zone if this row is the
// last one referencing it.
const remaining = await countManagedEmailDomainsBySubdomainExcludingId({
subdomain: domain.subdomain,
excludeId: domain.id,
});
if (remaining === 0) {
await deleteDnsimpleZoneByName(domain.subdomain);
}
Comment on lines +720 to +729
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Serialize shared-zone cleanup for a subdomain.

This remaining check happens before the current row is removed and without any lock. If two sibling domains for the same subdomain are deleted concurrently, each request can observe one remaining row and both skip DNSimple zone deletion, leaking the shared zone permanently. This needs a per-subdomain critical section (for example, an advisory lock plus delete/count in one DB transaction) so the “last reference” decision is made atomically.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/backend/src/lib/managed-email-onboarding.tsx` around lines 720 - 729,
The current "last reference" check uses
countManagedEmailDomainsBySubdomainExcludingId followed separately by
deleteDnsimpleZoneByName, which is racy; serialize cleanup for a given subdomain
by acquiring a per-subdomain critical section (e.g., a DB advisory lock or mutex
keyed by domain.subdomain) and perform the count-and-delete inside the same
transaction/locked section so the decision is atomic. Update the logic around
countManagedEmailDomainsBySubdomainExcludingId and deleteDnsimpleZoneByName (or
the caller createOrReuseDnsimpleZone flow) to: acquire lock for
domain.subdomain, re-check count (excluding the row being deleted) inside the
lock/transaction, call deleteDnsimpleZoneByName only if count === 0, then
release the lock; ensure lock acquisition/release errors are handled and do not
leave the zone orphaned.

}

await deleteManagedEmailDomainById(domain.id);
return { status: "deleted" };
}

export async function processResendDomainWebhookEvent(options: {
domainId: string,
providerStatusRaw: string,
Expand Down Expand Up @@ -691,4 +774,3 @@ async function saveManagedEmailProviderConfig(options: {
},
});
}

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading