Require opt-in and recipient allowlist for push:test

This commit is contained in:
Jose Olarte III
2026-11-18 16:55:53 +08:00
parent 6bbe5983ce
commit 9f7647a447
5 changed files with 292 additions and 26 deletions
+9 -4
View File
@@ -31,11 +31,16 @@
# "production" everywhere. Unset or blank appends nothing.
# MESSAGE_ENV_LABEL=test
# Diagnostic test push (pnpm push:test) sends only when MESSAGE_ENV_LABEL is
# exactly "test" and this value equals the project_id inside
# FIREBASE_SERVICE_ACCOUNT_JSON. There is no production override. Leave unset
# in production.
# Diagnostic test push (pnpm push:test). Test and production share one Firebase
# project, so a matching project_id does not distinguish them. It only confirms
# the loaded service account. A send also requires MESSAGE_ENV_LABEL=test
# above. There is no production override. Leave these unset in production.
# PUSH_TEST_FIREBASE_PROJECT_ID=
# Only the exact string true enables a send. TRUE, 1, and "true " do not.
# PUSH_DIAGNOSTIC_TEST_SEND_ENABLED=true
# One recipient. The command's --did and --device-id must match exactly.
# PUSH_DIAGNOSTIC_ALLOWED_DID=did:example:one
# PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID=phone-1
# --- SMS notifications (/notify-sms) ---
+29 -5
View File
@@ -11,8 +11,12 @@ import {
import { maskToken } from "../util/maskToken.js";
import { log } from "../util/log.js";
import {
SHARED_FIREBASE_PROJECT_NOTE,
describeDiagnosticSendSafety,
formatDiagnosticEnvironment,
resolveDiagnosticAllowlist,
resolveDiagnosticEnvironment,
resolveDiagnosticSendOptIn,
type DiagnosticEnvironmentResult,
} from "./pushDiagnosticEnv.js";
import {
@@ -126,6 +130,7 @@ export async function previewDiagnosticPush(input: {
const lines = [
"Preview only. No FCM message was sent.",
...formatDiagnosticEnvironment(environment),
...describeDiagnosticSendSafety(input.env ?? process.env, input.userId),
`DID: ${input.userId}`,
`Registrations: ${registrations.length}`,
`Eligible devices: ${eligible.length}`,
@@ -162,7 +167,7 @@ export async function previewDiagnosticPush(input: {
export type DiagnosticSendOutcome =
| {
ok: false;
stage: "environment" | "registration";
stage: "safety" | "environment" | "registration";
report: string;
}
| {
@@ -185,9 +190,19 @@ function failureCode(err: unknown): string {
return code ?? "unknown";
}
function safetyRefusal(reason: string): DiagnosticSendOutcome {
return {
ok: false,
stage: "safety",
report: `${reason}\nNothing was sent.\n${SHARED_FIREBASE_PROJECT_NOTE}`,
};
}
/**
* Send one diagnostic notification to the registration named by DID and
* device id. Refuses unless the environment check passes. A history-write
* Send one diagnostic notification to the one allowlisted registration.
* Checks run in this order, and any failure returns before Firebase is called:
* the exact opt-in flag, the test label and service-account consistency, the
* single-recipient allowlist, then the database registration. A history-write
* failure is logged and does not send again.
*/
export async function runDiagnosticSend(input: {
@@ -197,13 +212,17 @@ export async function runDiagnosticSend(input: {
env?: NodeJS.ProcessEnv;
send?: (message: PushDiagnosticMessage) => Promise<string>;
record?: (row: AlertPushDeviceSendInput) => Promise<void>;
select?: (userId: string, deviceId: string) => Promise<DiagnosticRegistrationDecision>;
onBeforeSend?: (info: {
environment: Extract<DiagnosticEnvironmentResult, { ok: true }>;
content: PushDiagnosticContent;
row: StoredRow;
}) => void;
}): Promise<DiagnosticSendOutcome> {
const environment = resolveDiagnosticEnvironment(input.env);
const env = input.env ?? process.env;
const optIn = resolveDiagnosticSendOptIn(env);
if (!optIn.ok) return safetyRefusal(optIn.reason);
const environment = resolveDiagnosticEnvironment(env);
if (!environment.ok) {
return {
ok: false,
@@ -211,7 +230,12 @@ export async function runDiagnosticSend(input: {
report: formatDiagnosticEnvironment(environment).join("\n"),
};
}
const selected = await selectDiagnosticRegistration(input.userId, input.deviceId);
const allowed = resolveDiagnosticAllowlist(env, {
userId: input.userId,
deviceId: input.deviceId,
});
if (!allowed.ok) return safetyRefusal(allowed.reason);
const selected = await (input.select ?? selectDiagnosticRegistration)(allowed.userId, allowed.deviceId);
if (!selected.ok) {
return { ok: false, stage: "registration", report: selected.detail };
}
+115 -10
View File
@@ -1,15 +1,26 @@
/**
* Whether this process may send a diagnostic test push.
*
* A label by itself is not enough: MESSAGE_ENV_LABEL is typed by the operator,
* and NODE_ENV is `production` on every Docker server. The send is allowed
* only when that label is exactly `test` and the Firebase service-account
* project id equals PUSH_TEST_FIREBASE_PROJECT_ID. Anything else is refused.
* This does not change the process environment or the Firebase app.
* Test and production use the same Firebase project. A matching project_id
* only checks that the service account is the project named by
* PUSH_TEST_FIREBASE_PROJECT_ID. It does not distinguish test from production.
*
* A send also requires MESSAGE_ENV_LABEL to be exactly `test`,
* PUSH_DIAGNOSTIC_TEST_SEND_ENABLED to be the exact string `true`, and the
* command's DID and device id to match the single configured recipient.
* There is no production override. This module does not change the process
* environment or the Firebase app.
*/
export const PUSH_DIAGNOSTIC_TEST_LABEL = "test";
export const PUSH_TEST_FIREBASE_PROJECT_ENV = "PUSH_TEST_FIREBASE_PROJECT_ID";
export const PUSH_DIAGNOSTIC_TEST_SEND_ENABLED_ENV = "PUSH_DIAGNOSTIC_TEST_SEND_ENABLED";
export const PUSH_DIAGNOSTIC_ALLOWED_DID_ENV = "PUSH_DIAGNOSTIC_ALLOWED_DID";
export const PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID_ENV = "PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID";
/** Printed wherever a project id is shown, so it is not read as an isolation boundary. */
export const SHARED_FIREBASE_PROJECT_NOTE =
"Test and production share this Firebase project. A project_id match checks the configured service account only. It does not distinguish test from production. The diagnostic send is limited to one allowlisted DID and device id.";
const PRODUCTION_LABELS = new Set(["production", "prod"]);
@@ -91,8 +102,10 @@ function refuse(
}
/**
* Read the label and the Firebase project. Does not initialize Firebase and
* does not include the service-account key in the result.
* Read the label and confirm the service account's project_id matches the
* configured project. Test and production share that project, so this is a
* consistency check, not a test-versus-production boundary. Does not
* initialize Firebase and does not include the service-account key.
*/
export function resolveDiagnosticEnvironment(
env: NodeJS.ProcessEnv = process.env
@@ -152,7 +165,7 @@ export function resolveDiagnosticEnvironment(
if (expectedProjectId === null) {
return refuse(
"unknown",
`${PUSH_TEST_FIREBASE_PROJECT_ENV} is unset, so the service-account project cannot be checked against the test project.`,
`${PUSH_TEST_FIREBASE_PROJECT_ENV} is unset, so the service-account project cannot be checked for consistency.`,
observed
);
}
@@ -174,8 +187,9 @@ export function resolveDiagnosticEnvironment(
export function formatDiagnosticEnvironment(result: DiagnosticEnvironmentResult): string[] {
if (result.ok) {
return [
"Environment: test",
"Environment label: test",
`Firebase project: ${result.firebaseProjectId}`,
SHARED_FIREBASE_PROJECT_NOTE,
"Credential: FIREBASE_SERVICE_ACCOUNT_JSON",
];
}
@@ -184,7 +198,98 @@ export function formatDiagnosticEnvironment(result: DiagnosticEnvironmentResult)
`Diagnostic send refused (${result.classification}): ${result.reason}`,
`Observed label: ${observed.label ?? "(unset)"}`,
`Observed Firebase project: ${observed.firebaseProjectId ?? "(unverified)"}`,
`Expected test project: ${observed.expectedProjectId ?? "(unset)"}`,
`Expected configured project: ${observed.expectedProjectId ?? "(unset)"}`,
`Credential source: ${observed.credential}`,
SHARED_FIREBASE_PROJECT_NOTE,
];
}
export type DiagnosticSafetyResult =
| { ok: true }
| { ok: false; reason: string };
/** The opt-in is the exact string `true`. `TRUE`, `1`, and `true ` do not count. */
export function resolveDiagnosticSendOptIn(
env: NodeJS.ProcessEnv = process.env
): DiagnosticSafetyResult {
const raw = env[PUSH_DIAGNOSTIC_TEST_SEND_ENABLED_ENV];
if (raw === "true") return { ok: true };
if (raw === undefined || raw.length === 0) {
return {
ok: false,
reason: `${PUSH_DIAGNOSTIC_TEST_SEND_ENABLED_ENV} is unset. A diagnostic send requires the exact string true.`,
};
}
return {
ok: false,
reason: `${PUSH_DIAGNOSTIC_TEST_SEND_ENABLED_ENV} is not the exact string true. A diagnostic send is refused.`,
};
}
export type DiagnosticAllowlistResult =
| { ok: true; userId: string; deviceId: string }
| { ok: false; reason: string };
/**
* One configured recipient. The command values must equal it. A blank value,
* a list, or a wildcard is not a match.
*/
export function resolveDiagnosticAllowlist(
env: NodeJS.ProcessEnv,
requested: { userId: string; deviceId: string }
): DiagnosticAllowlistResult {
const userId = trimmed(env[PUSH_DIAGNOSTIC_ALLOWED_DID_ENV]);
const deviceId = trimmed(env[PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID_ENV]);
if (userId === null) {
return { ok: false, reason: `${PUSH_DIAGNOSTIC_ALLOWED_DID_ENV} is unset or empty. Nothing was sent.` };
}
if (deviceId === null) {
return {
ok: false,
reason: `${PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID_ENV} is unset or empty. Nothing was sent.`,
};
}
if (requested.userId !== userId) {
return {
ok: false,
reason: `The requested DID does not match ${PUSH_DIAGNOSTIC_ALLOWED_DID_ENV}. Nothing was sent.`,
};
}
if (requested.deviceId !== deviceId) {
return {
ok: false,
reason: `The requested device id does not match ${PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID_ENV}. Nothing was sent.`,
};
}
return { ok: true, userId, deviceId };
}
/** What preview can say about the send gate. It does not include tokens. */
export function describeDiagnosticSendSafety(
env: NodeJS.ProcessEnv,
previewDid?: string
): string[] {
const optIn = resolveDiagnosticSendOptIn(env);
const userId = trimmed(env[PUSH_DIAGNOSTIC_ALLOWED_DID_ENV]);
const deviceId = trimmed(env[PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID_ENV]);
const lines = [
optIn.ok
? "Diagnostic send opt-in: enabled"
: "Diagnostic send opt-in: not enabled. push:preview does not send, and push:test would refuse.",
userId === null ? "Allowlisted DID: (unset)" : `Allowlisted DID: ${userId}`,
deviceId === null ? "Allowlisted device id: (unset)" : `Allowlisted device id: ${deviceId}`,
];
if (previewDid !== undefined) {
lines.push(
userId === null
? "Preview DID matches the allowlist: no allowlist"
: `Preview DID matches the allowlist: ${userId === previewDid ? "yes" : "no"}`
);
}
lines.push(
optIn.ok && userId !== null && deviceId !== null
? "Diagnostic-send safety configuration: complete for one DID and one device id"
: "Diagnostic-send safety configuration: incomplete"
);
return lines;
}
+5 -3
View File
@@ -1,8 +1,10 @@
/**
* Send one diagnostic notification to one registration of one DID.
* Refuses unless MESSAGE_ENV_LABEL is exactly `test` and the Firebase
* service-account project id equals PUSH_TEST_FIREBASE_PROJECT_ID.
* Does not write alert_push_sends and does not change the daily cap.
* Test and production share a Firebase project, so project_id is only a
* consistency check. The send also requires MESSAGE_ENV_LABEL=test,
* PUSH_DIAGNOSTIC_TEST_SEND_ENABLED=true, and an exact match with
* PUSH_DIAGNOSTIC_ALLOWED_DID and PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID.
* There is no production override. Does not write alert_push_sends.
*
* pnpm push:test -- --did <DID> --device-id <DEVICE_ID>
*/
+134 -4
View File
@@ -38,6 +38,9 @@ const PROJECT = "timesafari-test";
const ENV_KEYS = [
"MESSAGE_ENV_LABEL",
"PUSH_TEST_FIREBASE_PROJECT_ID",
"PUSH_DIAGNOSTIC_TEST_SEND_ENABLED",
"PUSH_DIAGNOSTIC_ALLOWED_DID",
"PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID",
"FIREBASE_SERVICE_ACCOUNT_JSON",
"GOOGLE_APPLICATION_CREDENTIALS",
"NOTIFY_DATA_DIR",
@@ -98,7 +101,7 @@ describe("diagnostic environment", () => {
process.env.FIREBASE_SERVICE_ACCOUNT_JSON = serviceAccount(projectId);
}
it("accepts a test label only when it matches the service-account project", () => {
it("accepts a test label when the service account matches the configured project", () => {
allowTest();
const result = resolveDiagnosticEnvironment();
assert.equal(result.ok, true);
@@ -248,6 +251,9 @@ describe("diagnostic preview and send", () => {
process.env.NOTIFY_DATA_DIR = dir;
process.env.MESSAGE_ENV_LABEL = "test";
process.env.PUSH_TEST_FIREBASE_PROJECT_ID = PROJECT;
process.env.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED = "true";
process.env.PUSH_DIAGNOSTIC_ALLOWED_DID = DID;
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = DEVICE;
process.env.FIREBASE_SERVICE_ACCOUNT_JSON = serviceAccount(PROJECT);
delete process.env.GOOGLE_APPLICATION_CREDENTIALS;
closeDatabase();
@@ -272,12 +278,15 @@ describe("diagnostic preview and send", () => {
const sendsBefore = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_sends`).get() as { n: number };
const attemptsBefore = getDatabase().prepare(`SELECT COUNT(*) AS n FROM alert_push_device_sends`).get() as { n: number };
const calls: unknown[] = [];
delete process.env.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED;
const preview = await previewDiagnosticPush({ userId: DID, now: NOW });
assert.equal(calls.length, 0);
assert.equal(preview.eligible.length, 2);
assert.match(preview.report, /Preview only\. No FCM message was sent\./);
assert.match(preview.report, /Eligible devices: 2/);
assert.match(preview.report, /Environment: test/);
assert.match(preview.report, /Environment label: test/);
assert.match(preview.report, /does not distinguish test from production/);
assert.match(preview.report, /Diagnostic send opt-in: not enabled/);
assert.match(preview.report, new RegExp(PROJECT));
assert.match(preview.report, /phone-1/);
assert.match(preview.report, /android/);
@@ -387,8 +396,11 @@ describe("diagnostic preview and send", () => {
assert.equal(otherDid.ok, false);
if (!otherDid.ok) assert.equal(otherDid.stage, "registration");
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = "missing-phone";
const missing = await runDiagnosticSend({ userId: DID, deviceId: "missing-phone", now: NOW, send });
assert.equal(missing.ok, false);
if (!missing.ok) assert.equal(missing.stage, "registration");
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = DEVICE;
process.env.MESSAGE_ENV_LABEL = "production";
const production = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
@@ -412,6 +424,117 @@ describe("diagnostic preview and send", () => {
assert.equal(sent.length, 0);
});
it("refuses the send unless the opt-in and the one-device allowlist match exactly", async () => {
await register(DID, DEVICE);
const sent: unknown[] = [];
const send = async (message: unknown) => {
sent.push(message);
return "msg";
};
delete process.env.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED;
const missingFlag = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(missingFlag.ok, false);
if (!missingFlag.ok) {
assert.equal(missingFlag.stage, "safety");
assert.match(missingFlag.report, /PUSH_DIAGNOSTIC_TEST_SEND_ENABLED is unset/);
assertNoSecrets(missingFlag.report);
}
for (const value of ["TRUE", "1", "yes", "true ", " true", "SECRET-OPT-IN"]) {
process.env.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED = value;
const refused = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(refused.ok, false, value);
if (!refused.ok) {
assert.equal(refused.stage, "safety", value);
assert.equal(refused.report.includes("SECRET-OPT-IN"), false);
}
}
process.env.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED = "true";
delete process.env.PUSH_DIAGNOSTIC_ALLOWED_DID;
const missingDid = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(missingDid.ok, false);
if (!missingDid.ok) assert.match(missingDid.report, /PUSH_DIAGNOSTIC_ALLOWED_DID is unset or empty/);
process.env.PUSH_DIAGNOSTIC_ALLOWED_DID = " ";
const blankDid = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(blankDid.ok, false);
process.env.PUSH_DIAGNOSTIC_ALLOWED_DID = DID;
delete process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID;
const missingDevice = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(missingDevice.ok, false);
if (!missingDevice.ok) assert.match(missingDevice.report, /PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID is unset or empty/);
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = DEVICE;
process.env.PUSH_DIAGNOSTIC_ALLOWED_DID = OTHER;
const otherDid = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(otherDid.ok, false);
if (!otherDid.ok) {
assert.equal(otherDid.stage, "safety");
assert.match(otherDid.report, /does not match PUSH_DIAGNOSTIC_ALLOWED_DID/);
}
process.env.PUSH_DIAGNOSTIC_ALLOWED_DID = `${DID},${OTHER}`;
const listed = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(listed.ok, false);
process.env.PUSH_DIAGNOSTIC_ALLOWED_DID = DID;
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = "phone-2";
const otherDevice = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(otherDevice.ok, false);
if (!otherDevice.ok) assert.match(otherDevice.report, /does not match PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID/);
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = "*";
const wildcard = await runDiagnosticSend({ userId: DID, deviceId: DEVICE, now: NOW, send });
assert.equal(wildcard.ok, false);
process.env.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID = DEVICE;
const inactive = await runDiagnosticSend({
userId: DID,
deviceId: "blank-phone",
now: NOW,
send,
env: {
...process.env,
PUSH_DIAGNOSTIC_ALLOWED_DID: DID,
PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID: "blank-phone",
},
});
await register(DID, "blank-phone", " ");
const inactiveAfter = await runDiagnosticSend({
userId: DID,
deviceId: "blank-phone",
now: NOW,
send,
env: {
...process.env,
PUSH_DIAGNOSTIC_ALLOWED_DID: DID,
PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID: "blank-phone",
},
});
assert.equal(inactive.ok, false);
assert.equal(inactiveAfter.ok, false);
if (!inactiveAfter.ok) assert.equal(inactiveAfter.stage, "registration");
const ambiguous = await runDiagnosticSend({
userId: DID,
deviceId: DEVICE,
now: NOW,
send,
select: async () => ({
ok: false,
reason: "ambiguous",
detail: "Found 2 registrations for this DID and device id. Nothing was sent.",
}),
});
assert.equal(ambiguous.ok, false);
if (!ambiguous.ok) assert.equal(ambiguous.stage, "registration");
assert.equal(sent.length, 0);
for (const outcome of [missingFlag, missingDid, otherDid, otherDevice, inactiveAfter, ambiguous]) {
assertNoSecrets(outcome.ok ? outcome.report : outcome.report);
}
});
it("records a failure without the token and does not resend when history writing throws", async () => {
await register(DID, DEVICE);
let calls = 0;
@@ -498,16 +621,23 @@ describe("push preview and test commands", () => {
closeDatabase();
delete process.env.NOTIFY_DATA_DIR;
const preview = run("src/tools/pushPreview.ts", ["--did", DID], {
const previewEnv: NodeJS.ProcessEnv = {
...process.env,
NOTIFY_DATA_DIR: databaseDir,
MESSAGE_ENV_LABEL: "test",
PUSH_TEST_FIREBASE_PROJECT_ID: PROJECT,
// A credential Firebase could not initialize. Preview must not load it.
FIREBASE_SERVICE_ACCOUNT_JSON: JSON.stringify({ project_id: PROJECT }),
});
};
delete previewEnv.PUSH_DIAGNOSTIC_TEST_SEND_ENABLED;
delete previewEnv.PUSH_DIAGNOSTIC_ALLOWED_DID;
delete previewEnv.PUSH_DIAGNOSTIC_ALLOWED_DEVICE_ID;
const preview = run("src/tools/pushPreview.ts", ["--did", DID], previewEnv);
assert.equal(preview.status, 0, preview.stderr);
assert.match(preview.stdout, /Preview only\. No FCM message was sent\./);
assert.match(preview.stdout, /Diagnostic send opt-in: not enabled/);
assert.match(preview.stdout, /safety configuration: incomplete/);
assert.match(preview.stdout, /does not distinguish test from production/);
assert.match(preview.stdout, new RegExp(`Data type: ${PUSH_WATCH_TEST_TYPE}`));
assert.match(preview.stdout, new RegExp(PUSH_DIAGNOSTIC_TITLE));
assert.equal(preview.stdout.includes(TOKEN), false);