Files
cloudron-box/src/storage/s3.js

561 lines
23 KiB
JavaScript
Raw Normal View History

2015-08-24 11:13:21 -07:00
'use strict';
exports = module.exports = {
getAvailableSize,
2021-02-01 14:23:15 -08:00
upload,
exists,
2021-02-01 14:23:15 -08:00
download,
copy,
2021-02-01 14:23:15 -08:00
listDir,
2018-07-28 09:05:44 -07:00
2021-02-01 14:23:15 -08:00
remove,
removeDir,
cleanup,
2021-02-01 14:23:15 -08:00
testConfig,
removePrivateFields,
injectPrivateFields,
2017-04-18 19:15:56 +02:00
// Used to mock AWS
2022-04-15 09:25:54 -05:00
_chunk: chunk
2015-08-24 11:13:21 -07:00
};
2021-06-16 22:36:01 -07:00
const assert = require('assert'),
async = require('async'),
2019-10-22 20:36:20 -07:00
BoxError = require('../boxerror.js'),
2025-02-12 20:56:46 +01:00
{ ConfiguredRetryStrategy } = require('@smithy/util-retry'),
constants = require('../constants.js'),
2025-02-13 19:23:04 +01:00
consumers = require('node:stream/consumers'),
debug = require('debug')('box:storage/s3'),
2025-02-12 20:56:46 +01:00
http = require('http'),
https = require('https'),
2025-02-12 20:56:46 +01:00
{ NodeHttpHandler } = require('@smithy/node-http-handler'),
{ PassThrough } = require('node:stream'),
path = require('path'),
2025-02-13 19:23:04 +01:00
{ Readable } = require('stream'),
2025-02-12 20:56:46 +01:00
{ S3 } = require('@aws-sdk/client-s3'),
2022-04-14 07:59:50 -05:00
safe = require('safetydance'),
2025-02-12 20:56:46 +01:00
{ Upload } = require('@aws-sdk/lib-storage');
2017-04-18 19:15:56 +02:00
2018-07-30 07:39:34 -07:00
function S3_NOT_FOUND(error) {
return error.code === 'NoSuchKey' || error.code === 'NotFound' || error.code === 'ENOENT';
}
2025-02-12 20:56:46 +01:00
const RETRY_STRATEGY = new ConfiguredRetryStrategy(10 /* max attempts */, (/* attempt */) => 20000 /* constant backoff */);
function createS3Client(apiConfig, options) {
2016-03-31 09:48:01 -07:00
assert.strictEqual(typeof apiConfig, 'object');
2025-02-12 20:56:46 +01:00
assert.strictEqual(typeof options, 'object');
2015-08-24 11:13:21 -07:00
2022-04-14 07:35:41 -05:00
const credentials = {
2016-03-31 09:48:01 -07:00
accessKeyId: apiConfig.accessKeyId,
2025-02-12 20:56:46 +01:00
secretAccessKey: apiConfig.secretAccessKey
2015-11-06 18:22:29 -08:00
};
2025-02-12 20:56:46 +01:00
const requestHandler = new NodeHttpHandler({
connectionTimeout: 60000,
socketTimeout: 20 * 60 * 1000
});
2025-02-12 20:56:46 +01:00
// sdk v3 only has signature support v4
const clientConfig = {
forcePathStyle: apiConfig.s3ForcePathStyle === true ? true : false, // Use vhost style instead of path style - https://forums.aws.amazon.com/ann.jspa?annID=6776
region: apiConfig.region || 'us-east-1',
credentials,
requestHandler: requestHandler
};
if (options.retryStrategy) clientConfig.retryStrategy = options.retryStrategy;
if (apiConfig.endpoint) clientConfig.endpoint = apiConfig.endpoint;
// s3 endpoint names come from the SDK
2025-02-12 20:56:46 +01:00
const isHttps = clientConfig.endpoint?.startsWith('https://') || apiConfig.provider === 's3';
if (isHttps) {
if (apiConfig.acceptSelfSignedCerts || apiConfig.bucket.includes('.')) {
2025-02-12 20:56:46 +01:00
requestHandler.agent = new https.Agent({ rejectUnauthorized: false });
}
2025-02-12 20:56:46 +01:00
} else { // http agent is required for http endpoints
requestHandler.agent = new http.Agent({});
}
2022-04-14 07:35:41 -05:00
2025-02-12 20:56:46 +01:00
return constants.TEST ? new globalThis.S3Mock(clientConfig) : new S3(clientConfig);
2015-08-24 11:13:21 -07:00
}
2015-08-25 10:01:04 -07:00
async function getAvailableSize(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return Number.POSITIVE_INFINITY;
}
async function upload(apiConfig, backupFilePath) {
2016-09-16 11:21:08 +02:00
assert.strictEqual(typeof apiConfig, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof backupFilePath, 'string');
2016-09-16 11:21:08 +02:00
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY });
2022-04-14 07:35:41 -05:00
// s3.upload automatically does a multi-part upload. we set queueSize to 3 to reduce memory usage
// uploader will buffer at most queueSize * partSize bytes into memory at any given time.
// scaleway only supports 1000 parts per object (https://www.scaleway.com/en/docs/s3-multipart-upload/)
// s3: https://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html (max 10k parts and no size limit on the last part!)
const partSize = apiConfig.limits?.uploadPartSize || (apiConfig.provider === 'scaleway-objectstorage' ? 100 * 1024 * 1024 : 10 * 1024 * 1024);
2019-09-30 20:42:37 -07:00
const passThrough = new PassThrough();
2025-02-12 20:56:46 +01:00
const options = {
client: s3,
params: {
Bucket: apiConfig.bucket,
Key: backupFilePath,
Body: passThrough
},
partSize,
queueSize: 3,
leavePartsOnError: false
};
2018-03-20 18:19:14 -07:00
2025-02-12 20:56:46 +01:00
const managedUpload = constants.TEST ? new globalThis.S3MockUpload(options) : new Upload(options);
managedUpload.on('httpUploadProgress', (progress) => debug(`Upload progress: ${JSON.stringify(progress)}`));
2025-02-12 20:56:46 +01:00
const uploadPromise = managedUpload.done();
return {
stream: passThrough,
async finish() {
const [error, data] = await safe(uploadPromise);
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Upload error: code: ${error.code} message: ${error.message}`); // sometimes message is null
debug(`Upload finished. ${JSON.stringify(data)}`);
}
};
2015-08-25 10:01:04 -07:00
}
2022-04-14 08:07:03 -05:00
async function exists(apiConfig, backupFilePath) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof backupFilePath, 'string');
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: null });
2022-04-14 07:35:41 -05:00
if (!backupFilePath.endsWith('/')) { // check for file
const params = {
Bucket: apiConfig.bucket,
Key: backupFilePath
};
2025-02-12 20:56:46 +01:00
const [error, response] = await safe(s3.headObject(params));
2022-04-14 08:07:03 -05:00
if (error && S3_NOT_FOUND(error)) return false;
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error headObject ${backupFilePath}. Message: ${error.message} HTTP Code: ${error.code}`);
2024-07-14 22:04:12 +02:00
if (!response || typeof response.Metadata !== 'object') throw new BoxError(BoxError.EXTERNAL_ERROR, 'not a s3 endpoint');
2022-04-14 08:07:03 -05:00
return true;
2022-04-14 07:35:41 -05:00
} else { // list dir contents
const listParams = {
Bucket: apiConfig.bucket,
Prefix: backupFilePath,
MaxKeys: 1
};
const [error, listData] = await safe(s3.listObjectsV2(listParams));
2022-04-14 08:07:03 -05:00
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error listing objects ${backupFilePath}. Message: ${error.message} HTTP Code: ${error.code}`);
2022-04-14 08:07:03 -05:00
return listData.Contents.length !== 0;
2022-04-14 07:35:41 -05:00
}
}
// Download the object in small parts. By downloading small parts, we reduce the chance of sporadic network errors when downloading large objects
// We can retry each part individually, but we haven't had the need for this yet
class S3MultipartDownloadStream extends Readable {
constructor (s3, params, options) {
super(options);
this._s3 = s3;
this._params = params;
this._readSize = 0;
this._fileSize = -1;
this._path = params.Bucket + '/' + params.Key;
this._blockSize = options.blockSize || 64 * 1048576; // MB
}
_done() {
this._readSize = 0;
this.push(null); // EOF
}
_handleError(error) {
if (S3_NOT_FOUND(error)) {
this.destroy(new BoxError(BoxError.NOT_FOUND, `Backup not found: ${this._path}`));
} else {
debug(`download: ${this._path} s3 stream error. %o`, error);
this.destroy(new BoxError(BoxError.EXTERNAL_ERROR, `Error multipartDownload ${this._path}. Message: ${error.message} HTTP Code: ${error.code}`));
}
}
2025-02-12 20:56:46 +01:00
async _downloadRange(offset, length) {
const params = Object.assign({}, this._params);
const lastPos = offset + length - 1;
const range = `bytes=${offset}-${lastPos}`;
params['Range'] = range;
2025-02-12 20:56:46 +01:00
const [error, data] = await safe(this._s3.getObject(params));
if (error) return this._handleError(error);
2025-02-12 20:56:46 +01:00
const contentLength = parseInt(data.ContentLength, 10); // should be same as length
2025-02-12 20:56:46 +01:00
if (contentLength > 0) {
this._readSize += contentLength;
2025-02-13 19:23:04 +01:00
const body = await consumers.buffer(data.Body); // data.Body.transformToString('binary') also works
this.push(body);
2025-02-12 20:56:46 +01:00
} else {
this._done();
}
}
_nextDownload() {
let len = 0;
if (this._readSize + this._blockSize < this._fileSize) {
len = this._blockSize;
} else {
len = this._fileSize - this._readSize;
}
this._downloadRange(this._readSize, len);
}
2025-02-12 20:56:46 +01:00
async _fetchSize() {
const [error, data] = await safe(this._s3.headObject(this._params));
if (error) return this._handleError(error);
2025-02-12 20:56:46 +01:00
const length = parseInt(data.ContentLength, 10);
2025-02-12 20:56:46 +01:00
if (length > 0) {
this._fileSize = length;
this._nextDownload();
} else {
this._done();
}
}
2025-02-12 20:56:46 +01:00
_read() { // reimp
if (this._readSize === this._fileSize) return this._done();
if (this._readSize === 0) return this._fetchSize();
this._nextDownload();
}
}
async function download(apiConfig, backupFilePath) {
assert.strictEqual(typeof apiConfig, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof backupFilePath, 'string');
2022-04-14 07:35:41 -05:00
const params = {
Bucket: apiConfig.bucket,
Key: backupFilePath
};
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY });
return new S3MultipartDownloadStream(s3, params, { blockSize: 64 * 1024 * 1024 });
}
async function listDir(apiConfig, dir, batchSize, marker) {
2018-07-28 09:05:44 -07:00
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof dir, 'string');
assert.strictEqual(typeof batchSize, 'number');
assert(typeof marker !== 'undefined');
2018-07-28 09:05:44 -07:00
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY });
2022-04-14 07:35:41 -05:00
const listParams = {
Bucket: apiConfig.bucket,
Prefix: dir,
MaxKeys: batchSize
};
if (marker) listParams.ContinuationToken = marker;
const [error, listData] = await safe(s3.listObjectsV2(listParams));
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error listing objects in ${dir}. Message: ${error.message} HTTP Code: ${error.code}`);
if (listData.Contents.length === 0) return { entries: [], marker: null }; // no more
const entries = listData.Contents.map(function (c) { return { fullPath: c.Key, size: c.Size }; });
return { entries, marker: !listData.IsTruncated ? null : listData.NextContinuationToken };
}
// https://github.com/aws/aws-sdk-js/blob/2b6bcbdec1f274fe931640c1b61ece999aae7a19/lib/util.js#L41
// https://github.com/GeorgePhillips/node-s3-url-encode/blob/master/index.js
// See aws-sdk-js/issues/1302
function encodeCopySource(bucket, path) {
// AWS percent-encodes some extra non-standard characters in a URI
2022-04-14 07:35:41 -05:00
const output = encodeURI(path).replace(/[+!"#$@&'()*+,:;=?@]/g, function(ch) {
return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
});
// the slash at the beginning is optional
return `/${bucket}/${output}`;
}
2025-02-12 20:56:46 +01:00
async function copyFile(apiConfig, oldFilePath, newFilePath, entry, progressCallback) {
2016-03-31 09:48:01 -07:00
assert.strictEqual(typeof apiConfig, 'object');
2017-09-19 20:40:38 -07:00
assert.strictEqual(typeof oldFilePath, 'string');
assert.strictEqual(typeof newFilePath, 'string');
2025-02-12 20:56:46 +01:00
assert.strictEqual(typeof entry, 'object');
2022-04-30 16:01:42 -07:00
assert.strictEqual(typeof progressCallback, 'function');
2015-09-21 14:02:00 -07:00
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY }); // https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html
const relativePath = path.relative(oldFilePath, entry.fullPath);
2025-02-12 20:56:46 +01:00
function throwError(error) {
if (error) debug(`copy: s3 copy error when copying ${entry.fullPath}: ${error}`);
2017-09-22 14:40:37 -07:00
2025-02-12 20:56:46 +01:00
if (error && S3_NOT_FOUND(error)) throw new BoxError(BoxError.NOT_FOUND, `Old backup not found: ${entry.fullPath}`);
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error copying ${entry.fullPath} (${entry.size} bytes): ${error.code || ''} ${error}`);
}
2025-02-12 20:56:46 +01:00
const copyParams = {
Bucket: apiConfig.bucket,
Key: path.join(newFilePath, relativePath)
};
2017-10-11 13:57:05 -07:00
2025-02-12 20:56:46 +01:00
// S3 copyObject has a file size limit of 5GB so if we have larger files, we do a multipart copy
const largeFileLimit = (apiConfig.provider === 'vultr-objectstorage' || apiConfig.provider === 'exoscale-sos' || apiConfig.provider === 'backblaze-b2' || apiConfig.provider === 'digitalocean-spaces') ? 1024 * 1024 * 1024 : 3 * 1024 * 1024 * 1024;
2025-02-12 20:56:46 +01:00
if (entry.size < largeFileLimit) {
progressCallback({ message: `Copying ${relativePath || oldFilePath}` });
2025-02-12 20:56:46 +01:00
copyParams.CopySource = encodeCopySource(apiConfig.bucket, entry.fullPath);
const [copyError] = await safe(s3.copyObject(copyParams));
if (copyError) return throwError(copyError);
return;
}
2025-02-12 20:56:46 +01:00
progressCallback({ message: `Copying (multipart) ${relativePath || oldFilePath}` });
2025-02-12 20:56:46 +01:00
const [createMultipartError, multipart] = await safe(s3.createMultipartUpload(copyParams));
if (createMultipartError) return throwError(createMultipartError);
2025-02-12 20:56:46 +01:00
// Exoscale (96M) was suggested by exoscale. 1GB for others is arbitrary size
const chunkSize = apiConfig.provider === 'exoscale-sos' ? 96 * 1024 * 1024 : 1024 * 1024 * 1024;
const uploadId = multipart.UploadId;
const uploadedParts = [], ranges = [];
2025-02-12 20:56:46 +01:00
let cur = 0;
while (cur + chunkSize < entry.size) {
ranges.push({ startBytes: cur, endBytes: cur + chunkSize - 1 });
cur += chunkSize;
}
ranges.push({ startBytes: cur, endBytes: entry.size-1 });
2025-02-12 20:56:46 +01:00
const [copyError] = await safe(async.eachOfLimit(ranges, 3, async function copyChunk(range, index) {
const partCopyParams = {
Bucket: apiConfig.bucket,
Key: path.join(newFilePath, relativePath),
CopySource: encodeCopySource(apiConfig.bucket, entry.fullPath), // See aws-sdk-js/issues/1302
CopySourceRange: 'bytes=' + range.startBytes + '-' + range.endBytes,
PartNumber: index+1,
UploadId: uploadId
};
2020-09-02 22:32:42 -07:00
2025-02-12 20:56:46 +01:00
progressCallback({ message: `Copying part ${partCopyParams.PartNumber} - ${partCopyParams.CopySource} ${partCopyParams.CopySourceRange}` });
2020-09-02 22:32:42 -07:00
2025-02-12 20:56:46 +01:00
const part = await s3.uploadPartCopy(partCopyParams);
progressCallback({ message: `Copied part ${partCopyParams.PartNumber} - Etag: ${part.CopyPartResult.ETag}` });
2025-02-12 20:56:46 +01:00
if (!part.CopyPartResult.ETag) throw new Error('Multi-part copy is broken or not implemented by the S3 storage provider');
2025-02-12 20:56:46 +01:00
uploadedParts[index] = { ETag: part.CopyPartResult.ETag, PartNumber: partCopyParams.PartNumber };
}));
2022-04-14 07:35:41 -05:00
if (copyError) {
2025-02-12 20:56:46 +01:00
const abortParams = {
Bucket: apiConfig.bucket,
Key: path.join(newFilePath, relativePath),
UploadId: uploadId
};
progressCallback({ message: `Aborting multipart copy of ${relativePath || oldFilePath}` });
await safe(s3.abortMultipartUpload(abortParams), { debug }); // ignore any abort errors
return throwError(copyError);
2017-10-11 13:57:05 -07:00
}
2025-02-12 20:56:46 +01:00
const completeMultipartParams = {
Bucket: apiConfig.bucket,
Key: path.join(newFilePath, relativePath),
MultipartUpload: { Parts: uploadedParts },
UploadId: uploadId
};
progressCallback({ message: `Finishing multipart copy - ${completeMultipartParams.Key}` });
const [completeMultipartError] = await safe(s3.completeMultipartUpload(completeMultipartParams));
if (completeMultipartError) return throwError(completeMultipartError);
}
async function copy(apiConfig, oldFilePath, newFilePath, progressCallback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof oldFilePath, 'string');
assert.strictEqual(typeof newFilePath, 'string');
assert.strictEqual(typeof progressCallback, 'function');
2020-09-02 22:32:42 -07:00
let total = 0;
const concurrency = apiConfig.limits?.copyConcurrency || (apiConfig.provider === 's3' ? 500 : 10);
2022-04-30 16:01:42 -07:00
progressCallback({ message: `Copying with concurrency of ${concurrency}` });
let marker = null;
while (true) {
const batch = await listDir(apiConfig, oldFilePath, 1000, marker);
total += batch.entries.length;
progressCallback({ message: `Copying files from ${total-batch.entries.length}-${total}` });
2025-02-12 20:56:46 +01:00
await async.eachLimit(batch.entries, concurrency, async (entry) => await copyFile(apiConfig, oldFilePath, newFilePath, entry, progressCallback));
if (!batch.marker) break;
marker = batch.marker;
}
progressCallback({ message: `Copied ${total} files` });
2015-09-21 14:02:00 -07:00
}
async function remove(apiConfig, filename) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof filename, 'string');
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY });
2022-04-14 07:35:41 -05:00
const deleteParams = {
Bucket: apiConfig.bucket,
Delete: {
Objects: [{ Key: filename }]
}
};
2022-04-14 07:35:41 -05:00
// deleteObjects does not return error if key is not found
2025-02-12 20:56:46 +01:00
const [error] = await safe(s3.deleteObjects(deleteParams));
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, `Unable to remove ${deleteParams.Key}. error: ${error.message}`);
}
2022-04-15 09:25:54 -05:00
function chunk(array, size) {
assert(Array.isArray(array));
assert.strictEqual(typeof size, 'number');
const length = array.length;
if (!length) return [];
2024-07-02 14:54:40 +02:00
let index = 0, resIndex = 0;
const result = Array(Math.ceil(length / size));
2022-04-15 09:25:54 -05:00
for (; index < length; index += size) {
result[resIndex++] = array.slice(index, index+size);
}
return result;
}
async function removeDir(apiConfig, pathPrefix, progressCallback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof pathPrefix, 'string');
assert.strictEqual(typeof progressCallback, 'function');
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY });
let total = 0;
let marker = null;
while (true) {
const batch = await listDir(apiConfig, pathPrefix, 1000, marker);
2017-10-11 13:57:05 -07:00
const entries = batch.entries;
2022-04-14 07:35:41 -05:00
total += entries.length;
2018-02-22 12:14:13 -08:00
const chunkSize = apiConfig.limits?.deleteConcurrency || (apiConfig.provider !== 'digitalocean-spaces' ? 1000 : 100); // throttle objects in each request
const chunks = chunk(entries, chunkSize);
2018-02-22 12:14:13 -08:00
await async.eachSeries(chunks, async function deleteFiles(objects) {
const deleteParams = {
2022-04-14 07:35:41 -05:00
Bucket: apiConfig.bucket,
Delete: {
Objects: objects.map(function (o) { return { Key: o.fullPath }; })
}
};
2018-02-22 12:14:13 -08:00
progressCallback({ message: `Removing ${objects.length} files from ${objects[0].fullPath} to ${objects[objects.length-1].fullPath}` });
2017-10-10 20:23:04 -07:00
2022-04-14 07:35:41 -05:00
// deleteObjects does not return error if key is not found
2025-02-12 20:56:46 +01:00
const [error] = await safe(s3.deleteObjects(deleteParams));
if (error) {
progressCallback({ message: `Unable to remove ${deleteParams.Key} ${error.message || error.code}` });
throw new BoxError(BoxError.EXTERNAL_ERROR, `Unable to remove ${deleteParams.Key}. error: ${error.message}`);
}
});
if (!batch.marker) break;
marker = batch.marker;
}
2017-10-10 20:23:04 -07:00
progressCallback({ message: `Removed ${total} files` });
}
// often, the AbortIncompleteMultipartUpload lifecycle rule is not added to the bucket resulting in large bucket sizes over time
async function cleanup(apiConfig, progressCallback) {
assert.strictEqual(typeof apiConfig, 'object');
assert.strictEqual(typeof progressCallback, 'function');
const s3 = createS3Client(apiConfig, { retryStrategy: RETRY_STRATEGY });
const uploads = await s3.listMultipartUploads({ Bucket: apiConfig.bucket, Prefix: apiConfig.prefix });
progressCallback({ message: `Cleaning up any aborted multi-part uploads. count:${uploads.Uploads?.length || 0} truncated:${uploads.IsTruncated}` });
if (!uploads.Uploads) return;
for (const upload of uploads.Uploads) {
if (Date.now() - new Date(upload.Initiated) < 3 * 24 * 60 * 60 * 1000) continue; // 3 days ago
progressCallback({ message: `Cleaning up multi-part upload uploadId:${upload.UploadId} key:${upload.Key}` });
await safe(s3.abortMultipartUpload({ Bucket: apiConfig.bucket, Key: upload.Key, UploadId: upload.UploadId }), { debug }); // ignore error
}
}
2022-04-14 07:59:50 -05:00
async function testConfig(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
2022-04-14 07:59:50 -05:00
if (typeof apiConfig.accessKeyId !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'accessKeyId must be a string');
if (typeof apiConfig.secretAccessKey !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'secretAccessKey must be a string');
2017-09-27 10:25:36 -07:00
2022-04-14 07:59:50 -05:00
if (typeof apiConfig.bucket !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'bucket must be a string');
2020-02-11 11:14:38 -08:00
// the node module seems to incorrectly accept bucket name with '/'
2022-04-14 07:59:50 -05:00
if (apiConfig.bucket.includes('/')) throw new BoxError(BoxError.BAD_FIELD, 'bucket name cannot contain "/"');
2020-02-11 11:14:38 -08:00
// names must be lowercase and start with a letter or number. can contain dashes
2022-04-14 07:59:50 -05:00
if (apiConfig.bucket.includes('_') || apiConfig.bucket.match(/[A-Z]/)) throw new BoxError(BoxError.BAD_FIELD, 'bucket name cannot contain "_" or capitals');
2022-04-14 07:59:50 -05:00
if (typeof apiConfig.prefix !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'prefix must be a string');
if ('signatureVersion' in apiConfig && typeof apiConfig.signatureVersion !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'signatureVersion must be a string');
if ('endpoint' in apiConfig && typeof apiConfig.endpoint !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'endpoint must be a string');
2022-04-14 07:59:50 -05:00
if ('acceptSelfSignedCerts' in apiConfig && typeof apiConfig.acceptSelfSignedCerts !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 'acceptSelfSignedCerts must be a boolean');
if ('s3ForcePathStyle' in apiConfig && typeof apiConfig.s3ForcePathStyle !== 'boolean') throw new BoxError(BoxError.BAD_FIELD, 's3ForcePathStyle must be a boolean');
2022-04-14 07:59:50 -05:00
const putParams = {
2022-04-14 07:35:41 -05:00
Bucket: apiConfig.bucket,
Key: path.join(apiConfig.prefix, 'snapshot/cloudron-testfile'),
2022-04-14 07:35:41 -05:00
Body: 'testcontent'
};
2025-02-12 20:56:46 +01:00
const s3 = createS3Client(apiConfig, {});
const [putError] = await safe(s3.putObject(putParams));
2022-04-14 07:59:50 -05:00
if (putError) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error put object cloudron-testfile. Message: ${putError.message} HTTP Code: ${putError.code}`);
const listParams = {
Bucket: apiConfig.bucket,
Prefix: path.join(apiConfig.prefix, 'snapshot'),
MaxKeys: 1
};
const [listError] = await safe(s3.listObjectsV2(listParams));
if (listError) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error listing objects. Message: ${listError.message} HTTP Code: ${listError.code}`);
2022-04-14 07:59:50 -05:00
const delParams = {
Bucket: apiConfig.bucket,
Key: path.join(apiConfig.prefix, 'snapshot/cloudron-testfile')
2022-04-14 07:59:50 -05:00
};
2025-02-12 20:56:46 +01:00
const [delError] = await safe(s3.deleteObject(delParams));
2022-04-14 07:59:50 -05:00
if (delError) throw new BoxError(BoxError.EXTERNAL_ERROR, `Error del object cloudron-testfile. Message: ${delError.message} HTTP Code: ${delError.code}`);
}
function removePrivateFields(apiConfig) {
apiConfig.secretAccessKey = constants.SECRET_PLACEHOLDER;
return apiConfig;
}
function injectPrivateFields(newConfig, currentConfig) {
if (newConfig.secretAccessKey === constants.SECRET_PLACEHOLDER) newConfig.secretAccessKey = currentConfig.secretAccessKey;
}