Skip to content
Merged
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
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ So a dev-side job that selects users by a generic predicate can still email real
and a cascade delete can still destroy a real repo.
The catalog purge removed one blast-radius vector; it did not remove the reason these fences exist.

Admin-facing notification mail (new-user approval, upload-access and publication requests,
import recovery, cron digests) is production-only by default,
via `getAdminEmailsForCategory`'s fence in `backend/src/services/email.ts`.
Set `DEV_ADMIN_NOTIFICATIONS=1` only for a deliberate staging test of admin mail.

`users.account_kind` (ADR 0048) is explicit on the seeded fixtures: `test-owner` and `test-admin`
are `service` (operational, no human signs in to them directly); `test-user`, `test-pending`,
`test-verified`, and `test-revoked` are `test` (a persona, not a real identity); `test-web` stays
Expand Down
4 changes: 2 additions & 2 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ async function scheduledCleanup(env: Bindings): Promise<void> {
if (env.RESEND_API_KEY) {
try {
const emailCfg = resolveEmailConfig(env);
const adminEmails = await getAdminEmailsForCategory(db, "publication_request");
const adminEmails = await getAdminEmailsForCategory(db, "publication_request", env);
if (adminEmails.length > 0) {
await sendExemplarInvariantAlertEmail(
adminEmails,
Expand Down Expand Up @@ -527,7 +527,7 @@ async function scheduledCleanup(env: Bindings): Promise<void> {
let adminEmails: string[] = [];
if (canEmail) {
try {
adminEmails = await getAdminEmailsForCategory(db, "publication_request");
adminEmails = await getAdminEmailsForCategory(db, "publication_request", env);
} catch (err) {
console.error("Scheduled cleanup: failed to fetch admin emails:", err);
}
Expand Down
2 changes: 1 addition & 1 deletion backend/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ authRoutes.get("/verify", async (c) => {

// Notify admins who have user_approval notifications enabled
try {
const adminEmails = await getAdminEmailsForCategory(db, "user_approval");
const adminEmails = await getAdminEmailsForCategory(db, "user_approval", c.env);
if (adminEmails.length > 0) {
const { fromEmail, replyTo, isDev } = resolveEmailConfig(c.env);
await sendAdminNotificationEmail(
Expand Down
4 changes: 2 additions & 2 deletions backend/src/routes/datasets/publication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ export function registerPublicationRoutes(datasetRoutes: DatasetsRouter): void {

// Notify admins who have publication_request notifications enabled
try {
const adminEmails = await getAdminEmailsForCategory(db, "publication_request");
const adminEmails = await getAdminEmailsForCategory(db, "publication_request", c.env);
if (adminEmails.length > 0) {
const { fromEmail, replyTo, isDev } = resolveEmailConfig(c.env);
await sendPublicationRequestEmail(
Expand Down Expand Up @@ -597,7 +597,7 @@ export function registerPublicationRoutes(datasetRoutes: DatasetsRouter): void {

// Resend notification to admins who have publication_request notifications enabled
try {
const adminEmails = await getAdminEmailsForCategory(db, "publication_request");
const adminEmails = await getAdminEmailsForCategory(db, "publication_request", c.env);
if (adminEmails.length > 0) {
const { fromEmail, replyTo, isDev } = resolveEmailConfig(c.env);
await sendPublicationRequestEmail(
Expand Down
21 changes: 14 additions & 7 deletions backend/src/routes/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { flag } from "../db/flag";
import { authMiddleware } from "../middleware/auth";
import {
getAdminEmailsForCategory,
isAdminNotificationAllowed,
resolveEmailConfig,
sendUploadAccessRequestEmail,
} from "../services/email";
Expand Down Expand Up @@ -243,14 +244,20 @@ async function notifyAdminsOfUploadRequest(
): Promise<{ delivered: number; attempted: number }> {
const db = c.env.DB;
try {
const adminEmails = await getAdminEmailsForCategory(db, "user_approval");
const adminEmails = await getAdminEmailsForCategory(db, "user_approval", c.env);
if (adminEmails.length === 0) {
// Not an error the USER can act on, so the request still succeeds -- but
// it is a misconfiguration an operator must see, and `admins_notified: 0`
// makes it visible in the response as well as the log.
console.error(
`[upload-access] no admin recipients for user_approval; request from id=${row.id} stored but nobody was told`,
);
// getAdminEmailsForCategory already logged (and returned []) when the
// production-only fence applied -- that is expected on a dev worker,
// not a misconfiguration, so only escalate to console.error when the
// fence was open and the admin table itself came back empty.
if (isAdminNotificationAllowed(c.env)) {
// Not an error the USER can act on, so the request still succeeds -- but
// it is a misconfiguration an operator must see, and `admins_notified: 0`
// makes it visible in the response as well as the log.
console.error(
`[upload-access] no admin recipients for user_approval; request from id=${row.id} stored but nobody was told`,
);
}
return { delivered: 0, attempted: 0 };
}

Expand Down
2 changes: 1 addition & 1 deletion backend/src/services/email-verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ export async function notifyAdminsOfVerifiedAccount(
user: { id: number; email: string; github_username: string | null; description: string },
): Promise<void> {
try {
const adminEmails = await getAdminEmailsForCategory(env.DB, "user_approval");
const adminEmails = await getAdminEmailsForCategory(env.DB, "user_approval", env);
if (adminEmails.length === 0) return;
const { fromEmail, replyTo, isDev } = resolveEmailConfig(env);
await sendAdminNotificationEmail(
Expand Down
55 changes: 55 additions & 0 deletions backend/src/services/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,15 +203,70 @@ export function parseEmailPreferences(raw: string | null): EmailPreferences {
}
}

/**
* Env fields the admin-notification fence below needs. Structurally typed
* (like EmailDeliveryEnv above), not `Bindings`, so this module stays
* decoupled from the full binding surface.
*/
export interface AdminNotificationEnv {
ENVIRONMENT?: string;
/** Opt-in escape hatch for a DELIBERATE staging test of admin mail: set to
* exactly "1" to let a non-production worker generate admin notifications.
* Unset/anything else keeps the fence closed. */
DEV_ADMIN_NOTIFICATIONS?: string;
}

/**
* True when a non-production worker may generate admin-facing notification
* mail at all (repo issue: admin notifications must be production-only).
* Production always allows. Every other (or unset/unrecognized) ENVIRONMENT
* requires the explicit opt-in `DEV_ADMIN_NOTIFICATIONS === "1"`.
*
* Deliberately mirrors isEmailDeliveryAllowed's notion of "production"
* (only the literal string "production" bypasses; unset/unknown fails
* toward suppressing) rather than services/environment.ts's
* isNonProductionEnv, which treats an unknown ENVIRONMENT as production.
* The risk here is the same as isEmailDeliveryAllowed's: the dev worker
* shares production's `users` table and holds a live RESEND_API_KEY, and
* its own admin account is on DEV_EMAIL_ALLOWLIST (so staging sign-in
* codes reach them) -- which means the per-recipient delivery fence alone
* does NOT stop admin notifications from reaching that admin in dev. A
* misconfigured/typo'd ENVIRONMENT on a worker that holds live secrets must
* fail toward NOT generating admin mail, not toward generating it.
*/
export function isAdminNotificationAllowed(env: AdminNotificationEnv | undefined): boolean {
const environment = (env?.ENVIRONMENT ?? "").trim().toLowerCase();
if (environment === "production") return true;
return (env?.DEV_ADMIN_NOTIFICATIONS ?? "").trim() === "1";
}

/**
* Get admin/owner emails filtered by notification category.
* If all admins have opted out, falls back to the first admin
* to ensure at least one recipient.
*
* `env` is the single chokepoint fence (repo issue: admin notifications
* must be production-only): every call site funnels through here, so no
* call site can forget the fence. On a non-production worker (and without
* the DEV_ADMIN_NOTIFICATIONS opt-in) this returns [] before the D1 query
* even runs, and logs one console.warn naming the category. `env` is a
* required parameter -- not optional -- so a caller cannot silently allow
* delivery by forgetting to pass it; TypeScript enforces that here, and
* isAdminNotificationAllowed's own undefined-safe checks keep the fence
* closed even if a caller passes an empty object.
*/
export async function getAdminEmailsForCategory(
db: D1Database,
category: EmailCategory,
env: AdminNotificationEnv,
): Promise<string[]> {
if (!isAdminNotificationAllowed(env)) {
console.warn(
`[email] admin notification for "${category}" suppressed: admin notifications are production-only (ENVIRONMENT=${env?.ENVIRONMENT ?? "unset"}). Set DEV_ADMIN_NOTIFICATIONS=1 to opt in for a deliberate staging test.`,
);
return [];
}

const result = await db
.prepare(
"SELECT email, email_preferences FROM users WHERE role IN ('owner', 'admin') AND status = 'approved' AND deleted_at IS NULL",
Expand Down
2 changes: 1 addition & 1 deletion backend/src/services/import-recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ async function alertAdmins(
): Promise<void> {
if (!env.RESEND_API_KEY) return; // best-effort; audit_log is the durable record
try {
const adminEmails = await getAdminEmailsForCategory(db, "publication_request");
const adminEmails = await getAdminEmailsForCategory(db, "publication_request", env);
if (adminEmails.length === 0) return;
const { fromEmail, replyTo, isDev } = resolveEmailConfig(env);
await sendImportQuarantineEmail(
Expand Down
10 changes: 10 additions & 0 deletions backend/src/types/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ export interface Bindings {
* sendBroadcast). Unset means nothing is allow-listed -- every
* non-production send is refused, fail-closed. Ignored in production. */
DEV_EMAIL_ALLOWLIST?: string;
/** Opt-in escape hatch so a non-production worker can generate admin-facing
* notification mail (new-user approval, publication requests, import
* recovery, cron digests): set to exactly "1" for a deliberate staging
* test. Unset/anything else keeps getAdminEmailsForCategory's fence
* closed (services/email.ts). Distinct from DEV_EMAIL_ALLOWLIST above:
* that fence gates WHO a send can reach, this one gates WHETHER an
* admin-notification send is generated at all -- the dev worker's own
* admin account is on DEV_EMAIL_ALLOWLIST, so the recipient fence alone
* does not stop admin mail from reaching them. */
DEV_ADMIN_NOTIFICATIONS?: string;
/** Domain attribute for the web-dashboard session cookie (#569).
* Set to "app.nemar.org" in production and left empty in dev so
* the cookie is host-only for *.workers.dev. The dashboard moves
Expand Down
95 changes: 95 additions & 0 deletions backend/test/email-delivery-fence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,25 @@
* applied per-recipient to a batch before any chunk is built, so
* `nemar admin notify` -- the highest-blast-radius manual flow -- gets
* the identical guarantee as a single transactional send.
* - isAdminNotificationAllowed / getAdminEmailsForCategory: a SEPARATE,
* stricter fence for admin-facing notification mail (new-user approval,
* upload-access/publication requests, import recovery, cron digests).
* The dev worker's own admin account is on DEV_EMAIL_ALLOWLIST above (so
* staging sign-in codes reach it), which means the recipient-level fence
* alone does NOT stop admin notifications from reaching it outside
* production -- this fence stops them being generated at all. Real D1
* (freshDb/realD1) for getAdminEmailsForCategory's own query.
*/

import type { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { sendBroadcast } from "../src/services/broadcast";
import {
type AdminNotificationEnv,
DevEmailFenceError,
type EmailDeliveryEnv,
getAdminEmailsForCategory,
isAdminNotificationAllowed,
isEmailDeliveryAllowed,
isRecipientAllowlisted,
redactRecipient,
Expand Down Expand Up @@ -327,3 +338,87 @@ describe("sendBroadcast delivery fence", () => {
});
});
});

// ---------------------------------------------------------------------------
// isAdminNotificationAllowed -- the pure predicate, exhaustively. Mirrors the
// isEmailDeliveryAllowed block above in shape, but the opt-in is
// DEV_ADMIN_NOTIFICATIONS (exact string "1"), not an allow-list of
// recipients: this fence is about whether admin-notification mail is
// generated at all, not about who it may reach.
// ---------------------------------------------------------------------------

describe("isAdminNotificationAllowed", () => {
test("production always allows, opt-in or not", () => {
expect(isAdminNotificationAllowed({ ENVIRONMENT: "production" })).toBe(true);
expect(
isAdminNotificationAllowed({ ENVIRONMENT: "PRODUCTION", DEV_ADMIN_NOTIFICATIONS: "0" }),
).toBe(true);
});

for (const environment of ["development", "staging", "test", "", undefined]) {
test(`ENVIRONMENT=${JSON.stringify(environment)} requires DEV_ADMIN_NOTIFICATIONS="1"`, () => {
const env: AdminNotificationEnv = { ENVIRONMENT: environment };
expect(isAdminNotificationAllowed(env)).toBe(false);
expect(isAdminNotificationAllowed({ ...env, DEV_ADMIN_NOTIFICATIONS: "1" })).toBe(true);
// Anything other than the literal "1" stays closed -- "true" is a
// plausible typo for the same intent and must not accidentally open
// the fence.
expect(isAdminNotificationAllowed({ ...env, DEV_ADMIN_NOTIFICATIONS: "true" })).toBe(false);
});
}

test("a wholly unset env (undefined) refuses -- fails toward suppressing, not allowing", () => {
expect(isAdminNotificationAllowed(undefined)).toBe(false);
});
});

// ---------------------------------------------------------------------------
// getAdminEmailsForCategory -- the chokepoint every admin-notification call
// site funnels through. Real D1 (freshDb/realD1), so a false positive here
// would mean the actual production query disagrees with the fence, not a
// hand-copied re-implementation of either.
// ---------------------------------------------------------------------------

function seedApprovedAdmin(db: Database): void {
db.run(
`INSERT INTO users (username, email, password_hash, github_username, status, role, email_verified)
VALUES ('fenceadmin', 'fenceadmin@nemar.org', 'x', 'fenceadmin-gh', 'approved', 'admin', 1)`,
);
}

describe("getAdminEmailsForCategory", () => {
test("production returns the seeded admin addresses", async () => {
const db = freshDb();
seedApprovedAdmin(db);
const emails = await getAdminEmailsForCategory(realD1(db), "user_approval", {
ENVIRONMENT: "production",
});
expect(emails).toEqual(["fenceadmin@nemar.org"]);
});

test("development returns [] -- the fence applies before the D1 query runs", async () => {
const db = freshDb();
seedApprovedAdmin(db);
const emails = await getAdminEmailsForCategory(realD1(db), "user_approval", {
ENVIRONMENT: "development",
});
expect(emails).toEqual([]);
});

test("an unset ENVIRONMENT returns [] -- fails toward suppressing, not allowing", async () => {
const db = freshDb();
seedApprovedAdmin(db);
const emails = await getAdminEmailsForCategory(realD1(db), "user_approval", {});
expect(emails).toEqual([]);
});

test("development + DEV_ADMIN_NOTIFICATIONS=1 opts back in for a deliberate staging test", async () => {
const db = freshDb();
seedApprovedAdmin(db);
const emails = await getAdminEmailsForCategory(realD1(db), "user_approval", {
ENVIRONMENT: "development",
DEV_ADMIN_NOTIFICATIONS: "1",
});
expect(emails).toEqual(["fenceadmin@nemar.org"]);
});
});
49 changes: 47 additions & 2 deletions backend/test/tier-emails.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,20 @@ describe("GET /auth/verify (the CLI verification link)", () => {
expect(row?.service_access).toBe(0);
});

test("notifies the admins that a new account is verified", async () => {
test("in production, notifies the admins that a new account is verified", async () => {
// Admin notifications are production-only (getAdminEmailsForCategory's
// fence in services/email.ts), so this now has to run against a
// production-configured app to actually observe the send -- production
// bypasses DEV_EMAIL_ALLOWLIST entirely, so no allow-list entry is
// needed for ADMIN_EMAIL here.
seedUnverifiedCliUser();

const calls = await withFakeResend(async (calls) => {
await app.request(`/auth/verify?token=${VERIFY_TOKEN}`, {}, env());
await app.request(
`/auth/verify?token=${VERIFY_TOKEN}`,
{},
{ ...env(), ENVIRONMENT: "production" },
);
return calls;
});

Expand All @@ -155,6 +164,42 @@ describe("GET /auth/verify (the CLI verification link)", () => {
// mail names.
expect(toAdmin[0].html).toContain("nemar admin approve");
});

test("outside production, the admin notification is suppressed by default", async () => {
// env() is a dev/test-configured app (ENVIRONMENT: "test") with
// ADMIN_EMAIL itself on DEV_EMAIL_ALLOWLIST -- proving that the
// per-recipient delivery fence alone would NOT have stopped this send
// (the admin's own address is deliverable to). getAdminEmailsForCategory's
// production-only fence is what actually suppresses it, before the
// recipient list is even built.
seedUnverifiedCliUser();

const calls = await withFakeResend(async (calls) => {
const res = await app.request(`/auth/verify?token=${VERIFY_TOKEN}`, {}, env());
expect(res.status).toBe(200);
return calls;
});

// The user-facing key-ready mail is unrelated to the admin-notification
// fence and still goes out, so this isn't the whole route going dark.
expect(sendsTo(calls, USER_EMAIL).length).toBe(1);
expect(sendsTo(calls, ADMIN_EMAIL).length).toBe(0);
});

test("outside production, DEV_ADMIN_NOTIFICATIONS=1 opts back in for a deliberate staging test", async () => {
seedUnverifiedCliUser();

const calls = await withFakeResend(async (calls) => {
await app.request(
`/auth/verify?token=${VERIFY_TOKEN}`,
{},
{ ...env(), DEV_ADMIN_NOTIFICATIONS: "1" },
);
return calls;
});

expect(sendsTo(calls, ADMIN_EMAIL).length).toBe(1);
});
});

describe("the signup verification email (the first one anyone gets)", () => {
Expand Down
Loading
Loading