All files / lib/lambda notifyAttachmentArchiveIntegrity.ts

78.77% Statements 141/179
60.86% Branches 70/115
92.3% Functions 24/26
78.53% Lines 139/177

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650                      1x 1x 1x                                                                     4x 4x 2x     2x       4x 4x       4x     4x   2x               5x     5x       5x       10x 14x                                                         14x 14x       14x 14x 14x 14x       14x             10x 10x   10x 14x 14x       14x 14x       14x 14x     10x       5x 5x       5x 5x 5x       5x 5x       5x     9x 9x         2x                                       4x   4x                           4x 2x                   4x 4x                                               4x               4x                       4x                               5x                 2x           2x       2x       2x       2x   2x           2x       2x 2x 2x       2x 2x             1x               1x                                                     1x 1x 1x 1x 1x 1x 1x 1x                                                       1x       2x                   2x 1x     2x   2x     2x 4x       2x               2x                       2x                         2x 1x     2x 2x       3x       3x 3x 3x 3x       3x       3x 1x 1x         1x           2x 2x       2x                           2x 2x 2x 2x           2x                                 4x 2x 2x   2x   2x     2x 1x           2x 1x                   1x 1x 1x   2x     2x 2x 1x     2x 2x                         2x 2x 2x 2x 2x                                 2x           1x 7x           7x 4x     3x    
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { SendRawEmailCommand, SESClient } from "@aws-sdk/client-ses";
import { randomUUID } from "crypto";
import { getSecret } from "shared-utils";
 
import {
  AttachmentArchiveIntegrityRunResult,
  AttachmentArchiveIntegrityRunSummary,
} from "../attachment-archive/integrity-types";
import { getJsonObject, putJsonObject } from "../attachment-archive/storage";
 
const awsRegion = process.env.region || process.env.AWS_REGION;
const archiveBucketClient = new S3Client({ region: awsRegion });
const sesClient = new SESClient({ region: awsRegion });
 
type NotificationMode = "discrepancy" | "failure";
 
type IntegrityNotificationEvent = {
  mode: NotificationMode;
  runResult?: Partial<AttachmentArchiveIntegrityRunResult> & { summaryKey?: string };
  error?: unknown;
  input?: {
    runResult?: Partial<AttachmentArchiveIntegrityRunResult> & { summaryKey?: string };
    error?: unknown;
  };
};
 
type RecipientConfig = {
  sourceEmailAddress: string;
  sourceEmailHeader: string;
  toEmailAddresses: string[];
  toEmailHeaders: string[];
};
 
type ParsedEmailAddress = {
  email: string;
  formatted: string;
};
 
type ParsedFailurePayload = {
  message: string;
  summaryKey?: string;
  runId?: string;
  stage?: string;
  reportBucketName?: string;
};
 
function getIntegrityStageName() {
  const stage = process.env.STAGE_NAME?.trim();
  if (!stage) {
    throw new Error("ATTACHMENT_ARCHIVE_INTEGRITY_STAGE_NAME must be defined via STAGE_NAME");
  }
 
  return stage;
}
 
function getStorageConfig() {
  const writeBucketName = process.env.ATTACHMENT_ARCHIVE_BUCKET_NAME;
  Iif (!writeBucketName) {
    throw new Error("ATTACHMENT_ARCHIVE_BUCKET_NAME must be defined");
  }
 
  const reportPrefix = (
    process.env.ATTACHMENT_ARCHIVE_INTEGRITY_REPORT_PREFIX || "archive-integrity"
  ).replace(/^\/+|\/+$/g, "");
  const stage = getIntegrityStageName();
 
  return {
    stage,
    reportPrefix,
    writeBucketName,
  };
}
 
function getEmailAddressLookupSecretName() {
  const emailAddressLookupSecretName = (
    process.env.emailAddressLookupSecretName || "emailAddresses"
  ).trim();
  Iif (!emailAddressLookupSecretName) {
    throw new Error("emailAddressLookupSecretName must be defined");
  }
 
  return emailAddressLookupSecretName;
}
 
function parseAddressEntries(value: unknown) {
  Eif (Array.isArray(value)) {
    return value.map((entry) => String(entry || "").trim()).filter((entry) => Boolean(entry));
  }
 
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (!trimmed) {
      return [] as string[];
    }
 
    if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
      try {
        const parsed = JSON.parse(trimmed);
        if (Array.isArray(parsed)) {
          return parsed
            .map((entry) => String(entry || "").trim())
            .filter((entry) => Boolean(entry));
        }
      } catch {
        // Fall through to treat as a single address string.
      }
    }
 
    return [trimmed];
  }
 
  return [] as string[];
}
 
function parseEmailAddress(address: string): ParsedEmailAddress | undefined {
  const formatted = address.trim();
  Iif (!formatted) {
    return undefined;
  }
 
  const angleMatch = formatted.match(/<([^<>]+)>/);
  const email = angleMatch ? angleMatch[1].trim() : formatted.trim().replace(/^"|"$/g, "");
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  Iif (!emailRegex.test(email)) {
    return undefined;
  }
 
  return {
    email,
    formatted,
  };
}
 
function parseEmailAddressList(addresses: string[]) {
  const parsed: ParsedEmailAddress[] = [];
  const seenEmails = new Set<string>();
 
  for (const address of addresses) {
    const parsedAddress = parseEmailAddress(address);
    Iif (!parsedAddress) {
      continue;
    }
 
    const normalized = parsedAddress.email.toLowerCase();
    Iif (seenEmails.has(normalized)) {
      continue;
    }
 
    seenEmails.add(normalized);
    parsed.push(parsedAddress);
  }
 
  return parsed;
}
 
async function getRecipientConfig(): Promise<RecipientConfig> {
  const rawSecret = await getSecret(getEmailAddressLookupSecretName());
  const secret = JSON.parse(rawSecret || "{}") as {
    sourceEmail?: unknown;
    archiveAlerts?: unknown;
  };
  const sourceAddresses = parseEmailAddressList(parseAddressEntries(secret.sourceEmail));
  const sourceEmail = sourceAddresses[0];
  Iif (!sourceEmail) {
    throw new Error("Integrity notification secret is missing sourceEmail");
  }
 
  const toAddresses = parseEmailAddressList(parseAddressEntries(secret.archiveAlerts));
  Iif (toAddresses.length === 0) {
    throw new Error("Integrity notification secret is missing archiveAlerts");
  }
 
  return {
    sourceEmailAddress: sourceEmail.email,
    sourceEmailHeader: sourceEmail.formatted,
    toEmailAddresses: toAddresses.map((address) => address.email),
    toEmailHeaders: toAddresses.map((address) => address.formatted),
  };
}
 
function chunkBase64(value: string) {
  return value.match(/.{1,76}/g)?.join("\n") || value;
}
 
function buildRawEmail({
  sourceEmailHeader,
  toEmailHeaders,
  subject,
  bodyText,
  attachment,
}: {
  sourceEmailHeader: string;
  toEmailHeaders: string[];
  subject: string;
  bodyText: string;
  attachment?: {
    filename: string;
    contentType: string;
    body: string;
  };
}) {
  const boundary = `boundary_${randomUUID().replace(/-/g, "")}`;
 
  const lines = [
    `From: ${sourceEmailHeader}`,
    `To: ${toEmailHeaders.join(", ")}`,
    `Subject: ${subject}`,
    "MIME-Version: 1.0",
    `Content-Type: multipart/mixed; boundary="${boundary}"`,
    "",
    `--${boundary}`,
    'Content-Type: text/plain; charset="UTF-8"',
    "Content-Transfer-Encoding: 7bit",
    "",
    bodyText,
  ];
 
  if (attachment) {
    lines.push(
      `--${boundary}`,
      `Content-Type: ${attachment.contentType}; name="${attachment.filename}"`,
      `Content-Disposition: attachment; filename="${attachment.filename}"`,
      "Content-Transfer-Encoding: base64",
      "",
      chunkBase64(Buffer.from(attachment.body, "utf8").toString("base64")),
    );
  }
 
  lines.push(`--${boundary}--`, "");
  return lines.join("\n");
}
 
async function sendRawEmail({
  sourceEmailAddress,
  sourceEmailHeader,
  toEmailAddresses,
  toEmailHeaders,
  subject,
  bodyText,
  attachment,
}: {
  sourceEmailAddress: string;
  sourceEmailHeader: string;
  toEmailAddresses: string[];
  toEmailHeaders: string[];
  subject: string;
  bodyText: string;
  attachment?: {
    filename: string;
    contentType: string;
    body: string;
  };
}) {
  const rawData = buildRawEmail({
    sourceEmailHeader,
    toEmailHeaders,
    subject,
    bodyText,
    attachment,
  });
 
  await sesClient.send(
    new SendRawEmailCommand({
      RawMessage: {
        Data: Buffer.from(rawData, "utf8"),
      },
      Source: sourceEmailAddress,
      Destinations: toEmailAddresses,
    }),
  );
}
 
async function loadSummary({ bucketName, summaryKey }: { bucketName: string; summaryKey: string }) {
  return await getJsonObject<AttachmentArchiveIntegrityRunSummary>({
    client: archiveBucketClient,
    bucket: bucketName,
    key: summaryKey,
  });
}
 
async function saveSummary({
  bucketName,
  summaryKey,
  summary,
}: {
  bucketName: string;
  summaryKey: string;
  summary: AttachmentArchiveIntegrityRunSummary;
}) {
  await putJsonObject({
    client: archiveBucketClient,
    bucket: bucketName,
    key: summaryKey,
    body: summary,
  });
}
 
async function loadCsvAttachment({ bucketName, key }: { bucketName: string; key: string }) {
  const response = await archiveBucketClient.send(
    new GetObjectCommand({
      Bucket: bucketName,
      Key: key,
    }),
  );
  return (await response.Body?.transformToString()) || "";
}
 
function parseFailurePayload(error: unknown): ParsedFailurePayload {
  const fallback = {
    message: "Attachment archive integrity check failed unexpectedly.",
  };
 
  Iif (!error || typeof error !== "object") {
    return fallback;
  }
 
  const top = error as { Cause?: unknown; Error?: unknown; message?: unknown };
  const causeString =
    typeof top.Cause === "string"
      ? top.Cause
      : typeof top.message === "string"
        ? top.message
        : undefined;
 
  Iif (!causeString) {
    return fallback;
  }
 
  try {
    const parsedCause = JSON.parse(causeString) as { errorMessage?: string };
    Iif (!parsedCause.errorMessage) {
      return fallback;
    }
 
    try {
      const parsedPayload = JSON.parse(parsedCause.errorMessage) as {
        message?: string;
        summaryKey?: string;
        runId?: string;
        stage?: string;
        reportBucketName?: string;
      };
      return {
        message: parsedPayload.message || fallback.message,
        summaryKey: parsedPayload.summaryKey,
        runId: parsedPayload.runId,
        stage: parsedPayload.stage,
        reportBucketName: parsedPayload.reportBucketName,
      };
    } catch {
      return {
        message: parsedCause.errorMessage,
      };
    }
  } catch {
    return {
      message: causeString,
    };
  }
}
 
function createFailureSummary({
  runId,
  stage,
  reportPrefix,
  reportBucketName,
  message,
}: {
  runId: string;
  stage: string;
  reportPrefix: string;
  reportBucketName: string;
  message: string;
}): {
  summary: AttachmentArchiveIntegrityRunSummary;
  summaryKey: string;
} {
  const runTimestamp = new Date().toISOString();
  const date = new Date(runTimestamp);
  const yyyy = date.getUTCFullYear();
  const mm = `${date.getUTCMonth() + 1}`.padStart(2, "0");
  const dd = `${date.getUTCDate()}`.padStart(2, "0");
  const runReportPrefix = `${reportPrefix}/${stage}/runs/${yyyy}/${mm}/${dd}/${runId}`;
  const summaryKey = `${runReportPrefix}/summary.json`;
  const summary: AttachmentArchiveIntegrityRunSummary = {
    runId,
    stage,
    runTimestamp,
    status: "FAILED",
    packagesScanned: 0,
    packagesTotal: 0,
    sectionsScanned: 0,
    discrepancyCount: 0,
    discrepancyTypeCounts: {},
    exceptionCount: 0,
    exceptionTypeCounts: {},
    topDiscrepancyTypes: [],
    reportBucketName,
    reportPrefix: runReportPrefix,
    checkpointKey: "",
    discrepancyJsonKey: "",
    discrepancyCsvKey: "",
    exceptionJsonKey: "",
    exceptionCsvKey: "",
    discrepancyCsvFilename: "discrepancies.csv",
    discrepancyCsvTruncated: false,
    discrepancyCsvRowsIncluded: 0,
    discrepancyCsvRowsTotal: 0,
    notificationStatus: "PENDING",
    errorMessage: message,
  };
 
  return { summary, summaryKey };
}
 
function buildDiscrepancyEmailBody(summary: AttachmentArchiveIntegrityRunSummary) {
  const lines = [
    "OneMAC archive integrity discrepancies were detected.",
    "",
    `Stage: ${summary.stage}`,
    `Run timestamp: ${summary.runTimestamp}`,
    `Packages scanned: ${summary.packagesScanned}`,
    `Sections scanned: ${summary.sectionsScanned}`,
    `Total discrepancies: ${summary.discrepancyCount}`,
  ];
 
  if (summary.exceptionJsonKey || summary.exceptionCount > 0) {
    lines.push(`Approved terminal exceptions: ${summary.exceptionCount}`);
  }
 
  lines.push("", "Top discrepancy types:");
 
  Iif (summary.topDiscrepancyTypes.length === 0) {
    lines.push("- none");
  } else {
    for (const typeCount of summary.topDiscrepancyTypes) {
      lines.push(`- ${typeCount.type}: ${typeCount.count}`);
    }
  }
 
  lines.push(
    "",
    "CSV discrepancy report is attached.",
    summary.discrepancyCsvTruncated
      ? `Attachment was truncated (${summary.discrepancyCsvRowsIncluded}/${summary.discrepancyCsvRowsTotal} rows included).`
      : `Attachment contains ${summary.discrepancyCsvRowsIncluded} discrepancy rows.`,
  );
 
  return lines.join("\n");
}
 
function buildFailureEmailBody({
  summary,
  summaryKey,
  message,
}: {
  summary: AttachmentArchiveIntegrityRunSummary;
  summaryKey?: string;
  message: string;
}) {
  const lines = [
    "OneMAC archive integrity check failed.",
    "",
    `Stage: ${summary.stage}`,
    `Run id: ${summary.runId}`,
    summaryKey ? `Summary key: ${summaryKey}` : "Summary key: unavailable",
    summary.packagesTotal > 0
      ? `Packages scanned: ${summary.packagesScanned}/${summary.packagesTotal}`
      : `Packages scanned: ${summary.packagesScanned}`,
    `Sections scanned: ${summary.sectionsScanned}`,
    `Discrepancies found so far: ${summary.discrepancyCount}`,
  ];
 
  if (summary.lastProcessedPackageId) {
    lines.push(`Last processed package: ${summary.lastProcessedPackageId}`);
  }
 
  lines.push("", "Error details:", message);
  return lines.join("\n");
}
 
async function handleDiscrepancyNotification(event: IntegrityNotificationEvent) {
  Iif (!event.runResult?.summaryKey || !event.runResult.reportBucketName) {
    throw new Error("Discrepancy notification event is missing summary location");
  }
 
  const bucketName = event.runResult.reportBucketName;
  const summaryKey = event.runResult.summaryKey;
  const recipients = await getRecipientConfig();
  const summary = await loadSummary({
    bucketName,
    summaryKey,
  });
  Iif (!summary) {
    throw new Error(`Summary not found at ${summaryKey}`);
  }
 
  if (summary.discrepancyCount <= 0) {
    summary.notificationStatus = "SKIPPED";
    await saveSummary({
      bucketName,
      summaryKey,
      summary,
    });
    return {
      notificationStatus: summary.notificationStatus,
      summaryKey,
    };
  }
 
  try {
    const csvBody = await loadCsvAttachment({
      bucketName,
      key: summary.discrepancyCsvKey,
    });
    await sendRawEmail({
      sourceEmailAddress: recipients.sourceEmailAddress,
      sourceEmailHeader: recipients.sourceEmailHeader,
      toEmailAddresses: recipients.toEmailAddresses,
      toEmailHeaders: recipients.toEmailHeaders,
      subject: `[${summary.stage}] OneMAC Archive Integrity Discrepancies (${summary.discrepancyCount})`,
      bodyText: buildDiscrepancyEmailBody(summary),
      attachment: {
        filename: summary.discrepancyCsvFilename,
        contentType: "text/csv",
        body: csvBody,
      },
    });
 
    summary.notificationStatus = "SENT";
    summary.notificationSentAt = new Date().toISOString();
    delete summary.notificationError;
    await saveSummary({
      bucketName,
      summaryKey,
      summary,
    });
 
    return {
      notificationStatus: summary.notificationStatus,
      summaryKey,
    };
  } catch (error) {
    summary.notificationStatus = "FAILED";
    summary.notificationError = error instanceof Error ? error.message : String(error);
    await saveSummary({
      bucketName,
      summaryKey,
      summary,
    });
    throw error;
  }
}
 
async function handleFailureNotification(event: IntegrityNotificationEvent) {
  const storage = getStorageConfig();
  const recipients = await getRecipientConfig();
  const parsedFailure = parseFailurePayload(event.error);
 
  let summaryKey = parsedFailure.summaryKey || event.runResult?.summaryKey;
  let bucketName =
    parsedFailure.reportBucketName || event.runResult?.reportBucketName || storage.writeBucketName;
  let summary: AttachmentArchiveIntegrityRunSummary | undefined;
 
  if (summaryKey) {
    summary = await loadSummary({
      bucketName,
      summaryKey,
    });
  }
 
  if (!summary) {
    const failure = createFailureSummary({
      runId:
        parsedFailure.runId ||
        event.runResult?.runId ||
        `${Date.now()}-${randomUUID().slice(0, 8)}`,
      stage: parsedFailure.stage || event.runResult?.stage || storage.stage,
      reportPrefix: storage.reportPrefix,
      reportBucketName: storage.writeBucketName,
      message: parsedFailure.message,
    });
    summary = failure.summary;
    summaryKey = failure.summaryKey;
    bucketName = storage.writeBucketName;
  }
  Iif (!summaryKey) {
    throw new Error("Failure notification could not resolve summaryKey");
  }
  const resolvedSummaryKey = summaryKey;
  if (summary.status === "RUNNING") {
    summary.status = "FAILED";
  }
 
  try {
    await sendRawEmail({
      sourceEmailAddress: recipients.sourceEmailAddress,
      sourceEmailHeader: recipients.sourceEmailHeader,
      toEmailAddresses: recipients.toEmailAddresses,
      toEmailHeaders: recipients.toEmailHeaders,
      subject: `[${summary.stage}] OneMAC Archive Integrity Check Failed`,
      bodyText: buildFailureEmailBody({
        summary,
        summaryKey: resolvedSummaryKey,
        message: parsedFailure.message,
      }),
    });
 
    summary.notificationStatus = "SENT";
    summary.notificationSentAt = new Date().toISOString();
    summary.errorMessage = parsedFailure.message;
    delete summary.notificationError;
    await saveSummary({
      bucketName,
      summaryKey: resolvedSummaryKey,
      summary,
    });
  } catch (error) {
    summary.notificationStatus = "FAILED";
    summary.notificationError = error instanceof Error ? error.message : String(error);
    summary.errorMessage = parsedFailure.message;
    await saveSummary({
      bucketName,
      summaryKey: resolvedSummaryKey,
      summary,
    });
    throw error;
  }
 
  return {
    notificationStatus: summary.notificationStatus,
    summaryKey: resolvedSummaryKey,
  };
}
 
export const handler = async (event: IntegrityNotificationEvent) => {
  const normalizedEvent: IntegrityNotificationEvent = {
    ...event,
    runResult: event.runResult || event.input?.runResult,
    error: event.error || event.input?.error,
  };
 
  if (normalizedEvent.mode === "failure") {
    return await handleFailureNotification(normalizedEvent);
  }
 
  return await handleDiscrepancyNotification(normalizedEvent);
};