All files / lib/lambda getExternalAttachmentUrl.ts

94.35% Statements 117/124
89.92% Branches 125/139
100% Functions 16/16
94.35% Lines 117/124

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                            1x 1x 1x                                                                   8x             11x 11x 11x       19x 16x     3x           1x     2x       24x 24x   24x 1x     23x 23x 19x     4x       4x       23x 60x         13x 1x     12x 12x 1x     11x 11x       11x 11x 11x 11x 2x     2x     11x                         9x 1x     8x 8x 1x     7x                 26x 1x       25x 25x   1x     24x 24x 1x     23x 14x 1x     13x     9x       18x 18x       18x 18x       69x                 1x 2x 2x       2x           2x             2x 1x       1x             1x             1x 1x 1x 1x                                           7x 7x 1x           6x 6x 6x             5x 1x               4x 1x 1x             1x                     3x             1x           2x                   2x                             1x 26x 26x 8x     18x 18x 1x           17x 17x 17x   17x 1x           16x 7x           9x 1x           8x                   5x                     4x 2x 1x           1x 1x             2x 2x 1x     1x            
import { APIGatewayProxyEvent } from "aws-lambda";
import { response } from "libs/handler-lib";
import { opensearch } from "shared-types";
 
import { sendAttachmentArchiveRebuildRequest } from "../attachment-archive/rebuild-queue";
import { getPackage, getPackageChangelog } from "../libs/api/package";
import { getRequestedAttachmentArchiveDownload } from "./attachmentArchive-lib";
import {
  getActiveClient,
  getExternalApiAuthConfig,
  isClientAllowedForObject,
} from "./external-auth";
import { generatePresignedDownloadUrl, isS3ObjectAccessError } from "./presignedAttachmentUrl";
 
const DEFAULT_EXPIRATION_SECONDS = 60;
const MAX_EXPIRATION_SECONDS = 604800;
const DEFAULT_ARCHIVE_ERROR_MESSAGE = "Unable to prepare the attachment archive.";
 
type AttachmentRequestBody = {
  bucket?: unknown;
  key?: unknown;
  objectName?: unknown;
  filename?: unknown;
  fileName?: unknown;
  expiresIn?: unknown;
  packageId?: unknown;
  sectionId?: unknown;
  section?: unknown;
};
 
type ParsedObjectRequest = {
  mode: "object";
  bucket: string;
  key: string;
  filename: string;
  expiresIn: number;
};
 
type ParsedArchiveRequest = {
  mode: "archive";
  expiresIn: number;
  packageId: string;
  sectionId?: string;
};
 
type ParsedRequest = ParsedObjectRequest | ParsedArchiveRequest;
 
type ErrorResponse = ReturnType<typeof badRequest>;
 
function badRequest(message: string) {
  return response({
    statusCode: 400,
    body: { message },
  });
}
 
function defaultFilenameFromKey(key: string) {
  const normalizedKey = key.replace(/\/+$/, "");
  const keySegments = normalizedKey.split("/");
  return keySegments[keySegments.length - 1] || normalizedKey;
}
 
function parseExpiresIn(expiresIn: unknown): number | ErrorResponse {
  if (expiresIn === undefined) {
    return DEFAULT_EXPIRATION_SECONDS;
  }
 
  if (
    typeof expiresIn !== "number" ||
    !Number.isInteger(expiresIn) ||
    expiresIn < 1 ||
    expiresIn > MAX_EXPIRATION_SECONDS
  ) {
    return badRequest(`expiresIn must be an integer between 1 and ${MAX_EXPIRATION_SECONDS}.`);
  }
 
  return expiresIn;
}
 
function parseOptionalSectionId(body: AttachmentRequestBody): string | undefined | ErrorResponse {
  const rawSectionId = body.sectionId;
  const rawSection = body.section;
 
  if (rawSectionId !== undefined && rawSection !== undefined && rawSectionId !== rawSection) {
    return badRequest("section and sectionId must match when both are provided.");
  }
 
  const sectionValue = rawSectionId ?? rawSection;
  if (sectionValue === undefined) {
    return undefined;
  }
 
  Iif (typeof sectionValue !== "string" || sectionValue.trim() === "") {
    return badRequest("sectionId must be a non-empty string when provided.");
  }
 
  return sectionValue.trim();
}
 
function isObjectLocatorFieldPresent(body: AttachmentRequestBody): boolean {
  return [body.bucket, body.key, body.objectName, body.filename, body.fileName].some(
    (value) => value !== undefined,
  );
}
 
function parseObjectRequest(body: AttachmentRequestBody): ParsedObjectRequest | ErrorResponse {
  if (typeof body.bucket !== "string" || body.bucket.trim() === "") {
    return badRequest("bucket is required.");
  }
 
  const keyCandidate = body.key ?? body.objectName ?? body.filename ?? body.fileName;
  if (typeof keyCandidate !== "string" || keyCandidate.trim() === "") {
    return badRequest("key is required.");
  }
 
  const expiresIn = parseExpiresIn(body.expiresIn);
  Iif (isErrorResponse(expiresIn)) {
    return expiresIn;
  }
 
  const normalizedKey = keyCandidate.trim();
  const rawFilename = body.filename ?? body.fileName;
  let filename = defaultFilenameFromKey(normalizedKey);
  if (rawFilename !== undefined) {
    Iif (typeof rawFilename !== "string" || rawFilename.trim() === "") {
      return badRequest("filename must be a non-empty string when provided.");
    }
    filename = rawFilename.trim();
  }
 
  return {
    mode: "object",
    bucket: body.bucket.trim(),
    key: normalizedKey,
    filename,
    expiresIn,
  };
}
 
function parseArchiveRequest(
  body: AttachmentRequestBody,
  sectionId: string | undefined,
): ParsedArchiveRequest | ErrorResponse {
  if (typeof body.packageId !== "string" || body.packageId.trim() === "") {
    return badRequest("packageId is required when requesting an archive.");
  }
 
  const expiresIn = parseExpiresIn(body.expiresIn);
  if (isErrorResponse(expiresIn)) {
    return expiresIn;
  }
 
  return {
    mode: "archive",
    expiresIn,
    packageId: body.packageId.trim(),
    ...(sectionId ? { sectionId } : {}),
  };
}
 
function parseRequestBody(event: APIGatewayProxyEvent): ParsedRequest | ErrorResponse {
  if (!event.body) {
    return badRequest("Request body is required.");
  }
 
  let body: AttachmentRequestBody;
  try {
    body = JSON.parse(event.body);
  } catch {
    return badRequest("Invalid JSON payload.");
  }
 
  const sectionId = parseOptionalSectionId(body);
  if (isErrorResponse(sectionId)) {
    return sectionId;
  }
 
  if (isObjectLocatorFieldPresent(body)) {
    if (sectionId) {
      return badRequest("sectionId cannot be combined with bucket/key attachment requests.");
    }
 
    return parseObjectRequest(body);
  }
 
  return parseArchiveRequest(body, sectionId);
}
 
function getClientIdFromAuthorizer(event: APIGatewayProxyEvent): string | null {
  const authorizer = event.requestContext.authorizer;
  Iif (!authorizer || typeof authorizer !== "object") {
    return null;
  }
 
  const clientId = (authorizer as Record<string, unknown>).clientId;
  return typeof clientId === "string" && clientId.trim() ? clientId : null;
}
 
function isErrorResponse(value: unknown): value is ErrorResponse {
  return (
    typeof value === "object" &&
    value !== null &&
    "statusCode" in value &&
    typeof (value as { statusCode?: unknown }).statusCode === "number"
  );
}
 
function getLatestChangelogTimestamp(changelog: Array<{ _source?: { timestamp?: number } }>) {
  return changelog.reduce<number | undefined>((latest, item) => {
    const timestamp = item._source?.timestamp;
    Iif (typeof timestamp !== "number") {
      return latest;
    }
 
    return latest === undefined ? timestamp : Math.max(latest, timestamp);
  }, undefined);
}
 
function getKnownErrorResponse(error: unknown) {
  const statusCode =
    typeof error === "object" &&
    error !== null &&
    "statusCode" in error &&
    typeof (error as { statusCode?: unknown }).statusCode === "number"
      ? (error as { statusCode: number }).statusCode
      : undefined;
 
  if (!statusCode) {
    return undefined;
  }
 
  const rawMessage =
    typeof error === "object" &&
    error !== null &&
    "message" in error &&
    typeof (error as { message?: unknown }).message === "string"
      ? (error as { message: string }).message
      : undefined;
 
  Iif (!rawMessage) {
    return response({
      statusCode,
      body: { message: "Request failed." },
    });
  }
 
  try {
    const parsed = JSON.parse(rawMessage) as { message?: string };
    Eif (typeof parsed.message === "string" && parsed.message) {
      return response({
        statusCode,
        body: { message: parsed.message },
      });
    }
  } catch {
    // Fall through to use the raw message.
  }
 
  return response({
    statusCode,
    body: { message: rawMessage },
  });
}
 
async function handleArchiveRequest({
  client,
  request,
}: {
  client: NonNullable<ReturnType<typeof getActiveClient>>;
  request: ParsedArchiveRequest;
}) {
  const mainResult = await getPackage(request.packageId);
  if (!mainResult || !mainResult.found) {
    return response({
      statusCode: 404,
      body: { message: "No record found for the given packageId" },
    });
  }
 
  const changelogResponse = await getPackageChangelog(request.packageId);
  const changelog = changelogResponse.hits.hits as opensearch.changelog.ItemResult[];
  const archiveResult = await getRequestedAttachmentArchiveDownload({
    packageId: request.packageId,
    scope: request.sectionId ? "section" : "all",
    sectionId: request.sectionId,
    changelog,
  });
 
  if (archiveResult.response.status === "FAILED") {
    return response({
      statusCode: 409,
      body: {
        message: archiveResult.response.message || DEFAULT_ARCHIVE_ERROR_MESSAGE,
      },
    });
  }
 
  if (archiveResult.response.status === "PENDING") {
    Eif (archiveResult.needsRebuild) {
      await sendAttachmentArchiveRebuildRequest({
        packageId: request.packageId,
        latestTimestamp: getLatestChangelogTimestamp(changelog),
        source: "request",
      });
    }
 
    return response({
      statusCode: 200,
      body: {
        status: "PENDING",
        pollAfterSeconds: archiveResult.response.pollAfterSeconds,
        packageId: request.packageId,
        ...(request.sectionId ? { sectionId: request.sectionId } : {}),
      },
    });
  }
 
  if (
    !isClientAllowedForObject(
      client,
      archiveResult.response.bucketName,
      archiveResult.response.artifactKey,
    )
  ) {
    return response({
      statusCode: 403,
      body: { message: "Client is not allowed to access the requested object." },
    });
  }
 
  const url = await generatePresignedDownloadUrl(
    archiveResult.response.bucketName,
    archiveResult.response.artifactKey,
    archiveResult.response.filename,
    request.expiresIn,
    {
      validateObjectAccess: true,
    },
  );
 
  return response({
    statusCode: 200,
    body: {
      status: "READY",
      target: request.sectionId ? "sectionArchive" : "packageArchive",
      filename: archiveResult.response.filename,
      url,
      expiresIn: request.expiresIn,
      ...(archiveResult.response.warningMessage
        ? { warningMessage: archiveResult.response.warningMessage }
        : {}),
    },
  });
}
 
export const handler = async (event: APIGatewayProxyEvent) => {
  const parsedRequest = parseRequestBody(event);
  if (isErrorResponse(parsedRequest)) {
    return parsedRequest;
  }
 
  const clientId = getClientIdFromAuthorizer(event);
  if (!clientId) {
    return response({
      statusCode: 401,
      body: { message: "Unauthorized" },
    });
  }
 
  try {
    const config = await getExternalApiAuthConfig();
    const client = getActiveClient(config, clientId);
 
    if (!client || !client.grants.includes("client_credentials")) {
      return response({
        statusCode: 403,
        body: { message: "Client is not authorized for this endpoint." },
      });
    }
 
    if (parsedRequest.mode === "archive") {
      return await handleArchiveRequest({
        client,
        request: parsedRequest,
      });
    }
 
    if (!isClientAllowedForObject(client, parsedRequest.bucket, parsedRequest.key)) {
      return response({
        statusCode: 403,
        body: { message: "Client is not allowed to access the requested object." },
      });
    }
 
    const url = await generatePresignedDownloadUrl(
      parsedRequest.bucket,
      parsedRequest.key,
      parsedRequest.filename,
      parsedRequest.expiresIn,
      {
        validateObjectAccess: true,
      },
    );
 
    return response({
      statusCode: 200,
      body: {
        status: "READY",
        target: "object",
        filename: parsedRequest.filename,
        url,
        expiresIn: parsedRequest.expiresIn,
      },
    });
  } catch (error) {
    if (isS3ObjectAccessError(error)) {
      if (error.s3Status === 403) {
        return response({
          statusCode: 403,
          body: { message: "Access to the requested S3 object is denied." },
        });
      }
 
      Eif (error.s3Status === 404) {
        return response({
          statusCode: 404,
          body: { message: "Requested S3 object was not found." },
        });
      }
    }
 
    const knownErrorResponse = getKnownErrorResponse(error);
    if (knownErrorResponse) {
      return knownErrorResponse;
    }
 
    return response({
      statusCode: 500,
      body: { message: "Internal server error." },
    });
  }
};