feat: Support IAM role authentication for S3 (#2830)

closes #2829
This commit is contained in:
Zero King
2021-12-11 01:08:03 +00:00
committed by GitHub
parent 05b9ae3e63
commit 11e14bc4f5
12 changed files with 44 additions and 19 deletions

View File

@@ -1,4 +1,5 @@
import crypto from "crypto";
import util from "util";
import AWS from "aws-sdk";
import { addHours, format } from "date-fns";
import fetch from "fetch-with-proxy";
@@ -24,6 +25,10 @@ const s3 = new AWS.S3({
new AWS.Endpoint(process.env.AWS_S3_UPLOAD_BUCKET_URL),
signatureVersion: "v4",
});
const createPresignedPost = util.promisify<
AWS.S3.PresignedPost.Params,
AWS.S3.PresignedPost
>(s3.createPresignedPost);
const hmac = (
key: string | Buffer,
@@ -93,6 +98,29 @@ export const getSignature = (policy: string) => {
return signature;
};
export const getPresignedPost = (
key: string,
acl: string,
contentType = "image"
) => {
const params = {
Bucket: process.env.AWS_S3_UPLOAD_BUCKET_NAME,
Conditions: [
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
["content-length-range", 0, +process.env.AWS_S3_UPLOAD_MAX_SIZE],
["starts-with", "$Content-Type", contentType],
["starts-with", "$Cache-Control", ""],
],
Fields: {
key,
acl,
},
Expires: 3600,
};
return createPresignedPost(params);
};
export const publicS3Endpoint = (isServerUpload?: boolean) => {
// lose trailing slash if there is one and convert fake-s3 url to localhost
// for access outside of docker containers in local development