All files / lib/lambda presignedAttachmentUrl.ts

74.46% Statements 35/47
31.42% Branches 11/35
80% Functions 8/10
74.46% Lines 35/47

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        3x                             1x       1x 1x 1x 1x 1x                                     13x           13x       13x             13x 13x   13x               1x 1x 1x   1x 1x                     5x 1x 1x             1x 1x       1x                 4x       2x 2x             1x 1x 1x                         5x 5x 2x     4x           4x        
import { GetObjectCommand, HeadObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
 
const LEGACY_BUCKET_PREFIX = "uploads";
 
type S3ErrorLike = Error & {
  $metadata?: {
    httpStatusCode?: number;
  };
  Code?: string;
  code?: string;
};
 
export type PresignedDownloadUrlOptions = {
  validateObjectAccess?: boolean;
};
 
export class S3ObjectAccessError extends Error {
  readonly kind = "S3_OBJECT_ACCESS";
  readonly s3Status: 403 | 404;
 
  constructor(s3Status: 403 | 404, message: string, cause?: unknown) {
    super(message);
    this.name = "S3ObjectAccessError";
    this.s3Status = s3Status;
    Eif (cause !== undefined) {
      (this as Error & { cause?: unknown }).cause = cause;
    }
  }
}
 
export function isS3ObjectAccessError(error: unknown): error is S3ObjectAccessError {
  if (error instanceof S3ObjectAccessError) {
    return true;
  }
 
  if (typeof error !== "object" || error === null) {
    return false;
  }
 
  const candidate = error as { kind?: string; s3Status?: number };
  return candidate.kind === "S3_OBJECT_ACCESS" && [403, 404].includes(candidate.s3Status || 0);
}
 
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()}`,
  );
}
 
export function buildResponseContentDisposition(filename: string) {
  const asciiFilename = getAsciiFilename(filename);
  const encodedFilename = encodeContentDispositionFilename(filename);
 
  return `attachment; filename="${asciiFilename}"; filename*=UTF-8''${encodedFilename}`;
}
 
function mapS3ObjectAccessError(
  error: unknown,
  bucket: string,
  key: string,
): S3ObjectAccessError | null {
  const s3Error = error as S3ErrorLike;
  const statusCode = s3Error?.$metadata?.httpStatusCode;
  const code = s3Error?.name || s3Error?.Code || s3Error?.code;
 
  Eif (statusCode === 403 || code === "AccessDenied" || code === "Forbidden") {
    return new S3ObjectAccessError(403, `Access denied for s3://${bucket}/${key}`, error);
  }
 
  if (statusCode === 404 || code === "NotFound" || code === "NoSuchKey") {
    return new S3ObjectAccessError(404, `Object not found at s3://${bucket}/${key}`, error);
  }
 
  return null;
}
 
async function getClientForBucket(bucket: string): Promise<S3Client> {
  if (bucket.startsWith(LEGACY_BUCKET_PREFIX)) {
    const stsClient = new STSClient({ region: process.env.region });
    const assumedRoleResponse = await stsClient.send(
      new AssumeRoleCommand({
        RoleArn: process.env.legacyS3AccessRoleArn,
        RoleSessionName: "AssumedRoleSession",
      }),
    );
 
    const assumedCredentials = assumedRoleResponse.Credentials;
    Iif (!assumedCredentials) {
      throw new Error("No assumed credentials");
    }
 
    return new S3Client({
      credentials: {
        accessKeyId: assumedCredentials.AccessKeyId as string,
        secretAccessKey: assumedCredentials.SecretAccessKey as string,
        sessionToken: assumedCredentials.SessionToken,
      },
    });
  }
 
  return new S3Client({});
}
 
async function validateObjectAccess(client: S3Client, bucket: string, key: string): Promise<void> {
  try {
    await client.send(
      new HeadObjectCommand({
        Bucket: bucket,
        Key: key,
      }),
    );
  } catch (error) {
    const mappedError = mapS3ObjectAccessError(error, bucket, key);
    Eif (mappedError) {
      throw mappedError;
    }
    throw error;
  }
}
 
export async function generatePresignedDownloadUrl(
  bucket: string,
  key: string,
  filename: string,
  expirationInSeconds: number,
  options?: PresignedDownloadUrlOptions,
): Promise<string> {
  const client = await getClientForBucket(bucket);
  if (options?.validateObjectAccess) {
    await validateObjectAccess(client, bucket, key);
  }
 
  const getObjectCommand = new GetObjectCommand({
    Bucket: bucket,
    Key: key,
    ResponseContentDisposition: buildResponseContentDisposition(filename),
  });
 
  return getSignedUrl(client, getObjectCommand, {
    expiresIn: expirationInSeconds,
  });
}