11'use strict' ;
22import * as Minio from 'minio' ;
3+ import Http from 'http' ;
4+ import Https from 'https' ;
5+
6+ import { getAWSInstanceCredentials } from '../utils/aws' ;
37
4- var minioClient ;
58const {
69 STORAGE_HOST ,
710 STORAGE_PORT ,
@@ -12,30 +15,64 @@ const {
1215 STORAGE_REGION
1316} = process . env ;
1417
15- switch ( STORAGE_ENGINE ) {
16- case 'minio' :
17- minioClient = new Minio . Client ( {
18- endPoint : STORAGE_HOST ,
19- port : parseInt ( STORAGE_PORT ) ,
20- secure : false ,
21- accessKey : STORAGE_ACCESS_KEY ,
22- secretKey : STORAGE_SECRET_KEY
23- } ) ;
24- break ;
25- case 's3' :
26- minioClient = new Minio . Client ( {
27- // Endpoint gets updated based on region.
28- endPoint : 's3.amazonaws.com' ,
29- region : STORAGE_REGION ,
30- accessKey : STORAGE_ACCESS_KEY ,
31- secretKey : STORAGE_SECRET_KEY
32- } ) ;
33- break ;
34- default :
35- throw new Error ( 'Invalid storage engine. Use s3 or minio' ) ;
36- }
37-
38- export default minioClient ;
39-
4018export const bucket = STORAGE_BUCKET ;
4119export const region = STORAGE_REGION ;
20+
21+ /**
22+ * Initializes the minio s3 client depending on the engine and credentials
23+ * source in use. Needs to be a promise because it may rely on asynchronously
24+ * fetched credentials.
25+ *
26+ * @returns Minio Client
27+ */
28+ export default async function S3 ( ) {
29+ let minioClient ;
30+ let agent ;
31+
32+ switch ( STORAGE_ENGINE ) {
33+ case 'minio' :
34+ minioClient = new Minio . Client ( {
35+ endPoint : STORAGE_HOST ,
36+ port : parseInt ( STORAGE_PORT ) ,
37+ secure : false ,
38+ accessKey : STORAGE_ACCESS_KEY ,
39+ secretKey : STORAGE_SECRET_KEY
40+ } ) ;
41+ agent = Http . globalAgent ;
42+ break ;
43+ case 's3' :
44+ let credentials ;
45+ if ( ! STORAGE_ACCESS_KEY && ! STORAGE_SECRET_KEY ) {
46+ // If we're using a S3 storage engine but no accessKey and secretKey
47+ // are set up, we assume that it is being run from a EC2 instance and
48+ // will try to get the credentials through the url. We're not throwing
49+ // any error if it fails because that is checked on startup.
50+ // See app/index.js
51+ const AWSInstanceCredentials = await getAWSInstanceCredentials ( ) ;
52+ credentials = {
53+ accessKey : AWSInstanceCredentials . accessKey ,
54+ secretKey : AWSInstanceCredentials . secretKey ,
55+ sessionToken : AWSInstanceCredentials . sessionToken
56+ } ;
57+ } else {
58+ credentials = {
59+ accessKey : STORAGE_ACCESS_KEY ,
60+ secretKey : STORAGE_SECRET_KEY
61+ } ;
62+ }
63+
64+ minioClient = new Minio . Client ( {
65+ endPoint : 's3.amazonaws.com' ,
66+ ...credentials
67+ } ) ;
68+ agent = Https . globalAgent ;
69+ break ;
70+ default :
71+ throw new Error ( 'Invalid storage engine. Use s3 or minio' ) ;
72+ }
73+
74+ // Temp fix for https://github.com/minio/minio-js/issues/641
75+ minioClient . agent = agent ;
76+
77+ return minioClient ;
78+ }
0 commit comments