All files / lib/lambda getAttachmentUrl.ts

97.29% Statements 72/74
80% Branches 32/40
88.88% Functions 16/18
97.29% Lines 72/74

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                                          17x             2x     2x 2x                                 3x                                             7x                                                   1x                                                       2x                                     10x                   10x   10x 3x             3x     7x 7x               7x               1x 15x 15x   1x           14x 1x           13x 13x   13x 13x 1x           12x 12x 12x       12x 1x                 11x 11x 11x 10x     11x 1x               10x 10x                   6x   5x         5x 2x           3x                                     10x 3x 3x 1x   2x 1x     1x                     8x 8x 5x     3x   3x 1x     2x                 2x         11x 11x                 6x           6x       6x             6x 6x   6x                   6x     6x             6x       5x    
import { GetObjectCommand, HeadObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { APIGatewayEvent } from "aws-lambda";
import { response } from "libs/handler-lib";
import { getDomain } from "libs/utils";
 
import {
  getAttachmentErrorMessage,
  isAttachmentNotFoundError,
  isLegacyAttachmentUnavailableError,
} from "../attachment-archive/attachment-errors";
import {
  createAttachmentBucketClientFactory,
  getAttachmentBucketMap,
  resolveTargetBucket as resolveMappedBucket,
} from "../attachment-archive/bucket-routing";
import { getStateFilter } from "../libs/api/auth/user";
import { getPackage, getPackageChangelog } from "../libs/api/package";
import { handleOpensearchError } from "./utils";
 
function getClient(bucket: string) {
  return createAttachmentBucketClientFactory({
    region: process.env.region || process.env.AWS_REGION,
    legacyS3AccessRoleArn: process.env.legacyS3AccessRoleArn,
  })(bucket);
}
 
class AttachmentUnavailableError extends Error {
  statusCode = 410;
 
  constructor(message: string) {
    super(message);
    this.name = "AttachmentUnavailableError";
  }
}
 
function logRemapApplied({
  packageId,
  sourceBucket,
  destinationBucket,
  key,
  filename,
}: {
  packageId: string;
  sourceBucket: string;
  destinationBucket: string;
  key: string;
  filename: string;
}) {
  console.info(
    JSON.stringify({
      event: "legacy_attachment_remap_applied",
      packageId,
      sourceBucket,
      destinationBucket,
      key,
      filename,
    }),
  );
}
 
function logRemapMissingMapping({
  packageId,
  sourceBucket,
  key,
  filename,
}: {
  packageId: string;
  sourceBucket: string;
  key: string;
  filename: string;
}) {
  console.warn(
    JSON.stringify({
      event: "legacy_attachment_remap_missing_mapping",
      packageId,
      sourceBucket,
      key,
      filename,
    }),
  );
}
 
function logRemapFallback({
  packageId,
  sourceBucket,
  destinationBucket,
  key,
  filename,
  reason,
}: {
  packageId: string;
  sourceBucket: string;
  destinationBucket: string;
  key: string;
  filename: string;
  reason: string;
}) {
  console.warn(
    JSON.stringify({
      event: "legacy_attachment_remap_fallback",
      packageId,
      sourceBucket,
      destinationBucket,
      key,
      filename,
      reason,
    }),
  );
}
 
function logAttachmentUnavailable({
  packageId,
  sourceBucket,
  destinationBucket,
  key,
  filename,
  reason,
}: {
  packageId: string;
  sourceBucket: string;
  destinationBucket?: string;
  key: string;
  filename: string;
  reason: string;
}) {
  console.warn(
    JSON.stringify({
      event: "legacy_attachment_unavailable",
      packageId,
      sourceBucket,
      destinationBucket,
      key,
      filename,
      reason,
    }),
  );
}
 
function resolveTargetBucket(
  packageId: string,
  sourceBucket: string,
  key: string,
  filename: string,
): { sourceBucket: string; destinationBucket: string; remapped: boolean } {
  const attachmentBucketMap = getAttachmentBucketMap(
    process.env.LEGACY_ATTACHMENT_BUCKET_MAP,
    (message) =>
      console.warn(
        JSON.stringify({
          event: "legacy_attachment_bucket_map_invalid",
          message,
        }),
      ),
  );
  const bucketResolution = resolveMappedBucket(sourceBucket, attachmentBucketMap);
 
  if (bucketResolution.remapped) {
    logRemapApplied({
      packageId,
      sourceBucket,
      destinationBucket: bucketResolution.destinationBucket,
      key,
      filename,
    });
    return bucketResolution;
  }
 
  Eif (sourceBucket.startsWith("uploads")) {
    logRemapMissingMapping({
      packageId,
      sourceBucket,
      key,
      filename,
    });
  }
 
  return {
    sourceBucket: bucketResolution.sourceBucket,
    destinationBucket: bucketResolution.destinationBucket,
    remapped: bucketResolution.remapped,
  };
}
 
// Handler function to get Seatool data
export const handler = async (event: APIGatewayEvent) => {
  try {
    getDomain();
  } catch (error) {
    return response({
      statusCode: 500,
      body: { message: `ERROR: ${error?.message || error}` },
    });
  }
 
  if (!event.body) {
    return response({
      statusCode: 400,
      body: { message: "Event body required" },
    });
  }
 
  try {
    const body = JSON.parse(event.body);
 
    const mainResult = await getPackage(body.id);
    if (!mainResult || !mainResult.found) {
      return response({
        statusCode: 404,
        body: { message: "No record found for the given id" },
      });
    }
 
    const stateFilter = await getStateFilter(event);
    Eif (stateFilter) {
      const stateAccessAllowed = stateFilter?.terms.state.includes(
        mainResult?._source?.state?.toLocaleLowerCase() || "",
      );
 
      if (!stateAccessAllowed) {
        return response({
          statusCode: 403,
          body: { message: "state access not permitted for the given id" },
        });
      }
    }
 
    // add state
    // Do we want to check
    const changelogs = await getPackageChangelog(body.id);
    const attachmentExists = changelogs.hits.hits.some((CL) => {
      return CL._source.attachments?.some(
        (ATT) => ATT.bucket === body.bucket && ATT.key === body.key,
      );
    });
    if (!attachmentExists) {
      return response({
        statusCode: 500,
        body: {
          message: "Attachment details not found for given record id.",
        },
      });
    }
 
    const bucketResolution = resolveTargetBucket(body.id, body.bucket, body.key, body.filename);
    const bucketToSign = await resolveDownloadBucket({
      packageId: body.id,
      sourceBucket: bucketResolution.sourceBucket,
      destinationBucket: bucketResolution.destinationBucket,
      remapped: bucketResolution.remapped,
      key: body.key,
      filename: body.filename,
    });
 
    // Now we can generate the presigned url
    const url = await generatePresignedUrl(bucketToSign, body.key, body.filename, 60);
 
    return response<unknown>({
      statusCode: 200,
      body: { url },
    });
  } catch (error) {
    if (error instanceof AttachmentUnavailableError) {
      return response({
        statusCode: error.statusCode,
        body: { message: error.message },
      });
    }
 
    return response(handleOpensearchError(error));
  }
};
 
async function resolveDownloadBucket({
  packageId,
  sourceBucket,
  destinationBucket,
  remapped,
  key,
  filename,
}: {
  packageId: string;
  sourceBucket: string;
  destinationBucket: string;
  remapped: boolean;
  key: string;
  filename: string;
}) {
  if (remapped) {
    try {
      await assertObjectAccessible(destinationBucket, key);
      return destinationBucket;
    } catch (error) {
      if (!isAttachmentNotFoundError(error)) {
        throw error;
      }
 
      logRemapFallback({
        packageId,
        sourceBucket,
        destinationBucket,
        key,
        filename,
        reason: error instanceof Error ? error.message : String(error),
      });
    }
  }
 
  try {
    await assertObjectAccessible(sourceBucket, key);
    return sourceBucket;
  } catch (error) {
    const attachmentUnavailable =
      isAttachmentNotFoundError(error) || isLegacyAttachmentUnavailableError(sourceBucket, error);
 
    if (!attachmentUnavailable) {
      throw error;
    }
 
    logAttachmentUnavailable({
      packageId,
      sourceBucket,
      destinationBucket: remapped ? destinationBucket : undefined,
      key,
      filename,
      reason: getAttachmentErrorMessage(error),
    });
 
    throw new AttachmentUnavailableError("This attachment is no longer available.");
  }
}
 
async function assertObjectAccessible(bucket: string, key: string) {
  const client = await getClient(bucket);
  await client.send(
    new HeadObjectCommand({
      Bucket: bucket,
      Key: key,
    }),
  );
}
 
function getAsciiFilename(filename: string) {
  const sanitized = filename
    .normalize("NFKD")
    .replace(/[^\x20-\x7E]+/g, "_")
    .replace(/["\\]/g, "_")
    .trim();
 
  return sanitized || "download";
}
 
function encodeContentDispositionFilename(filename: string) {
  return encodeURIComponent(filename).replace(
    /['()*]/g,
    (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
  );
}
 
function buildResponseContentDisposition(filename: string) {
  const asciiFilename = getAsciiFilename(filename);
  const encodedFilename = encodeContentDispositionFilename(filename);
 
  return `attachment; filename="${asciiFilename}"; filename*=UTF-8''${encodedFilename}`;
}
 
async function generatePresignedUrl(
  bucket: string,
  key: string,
  filename: string,
  expirationInSeconds: number,
) {
  // Get an S3 client
  const client = await getClient(bucket);
 
  // Create a command to get the object (you can adjust this according to your use case)
  const getObjectCommand = new GetObjectCommand({
    Bucket: bucket,
    Key: key,
    ResponseContentDisposition: buildResponseContentDisposition(filename),
  });
 
  // Generate a presigned URL
  const presignedUrl = await getSignedUrl(client, getObjectCommand, {
    expiresIn: expirationInSeconds,
  });
 
  return presignedUrl;
}